/*!
 * jQuery Browser Plugin 0.0.8
 * https://github.com/gabceb/jquery-browser-plugin
 *
 * Original jquery-browser code Copyright 2005, 2015 jQuery Foundation, Inc. and other contributors
 * http://jquery.org/license
 *
 * Modifications Copyright 2015 Gabriel Cebrian
 * https://github.com/gabceb
 *
 * Released under the MIT license
 *
 * Date: 05-07-2015
 */
/*global window: false */

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], function ($) {
      return factory($);
    });
  } else if (typeof module === 'object' && typeof module.exports === 'object') {
    // Node-like environment
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function(jQuery) {
  "use strict";

  function uaMatch( ua ) {
    // If an UA is not provided, default to the current browser UA.
    if ( ua === undefined ) {
      ua = window.navigator.userAgent;
    }
    ua = ua.toLowerCase();

    var match = /(edge)\/([\w.]+)/.exec( ua ) ||
        /(opr)[\/]([\w.]+)/.exec( ua ) ||
        /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

    var platform_match = /(ipad)/.exec( ua ) ||
        /(ipod)/.exec( ua ) ||
        /(iphone)/.exec( ua ) ||
        /(kindle)/.exec( ua ) ||
        /(silk)/.exec( ua ) ||
        /(android)/.exec( ua ) ||
        /(windows phone)/.exec( ua ) ||
        /(win)/.exec( ua ) ||
        /(mac)/.exec( ua ) ||
        /(linux)/.exec( ua ) ||
        /(cros)/.exec( ua ) ||
        /(playbook)/.exec( ua ) ||
        /(bb)/.exec( ua ) ||
        /(blackberry)/.exec( ua ) ||
        [];

    var browser = {},
        matched = {
          browser: match[ 5 ] || match[ 3 ] || match[ 1 ] || "",
          version: match[ 2 ] || match[ 4 ] || "0",
          versionNumber: match[ 4 ] || match[ 2 ] || "0",
          platform: platform_match[ 0 ] || ""
        };

    if ( matched.browser ) {
      browser[ matched.browser ] = true;
      browser.version = matched.version;
      browser.versionNumber = parseInt(matched.versionNumber, 10);
    }

    if ( matched.platform ) {
      browser[ matched.platform ] = true;
    }

    // These are all considered mobile platforms, meaning they run a mobile browser
    if ( browser.android || browser.bb || browser.blackberry || browser.ipad || browser.iphone ||
      browser.ipod || browser.kindle || browser.playbook || browser.silk || browser[ "windows phone" ]) {
      browser.mobile = true;
    }

    // These are all considered desktop platforms, meaning they run a desktop browser
    if ( browser.cros || browser.mac || browser.linux || browser.win ) {
      browser.desktop = true;
    }

    // Chrome, Opera 15+ and Safari are webkit based browsers
    if ( browser.chrome || browser.opr || browser.safari ) {
      browser.webkit = true;
    }

    // IE11 has a new token so we will assign it msie to avoid breaking changes
    // IE12 disguises itself as Chrome, but adds a new Edge token.
    if ( browser.rv || browser.edge ) {
      var ie = "msie";

      matched.browser = ie;
      browser[ie] = true;
    }

    // Blackberry browsers are marked as Safari on BlackBerry
    if ( browser.safari && browser.blackberry ) {
      var blackberry = "blackberry";

      matched.browser = blackberry;
      browser[blackberry] = true;
    }

    // Playbook browsers are marked as Safari on Playbook
    if ( browser.safari && browser.playbook ) {
      var playbook = "playbook";

      matched.browser = playbook;
      browser[playbook] = true;
    }

    // BB10 is a newer OS version of BlackBerry
    if ( browser.bb ) {
      var bb = "blackberry";

      matched.browser = bb;
      browser[bb] = true;
    }

    // Opera 15+ are identified as opr
    if ( browser.opr ) {
      var opera = "opera";

      matched.browser = opera;
      browser[opera] = true;
    }

    // Stock Android browsers are marked as Safari on Android.
    if ( browser.safari && browser.android ) {
      var android = "android";

      matched.browser = android;
      browser[android] = true;
    }

    // Kindle browsers are marked as Safari on Kindle
    if ( browser.safari && browser.kindle ) {
      var kindle = "kindle";

      matched.browser = kindle;
      browser[kindle] = true;
    }

     // Kindle Silk browsers are marked as Safari on Kindle
    if ( browser.safari && browser.silk ) {
      var silk = "silk";

      matched.browser = silk;
      browser[silk] = true;
    }

    // Assign the name and platform variable
    browser.name = matched.browser;
    browser.platform = matched.platform;
    return browser;
  }

  // Run the matching process, also assign the function to the returned object
  // for manual, jQuery-free use if desired
  window.jQBrowser = uaMatch( window.navigator.userAgent );
  window.jQBrowser.uaMatch = uaMatch;

  // Only assign to jQuery.browser if jQuery is loaded
  if ( jQuery ) {
    jQuery.browser = window.jQBrowser;
  }

  return window.jQBrowser;
}));

/* jshint strict: false, maxlen: 90, evil: true */
/* global -$, WYMeditor: true, console */

/*@version 1.1.1 */
/**
    WYMeditor
    =========

    version 1.1.1

    WYMeditor : what you see is What You Mean web-based editor

    Main JS file with core classes and functions.

    Copyright
    ---------

    Copyright (c) 2005 - 2010 Jean-Francois Hovinne, http://www.wymeditor.org/
    Dual licensed under the MIT (MIT-license.txt)
    and GPL (GPL-license.txt) licenses.

    Website
    -------

    For further information visit:
    http://www.wymeditor.org/


    Authors
    -------

    See AUTHORS file
*/

// Global WYMeditor namespace.
if (typeof (WYMeditor) === 'undefined') {
    /* jshint -W079 */
    var WYMeditor = {};
    /* jshint +W079 */
}

// Wrap the Firebug console in WYMeditor.console
(function () {
    if (typeof window.console === 'undefined' &&
        typeof console === 'undefined') {
        // No in-browser console logging available
        var names = [
                "log", "debug", "info", "warn", "error", "assert", "dir",
                "dirxml", "group", "groupEnd", "time", "timeEnd", "count",
                "trace", "profile", "profileEnd"
            ],
            noOp = function () {},
            i;

        WYMeditor.console = {};
        for (i = 0; i < names.length; i += 1) {
            WYMeditor.console[names[i]] = noOp;
        }
    } else if (typeof console !== 'undefined') {
        // ie8+
        WYMeditor.console = console;
    } else if (window.console.firebug) {
        // FF with firebug
        WYMeditor.console = window.console;
    } else if (window.console) {
        // Chrome
        WYMeditor.console = window.console;
    }
}());

jQuery.extend(WYMeditor, {

/**
    Constants
    =========

    Global WYMeditor constants.

    VERSION             - Defines WYMeditor version.
    INSTANCES           - An array of loaded WYMeditor.editor instances.
    STRINGS             - An array of loaded WYMeditor language pairs/values.
    SKINS               - An array of loaded WYMeditor skins.
    NAME                - The "name" attribute.
    WYM_INDEX           - A string used to get/set the instance index.
    WYM_PATH            - A string replaced by WYMeditor's main JS file path.
    IFRAME_BASE_PATH    - String replaced by the designmode iframe's base path.
    IFRAME_DEFAULT      - The iframe's default base path.
    JQUERY_PATH         - A string replaced by the computed jQuery path.
    DIRECTION           - A string replaced by the text direction (rtl or ltr).
    LOGO                - A string replaced by WYMeditor logo.
    TOOLS               - A string replaced by the toolbar's HTML.
    TOOLS_ITEMS         - A string replaced by the toolbar items.
    TOOL_NAME           - A string replaced by a toolbar item's name.
    TOOL_TITLE          - A string replaced by a toolbar item's title.
    TOOL_CLASS          - A string replaced by a toolbar item's class.
    CLASSES             - A string replaced by the classes panel's HTML.
    CLASSES_ITEMS       - A string replaced by the classes items.
    CLASS_NAME          - A string replaced by a class item's name.
    CLASS_TITLE         - A string replaced by a class item's title.
    CONTAINERS          - A string replaced by the containers panel's HTML.
    CONTAINERS_ITEMS    - A string replaced by the containers items.
    CONTAINER_NAME      - A string replaced by a container item's name.
    CONTAINER_TITLE     - A string replaced by a container item's title.
    CONTAINER_CLASS     - A string replaced by a container item's class.
    HTML                - A string replaced by the HTML view panel's HTML.
    IFRAME              - A string replaced by the designmode iframe.
    STATUS              - A string replaced by the status panel's HTML.
    BODY                - The BODY element.
    STRING              - The "string" type.
    BODY,DIV,P,
    H1,H2,H3,H4,H5,H6,
    PRE,BLOCKQUOTE,
    A,BR,IMG,
    TABLE,TD,TH,
    UL,OL,LI            - HTML elements string representation.
    CLASS,HREF,SRC,
    TITLE,REL,ALT       - HTML attributes string representation.
    KEY                 - Standard key codes.
    NODE                - Node types.

*/

    A                   : "a",
    ALT                 : "alt",
    BLOCKQUOTE          : "blockquote",
    BODY                : "body",
    CLASS               : "class",
    CLASSES             : "{Wym_Classes}",
    CLASSES_ITEMS       : "{Wym_Classes_Items}",
    CLASS_NAME          : "{Wym_Class_Name}",
    CLASS_TITLE         : "{Wym_Class_Title}",
    CONTAINERS          : "{Wym_Containers}",
    CONTAINERS_ITEMS    : "{Wym_Containers_Items}",
    CONTAINER_CLASS     : "{Wym_Container_Class}",
    CONTAINER_NAME      : "{Wym_Container_Name}",
    CONTAINER_TITLE     : "{Wym_Containers_Title}",
    DIRECTION           : "{Wym_Direction}",
    DIV                 : "div",
    H1                  : "h1",
    H2                  : "h2",
    H3                  : "h3",
    H4                  : "h4",
    H5                  : "h5",
    H6                  : "h6",
    HREF                : "href",
    HTML                : "{Wym_Html}",
    IFRAME              : "{Wym_Iframe}",
    IFRAME_BASE_PATH    : "{Wym_Iframe_Base_Path}",
    IFRAME_DEFAULT      : "iframe/default/",
    IMG                 : "img",
    INSERT_HTML         : "InsertHTML",
    INSTANCES           : [],
    JQUERY_PATH         : "{Wym_Jquery_Path}",
    LI                  : "li",
    LOGO                : "{Wym_Logo}",
    NAME                : "name",
    NBSP                : '\xA0',
    NEWLINE             : "\n",
    OL                  : "ol",
    P                   : "p",
    PRE                 : "pre",
    REL                 : "rel",
    SKINS               : [],
    SRC                 : "src",
    STATUS              : "{Wym_Status}",
    STRING              : "string",
    STRINGS             : [],
    TABLE               : "table",
    TD                  : "td",
    TH                  : "th",
    TITLE               : "title",
    TOOLS               : "{Wym_Tools}",
    TOOLS_ITEMS         : "{Wym_Tools_Items}",
    TOOL_CLASS          : "{Wym_Tool_Class}",
    TOOL_NAME           : "{Wym_Tool_Name}",
    TOOL_TITLE          : "{Wym_Tool_Title}",
    TR                  : "tr",
    UL                  : "ul",
    VERSION             : "1.1.1",
    WYM_INDEX           : "wym_index",
    WYM_PATH            : "{Wym_Wym_Path}",

    // Commands for the `editor.exec` method
    EXEC_COMMANDS: {
        // Inline wrapping element toggles
        BOLD                : "Bold",
        ITALIC              : "Italic",
        SUPERSCRIPT         : "Superscript",
        SUBSCRIPT           : "Subscript",
        // Other manipulations
        CREATE_LINK         : "CreateLink",
        UNLINK              : "Unlink",
        FORMAT_BLOCK        : "FormatBlock",
        INSERT_IMAGE        : "InsertImage",
        UNDO                : "Undo",
        REDO                : "Redo",
        INSERT_LINEBREAK    : "InsertLineBreak",
        // Lists
        INSERT_ORDEREDLIST  : "InsertOrderedList",
        INSERT_UNORDEREDLIST: "InsertUnorderedList",
        INDENT              : "Indent",
        OUTDENT             : "Outdent",
        // UI
        TOGGLE_HTML         : "ToggleHtml"
    },

    // Containers that we allow at the root of the document (as a direct child
    // of the body tag)
    ROOT_CONTAINERS : [
        "blockquote",
        "div",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "p",
        "pre"
    ],

    // Containers that we explicitly do not allow at the root of the document.
    // These containers must be wrapped in a valid root container.
    FORBIDDEN_ROOT_CONTAINERS : [
        "a",
        "b",
        "em",
        "i",
        "span",
        "strong",
        "sub",
        "sup"
    ],

    // All block (as opposed to inline) tags
    BLOCKS : [
        "address",
        "blockquote",
        "dd",
        "div",
        "dl",
        "dt",
        "fieldset",
        "form",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "hr",
        "li",
        "noscript",
        "ol",
        "p",
        "pre",
        "table",
        "tbody",
        "td",
        "tfoot",
        "th",
        "thead",
        "tr",
        "ul"
    ],

    // The subset of the `ROOT_CONTAINERS` that prevent the user from using
    // up/down/enter/backspace from moving above or below them. They
    // effectively block the creation of new blocks.
    BLOCKING_ELEMENTS : [
        "blockquote",
        "pre",
        "table"
    ],

    // Elements that are not containers. They don't generally have any child
    // nodes.
    NON_CONTAINING_ELEMENTS : [
        "br",
        "col",
        "hr",
        "img"
    ],

    // Elements that should not contain collapsed selection directly.
    NO_CARET_ELEMENTS: [
        "blockquote",
        "br",
        "col",
        "colgroup",
        "dl",
        "hr",
        "img",
        "ol",
        "table",
        "tbody",
        "tfoot",
        "thead",
        "tr",
        "ul"
    ],

    // Inline elements.
    INLINE_ELEMENTS : [
        "a",
        "abbr",
        "acronym",
        "b",
        "bdo",
        "big",
        "br",
        "button",
        "cite",
        "code",
        "dfn",
        "em",
        "i",
        "img",
        "input",
        "kbd",
        "label",
        "map",
        "object",
        "q",
        "samp",
        "script",
        "select",
        "small",
        "span",
        "strong",
        "sub",
        "sup",
        "textarea",
        "tt",
        "var"
    ],

    // The remaining `ROOT_CONTAINERS` that are not considered
    // `BLOCKING_ELEMENTS`
    NON_BLOCKING_ELEMENTS : [
        "div",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "p"
    ],

    // The elements that define a type of list.
    LIST_TYPE_ELEMENTS : [
        "ol",
        "ul"
    ],

    // The elements that define a heading
    HEADING_ELEMENTS : [
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6"
    ],

    // The elements that are allowed to be turned in to lists. If an item in
    // this array isn't in the ROOT_CONTAINERS array, then its contents will be
    // turned in to a list instead.
    POTENTIAL_LIST_ELEMENTS : [
        "blockquote",
        "div",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "p",
        "pre",
        "td"
    ],

    // The elements that are allowed to have a table inserted after them or
    // within them.
    POTENTIAL_TABLE_INSERT_ELEMENTS : [
        "blockquote",
        "div",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "li",
        "p",
        "pre"
    ],

    // The elements that are allowed to have a table inserted inline within
    // them.
    INLINE_TABLE_INSERTION_ELEMENTS : [
        "li"
    ],

    // The elements used in tables that can be selected by the user by clicking
    // in them.
    SELECTABLE_TABLE_ELEMENTS: [
        "caption",
        "td",
        "th"
    ],

    // Class for marking br elements used to space apart blocking elements in
    // the editor.
    BLOCKING_ELEMENT_SPACER_CLASS: "wym-blocking-element-spacer",

    // Class used to flag an element for removal by the xhtml parser so that
    // the element is removed from the output and only shows up internally
    // within the editor.
    EDITOR_ONLY_CLASS: "wym-editor-only",

    // Class for resize handles
    RESIZE_HANDLE_CLASS: "wym-resize-handle",

    // Classes that will be removed from all tags' class attribute by the
    // parser.
    CLASSES_REMOVED_BY_PARSER: [
        "apple-style-span"
    ],

    // Keyboard mappings so that we don't have to remember that 38 means up
    // when reading keyboard handlers
    KEY_CODE : {
        B: 66,
        BACKSPACE: 8,
        COMMAND: 224,
        CTRL: 17,
        CURSOR: [37, 38, 39, 40],
        DELETE: 46,
        DOWN: 40,
        END: 35,
        ENTER: 13,
        HOME: 36,
        I: 73,
        LEFT: 37,
        R: 82,
        RIGHT: 39,
        TAB: 9,
        UP: 38
    },

    // Key codes for the keys that can potentially create a block element when
    // inputted
    POTENTIAL_BLOCK_ELEMENT_CREATION_KEYS : [
        8,   // BACKSPACE
        13,  // ENTER
        37,  // LEFT
        38,  // UP
        39,  // RIGHT
        40,  // DOWN
        46   // DELETE
    ],

    EVENTS : {
        'postBlockMaybeCreated': 'wym-postBlockMaybeCreated',
        'postIframeInitialization': 'wym-postIframeInitialization',
        'postModification': 'wym-postModification',
        'postUndo': 'wym-postUndo',
        'postRedo': 'wym-postRedo'
    },

    // domNode.nodeType constants
    NODE_TYPE : {
        ELEMENT: 1,
        ATTRIBUTE: 2,
        TEXT: 3
    },

    /**
        WYMeditor.editor
        ================

        WYMeditor editor main class, instantiated for each editor occurrence.

        See also: WYMeditor.editor.init

        Use
        ---

        Initializes main values (index, elements, paths, ...)
        and calls WYMeditor.editor.init which initializes the editor.

        ### Parameters

        elem - The HTML element to be replaced by the editor.

        options - The hash of options.

        ### Returns

        Nothing.

    */
    editor : function (elem, options) {
        if (jQuery.getWymeditorByTextarea(elem[0])) {
            throw "It seems that this textarea already belongs to a " +
                "WYMeditor instance.";
        }
        var wym = this;
        // Store the instance in the INSTANCES array and store the index
        wym._index = WYMeditor.INSTANCES.push(wym) - 1;
        // The element replaced by the editor
        wym.element = elem;
        wym._options = options;
        // Path to the WYMeditor core
        wym._options.wymPath = wym._options.wymPath ||
            WYMeditor._computeWymPath();
        // Path to the main JS files
        wym._options.basePath = wym._options.basePath ||
            WYMeditor._computeBasePath(wym._options.wymPath);
        // The designmode iframe's base path
        wym._options.iframeBasePath = wym._options.iframeBasePath ||
            wym._options.basePath + WYMeditor.IFRAME_DEFAULT;

        // Initialize the editor instance
        wym._init();
    },

    EXTERNAL_MODULES : {}
});

/********** jQuery Plugin Definition **********/

/**
    wymeditor
    =========

    jQuery plugin function for replacing an HTML element with a WYMeditor
    instance.

    Example
    -------

    `jQuery(".wymeditor").wymeditor({});`
*/
jQuery.fn.wymeditor = function (options) {
    var $textareas = this;

    options = jQuery.extend({

        html:       "",
        basePath:   false,
        wymPath:    false,
        iframeBasePath: false,
        jQueryPath: false,
        skin:       "default",
        lang:       "en",
        direction:  "ltr",
        customCommands: [],

        // These values will override the default for their respective
        // `DocumentStructureManager.structureRules`
        structureRules: {
            defaultRootContainer:  'p'
        },

        boxHtml: String() +
            "<div class='wym_box'>" +
                "<div class='wym_area_top'>" +
                    WYMeditor.TOOLS +
                "</div>" +
                "<div class='wym_area_left'></div>" +
                "<div class='wym_area_right'>" +
                    WYMeditor.CONTAINERS +
                    WYMeditor.CLASSES +
                "</div>" +
                "<div class='wym_area_main'>" +
                    WYMeditor.HTML +
                    WYMeditor.IFRAME +
                    WYMeditor.STATUS +
                "</div>" +
                "<div class='wym_area_bottom'>" +
                    WYMeditor.LOGO +
                "</div>" +
            "</div>",

        logoHtml: String() +
            '<a class="wym_wymeditor_link" ' +
                'href="http://www.wymeditor.org/">WYMeditor</a>',

        iframeHtml: String() +
            '<div class="wym_iframe wym_section">' +
                '<iframe src="' + WYMeditor.IFRAME_BASE_PATH + 'wymiframe.html">' +
                '</iframe>' +
            "</div>",

        toolsHtml: String() +
            '<div class="wym_tools wym_section">' +
                '<h2>{Tools}</h2>' +
                '<ul>' +
                    WYMeditor.TOOLS_ITEMS +
                '</ul>' +
            '</div>',

        toolsItemHtml: String() +
            '<li class="' + WYMeditor.TOOL_CLASS + '">' +
                '<a href="#" name="' + WYMeditor.TOOL_NAME + '" ' +
                        'title="' + WYMeditor.TOOL_TITLE + '">' +
                    WYMeditor.TOOL_TITLE +
                '</a>' +
            '</li>',

        toolsItems: [
            {
                'name': 'Bold',
                'title': 'Strong',
                'css': 'wym_tools_strong'
            },
            {
                'name': 'Italic',
                'title': 'Emphasis',
                'css': 'wym_tools_emphasis'
            },
            {
                'name': 'Superscript',
                'title': 'Superscript',
                'css': 'wym_tools_superscript'
            },
            {
                'name': 'Subscript',
                'title': 'Subscript',
                'css': 'wym_tools_subscript'
            },
            {
                'name': 'InsertOrderedList',
                'title': 'Ordered_List',
                'css': 'wym_tools_ordered_list'
            },
            {
                'name': 'InsertUnorderedList',
                'title': 'Unordered_List',
                'css': 'wym_tools_unordered_list'
            },
            {
                'name': 'Indent',
                'title': 'Indent',
                'css': 'wym_tools_indent'
            },
            {
                'name': 'Outdent',
                'title': 'Outdent',
                'css': 'wym_tools_outdent'
            },
            {
                'name': 'Undo',
                'title': 'Undo',
                'css': 'wym_tools_undo'
            },
            {
                'name': 'Redo',
                'title': 'Redo',
                'css': 'wym_tools_redo'
            },
            {
                'name': 'CreateLink',
                'title': 'Link',
                'css': 'wym_tools_link wym_opens_dialog'
            },
            {
                'name': 'Unlink',
                'title': 'Unlink',
                'css': 'wym_tools_unlink'
            },
            {
                'name': 'InsertImage',
                'title': 'Image',
                'css': 'wym_tools_image wym_opens_dialog'
            },
            {
                'name': 'InsertTable',
                'title': 'Table',
                'css': 'wym_tools_table wym_opens_dialog'
            },
            {
                'name': 'Paste',
                'title': 'Paste_From_Word',
                'css': 'wym_tools_paste wym_opens_dialog'
            },
            {
                'name': 'ToggleHtml',
                'title': 'HTML',
                'css': 'wym_tools_html'
            },
            {
                'name': 'Preview',
                'title': 'Preview',
                'css': 'wym_tools_preview wym_opens_dialog'
            }
        ],

        containersHtml: String() +
            '<div class="wym_containers wym_section">' +
                '<h2>{Containers}</h2>' +
                '<ul>' +
                    WYMeditor.CONTAINERS_ITEMS +
                '</ul>' +
            '</div>',

        containersItemHtml: String() +
            '<li class="' + WYMeditor.CONTAINER_CLASS + '">' +
                '<a href="#" name="' + WYMeditor.CONTAINER_NAME + '">' +
                    WYMeditor.CONTAINER_TITLE +
                '</a>' +
            '</li>',

        containersItems: [
            {'name': 'P', 'title': 'Paragraph', 'css': 'wym_containers_p'},
            {'name': 'H1', 'title': 'Heading_1', 'css': 'wym_containers_h1'},
            {'name': 'H2', 'title': 'Heading_2', 'css': 'wym_containers_h2'},
            {'name': 'H3', 'title': 'Heading_3', 'css': 'wym_containers_h3'},
            {'name': 'H4', 'title': 'Heading_4', 'css': 'wym_containers_h4'},
            {'name': 'H5', 'title': 'Heading_5', 'css': 'wym_containers_h5'},
            {'name': 'H6', 'title': 'Heading_6', 'css': 'wym_containers_h6'},
            {'name': 'PRE', 'title': 'Preformatted', 'css': 'wym_containers_pre'},
            {'name': 'BLOCKQUOTE', 'title': 'Blockquote',
                'css': 'wym_containers_blockquote'},
            {'name': 'TH', 'title': 'Table_Header', 'css': 'wym_containers_th'}
        ],

        classesHtml: String() +
            '<div class="wym_classes wym_section">' +
                '<h2>{Classes}</h2>' +
                '<ul>' +
                    WYMeditor.CLASSES_ITEMS +
                '</ul>' +
            '</div>',

        classesItemHtml: String() +
            '<li class="wym_classes_' + WYMeditor.CLASS_NAME + '">' +
                '<a href="#" name="' + WYMeditor.CLASS_NAME + '">' +
                    WYMeditor.CLASS_TITLE +
                '</a>' +
            '</li>',

        classesItems:      [],
        statusHtml: String() +
            '<div class="wym_status wym_section">' +
                '<h2>{Status}</h2>' +
            '</div>',

        htmlHtml: String() +
            '<div class="wym_html wym_section">' +
                '<h2>{Source_Code}</h2>' +
                '<textarea class="wym_html_val"></textarea>' +
            '</div>',

        boxSelector:        ".wym_box",
        toolsSelector:      ".wym_tools",
        toolsListSelector:  " ul",
        containersSelector: ".wym_containers",
        classesSelector:    ".wym_classes",
        htmlSelector:       ".wym_html",
        iframeSelector:     ".wym_iframe iframe",
        iframeBodySelector: ".wym_iframe",
        statusSelector:     ".wym_status",
        toolSelector:       ".wym_tools a",
        containerSelector:  ".wym_containers a",
        classSelector:      ".wym_classes a",
        htmlValSelector:    ".wym_html_val",

        updateSelector:    ".wymupdate",
        updateEvent:       "click",

        stringDelimiterLeft:  "{",
        stringDelimiterRight: "}",

        preInit: null,
        preBind: null,
        postInit: null

    }, options);

    options = jQuery.extend(WYMeditor.DEFAULT_DIALOG_OPTIONS, options);

    return $textareas.each(function () {
        var textarea = this;
        // Assigning to _wym because the return value from new isn't
        // actually used, but we need to use new to properly change the
        // prototype
        textarea._wym = new WYMeditor.editor(jQuery(textarea), options);
    });
};

// Enable accessing of wymeditor instances via jQuery.wymeditors
jQuery.extend({
    wymeditors: function (i) {
        return WYMeditor.INSTANCES[i];
    }
});

jQuery.extend({
    getWymeditorByTextarea: function (textarea) {
        var i;
        if (
            !(
                textarea &&
                textarea.tagName &&
                textarea.tagName.toLowerCase() === 'textarea'
            )
        ) {
            throw "jQuery.getWymeditorByTextarea requires a textarea element.";
        }
        for (i = 0; i < WYMeditor.INSTANCES.length; i++) {
            if (textarea === WYMeditor.INSTANCES[i].element[0]) {
                return WYMeditor.INSTANCES[i];
            }
        }
        return false;
    }
});

/**
    jQuery.copyPropsFromObjectToObject
    =====================================

    General helper function that copies specified list of properties from a
    specified origin object to a specified target object.

    @param origin The origin object.
    @param target The target object.
    @param propNames An array of strings, representing the properties to copy.
*/
jQuery.extend({
    copyPropsFromObjectToObject: function (origin, target, propNames) {
        var i,
            propName,
            prop,
            props = {};

        for (i = 0; i < propNames.length; i++) {
            propName = propNames[i];
            prop = origin[propName];
            props[propName] = prop;
        }

        jQuery.extend(target, props);
    }
});

/**
    WYMeditor.isInternetExplorerPre11
    =================================

    Returns true if the current browser is an Internet Explorer version
    previous to 11. Otherwise, returns false.
*/
WYMeditor.isInternetExplorerPre11 = function () {
    if (
        jQuery.browser.msie &&
        jQuery.browser.versionNumber < 11
    ) {
        return true;
    }
    return false;
};

/**
    WYMeditor.isInternetExplorer11OrNewer
    =====================================

    Returns true if the current browser is an Internet Explorer version 11 or
    newer. Otherwise, returns false.
*/
WYMeditor.isInternetExplorer11OrNewer = function () {
    if (
        jQuery.browser.msie &&
        jQuery.browser.versionNumber >= 11
    ) {
        return true;
    }
    return false;
};

/**
    WYMeditor._computeWymPath
    =========================

    Get the relative path to the WYMeditor core js file for usage as
    a src attribute for script inclusion.

    Looks for script tags on the current page and finds the first matching
    src attribute matching any of these values:
    * jquery.wymeditor.pack.js
    * jquery.wymeditor.min.js
    * jquery.wymeditor.packed.js
    * jquery.wymeditor.js
    * /core.js
*/
WYMeditor._computeWymPath = function () {
    var script = jQuery(
        jQuery.grep(
            jQuery('script'),
            function (s) {
                if (!s.src) {
                    return null;
                }
                return (
                    s.src.match(
                        /jquery\.wymeditor(\.pack|\.min|\.packed)?\.js(\?.*)?$/
                    ) ||
                    s.src.match(
                            /\/core\.js(\?.*)?$/
                        )
                );
            }
        )
    );
    if (script.length > 0) {
        return script.attr('src');
    }
    // We couldn't locate the base path. This will break language loading
    // and other features.
    WYMeditor.console.warn(
        "Error determining wymPath. No base WYMeditor file located."
    );
    WYMeditor.console.warn("Assuming wymPath to be the current URL");
    WYMeditor.console.warn("Please pass a correct wymPath option");

    // Guess that the wymPath is the current directory
    return '';
};

/**
    WYMeditor._computeBasePath
    ==========================

    Get the relative path to the WYMeditor directory root based on the path to
    the wymeditor base file. This path is used as the basis for loading:
    * Language files
    * Skins
    * The popup document https://github.com/wymeditor/wymeditor/issues/731
*/
WYMeditor._computeBasePath = function (wymPath) {
    // Strip everything after the last slash to get the base path
    var lastSlashIndex = wymPath.lastIndexOf('/');
    return wymPath.substr(0, lastSlashIndex + 1);
};

/********** HELPERS **********/

// Returns true if it is a text node with whitespaces only
jQuery.fn.isPhantomNode = function () {
    var $nodes = this;
    if ($nodes[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
        return !(/[^\t\n\r ]/.test($nodes[0].data));
    }

    return false;
};

/**
    jQuery.fn.nextContentsUntil
    ===========================

    Acts like jQuery.nextUntil() but includes text nodes and comments and only
    works on the first element in the given jQuery collection..
*/
jQuery.fn.nextContentsUntil = function (selector, filter) {
    var $nodes = this,
        matched = [],
        $matched,
        cur = $nodes.get(0);

    selector = selector ? selector : '';
    filter = filter ? filter : '';

    if (!cur) {
        // Called on an empty selector. The sibling of nothing is nothing
        return jQuery();
    }
    // We don't want to include this element, only its siblings
    cur = cur.nextSibling;

    while (cur) {
        if (!jQuery(cur).is(selector)) {
            matched.push(cur);
            cur = cur.nextSibling;
        } else {
            break;
        }
    }

    $matched = jQuery(matched);
    if (filter) {
        return $matched.filter(filter);
    }
    return $matched;
};
/**
    jQuery.fn.nextAllContents
    =========================

    Acts like jQuery.nextAll() but includes text nodes and comments and only
    works on the first element in the given jQuery collection..

    Mostly cribbed from the jQuery source.
*/
jQuery.fn.nextAllContents = function () {
    var $nodes = this;
    return jQuery($nodes).nextContentsUntil('', '');
};

/**
    jQuery.fn.prevContentsUntil
    ===========================

    Acts like jQuery.prevUntil() but includes text nodes and comments and only
    works on the first element in the given jQuery collection..
*/
jQuery.fn.prevContentsUntil = function (selector, filter) {
    var $nodes = this,
        matched = [],
        $matched,
        cur = $nodes.get(0);

    selector = selector ? selector : '';
    filter = filter ? filter : '';

    if (!cur) {
        // Called on an empty selector. The sibling of nothing is nothing
        return jQuery();
    }
    // We don't want to include this element, only its siblings
    cur = cur.previousSibling;

    while (cur) {
        if (!jQuery(cur).is(selector)) {
            matched.push(cur);
            cur = cur.previousSibling;
        } else {
            break;
        }
    }

    $matched = jQuery(matched);
    if (filter) {
        return $matched.filter(filter);
    }
    return $matched;
};

/**
    jQuery.fn.prevAllContents
    =========================

    Acts like jQuery.prevAll() but includes text nodes and comments and only
    works on the first element in the given jQuery collection..

    Mostly cribbed from the jQuery source.
*/
jQuery.fn.prevAllContents = function () {
    var $nodes = this;
    return jQuery($nodes).prevContentsUntil('', '');
};

WYMeditor.isPhantomNode = function (n) {
    if (n.nodeType === WYMeditor.NODE_TYPE.TEXT) {
        return !(/[^\t\n\r ]/.test(n.data));
    }

    return false;
};

WYMeditor.isPhantomString = function (str) {
    return !(/[^\t\n\r ]/.test(str));
};

jQuery.fn.addBack = jQuery.fn.addBack ? jQuery.fn.addBack : jQuery.fn.andSelf;

// Returns the Parents or the node itself
// `selector` = a jQuery selector
jQuery.fn.parentsOrSelf = function (selector) {
    var $n = this;

    if (selector) {
        return $n.parents().addBack().filter(selector);
    } else {
        return $n.parents().addBack();
    }
};

// Various helpers

WYMeditor.Helper = {

    //replace all instances of 'old' by 'rep' in 'str' string
    replaceAllInStr: function (str, old, rep) {
        var rExp = new RegExp(old, "g");
        return str.replace(rExp, rep);
    },

    //insert 'inserted' at position 'pos' in 'str' string
    insertAt: function (str, inserted, pos) {
        return str.substr(0, pos) + inserted + str.substring(pos);
    },

    //trim 'str' string
    trim: function (str) {
        return str.replace(/^(\s*)|(\s*)$/gm, '');
    },

    //Returns true if `array`` contains `thing`. Uses `===` for comparison of
    //provided `thing` with contents of provided `array`.
    arrayContains: function (arr, elem) {
        var i;
        for (i = 0; i < arr.length; i += 1) {
            if (arr[i] === elem) {
                return true;
            }
        }
        return false;
    },

    //return 'item' position in 'arr' array, or -1
    indexOf: function (arr, item) {
        var ret = -1, i;
        for (i = 0; i < arr.length; i += 1) {
            if (arr[i] === item) {
                ret = i;
                break;
            }
        }
        return ret;
    },

    //return 'item' object in 'arr' array, checking its 'name' property, or null
    _getFromArrayByName: function (arr, name) {
        var i, item;
        for (i = 0; i < arr.length; i += 1) {
            item = arr[i];
            if (item.name === name) {
                return item;
            }
        }
        return null;
    },

    // naively returns all event types
    // of the provided an element
    // according the its property keys that
    // begin with 'on'
    getAllEventTypes: function (elem) {
        var result = [];
        for (var key in elem) {
            if (key.indexOf('on') === 0 && key !== 'onmousemove') {
                result.push(key.slice(2));
            }
        }
        return result.join(' ');
    }
};

/**
    WYMeditor._getWymClassForBrowser
    ================================

    Returns the constructor for the browser-specific wymeditor instance.

    If does not detect a supported browser, returns false;
*/
WYMeditor._getWymClassForBrowser = function () {

    // Using https://github.com/gabceb/jquery-browser-plugin
    switch (jQuery.browser.name) {
        case "msie":
            if (WYMeditor.isInternetExplorerPre11()) {
                return WYMeditor.WymClassTridentPre7;
            } else if (WYMeditor.isInternetExplorer11OrNewer()) {
                return WYMeditor.WymClassTrident7;
            } else {
                return false;
            }
            break;
        case "mozilla":
            return WYMeditor.WymClassGecko;
        case "chrome":
            return WYMeditor.WymClassBlink;
        case "safari":
            return WYMeditor.WymClassSafari;
    }

    if (jQuery.browser.webkit) {
        return WYMeditor.WymClassWebKit;
    }

    WYMeditor.console.warn("WYMeditor could not instantiate: this browser " +
        "is not supported");
    return false;
};

"use strict";
/**
    editor._openPopupWindow
    =======================

    Opens a popup window, provided the `windowFeatures`.
*/
WYMeditor.editor.prototype._openPopupWindow = function (windowFeatures) {
    var wym = this,
        popup,
        basePath = wym._options.basePath;

    popup = window.open(
        // https://github.com/wymeditor/wymeditor/issues/731
        jQuery.browser.msie ? basePath + 'popup.html' : '',
        "wymPopupWindow",
        windowFeatures
    );

    return popup;
};

/**
    editor.dialog
    =============

    Open a dialog box
*/
WYMeditor.editor.prototype.dialog = function (
    dialog,
    pDialogWindowFeatures,
    pBodyHtml
) {
    var wym = this,
        i,
        DIALOGS = WYMeditor.DIALOGS,
        dialogObject,
        dialogWindowFeatures,
        wDialog,
        htmlStrReplacements,
        dialogHtml,
        doc,
        selectedContainer,
        options = wym._options;

    if (jQuery.isPlainObject(dialog)) {
        // Dialog object provided. This is the documented public API way.
        dialogObject = dialog;
    } else if (
        // Dialog name string provided. This is undocumented.
        typeof dialog === "string" &&
        DIALOGS.hasOwnProperty(dialog)
    ) {
        WYMeditor.console.warn("DEPRECATION WARNING: `dialog` method " +
            "received a string dialog name. Please provide a dialog object " +
            "instead.");
        dialogObject = DIALOGS[dialog];
    }

    if (
        jQuery.isPlainObject(dialogObject) !== true &&
        typeof pBodyHtml !== "string"
    ) {
        throw "`dialog` method: No dialog provided";
    }

    if (dialogObject) {
        if (
            dialogObject.hasOwnProperty("title") !== true ||
            dialogObject.hasOwnProperty("shouldOpen") !== true ||
            dialogObject.hasOwnProperty("getBodyHtml") !== true
        ) {
            throw "Expected the dialog object to contain at least `title`, " +
                "`shouldOpen` and `getbodyHtml`";
        }
    }

    // Return `false` early if this dialog should not open. Use the dialog's
    // own function to check this.
    if (
        dialogObject &&
        dialogObject.shouldOpen.call(wym) !== true
    ) {
        return false;
    }

    if (pDialogWindowFeatures) {
        // Provided argument
        dialogWindowFeatures = pDialogWindowFeatures;
    } else if (dialogObject && dialogObject.getWindowFeatures) {
        // Dialog's code
        dialogWindowFeatures = dialogObject.getWindowFeatures.call(wym);
    } else if (options.dialogFeatures) {
        // Provided option
        dialogWindowFeatures = options.dialogFeatures;
    } else {
        // Default
        dialogWindowFeatures = [
            "menubar=no",
            "titlebar=no",
            "toolbar=no",
            "resizable=no",
            "width=560",
            "height=300",
            "top=0",
            "left=0"
        ].join(",");
    }

    wDialog = wym._openPopupWindow(dialogWindowFeatures);

    if (
        typeof wDialog !== "object" ||
        wDialog.window !== wDialog
    ) {
        WYMeditor.console.warn("Could not create a dialog window");
        return false;
    }

    // In the case where a dialog window already exists, it will be reused.
    // If it is in the background, behind another window, without the following
    // `focus` call, it will remain in the background and the user may not
    // understand where it is. This `focus` call brings the dialog to the
    // foreground, making reasonably sure the user notices it.
    wDialog.focus();

    // Construct the dialog
    dialogHtml = options.dialogHtml || String() +
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' +
                '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' +
        '<html dir="' + WYMeditor.DIRECTION + '">' +
            '<head>' +
                '<title>' + WYMeditor.DIALOG_TITLE + '</title>' +
            '</head>' +
            WYMeditor.DIALOG_BODY +
        '</html>';

    // HTML template replacements
    htmlStrReplacements = [
        {
            placeholder: WYMeditor.DIRECTION,
            replacement: options.direction
        },
        {
            placeholder: WYMeditor.DIALOG_TITLE,
            replacement: dialogObject ?
                wym._encloseString(dialogObject.title) : "Dialog"
        },
        {
            placeholder: WYMeditor.DIALOG_BODY,
            replacement: pBodyHtml || dialogObject.getBodyHtml.call(wym)
        }
    ];

    // Perform HTML template replacements
    for (i = 0; i < htmlStrReplacements.length; i++) {
        dialogHtml = WYMeditor.Helper.replaceAllInStr(
            dialogHtml,
            htmlStrReplacements[i].placeholder,
            htmlStrReplacements[i].replacement
        );
    }

    dialogHtml = wym.replaceStrings(dialogHtml);

    doc = wDialog.document;
    doc.write(dialogHtml);
    if (dialogObject && dialogObject.getBodyClass) {
        jQuery(doc.body).addClass(dialogObject.getBodyClass.call(wym));
    }
    doc.close();

    selectedContainer = wym.selectedContainer();

    wDialog.onbeforeunload = function () {
        wym.focusOnDocument();
    };

    // Pre-init function
    if (jQuery.isFunction(options.preInitDialog)) {
        options.preInitDialog(wym, wDialog);
    }

    // Dialog-specific initialization
    if (dialogObject && dialogObject.initialize) {
        dialogObject.initialize.call(wym, wDialog);
    }

    if (dialogObject && dialogObject.submitHandler) {
        jQuery("form", doc).submit(function () {
            dialogObject.submitHandler.call(wym, wDialog);
        });
    }

    // Cancel button
    jQuery(options.cancelSelector, doc).click(function () {
        wDialog.close();
    });

    // Post-init function
    if (jQuery.isFunction(options.postInitDialog)) {
        options.postInitDialog(wym, wDialog);
    }

    return wDialog;
};

/*
 * An object of default dialogs.
 *
 * See API documentation for the `dialog` method.
 */
WYMeditor.DIALOGS = {
    CreateLink: {
        title: "Link",
        shouldOpen: function () {
            var wym = this,
                selectedContainer;
            if (wym.hasSelection() !== true) {
                return false;
            }
            selectedContainer = wym.selectedContainer();
            if (selectedContainer === false) {
                return false;
            }
            if (
                wym.selection().isCollapsed &&
                selectedContainer.tagName.toLowerCase() !== "a"
            ) {
                return false;
            }
            return true;
        },
        getBodyHtml: function () {
            var wym = this;
            return wym._options.dialogLinkHtml || String() +
                '<form>' +
                    '<fieldset>' +
                        '<input type="hidden" class="wym_dialog_type" ' +
                            'value="' + WYMeditor.DIALOG_LINK + '" />' +
                        '<legend>{Link}</legend>' +
                        '<div class="row">' +
                            '<label>{URL}</label>' +
                            '<input type="text" class="wym_href" ' +
                                'value="" size="40" ' +
                                'autofocus="autofocus" />' +
                        '</div>' +
                        '<div class="row">' +
                            '<label>{Title}</label>' +
                            '<input type="text" class="wym_title" ' +
                                'value="" size="40" />' +
                        '</div>' +
                        '<div class="row">' +
                            '<label>{Relationship}</label>' +
                            '<input type="text" class="wym_rel" ' +
                                'value="" size="40" />' +
                        '</div>' +
                        '<div class="row row-indent">' +
                            '<input class="wym_submit" type="submit" ' +
                                'value="{Submit}" />' +
                            '<input class="wym_cancel" type="button" ' +
                                'value="{Cancel}" />' +
                        '</div>' +
                    '</fieldset>' +
                '</form>';
        },
        getBodyClass: function () {
            var wym = this;
            return wym._options.dialogSelectorLink || "wym_dialog_link";
        },
        initialize: function (wDialog) {
            var wym = this,
                doc = wDialog.document,
                options = wym._options,
                selectedContainer = wym.selectedContainer(),
                $hrefInput,
                $titleInput,
                $relInput,
                currentHref,
                currentTitle,
                currentRel;

            if (!selectedContainer) {
                return;
            }

            $hrefInput = jQuery(options.hrefSelector, doc);
            $titleInput = jQuery(options.titleSelector, doc);
            $relInput = jQuery(options.relSelector, doc);

            currentHref = jQuery(selectedContainer).attr(WYMeditor.HREF);
            currentTitle = jQuery(selectedContainer).attr(WYMeditor.TITLE);
            currentRel = jQuery(selectedContainer).attr(WYMeditor.REL);

            $hrefInput.val(currentHref);
            $titleInput.val(currentTitle);
            $relInput.val(currentRel);
        },
        submitHandler: function (wDialog) {
            var wym = this,
                options = wym._options,
                href = jQuery(options.hrefSelector, wDialog.document).val(),
                title = jQuery(options.titleSelector, wDialog.document).val(),
                rel = jQuery(options.relSelector, wDialog.document).val();

            wym.link({
                href: href,
                title: title,
                rel: rel
            });
            wDialog.close();
        }
    },
    InsertImage: {
        title: "Image",
        shouldOpen: function () {
            var wym = this,
                selectedImage = wym.getSelectedImage();
            if (
                selectedImage &&
                selectedImage.tagName &&
                selectedImage.tagName.toLowerCase() === "img"
            ) {
                return true;
            }
            return wym.hasSelection();
        },
        getBodyHtml: function () {
            var wym = this;
            return wym._options.dialogImageHtml || String() +
                '<form>' +
                    '<fieldset>' +
                        '<input type="hidden" class="wym_dialog_type" ' +
                            'value="' + WYMeditor.DIALOG_IMAGE + '" />' +
                        '<legend>{Image}</legend>' +
                        '<div class="row">' +
                            '<label>{URL}</label>' +
                            '<input type="text" class="wym_src" ' +
                                'value="" size="40" ' +
                                'autofocus="autofocus" />' +
                        '</div>' +
                        '<div class="row">' +
                            '<label>{Alternative_Text}</label>' +
                            '<input type="text" class="wym_alt" ' +
                                'value="" size="40" />' +
                        '</div>' +
                        '<div class="row">' +
                            '<label>{Title}</label>' +
                            '<input type="text" class="wym_title" ' +
                                'value="" size="40" />' +
                        '</div>' +
                        '<div class="row row-indent">' +
                            '<input class="wym_submit" type="submit" ' +
                                'value="{Submit}" />' +
                            '<input class="wym_cancel" type="button" ' +
                                'value="{Cancel}" />' +
                        '</div>' +
                    '</fieldset>' +
                '</form>';
        },
        getBodyClass: function () {
            var wym = this;
            return wym._options.dialogImageSelector || "wym_dialog_image";
        },
        initialize: function (wDialog) {
            var wym = this,
                doc = wDialog.document,
                options = wym._options,
                selectedImage = wym.getSelectedImage(),
                $srcInput,
                $titleInput,
                $altInput,
                currentSrc,
                currentTitle,
                currentAlt;

            if (!selectedImage) {
                return;
            }

            $srcInput = jQuery(options.srcSelector, doc);
            $titleInput = jQuery(options.titleSelector, doc);
            $altInput = jQuery(options.altSelector, doc);

            currentSrc = jQuery(selectedImage).attr(WYMeditor.SRC);
            currentTitle = jQuery(selectedImage).attr(WYMeditor.TITLE);
            currentAlt = jQuery(selectedImage).attr(WYMeditor.ALT);

            $srcInput.val(currentSrc);
            $titleInput.val(currentTitle);
            $altInput.val(currentAlt);
        },
        submitHandler: function (wDialog) {
            var wym = this,
                options = wym._options,
                imgAttrs,
                selectedImage = wym.getSelectedImage();

            imgAttrs = {
                src: jQuery(options.srcSelector, wDialog.document).val(),
                title: jQuery(options.titleSelector, wDialog.document).val(),
                alt: jQuery(options.altSelector, wDialog.document).val()
            };

            wym.focusOnDocument();

            if (selectedImage) {
                wym._updateImageAttrs(selectedImage, imgAttrs);
                wym.registerModification();
            } else {
                wym.insertImage(imgAttrs);
            }
            wDialog.close();
        }
    },
    InsertTable: {
        title: "Table",
        shouldOpen: function () {
            var wym = this;
            if (
                wym.hasSelection() !== true ||
                wym.selection().isCollapsed !== true
            ) {
                return false;
            }
            return true;
        },
        getBodyHtml: function () {
            var wym = this;
            return wym._options.dialogTableHtml || String() +
                '<form>' +
                    '<fieldset>' +
                        '<input type="hidden" class="wym_dialog_type" ' +
                            'value="' + WYMeditor.DIALOG_TABLE + '" />' +
                        '<legend>{Table}</legend>' +
                        '<div class="row">' +
                            '<label>{Caption}</label>' +
                            '<input type="text" class="wym_caption" ' +
                                'value="" size="40" />' +
                        '</div>' +
                        '<div class="row">' +
                            '<label>{Summary}</label>' +
                            '<input type="text" class="wym_summary" ' +
                                'value="" size="40" />' +
                        '</div>' +
                        '<div class="row">' +
                            '<label>{Number_Of_Rows}</label>' +
                            '<input type="text" class="wym_rows" ' +
                                'value="3" size="3" />' +
                        '</div>' +
                        '<div class="row">' +
                            '<label>{Number_Of_Cols}</label>' +
                            '<input type="text" class="wym_cols" ' +
                                'value="2" size="3" />' +
                        '</div>' +
                        '<div class="row row-indent">' +
                            '<input class="wym_submit" type="submit" ' +
                                'value="{Submit}" />' +
                            '<input class="wym_cancel" type="button" ' +
                                'value="{Cancel}" />' +
                        '</div>' +
                    '</fieldset>' +
                '</form>';
        },
        getBodyClass: function () {
            var wym = this;
            return wym._options.dialogTableSelector || "wym_dialog_table";
        },
        submitHandler: function (wDialog) {
            var wym = this,
                options = wym._options,
                doc = wDialog.document,
                numRows = jQuery(options.rowsSelector, doc).val(),
                numColumns = jQuery(options.colsSelector, doc).val(),
                caption = jQuery(options.captionSelector, doc).val(),
                summary = jQuery(options.summarySelector, doc).val();

            wym.insertTable(numRows, numColumns, caption, summary);
            wDialog.close();
        }
    },
    Paste: {
        title: "Paste_From_Word",
        shouldOpen: function () {
            var wym = this;
            return wym.hasSelection();
        },
        getBodyHtml: function () {
            var wym = this;
            return wym._options.dialogPasteHtml || String() +
                '<form>' +
                    '<input type="hidden" class="wym_dialog_type" ' +
                        'value="' + WYMeditor.DIALOG_PASTE + '" />' +
                    '<fieldset>' +
                        '<legend>{Paste_From_Word}</legend>' +
                        '<div class="row">' +
                            '<textarea class="wym_text" rows="10" ' +
                                'cols="50" autofocus="autofocus">' +
                            '</textarea>' +
                        '</div>' +
                        '<div class="row">' +
                            '<input class="wym_submit" type="submit" ' +
                                'value="{Submit}" />' +
                            '<input class="wym_cancel" type="button" ' +
                                'value="{Cancel}" />' +
                        '</div>' +
                    '</fieldset>' +
                '</form>';
        },
        getBodyClass: function () {
            var wym = this;
            return wym._options.dialogPasteSelector || "wym_dialog_paste";
        },
        submitHandler: function (wDialog) {
            var wym = this,
                sText;
            sText = jQuery(wym._options.textSelector, wDialog.document).val();
            wym.paste(sText);
            wDialog.close();
        }
    },
    Preview: {
        title: "Preview",
        shouldOpen: function () {
            return true;
        },
        getBodyHtml: function () {
            var wym = this;
            return wym._options.dialogPreviewHtml || wym.html();
        },
        getWindowFeatures: function () {
            return [
                "menubar=no",
                "titlebar=no",
                "toolbar=no",
                "resizable=no",
                "width=560",
                "height=300",
                "top=0",
                "left=0",
                "scrollbars=yes"
            ].join(",");
        },
        getBodyClass: function () {
            var wym = this;
            return wym._options.dialogPreviewSelector || "wym_dialog_preview";
        }
    }
};

WYMeditor.DIALOG_TITLE = "{Wym_Dialog_Title}";
WYMeditor.DIALOG_BODY = "{Wym_Dialog_Body}";
WYMeditor.DIALOG_BUTTON_SELECTOR = ".wym_opens_dialog a";

WYMeditor.DEFAULT_DIALOG_OPTIONS = {
    hrefSelector: ".wym_href",
    srcSelector: ".wym_src",
    titleSelector: ".wym_title",
    relSelector: ".wym_rel",
    altSelector: ".wym_alt",
    textSelector: ".wym_text",
    rowsSelector: ".wym_rows",
    colsSelector: ".wym_cols",
    captionSelector: ".wym_caption",
    summarySelector: ".wym_summary",
    submitSelector: "form",
    cancelSelector: ".wym_cancel",
    previewSelector: "",
    dialogLinkSelector: ".wym_dialog_link",
    dialogImageSelector: ".wym_dialog_image",
    dialogTableSelector: ".wym_dialog_table",
    dialogPasteSelector: ".wym_dialog_paste",
    dialogPreviewSelector: ".wym_dialog_preview"
};

/* jshint evil: true, camelcase: false, maxlen: 100 */
/* global -$, rangy */
"use strict";

/**
    WYMeditor.editor._init
    ======================

    Initialize a wymeditor instance, including detecting the
    current browser and enabling the browser-specific subclass.
*/
WYMeditor.editor.prototype._init = function () {
    // Load the browser-specific subclass
    // If this browser isn't supported, do nothing
    var wym = this,
        WymClass,
        browserInstance,
        SaxListener,
        prop,
        h,
        iframeHtml,
        boxHtml,
        aTools,
        sTools,
        oTool,
        sTool,
        i,
        aClasses,
        sClasses,
        oClass,
        sClass,
        aContainers,
        sContainers,
        sContainer,
        oContainer;

    // Get the constructor for the browser-specific instance
    WymClass = WYMeditor._getWymClassForBrowser();

    if (!WymClass) {
        // We don't support this browser. Don't initialize.
        return;
    }

    // Initialize the browser-specific instance
    browserInstance = new WymClass(wym);

    if (jQuery.isFunction(wym._options.preInit)) {
        wym._options.preInit(wym);
    }

    wym.parser = null;
    wym.helper = null;

    SaxListener = new WYMeditor.XhtmlSaxListener();
    wym.parser = new WYMeditor.XhtmlParser(SaxListener);

    wym.helper = new WYMeditor.XmlHelper();

    // Extend the editor object with the browser-specific version.
    // We're not using jQuery.extend because we *want* to copy properties via
    // the prototype chain
    for (prop in browserInstance) {
        /*jshint forin: false*/
        // Explicitly not using hasOwnProperty for the inheritance here
        // because we want to go up the prototype chain to get all of the
        // browser-specific editor methods. This is kind of a code smell,
        // but works just fine.
        wym[prop] = browserInstance[prop];
    }

    // Load wymbox
    wym._box = jQuery(wym.element).hide().after(
        wym._options.boxHtml
    ).next().addClass(
        'wym_box_' + wym._index
    );

    // Store the instance index and replaced element in wymbox
    // but keep it compatible with jQuery < 1.2.3, see #122
    if (jQuery.isFunction(jQuery.fn.data)) {
        jQuery.data(wym._box.get(0), WYMeditor.WYM_INDEX, wym._index);
        jQuery.data(wym.element.get(0), WYMeditor.WYM_INDEX, wym._index);
    }

    h = WYMeditor.Helper;

    // Construct the iframe
    iframeHtml = wym._options.iframeHtml;
    iframeHtml = h.replaceAllInStr(
        iframeHtml,
        WYMeditor.IFRAME_BASE_PATH,
        wym._options.iframeBasePath
    );

    // Construct wymbox
    boxHtml = jQuery(wym._box).html();

    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.LOGO, wym._options.logoHtml);
    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.TOOLS, wym._options.toolsHtml);
    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CONTAINERS, wym._options.containersHtml);
    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CLASSES, wym._options.classesHtml);
    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.HTML, wym._options.htmlHtml);
    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.IFRAME, iframeHtml);
    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.STATUS, wym._options.statusHtml);

    // Construct the tools list
    aTools = eval(wym._options.toolsItems);
    sTools = "";

    for (i = 0; i < aTools.length; i += 1) {
        oTool = aTools[i];
        sTool = '';
        if (oTool.name && oTool.title) {
            sTool = wym._options.toolsItemHtml;
        }
        sTool = h.replaceAllInStr(sTool, WYMeditor.TOOL_NAME, oTool.name);
        sTool = h.replaceAllInStr(
            sTool,
            WYMeditor.TOOL_TITLE,
            wym._options.stringDelimiterLeft + oTool.title + wym._options.stringDelimiterRight
        );
        sTool = h.replaceAllInStr(sTool, WYMeditor.TOOL_CLASS, oTool.css);
        sTools += sTool;
    }

    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.TOOLS_ITEMS, sTools);

    // Construct the classes list
    aClasses = eval(wym._options.classesItems);
    sClasses = "";

    for (i = 0; i < aClasses.length; i += 1) {
        oClass = aClasses[i];
        sClass = '';
        if (oClass.name && oClass.title) {
            sClass = wym._options.classesItemHtml;
        }
        sClass = h.replaceAllInStr(sClass, WYMeditor.CLASS_NAME, oClass.name);
        sClass = h.replaceAllInStr(sClass, WYMeditor.CLASS_TITLE, oClass.title);
        sClasses += sClass;
    }

    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CLASSES_ITEMS, sClasses);

    // Construct the containers list
    aContainers = eval(wym._options.containersItems);
    sContainers = "";

    for (i = 0; i < aContainers.length; i += 1) {
        oContainer = aContainers[i];
        sContainer = '';
        if (oContainer.name && oContainer.title) {
            sContainer = wym._options.containersItemHtml;
        }
        sContainer = h.replaceAllInStr(
            sContainer,
            WYMeditor.CONTAINER_NAME,
            oContainer.name
        );
        sContainer = h.replaceAllInStr(sContainer, WYMeditor.CONTAINER_TITLE,
            wym._options.stringDelimiterLeft +
            oContainer.title +
            wym._options.stringDelimiterRight);
        sContainer = h.replaceAllInStr(
            sContainer,
            WYMeditor.CONTAINER_CLASS,
            oContainer.css
        );
        sContainers += sContainer;
    }

    boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CONTAINERS_ITEMS, sContainers);

    // I10n
    boxHtml = wym.replaceStrings(boxHtml);

    // Load the html in wymbox
    jQuery(wym._box).html(boxHtml);

    // Hide the html value
    jQuery(wym._box).find(wym._options.htmlSelector).hide();

    wym.documentStructureManager = new WYMeditor.DocumentStructureManager(
        wym,
        wym._options.structureRules.defaultRootContainer
    );

    // Some browsers like to trigger an iframe's load event multiple times
    // depending on all sorts of small, annoying details. Instead of attempting
    // to work-around old ones and predict new ones, let's just ensure the
    // initialization only happens once. All methods of detecting load are
    // unreliable.
    wym.iframeInitialized = false;

    wym._iframe = jQuery(wym._box).find('iframe')[0];

    jQuery(wym._iframe).load(function () {
        wym._onEditorIframeLoad(wym);
    });

    wym.element.attr('data-wym-initialized', 'yes');

    wym._initSkin();
};

/**
    WYMeditor.editor._assignWymDoc
    ==============================

    Assigns an editor's document to the `_doc` property.
*/
WYMeditor.editor.prototype._assignWymDoc = function () {
    var wym = this;

    wym._doc = wym._iframe.contentDocument;
};

/**
    WYMeditor.editor._isDesignModeOn
    ================================

    Returns true if the designMode property of the editor's document is "On".
    Returns false, otherwise.
*/
WYMeditor.editor.prototype._isDesignModeOn = function () {
    var wym = this;

    if (
        typeof wym._doc.designMode === "string" &&
        wym._doc.designMode.toLowerCase() === "on"
    ) {
        return true;
    }
    return false;
};

/**
    WYMeditor.editor._onEditorIframeLoad
    ====================================

    This is a part of the initialization of an editor.

    The initialization procedure of an editor turns asynchronous because part of
    it must occur after the loading of the editor's Iframe.

    This function is supposed to be the event handler of the loading of the
    editor's Iframe. Therefore, it is the first step since the initialization
    procedure gets asynchronous.

    @param wym The editor instance that's being initialized.
*/
WYMeditor.editor.prototype._onEditorIframeLoad = function (wym) {
    wym._assignWymDoc();
    wym._enableDesignModeOnDocument();
    wym._afterDesignModeOn();
};

/**
    WYMeditor.editor.get$Buttons
    ============================

    Returns a jQuery object, containing all the UI buttons.
*/
WYMeditor.editor.prototype.get$Buttons = function () {
    var wym = this,
        buttonsSelector,
        $buttons;

    buttonsSelector = [
        wym._options.toolSelector,
        wym._options.containerSelector,
        wym._options.classSelector
    ].join(', ');
    $buttons = jQuery(wym._box).find(buttonsSelector);

    return $buttons;
};

/**
    WYMeditor.editor.focusOnDocument
    ================================

    Sets focus on the document.
*/
WYMeditor.editor.prototype.focusOnDocument = function () {
    var wym = this,
        doc = wym._iframe.contentWindow;

    doc.focus();
};

/**
    WYMeditor.editor.registerModification
    =====================================

    Registers a change in the document. This should be called after changes
    are made in the document.

    Triggers the `postModification` event afterwards.
*/
WYMeditor.editor.prototype.registerModification = function (isNativeEdit) {
    var wym = this;

    wym.undoRedo._add();

    if (!isNativeEdit) {
        // A non-native-edit modification is registered. Reset Edited.
        wym.nativeEditRegistration.edited.reset();
    }

    jQuery(wym.element).trigger(WYMeditor.EVENTS.postModification);
};

/**
    WYMeditor.editor._bindFocusOnDocumentToButtons
    ==============================================

    Binds a handler to clicks on the UI buttons, that sets focus back to the
    document.

    Doesn't bind to dialog-opening buttons, because that would cause them to
    fall behind the opening window, in some browsers.
*/
WYMeditor.editor.prototype._bindFocusOnDocumentToButtons = function () {
    var wym = this,
        $buttons = wym.get$Buttons();

    $buttons = $buttons.parent().not('.wym_opens_dialog').children('a');
    $buttons.click(function () {
        wym.focusOnDocument();
    });
};

/**
    WYMeditor.editor._uiQuirks
    ==========================

    A hook for browser quirks that work on the UI.

    To be run after plugins had a chance to modify the UI.
*/
WYMeditor.editor.prototype._uiQuirks = function () {
    return;
};


/**
    WYMeditor.editor._afterDesignModeOn
    ===================================

    This is part of the initialization of an editor, designed to be called
    after the editor's document is in designMode.
*/
WYMeditor.editor.prototype._afterDesignModeOn = function () {
    var wym = this;

    if (wym.iframeInitialized === true) {
        return;
    }

    wym._assignWymDoc();
    wym.$body().addClass("wym_iframe combokeys");

    wym._doc.title = wym._index;

    // Set the text direction.
    jQuery('html', wym._doc).attr('dir', wym._options.direction);

    wym.keyboard = new WYMeditor.Keyboard(wym);
    wym.keyboard._attachDefaultKeyboardShortcuts();

    wym._docEventQuirks();

    wym._initializeDocumentContent();

    if (jQuery.isFunction(wym._options.preBind)) {
        wym._options.preBind(wym);
    }

    wym._bindUIEvents();

    wym.iframeInitialized = true;

    if (jQuery.isFunction(wym._options.postInit)) {
        wym._options.postInit(wym);
    }

    // Importantly, these two are  after `postInit`, where plugins had a chance
    // to modify the UI (add buttons, etc.).
    wym._bindFocusOnDocumentToButtons();
    wym._uiQuirks();

    // Add event listeners to doc elements, e.g. images
    wym._listen();

    wym.undoRedo = new WYMeditor.UndoRedo(wym);

    wym.nativeEditRegistration = new WYMeditor.NativeEditRegistration(wym);

    wym.ih = new WYMeditor.ImageHandler(wym);

    jQuery(wym.element).trigger(
        WYMeditor.EVENTS.postIframeInitialization,
        wym
    );
};

/**
    WYMeditor.editor._initializeDocumentContent
    ===========================================

    Populates the editor's document with the initial content, according to the
    configuration and/or the textarea element's value.
*/
WYMeditor.editor.prototype._initializeDocumentContent = function () {
    var wym = this;

    if (wym._options.html) {
        // Populate from the configuration option
        wym.html(wym._options.html);
    } else {
        // Populate from the textarea element
        wym.html(wym.element[0].value);
    }
};

/**
    WYMeditor.editor._docEventQuirks
    ================================

    Misc. event bindings on the editor's document, that may be required.
*/
WYMeditor.editor.prototype._docEventQuirks = function () {
    return;
};

/**
    WYMeditor.editor._bindUIEvents
    ==============================

    Binds event handlers for the UI elements.
*/
WYMeditor.editor.prototype._bindUIEvents = function () {
    var wym = this,
        $toolbarButtons = jQuery(wym._box).find(wym._options.toolSelector),
        dialogButtonSelector = WYMeditor.DIALOG_BUTTON_SELECTOR,
        $html_val;

    // Action buttons
    $toolbarButtons.not(dialogButtonSelector).click(function () {
        var button = this;
        wym.exec(jQuery(button).attr(WYMeditor.NAME));
        return false;
    });

    // Dialog buttons
    $toolbarButtons.filter(dialogButtonSelector).click(function () {
        var button = this,
            dialogName = jQuery(button).attr(WYMeditor.NAME),
            dialog = WYMeditor.DIALOGS[dialogName];

        // The following would also work, but is deprecated:
        // wym.dialog(dialogName);
        wym.dialog(dialog);
        return false;
    });

    // Containers buttons
    jQuery(wym._box).find(wym._options.containerSelector).click(function () {
        var containerButton = this;
        wym.setRootContainer(jQuery(containerButton).attr(WYMeditor.NAME));
        return false;
    });

    // Handle keyup event on the HTML value textarea: set the editor value
    // Handle focus/blur events to check if the element has focus, see #147
    $html_val = jQuery(wym._box).find(wym._options.htmlValSelector);
    $html_val.keyup(function () {
        var valTextarea = this;
        wym.$body().html(jQuery(valTextarea).val());
    });
    $html_val.focus(function () {
        var valTextarea = this;
        jQuery(valTextarea).toggleClass('hasfocus');
    });
    $html_val.blur(function () {
        var valTextarea = this;
        jQuery(valTextarea).toggleClass('hasfocus');
    });

    // Handle click events on classes buttons
    jQuery(wym._box).find(wym._options.classSelector).click(function () {
        var classButton = this,
            aClasses = eval(wym._options.classesItems),
            sName = jQuery(classButton).attr(WYMeditor.NAME),

            oClass = WYMeditor.Helper._getFromArrayByName(aClasses, sName),
            jqexpr;

        if (oClass) {
            jqexpr = oClass.expr;
            wym.toggleClass(sName, jqexpr);
        }
        return false;
    });

    // Handle update event on update element
    jQuery(wym._options.updateSelector).bind(
        wym._options.updateEvent,
        function () {
            wym.update();
        }
    );

    // This may recover an unexpected shut down of `designMode`.
    wym.$body().bind("focus", function () {
        if (wym._isDesignModeOn() !== true) {
            wym._enableDesignModeOnDocument();
        }
    });
};

/**
    WYMeditor.editor._enableDesignModeOnDocument
    ============================================

    Enables `designMode` on the document, if it is not already enabled.
*/
WYMeditor.editor.prototype._enableDesignModeOnDocument = function () {
    var wym = this;

    if (wym._isDesignModeOn()) {
        throw "Expected `designMode` to be off.";
    }

    try {
        wym._doc.designMode = "On";
    } catch (e) {
        // Bail out gracefully if this went wrong.
    }
    if (typeof wym._designModeQuirks === "function") {
        wym._designModeQuirks();
    }
};

/**
    WYMeditor.editor.get$WymBox
    ===========================

    Get a jQuery containing the WYMeditor box.
*/
WYMeditor.editor.prototype.get$WymBox = function () {
    var wym = this;
    return wym._box;
};

/**
    WYMeditor.editor.vanish
    =========================

    Removes the WYMeditor instance from existence and replaces the
    'data-wym-initialized' attirbute of its textarea with 'data-wym-vanished'.
*/
WYMeditor.editor.prototype.vanish = function () {
    var wym = this,
        instances = WYMeditor.INSTANCES,
        i;

    wym._box.remove();
    wym.element
        .removeAttr('data-wym-initialized')
        .attr('data-wym-vanished', '')
        .show();
    instances.splice(wym._index, 1);

    // Refresh each editor's _index value
    for (i = 0; i < instances.length; i++) {
        instances[i]._index = i;
    }
};

WYMeditor.editor.prototype._exec = function (cmd, param) {
    var wym = this,
        $span;

    if (typeof cmd !== "string") {
        throw "`_exec` expected a String `cmd`";
    }

    if (param && typeof param !== "string") {
        throw "`_exec` expected a String `param`";
    }

    if (
        wym.selectedContainer() === wym.body() &&
        // These are the two commands that are allowed directly in the body.
        cmd !== WYMeditor.EXEC_COMMANDS.INSERT_IMAGE &&
        cmd !== WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK
    ) {
        return false;
    }

    wym._doc.execCommand(cmd, false, param);

    $span = jQuery(wym.selectedContainer()).filter("span").not("[id]");
    if ($span.length === 0) {
        return true;
    }
    if (
        $span.attr("class") === "" &&
        $span.attr("style") === "font-weight: normal;" ||
        $span.attr("class").toLowerCase() === "apple-style-span"
    ) {
        // An undesireable `span` was created. WebKit & Blink do this.
        $span.contents().unwrap();
    }

    return true;
};

/**
    WYMeditor.editor.rawHtml
    =====================

    Get or set the wymbox html value. HTML is NOT parsed when either set/get.
    Use html() if you are unsure what this function does.
*/
WYMeditor.editor.prototype.rawHtml = function (html) {
    var wym = this;
    if (typeof html === 'string') {
        wym.$body().html(html);
        wym.update();
    } else {
        return wym.$body().html();
    }
};

/**
    WYMeditor.editor.html
    =====================

    Get or set the wymbox html value. HTML is parsed before it is inserted and
    parsed before it is return. Use rawHtml() if parsing is not wanted/needed.
*/
WYMeditor.editor.prototype.html = function (html) {
    var wym = this;
    if (typeof html === 'string') {
        wym.rawHtml(wym.parser.parse(html));
        wym.prepareDocForEditing();
    } else {
        return wym.parser.parse(wym.rawHtml());
    }
};

/**
    WYMeditor.editor.exec
    =====================

    Execute a button command on the currently-selected container. The command
    can be anything from "indent this element" to "open a dialog to create a
    table."

    `cmd` is a string corresponding to the command that should be run, roughly
    matching the designMode execCommand strategy (and falling through to
    execCommand in some cases).
*/
WYMeditor.editor.prototype.exec = function (cmd) {
    var wym = this,
        custom_run;
    switch (cmd) {

    case WYMeditor.EXEC_COMMANDS.TOGGLE_HTML:
        wym.update();
        wym.toggleHtml();
        break;

    case WYMeditor.EXEC_COMMANDS.INSERT_ORDEREDLIST:
        wym._insertOrderedList();
        break;

    case WYMeditor.EXEC_COMMANDS.INSERT_UNORDEREDLIST:
        wym._insertUnorderedList();
        break;

    case WYMeditor.EXEC_COMMANDS.INDENT:
        wym.indent();
        break;

    case WYMeditor.EXEC_COMMANDS.OUTDENT:
        wym.outdent();
        break;

    case WYMeditor.EXEC_COMMANDS.UNDO:
        wym.undoRedo.undo();
        break;

    case WYMeditor.EXEC_COMMANDS.REDO:
        wym.undoRedo.redo();
        break;


    default:
        custom_run = false;
        jQuery.each(wym._options.customCommands, function () {
            var customCommand = this;
            if (cmd === customCommand.name) {
                custom_run = true;
                customCommand.run.apply(wym);
                return false;
            }
        });
        if (!custom_run) {
            if (
                // Deligate all other commands to `_exec`
                wym._exec(cmd) === true
            ) {
                wym.registerModification();
            }
        }
        break;
    }
};

/**
    WYMeditor.editor.selection
    ==========================

    Override the default selection function to use rangy.
*/
WYMeditor.editor.prototype.selection = function () {
    var wym = this,
        iframe = wym._iframe,
        sel;

    if (window.rangy && !rangy.initialized) {
        rangy.init();
    }

    sel = rangy.getIframeSelection(iframe);

    return sel;
};

/**
    WYMeditor.editor.nodeAfterSel
    =============================

    Returns the node that is immediately after the selection.
*/
WYMeditor.editor.prototype.nodeAfterSel = function () {
    var wym = this,
       sel = wym.selection();

    // Different browsers describe selection differently. Here be dragons.
    if (
        sel.anchorNode.tagName &&
        jQuery.inArray(
            sel.anchorNode.tagName.toLowerCase(),
            WYMeditor.NON_CONTAINING_ELEMENTS
        ) === -1
    ) {
        if (sel.anchorNode.childNodes.length === 0) {
            return;
        }
        return sel.anchorNode.childNodes[sel.anchorOffset];
    }

    if (
        sel.focusNode.nodeType === WYMeditor.NODE_TYPE.TEXT &&
        sel.focusNode.data.length === sel.focusOffset
    ) {
        if (!sel.focusNode.nextSibling) {
            return;
        }
        return sel.focusNode.nextSibling;
    }

    return sel.focusNode;
};

/**
    WYMeditor.editor.get$CommonParent
    =================================

    Returns a jQuery of the common parent of two nodes.
*/
WYMeditor.editor.prototype.get$CommonParent = function (one, two) {
    if (
        typeof one !== 'object' ||
        typeof one.nodeType !== 'number' ||
        typeof two !== 'object' ||
        typeof two.nodeType !== 'number'
    ) {
        throw "`one` and `two` must be DOM nodes.";
    }

    if (one.nodeType === WYMeditor.NODE_TYPE.TEXT) {
        // These checks seem to be required for our tests to pass in PhantomJS.
        one = one.parentNode;
    }
    if (two.nodeType === WYMeditor.NODE_TYPE.TEXT) {
        // These checks seem to be required for our tests to pass in PhantomJS.
        two = two.parentNode;
    }

    if (one === two) {
        // This is just an optimisation.
        return jQuery(one);
    }

    var $one = jQuery(one),
        $two = jQuery(two),
        $commonParent;

    $commonParent = $one.parents().addBack().has($two).last();

    if ($commonParent.length === 0) {
        throw "Couldn't find common parent. This shouldn't happen.";
    }

    return $commonParent;
};

/**
    WYMeditor.editor.selectedContainer
    ==================================

    Get the selected container.

    * If no selection, returns `false`.
    * If selection starts and ends in the same element, returns that element.
    * If an element that contains one end of the selection is ancestor to the
      element that contains the other end, return that ancestor element.
    * Otherwise, returns `false`.

    For example (``|`` marks selection ends):

        <p>|Foo <i>bar|</i></p>

    The ``p`` is returned.

        <p>Foo <i>|bar|</i></p>

    The ``i`` is returned.
*/
WYMeditor.editor.prototype.selectedContainer = function () {
    var wym = this,
        selection,
        $anchor,
        $focus,
        $selectedContainer;

    if (wym.hasSelection() !== true) {
        return false;
    }

    selection = wym.selection();
    $anchor = jQuery(selection.anchorNode);
    $focus = jQuery(selection.focusNode);

    if ($anchor[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
        $anchor = $anchor.parent();
    }

    if ($focus[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
        $focus = $focus.parent();
    }

    if ($anchor[0] === $focus[0]) {
        return $anchor[0];
    }

    $selectedContainer = $anchor.has($focus);
    if ($selectedContainer.length === 0) {
        $selectedContainer = $focus.has($anchor);
    }

    if ($selectedContainer.length === 0) {
        return false;
    }

    return $selectedContainer[0];
};

// Deprecated in favor of `WYMeditor.editor.selectedContainer`.
WYMeditor.editor.prototype.selected = function () {
    var wym = this;

    WYMeditor.console.warn(
        "The function WYMeditor.editor.selected() is " +
        "deprecated. Use WYMeditor.editor.selectedContainer"
    );

    return wym.selectedContainer();
};

/**
    WYMeditor.editor.isBlockNode
    =============================

    Returns true if the provided node is a block type node. Otherwise
    returns false.

    @param node The node to check.
*/

WYMeditor.editor.prototype.isBlockNode = function (node) {
    if (
        node.tagName &&
        jQuery.inArray(
            node.tagName.toLowerCase(),
            WYMeditor.BLOCKS
        ) > -1
    ) {
        return true;
    }
    return false;
};

/**
    WYMeditor.editor.isInlineNode
    =============================

    Returns true if the provided node is an inline type node. Otherwise
    returns false.

    @param node The node to check.
*/

WYMeditor.editor.prototype.isInlineNode = function (node) {
    if (
        node.nodeType === WYMeditor.NODE_TYPE.TEXT ||
        jQuery.inArray(
            node.tagName.toLowerCase(),
            WYMeditor.INLINE_ELEMENTS
        ) > -1
    ) {
        return true;
    }
    return false;
};

/**
    WYMeditor.editor.isListNode
    ===========================

    Returns true if the provided node is a list element. Otherwise
    returns false.

    @param node The node to check.
*/

WYMeditor.editor.prototype.isListNode = function (node) {
    if (
        node.tagName &&
        jQuery.inArray(
            node.tagName.toLowerCase(),
            WYMeditor.LIST_TYPE_ELEMENTS
        ) > -1
    ) {
        return true;
    }
    return false;
};

/**
   WYMeditor.editor.unwrapIfMeaninglessSpan

   If the given node is a span with no useful attributes, unwrap it.

   For certain editing actions (mostly list indent/outdent), it's necessary to
   wrap content in a span element to retain grouping because it's not obvious that
   the content will stay together without grouping. This method detects that
   specific situation and then unwraps the content if the span is in fact not
   necessary.

   @param element The element.
*/
WYMeditor.editor.prototype.unwrapIfMeaninglessSpan = function (element) {
    var $element = jQuery(element),
        i = 0,
        attrName,
        meaninglessAttrNames = [
            '_wym_visited',
            'length',
            'ie8_length'
        ];

    if (!element || typeof (element.tagName) === 'undefined' ||
        element.tagName.toLowerCase() !== 'span') {
        return false;
    }

    while (i < element.attributes.length) {
        attrName = element.attributes[i].nodeName;
        if (jQuery.inArray(attrName, meaninglessAttrNames) === -1) {
            return false;
        }
        i++;
    }

    $element.before($element.contents());
    $element.remove();
    return true;
};

/**
    WYMeditor.editor.getRootContainer
    =================================

    Get the selected root container.
*/
WYMeditor.editor.prototype.getRootContainer = function () {
    var wym = this;

    return jQuery(wym.selectedContainer())
        .parentsOrSelf()
        .not('html, body, blockquote')
        .last()[0];
};

/**
    WYMeditor.editor.setRootContainer
    =================================

    Set the selected root container.
*/
WYMeditor.editor.prototype.setRootContainer = function (sType) {
    var wym = this,
        container = null,
        aTypes,
        newNode,
        blockquote,
        nodes,
        lgt,
        firstNode,
        x;

    if (sType.toLowerCase() === WYMeditor.TH) {
        container = wym.selectedContainer();

        // Find the TD or TH container
        switch (container.tagName.toLowerCase()) {

        case WYMeditor.TD:
        case WYMeditor.TH:
            break;
        default:
            aTypes = [WYMeditor.TD, WYMeditor.TH];
            container = wym.findUp(wym.selectedContainer(), aTypes);
            break;
        }

        // If it exists, switch
        if (container !== null) {
            sType = WYMeditor.TD;
            if (container.tagName.toLowerCase() === WYMeditor.TD) {
                sType = WYMeditor.TH;
            }
            wym.restoreSelectionAfterManipulation(function () {
                wym.switchTo(container, sType, false);
                return true;
            });
            wym.update();
            wym.registerModification();
        }
    } else {
        // Set the container type
        aTypes = [
            WYMeditor.P,
            WYMeditor.DIV,
            WYMeditor.H1,
            WYMeditor.H2,
            WYMeditor.H3,
            WYMeditor.H4,
            WYMeditor.H5,
            WYMeditor.H6,
            WYMeditor.PRE,
            WYMeditor.BLOCKQUOTE
        ];
        container = wym.findUp(wym.selectedContainer(), aTypes);

        if (container) {
            if (sType.toLowerCase() === WYMeditor.BLOCKQUOTE) {
                // Blockquotes must contain a block level element
                blockquote = wym.findUp(
                    wym.selectedContainer(),
                    WYMeditor.BLOCKQUOTE
                );
                if (blockquote === null) {
                    newNode = wym._doc.createElement(sType);
                    container.parentNode.insertBefore(newNode, container);
                    newNode.appendChild(container);
                    wym.setCaretIn(newNode.firstChild);
                } else {
                    nodes = blockquote.childNodes;
                    lgt = nodes.length;

                    if (lgt > 0) {
                        firstNode = nodes.item(0);
                    }
                    for (x = 0; x < lgt; x += 1) {
                        blockquote.parentNode.insertBefore(
                            nodes.item(0),
                            blockquote
                        );
                    }
                    blockquote.parentNode.removeChild(blockquote);
                    if (firstNode) {
                        wym.setCaretIn(firstNode);
                    }
                }
            } else {
                // Not a blockquote
                wym.restoreSelectionAfterManipulation(function () {
                    wym.switchTo(container, sType, false);
                    return true;
                });
            }

            wym.update();
            wym.registerModification();
        }
    }

    return false;
};

/**
    WYMeditor.editor.isForbiddenRootContainer
    =========================================

    Returns true if provided `tagName` is disallowed as a root container.
    Returns false if it is allowed.

    @param tagName A string of the tag name.
*/
WYMeditor.editor.prototype.isForbiddenRootContainer = function (tagName) {
    return jQuery.inArray(tagName.toLowerCase(),
                          WYMeditor.FORBIDDEN_ROOT_CONTAINERS) > -1;
};

/**
    WYMeditor.editor.keyCanCreateBlockElement
    =========================================

    Determines whether the key represented by the passed keyCode can create a
    block element within the editor when pressed. Returns true if the key can
    create a block element when pressed, and returns false if otherwise.

    @param keyCode A numberic key code representing a key
*/
WYMeditor.editor.prototype.keyCanCreateBlockElement = function (keyCode) {
    return jQuery.inArray(keyCode,
                    WYMeditor.POTENTIAL_BLOCK_ELEMENT_CREATION_KEYS) > -1;
};

/**
    WYMeditor.editor.toggleClass
    ============================

    Toggle a class on the selected element or one of its parents
*/
WYMeditor.editor.prototype.toggleClass = function (sClass, jqexpr) {
    var wym = this,
        $element;

    $element = jQuery(wym.getSelectedImage());
    if ($element.length !== 1) {
        $element = jQuery(wym.selectedContainer())
            // `.last()` is used here because the `.addBack()` from
            // `.parentsOrSelf` reverses the array.
            .parentsOrSelf(jqexpr).last();
    }
    $element.toggleClass(sClass);

    if (!$element.attr(WYMeditor.CLASS)) {
        $element.removeAttr(wym._class);
    }
    wym.registerModification();
};

/**
    WYMeditor.editor.getSelectedImage
    =================================

    If selection encompasses exactly a single image, returns that image.
    Otherwise returns `false`.
*/
WYMeditor.editor.prototype.getSelectedImage = function () {
    var wym = this,
        selectedNodes,
        selectedNode;

    if (wym.hasSelection() !== true) {
        return false;
    }
    if (wym.selection().isCollapsed !== false) {
        return false;
    }

    selectedNodes = wym._getSelectedNodes();

    if (selectedNodes.length !== 1) {
        return false;
    }

    selectedNode = selectedNodes[0];

    if (
        !selectedNode.tagName ||
        selectedNode.tagName.toLowerCase() !== "img"
    ) {
        return false;
    }

    return selectedNode;
};

/**
    WYMeditor.editor.findUp
    =======================

    Return the first parent or self container, based on its type

    `filter` is a string or an array of strings on which to filter the container
*/
WYMeditor.editor.prototype.findUp = function (node, filter) {
    if (typeof (node) === 'undefined' || node === null) {
        return null;
    }

    if (node.nodeName === "#text") {
        // For text nodes, we need to look from the nodes container object
        node = node.parentNode;
    }
    var tagname = node.tagName.toLowerCase(),
        bFound,
        i;
    if (typeof (filter) === WYMeditor.STRING) {
        while (tagname !== filter && tagname !== WYMeditor.BODY) {
            node = node.parentNode;
            tagname = node.tagName.toLowerCase();
        }
    } else {
        bFound = false;
        while (!bFound && tagname !== WYMeditor.BODY) {
            for (i = 0; i < filter.length; i += 1) {
                if (tagname === filter[i]) {
                    bFound = true;
                    break;
                }
            }
            if (!bFound) {
                node = node.parentNode;
                if (node === null) {
                    // No parentNode, so we're not going to find anything
                    // up the ancestry chain that matches
                    return null;
                }
                tagname = node.tagName.toLowerCase();
            }
        }
    }

    if (tagname === WYMeditor.BODY) {
        return null;
    }

    return node;
};

/**
    WYMeditor.editor.switchTo
    =========================

    Switch the type of an element.

    @param element The element.
    @param sType A string of the desired type. For example, 'p'.
    @param stripAttrs a boolean that determines whether the attributes of
                      the element will be stripped or preserved.

*/
WYMeditor.editor.prototype.switchTo = function (
    element,
    sType,
    stripAttrs
) {
    var wym = this,
        $element = jQuery(element),
        newElement,
        i,
        attrs = element.attributes;

    if (!element.tagName) {
        throw "This must be an element.";
    }

    if (element.tagName.toLowerCase() === 'img') {
        throw "Will not change the type of an 'img' element.";
    }

    newElement = wym._doc.createElement(sType);
    jQuery(newElement).append(element.childNodes);
    $element.replaceWith(newElement);

    if (!stripAttrs) {
        for (i = 0; i < attrs.length; ++i) {
            newElement.setAttribute(
                attrs.item(i).nodeName,
                attrs.item(i).value
            );
        }
    }

    return newElement;
};

WYMeditor.editor.prototype.replaceStrings = function (sVal) {
    var wym = this,
        key;
    // Check if the language file has already been loaded
    // if not, get it via a synchronous ajax call
    if (!WYMeditor.STRINGS[wym._options.lang]) {
        WYMeditor.console.error(
            "WYMeditor: language '" + wym._options.lang + "' not found."
        );
        WYMeditor.console.error(
            "Unable to perform i10n."
        );
        return sVal;
    }

    // Replace all the strings in sVal and return it
    for (key in WYMeditor.STRINGS[wym._options.lang]) {
        if (WYMeditor.STRINGS[wym._options.lang].hasOwnProperty(key)) {
            sVal = WYMeditor.Helper.replaceAllInStr(
                sVal,
                wym._options.stringDelimiterLeft + key + wym._options.stringDelimiterRight,
                WYMeditor.STRINGS[wym._options.lang][key]
            );
        }
    }
    return sVal;
};

WYMeditor.editor.prototype._encloseString = function (sVal) {
    var wym = this;
    return wym._options.stringDelimiterLeft +
        sVal +
        wym._options.stringDelimiterRight;
};

/**
    editor.getCurrentState
    ======================

    Returns an object with the current state of the editor.

    The state includes:

    ``html``
        The return value of ``editor.rawHtml()``.
    ``savedSelection``
        A Rangy saved selection, if anything is selected.
        The ``win`` and the ``doc``  properties are deleted,
        instead of referencing the window object and the document object,
        respectively.
        In order to provide this as an argument to Rangy's ``restoreSelection``,
        these must be reassigned.

    It may include more things in the future.
*/
WYMeditor.editor.prototype.getCurrentState = function () {
    var wym = this,
        state = {},
        selection,
        wymIframeWindow = wym._iframe.contentWindow;

    if (wym.hasSelection()) {
        selection = wym.selection();
    }

    if (
        selection &&
        selection.anchorNode === wym.body() &&
        selection.anchorOffset === 0 &&
        selection.isCollapsed
    ) {
        // meaningless selection
        selection = false;
    }

    if (selection) {
        state.savedSelection = rangy.saveSelection(wymIframeWindow);
    }

    state.html = wym.rawHtml();

    if (state.savedSelection) {
        // Selection was saved. This means that in the document, DOM elements,
        // which are markers for the selection, were placed, and that references
        // to these markers were saved in `state.savedselection`. The markers
        // were saved in `state.html`, along with the whole document, as HTML.
        // Restoring the selection removes the markers and restores the
        // selection to almost exactly as it was before it was saved.
        rangy.restoreSelection(state.savedSelection);
        // This is for time-travel, so selection is considered not to be
        // restored. The markers may be created again from the saved HTML. In
        // that case, leaving this value at `true` would mean that
        // `rangy.restoreSelection` will refuse to restore this selection.
        state.savedSelection.restored = false;
        // These refer to the window and the document and can't be processed by
        // the `object-history` module that is used by the `UndoRedo` module.
        delete state.savedSelection.win;
        delete state.savedSelection.doc;
    }

    return state;
};

/**
    editor.hasSelection
    ===================

    Returns true if there is a selection. Returns false otherwise.
*/
WYMeditor.editor.prototype.hasSelection = function () {
    var wym = this;

    if (
        // `isSelectionValid` is undocumented in current Rangy (`1.2.2`).
        // It seems to be required because the `rangeCount` in `IE <= 8` seems
        // to be misleading.
        rangy.isSelectionValid(wym._iframe.contentWindow) !== true
    ) {
        return false;
    }

    if (wym.selection().rangeCount === 0) {
        return false;
    }

    return true;
};

/**
    editor._setSingleSelectionRange
    ===============================

    Sets the selection to the single provided Rangy range.

    @param range A Rangy range.
*/
WYMeditor.editor.prototype._setSingleSelectionRange = function (range) {
    var wym = this,
        selection;

    selection = wym.selection();

    selection.setSingleRange(range);
};

/**
    editor.status
    =============

    Print the given string as a status message.
*/
WYMeditor.editor.prototype.status = function (sMessage) {
    var wym = this;
    // Print status message
    jQuery(wym._box).find(wym._options.statusSelector).html(sMessage);
};

/**
    editor.update
    =============

    Update the element and textarea values.
*/
WYMeditor.editor.prototype.update = function () {
    var wym = this,
        html;

    html = wym.html();
    jQuery(wym.element).val(html);
    jQuery(wym._box).find(wym._options.htmlValSelector).not('.hasfocus').val(html); //#147
};

/**
    editor.prepareDocForEditing
    ===========================

    Makes some editor-only modifications to the body of the document, which are necessary
    for the user interface. For example, inserts `br` elements in certain places.
    These modifications will not show up in the HTML output.

*/
WYMeditor.editor.prototype.prepareDocForEditing = function () {
    var wym = this,
        $body;

    wym._spaceBlockingElements();
    wym._fixDoubleBr();

    $body = wym.$body();
    if ($body.children().length === 0) {
        wym.$body().append('<br />');
    }

    jQuery(wym.element).trigger(WYMeditor.EVENTS.postBlockMaybeCreated, wym);
};

/**
    editor._spaceBlockingElements
    =============================

    Insert <br> elements between adjacent blocking elements and
    p elements, between block elements or blocking elements and the
    start/end of the document.
*/
WYMeditor.editor.prototype._spaceBlockingElements = function () {
    var wym = this,
        blockingSelector =
            WYMeditor.DocumentStructureManager.CONTAINERS_BLOCKING_NAVIGATION.join(', '),
        $body = wym.$body(),
        children = $body.children(),

        placeholderNode,
        $firstChild,
        $lastChild,
        blockSepSelector,
        blockInListSepSelector,
        $blockInList;

    if (jQuery.browser.mozilla) {
        placeholderNode = '<br ' +
                            'class="' +
                            WYMeditor.BLOCKING_ELEMENT_SPACER_CLASS + ' ' +
                            WYMeditor.EDITOR_ONLY_CLASS + '" ' +
                            '_moz_editor_bogus_node="TRUE" ' +
                            '_moz_dirty=""' +
                          '/>';
    } else {
        placeholderNode = '<br ' +
                            'class="' +
                            WYMeditor.BLOCKING_ELEMENT_SPACER_CLASS + ' ' +
                            WYMeditor.EDITOR_ONLY_CLASS + '"' +
                          '/>';
    }

    // Make sure that we still have a placeholder node at both the begining and
    // end
    if (children.length > 0) {
        $firstChild = jQuery(children[0]);
        $lastChild = jQuery(children[children.length - 1]);

        if ($firstChild.is(blockingSelector)) {
            $firstChild.before(placeholderNode);
        }

        if ($lastChild.is(blockingSelector)) {
            $lastChild.after(placeholderNode);
        }
    }

    blockSepSelector = wym._getBlockSepSelector();

    // Put placeholder nodes between consecutive blocking elements and between
    // blocking elements and normal block-level elements
    $body.find(blockSepSelector).before(placeholderNode);

    blockInListSepSelector = wym._getBlockInListSepSelector();
    $blockInList = $body.find(blockInListSepSelector);

    // The $blockInList selection must be iterated over to only add placeholder
    // nodes after blocking elements at the end of a list item rather than all
    // blocking elements in a list. No jQuery selection that is supported on
    // all browsers can do this check, so that is why it must be done by using
    // `each` to iterate over the selection. Note that the handling of the
    // spacing of other blocking elements in a list besides after the last
    // blocking element in a list item is already handled by the
    // blockSepSelector used before this.
    $blockInList.each(function () {
        var block = this,
            $block = jQuery(block);

        if (!$block.next(blockingSelector).length &&
           !$block.next('br').length) {

            $block.after(placeholderNode);
        }
    });
};

/**
    editor._getBlockSepSelector
    ===========================

    Build a string representing a jquery selector that will find all
    elements which need a spacer <br> before them. This includes all consecutive
    blocking elements and between blocking elements and normal non-blocking
    elements.
*/
WYMeditor.editor.prototype._getBlockSepSelector = function () {
    var wym = this,
        blockCombo = [],
        containersBlockingNav =
            WYMeditor.DocumentStructureManager.CONTAINERS_BLOCKING_NAVIGATION,
        containersNotBlockingNav;

    if (typeof (wym._blockSpacersSel) !== 'undefined') {
        return wym._blockSpacersSel;
    }

    // Generate the list of non-blocking elements by removing the blocking
    // elements from the list of validRootContainers
    containersNotBlockingNav = jQuery.grep(
        wym.documentStructureManager.structureRules.validRootContainers,
        function (item) {
            return jQuery.inArray(item, containersBlockingNav) === -1;
        }
    );

    // Consecutive blocking elements need separators
    jQuery.each(
        containersBlockingNav,
        function (indexO, elementO) {
            jQuery.each(
                containersBlockingNav,
                function (indexI, elementI) {
                    blockCombo.push(elementO + ' + ' + elementI);
                }
            );
        }
    );

    // A blocking element either followed by or preceeded by a not blocking
    // element needs separators
    jQuery.each(
        containersBlockingNav,
        function (indexO, elementO) {
            jQuery.each(
                containersNotBlockingNav,
                function (indexI, elementI) {
                    blockCombo.push(elementO + ' + ' + elementI);
                    blockCombo.push(elementI + ' + ' + elementO);
                }
            );
        }
    );
    wym._blockSpacersSel = blockCombo.join(', ');
    return wym._blockSpacersSel;
};

/*
    editor._getBlockInListSepSelector
    =================================

    Returns a selector for getting all of the block elements in lists
    or sublists. The block elements at the end of lists or sublists should have
    a spacer line break after them in the editor at all times.
*/
WYMeditor.editor.prototype._getBlockInListSepSelector = function () {
    var wym = this,
        blockCombo = [];

    if (typeof (wym._blockInListSpacersSel) !== 'undefined') {
        return wym._blockInListSpacersSel;
    }

    jQuery.each(WYMeditor.LIST_TYPE_ELEMENTS, function (indexO, elementO) {
        jQuery.each(WYMeditor.BLOCKING_ELEMENTS, function (indexI, elementI) {
            blockCombo.push(elementO + ' ' + elementI);
        });
    });

    wym._blockInListSpacersSel = blockCombo.join(', ');
    return wym._blockInListSpacersSel;
};

/**
    editor._fixDoubleBr
    ===================

    Remove the <br><br> elements that are inserted between
    paragraphs, usually after hitting enter from an existing paragraph.
*/
WYMeditor.editor.prototype._fixDoubleBr = function () {
    var wym = this,
        $body = wym.$body(),
        $last_br;

    // Strip consecutive brs unless they're in a pre tag
    $body.children('br + br').filter(':not(pre br)').remove();

    // Also remove any brs between two p's
    $body.find('p + br').next('p').prev('br').remove();

    // Remove brs floating at the end after a p
    $last_br = $body.find('p + br').slice(-1);
    if ($last_br.length > 0) {
        if ($last_br.next().length === 0) {
            $last_br.remove();
        }
    }
};

/**
    WYMeditor.editor.link
    ======================

    Creates a link, or changes attributes of an `a`, at selection.

    @param attrs Object with key-value pairs of attributes for the `a`.
*/
WYMeditor.editor.prototype.link = function (attrs) {
    var wym = this,
        $selected,
        uniqueStamp,
        $a;

    if (jQuery.isPlainObject(attrs) !== true) {
        throw "Expected a plain object.";
    }

    if (
        attrs.hasOwnProperty('href') !== true ||
        typeof attrs.href !== 'string' ||
        attrs.href.length === 0
    ) {
        // Would probably be best to throw here, but...
        // This is used by a dialog that doesn't check input.
        // The dialog is created by `WYMeditor.INIT_DIALOG`.
        return;
    }

    $selected = jQuery(wym.selectedContainer());
    if ($selected.is('a')) {
        $a = $selected;
    } else {
        uniqueStamp = wym.uniqueStamp();
        wym._exec(WYMeditor.EXEC_COMMANDS.CREATE_LINK, uniqueStamp);
        $a = jQuery("a[href=" + uniqueStamp + "]", wym.body());
    }

    if ($a.length === 0) {
        // This occurs when a link wasn't created, because, for example
        // the selection didn't allow it.
        return;
    }
    $a.attr(attrs);

    wym.registerModification();
};

/**
    WYMeditor.editor.insertImage
    ============================

    Inserts an image at selection.

    @param attrs Object with key-value pairs of attributes for the `img`.
*/
WYMeditor.editor.prototype.insertImage = function (attrs) {
    var wym = this,
        uniqueStamp,
        $img;

    if (jQuery.isPlainObject(attrs) !== true) {
        throw "Expected a plain object.";
    }

    if (
        attrs.hasOwnProperty('src') !== true ||
        typeof attrs.src !== 'string' ||
        attrs.src.length === 0
    ) {
        // Would probably be best to throw here, but...
        // This is used by a dialog that doesn't check input.
        // The dialog is created by `WYMeditor.INIT_DIALOG`.
        return;
    }

    uniqueStamp = wym.uniqueStamp();
    wym._exec(WYMeditor.EXEC_COMMANDS.INSERT_IMAGE, uniqueStamp);
    $img = jQuery("img[src=" + uniqueStamp + "]", wym.body());

    if ($img.length === 0) {
        // This occurs when a link wasn't created, because, for example
        // the selection didn't allow it.
        return;
    }
    $img.attr(attrs);

    // PhantomJS seems to add strange spans around images.
    wym.$body().find('.Apple-style-span').children().unwrap();

    wym.registerModification();
};

/**
    editor._updateImageAttrs
    ========================

    Updates provided `img`'s attributes with provided `attrs`.
*/
WYMeditor.editor.prototype._updateImageAttrs = function (img, attrs) {
    var $img = jQuery(img);
    if (attrs.src !== $img.attr('src')) {
        // this data is used in the ImageHandler.
        // height/width ratio is now most likely invalid
        $img.data('DimensionsRatio', null);

        // since the height/width ration is most likely different
        // these proportions are most likely wrong.
        // easiest solution is to remove them
        // and let the user deal with
        // the real size of the source image
        // and he'll be able to resize it
        $img.removeAttr('height').removeAttr('width');
    }
    $img.attr(attrs);
};

/**
    editor.toggleHtml
    =================

    Show/Hide the HTML textarea.
*/
WYMeditor.editor.prototype.toggleHtml = function () {
    var wym = this;
    jQuery(wym._box).find(wym._options.htmlSelector).toggle();
};

WYMeditor.editor.prototype.uniqueStamp = function () {
    var now = new Date();
    return "wym" + now.getTime();
};

/**
    Paste the given array of paragraph-items at the given range inside the given $container.

    It has already been determined that the paragraph has multiple lines and
    that the container we're pasting to is a block container capable of accepting
    further nested blocks.
*/
WYMeditor.editor.prototype._handleMultilineBlockContainerPaste = function (
    wym, $container, range, paragraphStrings
) {

    var i,
        $insertAfter,
        html,
        blockSplitter,
        leftSide,
        rightSide,
        rangeNodeComparison,
        $splitRightParagraph,
        firstParagraphString,
        firstParagraphHtml,
        blockParent,
        blockParentType;


    // Now append all subsequent paragraphs
    $insertAfter = jQuery(blockParent);

    // Just need to split the current container and put new block elements
    // in between
    blockSplitter = 'p';
    if ($container.is('li')) {
        // Instead of creating paragraphs on line breaks, we'll need to create li's
        blockSplitter = 'li';
    }
    // Split the selected element then build and insert the appropriate html
    // This accounts for cases where the start selection is at the
    // start of a node or in the middle of a text node by splitting the
    // text nodes using rangy's splitBoundaries()
    range.splitBoundaries(); // Split any partially-select text nodes
    blockParent = wym.findUp(
        range.startContainer,
        ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li']
    );
    blockParentType = blockParent.tagName;
    leftSide = [];
    rightSide = [];
    jQuery(blockParent).contents().each(function (index, element) {
        // Capture all of the dom nodes to the left and right of our
        // range. We can't remove them in the same step because that
        // loses the selection in webkit

        rangeNodeComparison = range.compareNode(element);
        if (rangeNodeComparison === range.NODE_BEFORE ||
                (rangeNodeComparison === range.NODE_BEFORE_AND_AFTER &&
                 range.startOffset === range.startContainer.length)) {
            // Because of the way splitBoundaries() works, the
            // collapsed selection might appear in the right-most index
            // of the border node, which means it will show up as
            //
            // eg. | is the selection and <> are text node boundaries
            // <foo|><bar>
            //
            // We detect that case by counting any
            // NODE_BEFORE_AND_AFTER result where the offset is at the
            // very end of the node as a member of the left side
            leftSide.push(element);
        } else {
            rightSide.push(element);
        }
    });
    // Now remove all of the left and right nodes
    for (i = 0; i < leftSide.length; i++) {
        jQuery(leftSide[i]).remove();
    }
    for (i = 0; i < rightSide.length; i++) {
        jQuery(rightSide[i]).remove();
    }

    // Rebuild our split nodes and add the inserted content
    if (leftSide.length > 0) {
        // We have left-of-selection content
        // Put the content back inside our blockParent
        jQuery(blockParent).prepend(leftSide);
    }
    if (rightSide.length > 0) {
        // We have right-of-selection content.
        // Split it off in to a node of the same type after our
        // blockParent
        $splitRightParagraph = jQuery('<' + blockParentType + '>' +
            '</' + blockParentType + '>', wym._doc);
        $splitRightParagraph.insertAfter(jQuery(blockParent));
        $splitRightParagraph.append(rightSide);
    }

    // Insert the first paragraph in to the current node, and then
    // start appending subsequent paragraphs
    firstParagraphString = paragraphStrings.splice(
        0,
        1
    )[0];
    firstParagraphHtml = firstParagraphString.split(WYMeditor.NEWLINE).join('<br />');
    jQuery(blockParent).html(jQuery(blockParent).html() + firstParagraphHtml);

    // Now append all subsequent paragraphs
    $insertAfter = jQuery(blockParent);
    for (i = 0; i < paragraphStrings.length; i++) {
        html = '<' + blockSplitter + '>' +
            (paragraphStrings[i].split(WYMeditor.NEWLINE).join('<br />')) +
            '</' + blockSplitter + '>';
        $insertAfter = jQuery(html, wym._doc).insertAfter($insertAfter);
    }
};

/**
    editor.paste
    ============

    Paste text into the editor below the carret, used for "Paste from Word".

    Takes the string to insert as an argument. Two or more newlines separates
    paragraphs. May contain inline HTML.
*/
WYMeditor.editor.prototype.paste = function (str) {
    var wym = this,
        container = wym.selectedContainer(),
        paragraphStrings,
        j,
        textNodesToInsert,
        blockSplitter,
        $container = jQuery(container),
        html = '',
        paragraphs,
        i,
        isSingleLine = false,
        sel = wym.selection(),
        textNode,
        range = sel.getRangeAt(0),
        insertionNodes;

    // Start by collapsing the range to the start of the selection. We're
    // punting on implementing a paste that also replaces existing content for
    // now,
    range.collapse(true); // Collapse to the the begining of the selection

    // Split string into paragraphs by two or more newlines
    paragraphStrings = str.split(new RegExp(WYMeditor.NEWLINE + '{2,}', 'g'));

    if (paragraphStrings.length === 1) {
        // This is a one-line paste, which is an easy case.
        // We try not to wrap these in paragraphs
        isSingleLine = true;
    }

    if (typeof container === 'undefined' ||
            (container && container.tagName.toLowerCase() === WYMeditor.BODY)) {
        // No selection, or body selection. Paste at the end of the document

        if (isSingleLine) {
            // Easy case. Wrap the string in p tags
            paragraphs = jQuery(
                '<p>' + paragraphStrings[0] + '</p>',
                wym._doc
            ).appendTo(wym._doc.body);
        } else {
            // Need to build paragraphs and insert them at the end
            blockSplitter = 'p';
            for (i = paragraphStrings.length - 1; i >= 0; i -= 1) {
                // Going backwards because rangy.insertNode leaves the
                // selection in front of the inserted node
                html = '<' + blockSplitter + '>' +
                    (paragraphStrings[i].split(WYMeditor.NEWLINE).join('<br />')) +
                    '</' + blockSplitter + '>';
                // Build multiple nodes from the HTML because ie6 chokes
                // creating multiple nodes implicitly via jquery
                insertionNodes = jQuery(html, wym._doc);
                for (j = insertionNodes.length - 1; j >= 0; j--) {
                    // Loop backwards through all of the nodes because
                    // insertNode moves that direction
                    range.insertNode(insertionNodes[j]);
                }
            }
        }
    } else {
        // Pasting inside an existing element
        if (isSingleLine || $container.is('pre')) {
            // Easy case. Insert a text node at the current selection
            textNode = wym._doc.createTextNode(str);
            range.insertNode(textNode);
        } else if ($container.is('p,h1,h2,h3,h4,h5,h6,li')) {
            wym._handleMultilineBlockContainerPaste(wym, $container, range, paragraphStrings);
        } else {
            // We're in a container that doesn't accept nested paragraphs (eg. td). Use
            // <br> separators everywhere instead
            textNodesToInsert = str.split(WYMeditor.NEWLINE);
            for (i = textNodesToInsert.length - 1; i >= 0; i -= 1) {
                // Going backwards because rangy.insertNode leaves the
                // selection in front of the inserted node
                textNode = wym._doc.createTextNode(textNodesToInsert[i]);
                range.insertNode(textNode);
                if (i > 0) {
                    // Don't insert an opening br
                    range.insertNode(jQuery('<br />', wym._doc).get(0));
                }
            }
        }
    }
    wym.registerModification();
};

WYMeditor.editor.prototype.insert = function (html) {
    // Do we have a selection?
    var wym = this,
        selection = wym.hasSelection() ? wym.selection() : false,
        range,
        node;
    if (selection) {
        // Overwrite selection with provided html
        range = selection.getRangeAt(0);
        node = range.createContextualFragment(html);
        range.deleteContents();
        range.insertNode(node);
    }
};

/**
    editor.canSetCaretBefore
    ========================

    Returns true if it is OK to set a collapsed selection immediately before
    a node. Otherwise returns false.

    @param node A node to check about.
 */
WYMeditor.editor.prototype.canSetCaretBefore = function (node) {
    var wym = this;
    if (node.nodeType === WYMeditor.NODE_TYPE.TEXT) {
        return true;
    }
    if (
        node.tagName &&
        node.tagName.toLowerCase() === 'br'
    ) {
        if (
            !node.previousSibling
        ) {
            return true;

        } else if (
            node.previousSibling.tagName &&
            node.previousSibling.tagName.toLowerCase() === 'br'
        ) {
            return true;

        } else if (wym.isBlockNode(node.previousSibling)) {
            return true;

        } else if (node.previousSibling.nodeType === WYMeditor.NODE_TYPE.TEXT) {
            return true;
        }
    }
    return false;
};

/**
    editor.setCaretBefore
    =====================

    Sets a collapsed selection to immediately before a provided node.

    Not to be confused with `editor.setCaretIn`, which sets a collapsed
    selection inside a container node, at the start.

    @param node A node to set the selection to immediately before of.
 */
WYMeditor.editor.prototype.setCaretBefore = function (node) {
    var wym = this,
        range = rangy.createRange(wym._doc),
        selection = wym.selection();

    if (!wym.canSetCaretBefore(node)) {
        throw "Can't set caret before this node.";
    }

    range.selectNode(node);
    range.collapse(true);

    selection.setSingleRange(range);
};

/**
    editor.canSetCaretIn
    ====================

    Returns true if it is OK to set a collapsed selection inside a node.
    Otherwise returns false.

    @param node A node to check about.
 */
WYMeditor.editor.prototype.canSetCaretIn = function (node) {
    var wym = this;
    if (
        node.nodeType === WYMeditor.NODE_TYPE.TEXT ||
        (
            node.tagName &&
            jQuery.inArray(
                node.tagName.toLowerCase(),
                WYMeditor.NO_CARET_ELEMENTS
            ) > -1
        )
    ) {
        return false;
    }
    // Rangy issue #209.
    if (wym.isInlineNode(node)) {

        if (node.childNodes.length === 0) {
            // Not possible to work-around this issue.
            return false;
        }
        // It is possible to work-around this issue by setting a non-collapsed
        // selection. Warn about this.
        WYMeditor.console.warn("Can set a non-collapsed selection. Rangy issue #209.");
    }
    return true;
};

/**
    editor.setCaretIn
    =================

    Sets a collapsed selection to inside provided container element, at the start.

    Not to be confused with `editor.setCaretBefore`, which sets a collapsed
    selection immediately before a node.

    @param element An element to set the selection inside of, at the start.
 */
WYMeditor.editor.prototype.setCaretIn = function (element) {
    var wym = this,
        range = rangy.createRange(wym._doc),
        selection = wym.selection();

    if (
        !wym.canSetCaretIn(element)
    ) {
        throw "The element must be able to contain other elements. Perhaps " +
            " you would like to use `setCaretBefore`, instead.";
    }

    range.selectNodeContents(element);

    // Rangy issue #209.
    if (wym.isInlineNode(element)) {

        // Don't collapse the range. As long as
        // this occurs only in tests it is probably OK. Warn.
        WYMeditor.console.warn("Can't set a collapsed selection. Setting " +
           "a non-collapsed selection, instead. Rangy issue #209.");
    } else {
        range.collapse(true);
    }

    selection.setSingleRange(range);
};

/**
    editor._splitListItemContents
    =============================

    Utility

    Splits a list item into the content that should stay with the li as it is
    indented/outdent and the things that should stay at their current indent level.

    `itemContents` are what a user would consider that list's contents
    `sublistContents` are the sub-items that are nested inside the li
    (basically everything after the first ol/ul inclusive).

    The returned object has `itemContents` and `sublistContents` properties.
*/
WYMeditor.editor.prototype._splitListItemContents = function ($listItem) {
    var $allContents,
        i,
        elmnt,
        hitSublist = false,
        splitObject = {itemContents: [], sublistContents: []};

    $allContents = $listItem.contents();

    for (i = 0; i < $allContents.length; i++) {
        elmnt = $allContents.get(i);
        if (hitSublist || jQuery(elmnt).is('ol,ul')) {
            // We've hit the first sublist. Everything from this point on is
            // considered `sublistContents`
            hitSublist = true;
            splitObject.sublistContents.push(elmnt);
        } else {
            splitObject.itemContents.push(elmnt);
        }
    }

    return splitObject;
};

/**
    editor._joinAdjacentLists
    =========================

    Utility

    Joins two lists if they are adjacent and are of the same type.

    The end result will be `listTwo`s contents being appended to `listOne`
*/
WYMeditor.editor.prototype._joinAdjacentLists = function (listOne, listTwo) {
    var $listTwoContents;

    if (typeof listOne === 'undefined' ||
            typeof listTwo === 'undefined') {
        // Invalid arguments
        return;
    }
    if (listOne.nextSibling !== listTwo ||
            listOne.tagName.toLowerCase() !== listTwo.tagName.toLowerCase()) {
        return;
    }

    $listTwoContents = jQuery(listTwo).contents();
    $listTwoContents.unwrap(); // Kill listTwo
    $listTwoContents.detach();
    jQuery(listOne).append($listTwoContents);
};

/**
    editor._indentSingleItem
    ========================

    Indent a single list item via the dom, ensuring that the selected node moves in
    exactly one level and all other nodes stay at the same level.
 */
WYMeditor.editor.prototype._indentSingleItem = function (listItem) {
    var wym = this,
        $liToIndent,
        listType,
        spacerHtml,
        containerHtml,

        splitContent,
        $itemContents,
        $sublistContents,

        $prevLi,
        $prevSublist,
        $firstSublist,

        $spacer,
        $spacerContents;

    // The algorithm used here is generally:
    // 1. Ensure there's a previous li to put the `liToIndent`.
    // 2. Move the `liToIndent` into a sublist in the previous li.
    // 3. If we added a spacer_li after `liToIndent` remove it and move its
    // contents inside `liToIndent`.

    // For step 2, the sublist to use can either be:
    // 1. An existing sublist of the correct type at the end of the previous li.
    // 2. An existing sublist inside `liToIndent`.
    // 3. A new sublist that we create.

    $liToIndent = jQuery(listItem);
    listType = $liToIndent.parent()[0].tagName.toLowerCase();

    // Separate out the contents into things that should stay with the li as it
    // moves and things that should stay at their current level
    splitContent = wym._splitListItemContents($liToIndent);
    $sublistContents = jQuery(splitContent.sublistContents);
    $itemContents = jQuery(splitContent.itemContents);

    $prevLi = $liToIndent.prev().filter('li');
    // Ensure we actually have a previous li in which to put the `liToIndent`
    if ($prevLi.length === 0) {
        spacerHtml = '<li class="spacer_li"></li>';
        $liToIndent.before(spacerHtml);
        $prevLi = $liToIndent.prev();
    }

    // Move `liToIndent` to a sublist inside its previous sibling li
    $prevSublist = $prevLi.contents().last().filter('ol,ul');
    if ($prevSublist.length > 0) {
        // Case 1: We have a sublist at the appropriate level as a previous
        // sibling. Leave the sublist contents where they are and join the
        // previous sublist

        // Join our node at the end of the target sublist
        $prevSublist.append($liToIndent);

        // Stick all of the sublist contents at the end of the previous li
        $sublistContents.detach();
        $prevLi.append($sublistContents);

        // If we just moved two lists of the same type next to eachother, join
        // them
        $firstSublist = $sublistContents.first();
        wym._joinAdjacentLists($prevSublist.get(0), $firstSublist.get(0));
    } else {
        if ($sublistContents.length > 0) {
            // Case 2: We need to move our existing sublist to the previous li
            $sublistContents.detach();
            $prevLi.append($sublistContents);
            $prevSublist = $sublistContents.first();
        } else {
            // Case 3: Create a spacer sublist in the previous li in which to
            // place `liToIndent`
            containerHtml = '<' + listType + '></' + listType + '>';
            $prevLi.append(containerHtml);
            $prevSublist = $prevLi.contents().last();
        }

        // Move our li to the start of the sublist
        $prevSublist.prepend($liToIndent);
    }

    // If we eliminated the need for a spacer_li, remove it
    if ($liToIndent.next().is('.spacer_li')) {
        $spacer = $liToIndent.next('.spacer_li');
        $spacerContents = $spacer.contents();
        $spacerContents.detach();
        $liToIndent.append($spacerContents);
        $spacer.remove();
    }

};

/**
    editor._outdentSingleItem
    =========================

    Outdent a single list item via the dom, ensuring that the selected node moves in
    exactly one level and all other nodes stay at the same level.
 */
WYMeditor.editor.prototype._outdentSingleItem = function (listItem) {
    var wym = this,
        $liToOutdent,
        listType,
        spacerListHtml,

        splitContent,
        $itemContents,
        $sublistContents,

        $parentLi,
        $parentList,

        $subsequentSiblingContent,
        $subsequentParentListSiblingContent,

        $sublist;

    // The algorithm used here is generally:
    // 1. Gather all subsequent sibling content in `liToIndent`s list along
    // with all subsequent sibling content in `liToIndent`s parent list.
    // 2. Move `liToIndent` after the li whose sublist it's in.
    // 3. Create a sublist of the same type of `liToIndent`s parent list inside
    // `liToIndent`.
    // 4. If `liToIndent` has a sublist, use a spacer_li and list to hold its
    // position inside the new sublist.
    // 5. Append all original subsequent siblings inside the created sublist.
    // 6. Append all of `liToIndent`s original parent list subsequent sibling
    // content after the created sublist.
    // 7. Remove `liToOutdent`'s original parent list and parent li if either
    // are now empty

    $liToOutdent = jQuery(listItem);
    listType = $liToOutdent.parent()[0].tagName.toLowerCase();

    // If this list item isn't already indented at least one level, don't allow
    // outdenting
    if (!$liToOutdent.parent().parent().is('ol,ul,li')) {
        return;
    }
    if (!$liToOutdent.parent().parent().is('li')) {
        // We have invalid list nesting and we need to fix that
        WYMeditor.console.log(
            'Attempting to fix invalid list nesting before outdenting.'
        );
        wym._fixInvalidListNesting(listItem);
    }

    // Separate out the contents into things that should stay with the li as it
    // moves and things that should stay at their current level
    splitContent = wym._splitListItemContents($liToOutdent);
    $sublistContents = jQuery(splitContent.sublistContents);
    $itemContents = jQuery(splitContent.itemContents);

    // Gather subsequent sibling and parent sibling content
    $parentLi = $liToOutdent.parent().parent('li');
    // Invalid HTML could cause this selector to fail, which breaks our logic.
    // Bail out rather than possibly losing content
    if ($parentLi.length === 0) {
        WYMeditor.console.error('Invalid list. No parentLi found, so aborting outdent');
        return;
    }
    $parentList = $liToOutdent.parent();
    $subsequentSiblingContent = $liToOutdent.nextAllContents();
    $subsequentParentListSiblingContent = $parentList.nextAllContents();

    // Move the li to after the parent li
    $liToOutdent.detach();
    $parentLi.after($liToOutdent);

    // If this node has one or more sublists, they will need to be indented
    // by one with a fake parent to hold their previous position
    if ($sublistContents.length > 0) {
        spacerListHtml = '<' + listType + '>' +
            '<li class="spacer_li"></li>' +
            '</' + listType + '>';
        $liToOutdent.append(spacerListHtml);
        $sublist = $liToOutdent.children().last();
        // Add all of the sublistContents inside our new spacer li
        $sublistContents.detach();
        $sublist.children('li').append($sublistContents);
    }

    if ($subsequentSiblingContent.length > 0) {
        // Nest the previously-subsequent items inside the list to
        // retain order and their indent level
        if (typeof $sublist === 'undefined') {
            // Insert a sublist if we don't already have one
            spacerListHtml = '<' + listType + '></' + listType + '>';
            $liToOutdent.append(spacerListHtml);
            $sublist = $liToOutdent.children().last();
        }
        $subsequentSiblingContent.detach();
        $sublist.append($subsequentSiblingContent);
    }

    // If we have a parentItem with content after our parent list
    // eg. <ol>
    //       <li>one
    //         <ul ...>
    //         two
    //         <ul ...>
    //         three
    //       </li>
    //     </ol>
    // we'll need to split that parentItem to retain proper content ordering
    if ($subsequentParentListSiblingContent.length > 0) {
        // Move the subsequent content in to a new list item after our parent li
        $subsequentParentListSiblingContent.detach();

        // If our last content and the first content in the subsequent content
        // are both text nodes, insert a <br /> spacer to avoid crunching the
        // text together visually. This maintains the same "visual" structure.
        if ($liToOutdent.contents().length > 0 &&
                $liToOutdent.contents().last()[0].nodeType === WYMeditor.NODE_TYPE.TEXT &&
                $subsequentParentListSiblingContent[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
            $liToOutdent.append('<br />');
        }

        $liToOutdent.append($subsequentParentListSiblingContent);
    }

    // Remove our parentList if it's empty and if we just removed that, the
    // parentLi is likely to be empty also
    if ($parentList.contents().length === 0) {
        $parentList.remove();
    }
    if ($parentLi.contents().length === 0) {
        $parentLi.remove();
    }
};

/**
    editor._fixInvalidListNesting
    =============================

    Take an li/ol/ul and correct any list nesting issues in the entire list
    tree.

    Corrected lists have the following properties:
    1. ol and ul nodes *only* allow li children.
    2. All li nodes have either an ol or ul parent.

    The `alreadyCorrected` argument is used to indicate if a correction has
    already been made, which means we need to return true even if no further
    corrections are made.

    Returns true if any nodes were corrected.
 */
WYMeditor.editor.prototype._fixInvalidListNesting = function (listItem, alreadyCorrected) {
    // Travel up the dom until we're at the root ol/ul/li
    var wym = this,
        currentNode = listItem,
        parentNode,
        tagName;
    if (typeof alreadyCorrected === 'undefined') {
        alreadyCorrected = false;
    }
    if (!currentNode) {
        return alreadyCorrected;
    }
    while (currentNode.parentNode) {
        parentNode = currentNode.parentNode;
        if (parentNode.nodeType !== WYMeditor.NODE_TYPE.ELEMENT) {
            // Our parent is outside a valid list structure. Stop at this node.
            break;
        }
        tagName = parentNode.tagName.toLowerCase();
        if (tagName !== 'ol' && tagName !== 'ul' && tagName !== 'li') {
            // Our parent is outside a valid list structure. Stop at this node.
            break;

        }
        // We're still traversing up a list structure. Keep going
        currentNode = parentNode;
    }
    // We have the root node. Make sure it's legit
    if (jQuery(currentNode).is('li')) {
        // We have an li as the "root" because its missing a parent list.
        // Correct this problem and then try again to correct the nesting.
        WYMeditor.console.log(
            "Correcting orphaned root li before correcting invalid list nesting."
        );
        wym._correctOrphanedListItem(currentNode);
        return wym._fixInvalidListNesting(currentNode, true);
    }
    if (!jQuery(currentNode).is('ol,ul')) {
        WYMeditor.console.error("Can't correct invalid list nesting. No root list found");
        return alreadyCorrected;
    }
    return wym._fixInvalidlyNestedList(currentNode, alreadyCorrected);
};

/**
    editor._isPOrDivAfterEnterInEmptyNestedLi(container)
    ====================================================

    Detects one of the types of resulting DOM in issue #430.

    The case is when a 'p' or a 'div' are introduced into the parent 'li'.
    Since we don't allow a 'p' or a 'div' directly within 'li's it is replaced
    with a 'br'.

    Returns true if detected positively and false otherwise.

    @param container An element to check this about.
 */

WYMeditor.editor.prototype._isPOrDivAfterEnterInEmptyNestedLi = function
(container) {
    if (
        jQuery.inArray(
            container.tagName.toLowerCase(),
            WYMeditor.DocumentStructureManager.VALID_DEFAULT_ROOT_CONTAINERS
        ) > -1 &&
        container.parentNode.tagName.toLowerCase() === 'li'
    ) {
        switch (container.childNodes.length) {
        case 0:
            return true;
        case 1:
            if (
                container.childNodes[0].tagName &&
                container.childNodes[0].tagName.toLowerCase() === 'br'
            ) {
                return true;
            } else if (
                container.childNodes[0].nodeType === WYMeditor.NODE_TYPE.TEXT &&
                container.childNodes[0].data === WYMeditor.NBSP
            ) {
                return true;
            }
        }
    }
    return false;
};

/**
    editor._isSpilledListAfterEnterInEmptyLi
    ========================================

    Detects one of the types of resulting DOM in issue #430.

    In this type of resulting DOM, the contents of a `li` have been
    "spilled" after that `li`.

    Returns true if detected positively and false otherwise.

    @param container An element to check this about.
 */

WYMeditor.editor.prototype._isSpilledListAfterEnterInEmptyLi = function
    (container) {
    var wym = this;
    if (
        container.tagName.toLowerCase() === 'li' &&
        container.previousSibling &&
        wym.isListNode(container.previousSibling) &&
        container.previousSibling.previousSibling &&
        container.previousSibling.previousSibling.tagName
            .toLowerCase() === 'li' &&
        wym.isListNode(container.parentNode)
    ) {
        return true;
    }
    return false;
};

/**
    editor._handlePotentialEnterInEmptyNestedLi
    ===========================================

    Issue #430. When the caret is in an empty nested `li` and the enter key is
    pressed, browsers perform DOM manipulations that are different than what
    we desire.

    This detects two out of three types of the DOM manipulations and calls for
    their correction.

    The third type of DOM manipulation is harder to detect, but, luckily, it
    is tolerable, so it goes undetected. This results in a difference in UX
    across browsers.

    For detailed information on this please see the issue #430's description.

    @param keyPressed The code of the key that was pressed, to check whether
                      it is an enter.
    @param container The currently selected container.
 */

WYMeditor.editor.prototype._handlePotentialEnterInEmptyNestedLi = function (
    keyPressed, container) {

    if (keyPressed !== WYMeditor.KEY_CODE.ENTER) {
        // Only an enter key press can result a p/div in an empty nested list.
        return null;
    }

    var wym = this;

    if (wym._isPOrDivAfterEnterInEmptyNestedLi(container)) {
        wym._replaceNodeWithBrAndSetCaret(container);
    } else if (wym._isSpilledListAfterEnterInEmptyLi(container)) {
        wym._appendSiblingsUntilNextLiToPreviousLi(container);
        wym._replaceNodeWithBrAndSetCaret(container);
    }
};

/**
    editor._replaceNodeWithBrAndSetCaret
    ====================================

    Replaces a node with a `br` element and sets caret before it.

    If the previousSibling is inline (except for a `br`) then another `br`
    is added before.

    @param node This is the node to be replaced.
*/
WYMeditor.editor.prototype._replaceNodeWithBrAndSetCaret = function (node) {
    var wym = this,
        $node = jQuery(node);

    if (
        node.previousSibling &&
        !node.previousSibling.tagName ||
        node.previousSibling.tagName.toLowerCase() !== 'br' &&
        wym.isInlineNode(node.previousSibling)
    ) {
        $node.before('<br />');
    }

    $node.before('<br />');
    wym.setCaretBefore(node.previousSibling);
    $node.remove();
};

/**
    editor._appendSiblingsUntilNextLiToPreviousLi
    =============================================

    This corrects the type of resulting DOM from issue #430 where the
    contents of a `li` have been spilled to after that `li`.

    It only corrects the spillage itself and doesn't modify the new `li`.

    @param newLi This is the new 'li' that was created. It is supposed to
                 contain the caret.
*/

WYMeditor.editor.prototype._appendSiblingsUntilNextLiToPreviousLi =
    function (newLi) {

    var $newLi = jQuery(newLi),
        // The spilled nodes are a subset of these.
        $parentContents = $newLi.parent().contents(),
        // This is the `li` that spilled its contents.
        $sadLi = $newLi.prevAll('li').first(),
        // This is the next `li` after the newLi. If it exists, it marks the
        // end of the spill.
        $nextLi = $newLi.nextAll('li').first(),
        // The spill start index is after the source `li`.
        spillStart = $sadLi.index() + 1,
        $spilled;

    if ($nextLi.length === 1) {
        $spilled = $parentContents.slice(spillStart, $nextLi.index());
    } else {
        // There are no `li` elements after our newLi. The spill ends at the
        // end of its parent.
        $spilled = $parentContents.slice(spillStart);
    }
    $sadLi.append($spilled);
};

/**
    editor._correctOrphanedListItem
    ===============================

    Ensure that the given ophaned list item has a proper list parent.

    Uses the sibling nodes to determine what kind of list should be used. Also
    wraps sibling adjacent orphaned li nodes in the same list.
 */
WYMeditor.editor.prototype._correctOrphanedListItem = function (listNode) {
    var prevAdjacentLis,
        nextAdjacentLis,
        $adjacentLis = jQuery(),
        prevList,
        prevNode;

    prevAdjacentLis = jQuery(listNode).prevContentsUntil(':not(li)');
    nextAdjacentLis = jQuery(listNode).nextContentsUntil(':not(li)');

    // Merge the collections together
    $adjacentLis = $adjacentLis.add(prevAdjacentLis);
    $adjacentLis = $adjacentLis.add(listNode);
    $adjacentLis = $adjacentLis.add(nextAdjacentLis);

    // Determine if we have a list node in which to insert all of our orphaned
    // li's
    prevNode = $adjacentLis[0].previousSibling;
    if (prevNode && jQuery(prevNode).is('ol,ul')) {
        prevList = prevNode;
    } else {
        // No previous existing list to use. Need to create one
        $adjacentLis.before('<ol></ol>');
        prevList = $adjacentLis.prev()[0];
    }

    // Insert all of the adjacent orphaned lists inside the new parent
    jQuery(prevList).append($adjacentLis);
};

/**
    editor._fixInvalidlyNestedList
    ==============================

    This is the function that actually does the list correction.
    _fixInvalidListNesting is just a helper function that first finds the root
    of the list.

    Returns true if any correction was made.

    We use a reverse preorder traversal to navigate the DOM because we might be:

    * Making nodes children of their previous sibling (in the <ol><li></li><ol>...</ol></ol> case)
    * Adding nodes at the current level (wrapping any non-li node inside a ul/ol in a new li node)

    Adapted from code at: Tavs Dokkedahl from
    http://www.jslab.dk/articles/non.recursive.preorder.traversal.part3
 */
WYMeditor.editor.prototype._fixInvalidlyNestedList = function (listNode, alreadyCorrected) {
    var rootNode = listNode,
        currentNode = listNode,
        wasCorrected = false,
        previousSibling,
        tagName,
        ancestorNode,
        nodesToMove,
        targetLi,
        lastContentNode,
        spacerHtml = '<li class="spacer_li"></li>';
    if (typeof alreadyCorrected !== 'undefined') {
        wasCorrected = alreadyCorrected;
    }

    while (currentNode) {
        if (currentNode._wym_visited) {
            // This node has already been visited.
            // Remove mark for visited nodes
            currentNode._wym_visited = false;
            // Once we reach the root element again traversal
            // is done and we can break
            if (currentNode === rootNode) {
                break;
            }
            if (currentNode.previousSibling) {
                currentNode = currentNode.previousSibling;
            } else {
                currentNode = currentNode.parentNode;
            }
        } else {
            // This is the first visit for this node

            // All non-li nodes must have an
            // ancestor li node that's closer than any ol/ul ancestor node.
            // Basically, everything needs to be inside an li node.
            if (currentNode !== rootNode && !jQuery(currentNode).is('li')) {
                // We have a non-li node.
                // Ensure that we have an li ancestor before we have any ol/ul
                // ancestors

                ancestorNode = currentNode;
                while (ancestorNode.parentNode) {
                    ancestorNode = ancestorNode.parentNode;
                    if (jQuery(ancestorNode).is('li')) {
                        // Everything is ok. Hit an li before a ol/ul
                        break;
                    }

                    if (ancestorNode.nodeType !== WYMeditor.NODE_TYPE.ELEMENT) {
                        // Our parent is outside a valid list structure. Stop at this node.
                        break;
                    }
                    tagName = ancestorNode.tagName.toLowerCase();
                    if (tagName === 'ol' || tagName === 'ul') {
                        // We've hit a list container before any list item.
                        // This isn't valid html and causes editing problems.
                        //
                        // Convert the list to a valid structure that closely
                        // mimics the layout and behavior of invalidly nested
                        // content inside a list. The browser treats the
                        // content similar to how it would treat that same
                        // content separated by a <br /> within its previous
                        // sibling list item, so recreate that structure.
                        //
                        // The algorithm for performing this is basically:
                        // 1. Gather this and any previous siblings up until the
                        // previous li (if one exists) as content to move.
                        // 2. If we don't have any previous or subsequent li
                        // sibling, create a spacer li in which to insert all
                        // the gathered content.
                        // 3. Move all of the content to the previous li or the
                        // subsequent li (in that priority).
                        WYMeditor.console.log("Fixing orphaned list content");
                        wasCorrected = true;

                        // Gather this and previous sibling until the previous li
                        nodesToMove = [currentNode];
                        previousSibling = currentNode;
                        targetLi = null;
                        while (previousSibling.previousSibling) {
                            previousSibling = previousSibling.previousSibling;
                            if (jQuery(previousSibling).is('li')) {
                                targetLi = previousSibling;
                                // We hit an li. Store it as the target in
                                // which to move the nodes
                                break;
                            }
                            nodesToMove.push(previousSibling);
                        }

                        // We have our nodes ordered right to left and we need
                        // them left to right
                        nodesToMove.reverse();

                        // If there are no previous siblings, we can join the next li instead
                        if (!targetLi && nodesToMove.length === 1) {
                            if (jQuery(currentNode.nextSibling).is('li')) {
                                targetLi = currentNode.nextSibling;
                            }
                        }

                        // If we still don't have an li in which to move, we
                        // need to create a spacer li
                        if (!targetLi) {
                            jQuery(nodesToMove[0]).before(spacerHtml);
                            targetLi = jQuery(nodesToMove[0]).prev()[0];
                        }

                        // Move all of our content inside the li we've chosen
                        // If the last content node inside the target li is
                        // text and so is the first content node to move, separate them
                        // with a <br /> to preserve the visual layout of them
                        // being on separate lines
                        lastContentNode = jQuery(targetLi).contents().last();
                        if (lastContentNode.length === 1 &&
                                lastContentNode[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
                            if (nodesToMove[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
                                jQuery(targetLi).append('<br />');
                            }
                        }
                        jQuery(targetLi).append(jQuery(nodesToMove));

                        break;

                    }
                    // We're still traversing up a list structure. Keep going
                }
            }

            if (currentNode.lastChild) {
                // Since we have childnodes, mark this as visited because
                // we'll return later
                currentNode._wym_visited = true;
                currentNode = currentNode.lastChild;
            } else if (currentNode.previousSibling) {
                currentNode = currentNode.previousSibling;
            } else {
                currentNode = currentNode.parentNode;
            }
        }
    }

    return wasCorrected;
};

/**
    editor._getCommonParentList
    ===========================

    Get the common parent ol/ul for the given li nodes. If the parent ol/ul for
    each cell isn't the same, returns null.

    @param listItems An array of list item nodes to check for a common parent
    @param getClosest If true, checks if the closest list parent to each list
                      node is the same. If false, checks if the furthest list
                      parent to each list node is the same.
 */
WYMeditor.editor.prototype._getCommonParentList = function (listItems, getClosest) {
    var firstLi,
        parentList,
        rootList,
        haveCommonParent = true;

    listItems = jQuery(listItems).filter('li');
    if (listItems.length === 0) {
        return null;
    }
    firstLi = listItems[0];
    parentList = jQuery(firstLi).parents('ol,ul');
    parentList = (getClosest ? parentList.first() : parentList.last());

    if (parentList.length === 0) {
        return null;
    }
    rootList = parentList[0];

    // Ensure that all of the li's have the same parent list
    jQuery(listItems).each(function (index, elmnt) {
        parentList = jQuery(elmnt).parents('ol,ul');
        parentList = (getClosest ? parentList.first() : parentList.last());
        if (parentList.length === 0 || parentList[0] !== rootList) {
            haveCommonParent = false;
        }
    });

    if (!haveCommonParent) {
        return null;
    }
    return rootList;
};

/**
    editor.deselect
    ===============

    Removes seletion.
*/
WYMeditor.editor.prototype.deselect = function () {
    var wym = this;

    wym.selection().removeAllRanges();
    // Blur seems to be required for IE8.
    wym.body().blur();
};

/**
    editor._getSelectedNodes
    ========================

    Returns an array of the selected and partially selected nodes.

    Returns false if there is not selection.

Returns false if there is no selection.
*/
WYMeditor.editor.prototype._getSelectedNodes = function () {
    var wym = this,
        selection = wym.selection(),
        selectedNodes;

    if (wym.hasSelection() !== true) {
        return false;
    }

    selectedNodes = selection.getAllRanges()
        .reduce(function (nodes, range) {
            return nodes.concat(range.getNodes());
        }, []);
    return selectedNodes;
};

/**
    editor._getSelectedListItems
    ============================

    Determine which `li` nodes are "selected" from the user's standpoint.

    These are the `li` nodes that they would expect to be affected by an action
    with the given selection.

    For a better understanding, comments are provided inside.

    @param selection A Rangy Selection object.
*/
WYMeditor.editor.prototype._getSelectedListItems = function (selection) {
    var wym = this,
        $selectedContainer,
        $selectedNodes,
        $selectedLis;

    if (selection.isCollapsed) {
        $selectedContainer = jQuery(wym.selectedContainer());

        if ($selectedContainer.closest('li, table').is('table')) {
            // Inside a table and not inside a list inside it. This prevents
            // the inclusion of the list item that might be an ancestor of the
            // table.
            return [];
        }
        return $selectedContainer.closest('li');
    }

    // All the selected nodes in the selection's first range.
    $selectedNodes = jQuery(wym._getSelectedNodes());

    if ($selectedNodes.closest('li, table').filter('li').length === 0) {
        // Selection is in a table before it is in a list. This prevents
        // inclusion of the list item that the table may be contained
        // in.
        return [];
    }

    // The technique is to get selected contents of the list items and then
    // get their closest parent list items. So we don't want the list elements.
    // Some list items may be empty and we do want those so we'll add them back
    // later.
    $selectedLis = $selectedNodes.not('li, ol, ul')

    // IE doesn't include the Rangy selection boundary `span` in the above
    // `.getNodes`. This effects an edge case, where a `li` contains only
    // that `span`.
    .add($selectedNodes.find('.rangySelectionBoundary'))

    // Add back the text nodes because jQuery.not always excludes them.
    .add(
        $selectedNodes.filter(
            function () {
                return wym.nodeType === WYMeditor.NODE_TYPE.TEXT;
            }
        )
    )
    .closest('li')

    // Add `li`s that are selected and are empty. Because they didn't
    // get found by `.closest`. We can safely add them because they don't
    // contain other list items so surely if they are in the selection it is
    // because the user wants to manipulate them.
    .add($selectedNodes.filter('li:empty'))

    // Exclude list items that are children of table elements that are in the
    // selection.
    .not($selectedNodes.filter('table').find('li'));

    return jQuery.unique($selectedLis.get());
};

/**
    editor._selectionOnlyInList
    ===========================

    Tests if all of the nodes within the passed selection are contained in one
    list. Returns true if all of the nodes are within one list, and returns
    false if otherwise.

    @param sel A selection to test for being entirely contained within one
               list.
*/
WYMeditor.editor.prototype._selectionOnlyInList = function (sel) {
    var wym = this,
        selStartNode,
        selEndNode,
        i;

    for (i = 0; i < sel.rangeCount; ++i) {
        selStartNode = wym.findUp(sel.getRangeAt(i).startContainer, ['li']);
        selEndNode = wym.findUp(sel.getRangeAt(i).endContainer, ['li']);

        // If the start or end node is not contained within a list item, return
        // false.
        if (!selStartNode || !selEndNode) {
            return false;
        }

        // If the two list items do not have a common parent list, return
        // false.
        if (!wym._getCommonParentList([selStartNode, selEndNode], false)) {
            return false;
        }
    }

    return true;
};

/**
    editor.indent
    =============

    Indent the selected list items via the dom.

    Only list items that have a common list will be indented.
 */
WYMeditor.editor.prototype.indent = function () {
    var wym = this,
        sel = wym.selection(),
        listItems,
        manipulationFunc,
        i;

    // First, make sure this list is properly structured
    manipulationFunc = function () {
        var selection = wym.selection(),
            selectedBlock = wym.get$CommonParent(
                selection.anchorNode,
                selection.focusNode
            )[0],
            potentialListBlock = wym.findUp(
                selectedBlock,
                ['ol', 'ul', 'li']
            );
        return wym._fixInvalidListNesting(potentialListBlock);
    };
    if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
        // We actually made some list correction
        // Don't actually perform the action if we've potentially just changed
        // the list, and maybe the list appearance as a result.
        wym.registerModification();
        return true;
    }

    // We just changed and restored the selection when possibly correcting the
    // lists
    sel = wym.selection();

    // If all of the selected nodes are not contained within one list, don't
    // perform the action.
    if (!wym._selectionOnlyInList(sel)) {
        return false;
    }

    // Gather the li nodes the user means to affect based on their current
    // selection
    listItems = wym._getSelectedListItems(sel);
    if (listItems.length === 0) {
        return false;
    }

    manipulationFunc = function () {
        var domChanged = false;

        for (i = 0; i < listItems.length; i++) {
            wym._indentSingleItem(listItems[i]);
            domChanged = true;
        }

        return domChanged;
    };
    return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
        wym.registerModification();
};

/**
    editor.outdent
    ==============

    Outdent a list item, accounting for firefox bugs to ensure consistent
    behavior and valid HTML.
*/
WYMeditor.editor.prototype.outdent = function () {
    var wym = this,
        sel = wym.selection(),
        listItems,
        manipulationFunc,
        i;

    // First, make sure this list is properly structured
    manipulationFunc = function () {
        var selection = wym.selection(),
            selectedBlock = wym.get$CommonParent(
                selection.anchorNode,
                selection.focusNode
            )[0],
            potentialListBlock = wym.findUp(
                selectedBlock,
                ['ol', 'ul', 'li']
            );
        return wym._fixInvalidListNesting(potentialListBlock);
    };
    if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
        // We actually made some list correction
        // Don't actually perform the action if we've potentially just changed
        // the list, and maybe the list appearance as a result.
        wym.registerModification();
        return true;
    }

    // We just changed and restored the selection when possibly correcting the
    // lists
    sel = wym.selection();

    // If all of the selected nodes are not contained within one list, don't
    // perform the action.
    if (!wym._selectionOnlyInList(sel)) {
        return false;
    }

    // Gather the li nodes the user means to affect based on their current
    // selection
    listItems = wym._getSelectedListItems(sel);

    if (listItems.length === 0) {
        return false;
    }

    manipulationFunc = function () {
        var domChanged = false;

        for (i = 0; i < listItems.length; i++) {
            wym._outdentSingleItem(listItems[i]);
            domChanged = true;
        }

        return domChanged;
    };
    return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
        wym.registerModification();
};

/**
    editor.restoreSelectionAfterManipulation
    ========================================

    A helper function to ensure that the selection is restored to the same
    location after a potentially complicated DOM manipulation is performed. This
    also handles the case where the DOM manipulation throws an error by cleaning
    up any selection markers that were added to the DOM.

    `manipulationFunc` is a function that takes no arguments and performs the
    manipulation. It should return `true` if changes were made that could have
    potentially destroyed the selection.
*/
WYMeditor.editor.prototype.restoreSelectionAfterManipulation = function (manipulationFunc) {
    var wym = this,
        savedSelection = rangy.saveSelection(
            rangy.dom.getIframeWindow(wym._iframe)
        ),
        changesMade = true;

    // If something goes wrong, we don't want to leave selection markers
    // floating around
    try {
        changesMade = manipulationFunc();
        if (changesMade) {
            rangy.restoreSelection(savedSelection);
        } else {
            rangy.removeMarkers(savedSelection);
        }
    } catch (e) {
        WYMeditor.console.error("Error during manipulation");
        WYMeditor.console.error(e);
        rangy.removeMarkers(savedSelection);
    }

    return changesMade;
};

/**
    editor._insertOrderedList
    =========================

    Convert the selected block in to an ordered list.

    If the selection is already inside a list, switch the type of the nearest
    parent list to an `<ol>`. If the selection is in a block element that can be a
    valid list, place that block element's contents inside an ordered list.

    Pure dom implementation consistently cross-browser implementation of
    `execCommand(InsertOrderedList)`.
 */
WYMeditor.editor.prototype._insertOrderedList = function () {
    var wym = this,
        manipulationFunc;

    // First, make sure this list is properly structured
    manipulationFunc = function () {
        // There is a design flaw here. Especially in the case where we may
        // have multiple root-level lists or even `li` items (which shouldn't
        // happen) selected. This code seems to make our tests pass but this
        // should be considered broken.
        var potentialListBlock = jQuery(wym._getSelectedNodes())
                .parents().addBack().filter('ol, ul, li').last()[0];
        potentialListBlock = potentialListBlock || wym.selectedContainer();
        return wym._fixInvalidListNesting(potentialListBlock);
    };
    if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
        // We actually made some list correction
        // Don't actually perform the action if we've potentially just changed
        // the list, and maybe the list appearance as a result.
        wym.registerModification();
        return true;
    }

    // Actually perform the list insertion
    manipulationFunc = function () {
        return wym.insertList('ol');
    };

    return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
        wym.registerModification();
};

/**
    editor._insertUnorderedList
    ===========================

    Convert the selected block in to an unordered list.

    Exactly the same as `editor.insert_orderedlist` except with `<ol>` instead.

    Pure dom implementation consistently cross-browser implementation of
    `execCommand(InsertUnorderedList)`.
 */
WYMeditor.editor.prototype._insertUnorderedList = function () {
    var wym = this,
        manipulationFunc;

    // First, make sure this list is properly structured
    manipulationFunc = function () {
        // There is a design flaw here. Especially in the case where we may
        // have multiple root-level lists or even `li` items (which shouldn't
        // happen) selected. This code seems to make our tests pass but this
        // should be considered broken.
        var potentialListBlock = jQuery(wym._getSelectedNodes())
                .parents().addBack().filter('ol, ul, li').last()[0];
        potentialListBlock = potentialListBlock || wym.selectedContainer();
        return wym._fixInvalidListNesting(potentialListBlock);
    };
    if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
        // We actually made some list correction
        // Don't actually perform the action if we've potentially just changed
        // the list, and maybe the list appearance as a result.
        wym.registerModification();
        return true;
    }

    // Actually perform the list insertion
    manipulationFunc = function () {
        return wym.insertList('ul');
    };

    return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
        wym.registerModification();
};

/**
    editor.insertList
    =================

    This either manipulates existing lists or creates a new one.

    The action that will be performed depends on the contents of the
    selection and their context.

    This can result in one of:

     1. Changing the type of lists.
     2. Removing items from list.
     3. Creating a list.
     4. Nothing.

    If existing list items are selected this means either changing list type
    or de-listing. Changing list type occurs when selected list items all share
    a list of a different type than the requested. Removing items from lists
    occurs when selected list items are all of the same type as the requested.

    If no list items are selected, then, if possible, a list will be created.
    If not possible, no change is made.

    Returns `true` if a change was made, `false` otherwise.

    @param listType A string, representing the user's action, either 'ul'
                    or 'ol'.
 */
WYMeditor.editor.prototype.insertList = function (listType) {
    var wym = this,
        sel = wym.selection(),
        listItems,
        $listItems,
        $parentListsOfDifferentType,
        commonParentList,
        potentialListBlock;

    listItems = wym._getSelectedListItems(sel);
    if (listItems.length > 0) {
        // We have existing list items selected. This means either changing
        // their parent lists' types or de-listing.

        $listItems = jQuery(listItems);

        $parentListsOfDifferentType = $listItems
            .parent(':not(' + listType + ')');
        if ($parentListsOfDifferentType.length > 0) {
            // Some of the lists are of a different type than that which was
            // requested.

            // Change list type only if selected list items share a common parent
            // list. TODO: Change types over several lists:
            // https://github.com/wymeditor/wymeditor/issues/541
            commonParentList = wym._getCommonParentList(listItems, true);
            if (commonParentList) {
                wym.changeListType(commonParentList, listType);
                return true;
            }
        } else {
            // List types are the same as requested. De-list.
            wym._removeItemsFromList($listItems);
            return true;
        }
    }
    // Get a potential block element from selection that could be converted
    // into a list:
    // TODO: Use `_containerRules['root']` minus the ol/ul and
    // `_containerRules['contentsCanConvertToList']
    potentialListBlock = wym.findUp(
        wym.selectedContainer(),
        WYMeditor.POTENTIAL_LIST_ELEMENTS
    );
    if (potentialListBlock) {
        wym.convertToList(potentialListBlock, listType);
        return true;
    }
    // The user has something selected that wouldn't be a valid list
    return false;
};

WYMeditor.editor.prototype.changeListType = function (list, listType) {
    var wym = this;
    // Wrap the contents in a new list of `listType` and remove the old list
    // container.
    return wym.switchTo(list, listType);
};

WYMeditor.editor.prototype.convertToList = function (blockElement, listType) {
    var wym = this,
        $blockElement = jQuery(blockElement),
        newListHtml,
        $newList;

    // ie6 doesn't support calling wrapInner with a dom node. Build html
    newListHtml = '<' + listType + '><li></li></' + listType + '>';

    if (wym.findUp(blockElement, WYMeditor.ROOT_CONTAINERS) === blockElement) {
        // TODO: Handle ol/ul elements, since these are now in the `root`
        // containers list

        // This is a root container block, so we can just replace it with the
        // list structure
        $blockElement.wrapInner(newListHtml);
        $newList = $blockElement.children();
        $newList.unwrap();

        return $newList.get(0);
    }
    // We're converting a block that's not a root container, so we need to nest
    // this list around its contents and NOT remove the container (eg. a td
    // node).
    $blockElement.wrapInner(newListHtml);
    $newList = $blockElement.children();

    return $newList.get(0);
};

/**
    editor._removeItemsFromList
    ===========================

    De-list the provided list items.

    @param listItems A jQuery object of list items.
*/
WYMeditor.editor.prototype._removeItemsFromList = function ($listItems) {
    var wym = this,
        $listItem,
        i,
        j,
        listItemChild,
        $childNodesToTransfer,
        k,
        $childNodeToTransfer,
        rootContainer = wym.documentStructureManager.structureRules
            .defaultRootContainer,
        attributes;

    // This is left here for future reference because it may or may not be a
    // better behavior:
    // It is reasonable to de-list only a subset of the provided list items.
    // The subset are the list items which are not ancestors of any other list
    // items.
    //$listItems = $listItems.not($listItems.find('li'));

    for (i = 0; i < $listItems.length; i++) {
        $listItem = $listItems.eq(i);

        // Determine the type of element this list item will be transformed
        // into and call for this transformation.
        if ($listItem.parent().parent('li, th, td').length === 1) {
            // The list item will end up inside another list item or inside a
            // table cell. Turn it into a `span`.
            $listItem = jQuery(
                wym.switchTo(
                    $listItem[0],
                    'span',
                    false
                )
            );
        } else {
            // The list item will end up in the root of the document. Turn it
            // into a default root container.
            $listItem = jQuery(
                wym.switchTo(
                    $listItem[0],
                    rootContainer,
                    false
                )
            );
        }
        // The transformation should be complete and the element is no longer
        // a list item, hence we call it 'the de-listed element'.

        // Move the de-listed element according to its relation to its
        // sibling nodes.
        if ($listItem.parent().children().length === 1) {
            // It is the only child in the list.

            $listItem.parent().before($listItem);
            // Remove the list because it is empty.
            $listItem.next().remove();

        } else if ($listItem[0] === $listItem.parent().children().first()[0]) {
            // It is not the only child. It is the first child.

            $listItem.parent().before($listItem);
        } else if (
            $listItem[0] !== $listItem.parent().children().first()[0] &&
            $listItem[0] !== $listItem.parent().children().last()[0]
        ) {
            // It is not the first and not the last child.
            $listItem.parent().before(
                '<' + $listItem.parent()[0].tagName + '/>'
            );
            jQuery($listItem.prevAll().toArray().reverse())
                .appendTo($listItem.parent().prev());
            $listItem.parent().before($listItem);

        } else if ($listItem[0] === $listItem.parent().children().last()[0]) {
            // It is not the only child. It is the last child.
            $listItem.parent().after($listItem);
        }
        // The de-listed element should now be at it's final destination.
        // Now, deal with its contents.
        for (j = 0; j < $listItem.contents().length; j++) {
            listItemChild = $listItem.contents()[j];
            if (
                wym.isBlockNode(listItemChild) &&
                // Prevents a rangy selection boundary element from interfering.
                listItemChild.className !== 'rangySelectionBoundary' &&
                listItemChild.tagName.toLowerCase() !== 'br'
            ) {
                // We have hit the first block child. From this child onward,
                // the contents will be moved to after the de-listed element.
                $childNodesToTransfer = $listItem.contents().slice(j);
                if (
                    $listItem[0].tagName.toLowerCase() ===
                        rootContainer
                ) {
                    // The destination of these nodes is the root element.
                    // Prepare them as such.
                    for (k = 0; k < $childNodesToTransfer.length; k++) {
                        $childNodeToTransfer = $childNodesToTransfer.eq(k);
                        if (
                            $childNodeToTransfer[0]
                                .nodeType === WYMeditor.NODE_TYPE.TEXT
                        ) {
                            $childNodeToTransfer.wrap(
                                '<' + rootContainer + ' />'
                            );
                        } else if (
                            $childNodeToTransfer[0].tagName &&
                            !(wym.isBlockNode($childNodeToTransfer[0])) &&
                            $childNodeToTransfer[0].tagName
                                .toLowerCase() !== 'br'
                        ) {
                            wym.switchTo(
                                $childNodesToTransfer[k],
                                rootContainer,
                                false
                            );
                        }
                    }
                }
                // The contents should be ready now.
                $listItem.after($listItem.contents().slice(j));
                // The loop was for finding the first block element.
                break;
            }
        }
        // `br`s may have been transferred to the root container. They don't
        // belong there.
        wym.$body().children('br').remove();

        if ($listItem[0].tagName.toLowerCase() === 'span') {
            // Get rid of empty `span`s and ones that contain only `br`s.
            if (
                $listItem.contents(':not(.rangySelectionBoundary)')
                    .length === 0 ||
                $listItem.contents(':not(.rangySelectionBoundary)').length ===
                    $listItem.contents('br').length
            ) {
                // The Rangy selection boundary `span` may be inside.
                $listItem.before($listItem.contents('.rangySelectionBoundary'));
                $listItem.remove();
            } else {
                // The `span` wasn't removed.

                // Add `br` elements that may be necessary because by turning
                // a `li` element into a `span` element we turn a block
                // type element into an inline type element.
                if (
                    $listItem[0].previousSibling &&
                    $listItem[0].previousSibling.nodeType === WYMeditor
                        .NODE_TYPE.TEXT ||

                    $listItem.prevAll(':not(.rangySelectionBoundary)')
                        .length > 0 &&
                    wym.isBlockNode(
                        $listItem.prevAll(':not(.rangySelectionBoundary)')[0]
                    ) === false
                ) {
                    $listItem.before('<br />');
                }
                if (
                    $listItem[0].nextSibling &&
                    $listItem[0].nextSibling.nodeType === WYMeditor
                        .NODE_TYPE.TEXT ||

                    $listItem.nextAll(':not(.rangySelectionBoundary)')
                        .length > 0 &&
                    wym.isBlockNode(
                        $listItem.nextAll(':not(.rangySelectionBoundary)')[0]
                    ) === false
                ) {
                    $listItem.after('<br />');
                }

                // If the de-listed element has no meaningful attributes, there is
                // no use for it being a span.
                attributes = $listItem[0].attributes;
                wym.unwrapIfMeaninglessSpan($listItem[0]);
            }
        }
    }

    // Reintroduce any necessary DOM-level corrections for editing purposes
    wym.prepareDocForEditing();
};

/**
     editor.insertTable
     ==================

     Insert a table at the current selection with the given number of rows
     and columns and with the given caption and summary text.
*/
WYMeditor.editor.prototype.insertTable = function (rows, columns, caption, summary) {
    if ((rows <= 0) || (columns <= 0)) {
        // We need rows and columns to make a table

        // TODO: It seems to me we should warn the user when zero columns and/or
        // rows were entered.
        return;
    }

    var wym = this,
        table = wym._doc.createElement(WYMeditor.TABLE),
        newRow = null,
        newCaption,

        x,
        y,
        container,
        selectedNode;

    // Create the table caption
    newCaption = table.createCaption();
    newCaption.innerHTML = caption;

    // Create the rows and cells
    for (x = 0; x < rows; x += 1) {
        newRow = table.insertRow(x);
        for (y = 0; y < columns; y += 1) {
            newRow.insertCell(y);
        }
    }

    if (summary !== "") {
        // Only need to set the summary if we actually have a summary
        jQuery(table).attr('summary', summary);
    }

    // Find the currently-selected container
    container = jQuery(
        wym.findUp(wym.selectedContainer(), WYMeditor.POTENTIAL_TABLE_INSERT_ELEMENTS)
    ).get(0);

    if (!container || !container.parentNode) {
        // No valid selected container. Put the table at the end.
        wym.$body().append(table);

    } else if (jQuery.inArray(container.nodeName.toLowerCase(),
                       WYMeditor.INLINE_TABLE_INSERTION_ELEMENTS) > -1) {
        // Insert table after selection if container is allowed to have tables
        // inserted inline.
        selectedNode = wym.selection().focusNode;

        // If the selection is within a table, move the selection to the parent
        // table to avoid nesting the tables.
        if (jQuery.inArray(selectedNode.nodeName.toLowerCase(),
                           WYMeditor.SELECTABLE_TABLE_ELEMENTS) > -1 ||
            jQuery.inArray(selectedNode.parentNode.nodeName.toLowerCase(),
                           WYMeditor.SELECTABLE_TABLE_ELEMENTS) > -1) {

            while (selectedNode.nodeName.toLowerCase() !== WYMeditor.TABLE) {
                selectedNode = selectedNode.parentNode;
            }
        }

        // If the list item itself is selected, append the table to it. If the
        // selection is within the list item, put the table after it. Either
        // way, this ensures the table will always be inserted within the list
        // item.
        if (selectedNode.nodeName.toLowerCase() === WYMeditor.LI) {
            jQuery(selectedNode).append(table);
        } else {
            jQuery(selectedNode).after(table);
        }

    } else {
        // If the table is not allowed to be inserted inline with the
        // container, insert it after the container.
        jQuery(container).after(table);
    }

    // Handle any browser-specific cleanup
    wym._afterInsertTable(table);
    wym.prepareDocForEditing();

    wym.registerModification();
    return table;
};

/**
    editor._afterInsertTable
    ========================

    Handle cleanup/normalization after inserting a table. Different browsers
    need slightly different tweaks.
*/
WYMeditor.editor.prototype._afterInsertTable = function () {
};

WYMeditor.editor.prototype._listen = function () {
    var wym = this;

    jQuery(wym._doc).bind('paste', function () {
        wym._handlePasteEvent();
    });
};

WYMeditor.editor.prototype._handlePasteEvent = function () {
    var wym = this;

    // The paste event happens *before* the paste actually occurs.
    // Use a timer to delay execution until after whatever is being pasted has
    // actually been added.
    window.setTimeout(
        function () {
            jQuery(wym.element).trigger(
                WYMeditor.EVENTS.postBlockMaybeCreated,
                wym
            );
        },
        20
    );
};

/**
    WYMeditor.editor._selectSingleNode
    ==================================

    Sets selection to a single node, exclusively.
    Not public API because not tested enough.
    For example, what happens when selecting containing element, this way?
*/
WYMeditor.editor.prototype._selectSingleNode = function (node) {
    var wym = this,
        selection,
        nodeRange;

    if (!node) {
        throw "Expected a node";
    }
    selection = wym.selection();
    nodeRange = rangy.createRangyRange();
    nodeRange.selectNode(node);

    selection.setSingleRange(nodeRange);
};

/**
    WYMeditor.editor._initSkin
    ==========================

    Apply the appropriate CSS class to "activate" that skin's CSS and call the
    skin's javascript `init` method.
*/
WYMeditor.editor.prototype._initSkin = function () {
    var wym = this;
    // Put the classname (ex. wym_skin_default) on wym_box
    jQuery(wym._box).addClass("wym_skin_" + wym._options.skin);

    // Init the skin, if needed
    if (typeof WYMeditor.SKINS[wym._options.skin] !== "undefined") {
        if (typeof WYMeditor.SKINS[wym._options.skin].init === "function") {
            WYMeditor.SKINS[wym._options.skin].init(wym);
        }
    } else {
        WYMeditor.console.warn(
            "Chosen skin _" + wym.options.skin + "_ not found."
        );
    }
};

/**
    WYMeditor.editor.body
    =====================

    Returns the document's body element.
*/
WYMeditor.editor.prototype.body = function () {
    var wym = this,
        body;

    if (!wym._doc.body) {
        throw "The document seems to have no body element.";
    }

    body = wym._doc.body;

    if (
        !body.tagName ||
        body.tagName.toLowerCase() !== 'body'
    ) {
        throw "The document's body doesn't seem to be a `body` element.";
    }

    return body;
};

/**
    WYMEditor.editor.$body
    ======================

    Returns a jQuery object of the document's body element.
*/
WYMeditor.editor.prototype.$body = function () {
    var wym = this,
        body;

    body = wym.body();
    return jQuery(body);
};

/**
    WYMeditor.editor.doesElementContainSelection
    ============================================

    Returns ``true`` if the supplied element contains at least part of the
    selection.
    Otherwise returns ``false``.
*/
WYMeditor.editor.prototype.doesElementContainSelection = function (element) {
    var wym = this,
        $element,
        selectedContainer,
        $selectedNodes,
        i,
        $selectedNodeAncestors,
        j;

    if (wym.hasSelection() !== true) {
        return false;
    }
    $element = jQuery(element);

    if (wym.selection().isCollapsed === true) {
        selectedContainer = wym.selectedContainer();

        if (element === selectedContainer) {
            return true;
        }
        if ($element.has(selectedContainer).length > 0) {
            return true;
        }
        return false;
    }

    // For non-collapsed selections.
    // We could have used the following, but it
    // doesn't work in IE8.
    // if ($element.has(wym._getSelectedNodes()).length > 0) {
    //     return true;
    // }
    $selectedNodes = jQuery(wym._getSelectedNodes());
    for (i = 0; i < $selectedNodes.length; i++) {
        $selectedNodeAncestors = $selectedNodes.eq(i).parents();
        for (j = 0; j < $selectedNodeAncestors.length; j++) {
            if ($selectedNodeAncestors[j] === element) {
                return true;
            }
        }
    }

    return false;
};

/*jslint maxlen: 90 */
/* global -$ */
"use strict";

/**
 * WYMeditor.DocumentStructureManager
 * ==================================
 *
 * This manager controls the rules for the subset of HTML that WYMeditor will
 * allow the user to create. For technical users, there are justifiable reasons
 * to use any in-spec HTML, but for users of WYMeditor (not implementors), the
 * goal is make it intuitive for them to create the structured markup that will
 * fit their needs.
 *
 * For example, while it's valid HTML to have a mix
 * of DIV and P tags at the top level of a document, in practice, this is
 * confusing for non-technical users. The DocumentStructureManager allows the
 * WYMeditor implementor to standardize on P tags in the root of the document,
 * which will automatically convert DIV tags in the root to P tags.
 *
 */
WYMeditor.DocumentStructureManager = function (wym, defaultRootContainer) {
    var dsm = this;
    dsm._wym = wym;
    dsm.structureRules = WYMeditor.DocumentStructureManager.DEFAULTS;
    dsm.setDefaultRootContainer(defaultRootContainer);
};

jQuery.extend(WYMeditor.DocumentStructureManager, {
    // Only these containers are allowed as valid `defaultRootContainer`
    // options.
    VALID_DEFAULT_ROOT_CONTAINERS : [
        "p",
        "div"
    ],

    // Cooresponding titles for use in the containers panel for the valid
    // default root containers
    DEFAULT_ROOT_CONTAINER_TITLES : {
        p: "Paragraph",
        div: "Division"
    },

    // These containers prevent the user from using up/down/enter/backspace
    // to move above or below them, thus effectively blocking the creation
    // of new blocks. We must use temporary spacer elements to correct this
    // while the document is being edited.
    CONTAINERS_BLOCKING_NAVIGATION : ["table", "blockquote", "pre"],


    DEFAULTS : {
        // By default, this container will be used for all root contents. This
        // defines the container used when "enter" is pressed from the root and
        // also which container wraps or replaces containers found at the root
        // that aren't allowed. Only
        // `DocumentStructureManager.VALID_DEFAULT_ROOT_CONTAINERS` are allowed
        // here. Whichever you choose, the VALID_DEFAULT_ROOT_CONTAINERS will
        // be automatically converted when found at the top level of your
        // document.
        defaultRootContainer: 'p',

        // These containers cannot be used as root containers. This includes
        // any default root containers that are not the chosen default root
        // container. By default, this is set to the list of valid root
        // containers that are not the defaultRootContainer.
        notValidRootContainers: ['div'],

        // Only these containers are allowed as a direct child of the body tag.
        // All other containers located there will be wrapped in the
        // `defaultRootContainer`, unless they're one of the tags in
        // `convertIfRoot`.
        validRootContainers: [
            'p',
            'div',
            'h1',
            'h2',
            'h3',
            'h4',
            'h5',
            'h6',
            'pre',
            'blockquote',
            'table',
            'ol',
            'ul'
        ],

        // If these tags are found in the root, they'll be converted to the
        // `defaultRootContainer` container instead of the default of being
        // wrapped.
        convertIfRootContainers: [
            'div'
        ],

        // The elements that are allowed to be turned in to lists.
        validListConversionTargetContainers: [
            "p",
            "div",
            "h1",
            "h2",
            "h3",
            "h4",
            "h5",
            "h6",
            "pre",
            "blockquote",
            "td",
            "th"
        ],

        // For most block elements, the default behavior when a user attempts
        // to convert it to a list is to convert that block to a ol/ul and wrap
        // the contents in an li. For containers in `wrapContentsInList`,
        // instead of converting the container, we should just wrap the
        // contents of the container in a ul/ol + li.
        wrapContentsInList: [
            'td',
            'th'
        ]
    }
});

/**
 * Set the default container created/used in the root.
 *
 * @param defaultRootContainer String A string representation of the tag to
 * use.
 */
WYMeditor.DocumentStructureManager.prototype.setDefaultRootContainer = function
(
    defaultRootContainer
) {
    var dsm = this,
        validContainers,
        index,
        DSManager;

    if (dsm.structureRules.defaultRootContainer === defaultRootContainer) {
        // This is already our current configuration. No need to do the
        // work again.
        return;
    }

    // Make sure the new container is one of the valid options
    DSManager = WYMeditor.DocumentStructureManager;
    validContainers = DSManager.VALID_DEFAULT_ROOT_CONTAINERS;
    index = jQuery.inArray(defaultRootContainer, validContainers);
    if (index === -1) {
        throw new Error(
            "a defaultRootContainer of '" +
            defaultRootContainer +
            "' is not supported"
        );
    }

    dsm.structureRules.defaultRootContainer = defaultRootContainer;

    // No other possible option for default root containers is valid expect for
    // the one choosen default root container
    dsm.structureRules.notValidRootContainers =
        WYMeditor.DocumentStructureManager.VALID_DEFAULT_ROOT_CONTAINERS;
    dsm.structureRules.notValidRootContainers.splice(index, 1);

    dsm._adjustDefaultRootContainerUI();

    // TODO: Actually do all of the switching required to move from p to div or
    // from div to p for the topLevelContainer
};

/**
    _adjustDefaultRootContainerUI
    =============================

    Adds a new link for the default root container to the containers panel in
    the editor if needed, and removes any other links for valid default root
    containers form the containers panel besides the link for the chosen
    default root container.
*/
WYMeditor.DocumentStructureManager.prototype._adjustDefaultRootContainerUI = function () {
    var dsm = this,
        wym = dsm._wym,
        defaultRootContainer = dsm.structureRules.defaultRootContainer,
        $containerItems,
        $containerLink,
        $newContainerItem,
        containerName,
        newContainerLinkNeeded,
        newContainerLinkHtml,
        i,
        DSManager;

    $containerItems = jQuery(wym._box).find(wym._options.containersSelector)
                                      .find('li');
    newContainerLinkNeeded = true;

    // Remove container links for any other valid default root container from
    // the containers panel besides the link for the chosen default root
    // container
    for (i = 0; i < $containerItems.length; ++i) {
        $containerLink = $containerItems.eq(i).find('a');
        containerName = $containerLink.attr('name').toLowerCase();
        if (jQuery.inArray(containerName,
                           dsm.structureRules.notValidRootContainers) > -1) {
            $containerItems.eq(i).remove();
        }
        if (containerName === defaultRootContainer) {
            newContainerLinkNeeded = false;
        }
    }

    // Add new link for the default root container to the containers panel if
    // needed
    if (newContainerLinkNeeded) {
        newContainerLinkHtml = wym._options.containersItemHtml;
        newContainerLinkHtml = WYMeditor.Helper.replaceAllInStr(
            newContainerLinkHtml,
            WYMeditor.CONTAINER_NAME,
            defaultRootContainer.toUpperCase()
        );
        DSManager = WYMeditor.DocumentStructureManager;
        newContainerLinkHtml = WYMeditor.Helper.replaceAllInStr(
            newContainerLinkHtml,
            WYMeditor.CONTAINER_TITLE,
            DSManager.DEFAULT_ROOT_CONTAINER_TITLES[defaultRootContainer]
        );
        newContainerLinkHtml = WYMeditor.Helper.replaceAllInStr(
            newContainerLinkHtml,
            WYMeditor.CONTAINER_CLASS,
            "wym_containers_" + defaultRootContainer
        );
        $newContainerItem = jQuery(newContainerLinkHtml);
        $containerItems = jQuery(wym._box).find(wym._options.containersSelector)
                                          .find('li');
        $containerItems.eq(0).before($newContainerItem);

        // Bind click event for the new link
        $newContainerItem.find('a').click(function () {
            var button = this;
            wym.setRootContainer(jQuery(button).attr(WYMeditor.NAME));
            return false;
        });
    }
};


/* jshint maxlen:100 */
"use strict";

/*
 * # The Image Handler
 *
 * Give it an editor instance and it will make
 * most of your image resizing dreams come true.
 *
 * ## IE8 Shenanigans
 *
 * When IE8 is not longer supported,
 * `rem` could be used for more accurate UI element dimensions
 *
 * Dragging and dropping of images is not suggested in the UI.
 * See the `_isImgDragDropAllowed` function
 * and the `_onImgMousedown` function.
 *
 * ## IE9 Shenanigans
 *
 * Dragging and dropping of images is disabled.
 * See the `_isImgDragDropAllowed` function.
 *
 * ## IE8-11 Shenanigans
 *
 * SVG images are not scaled.
 * They are cropped. That's right.
 * And applying style to them does not help,
 * as well. Ideas are welcome.
 *
 * ## General Shenanigans (http://i.imgur.com/wbQ6U5C.jpg)
 *
 * This module is covered by only a few basic tests
 * so any change must be meticulously manually tested
 * in all the supported browsers
 * by psychologically stable individuals.
 *
 * Dragging and dropping of images
 * might produce undesired results on drop.
 * Uncharted territory.
 *
 * In event handlers of events that
 * are not expected to perform useful default actions
 * `return false` is used to prevent any bad feelings
 * towards unexpected browser behavior.
 */

// the image handler class.
WYMeditor.ImageHandler = function (wym) {
    var ih = this;
    ih._wym = wym;

    ih._$resizeHandle = ih._createResizeHandle();

    ih._$currentImageMarker = null;

    // references the image that
    // has the resize handle placed on it
    ih._$currentImg = null;

    // flags whether a resize operation is
    // occurring at this moment
    ih._resizingNow = false;

    ih._imgDragDropAllowed = WYMeditor.ImageHandler._isImgDragDropAllowed();

    ih._addEventListeners();

    return ih;
};

WYMeditor.ImageHandler._isImgDragDropAllowed = function () {
    var browser = jQuery.browser;
    if (browser.msie) {
        if (browser.versionNumber <= 9) {
            // dragging and dropping seems to not consistently work.
            // the image would only some times get picked up by the mouse drag attempt.
            // to prevent confusion
            return false;
        }
    }
    return true;
};

WYMeditor.ImageHandler._RESIZE_HANDLE_HR_HTML = jQuery('<hr>')
    .addClass(WYMeditor.EDITOR_ONLY_CLASS)
    .css({margin: 0, padding: 0})
    .attr('outerHTML');

WYMeditor.ImageHandler._RESIZE_HANDLE_INNER_HTML = [
    'drag this to resize',
    'click on image to select'
].join(WYMeditor.ImageHandler._RESIZE_HANDLE_HR_HTML);

WYMeditor.ImageHandler._IMAGE_HIGHLIGHT_COLOR = 'yellow';

// creates and returns
// a yet detached UI resize handle element
// in a jQuery object
WYMeditor.ImageHandler.prototype._createResizeHandle = function () {
    var $handle = jQuery('<div/>');

    // In IE11 it was very easy to
    // accidentally enter into editing mode
    // in the resize handle.
    // This seamlessly prevents it.
    $handle.attr('contentEditable', 'false');

    $handle.html(WYMeditor.ImageHandler._RESIZE_HANDLE_INNER_HTML);

    $handle
        .addClass(WYMeditor.RESIZE_HANDLE_CLASS)
        .addClass(WYMeditor.EDITOR_ONLY_CLASS);

    $handle.css({
        margin: '0',
        padding: '0',

        // when IE9 is no longer supported
        // this could be `ns-resize`
        cursor: 'row-resize',

        'text-align': 'center',

        // this means that
        // elements after the resize handle
        // will not be pushed down because of its presence.
        // we later use the `left` and `top` properties
        // to keep the resize handle exactly
        // below its current image
        position: 'absolute',

        'background-color': WYMeditor.ImageHandler._IMAGE_HIGHLIGHT_COLOR,

        // override default iframe stylesheet
        // so that a 'div' does not appear
        'background-image': 'none',

        // so that the text inside the resize handle
        // fits in one line.
        // in the theoretical future
        // the more appropriate value would be
        // `min-content`
        'min-width': '13em',

        width: '100%'
    });

    return $handle;
};

WYMeditor.ImageHandler.prototype._getCurrentImageMarker = function () {
    var ih = this;
    if (
        // a marker was not yet created
        !ih._$currentImageMarker ||
        // a marker was destroyed via native edit
        !ih._$currentImageMarker.length
    ) {
        ih._$currentImageMarker = ih._createCurrentImageMarker();
    }
    return ih._$currentImageMarker;
};

WYMeditor.ImageHandler._IMAGE_MARKER_CLASS = 'wym-image-marker';

WYMeditor.ImageHandler.prototype._createCurrentImageMarker = function () {
    return jQuery('<div/>')
        .addClass(WYMeditor.EDITOR_ONLY_CLASS)
        .addClass(WYMeditor.ImageHandler._IMAGE_MARKER_CLASS)
        .hide();
};

WYMeditor.ImageHandler.prototype._addEventListeners = function () {
    var ih = this;
    var $doc = jQuery(ih._wym._doc);

    $doc.delegate(
        'img', 'mouseover',
        ih._onImgMouseover.bind(ih)
    );
    $doc.delegate(
        'img', 'click',
        ih._onImgClick.bind(ih)
    );
    $doc.delegate(
        '.' + WYMeditor.RESIZE_HANDLE_CLASS, 'mousedown',
        ih._onResizeHandleMousedown.bind(ih)
    );
    $doc.delegate(
        'img',
        'mousedown',
        ih._onImgMousedown.bind(ih)
    );
    $doc.delegate(
        'img',
        'dragstart',
        ih._onImgDragstart.bind(ih)
    );
    $doc.bind(
        'mousemove',
        ih._onMousemove.bind(ih)
    );
    $doc.bind(
        'mouseup',
        ih._onMouseup.bind(ih)
    );
    ih._edited = new WYMeditor.EXTERNAL_MODULES.Edited(
        $doc[0],
        function () {}, // do not do anything with strictly sensible edits
        ih._onAnyNativeEdit.bind(ih) // handle all edits
    );
    $doc.delegate(
        '.' + WYMeditor.RESIZE_HANDLE_CLASS,
        'click dblclick',
        ih._onResizeHandleClickDblclick.bind(ih)
    );
    // useful for debugging
    if (false) {
        ih._wym.$body().delegate(
            '*',
            WYMeditor.Helper.getAllEventTypes(ih._wym.$body()[0]),
            ih._onAllEvents.bind(ih)
        );
    }
};

WYMeditor.ImageHandler.prototype._onImgMouseover = function (evt) {
    var ih = this;
    var $img = jQuery(evt.target);
    if (
        !$img.data('cE disabled') &&
        jQuery.browser.msie
    ) {
        // in IE8-11 it seems that the default cursor for images
        // (in `designMode`) is 'move' (4 directions arrow)
        // and simply setting a different cursor
        // does not change that default.
        // this works around the issue.
        // the result is still not just any cursor we'd like,
        // but only the 'default' cursor,
        // which is better than the default 'move' cursor.
        // this workaround does not seem to have obvious side effects
        $img.attr('contentEditable', 'false');
        $img.data('cE disabled', true);
    }
    ih._setImgCursor($img);
};

WYMeditor.ImageHandler.prototype._setImgCursor = function ($img) {
    var ih = this;
    if (ih._wym.getSelectedImage() !== $img[0]) {
        // hint that image is selectable by click
        $img.css('cursor', 'pointer');
        return;
    }
    // image is selected
    if (ih._imgDragDropAllowed) {
        // in IE8-11 this does not work
        // and the cursor remains 'default'.
        // see the `_onImgMouseover` handler
        $img.css('cursor', 'move');
    } else {
        $img.css('cursor', 'default');
    }
};

WYMeditor.ImageHandler.prototype._onImgClick = function (evt) {
    var ih = this;

    // firefox seems to natively select the image on mousedown
    // this means that by the time this handler executes,
    // the image is already selected.
    //
    // in IE8, by this point
    // the image is always deselected,
    // even if it was selected just before the click,
    // because the mouse event itself
    // causes the deselection of the image
    // (see the `_selectImage` method).
    //
    // because of the above browser limitations,
    // it is more simple to always select the image here,
    // regardless of whether it is selected already or not

    ih._selectImage(evt.target);
    ih._indicateOnResizeHandleThatImageIsSelected();
    return false;
};

WYMeditor.ImageHandler.prototype._selectImage = function (img) {
    var ih = this;
    var $img = jQuery(img);

    if (jQuery.browser.msie && jQuery.browser.versionNumber === 8) {
        // in IE8 when the right side of an img is clicked
        // (you can't make this up),
        // any selection that was set on click is discarded.
        // scheduling the image selection
        // for after synchronous execution
        // works around the issue
        setTimeout(function () {
             //ih._isAnImgSelected('IE8 ASYNC `_selectImage` (before select)'); // for debugging
            ih._wym._selectSingleNode(img);
             //ih._isAnImgSelected('IE8 ASYNC `_selectImage` (after select)'); // for debugging
        }, 0);
    } else {
         //ih._isAnImgSelected('`_selectImage` (before select)'); // for debugging
        ih._wym._selectSingleNode(img);
         //ih._isAnImgSelected('`_selectImage` (after select)'); // for debugging
    }

    ih._setImgCursor($img);
};

WYMeditor.ImageHandler.prototype._indicateOnResizeHandleThatImageIsSelected = function () {
    var ih = this;

    var indication = 'image is selected';
    if (ih._imgDragDropAllowed) {
        indication = [
            indication,
            'drag image to move it'
        ].join(WYMeditor.ImageHandler._RESIZE_HANDLE_HR_HTML);
    }

    ih._$resizeHandle
        .css('font-weight', 'bold')
        .html(indication);

    // ideally, the above indication text would remain
    // until the image is no longer selected.
    // since it is not easy to detect when that happens,
    // the indication text is replaced with the initial text
    // after a short moment.
    setTimeout(function () {
        ih._$resizeHandle
          .css('font-weight', 'normal')
          .html(WYMeditor.ImageHandler._RESIZE_HANDLE_INNER_HTML);
    }, 1000);
};

WYMeditor.ImageHandler.prototype._placeResizeHandleOnImg = function (img) {
    var ih = this;
    var IMAGE_PADDING = '0.8em';
    var $img = jQuery(img);

    ih._$currentImg = $img;

    ih._getCurrentImageMarker().insertAfter($img);

    // colored padding around the image and the handle
    // visually marks the image
    // that currently has the resize handle placed on it.
    // it also makes it possible to resize very small images
    // (see the `_detachResizeHandle` method)
    $img.css({
        'background-color': WYMeditor.ImageHandler._IMAGE_HIGHLIGHT_COLOR,

        'padding-top': IMAGE_PADDING,
        'padding-right': IMAGE_PADDING,
        'padding-bottom': '0',
        'padding-left': IMAGE_PADDING,
        'margin-top': '-' + IMAGE_PADDING,
        'margin-right': '-' + IMAGE_PADDING,
        'margin-bottom': '0',
        'margin-left': '-' + IMAGE_PADDING
    });

    // the resize handle, prepended to the body in this way,
    // can be removed from the body using DOM manipulation
    // such as setting the content with the `html` method.
    // so we place it there in case that occurred.
    // this could be done conditionally
    // but there is practically no performance hit so keeping it simple
    ih._$resizeHandle.prependTo(ih._wym.$body());

    // it is important that the resize handle's offset
    // is updated after the above style modification
    // adds top padding to the image
    // because that alters the image's outside height
    ih._correctResizeHandleOffsetAndWidth();

    ih._$resizeHandle.show();
};

WYMeditor.ImageHandler.prototype._correctResizeHandleOffsetAndWidth = function () {
    var ih = this;

    ih._$resizeHandle.css('max-width', ih._$currentImg.outerWidth());

    var offset = ih._$currentImg.offset();

    ih._$resizeHandle.css('left', offset.left);

    // the Y position of the first pixel after the image's outer Y dimension.
    // in other words, just below the image's margin (if it had a margin)
    var yAfterImg = offset.top + ih._$currentImg.outerHeight();

    if (jQuery.browser.msie) {
        // in IE8-11 there might be a visible 1 pixes gap
        // between the image and the resize handle
        // possibly this issue:
        // https://github.com/jquery/jquery/issues/1724
        yAfterImg--;
    }

    ih._$resizeHandle.css('top', yAfterImg);
};

WYMeditor.ImageHandler.prototype._onResizeHandleMousedown = function (evt) {
    var ih = this;

    if (!ih._resizingNow) {
        ih._startResize(evt.clientY);
    }
    return false;
};

WYMeditor.ImageHandler.prototype._startResize = function (startMouseY) {
    var ih = this;

    ih._startMouseY = startMouseY;
    ih._$currentImg.data('StartHeight', ih._$currentImg.height());
    ih._resizingNow = true;
};

WYMeditor.ImageHandler.prototype._onMousemove = function (evt) {
    var ih = this;

    // default action for this event may be a `mousedown` and `mousemove`
    // with the intention to select text
    // or to drag (for later dropping of) content
    // so be careful about preventing default

    if (!evt.target.tagName) {
        // IE8 may fire such an event.
        // what element was it fired on?
        return;
    }

    if (ih._resizingNow) {
        // this is up high in this method for performance
        ih._resizeImage(evt.clientY);
        return false;
    }

    if (
        evt.target.tagName.toLowerCase() === 'img' &&
        !ih._isResizeHandleAttached()
    ) {
        ih._placeResizeHandleOnImg(evt.target);
        return false;
    }

    if (!ih._isResizeHandleAttached()) {
        return;
    }

    // from this point on, this event handler is all about
    // checking whether the resize handle should be detached

    if (
        !jQuery(evt.target).hasClass(WYMeditor.EDITOR_ONLY_CLASS) &&
        !ih._isCurrentImg(evt.target)
    ) {
        // this must be after the above check for whether resizing now
        // because, while the resize operation does begin
        // with the mouse pointing on the resize handle,
        // the mouse might leave the resize handle during the resize operation.
        // in that case, we would like the operation to continue
        ih._detachResizeHandle();
        return;
    }

    if (!ih._isCurrentImgAtMarker()) {
        ih._detachResizeHandle();
        return;
    }
};

WYMeditor.ImageHandler.prototype._isCurrentImgAtMarker = function () {
    var ih = this;
    var $marker = ih._$currentImageMarker;
    if (!$marker.length) {
        // the marker was removed by some DOM manipulation
        return false;
    }
    var $img = ih._$currentImg;
    var $imgPrevToMarker = $marker.prev('img');
    if (
        $img.length &&
        $imgPrevToMarker.length &&
        $imgPrevToMarker[0] === $img[0]
    ) {
        return true;
    }
    // this happens when:
    //
    // * the image was selected and
    //   * replaced by pasted content
    //   * replaced by character insertion from key press
    //   * removed with backspace/delete
    // * caret was before/after image and delete/backspace pressed
    // * the image was dragged and dropped somewhere
    return false;
};

WYMeditor.ImageHandler.prototype._isResizeHandle = function (elem) {
    return jQuery(elem).hasClass(WYMeditor.RESIZE_HANDLE_CLASS);
};

WYMeditor.ImageHandler.prototype._isCurrentImg = function (img) {
    var ih = this;
    return img === ih._$currentImg[0];
};

WYMeditor.ImageHandler.prototype._resizeImage = function (currentMouseY) {
    var ih = this;
    var $img = ih._$currentImg;

    var dimensionsRatio = $img.data('DimensionsRatio');

    if (!dimensionsRatio) {
        // in order to prevent dimensions ratio corruption
        var originalHeight = $img.height();
        var originalWidth = $img.width();
        dimensionsRatio = originalWidth / originalHeight;
        $img.data('DimensionsRatio', dimensionsRatio);
    }

    // calculate the new dimensions
    var startHeight = $img.data('StartHeight');
    var newHeight = startHeight - ih._startMouseY + currentMouseY;
    newHeight = newHeight > 0 ? newHeight : 0;
    var newWidth = newHeight * dimensionsRatio;

    // update the dimensions
    $img.attr('height', newHeight);
    $img.attr('width', newWidth);

    ih._correctResizeHandleOffsetAndWidth();
};

WYMeditor.ImageHandler.prototype._onMouseup = function () {
    // this could be a case where
    // there was a `mousedown` on a selection
    // and then a `mouseup` without having moved the mouse.
    // the default action would be
    // to collapse the selection to a caret where the pointer is.
    // we'd not like to prevent that

    var ih = this;

    if (ih._resizingNow) {
        ih._stopResize();
    }
};

WYMeditor.ImageHandler.prototype._stopResize = function () {
    var ih = this;

    ih._resizingNow = false;
    ih._startMouseY = null;
    ih._wym.registerModification();
};

WYMeditor.ImageHandler.prototype._onImgMousedown = function (evt) {
    var ih = this;

    if (jQuery.browser.msie && jQuery.browser.versionNumber === 11) {
        // IE11 on image mousedown places native resize handles around the image.
        // selecting the image both here and on `click` refrains from those handles
        // completely and seemingly without side effects.
        ih._selectImage(evt.target);
        // another way to refrain from the handles is preventing default.
        // but that would have an undesired side effect
        // of not allowing dragging and dropping of images.
    }

    // returning false here prevents drag of image
    // except for in IE8
    return ih._imgDragDropAllowed;
};

WYMeditor.ImageHandler.prototype._onAnyNativeEdit = function () {
    var ih = this;
    // modifications possibly not have occurred yet.
    // schedule immediate async in order to execute
    // after the possible modifications may have occurred
    setTimeout(ih._handlePossibleModification.bind(ih), 0);
};

WYMeditor.ImageHandler.prototype._handlePossibleModification = function () {
    var ih = this;

    if (!ih._isResizeHandleAttached()) {
        return;
    }

    if (!ih._isCurrentImgAtMarker()) {
        ih._detachResizeHandle();
        return;
    }

    // any edit to the document might result
    // in the image ending up in a different position than before.
    // for example, inserting a character before the image
    // pushes it to the right.
    ih._correctResizeHandleOffsetAndWidth();
};

WYMeditor.ImageHandler.prototype._isResizeHandleAttached = function () {
    var ih = this;
    var $handle = ih._getResizeHandle();
    return $handle && $handle.css('display') !== 'none';
};

WYMeditor.ImageHandler.prototype._getResizeHandle = function () {
    var ih = this;
    var $handle = ih._wym.$body().find('.' + WYMeditor.RESIZE_HANDLE_CLASS);
    return $handle.length ? $handle : false;
};

WYMeditor.ImageHandler.prototype._detachResizeHandle = function () {
    var ih = this;

    ih._$currentImageMarker.detach();
    if (
        // the size of the image might be so small,
        // that it would be hard to mouse over it
        // in order to make the resize handle appear.
        // in that case (an arbitrary number of pixels)
        // leave the padding on, as it will allow
        // easy mouse over the image,
        // even when the image is 0 in size
        ih._$currentImg.height() >= 16 &&
        ih._$currentImg.width() >= 16
    ) {
        ih._$currentImg.css({padding: 0, margin: 0});
    }
    ih._$currentImg = null;
    ih._$resizeHandle.hide();
};

WYMeditor.ImageHandler.prototype._onImgDragstart = function () {
    var ih = this;
    ih._detachResizeHandle();
};

WYMeditor.ImageHandler.prototype._onResizeHandleClickDblclick = function () {
    var ih = this;

    if (jQuery.browser.msie && jQuery.browser.versionNumber === 11) {
        // in IE11 some mouse events on the resize handle
        // result in native resize handles on it (eight small squares around it).
        // trying to resize the resize handle using these native handles
        // fails quite gracefully, as they seem to have no effect at all.
        // it fails most likely due to prevented native actions
        // in one of our event handlers.
        // however, deselecting here completely prevents these handles
        ih._wym.deselect();
    }
    // prevents entering edit mode in the handle
    return false;
};

// useful for debugging
WYMeditor.ImageHandler.prototype._isAnImgSelected = function (message) {
    var ih = this;
    message = message.toUpperCase();

    function check(prefix) {
        var result = ih._wym.getSelectedImage() ? '***YES***' : '';
        prefix = prefix ? prefix + ' ' : '';
        WYMeditor.console.log(prefix + message + ' ' + result);
    }

    check('sync');

    setTimeout(function () {
        check('async');
    }, 0);
};

// for debugging
WYMeditor.ImageHandler._onAllEvents = function (evt) {
    var ih = this;

    ih._isAnImgSelected([
        evt.type,
        evt.target.tagName,
        jQuery(evt.target).attr('className')
    ].join(' '));
};

/*jslint evil: true */
/* global -$ */
"use strict";

WYMeditor.WymClassGecko = function (wym) {
    var wymClassGecko = this;
    wymClassGecko._wym = wym;
    wymClassGecko._class = "class";
};

// Placeholder cell to allow content in TD cells for FF 3.5+
WYMeditor.WymClassGecko.CELL_PLACEHOLDER = '<br _moz_dirty="" />';

// Firefox 3.5 and 3.6 require the CELL_PLACEHOLDER and 4.0 doesn't
WYMeditor.WymClassGecko.NEEDS_CELL_FIX = parseInt(
    jQuery.browser.version, 10) === 1 &&
    jQuery.browser.version >= '1.9.1' &&
    jQuery.browser.version < '2.0';

WYMeditor.WymClassGecko.prototype._docEventQuirks = function () {
    var wym = this;
    var $doc = jQuery(wym._doc);

    $doc.keyup(wym._keyup.bind(wym));
    $doc.focus(function () {
        // not providing _onBodyFocus here because it doesn't exist yet
        wym.undoRedo._onBodyFocus();
    });
    $doc.click(wym._click.bind(wym));
};

// Keyup handler, mainly used for cleanups
WYMeditor.WymClassGecko.prototype._keyup = function (evt) {
    var wym = this,
        container,
        defaultRootContainer,
        notValidRootContainers,
        name,
        parentName;

    notValidRootContainers =
        wym.documentStructureManager.structureRules.notValidRootContainers;
    defaultRootContainer =
        wym.documentStructureManager.structureRules.defaultRootContainer;
    container = null;

    // If the inputted key cannont create a block element and is not a command,
    // check to make sure the selection is properly wrapped in a container
    if (!wym.keyCanCreateBlockElement(evt.which) &&
            evt.which !== WYMeditor.KEY_CODE.CTRL &&
            evt.which !== WYMeditor.KEY_CODE.COMMAND &&
            !evt.metaKey &&
            !evt.ctrlKey) {

        container = wym.selectedContainer();
        name = container.tagName.toLowerCase();
        if (container.parentNode) {
            parentName = container.parentNode.tagName.toLowerCase();
        }

        // Fix forbidden root containers
        if (wym.isForbiddenRootContainer(name)) {
            name = parentName;
        }

        // Replace text nodes with default root tags and make sure the
        // container is valid if it is a root container
        if (name === WYMeditor.BODY ||
                (jQuery.inArray(name, notValidRootContainers) > -1 &&
                parentName === WYMeditor.BODY)) {

            wym._exec(
                WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
                defaultRootContainer
            );
            wym.prepareDocForEditing();
        }
    }

    // If we potentially created a new block level element or moved to a new
    // one, then we should ensure the container is valid and the formatting is
    // proper.
    if (wym.keyCanCreateBlockElement(evt.which)) {
        // If the selected container is a root container, make sure it is not a
        // different possible default root container than the chosen one.
        container = wym.selectedContainer();
        name = container.tagName.toLowerCase();
        if (container.parentNode) {
            parentName = container.parentNode.tagName.toLowerCase();
        }
        if (jQuery.inArray(name, notValidRootContainers) > -1 &&
                parentName === WYMeditor.BODY) {
            wym._exec(
                WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
                defaultRootContainer
            );
        }

        // Call for the check for--and possible correction of--issue #430.
        wym._handlePotentialEnterInEmptyNestedLi(evt.which, container);

        // Fix formatting if necessary
        wym.prepareDocForEditing();
    }
};

WYMeditor.WymClassGecko.prototype._click = function () {
    var wym = this,
        container = wym.selectedContainer(),
        sel;

    if (WYMeditor.WymClassGecko.NEEDS_CELL_FIX === true) {
        if (container && container.tagName.toLowerCase() === WYMeditor.TR) {
            // Starting with FF 3.6, inserted tables need some content in their
            // cells before they're editable
            jQuery(WYMeditor.TD, wym._doc.body).append(
                WYMeditor.WymClassGecko.CELL_PLACEHOLDER);

            // The user is still going to need to move out of and then back in
            // to this cell if the table was inserted via an inner_html call
            // (like via the manual HTML editor).
            // TODO: Use rangy or some other selection library to consistently
            // put the users selection out of and then back in this cell
            // so that it appears to be instantly editable
            // Once accomplished, can remove the _afterInsertTable handling
        }
    }

    if (container && container.tagName.toLowerCase() === WYMeditor.BODY) {
        // A click in the body means there is no content at all, so we
        // should automatically create a starter paragraph
        sel = wym.selection();
        if (sel.isCollapsed === true) {
            // If the selection isn't collapsed, we might have a selection that
            // drags over the body, but we shouldn't turn everything in to a
            // paragraph tag. Otherwise, double-clicking in the space to the
            // right of an h2 tag would turn it in to a paragraph
            wym._exec(WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK, WYMeditor.P);
        }
    }
};

WYMeditor.WymClassGecko.prototype._designModeQuirks = function () {
    var wym = this;
    // Handle any errors that might occur.
    try {
        wym._doc.execCommand("styleWithCSS", '', false);
        wym._doc.execCommand("enableObjectResizing", false, false);
        wym._doc.execCommand("enableInlineTableEditing", false, false);
    } catch (e) {}
};

/*
 * Fix new cell contents and ability to insert content at the front and end of
 * the contents.
 */
WYMeditor.WymClassGecko.prototype._afterInsertTable = function (table) {
    if (WYMeditor.WymClassGecko.NEEDS_CELL_FIX === true) {
        // In certain FF versions, inserted tables need some content in their
        // cells before they're editable, otherwise the user has to move focus
        // in and then out of a cell first, even with our _click() hack
        jQuery(table).find('td').each(function (index, element) {
            jQuery(element).append(WYMeditor.WymClassGecko.CELL_PLACEHOLDER);
        });
    }
};

/*jslint evil: true */
/* global -$ */
"use strict";

WYMeditor.WymClassWebKit = function (wym) {
    var wymClassWebKit = this;
    wymClassWebKit._wym = wym;
    wymClassWebKit._class = "class";
};

WYMeditor.WymClassWebKit.prototype._docEventQuirks = function () {
    var wym = this;

    jQuery(wym._doc).bind("keyup", function (evt) {
        wym._keyup(evt);
    });

    wym.keyboard.combokeys.bind(
        "shift+enter",
        // WebKit's shift+enter seems to create a new paragraph so we fix it
        function () {
            wym._exec(WYMeditor.EXEC_COMMANDS.INSERT_LINEBREAK);
            return false;
        }
    );

    wym.$body().bind("focus", function () {
        wym.undoRedo._onBodyFocus();
    });
};

// A `div` can be created by breaking out of a list in some cases. Issue #549.
WYMeditor.WymClassWebKit.prototype._inListBreakoutDiv = function (evtWhich) {
    var wym = this,
        $rootContainer = jQuery(wym.getRootContainer());

    if (
        evtWhich === WYMeditor.KEY_CODE.ENTER &&
        $rootContainer.is('div') &&
        wym.documentStructureManager.defaultRootContainer !== 'div' &&
        $rootContainer.prev('ol, ul').length === 1
    ) {
        return true;
    }
    return false;
};

// Checks whether this is issue #542.
WYMeditor.WymClassWebKit.prototype._isLiInLiAfterEnter = function (evtWhich) {
    var wym = this,
        nodeAfterSel = wym.nodeAfterSel(),
        parentNode,
        previousSibling,
        previousSiblingChild,
        previousPreviousSibling;

    if (evtWhich !== WYMeditor.KEY_CODE.ENTER) {
        return false;
    }

    if (!nodeAfterSel) {
        return false;
    }

    parentNode = nodeAfterSel.parentNode;
    if (!parentNode) {
        return false;
    }
    if (typeof parentNode.tagName !== 'string') {
        return false;
    }
    if (parentNode.tagName.toLowerCase() !== 'li') {
        return false;
    }

    previousSibling = nodeAfterSel.previousSibling;
    if (!previousSibling) {
        return false;
    }
    if (typeof previousSibling.tagName !== 'string') {
        return false;
    }
    if (previousSibling.tagName.toLowerCase() !== 'li') {
        return false;
    }

    if (previousSibling.childNodes.length !== 1) {
        return false;
    }
    previousSiblingChild = previousSibling.childNodes[0];
    if (!previousSiblingChild) {
        return false;
    }
    if (typeof previousSiblingChild.tagName !== 'string') {
        return false;
    }
    if (previousSiblingChild.tagName.toLowerCase() !== 'br') {
        return false;
    }

    previousPreviousSibling = previousSibling.previousSibling;
    if (!previousPreviousSibling) {
        return false;
    }
    if (typeof previousPreviousSibling.tagName !== 'string') {
        return false;
    }
    if (
        jQuery.inArray(
        previousPreviousSibling.tagName.toLowerCase(),
        ['ol', 'ul']
        ) === -1
    ) {
        return false;
    }

    return true;
};

// Fixes issue #542.
WYMeditor.WymClassWebKit.prototype
    ._fixLiInLiAfterEnter = function () {
    var wym = this,
        nodeAfterSel = wym.nodeAfterSel(),
        $errorLi = jQuery(nodeAfterSel.previousSibling),
        $parentLi = $errorLi.parent('li'),
        errorLiIndex = $parentLi.contents().index($errorLi),
        $contentsAfterErrorLi = $parentLi.contents().slice(errorLiIndex + 1);

    $errorLi.remove();
    $parentLi.after('<li><br /></li>');
    $parentLi.next().append($contentsAfterErrorLi);
    wym.setCaretBefore($parentLi.next('li').children().first('br')[0]);
};

// Keyup handler, mainly used for cleanups
WYMeditor.WymClassWebKit.prototype._keyup = function (evt) {
    var wym = this,
        container,
        defaultRootContainer,
        notValidRootContainers,
        name,
        parentName,
        rootContainer;

    notValidRootContainers =
        wym.documentStructureManager.structureRules.notValidRootContainers;
    defaultRootContainer =
        wym.documentStructureManager.structureRules.defaultRootContainer;

    // Fix to allow shift + return to insert a line break in older safari
    if (jQuery.browser.version < 534.1) {
        // Not needed in AT MAX chrome 6.0. Probably safe earlier
        if (evt.which === WYMeditor.KEY_CODE.ENTER && evt.shiftKey) {
            wym._exec('InsertLineBreak');
        }
    }

    // If the inputted key cannont create a block element and is not a command,
    // check to make sure the selection is properly wrapped in a container
    if (!wym.keyCanCreateBlockElement(evt.which) &&
            evt.which !== WYMeditor.KEY_CODE.CTRL &&
            evt.which !== WYMeditor.KEY_CODE.COMMAND &&
            !evt.metaKey &&
            !evt.ctrlKey) {

        container = wym.selectedContainer();
        name = container.tagName.toLowerCase();
        if (container.parentNode) {
            parentName = container.parentNode.tagName.toLowerCase();
        }

        // Fix forbidden root containers
        if (wym.isForbiddenRootContainer(name)) {
            name = parentName;
        }

        // Replace text nodes with default root tags and make sure the
        // container is valid if it is a root container
        if (name === WYMeditor.BODY ||
                (jQuery.inArray(name, notValidRootContainers) > -1 &&
                parentName === WYMeditor.BODY)) {

            wym._exec(
                WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
                defaultRootContainer
            );
            wym.prepareDocForEditing();
        }
    }

    // If we potentially created a new block level element or moved to a new
    // one, then we should ensure the container is valid and the formatting is
    // proper.
    if (wym.keyCanCreateBlockElement(evt.which)) {
        // If the selected container is a root container, make sure it is not a
        // different possible default root container than the chosen one.
        container = wym.selectedContainer();
        name = container.tagName.toLowerCase();
        if (container.parentNode) {
            parentName = container.parentNode.tagName.toLowerCase();
        }
        if (jQuery.inArray(name, notValidRootContainers) > -1 &&
                parentName === WYMeditor.BODY) {
            wym._exec(
                WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
                defaultRootContainer
            );
            container = wym.selectedContainer();
        }

        // Issue #542
        if (wym._isLiInLiAfterEnter(evt.which, container)) {
            wym._fixLiInLiAfterEnter();
            // Container may have changed.
            container = wym.selectedContainer();
            return;
        }

        // Call for the check for--and possible correction of--issue #430.
        wym._handlePotentialEnterInEmptyNestedLi(evt.which, container);

        // Issue #549.
        if (wym._inListBreakoutDiv(evt.which)) {
            rootContainer = wym.switchTo(
                wym.getRootContainer(),
                defaultRootContainer
            );
            wym.setCaretIn(rootContainer);
        }

        // Fix formatting if necessary
        wym.prepareDocForEditing();
    }
};

/* jshint evil: true */
"use strict";

WYMeditor.WymClassBlink = function (wym) {
    var wymClassBlink = this;
    wymClassBlink._wym = wym;
};

jQuery.extend(
    WYMeditor.WymClassBlink.prototype,
    WYMeditor.WymClassWebKit.prototype
);

/* jshint evil: true */
"use strict";

WYMeditor.WymClassSafari = function (wym) {
    var wymClassSafari = this;
    wymClassSafari._wym = wym;
};

jQuery.extend(
    WYMeditor.WymClassSafari.prototype,
    WYMeditor.WymClassWebKit.prototype
);

/*jslint evil: true */
/* global rangy, -$ */
"use strict";

WYMeditor.WymClassTridentPre7 = function (wym) {
    var wymClassTridentPre7 = this;
    wymClassTridentPre7._wym = wym;
    wymClassTridentPre7._class = "className";
};

WYMeditor.WymClassTridentPre7.prototype._onEditorIframeLoad = function (wym) {
    wym._assignWymDoc();

    if (wym._isDesignModeOn() === false) {
        wym._doc.designMode = "On";
    } else {
        // Pre-7 Trident Internet Explorer versions reload the Iframe when its
        // designMode property is set to "on". So this will run on the second
        // time this handler is called.
        wym._afterDesignModeOn();
    }
};

WYMeditor.WymClassTridentPre7.prototype._assignWymDoc = function () {
    var wym = this;

    wym._doc = wym._iframe.contentWindow.document;
};

WYMeditor.WymClassTridentPre7.prototype._docEventQuirks = function () {
    var wym = this;

    wym._doc.onbeforedeactivate = function () {
        wym._saveCaret();
    };
    jQuery(wym._doc).bind('keyup', function (evt) {
        wym._keyup(evt);
    });
    wym._doc.onkeyup = function () {
        wym._saveCaret();
    };
    wym._doc.onclick = function () {
        wym._saveCaret();
    };

    wym.$body().bind("focus", function () {
        wym.undoRedo._onBodyFocus();
    });

    wym._doc.body.onbeforepaste = function () {
        wym._iframe.contentWindow.event.returnValue = false;
    };

    wym._doc.body.onpaste = function () {
        wym._iframe.contentWindow.event.returnValue = false;
        wym.paste(window.clipboardData.getData("Text"));
    };

    // https://github.com/wymeditor/wymeditor/pull/641
    wym.$body().bind("dragend", function (evt) {
        if (evt.target.tagName.toLowerCase() === WYMeditor.IMG) {
            wym.deselect();
        }
    });

    wym._doc.oncontrolselect = function () {
        // this prevents resize handles on various element
        // such as images, at least in IE8
        return false;
    };
};

WYMeditor.WymClassTridentPre7.prototype._setButtonsUnselectable = function () {
    // Mark UI buttons as unselectable (#203)
    // Issue explained here:
    // http://stackoverflow.com/questions/1470932
    var wym = this,
        $buttons = wym.get$Buttons();

    $buttons.attr('unselectable', 'on');
};

WYMeditor.WymClassTridentPre7.prototype._uiQuirks = function () {
    var wym = this;
    if (jQuery.browser.versionNumber === 8) {
        wym._setButtonsUnselectable();
    }
};

WYMeditor.WymClassTridentPre7.prototype._saveCaret = function () {
    var wym = this,
        nativeSelection = wym._doc.selection;

    if (nativeSelection.type === "None") {
        return;
    }
    wym._doc.caretPos = nativeSelection.createRange();
};

/**
    _wrapWithContainer
    ==================

    Wraps the passed node in a container of the passed type. Also, restores the
    selection to being after the node within its new container.

    @param node A DOM node to be wrapped in a container
    @param containerType A string of an HTML tag that specifies the container
                         type to use for wrapping the node.
*/
WYMeditor.WymClassTridentPre7.prototype._wrapWithContainer = function (
    node, containerType
) {
    var wym = this,
        $wrappedNode,
        selection,
        range;

    $wrappedNode = jQuery(node).wrap('<' + containerType + ' />');
    selection = wym.selection();
    range = rangy.createRange(wym._doc);
    range.selectNodeContents($wrappedNode[0]);
    range.collapse();
    selection.setSingleRange(range);
};

WYMeditor.WymClassTridentPre7.prototype._keyup = function (evt) {
    var wym = this,
        container,
        defaultRootContainer,
        notValidRootContainers,
        name,
        parentName,
        forbiddenMainContainer = false,
        selectedNode;

    notValidRootContainers =
        wym.documentStructureManager.structureRules.notValidRootContainers;
    defaultRootContainer =
        wym.documentStructureManager.structureRules.defaultRootContainer;

    // If the pressed key can't create a block element and is not a command,
    // check to make sure the selection is properly wrapped in a container
    if (!wym.keyCanCreateBlockElement(evt.which) &&
            evt.which !== WYMeditor.KEY_CODE.CTRL &&
            evt.which !== WYMeditor.KEY_CODE.COMMAND &&
            !evt.metaKey &&
            !evt.ctrlKey) {

        container = wym.selectedContainer();
        selectedNode = wym.selection().focusNode;
        if (container !== null) {
            name = container.tagName.toLowerCase();
        }
        if (container.parentNode) {
            parentName = container.parentNode.tagName.toLowerCase();
        }

        // Fix forbidden root containers
        if (wym.isForbiddenRootContainer(name)) {
            name = parentName;
            forbiddenMainContainer = true;
        }

        // Wrap text nodes and forbidden root containers with default root node
        // tags
        if (name === WYMeditor.BODY && selectedNode.nodeName === "#text") {
            // If we're in a forbidden root container, switch the selected node
            // to its parent node so that we wrap the forbidden root container
            // itself and not its inner text content
            if (forbiddenMainContainer) {
                selectedNode = selectedNode.parentNode;
            }
            wym._wrapWithContainer(selectedNode, defaultRootContainer);
            wym.prepareDocForEditing();
        }

        if (jQuery.inArray(name, notValidRootContainers) > -1 &&
                parentName === WYMeditor.BODY) {
            wym.switchTo(container, defaultRootContainer);
            wym.prepareDocForEditing();
        }
    }

    // If we potentially created a new block level element or moved to a new
    // one, then we should ensure the container is valid and the formatting is
    // proper.
    if (wym.keyCanCreateBlockElement(evt.which)) {
        // If the selected container is a root container, make sure it is not a
        // different possible default root container than the chosen one.
        container = wym.selectedContainer();
        name = container.tagName.toLowerCase();
        if (container.parentNode) {
            parentName = container.parentNode.tagName.toLowerCase();
        }
        if (jQuery.inArray(name, notValidRootContainers) > -1 &&
                parentName === WYMeditor.BODY) {
            wym.switchTo(container, defaultRootContainer);
        }

        // Call for the check for--and possible correction of--issue #430.
        wym._handlePotentialEnterInEmptyNestedLi(evt.which, container);

        // IE8 bug https://github.com/wymeditor/wymeditor/issues/446
        if (
            evt.which === WYMeditor.KEY_CODE.BACKSPACE &&
            jQuery.browser.versionNumber === 8 &&
            container.parentNode && (
                parentName === 'ul' ||
                parentName === 'ol'
            )
        ) {
            wym._fixInvalidListNesting(container);
        }

        // Fix formatting if necessary
        wym.prepareDocForEditing();
    }
};

/* jshint evil: true */
/* global -$ */
"use strict";

/* This file is the custom code for Trident 7 and newer. At the time of writing
 * this, it is only IE11.
 */

WYMeditor.WymClassTrident7 = function (wym) {
    var wymClassTrident7 =  this;
    wymClassTrident7._wym = wym;
    wymClassTrident7._class = "class";
};

jQuery.extend(
    WYMeditor.WymClassTrident7.prototype,
    WYMeditor.WymClassGecko.prototype
);

jQuery.copyPropsFromObjectToObject(
    WYMeditor.WymClassTridentPre7.prototype,
    WYMeditor.WymClassTrident7.prototype,
    [
        '_exec',
        '_keyup',
        '_wrapWithContainer'
    ]
);

// Some tests fail in what seems to be an edge case of selection corruption.
// This method makes those tests pass.
// It seems to be an issue with Rangy and IE11.
WYMeditor.WymClassTrident7.prototype.rawHtml = function (html) {
    var wym = this;

    if (typeof html === "string") {
        wym._doc.designMode = "off";
        wym.$body().html(html);
        if (wym._isDesignModeOn() !== true) {
            wym._enableDesignModeOnDocument();
        }
    } else {
        return wym.$body().html();
    }
    return false;
};

WYMeditor.WymClassTrident7.prototype._docEventQuirks = function () {
    var wym = this;

    jQuery(wym._doc).bind("keyup", function (evt) {
        wym._keyup(evt);
    });

    // https://github.com/wymeditor/wymeditor/pull/641
    wym.$body().bind("dragend", function (evt) {
        if (evt.target.tagName.toLowerCase() === WYMeditor.IMG) {
            wym.deselect();
        }
    });

    wym.$body().bind("focus", function () {
        wym.undoRedo._onBodyFocus();
    });
};

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.foo = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict'

var _ = require('lodash')
var clone = require('udc')
var xtend = require('xtend')

/**
 * Gives birth to instances
 *
 * ```js
 * var History = require('object-history')
 * var initial = {foo: 'bar', name: 'victoria'}
 * var history = new History(initial, {limit: 33})
 * ```
 *
 * @name History
 * @param {Object} `initial` The initial history point
 * @param {Object} `options` `limit`: `{Number}` Remember this many backward points
 * @constructor
 * @api public
 */

module.exports = function (initial, options) {
  var self = this
  self.options = xtend({
    limit: null
  }, options)

  self.notObjError = new Error('requires a plain object')
  if (!initial || !_.isPlainObject(initial)) {
    throw self.notObjError
  }

  self.current = clone(initial)
  self.changesets = {
    backward: [],
    forward: []
  }
}

var proto = module.exports.prototype

proto.add = require('./prototype/add')
proto.get = require('./prototype/get')
proto.lengthBackward = require('./prototype/length-backward')
proto.lengthForward = require('./prototype/length-forward')
proto.backward = require('./prototype/backward')
proto.forward = require('./prototype/forward')
proto.move = require('./prototype/move')
proto.forgetAllInDirection = require('./prototype/forget-all-in-direction')
proto.forgetAllBackward = require('./prototype/forget-all-backward')
proto.forgetAllForward = require('./prototype/forget-all-forward')

},{"./prototype/add":2,"./prototype/backward":3,"./prototype/forget-all-backward":4,"./prototype/forget-all-forward":5,"./prototype/forget-all-in-direction":6,"./prototype/forward":7,"./prototype/get":8,"./prototype/length-backward":9,"./prototype/length-forward":10,"./prototype/move":11,"lodash":14,"udc":15,"xtend":16}],2:[function(require,module,exports){
'use strict'
var _ = require('lodash')
var diff = require('changeset')
var clone = require('udc')

/**
 * Add a history point object
 *
 * ```js
 * history.add({
 *   foo: 'bar',
 *   bar: 'foo'
 * })
 * ```
 *
 * @name add
 * @param {Object} `obj` The history point
 * @api public
 */

module.exports = function (obj) {
  var self = this

  if (!obj || !_.isPlainObject(obj)) {
    throw self.notObjError
  }

  if (self.lengthBackward() === self.options.limit) {
    // limit reached. remove the oldest
    self.changesets.backward.shift()
  }

  self.changesets.backward.push(diff(obj, self.current))

  self.current = clone(obj)

  self.changesets.forward = []
}

},{"changeset":12,"lodash":14,"udc":15}],3:[function(require,module,exports){
'use strict'

/**
 * Go back one history point
 *
 * @name backward
 * @api public
 */

module.exports = function () {
  var self = this

  self.move('backward')
}

},{}],4:[function(require,module,exports){
'use strict'

/**
 * Makes all backward history forgotten
 *
 * @name forgetAllBackward
 * @api public
 * @since 3.1.0
 */

module.exports = function () {
  var self = this

  self.forgetAllInDirection('backward')
}

},{}],5:[function(require,module,exports){
'use strict'

/**
 * Makes all forward history forgotten
 *
 * @name forgetAllForward
 * @api public
 * @since 3.1.0
 */

module.exports = function () {
  var self = this

  self.forgetAllInDirection('forward')
}

},{}],6:[function(require,module,exports){
/**
 * Makes all history in a certain direction forgotten
 *
 * @param {String} `direction` The direction in which to forget
 *   @option `'forward'` [direction]
 *   @option `'backward'` [direction]
 * @api private
 * @since 3.1.0
 */
var forgetAllInDirection = function (direction) {
  var self = this
  var changesets = self.changesets

  if (!changesets.hasOwnProperty(direction)) {
    throw new Error('there is no such direction')
  }

  changesets[direction] = []
}

module.exports = forgetAllInDirection

},{}],7:[function(require,module,exports){
'use strict'

/**
 * Go forward one history point
 *
 * @name forward
 * @api public
 */

module.exports = function () {
  var self = this

  self.move('forward')
}

},{}],8:[function(require,module,exports){
'use strict'

var clone = require('udc')

/**
 * @name get
 * @return {Object} "Current" history point
 * @api public
 */

module.exports = function () {
  var self = this

  return clone(self.current)
}

},{"udc":15}],9:[function(require,module,exports){
'use strict'

/**
 * @name lengthBackward
 * @return {Number} Number of history points backwards
 * @api public
 */

module.exports = function () {
  var self = this

  return self.changesets.backward.length
}

},{}],10:[function(require,module,exports){
'use strict'

/**
 * @name lengthForward
 * @return {Number} Number of history points forward
 * @api public
 */

module.exports = function () {
  var self = this

  return self.changesets.forward.length
}

},{}],11:[function(require,module,exports){
'use strict'
var diff = require('changeset')
var apply = diff.apply
var without = require('lodash').without

/**
 * Move forward or backwards
 *
 * @api private
 * @param {String} `direction` direction of movement either `'backward'` or `'forward'`
 */

var move = function (direction) {
  var self = this

  if (!direction || !self.changesets.hasOwnProperty(direction)) {
    throw new Error('Invalid direction')
  }

  // get the reverse direction name
  var directions = Object.getOwnPropertyNames(self.changesets)
  var reverseDirection = without(directions, direction)[0]

  // the directions will refer to the arrays of changesets
  var changesets = self.changesets[direction]
  var reverseChangesets = self.changesets[reverseDirection]

  if (changesets.length === 0) {
    throw new Error('There\'s no going ' + direction)
  }

  // create the new object by applying the last changeset from
  // this direction on the current object. this will be our new current
  var newCurrent = apply(changesets.pop(), self.current)

  // push to the reverse direction a changeset from the new object
  // to the current object so that we could go back
  reverseChangesets.push(diff(newCurrent, self.current))

  self.current = newCurrent
}

module.exports = move

},{"changeset":12,"lodash":14}],12:[function(require,module,exports){
var _ = require('underscore');

module.exports = diff;
function diff(old, new_) {
  var changes = [];

  changes = changes.concat(compare([], old, new_));

  comparing = [];
  return changes;
}

function delCheck(op) {
  if (op.type === 'put' && op.value === undefined) {
    op.type = 'del';
    delete op.value;
  }
  return op;
}

var comparing = [];
function compare(path, old, new_) {
  var changes = [];
  if (old !== null && new_ !== null &&
      typeof old === 'object' &&
      !_.contains(comparing, old)) {

    comparing.push(old);
    var oldKeys = Object.keys(old);
    var newKeys = Object.keys(new_);

    var sameKeys = _.intersection(oldKeys, newKeys);
    sameKeys.forEach(function (k) {
      var childChanges = compare(path.concat(k), old[k], new_[k]);
      changes = changes.concat(childChanges);
    });

    var delKeys = _.difference(oldKeys, newKeys);
    delKeys.forEach(function (k) {
      changes.push({ type: 'del', key: path.concat(k) });
    });

    var newKeys_ = _.difference(newKeys, oldKeys);
    newKeys_.forEach(function (k) {
      changes.push(delCheck(
        { type: 'put', key: path.concat(k), value: new_[k] }));
    });

  } else if (old !== new_) {
    changes.push(delCheck({ type: 'put', key: path, value: new_ }));
  }

  return changes;
}

module.exports.apply = apply;
function apply(changes, target, modify) {
  var obj, clone;
  if (modify) {
    obj = target;
  } else {
    clone = require("udc");
    obj = clone(target);
  }
  changes.forEach(function (ch) {
    var ptr, keys, len;
    switch (ch.type) {
      case 'put':
        ptr = obj;
        keys = ch.key;
        len = keys.length;
        if (len) {
          keys.forEach(function (prop, i) {
            if (!(prop in ptr)) {
              ptr[prop] = {};
            }

            if (i < len - 1) {
              ptr = ptr[prop];
            } else {
              ptr[prop] = ch.value;
            }
          });
        } else {
          obj = ch.value;
        }
        break;

      case 'del':
        ptr = obj;
        keys = ch.key;
        len = keys.length;
        if (len) {
          keys.forEach(function (prop, i) {
            if (!(prop in ptr)) {
              ptr[prop] = {};
            }

            if (i < len - 1) {
              ptr = ptr[prop];
            } else {
              delete ptr[prop];
            }
          });
        } else {
          obj = null;
        }
        break;
    }
  });
  return obj;
}

},{"udc":15,"underscore":13}],13:[function(require,module,exports){
//     Underscore.js 1.4.4
//     http://underscorejs.org
//     (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
//     Underscore may be freely distributed under the MIT license.

(function() {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `global` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var push             = ArrayProto.push,
      slice            = ArrayProto.slice,
      concat           = ArrayProto.concat,
      toString         = ObjProto.toString,
      hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `_` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  // Current version.
  _.VERSION = '1.4.4';

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      for (var key in obj) {
        if (_.has(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) return;
        }
      }
    }
  };

  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results[results.length] = iterator.call(context, value, index, list);
    });
    return results;
  };

  var reduceError = 'Reduce of empty array with no initial value';

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduce && obj.reduce === nativeReduce) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
    }
    each(obj, function(value, index, list) {
      if (!initial) {
        memo = value;
        initial = true;
      } else {
        memo = iterator.call(context, memo, value, index, list);
      }
    });
    if (!initial) throw new TypeError(reduceError);
    return memo;
  };

  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
    }
    var length = obj.length;
    if (length !== +length) {
      var keys = _.keys(obj);
      length = keys.length;
    }
    each(obj, function(value, index, list) {
      index = keys ? keys[--length] : --length;
      if (!initial) {
        memo = obj[index];
        initial = true;
      } else {
        memo = iterator.call(context, memo, obj[index], index, list);
      }
    });
    if (!initial) throw new TypeError(reduceError);
    return memo;
  };

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, iterator, context) {
    var result;
    any(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) {
        result = value;
        return true;
      }
    });
    return result;
  };

  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
    each(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) results[results.length] = value;
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, iterator, context) {
    return _.filter(obj, function(value, index, list) {
      return !iterator.call(context, value, index, list);
    }, context);
  };

  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = true;
    if (obj == null) return result;
    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
    each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
    each(obj, function(value, index, list) {
      if (result || (result = iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if the array or object contains a given value (using `===`).
  // Aliased as `include`.
  _.contains = _.include = function(obj, target) {
    if (obj == null) return false;
    if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
    return any(obj, function(value) {
      return value === target;
    });
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    var isFunc = _.isFunction(method);
    return _.map(obj, function(value) {
      return (isFunc ? method : value[method]).apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, function(value){ return value[key]; });
  };

  // Convenience version of a common use case of `filter`: selecting only objects
  // containing specific `key:value` pairs.
  _.where = function(obj, attrs, first) {
    if (_.isEmpty(attrs)) return first ? null : [];
    return _[first ? 'find' : 'filter'](obj, function(value) {
      for (var key in attrs) {
        if (attrs[key] !== value[key]) return false;
      }
      return true;
    });
  };

  // Convenience version of a common use case of `find`: getting the first object
  // containing specific `key:value` pairs.
  _.findWhere = function(obj, attrs) {
    return _.where(obj, attrs, true);
  };

  // Return the maximum element or (element-based computation).
  // Can't optimize arrays of integers longer than 65,535 elements.
  // See: https://bugs.webkit.org/show_bug.cgi?id=80797
  _.max = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
      return Math.max.apply(Math, obj);
    }
    if (!iterator && _.isEmpty(obj)) return -Infinity;
    var result = {computed : -Infinity, value: -Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed >= result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
      return Math.min.apply(Math, obj);
    }
    if (!iterator && _.isEmpty(obj)) return Infinity;
    var result = {computed : Infinity, value: Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed < result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Shuffle an array.
  _.shuffle = function(obj) {
    var rand;
    var index = 0;
    var shuffled = [];
    each(obj, function(value) {
      rand = _.random(index++);
      shuffled[index - 1] = shuffled[rand];
      shuffled[rand] = value;
    });
    return shuffled;
  };

  // An internal function to generate lookup iterators.
  var lookupIterator = function(value) {
    return _.isFunction(value) ? value : function(obj){ return obj[value]; };
  };

  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, value, context) {
    var iterator = lookupIterator(value);
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value : value,
        index : index,
        criteria : iterator.call(context, value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index < right.index ? -1 : 1;
    }), 'value');
  };

  // An internal function used for aggregate "group by" operations.
  var group = function(obj, value, context, behavior) {
    var result = {};
    var iterator = lookupIterator(value || _.identity);
    each(obj, function(value, index) {
      var key = iterator.call(context, value, index, obj);
      behavior(result, key, value);
    });
    return result;
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = function(obj, value, context) {
    return group(obj, value, context, function(result, key, value) {
      (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
    });
  };

  // Counts instances of an object that group by a certain criterion. Pass
  // either a string attribute to count by, or a function that returns the
  // criterion.
  _.countBy = function(obj, value, context) {
    return group(obj, value, context, function(result, key) {
      if (!_.has(result, key)) result[key] = 0;
      result[key]++;
    });
  };

  // Use a comparator function to figure out the smallest index at which
  // an object should be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iterator, context) {
    iterator = iterator == null ? _.identity : lookupIterator(iterator);
    var value = iterator.call(context, obj);
    var low = 0, high = array.length;
    while (low < high) {
      var mid = (low + high) >>> 1;
      iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
    }
    return low;
  };

  // Safely convert anything iterable into a real, live array.
  _.toArray = function(obj) {
    if (!obj) return [];
    if (_.isArray(obj)) return slice.call(obj);
    if (obj.length === +obj.length) return _.map(obj, _.identity);
    return _.values(obj);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    if (obj == null) return 0;
    return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

  // Returns everything but the last entry of the array. Especially useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N. The **guard** check allows it to work with
  // `_.map`.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array. The **guard** check allows it to work with `_.map`.
  _.last = function(array, n, guard) {
    if (array == null) return void 0;
    if ((n != null) && !guard) {
      return slice.call(array, Math.max(array.length - n, 0));
    } else {
      return array[array.length - 1];
    }
  };

  // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  // Especially useful on the arguments object. Passing an **n** will return
  // the rest N values in the array. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = _.drop = function(array, n, guard) {
    return slice.call(array, (n == null) || guard ? 1 : n);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, _.identity);
  };

  // Internal implementation of a recursive `flatten` function.
  var flatten = function(input, shallow, output) {
    each(input, function(value) {
      if (_.isArray(value)) {
        shallow ? push.apply(output, value) : flatten(value, shallow, output);
      } else {
        output.push(value);
      }
    });
    return output;
  };

  // Return a completely flattened version of an array.
  _.flatten = function(array, shallow) {
    return flatten(array, shallow, []);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted, iterator, context) {
    if (_.isFunction(isSorted)) {
      context = iterator;
      iterator = isSorted;
      isSorted = false;
    }
    var initial = iterator ? _.map(array, iterator, context) : array;
    var results = [];
    var seen = [];
    each(initial, function(value, index) {
      if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
        seen.push(value);
        results.push(array[index]);
      }
    });
    return results;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(concat.apply(ArrayProto, arguments));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  _.intersection = function(array) {
    var rest = slice.call(arguments, 1);
    return _.filter(_.uniq(array), function(item) {
      return _.every(rest, function(other) {
        return _.indexOf(other, item) >= 0;
      });
    });
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function(array) {
    var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
    return _.filter(array, function(value){ return !_.contains(rest, value); });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
    var args = slice.call(arguments);
    var length = _.max(_.pluck(args, 'length'));
    var results = new Array(length);
    for (var i = 0; i < length; i++) {
      results[i] = _.pluck(args, "" + i);
    }
    return results;
  };

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values.
  _.object = function(list, values) {
    if (list == null) return {};
    var result = {};
    for (var i = 0, l = list.length; i < l; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  };

  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i = 0, l = array.length;
    if (isSorted) {
      if (typeof isSorted == 'number') {
        i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
      } else {
        i = _.sortedIndex(array, item);
        return array[i] === item ? i : -1;
      }
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
    for (; i < l; i++) if (array[i] === item) return i;
    return -1;
  };

  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item, from) {
    if (array == null) return -1;
    var hasIndex = from != null;
    if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
      return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
    }
    var i = (hasIndex ? from : array.length);
    while (i--) if (array[i] === item) return i;
    return -1;
  };

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
    if (arguments.length <= 1) {
      stop = start || 0;
      start = 0;
    }
    step = arguments[2] || 1;

    var len = Math.max(Math.ceil((stop - start) / step), 0);
    var idx = 0;
    var range = new Array(len);

    while(idx < len) {
      range[idx++] = start;
      start += step;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  // available.
  _.bind = function(func, context) {
    if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    var args = slice.call(arguments, 2);
    return function() {
      return func.apply(context, args.concat(slice.call(arguments)));
    };
  };

  // Partially apply a function by creating a version that has had some of its
  // arguments pre-filled, without changing its dynamic `this` context.
  _.partial = function(func) {
    var args = slice.call(arguments, 1);
    return function() {
      return func.apply(this, args.concat(slice.call(arguments)));
    };
  };

  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function(obj) {
    var funcs = slice.call(arguments, 1);
    if (funcs.length === 0) funcs = _.functions(obj);
    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memo = {};
    hasher || (hasher = _.identity);
    return function() {
      var key = hasher.apply(this, arguments);
      return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
    };
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){ return func.apply(null, args); }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function(func) {
    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time.
  _.throttle = function(func, wait) {
    var context, args, timeout, result;
    var previous = 0;
    var later = function() {
      previous = new Date;
      timeout = null;
      result = func.apply(context, args);
    };
    return function() {
      var now = new Date;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0) {
        clearTimeout(timeout);
        timeout = null;
        previous = now;
        result = func.apply(context, args);
      } else if (!timeout) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  _.debounce = function(func, wait, immediate) {
    var timeout, result;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) result = func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) result = func.apply(context, args);
      return result;
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
    return function() {
      var args = [func];
      push.apply(args, arguments);
      return wrapper.apply(this, args);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
    var funcs = arguments;
    return function() {
      var args = arguments;
      for (var i = funcs.length - 1; i >= 0; i--) {
        args = [funcs[i].apply(this, args)];
      }
      return args[0];
    };
  };

  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
    if (times <= 0) return func();
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

  // Object Functions
  // ----------------

  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    var values = [];
    for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
    return values;
  };

  // Convert an object into a list of `[key, value]` pairs.
  _.pairs = function(obj) {
    var pairs = [];
    for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
    return pairs;
  };

  // Invert the keys and values of an object. The values must be serializable.
  _.invert = function(obj) {
    var result = {};
    for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
    return result;
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = function(obj) {
    var copy = {};
    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
    each(keys, function(key) {
      if (key in obj) copy[key] = obj[key];
    });
    return copy;
  };

   // Return a copy of the object without the blacklisted properties.
  _.omit = function(obj) {
    var copy = {};
    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
    for (var key in obj) {
      if (!_.contains(keys, key)) copy[key] = obj[key];
    }
    return copy;
  };

  // Fill in a given object with default properties.
  _.defaults = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          if (obj[prop] == null) obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Internal recursive comparison function for `isEqual`.
  var eq = function(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
    if (a === b) return a !== 0 || 1 / a == 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a instanceof _) a = a._wrapped;
    if (b instanceof _) b = b._wrapped;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className != toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, dates, and booleans are compared by value.
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return a == String(b);
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
        // other numeric values.
        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a == +b;
      // RegExps are compared by their source patterns and flags.
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') return false;
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
    var length = aStack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (aStack[length] == a) return bStack[length] == b;
    }
    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);
    var size = 0, result = true;
    // Recursively compare objects and arrays.
    if (className == '[object Array]') {
      // Compare array lengths to determine if a deep comparison is necessary.
      size = a.length;
      result = size == b.length;
      if (result) {
        // Deep compare the contents, ignoring non-numeric properties.
        while (size--) {
          if (!(result = eq(a[size], b[size], aStack, bStack))) break;
        }
      }
    } else {
      // Objects with different constructors are not equivalent, but `Object`s
      // from different frames are.
      var aCtor = a.constructor, bCtor = b.constructor;
      if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
                               _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
        return false;
      }
      // Deep compare objects.
      for (var key in a) {
        if (_.has(a, key)) {
          // Count the expected number of properties.
          size++;
          // Deep compare each member.
          if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
        }
      }
      // Ensure that both objects contain the same number of properties.
      if (result) {
        for (key in b) {
          if (_.has(b, key) && !(size--)) break;
        }
        result = !size;
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return result;
  };

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
    return eq(a, b, [], []);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (obj == null) return true;
    if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
    for (var key in obj) if (_.has(obj, key)) return false;
    return true;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType === 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) == '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    return obj === Object(obj);
  };

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) == '[object ' + name + ']';
    };
  });

  // Define a fallback version of the method in browsers (ahem, IE), where
  // there isn't any inspectable "Arguments" type.
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return !!(obj && _.has(obj, 'callee'));
    };
  }

  // Optimize `isFunction` if appropriate.
  if (typeof (/./) !== 'function') {
    _.isFunction = function(obj) {
      return typeof obj === 'function';
    };
  }

  // Is a given object a finite number?
  _.isFinite = function(obj) {
    return isFinite(obj) && !isNaN(parseFloat(obj));
  };

  // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  _.isNaN = function(obj) {
    return _.isNumber(obj) && obj != +obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  _.has = function(obj, key) {
    return hasOwnProperty.call(obj, key);
  };

  // Utility Functions
  // -----------------

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iterators.
  _.identity = function(value) {
    return value;
  };

  // Run a function **n** times.
  _.times = function(n, iterator, context) {
    var accum = Array(n);
    for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
    return accum;
  };

  // Return a random integer between min and max (inclusive).
  _.random = function(min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
  };

  // List of HTML entities for escaping.
  var entityMap = {
    escape: {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;',
      '/': '&#x2F;'
    }
  };
  entityMap.unescape = _.invert(entityMap.escape);

  // Regexes containing the keys and values listed immediately above.
  var entityRegexes = {
    escape:   new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
    unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  };

  // Functions for escaping and unescaping strings to/from HTML interpolation.
  _.each(['escape', 'unescape'], function(method) {
    _[method] = function(string) {
      if (string == null) return '';
      return ('' + string).replace(entityRegexes[method], function(match) {
        return entityMap[method][match];
      });
    };
  });

  // If the value of the named property is a function then invoke it;
  // otherwise, return it.
  _.result = function(object, property) {
    if (object == null) return null;
    var value = object[property];
    return _.isFunction(value) ? value.call(object) : value;
  };

  // Add your own custom functions to the Underscore object.
  _.mixin = function(obj) {
    each(_.functions(obj), function(name){
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result.call(this, func.apply(_, args));
      };
    });
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'":      "'",
    '\\':     '\\',
    '\r':     'r',
    '\n':     'n',
    '\t':     't',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(text, data, settings) {
    var render;
    settings = _.defaults({}, settings, _.templateSettings);

    // Combine delimiters into one regular expression via alternation.
    var matcher = new RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset)
        .replace(escaper, function(match) { return '\\' + escapes[match]; });

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      }
      if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      }
      if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }
      index = offset + match.length;
      return match;
    });
    source += "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + "return __p;\n";

    try {
      render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    if (data) return render(data, _);
    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled function source as a convenience for precompilation.
    template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';

    return template;
  };

  // Add a "chain" function, which will delegate to the wrapper.
  _.chain = function(obj) {
    return _(obj).chain();
  };

  // OOP
  // ---------------
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.

  // Helper function to continue chaining intermediate results.
  var result = function(obj) {
    return this._chain ? _(obj).chain() : obj;
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      var obj = this._wrapped;
      method.apply(obj, arguments);
      if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
      return result.call(this, obj);
    };
  });

  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      return result.call(this, method.apply(this._wrapped, arguments));
    };
  });

  _.extend(_.prototype, {

    // Start chaining a wrapped Underscore object.
    chain: function() {
      this._chain = true;
      return this;
    },

    // Extracts the result from a wrapped and chained object.
    value: function() {
      return this._wrapped;
    }

  });

}).call(this);

},{}],14:[function(require,module,exports){
(function (global){
/**
 * @license
 * Lo-Dash 2.4.2 (Custom Build) <https://lodash.com/>
 * Build: `lodash modern -o ./dist/lodash.js`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <https://lodash.com/license>
 */
;(function() {

  /** Used as a safe reference for `undefined` in pre ES5 environments */
  var undefined;

  /** Used to pool arrays and objects used internally */
  var arrayPool = [],
      objectPool = [];

  /** Used to generate unique IDs */
  var idCounter = 0;

  /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
  var keyPrefix = +new Date + '';

  /** Used as the size when optimizations are enabled for large arrays */
  var largeArraySize = 75;

  /** Used as the max size of the `arrayPool` and `objectPool` */
  var maxPoolSize = 40;

  /** Used to detect and test whitespace */
  var whitespace = (
    // whitespace
    ' \t\x0B\f\xA0\ufeff' +

    // line terminators
    '\n\r\u2028\u2029' +

    // unicode category "Zs" space separators
    '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
  );

  /** Used to match empty string literals in compiled template source */
  var reEmptyStringLeading = /\b__p \+= '';/g,
      reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
      reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;

  /**
   * Used to match ES6 template delimiters
   * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals
   */
  var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;

  /** Used to match regexp flags from their coerced string values */
  var reFlags = /\w*$/;

  /** Used to detected named functions */
  var reFuncName = /^\s*function[ \n\r\t]+\w/;

  /** Used to match "interpolate" template delimiters */
  var reInterpolate = /<%=([\s\S]+?)%>/g;

  /** Used to match leading whitespace and zeros to be removed */
  var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');

  /** Used to ensure capturing order of template delimiters */
  var reNoMatch = /($^)/;

  /** Used to detect functions containing a `this` reference */
  var reThis = /\bthis\b/;

  /** Used to match unescaped characters in compiled string literals */
  var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;

  /** Used to assign default `context` object properties */
  var contextProps = [
    'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object',
    'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
    'parseInt', 'setTimeout'
  ];

  /** Used to make template sourceURLs easier to identify */
  var templateCounter = 0;

  /** `Object#toString` result shortcuts */
  var argsClass = '[object Arguments]',
      arrayClass = '[object Array]',
      boolClass = '[object Boolean]',
      dateClass = '[object Date]',
      funcClass = '[object Function]',
      numberClass = '[object Number]',
      objectClass = '[object Object]',
      regexpClass = '[object RegExp]',
      stringClass = '[object String]';

  /** Used to identify object classifications that `_.clone` supports */
  var cloneableClasses = {};
  cloneableClasses[funcClass] = false;
  cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
  cloneableClasses[boolClass] = cloneableClasses[dateClass] =
  cloneableClasses[numberClass] = cloneableClasses[objectClass] =
  cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;

  /** Used as an internal `_.debounce` options object */
  var debounceOptions = {
    'leading': false,
    'maxWait': 0,
    'trailing': false
  };

  /** Used as the property descriptor for `__bindData__` */
  var descriptor = {
    'configurable': false,
    'enumerable': false,
    'value': null,
    'writable': false
  };

  /** Used to determine if values are of the language type Object */
  var objectTypes = {
    'boolean': false,
    'function': true,
    'object': true,
    'number': false,
    'string': false,
    'undefined': false
  };

  /** Used to escape characters for inclusion in compiled string literals */
  var stringEscapes = {
    '\\': '\\',
    "'": "'",
    '\n': 'n',
    '\r': 'r',
    '\t': 't',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  /** Used as a reference to the global object */
  var root = (objectTypes[typeof window] && window) || this;

  /** Detect free variable `exports` */
  var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;

  /** Detect free variable `module` */
  var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;

  /** Detect the popular CommonJS extension `module.exports` */
  var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;

  /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
  var freeGlobal = objectTypes[typeof global] && global;
  if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
    root = freeGlobal;
  }

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

  /**
   * The base implementation of `_.indexOf` without support for binary searches
   * or `fromIndex` constraints.
   *
   * @private
   * @param {Array} array The array to search.
   * @param {*} value The value to search for.
   * @param {number} [fromIndex=0] The index to search from.
   * @returns {number} Returns the index of the matched value or `-1`.
   */
  function baseIndexOf(array, value, fromIndex) {
    var index = (fromIndex || 0) - 1,
        length = array ? array.length : 0;

    while (++index < length) {
      if (array[index] === value) {
        return index;
      }
    }
    return -1;
  }

  /**
   * An implementation of `_.contains` for cache objects that mimics the return
   * signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
   *
   * @private
   * @param {Object} cache The cache object to inspect.
   * @param {*} value The value to search for.
   * @returns {number} Returns `0` if `value` is found, else `-1`.
   */
  function cacheIndexOf(cache, value) {
    var type = typeof value;
    cache = cache.cache;

    if (type == 'boolean' || value == null) {
      return cache[value] ? 0 : -1;
    }
    if (type != 'number' && type != 'string') {
      type = 'object';
    }
    var key = type == 'number' ? value : keyPrefix + value;
    cache = (cache = cache[type]) && cache[key];

    return type == 'object'
      ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
      : (cache ? 0 : -1);
  }

  /**
   * Adds a given value to the corresponding cache object.
   *
   * @private
   * @param {*} value The value to add to the cache.
   */
  function cachePush(value) {
    var cache = this.cache,
        type = typeof value;

    if (type == 'boolean' || value == null) {
      cache[value] = true;
    } else {
      if (type != 'number' && type != 'string') {
        type = 'object';
      }
      var key = type == 'number' ? value : keyPrefix + value,
          typeCache = cache[type] || (cache[type] = {});

      if (type == 'object') {
        (typeCache[key] || (typeCache[key] = [])).push(value);
      } else {
        typeCache[key] = true;
      }
    }
  }

  /**
   * Used by `_.max` and `_.min` as the default callback when a given
   * collection is a string value.
   *
   * @private
   * @param {string} value The character to inspect.
   * @returns {number} Returns the code unit of given character.
   */
  function charAtCallback(value) {
    return value.charCodeAt(0);
  }

  /**
   * Used by `sortBy` to compare transformed `collection` elements, stable sorting
   * them in ascending order.
   *
   * @private
   * @param {Object} a The object to compare to `b`.
   * @param {Object} b The object to compare to `a`.
   * @returns {number} Returns the sort order indicator of `1` or `-1`.
   */
  function compareAscending(a, b) {
    var ac = a.criteria,
        bc = b.criteria,
        index = -1,
        length = ac.length;

    while (++index < length) {
      var value = ac[index],
          other = bc[index];

      if (value !== other) {
        if (value > other || typeof value == 'undefined') {
          return 1;
        }
        if (value < other || typeof other == 'undefined') {
          return -1;
        }
      }
    }
    // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
    // that causes it, under certain circumstances, to return the same value for
    // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
    //
    // This also ensures a stable sort in V8 and other engines.
    // See http://code.google.com/p/v8/issues/detail?id=90
    return a.index - b.index;
  }

  /**
   * Creates a cache object to optimize linear searches of large arrays.
   *
   * @private
   * @param {Array} [array=[]] The array to search.
   * @returns {null|Object} Returns the cache object or `null` if caching should not be used.
   */
  function createCache(array) {
    var index = -1,
        length = array.length,
        first = array[0],
        mid = array[(length / 2) | 0],
        last = array[length - 1];

    if (first && typeof first == 'object' &&
        mid && typeof mid == 'object' && last && typeof last == 'object') {
      return false;
    }
    var cache = getObject();
    cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;

    var result = getObject();
    result.array = array;
    result.cache = cache;
    result.push = cachePush;

    while (++index < length) {
      result.push(array[index]);
    }
    return result;
  }

  /**
   * Used by `template` to escape characters for inclusion in compiled
   * string literals.
   *
   * @private
   * @param {string} match The matched character to escape.
   * @returns {string} Returns the escaped character.
   */
  function escapeStringChar(match) {
    return '\\' + stringEscapes[match];
  }

  /**
   * Gets an array from the array pool or creates a new one if the pool is empty.
   *
   * @private
   * @returns {Array} The array from the pool.
   */
  function getArray() {
    return arrayPool.pop() || [];
  }

  /**
   * Gets an object from the object pool or creates a new one if the pool is empty.
   *
   * @private
   * @returns {Object} The object from the pool.
   */
  function getObject() {
    return objectPool.pop() || {
      'array': null,
      'cache': null,
      'criteria': null,
      'false': false,
      'index': 0,
      'null': false,
      'number': null,
      'object': null,
      'push': null,
      'string': null,
      'true': false,
      'undefined': false,
      'value': null
    };
  }

  /**
   * Releases the given array back to the array pool.
   *
   * @private
   * @param {Array} [array] The array to release.
   */
  function releaseArray(array) {
    array.length = 0;
    if (arrayPool.length < maxPoolSize) {
      arrayPool.push(array);
    }
  }

  /**
   * Releases the given object back to the object pool.
   *
   * @private
   * @param {Object} [object] The object to release.
   */
  function releaseObject(object) {
    var cache = object.cache;
    if (cache) {
      releaseObject(cache);
    }
    object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
    if (objectPool.length < maxPoolSize) {
      objectPool.push(object);
    }
  }

  /**
   * Slices the `collection` from the `start` index up to, but not including,
   * the `end` index.
   *
   * Note: This function is used instead of `Array#slice` to support node lists
   * in IE < 9 and to ensure dense arrays are returned.
   *
   * @private
   * @param {Array|Object|string} collection The collection to slice.
   * @param {number} start The start index.
   * @param {number} end The end index.
   * @returns {Array} Returns the new array.
   */
  function slice(array, start, end) {
    start || (start = 0);
    if (typeof end == 'undefined') {
      end = array ? array.length : 0;
    }
    var index = -1,
        length = end - start || 0,
        result = Array(length < 0 ? 0 : length);

    while (++index < length) {
      result[index] = array[start + index];
    }
    return result;
  }

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

  /**
   * Create a new `lodash` function using the given context object.
   *
   * @static
   * @memberOf _
   * @category Utilities
   * @param {Object} [context=root] The context object.
   * @returns {Function} Returns the `lodash` function.
   */
  function runInContext(context) {
    // Avoid issues with some ES3 environments that attempt to use values, named
    // after built-in constructors like `Object`, for the creation of literals.
    // ES5 clears this up by stating that literals must use built-in constructors.
    // See http://es5.github.io/#x11.1.5.
    context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;

    /** Native constructor references */
    var Array = context.Array,
        Boolean = context.Boolean,
        Date = context.Date,
        Function = context.Function,
        Math = context.Math,
        Number = context.Number,
        Object = context.Object,
        RegExp = context.RegExp,
        String = context.String,
        TypeError = context.TypeError;

    /**
     * Used for `Array` method references.
     *
     * Normally `Array.prototype` would suffice, however, using an array literal
     * avoids issues in Narwhal.
     */
    var arrayRef = [];

    /** Used for native method references */
    var objectProto = Object.prototype;

    /** Used to restore the original `_` reference in `noConflict` */
    var oldDash = context._;

    /** Used to resolve the internal [[Class]] of values */
    var toString = objectProto.toString;

    /** Used to detect if a method is native */
    var reNative = RegExp('^' +
      String(toString)
        .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
        .replace(/toString| for [^\]]+/g, '.*?') + '$'
    );

    /** Native method shortcuts */
    var ceil = Math.ceil,
        clearTimeout = context.clearTimeout,
        floor = Math.floor,
        fnToString = Function.prototype.toString,
        getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
        hasOwnProperty = objectProto.hasOwnProperty,
        push = arrayRef.push,
        setTimeout = context.setTimeout,
        splice = arrayRef.splice,
        unshift = arrayRef.unshift;

    /** Used to set meta data on functions */
    var defineProperty = (function() {
      // IE 8 only accepts DOM elements
      try {
        var o = {},
            func = isNative(func = Object.defineProperty) && func,
            result = func(o, o, o) && func;
      } catch(e) { }
      return result;
    }());

    /* Native method shortcuts for methods with the same name as other `lodash` methods */
    var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
        nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
        nativeIsFinite = context.isFinite,
        nativeIsNaN = context.isNaN,
        nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
        nativeMax = Math.max,
        nativeMin = Math.min,
        nativeParseInt = context.parseInt,
        nativeRandom = Math.random;

    /** Used to lookup a built-in constructor by [[Class]] */
    var ctorByClass = {};
    ctorByClass[arrayClass] = Array;
    ctorByClass[boolClass] = Boolean;
    ctorByClass[dateClass] = Date;
    ctorByClass[funcClass] = Function;
    ctorByClass[objectClass] = Object;
    ctorByClass[numberClass] = Number;
    ctorByClass[regexpClass] = RegExp;
    ctorByClass[stringClass] = String;

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

    /**
     * Creates a `lodash` object which wraps the given value to enable intuitive
     * method chaining.
     *
     * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
     * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
     * and `unshift`
     *
     * Chaining is supported in custom builds as long as the `value` method is
     * implicitly or explicitly included in the build.
     *
     * The chainable wrapper functions are:
     * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
     * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
     * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
     * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
     * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
     * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
     * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
     * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
     * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
     * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
     * and `zip`
     *
     * The non-chainable wrapper functions are:
     * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
     * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
     * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
     * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
     * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
     * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
     * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
     * `template`, `unescape`, `uniqueId`, and `value`
     *
     * The wrapper functions `first` and `last` return wrapped values when `n` is
     * provided, otherwise they return unwrapped values.
     *
     * Explicit chaining can be enabled by using the `_.chain` method.
     *
     * @name _
     * @constructor
     * @category Chaining
     * @param {*} value The value to wrap in a `lodash` instance.
     * @returns {Object} Returns a `lodash` instance.
     * @example
     *
     * var wrapped = _([1, 2, 3]);
     *
     * // returns an unwrapped value
     * wrapped.reduce(function(sum, num) {
     *   return sum + num;
     * });
     * // => 6
     *
     * // returns a wrapped value
     * var squares = wrapped.map(function(num) {
     *   return num * num;
     * });
     *
     * _.isArray(squares);
     * // => false
     *
     * _.isArray(squares.value());
     * // => true
     */
    function lodash(value) {
      // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
      return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
       ? value
       : new lodashWrapper(value);
    }

    /**
     * A fast path for creating `lodash` wrapper objects.
     *
     * @private
     * @param {*} value The value to wrap in a `lodash` instance.
     * @param {boolean} chainAll A flag to enable chaining for all methods
     * @returns {Object} Returns a `lodash` instance.
     */
    function lodashWrapper(value, chainAll) {
      this.__chain__ = !!chainAll;
      this.__wrapped__ = value;
    }
    // ensure `new lodashWrapper` is an instance of `lodash`
    lodashWrapper.prototype = lodash.prototype;

    /**
     * An object used to flag environments features.
     *
     * @static
     * @memberOf _
     * @type Object
     */
    var support = lodash.support = {};

    /**
     * Detect if functions can be decompiled by `Function#toString`
     * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
     *
     * @memberOf _.support
     * @type boolean
     */
    support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);

    /**
     * Detect if `Function#name` is supported (all but IE).
     *
     * @memberOf _.support
     * @type boolean
     */
    support.funcNames = typeof Function.name == 'string';

    /**
     * By default, the template delimiters used by Lo-Dash are similar to those in
     * embedded Ruby (ERB). Change the following template settings to use alternative
     * delimiters.
     *
     * @static
     * @memberOf _
     * @type Object
     */
    lodash.templateSettings = {

      /**
       * Used to detect `data` property values to be HTML-escaped.
       *
       * @memberOf _.templateSettings
       * @type RegExp
       */
      'escape': /<%-([\s\S]+?)%>/g,

      /**
       * Used to detect code to be evaluated.
       *
       * @memberOf _.templateSettings
       * @type RegExp
       */
      'evaluate': /<%([\s\S]+?)%>/g,

      /**
       * Used to detect `data` property values to inject.
       *
       * @memberOf _.templateSettings
       * @type RegExp
       */
      'interpolate': reInterpolate,

      /**
       * Used to reference the data object in the template text.
       *
       * @memberOf _.templateSettings
       * @type string
       */
      'variable': '',

      /**
       * Used to import variables into the compiled template.
       *
       * @memberOf _.templateSettings
       * @type Object
       */
      'imports': {

        /**
         * A reference to the `lodash` function.
         *
         * @memberOf _.templateSettings.imports
         * @type Function
         */
        '_': lodash
      }
    };

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

    /**
     * The base implementation of `_.bind` that creates the bound function and
     * sets its meta data.
     *
     * @private
     * @param {Array} bindData The bind data array.
     * @returns {Function} Returns the new bound function.
     */
    function baseBind(bindData) {
      var func = bindData[0],
          partialArgs = bindData[2],
          thisArg = bindData[4];

      function bound() {
        // `Function#bind` spec
        // http://es5.github.io/#x15.3.4.5
        if (partialArgs) {
          // avoid `arguments` object deoptimizations by using `slice` instead
          // of `Array.prototype.slice.call` and not assigning `arguments` to a
          // variable as a ternary expression
          var args = slice(partialArgs);
          push.apply(args, arguments);
        }
        // mimic the constructor's `return` behavior
        // http://es5.github.io/#x13.2.2
        if (this instanceof bound) {
          // ensure `new bound` is an instance of `func`
          var thisBinding = baseCreate(func.prototype),
              result = func.apply(thisBinding, args || arguments);
          return isObject(result) ? result : thisBinding;
        }
        return func.apply(thisArg, args || arguments);
      }
      setBindData(bound, bindData);
      return bound;
    }

    /**
     * The base implementation of `_.clone` without argument juggling or support
     * for `thisArg` binding.
     *
     * @private
     * @param {*} value The value to clone.
     * @param {boolean} [isDeep=false] Specify a deep clone.
     * @param {Function} [callback] The function to customize cloning values.
     * @param {Array} [stackA=[]] Tracks traversed source objects.
     * @param {Array} [stackB=[]] Associates clones with source counterparts.
     * @returns {*} Returns the cloned value.
     */
    function baseClone(value, isDeep, callback, stackA, stackB) {
      if (callback) {
        var result = callback(value);
        if (typeof result != 'undefined') {
          return result;
        }
      }
      // inspect [[Class]]
      var isObj = isObject(value);
      if (isObj) {
        var className = toString.call(value);
        if (!cloneableClasses[className]) {
          return value;
        }
        var ctor = ctorByClass[className];
        switch (className) {
          case boolClass:
          case dateClass:
            return new ctor(+value);

          case numberClass:
          case stringClass:
            return new ctor(value);

          case regexpClass:
            result = ctor(value.source, reFlags.exec(value));
            result.lastIndex = value.lastIndex;
            return result;
        }
      } else {
        return value;
      }
      var isArr = isArray(value);
      if (isDeep) {
        // check for circular references and return corresponding clone
        var initedStack = !stackA;
        stackA || (stackA = getArray());
        stackB || (stackB = getArray());

        var length = stackA.length;
        while (length--) {
          if (stackA[length] == value) {
            return stackB[length];
          }
        }
        result = isArr ? ctor(value.length) : {};
      }
      else {
        result = isArr ? slice(value) : assign({}, value);
      }
      // add array properties assigned by `RegExp#exec`
      if (isArr) {
        if (hasOwnProperty.call(value, 'index')) {
          result.index = value.index;
        }
        if (hasOwnProperty.call(value, 'input')) {
          result.input = value.input;
        }
      }
      // exit for shallow clone
      if (!isDeep) {
        return result;
      }
      // add the source value to the stack of traversed objects
      // and associate it with its clone
      stackA.push(value);
      stackB.push(result);

      // recursively populate clone (susceptible to call stack limits)
      (isArr ? forEach : forOwn)(value, function(objValue, key) {
        result[key] = baseClone(objValue, isDeep, callback, stackA, stackB);
      });

      if (initedStack) {
        releaseArray(stackA);
        releaseArray(stackB);
      }
      return result;
    }

    /**
     * The base implementation of `_.create` without support for assigning
     * properties to the created object.
     *
     * @private
     * @param {Object} prototype The object to inherit from.
     * @returns {Object} Returns the new object.
     */
    function baseCreate(prototype, properties) {
      return isObject(prototype) ? nativeCreate(prototype) : {};
    }
    // fallback for browsers without `Object.create`
    if (!nativeCreate) {
      baseCreate = (function() {
        function Object() {}
        return function(prototype) {
          if (isObject(prototype)) {
            Object.prototype = prototype;
            var result = new Object;
            Object.prototype = null;
          }
          return result || context.Object();
        };
      }());
    }

    /**
     * The base implementation of `_.createCallback` without support for creating
     * "_.pluck" or "_.where" style callbacks.
     *
     * @private
     * @param {*} [func=identity] The value to convert to a callback.
     * @param {*} [thisArg] The `this` binding of the created callback.
     * @param {number} [argCount] The number of arguments the callback accepts.
     * @returns {Function} Returns a callback function.
     */
    function baseCreateCallback(func, thisArg, argCount) {
      if (typeof func != 'function') {
        return identity;
      }
      // exit early for no `thisArg` or already bound by `Function#bind`
      if (typeof thisArg == 'undefined' || !('prototype' in func)) {
        return func;
      }
      var bindData = func.__bindData__;
      if (typeof bindData == 'undefined') {
        if (support.funcNames) {
          bindData = !func.name;
        }
        bindData = bindData || !support.funcDecomp;
        if (!bindData) {
          var source = fnToString.call(func);
          if (!support.funcNames) {
            bindData = !reFuncName.test(source);
          }
          if (!bindData) {
            // checks if `func` references the `this` keyword and stores the result
            bindData = reThis.test(source);
            setBindData(func, bindData);
          }
        }
      }
      // exit early if there are no `this` references or `func` is bound
      if (bindData === false || (bindData !== true && bindData[1] & 1)) {
        return func;
      }
      switch (argCount) {
        case 1: return function(value) {
          return func.call(thisArg, value);
        };
        case 2: return function(a, b) {
          return func.call(thisArg, a, b);
        };
        case 3: return function(value, index, collection) {
          return func.call(thisArg, value, index, collection);
        };
        case 4: return function(accumulator, value, index, collection) {
          return func.call(thisArg, accumulator, value, index, collection);
        };
      }
      return bind(func, thisArg);
    }

    /**
     * The base implementation of `createWrapper` that creates the wrapper and
     * sets its meta data.
     *
     * @private
     * @param {Array} bindData The bind data array.
     * @returns {Function} Returns the new function.
     */
    function baseCreateWrapper(bindData) {
      var func = bindData[0],
          bitmask = bindData[1],
          partialArgs = bindData[2],
          partialRightArgs = bindData[3],
          thisArg = bindData[4],
          arity = bindData[5];

      var isBind = bitmask & 1,
          isBindKey = bitmask & 2,
          isCurry = bitmask & 4,
          isCurryBound = bitmask & 8,
          key = func;

      function bound() {
        var thisBinding = isBind ? thisArg : this;
        if (partialArgs) {
          var args = slice(partialArgs);
          push.apply(args, arguments);
        }
        if (partialRightArgs || isCurry) {
          args || (args = slice(arguments));
          if (partialRightArgs) {
            push.apply(args, partialRightArgs);
          }
          if (isCurry && args.length < arity) {
            bitmask |= 16 & ~32;
            return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
          }
        }
        args || (args = arguments);
        if (isBindKey) {
          func = thisBinding[key];
        }
        if (this instanceof bound) {
          thisBinding = baseCreate(func.prototype);
          var result = func.apply(thisBinding, args);
          return isObject(result) ? result : thisBinding;
        }
        return func.apply(thisBinding, args);
      }
      setBindData(bound, bindData);
      return bound;
    }

    /**
     * The base implementation of `_.difference` that accepts a single array
     * of values to exclude.
     *
     * @private
     * @param {Array} array The array to process.
     * @param {Array} [values] The array of values to exclude.
     * @returns {Array} Returns a new array of filtered values.
     */
    function baseDifference(array, values) {
      var index = -1,
          indexOf = getIndexOf(),
          length = array ? array.length : 0,
          isLarge = length >= largeArraySize && indexOf === baseIndexOf,
          result = [];

      if (isLarge) {
        var cache = createCache(values);
        if (cache) {
          indexOf = cacheIndexOf;
          values = cache;
        } else {
          isLarge = false;
        }
      }
      while (++index < length) {
        var value = array[index];
        if (indexOf(values, value) < 0) {
          result.push(value);
        }
      }
      if (isLarge) {
        releaseObject(values);
      }
      return result;
    }

    /**
     * The base implementation of `_.flatten` without support for callback
     * shorthands or `thisArg` binding.
     *
     * @private
     * @param {Array} array The array to flatten.
     * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
     * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
     * @param {number} [fromIndex=0] The index to start from.
     * @returns {Array} Returns a new flattened array.
     */
    function baseFlatten(array, isShallow, isStrict, fromIndex) {
      var index = (fromIndex || 0) - 1,
          length = array ? array.length : 0,
          result = [];

      while (++index < length) {
        var value = array[index];

        if (value && typeof value == 'object' && typeof value.length == 'number'
            && (isArray(value) || isArguments(value))) {
          // recursively flatten arrays (susceptible to call stack limits)
          if (!isShallow) {
            value = baseFlatten(value, isShallow, isStrict);
          }
          var valIndex = -1,
              valLength = value.length,
              resIndex = result.length;

          result.length += valLength;
          while (++valIndex < valLength) {
            result[resIndex++] = value[valIndex];
          }
        } else if (!isStrict) {
          result.push(value);
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.isEqual`, without support for `thisArg` binding,
     * that allows partial "_.where" style comparisons.
     *
     * @private
     * @param {*} a The value to compare.
     * @param {*} b The other value to compare.
     * @param {Function} [callback] The function to customize comparing values.
     * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
     * @param {Array} [stackA=[]] Tracks traversed `a` objects.
     * @param {Array} [stackB=[]] Tracks traversed `b` objects.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     */
    function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
      // used to indicate that when comparing objects, `a` has at least the properties of `b`
      if (callback) {
        var result = callback(a, b);
        if (typeof result != 'undefined') {
          return !!result;
        }
      }
      // exit early for identical values
      if (a === b) {
        // treat `+0` vs. `-0` as not equal
        return a !== 0 || (1 / a == 1 / b);
      }
      var type = typeof a,
          otherType = typeof b;

      // exit early for unlike primitive values
      if (a === a &&
          !(a && objectTypes[type]) &&
          !(b && objectTypes[otherType])) {
        return false;
      }
      // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
      // http://es5.github.io/#x15.3.4.4
      if (a == null || b == null) {
        return a === b;
      }
      // compare [[Class]] names
      var className = toString.call(a),
          otherClass = toString.call(b);

      if (className == argsClass) {
        className = objectClass;
      }
      if (otherClass == argsClass) {
        otherClass = objectClass;
      }
      if (className != otherClass) {
        return false;
      }
      switch (className) {
        case boolClass:
        case dateClass:
          // coerce dates and booleans to numbers, dates to milliseconds and booleans
          // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
          return +a == +b;

        case numberClass:
          // treat `NaN` vs. `NaN` as equal
          return (a != +a)
            ? b != +b
            // but treat `+0` vs. `-0` as not equal
            : (a == 0 ? (1 / a == 1 / b) : a == +b);

        case regexpClass:
        case stringClass:
          // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
          // treat string primitives and their corresponding object instances as equal
          return a == String(b);
      }
      var isArr = className == arrayClass;
      if (!isArr) {
        // unwrap any `lodash` wrapped values
        var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
            bWrapped = hasOwnProperty.call(b, '__wrapped__');

        if (aWrapped || bWrapped) {
          return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
        }
        // exit for functions and DOM nodes
        if (className != objectClass) {
          return false;
        }
        // in older versions of Opera, `arguments` objects have `Array` constructors
        var ctorA = a.constructor,
            ctorB = b.constructor;

        // non `Object` object instances with different constructors are not equal
        if (ctorA != ctorB &&
              !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
              ('constructor' in a && 'constructor' in b)
            ) {
          return false;
        }
      }
      // assume cyclic structures are equal
      // the algorithm for detecting cyclic structures is adapted from ES 5.1
      // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
      var initedStack = !stackA;
      stackA || (stackA = getArray());
      stackB || (stackB = getArray());

      var length = stackA.length;
      while (length--) {
        if (stackA[length] == a) {
          return stackB[length] == b;
        }
      }
      var size = 0;
      result = true;

      // add `a` and `b` to the stack of traversed objects
      stackA.push(a);
      stackB.push(b);

      // recursively compare objects and arrays (susceptible to call stack limits)
      if (isArr) {
        // compare lengths to determine if a deep comparison is necessary
        length = a.length;
        size = b.length;
        result = size == length;

        if (result || isWhere) {
          // deep compare the contents, ignoring non-numeric properties
          while (size--) {
            var index = length,
                value = b[size];

            if (isWhere) {
              while (index--) {
                if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
                  break;
                }
              }
            } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
              break;
            }
          }
        }
      }
      else {
        // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
        // which, in this case, is more costly
        forIn(b, function(value, key, b) {
          if (hasOwnProperty.call(b, key)) {
            // count the number of properties.
            size++;
            // deep compare each property value.
            return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
          }
        });

        if (result && !isWhere) {
          // ensure both objects have the same number of properties
          forIn(a, function(value, key, a) {
            if (hasOwnProperty.call(a, key)) {
              // `size` will be `-1` if `a` has more properties than `b`
              return (result = --size > -1);
            }
          });
        }
      }
      stackA.pop();
      stackB.pop();

      if (initedStack) {
        releaseArray(stackA);
        releaseArray(stackB);
      }
      return result;
    }

    /**
     * The base implementation of `_.merge` without argument juggling or support
     * for `thisArg` binding.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @param {Function} [callback] The function to customize merging properties.
     * @param {Array} [stackA=[]] Tracks traversed source objects.
     * @param {Array} [stackB=[]] Associates values with source counterparts.
     */
    function baseMerge(object, source, callback, stackA, stackB) {
      (isArray(source) ? forEach : forOwn)(source, function(source, key) {
        var found,
            isArr,
            result = source,
            value = object[key];

        if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
          // avoid merging previously merged cyclic sources
          var stackLength = stackA.length;
          while (stackLength--) {
            if ((found = stackA[stackLength] == source)) {
              value = stackB[stackLength];
              break;
            }
          }
          if (!found) {
            var isShallow;
            if (callback) {
              result = callback(value, source);
              if ((isShallow = typeof result != 'undefined')) {
                value = result;
              }
            }
            if (!isShallow) {
              value = isArr
                ? (isArray(value) ? value : [])
                : (isPlainObject(value) ? value : {});
            }
            // add `source` and associated `value` to the stack of traversed objects
            stackA.push(source);
            stackB.push(value);

            // recursively merge objects and arrays (susceptible to call stack limits)
            if (!isShallow) {
              baseMerge(value, source, callback, stackA, stackB);
            }
          }
        }
        else {
          if (callback) {
            result = callback(value, source);
            if (typeof result == 'undefined') {
              result = source;
            }
          }
          if (typeof result != 'undefined') {
            value = result;
          }
        }
        object[key] = value;
      });
    }

    /**
     * The base implementation of `_.random` without argument juggling or support
     * for returning floating-point numbers.
     *
     * @private
     * @param {number} min The minimum possible value.
     * @param {number} max The maximum possible value.
     * @returns {number} Returns a random number.
     */
    function baseRandom(min, max) {
      return min + floor(nativeRandom() * (max - min + 1));
    }

    /**
     * The base implementation of `_.uniq` without support for callback shorthands
     * or `thisArg` binding.
     *
     * @private
     * @param {Array} array The array to process.
     * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
     * @param {Function} [callback] The function called per iteration.
     * @returns {Array} Returns a duplicate-value-free array.
     */
    function baseUniq(array, isSorted, callback) {
      var index = -1,
          indexOf = getIndexOf(),
          length = array ? array.length : 0,
          result = [];

      var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
          seen = (callback || isLarge) ? getArray() : result;

      if (isLarge) {
        var cache = createCache(seen);
        indexOf = cacheIndexOf;
        seen = cache;
      }
      while (++index < length) {
        var value = array[index],
            computed = callback ? callback(value, index, array) : value;

        if (isSorted
              ? !index || seen[seen.length - 1] !== computed
              : indexOf(seen, computed) < 0
            ) {
          if (callback || isLarge) {
            seen.push(computed);
          }
          result.push(value);
        }
      }
      if (isLarge) {
        releaseArray(seen.array);
        releaseObject(seen);
      } else if (callback) {
        releaseArray(seen);
      }
      return result;
    }

    /**
     * Creates a function that aggregates a collection, creating an object composed
     * of keys generated from the results of running each element of the collection
     * through a callback. The given `setter` function sets the keys and values
     * of the composed object.
     *
     * @private
     * @param {Function} setter The setter function.
     * @returns {Function} Returns the new aggregator function.
     */
    function createAggregator(setter) {
      return function(collection, callback, thisArg) {
        var result = {};
        callback = lodash.createCallback(callback, thisArg, 3);

        var index = -1,
            length = collection ? collection.length : 0;

        if (typeof length == 'number') {
          while (++index < length) {
            var value = collection[index];
            setter(result, value, callback(value, index, collection), collection);
          }
        } else {
          forOwn(collection, function(value, key, collection) {
            setter(result, value, callback(value, key, collection), collection);
          });
        }
        return result;
      };
    }

    /**
     * Creates a function that, when called, either curries or invokes `func`
     * with an optional `this` binding and partially applied arguments.
     *
     * @private
     * @param {Function|string} func The function or method name to reference.
     * @param {number} bitmask The bitmask of method flags to compose.
     *  The bitmask may be composed of the following flags:
     *  1 - `_.bind`
     *  2 - `_.bindKey`
     *  4 - `_.curry`
     *  8 - `_.curry` (bound)
     *  16 - `_.partial`
     *  32 - `_.partialRight`
     * @param {Array} [partialArgs] An array of arguments to prepend to those
     *  provided to the new function.
     * @param {Array} [partialRightArgs] An array of arguments to append to those
     *  provided to the new function.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {number} [arity] The arity of `func`.
     * @returns {Function} Returns the new function.
     */
    function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
      var isBind = bitmask & 1,
          isBindKey = bitmask & 2,
          isCurry = bitmask & 4,
          isCurryBound = bitmask & 8,
          isPartial = bitmask & 16,
          isPartialRight = bitmask & 32;

      if (!isBindKey && !isFunction(func)) {
        throw new TypeError;
      }
      if (isPartial && !partialArgs.length) {
        bitmask &= ~16;
        isPartial = partialArgs = false;
      }
      if (isPartialRight && !partialRightArgs.length) {
        bitmask &= ~32;
        isPartialRight = partialRightArgs = false;
      }
      var bindData = func && func.__bindData__;
      if (bindData && bindData !== true) {
        // clone `bindData`
        bindData = slice(bindData);
        if (bindData[2]) {
          bindData[2] = slice(bindData[2]);
        }
        if (bindData[3]) {
          bindData[3] = slice(bindData[3]);
        }
        // set `thisBinding` is not previously bound
        if (isBind && !(bindData[1] & 1)) {
          bindData[4] = thisArg;
        }
        // set if previously bound but not currently (subsequent curried functions)
        if (!isBind && bindData[1] & 1) {
          bitmask |= 8;
        }
        // set curried arity if not yet set
        if (isCurry && !(bindData[1] & 4)) {
          bindData[5] = arity;
        }
        // append partial left arguments
        if (isPartial) {
          push.apply(bindData[2] || (bindData[2] = []), partialArgs);
        }
        // append partial right arguments
        if (isPartialRight) {
          unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
        }
        // merge flags
        bindData[1] |= bitmask;
        return createWrapper.apply(null, bindData);
      }
      // fast path for `_.bind`
      var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
      return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
    }

    /**
     * Used by `escape` to convert characters to HTML entities.
     *
     * @private
     * @param {string} match The matched character to escape.
     * @returns {string} Returns the escaped character.
     */
    function escapeHtmlChar(match) {
      return htmlEscapes[match];
    }

    /**
     * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
     * customized, this method returns the custom method, otherwise it returns
     * the `baseIndexOf` function.
     *
     * @private
     * @returns {Function} Returns the "indexOf" function.
     */
    function getIndexOf() {
      var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
      return result;
    }

    /**
     * Checks if `value` is a native function.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
     */
    function isNative(value) {
      return typeof value == 'function' && reNative.test(value);
    }

    /**
     * Sets `this` binding data on a given function.
     *
     * @private
     * @param {Function} func The function to set data on.
     * @param {Array} value The data array to set.
     */
    var setBindData = !defineProperty ? noop : function(func, value) {
      descriptor.value = value;
      defineProperty(func, '__bindData__', descriptor);
      descriptor.value = null;
    };

    /**
     * A fallback implementation of `isPlainObject` which checks if a given value
     * is an object created by the `Object` constructor, assuming objects created
     * by the `Object` constructor have no inherited enumerable properties and that
     * there are no `Object.prototype` extensions.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
     */
    function shimIsPlainObject(value) {
      var ctor,
          result;

      // avoid non Object objects, `arguments` objects, and DOM elements
      if (!(value && toString.call(value) == objectClass) ||
          (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
        return false;
      }
      // In most environments an object's own properties are iterated before
      // its inherited properties. If the last iterated property is an object's
      // own property then there are no inherited enumerable properties.
      forIn(value, function(value, key) {
        result = key;
      });
      return typeof result == 'undefined' || hasOwnProperty.call(value, result);
    }

    /**
     * Used by `unescape` to convert HTML entities to characters.
     *
     * @private
     * @param {string} match The matched character to unescape.
     * @returns {string} Returns the unescaped character.
     */
    function unescapeHtmlChar(match) {
      return htmlUnescapes[match];
    }

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

    /**
     * Checks if `value` is an `arguments` object.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
     * @example
     *
     * (function() { return _.isArguments(arguments); })(1, 2, 3);
     * // => true
     *
     * _.isArguments([1, 2, 3]);
     * // => false
     */
    function isArguments(value) {
      return value && typeof value == 'object' && typeof value.length == 'number' &&
        toString.call(value) == argsClass || false;
    }

    /**
     * Checks if `value` is an array.
     *
     * @static
     * @memberOf _
     * @type Function
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is an array, else `false`.
     * @example
     *
     * (function() { return _.isArray(arguments); })();
     * // => false
     *
     * _.isArray([1, 2, 3]);
     * // => true
     */
    var isArray = nativeIsArray || function(value) {
      return value && typeof value == 'object' && typeof value.length == 'number' &&
        toString.call(value) == arrayClass || false;
    };

    /**
     * A fallback implementation of `Object.keys` which produces an array of the
     * given object's own enumerable property names.
     *
     * @private
     * @type Function
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns an array of property names.
     */
    var shimKeys = function(object) {
      var index, iterable = object, result = [];
      if (!iterable) return result;
      if (!(objectTypes[typeof object])) return result;
        for (index in iterable) {
          if (hasOwnProperty.call(iterable, index)) {
            result.push(index);
          }
        }
      return result
    };

    /**
     * Creates an array composed of the own enumerable property names of an object.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns an array of property names.
     * @example
     *
     * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
     * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
     */
    var keys = !nativeKeys ? shimKeys : function(object) {
      if (!isObject(object)) {
        return [];
      }
      return nativeKeys(object);
    };

    /**
     * Used to convert characters to HTML entities:
     *
     * Though the `>` character is escaped for symmetry, characters like `>` and `/`
     * don't require escaping in HTML and have no special meaning unless they're part
     * of a tag or an unquoted attribute value.
     * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
     */
    var htmlEscapes = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#39;'
    };

    /** Used to convert HTML entities to characters */
    var htmlUnescapes = invert(htmlEscapes);

    /** Used to match HTML entities and HTML characters */
    var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
        reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');

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

    /**
     * Assigns own enumerable properties of source object(s) to the destination
     * object. Subsequent sources will overwrite property assignments of previous
     * sources. If a callback is provided it will be executed to produce the
     * assigned values. The callback is bound to `thisArg` and invoked with two
     * arguments; (objectValue, sourceValue).
     *
     * @static
     * @memberOf _
     * @type Function
     * @alias extend
     * @category Objects
     * @param {Object} object The destination object.
     * @param {...Object} [source] The source objects.
     * @param {Function} [callback] The function to customize assigning values.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns the destination object.
     * @example
     *
     * _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
     * // => { 'name': 'fred', 'employer': 'slate' }
     *
     * var defaults = _.partialRight(_.assign, function(a, b) {
     *   return typeof a == 'undefined' ? b : a;
     * });
     *
     * var object = { 'name': 'barney' };
     * defaults(object, { 'name': 'fred', 'employer': 'slate' });
     * // => { 'name': 'barney', 'employer': 'slate' }
     */
    var assign = function(object, source, guard) {
      var index, iterable = object, result = iterable;
      if (!iterable) return result;
      var args = arguments,
          argsIndex = 0,
          argsLength = typeof guard == 'number' ? 2 : args.length;
      if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
        var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);
      } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
        callback = args[--argsLength];
      }
      while (++argsIndex < argsLength) {
        iterable = args[argsIndex];
        if (iterable && objectTypes[typeof iterable]) {
        var ownIndex = -1,
            ownProps = objectTypes[typeof iterable] && keys(iterable),
            length = ownProps ? ownProps.length : 0;

        while (++ownIndex < length) {
          index = ownProps[ownIndex];
          result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
        }
        }
      }
      return result
    };

    /**
     * Creates a clone of `value`. If `isDeep` is `true` nested objects will also
     * be cloned, otherwise they will be assigned by reference. If a callback
     * is provided it will be executed to produce the cloned values. If the
     * callback returns `undefined` cloning will be handled by the method instead.
     * The callback is bound to `thisArg` and invoked with one argument; (value).
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to clone.
     * @param {boolean} [isDeep=false] Specify a deep clone.
     * @param {Function} [callback] The function to customize cloning values.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the cloned value.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * var shallow = _.clone(characters);
     * shallow[0] === characters[0];
     * // => true
     *
     * var deep = _.clone(characters, true);
     * deep[0] === characters[0];
     * // => false
     *
     * _.mixin({
     *   'clone': _.partialRight(_.clone, function(value) {
     *     return _.isElement(value) ? value.cloneNode(false) : undefined;
     *   })
     * });
     *
     * var clone = _.clone(document.body);
     * clone.childNodes.length;
     * // => 0
     */
    function clone(value, isDeep, callback, thisArg) {
      // allows working with "Collections" methods without using their `index`
      // and `collection` arguments for `isDeep` and `callback`
      if (typeof isDeep != 'boolean' && isDeep != null) {
        thisArg = callback;
        callback = isDeep;
        isDeep = false;
      }
      return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
    }

    /**
     * Creates a deep clone of `value`. If a callback is provided it will be
     * executed to produce the cloned values. If the callback returns `undefined`
     * cloning will be handled by the method instead. The callback is bound to
     * `thisArg` and invoked with one argument; (value).
     *
     * Note: This method is loosely based on the structured clone algorithm. Functions
     * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
     * objects created by constructors other than `Object` are cloned to plain `Object` objects.
     * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to deep clone.
     * @param {Function} [callback] The function to customize cloning values.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the deep cloned value.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * var deep = _.cloneDeep(characters);
     * deep[0] === characters[0];
     * // => false
     *
     * var view = {
     *   'label': 'docs',
     *   'node': element
     * };
     *
     * var clone = _.cloneDeep(view, function(value) {
     *   return _.isElement(value) ? value.cloneNode(true) : undefined;
     * });
     *
     * clone.node == view.node;
     * // => false
     */
    function cloneDeep(value, callback, thisArg) {
      return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
    }

    /**
     * Creates an object that inherits from the given `prototype` object. If a
     * `properties` object is provided its own enumerable properties are assigned
     * to the created object.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} prototype The object to inherit from.
     * @param {Object} [properties] The properties to assign to the object.
     * @returns {Object} Returns the new object.
     * @example
     *
     * function Shape() {
     *   this.x = 0;
     *   this.y = 0;
     * }
     *
     * function Circle() {
     *   Shape.call(this);
     * }
     *
     * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
     *
     * var circle = new Circle;
     * circle instanceof Circle;
     * // => true
     *
     * circle instanceof Shape;
     * // => true
     */
    function create(prototype, properties) {
      var result = baseCreate(prototype);
      return properties ? assign(result, properties) : result;
    }

    /**
     * Assigns own enumerable properties of source object(s) to the destination
     * object for all destination properties that resolve to `undefined`. Once a
     * property is set, additional defaults of the same property will be ignored.
     *
     * @static
     * @memberOf _
     * @type Function
     * @category Objects
     * @param {Object} object The destination object.
     * @param {...Object} [source] The source objects.
     * @param- {Object} [guard] Allows working with `_.reduce` without using its
     *  `key` and `object` arguments as sources.
     * @returns {Object} Returns the destination object.
     * @example
     *
     * var object = { 'name': 'barney' };
     * _.defaults(object, { 'name': 'fred', 'employer': 'slate' });
     * // => { 'name': 'barney', 'employer': 'slate' }
     */
    var defaults = function(object, source, guard) {
      var index, iterable = object, result = iterable;
      if (!iterable) return result;
      var args = arguments,
          argsIndex = 0,
          argsLength = typeof guard == 'number' ? 2 : args.length;
      while (++argsIndex < argsLength) {
        iterable = args[argsIndex];
        if (iterable && objectTypes[typeof iterable]) {
        var ownIndex = -1,
            ownProps = objectTypes[typeof iterable] && keys(iterable),
            length = ownProps ? ownProps.length : 0;

        while (++ownIndex < length) {
          index = ownProps[ownIndex];
          if (typeof result[index] == 'undefined') result[index] = iterable[index];
        }
        }
      }
      return result
    };

    /**
     * This method is like `_.findIndex` except that it returns the key of the
     * first element that passes the callback check, instead of the element itself.
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to search.
     * @param {Function|Object|string} [callback=identity] The function called per
     *  iteration. If a property name or object is provided it will be used to
     *  create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {string|undefined} Returns the key of the found element, else `undefined`.
     * @example
     *
     * var characters = {
     *   'barney': {  'age': 36, 'blocked': false },
     *   'fred': {    'age': 40, 'blocked': true },
     *   'pebbles': { 'age': 1,  'blocked': false }
     * };
     *
     * _.findKey(characters, function(chr) {
     *   return chr.age < 40;
     * });
     * // => 'barney' (property order is not guaranteed across environments)
     *
     * // using "_.where" callback shorthand
     * _.findKey(characters, { 'age': 1 });
     * // => 'pebbles'
     *
     * // using "_.pluck" callback shorthand
     * _.findKey(characters, 'blocked');
     * // => 'fred'
     */
    function findKey(object, callback, thisArg) {
      var result;
      callback = lodash.createCallback(callback, thisArg, 3);
      forOwn(object, function(value, key, object) {
        if (callback(value, key, object)) {
          result = key;
          return false;
        }
      });
      return result;
    }

    /**
     * This method is like `_.findKey` except that it iterates over elements
     * of a `collection` in the opposite order.
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to search.
     * @param {Function|Object|string} [callback=identity] The function called per
     *  iteration. If a property name or object is provided it will be used to
     *  create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {string|undefined} Returns the key of the found element, else `undefined`.
     * @example
     *
     * var characters = {
     *   'barney': {  'age': 36, 'blocked': true },
     *   'fred': {    'age': 40, 'blocked': false },
     *   'pebbles': { 'age': 1,  'blocked': true }
     * };
     *
     * _.findLastKey(characters, function(chr) {
     *   return chr.age < 40;
     * });
     * // => returns `pebbles`, assuming `_.findKey` returns `barney`
     *
     * // using "_.where" callback shorthand
     * _.findLastKey(characters, { 'age': 40 });
     * // => 'fred'
     *
     * // using "_.pluck" callback shorthand
     * _.findLastKey(characters, 'blocked');
     * // => 'pebbles'
     */
    function findLastKey(object, callback, thisArg) {
      var result;
      callback = lodash.createCallback(callback, thisArg, 3);
      forOwnRight(object, function(value, key, object) {
        if (callback(value, key, object)) {
          result = key;
          return false;
        }
      });
      return result;
    }

    /**
     * Iterates over own and inherited enumerable properties of an object,
     * executing the callback for each property. The callback is bound to `thisArg`
     * and invoked with three arguments; (value, key, object). Callbacks may exit
     * iteration early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @type Function
     * @category Objects
     * @param {Object} object The object to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns `object`.
     * @example
     *
     * function Shape() {
     *   this.x = 0;
     *   this.y = 0;
     * }
     *
     * Shape.prototype.move = function(x, y) {
     *   this.x += x;
     *   this.y += y;
     * };
     *
     * _.forIn(new Shape, function(value, key) {
     *   console.log(key);
     * });
     * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
     */
    var forIn = function(collection, callback, thisArg) {
      var index, iterable = collection, result = iterable;
      if (!iterable) return result;
      if (!objectTypes[typeof iterable]) return result;
      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
        for (index in iterable) {
          if (callback(iterable[index], index, collection) === false) return result;
        }
      return result
    };

    /**
     * This method is like `_.forIn` except that it iterates over elements
     * of a `collection` in the opposite order.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns `object`.
     * @example
     *
     * function Shape() {
     *   this.x = 0;
     *   this.y = 0;
     * }
     *
     * Shape.prototype.move = function(x, y) {
     *   this.x += x;
     *   this.y += y;
     * };
     *
     * _.forInRight(new Shape, function(value, key) {
     *   console.log(key);
     * });
     * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
     */
    function forInRight(object, callback, thisArg) {
      var pairs = [];

      forIn(object, function(value, key) {
        pairs.push(key, value);
      });

      var length = pairs.length;
      callback = baseCreateCallback(callback, thisArg, 3);
      while (length--) {
        if (callback(pairs[length--], pairs[length], object) === false) {
          break;
        }
      }
      return object;
    }

    /**
     * Iterates over own enumerable properties of an object, executing the callback
     * for each property. The callback is bound to `thisArg` and invoked with three
     * arguments; (value, key, object). Callbacks may exit iteration early by
     * explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @type Function
     * @category Objects
     * @param {Object} object The object to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns `object`.
     * @example
     *
     * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
     *   console.log(key);
     * });
     * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
     */
    var forOwn = function(collection, callback, thisArg) {
      var index, iterable = collection, result = iterable;
      if (!iterable) return result;
      if (!objectTypes[typeof iterable]) return result;
      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
        var ownIndex = -1,
            ownProps = objectTypes[typeof iterable] && keys(iterable),
            length = ownProps ? ownProps.length : 0;

        while (++ownIndex < length) {
          index = ownProps[ownIndex];
          if (callback(iterable[index], index, collection) === false) return result;
        }
      return result
    };

    /**
     * This method is like `_.forOwn` except that it iterates over elements
     * of a `collection` in the opposite order.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns `object`.
     * @example
     *
     * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
     *   console.log(key);
     * });
     * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
     */
    function forOwnRight(object, callback, thisArg) {
      var props = keys(object),
          length = props.length;

      callback = baseCreateCallback(callback, thisArg, 3);
      while (length--) {
        var key = props[length];
        if (callback(object[key], key, object) === false) {
          break;
        }
      }
      return object;
    }

    /**
     * Creates a sorted array of property names of all enumerable properties,
     * own and inherited, of `object` that have function values.
     *
     * @static
     * @memberOf _
     * @alias methods
     * @category Objects
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns an array of property names that have function values.
     * @example
     *
     * _.functions(_);
     * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
     */
    function functions(object) {
      var result = [];
      forIn(object, function(value, key) {
        if (isFunction(value)) {
          result.push(key);
        }
      });
      return result.sort();
    }

    /**
     * Checks if the specified property name exists as a direct property of `object`,
     * instead of an inherited property.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to inspect.
     * @param {string} key The name of the property to check.
     * @returns {boolean} Returns `true` if key is a direct property, else `false`.
     * @example
     *
     * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
     * // => true
     */
    function has(object, key) {
      return object ? hasOwnProperty.call(object, key) : false;
    }

    /**
     * Creates an object composed of the inverted keys and values of the given object.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to invert.
     * @returns {Object} Returns the created inverted object.
     * @example
     *
     * _.invert({ 'first': 'fred', 'second': 'barney' });
     * // => { 'fred': 'first', 'barney': 'second' }
     */
    function invert(object) {
      var index = -1,
          props = keys(object),
          length = props.length,
          result = {};

      while (++index < length) {
        var key = props[index];
        result[object[key]] = key;
      }
      return result;
    }

    /**
     * Checks if `value` is a boolean value.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
     * @example
     *
     * _.isBoolean(null);
     * // => false
     */
    function isBoolean(value) {
      return value === true || value === false ||
        value && typeof value == 'object' && toString.call(value) == boolClass || false;
    }

    /**
     * Checks if `value` is a date.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a date, else `false`.
     * @example
     *
     * _.isDate(new Date);
     * // => true
     */
    function isDate(value) {
      return value && typeof value == 'object' && toString.call(value) == dateClass || false;
    }

    /**
     * Checks if `value` is a DOM element.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
     * @example
     *
     * _.isElement(document.body);
     * // => true
     */
    function isElement(value) {
      return value && value.nodeType === 1 || false;
    }

    /**
     * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
     * length of `0` and objects with no own enumerable properties are considered
     * "empty".
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Array|Object|string} value The value to inspect.
     * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
     * @example
     *
     * _.isEmpty([1, 2, 3]);
     * // => false
     *
     * _.isEmpty({});
     * // => true
     *
     * _.isEmpty('');
     * // => true
     */
    function isEmpty(value) {
      var result = true;
      if (!value) {
        return result;
      }
      var className = toString.call(value),
          length = value.length;

      if ((className == arrayClass || className == stringClass || className == argsClass ) ||
          (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
        return !length;
      }
      forOwn(value, function() {
        return (result = false);
      });
      return result;
    }

    /**
     * Performs a deep comparison between two values to determine if they are
     * equivalent to each other. If a callback is provided it will be executed
     * to compare values. If the callback returns `undefined` comparisons will
     * be handled by the method instead. The callback is bound to `thisArg` and
     * invoked with two arguments; (a, b).
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} a The value to compare.
     * @param {*} b The other value to compare.
     * @param {Function} [callback] The function to customize comparing values.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     * @example
     *
     * var object = { 'name': 'fred' };
     * var copy = { 'name': 'fred' };
     *
     * object == copy;
     * // => false
     *
     * _.isEqual(object, copy);
     * // => true
     *
     * var words = ['hello', 'goodbye'];
     * var otherWords = ['hi', 'goodbye'];
     *
     * _.isEqual(words, otherWords, function(a, b) {
     *   var reGreet = /^(?:hello|hi)$/i,
     *       aGreet = _.isString(a) && reGreet.test(a),
     *       bGreet = _.isString(b) && reGreet.test(b);
     *
     *   return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
     * });
     * // => true
     */
    function isEqual(a, b, callback, thisArg) {
      return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
    }

    /**
     * Checks if `value` is, or can be coerced to, a finite number.
     *
     * Note: This is not the same as native `isFinite` which will return true for
     * booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is finite, else `false`.
     * @example
     *
     * _.isFinite(-101);
     * // => true
     *
     * _.isFinite('10');
     * // => true
     *
     * _.isFinite(true);
     * // => false
     *
     * _.isFinite('');
     * // => false
     *
     * _.isFinite(Infinity);
     * // => false
     */
    function isFinite(value) {
      return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
    }

    /**
     * Checks if `value` is a function.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
     * @example
     *
     * _.isFunction(_);
     * // => true
     */
    function isFunction(value) {
      return typeof value == 'function';
    }

    /**
     * Checks if `value` is the language type of Object.
     * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
     * @example
     *
     * _.isObject({});
     * // => true
     *
     * _.isObject([1, 2, 3]);
     * // => true
     *
     * _.isObject(1);
     * // => false
     */
    function isObject(value) {
      // check if the value is the ECMAScript language type of Object
      // http://es5.github.io/#x8
      // and avoid a V8 bug
      // http://code.google.com/p/v8/issues/detail?id=2291
      return !!(value && objectTypes[typeof value]);
    }

    /**
     * Checks if `value` is `NaN`.
     *
     * Note: This is not the same as native `isNaN` which will return `true` for
     * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
     * @example
     *
     * _.isNaN(NaN);
     * // => true
     *
     * _.isNaN(new Number(NaN));
     * // => true
     *
     * isNaN(undefined);
     * // => true
     *
     * _.isNaN(undefined);
     * // => false
     */
    function isNaN(value) {
      // `NaN` as a primitive is the only value that is not equal to itself
      // (perform the [[Class]] check first to avoid errors with some host objects in IE)
      return isNumber(value) && value != +value;
    }

    /**
     * Checks if `value` is `null`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
     * @example
     *
     * _.isNull(null);
     * // => true
     *
     * _.isNull(undefined);
     * // => false
     */
    function isNull(value) {
      return value === null;
    }

    /**
     * Checks if `value` is a number.
     *
     * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a number, else `false`.
     * @example
     *
     * _.isNumber(8.4 * 5);
     * // => true
     */
    function isNumber(value) {
      return typeof value == 'number' ||
        value && typeof value == 'object' && toString.call(value) == numberClass || false;
    }

    /**
     * Checks if `value` is an object created by the `Object` constructor.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
     * @example
     *
     * function Shape() {
     *   this.x = 0;
     *   this.y = 0;
     * }
     *
     * _.isPlainObject(new Shape);
     * // => false
     *
     * _.isPlainObject([1, 2, 3]);
     * // => false
     *
     * _.isPlainObject({ 'x': 0, 'y': 0 });
     * // => true
     */
    var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
      if (!(value && toString.call(value) == objectClass)) {
        return false;
      }
      var valueOf = value.valueOf,
          objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);

      return objProto
        ? (value == objProto || getPrototypeOf(value) == objProto)
        : shimIsPlainObject(value);
    };

    /**
     * Checks if `value` is a regular expression.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
     * @example
     *
     * _.isRegExp(/fred/);
     * // => true
     */
    function isRegExp(value) {
      return value && typeof value == 'object' && toString.call(value) == regexpClass || false;
    }

    /**
     * Checks if `value` is a string.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is a string, else `false`.
     * @example
     *
     * _.isString('fred');
     * // => true
     */
    function isString(value) {
      return typeof value == 'string' ||
        value && typeof value == 'object' && toString.call(value) == stringClass || false;
    }

    /**
     * Checks if `value` is `undefined`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
     * @example
     *
     * _.isUndefined(void 0);
     * // => true
     */
    function isUndefined(value) {
      return typeof value == 'undefined';
    }

    /**
     * Creates an object with the same keys as `object` and values generated by
     * running each own enumerable property of `object` through the callback.
     * The callback is bound to `thisArg` and invoked with three arguments;
     * (value, key, object).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a new object with values of the results of each `callback` execution.
     * @example
     *
     * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
     * // => { 'a': 3, 'b': 6, 'c': 9 }
     *
     * var characters = {
     *   'fred': { 'name': 'fred', 'age': 40 },
     *   'pebbles': { 'name': 'pebbles', 'age': 1 }
     * };
     *
     * // using "_.pluck" callback shorthand
     * _.mapValues(characters, 'age');
     * // => { 'fred': 40, 'pebbles': 1 }
     */
    function mapValues(object, callback, thisArg) {
      var result = {};
      callback = lodash.createCallback(callback, thisArg, 3);

      forOwn(object, function(value, key, object) {
        result[key] = callback(value, key, object);
      });
      return result;
    }

    /**
     * Recursively merges own enumerable properties of the source object(s), that
     * don't resolve to `undefined` into the destination object. Subsequent sources
     * will overwrite property assignments of previous sources. If a callback is
     * provided it will be executed to produce the merged values of the destination
     * and source properties. If the callback returns `undefined` merging will
     * be handled by the method instead. The callback is bound to `thisArg` and
     * invoked with two arguments; (objectValue, sourceValue).
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The destination object.
     * @param {...Object} [source] The source objects.
     * @param {Function} [callback] The function to customize merging properties.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns the destination object.
     * @example
     *
     * var names = {
     *   'characters': [
     *     { 'name': 'barney' },
     *     { 'name': 'fred' }
     *   ]
     * };
     *
     * var ages = {
     *   'characters': [
     *     { 'age': 36 },
     *     { 'age': 40 }
     *   ]
     * };
     *
     * _.merge(names, ages);
     * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
     *
     * var food = {
     *   'fruits': ['apple'],
     *   'vegetables': ['beet']
     * };
     *
     * var otherFood = {
     *   'fruits': ['banana'],
     *   'vegetables': ['carrot']
     * };
     *
     * _.merge(food, otherFood, function(a, b) {
     *   return _.isArray(a) ? a.concat(b) : undefined;
     * });
     * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
     */
    function merge(object) {
      var args = arguments,
          length = 2;

      if (!isObject(object)) {
        return object;
      }
      // allows working with `_.reduce` and `_.reduceRight` without using
      // their `index` and `collection` arguments
      if (typeof args[2] != 'number') {
        length = args.length;
      }
      if (length > 3 && typeof args[length - 2] == 'function') {
        var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
      } else if (length > 2 && typeof args[length - 1] == 'function') {
        callback = args[--length];
      }
      var sources = slice(arguments, 1, length),
          index = -1,
          stackA = getArray(),
          stackB = getArray();

      while (++index < length) {
        baseMerge(object, sources[index], callback, stackA, stackB);
      }
      releaseArray(stackA);
      releaseArray(stackB);
      return object;
    }

    /**
     * Creates a shallow clone of `object` excluding the specified properties.
     * Property names may be specified as individual arguments or as arrays of
     * property names. If a callback is provided it will be executed for each
     * property of `object` omitting the properties the callback returns truey
     * for. The callback is bound to `thisArg` and invoked with three arguments;
     * (value, key, object).
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The source object.
     * @param {Function|...string|string[]} [callback] The properties to omit or the
     *  function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns an object without the omitted properties.
     * @example
     *
     * _.omit({ 'name': 'fred', 'age': 40 }, 'age');
     * // => { 'name': 'fred' }
     *
     * _.omit({ 'name': 'fred', 'age': 40 }, function(value) {
     *   return typeof value == 'number';
     * });
     * // => { 'name': 'fred' }
     */
    function omit(object, callback, thisArg) {
      var result = {};
      if (typeof callback != 'function') {
        var props = [];
        forIn(object, function(value, key) {
          props.push(key);
        });
        props = baseDifference(props, baseFlatten(arguments, true, false, 1));

        var index = -1,
            length = props.length;

        while (++index < length) {
          var key = props[index];
          result[key] = object[key];
        }
      } else {
        callback = lodash.createCallback(callback, thisArg, 3);
        forIn(object, function(value, key, object) {
          if (!callback(value, key, object)) {
            result[key] = value;
          }
        });
      }
      return result;
    }

    /**
     * Creates a two dimensional array of an object's key-value pairs,
     * i.e. `[[key1, value1], [key2, value2]]`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns new array of key-value pairs.
     * @example
     *
     * _.pairs({ 'barney': 36, 'fred': 40 });
     * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
     */
    function pairs(object) {
      var index = -1,
          props = keys(object),
          length = props.length,
          result = Array(length);

      while (++index < length) {
        var key = props[index];
        result[index] = [key, object[key]];
      }
      return result;
    }

    /**
     * Creates a shallow clone of `object` composed of the specified properties.
     * Property names may be specified as individual arguments or as arrays of
     * property names. If a callback is provided it will be executed for each
     * property of `object` picking the properties the callback returns truey
     * for. The callback is bound to `thisArg` and invoked with three arguments;
     * (value, key, object).
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The source object.
     * @param {Function|...string|string[]} [callback] The function called per
     *  iteration or property names to pick, specified as individual property
     *  names or arrays of property names.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns an object composed of the picked properties.
     * @example
     *
     * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
     * // => { 'name': 'fred' }
     *
     * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
     *   return key.charAt(0) != '_';
     * });
     * // => { 'name': 'fred' }
     */
    function pick(object, callback, thisArg) {
      var result = {};
      if (typeof callback != 'function') {
        var index = -1,
            props = baseFlatten(arguments, true, false, 1),
            length = isObject(object) ? props.length : 0;

        while (++index < length) {
          var key = props[index];
          if (key in object) {
            result[key] = object[key];
          }
        }
      } else {
        callback = lodash.createCallback(callback, thisArg, 3);
        forIn(object, function(value, key, object) {
          if (callback(value, key, object)) {
            result[key] = value;
          }
        });
      }
      return result;
    }

    /**
     * An alternative to `_.reduce` this method transforms `object` to a new
     * `accumulator` object which is the result of running each of its own
     * enumerable properties through a callback, with each callback execution
     * potentially mutating the `accumulator` object. The callback is bound to
     * `thisArg` and invoked with four arguments; (accumulator, value, key, object).
     * Callbacks may exit iteration early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Array|Object} object The object to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [accumulator] The custom accumulator value.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the accumulated value.
     * @example
     *
     * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
     *   num *= num;
     *   if (num % 2) {
     *     return result.push(num) < 3;
     *   }
     * });
     * // => [1, 9, 25]
     *
     * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
     *   result[key] = num * 3;
     * });
     * // => { 'a': 3, 'b': 6, 'c': 9 }
     */
    function transform(object, callback, accumulator, thisArg) {
      var isArr = isArray(object);
      if (accumulator == null) {
        if (isArr) {
          accumulator = [];
        } else {
          var ctor = object && object.constructor,
              proto = ctor && ctor.prototype;

          accumulator = baseCreate(proto);
        }
      }
      if (callback) {
        callback = lodash.createCallback(callback, thisArg, 4);
        (isArr ? forEach : forOwn)(object, function(value, index, object) {
          return callback(accumulator, value, index, object);
        });
      }
      return accumulator;
    }

    /**
     * Creates an array composed of the own enumerable property values of `object`.
     *
     * @static
     * @memberOf _
     * @category Objects
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns an array of property values.
     * @example
     *
     * _.values({ 'one': 1, 'two': 2, 'three': 3 });
     * // => [1, 2, 3] (property order is not guaranteed across environments)
     */
    function values(object) {
      var index = -1,
          props = keys(object),
          length = props.length,
          result = Array(length);

      while (++index < length) {
        result[index] = object[props[index]];
      }
      return result;
    }

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

    /**
     * Creates an array of elements from the specified indexes, or keys, of the
     * `collection`. Indexes may be specified as individual arguments or as arrays
     * of indexes.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
     *   to retrieve, specified as individual indexes or arrays of indexes.
     * @returns {Array} Returns a new array of elements corresponding to the
     *  provided indexes.
     * @example
     *
     * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
     * // => ['a', 'c', 'e']
     *
     * _.at(['fred', 'barney', 'pebbles'], 0, 2);
     * // => ['fred', 'pebbles']
     */
    function at(collection) {
      var args = arguments,
          index = -1,
          props = baseFlatten(args, true, false, 1),
          length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
          result = Array(length);

      while(++index < length) {
        result[index] = collection[props[index]];
      }
      return result;
    }

    /**
     * Checks if a given value is present in a collection using strict equality
     * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
     * offset from the end of the collection.
     *
     * @static
     * @memberOf _
     * @alias include
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {*} target The value to check for.
     * @param {number} [fromIndex=0] The index to search from.
     * @returns {boolean} Returns `true` if the `target` element is found, else `false`.
     * @example
     *
     * _.contains([1, 2, 3], 1);
     * // => true
     *
     * _.contains([1, 2, 3], 1, 2);
     * // => false
     *
     * _.contains({ 'name': 'fred', 'age': 40 }, 'fred');
     * // => true
     *
     * _.contains('pebbles', 'eb');
     * // => true
     */
    function contains(collection, target, fromIndex) {
      var index = -1,
          indexOf = getIndexOf(),
          length = collection ? collection.length : 0,
          result = false;

      fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
      if (isArray(collection)) {
        result = indexOf(collection, target, fromIndex) > -1;
      } else if (typeof length == 'number') {
        result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
      } else {
        forOwn(collection, function(value) {
          if (++index >= fromIndex) {
            return !(result = value === target);
          }
        });
      }
      return result;
    }

    /**
     * Creates an object composed of keys generated from the results of running
     * each element of `collection` through the callback. The corresponding value
     * of each key is the number of times the key was returned by the callback.
     * The callback is bound to `thisArg` and invoked with three arguments;
     * (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
     * // => { '4': 1, '6': 2 }
     *
     * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
     * // => { '4': 1, '6': 2 }
     *
     * _.countBy(['one', 'two', 'three'], 'length');
     * // => { '3': 2, '5': 1 }
     */
    var countBy = createAggregator(function(result, value, key) {
      (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
    });

    /**
     * Checks if the given callback returns truey value for **all** elements of
     * a collection. The callback is bound to `thisArg` and invoked with three
     * arguments; (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias all
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {boolean} Returns `true` if all elements passed the callback check,
     *  else `false`.
     * @example
     *
     * _.every([true, 1, null, 'yes']);
     * // => false
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.every(characters, 'age');
     * // => true
     *
     * // using "_.where" callback shorthand
     * _.every(characters, { 'age': 36 });
     * // => false
     */
    function every(collection, callback, thisArg) {
      var result = true;
      callback = lodash.createCallback(callback, thisArg, 3);

      var index = -1,
          length = collection ? collection.length : 0;

      if (typeof length == 'number') {
        while (++index < length) {
          if (!(result = !!callback(collection[index], index, collection))) {
            break;
          }
        }
      } else {
        forOwn(collection, function(value, index, collection) {
          return (result = !!callback(value, index, collection));
        });
      }
      return result;
    }

    /**
     * Iterates over elements of a collection, returning an array of all elements
     * the callback returns truey for. The callback is bound to `thisArg` and
     * invoked with three arguments; (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias select
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a new array of elements that passed the callback check.
     * @example
     *
     * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
     * // => [2, 4, 6]
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36, 'blocked': false },
     *   { 'name': 'fred',   'age': 40, 'blocked': true }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.filter(characters, 'blocked');
     * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
     *
     * // using "_.where" callback shorthand
     * _.filter(characters, { 'age': 36 });
     * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
     */
    function filter(collection, callback, thisArg) {
      var result = [];
      callback = lodash.createCallback(callback, thisArg, 3);

      var index = -1,
          length = collection ? collection.length : 0;

      if (typeof length == 'number') {
        while (++index < length) {
          var value = collection[index];
          if (callback(value, index, collection)) {
            result.push(value);
          }
        }
      } else {
        forOwn(collection, function(value, index, collection) {
          if (callback(value, index, collection)) {
            result.push(value);
          }
        });
      }
      return result;
    }

    /**
     * Iterates over elements of a collection, returning the first element that
     * the callback returns truey for. The callback is bound to `thisArg` and
     * invoked with three arguments; (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias detect, findWhere
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the found element, else `undefined`.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney',  'age': 36, 'blocked': false },
     *   { 'name': 'fred',    'age': 40, 'blocked': true },
     *   { 'name': 'pebbles', 'age': 1,  'blocked': false }
     * ];
     *
     * _.find(characters, function(chr) {
     *   return chr.age < 40;
     * });
     * // => { 'name': 'barney', 'age': 36, 'blocked': false }
     *
     * // using "_.where" callback shorthand
     * _.find(characters, { 'age': 1 });
     * // =>  { 'name': 'pebbles', 'age': 1, 'blocked': false }
     *
     * // using "_.pluck" callback shorthand
     * _.find(characters, 'blocked');
     * // => { 'name': 'fred', 'age': 40, 'blocked': true }
     */
    function find(collection, callback, thisArg) {
      callback = lodash.createCallback(callback, thisArg, 3);

      var index = -1,
          length = collection ? collection.length : 0;

      if (typeof length == 'number') {
        while (++index < length) {
          var value = collection[index];
          if (callback(value, index, collection)) {
            return value;
          }
        }
      } else {
        var result;
        forOwn(collection, function(value, index, collection) {
          if (callback(value, index, collection)) {
            result = value;
            return false;
          }
        });
        return result;
      }
    }

    /**
     * This method is like `_.find` except that it iterates over elements
     * of a `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the found element, else `undefined`.
     * @example
     *
     * _.findLast([1, 2, 3, 4], function(num) {
     *   return num % 2 == 1;
     * });
     * // => 3
     */
    function findLast(collection, callback, thisArg) {
      var result;
      callback = lodash.createCallback(callback, thisArg, 3);
      forEachRight(collection, function(value, index, collection) {
        if (callback(value, index, collection)) {
          result = value;
          return false;
        }
      });
      return result;
    }

    /**
     * Iterates over elements of a collection, executing the callback for each
     * element. The callback is bound to `thisArg` and invoked with three arguments;
     * (value, index|key, collection). Callbacks may exit iteration early by
     * explicitly returning `false`.
     *
     * Note: As with other "Collections" methods, objects with a `length` property
     * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
     * may be used for object iteration.
     *
     * @static
     * @memberOf _
     * @alias each
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array|Object|string} Returns `collection`.
     * @example
     *
     * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
     * // => logs each number and returns '1,2,3'
     *
     * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
     * // => logs each number and returns the object (property order is not guaranteed across environments)
     */
    function forEach(collection, callback, thisArg) {
      var index = -1,
          length = collection ? collection.length : 0;

      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
      if (typeof length == 'number') {
        while (++index < length) {
          if (callback(collection[index], index, collection) === false) {
            break;
          }
        }
      } else {
        forOwn(collection, callback);
      }
      return collection;
    }

    /**
     * This method is like `_.forEach` except that it iterates over elements
     * of a `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @alias eachRight
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array|Object|string} Returns `collection`.
     * @example
     *
     * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
     * // => logs each number from right to left and returns '3,2,1'
     */
    function forEachRight(collection, callback, thisArg) {
      var length = collection ? collection.length : 0;
      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
      if (typeof length == 'number') {
        while (length--) {
          if (callback(collection[length], length, collection) === false) {
            break;
          }
        }
      } else {
        var props = keys(collection);
        length = props.length;
        forOwn(collection, function(value, key, collection) {
          key = props ? props[--length] : --length;
          return callback(collection[key], key, collection);
        });
      }
      return collection;
    }

    /**
     * Creates an object composed of keys generated from the results of running
     * each element of a collection through the callback. The corresponding value
     * of each key is an array of the elements responsible for generating the key.
     * The callback is bound to `thisArg` and invoked with three arguments;
     * (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
     * // => { '4': [4.2], '6': [6.1, 6.4] }
     *
     * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
     * // => { '4': [4.2], '6': [6.1, 6.4] }
     *
     * // using "_.pluck" callback shorthand
     * _.groupBy(['one', 'two', 'three'], 'length');
     * // => { '3': ['one', 'two'], '5': ['three'] }
     */
    var groupBy = createAggregator(function(result, value, key) {
      (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
    });

    /**
     * Creates an object composed of keys generated from the results of running
     * each element of the collection through the given callback. The corresponding
     * value of each key is the last element responsible for generating the key.
     * The callback is bound to `thisArg` and invoked with three arguments;
     * (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * var keys = [
     *   { 'dir': 'left', 'code': 97 },
     *   { 'dir': 'right', 'code': 100 }
     * ];
     *
     * _.indexBy(keys, 'dir');
     * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
     *
     * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
     *
     * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String);
     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
     */
    var indexBy = createAggregator(function(result, value, key) {
      result[key] = value;
    });

    /**
     * Invokes the method named by `methodName` on each element in the `collection`
     * returning an array of the results of each invoked method. Additional arguments
     * will be provided to each invoked method. If `methodName` is a function it
     * will be invoked for, and `this` bound to, each element in the `collection`.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|string} methodName The name of the method to invoke or
     *  the function invoked per iteration.
     * @param {...*} [arg] Arguments to invoke the method with.
     * @returns {Array} Returns a new array of the results of each invoked method.
     * @example
     *
     * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
     * // => [[1, 5, 7], [1, 2, 3]]
     *
     * _.invoke([123, 456], String.prototype.split, '');
     * // => [['1', '2', '3'], ['4', '5', '6']]
     */
    function invoke(collection, methodName) {
      var args = slice(arguments, 2),
          index = -1,
          isFunc = typeof methodName == 'function',
          length = collection ? collection.length : 0,
          result = Array(typeof length == 'number' ? length : 0);

      forEach(collection, function(value) {
        result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
      });
      return result;
    }

    /**
     * Creates an array of values by running each element in the collection
     * through the callback. The callback is bound to `thisArg` and invoked with
     * three arguments; (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias collect
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a new array of the results of each `callback` execution.
     * @example
     *
     * _.map([1, 2, 3], function(num) { return num * 3; });
     * // => [3, 6, 9]
     *
     * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
     * // => [3, 6, 9] (property order is not guaranteed across environments)
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.map(characters, 'name');
     * // => ['barney', 'fred']
     */
    function map(collection, callback, thisArg) {
      var index = -1,
          length = collection ? collection.length : 0;

      callback = lodash.createCallback(callback, thisArg, 3);
      if (typeof length == 'number') {
        var result = Array(length);
        while (++index < length) {
          result[index] = callback(collection[index], index, collection);
        }
      } else {
        result = [];
        forOwn(collection, function(value, key, collection) {
          result[++index] = callback(value, key, collection);
        });
      }
      return result;
    }

    /**
     * Retrieves the maximum value of a collection. If the collection is empty or
     * falsey `-Infinity` is returned. If a callback is provided it will be executed
     * for each value in the collection to generate the criterion by which the value
     * is ranked. The callback is bound to `thisArg` and invoked with three
     * arguments; (value, index, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the maximum value.
     * @example
     *
     * _.max([4, 2, 8, 6]);
     * // => 8
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * _.max(characters, function(chr) { return chr.age; });
     * // => { 'name': 'fred', 'age': 40 };
     *
     * // using "_.pluck" callback shorthand
     * _.max(characters, 'age');
     * // => { 'name': 'fred', 'age': 40 };
     */
    function max(collection, callback, thisArg) {
      var computed = -Infinity,
          result = computed;

      // allows working with functions like `_.map` without using
      // their `index` argument as a callback
      if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
        callback = null;
      }
      if (callback == null && isArray(collection)) {
        var index = -1,
            length = collection.length;

        while (++index < length) {
          var value = collection[index];
          if (value > result) {
            result = value;
          }
        }
      } else {
        callback = (callback == null && isString(collection))
          ? charAtCallback
          : lodash.createCallback(callback, thisArg, 3);

        forEach(collection, function(value, index, collection) {
          var current = callback(value, index, collection);
          if (current > computed) {
            computed = current;
            result = value;
          }
        });
      }
      return result;
    }

    /**
     * Retrieves the minimum value of a collection. If the collection is empty or
     * falsey `Infinity` is returned. If a callback is provided it will be executed
     * for each value in the collection to generate the criterion by which the value
     * is ranked. The callback is bound to `thisArg` and invoked with three
     * arguments; (value, index, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the minimum value.
     * @example
     *
     * _.min([4, 2, 8, 6]);
     * // => 2
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * _.min(characters, function(chr) { return chr.age; });
     * // => { 'name': 'barney', 'age': 36 };
     *
     * // using "_.pluck" callback shorthand
     * _.min(characters, 'age');
     * // => { 'name': 'barney', 'age': 36 };
     */
    function min(collection, callback, thisArg) {
      var computed = Infinity,
          result = computed;

      // allows working with functions like `_.map` without using
      // their `index` argument as a callback
      if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
        callback = null;
      }
      if (callback == null && isArray(collection)) {
        var index = -1,
            length = collection.length;

        while (++index < length) {
          var value = collection[index];
          if (value < result) {
            result = value;
          }
        }
      } else {
        callback = (callback == null && isString(collection))
          ? charAtCallback
          : lodash.createCallback(callback, thisArg, 3);

        forEach(collection, function(value, index, collection) {
          var current = callback(value, index, collection);
          if (current < computed) {
            computed = current;
            result = value;
          }
        });
      }
      return result;
    }

    /**
     * Retrieves the value of a specified property from all elements in the collection.
     *
     * @static
     * @memberOf _
     * @type Function
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {string} property The name of the property to pluck.
     * @returns {Array} Returns a new array of property values.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * _.pluck(characters, 'name');
     * // => ['barney', 'fred']
     */
    var pluck = map;

    /**
     * Reduces a collection to a value which is the accumulated result of running
     * each element in the collection through the callback, where each successive
     * callback execution consumes the return value of the previous execution. If
     * `accumulator` is not provided the first element of the collection will be
     * used as the initial `accumulator` value. The callback is bound to `thisArg`
     * and invoked with four arguments; (accumulator, value, index|key, collection).
     *
     * @static
     * @memberOf _
     * @alias foldl, inject
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [accumulator] Initial value of the accumulator.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the accumulated value.
     * @example
     *
     * var sum = _.reduce([1, 2, 3], function(sum, num) {
     *   return sum + num;
     * });
     * // => 6
     *
     * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
     *   result[key] = num * 3;
     *   return result;
     * }, {});
     * // => { 'a': 3, 'b': 6, 'c': 9 }
     */
    function reduce(collection, callback, accumulator, thisArg) {
      if (!collection) return accumulator;
      var noaccum = arguments.length < 3;
      callback = lodash.createCallback(callback, thisArg, 4);

      var index = -1,
          length = collection.length;

      if (typeof length == 'number') {
        if (noaccum) {
          accumulator = collection[++index];
        }
        while (++index < length) {
          accumulator = callback(accumulator, collection[index], index, collection);
        }
      } else {
        forOwn(collection, function(value, index, collection) {
          accumulator = noaccum
            ? (noaccum = false, value)
            : callback(accumulator, value, index, collection)
        });
      }
      return accumulator;
    }

    /**
     * This method is like `_.reduce` except that it iterates over elements
     * of a `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @alias foldr
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function} [callback=identity] The function called per iteration.
     * @param {*} [accumulator] Initial value of the accumulator.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the accumulated value.
     * @example
     *
     * var list = [[0, 1], [2, 3], [4, 5]];
     * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
     * // => [4, 5, 2, 3, 0, 1]
     */
    function reduceRight(collection, callback, accumulator, thisArg) {
      var noaccum = arguments.length < 3;
      callback = lodash.createCallback(callback, thisArg, 4);
      forEachRight(collection, function(value, index, collection) {
        accumulator = noaccum
          ? (noaccum = false, value)
          : callback(accumulator, value, index, collection);
      });
      return accumulator;
    }

    /**
     * The opposite of `_.filter` this method returns the elements of a
     * collection that the callback does **not** return truey for.
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a new array of elements that failed the callback check.
     * @example
     *
     * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
     * // => [1, 3, 5]
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36, 'blocked': false },
     *   { 'name': 'fred',   'age': 40, 'blocked': true }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.reject(characters, 'blocked');
     * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
     *
     * // using "_.where" callback shorthand
     * _.reject(characters, { 'age': 36 });
     * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
     */
    function reject(collection, callback, thisArg) {
      callback = lodash.createCallback(callback, thisArg, 3);
      return filter(collection, function(value, index, collection) {
        return !callback(value, index, collection);
      });
    }

    /**
     * Retrieves a random element or `n` random elements from a collection.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to sample.
     * @param {number} [n] The number of elements to sample.
     * @param- {Object} [guard] Allows working with functions like `_.map`
     *  without using their `index` arguments as `n`.
     * @returns {Array} Returns the random sample(s) of `collection`.
     * @example
     *
     * _.sample([1, 2, 3, 4]);
     * // => 2
     *
     * _.sample([1, 2, 3, 4], 2);
     * // => [3, 1]
     */
    function sample(collection, n, guard) {
      if (collection && typeof collection.length != 'number') {
        collection = values(collection);
      }
      if (n == null || guard) {
        return collection ? collection[baseRandom(0, collection.length - 1)] : undefined;
      }
      var result = shuffle(collection);
      result.length = nativeMin(nativeMax(0, n), result.length);
      return result;
    }

    /**
     * Creates an array of shuffled values, using a version of the Fisher-Yates
     * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to shuffle.
     * @returns {Array} Returns a new shuffled collection.
     * @example
     *
     * _.shuffle([1, 2, 3, 4, 5, 6]);
     * // => [4, 1, 6, 3, 5, 2]
     */
    function shuffle(collection) {
      var index = -1,
          length = collection ? collection.length : 0,
          result = Array(typeof length == 'number' ? length : 0);

      forEach(collection, function(value) {
        var rand = baseRandom(0, ++index);
        result[index] = result[rand];
        result[rand] = value;
      });
      return result;
    }

    /**
     * Gets the size of the `collection` by returning `collection.length` for arrays
     * and array-like objects or the number of own enumerable properties for objects.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to inspect.
     * @returns {number} Returns `collection.length` or number of own enumerable properties.
     * @example
     *
     * _.size([1, 2]);
     * // => 2
     *
     * _.size({ 'one': 1, 'two': 2, 'three': 3 });
     * // => 3
     *
     * _.size('pebbles');
     * // => 7
     */
    function size(collection) {
      var length = collection ? collection.length : 0;
      return typeof length == 'number' ? length : keys(collection).length;
    }

    /**
     * Checks if the callback returns a truey value for **any** element of a
     * collection. The function returns as soon as it finds a passing value and
     * does not iterate over the entire collection. The callback is bound to
     * `thisArg` and invoked with three arguments; (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias any
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {boolean} Returns `true` if any element passed the callback check,
     *  else `false`.
     * @example
     *
     * _.some([null, 0, 'yes', false], Boolean);
     * // => true
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36, 'blocked': false },
     *   { 'name': 'fred',   'age': 40, 'blocked': true }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.some(characters, 'blocked');
     * // => true
     *
     * // using "_.where" callback shorthand
     * _.some(characters, { 'age': 1 });
     * // => false
     */
    function some(collection, callback, thisArg) {
      var result;
      callback = lodash.createCallback(callback, thisArg, 3);

      var index = -1,
          length = collection ? collection.length : 0;

      if (typeof length == 'number') {
        while (++index < length) {
          if ((result = callback(collection[index], index, collection))) {
            break;
          }
        }
      } else {
        forOwn(collection, function(value, index, collection) {
          return !(result = callback(value, index, collection));
        });
      }
      return !!result;
    }

    /**
     * Creates an array of elements, sorted in ascending order by the results of
     * running each element in a collection through the callback. This method
     * performs a stable sort, that is, it will preserve the original sort order
     * of equal elements. The callback is bound to `thisArg` and invoked with
     * three arguments; (value, index|key, collection).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an array of property names is provided for `callback` the collection
     * will be sorted by each property value.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Array|Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a new array of sorted elements.
     * @example
     *
     * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
     * // => [3, 1, 2]
     *
     * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
     * // => [3, 1, 2]
     *
     * var characters = [
     *   { 'name': 'barney',  'age': 36 },
     *   { 'name': 'fred',    'age': 40 },
     *   { 'name': 'barney',  'age': 26 },
     *   { 'name': 'fred',    'age': 30 }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.map(_.sortBy(characters, 'age'), _.values);
     * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
     *
     * // sorting by multiple properties
     * _.map(_.sortBy(characters, ['name', 'age']), _.values);
     * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
     */
    function sortBy(collection, callback, thisArg) {
      var index = -1,
          isArr = isArray(callback),
          length = collection ? collection.length : 0,
          result = Array(typeof length == 'number' ? length : 0);

      if (!isArr) {
        callback = lodash.createCallback(callback, thisArg, 3);
      }
      forEach(collection, function(value, key, collection) {
        var object = result[++index] = getObject();
        if (isArr) {
          object.criteria = map(callback, function(key) { return value[key]; });
        } else {
          (object.criteria = getArray())[0] = callback(value, key, collection);
        }
        object.index = index;
        object.value = value;
      });

      length = result.length;
      result.sort(compareAscending);
      while (length--) {
        var object = result[length];
        result[length] = object.value;
        if (!isArr) {
          releaseArray(object.criteria);
        }
        releaseObject(object);
      }
      return result;
    }

    /**
     * Converts the `collection` to an array.
     *
     * @static
     * @memberOf _
     * @category Collections
     * @param {Array|Object|string} collection The collection to convert.
     * @returns {Array} Returns the new converted array.
     * @example
     *
     * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
     * // => [2, 3, 4]
     */
    function toArray(collection) {
      if (collection && typeof collection.length == 'number') {
        return slice(collection);
      }
      return values(collection);
    }

    /**
     * Performs a deep comparison of each element in a `collection` to the given
     * `properties` object, returning an array of all elements that have equivalent
     * property values.
     *
     * @static
     * @memberOf _
     * @type Function
     * @category Collections
     * @param {Array|Object|string} collection The collection to iterate over.
     * @param {Object} props The object of property values to filter by.
     * @returns {Array} Returns a new array of elements that have the given properties.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
     *   { 'name': 'fred',   'age': 40, 'pets': ['baby puss', 'dino'] }
     * ];
     *
     * _.where(characters, { 'age': 36 });
     * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
     *
     * _.where(characters, { 'pets': ['dino'] });
     * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
     */
    var where = filter;

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

    /**
     * Creates an array with all falsey values removed. The values `false`, `null`,
     * `0`, `""`, `undefined`, and `NaN` are all falsey.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to compact.
     * @returns {Array} Returns a new array of filtered values.
     * @example
     *
     * _.compact([0, 1, false, 2, '', 3]);
     * // => [1, 2, 3]
     */
    function compact(array) {
      var index = -1,
          length = array ? array.length : 0,
          result = [];

      while (++index < length) {
        var value = array[index];
        if (value) {
          result.push(value);
        }
      }
      return result;
    }

    /**
     * Creates an array excluding all values of the provided arrays using strict
     * equality for comparisons, i.e. `===`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to process.
     * @param {...Array} [values] The arrays of values to exclude.
     * @returns {Array} Returns a new array of filtered values.
     * @example
     *
     * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
     * // => [1, 3, 4]
     */
    function difference(array) {
      return baseDifference(array, baseFlatten(arguments, true, true, 1));
    }

    /**
     * This method is like `_.find` except that it returns the index of the first
     * element that passes the callback check, instead of the element itself.
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to search.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {number} Returns the index of the found element, else `-1`.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney',  'age': 36, 'blocked': false },
     *   { 'name': 'fred',    'age': 40, 'blocked': true },
     *   { 'name': 'pebbles', 'age': 1,  'blocked': false }
     * ];
     *
     * _.findIndex(characters, function(chr) {
     *   return chr.age < 20;
     * });
     * // => 2
     *
     * // using "_.where" callback shorthand
     * _.findIndex(characters, { 'age': 36 });
     * // => 0
     *
     * // using "_.pluck" callback shorthand
     * _.findIndex(characters, 'blocked');
     * // => 1
     */
    function findIndex(array, callback, thisArg) {
      var index = -1,
          length = array ? array.length : 0;

      callback = lodash.createCallback(callback, thisArg, 3);
      while (++index < length) {
        if (callback(array[index], index, array)) {
          return index;
        }
      }
      return -1;
    }

    /**
     * This method is like `_.findIndex` except that it iterates over elements
     * of a `collection` from right to left.
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to search.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {number} Returns the index of the found element, else `-1`.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney',  'age': 36, 'blocked': true },
     *   { 'name': 'fred',    'age': 40, 'blocked': false },
     *   { 'name': 'pebbles', 'age': 1,  'blocked': true }
     * ];
     *
     * _.findLastIndex(characters, function(chr) {
     *   return chr.age > 30;
     * });
     * // => 1
     *
     * // using "_.where" callback shorthand
     * _.findLastIndex(characters, { 'age': 36 });
     * // => 0
     *
     * // using "_.pluck" callback shorthand
     * _.findLastIndex(characters, 'blocked');
     * // => 2
     */
    function findLastIndex(array, callback, thisArg) {
      var length = array ? array.length : 0;
      callback = lodash.createCallback(callback, thisArg, 3);
      while (length--) {
        if (callback(array[length], length, array)) {
          return length;
        }
      }
      return -1;
    }

    /**
     * Gets the first element or first `n` elements of an array. If a callback
     * is provided elements at the beginning of the array are returned as long
     * as the callback returns truey. The callback is bound to `thisArg` and
     * invoked with three arguments; (value, index, array).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias head, take
     * @category Arrays
     * @param {Array} array The array to query.
     * @param {Function|Object|number|string} [callback] The function called
     *  per element or the number of elements to return. If a property name or
     *  object is provided it will be used to create a "_.pluck" or "_.where"
     *  style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the first element(s) of `array`.
     * @example
     *
     * _.first([1, 2, 3]);
     * // => 1
     *
     * _.first([1, 2, 3], 2);
     * // => [1, 2]
     *
     * _.first([1, 2, 3], function(num) {
     *   return num < 3;
     * });
     * // => [1, 2]
     *
     * var characters = [
     *   { 'name': 'barney',  'blocked': true,  'employer': 'slate' },
     *   { 'name': 'fred',    'blocked': false, 'employer': 'slate' },
     *   { 'name': 'pebbles', 'blocked': true,  'employer': 'na' }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.first(characters, 'blocked');
     * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }]
     *
     * // using "_.where" callback shorthand
     * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
     * // => ['barney', 'fred']
     */
    function first(array, callback, thisArg) {
      var n = 0,
          length = array ? array.length : 0;

      if (typeof callback != 'number' && callback != null) {
        var index = -1;
        callback = lodash.createCallback(callback, thisArg, 3);
        while (++index < length && callback(array[index], index, array)) {
          n++;
        }
      } else {
        n = callback;
        if (n == null || thisArg) {
          return array ? array[0] : undefined;
        }
      }
      return slice(array, 0, nativeMin(nativeMax(0, n), length));
    }

    /**
     * Flattens a nested array (the nesting can be to any depth). If `isShallow`
     * is truey, the array will only be flattened a single level. If a callback
     * is provided each element of the array is passed through the callback before
     * flattening. The callback is bound to `thisArg` and invoked with three
     * arguments; (value, index, array).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to flatten.
     * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a new flattened array.
     * @example
     *
     * _.flatten([1, [2], [3, [[4]]]]);
     * // => [1, 2, 3, 4];
     *
     * _.flatten([1, [2], [3, [[4]]]], true);
     * // => [1, 2, 3, [[4]]];
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
     *   { 'name': 'fred',   'age': 40, 'pets': ['baby puss', 'dino'] }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.flatten(characters, 'pets');
     * // => ['hoppy', 'baby puss', 'dino']
     */
    function flatten(array, isShallow, callback, thisArg) {
      // juggle arguments
      if (typeof isShallow != 'boolean' && isShallow != null) {
        thisArg = callback;
        callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow;
        isShallow = false;
      }
      if (callback != null) {
        array = map(array, callback, thisArg);
      }
      return baseFlatten(array, isShallow);
    }

    /**
     * Gets the index at which the first occurrence of `value` is found using
     * strict equality for comparisons, i.e. `===`. If the array is already sorted
     * providing `true` for `fromIndex` will run a faster binary search.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to search.
     * @param {*} value The value to search for.
     * @param {boolean|number} [fromIndex=0] The index to search from or `true`
     *  to perform a binary search on a sorted array.
     * @returns {number} Returns the index of the matched value or `-1`.
     * @example
     *
     * _.indexOf([1, 2, 3, 1, 2, 3], 2);
     * // => 1
     *
     * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
     * // => 4
     *
     * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
     * // => 2
     */
    function indexOf(array, value, fromIndex) {
      if (typeof fromIndex == 'number') {
        var length = array ? array.length : 0;
        fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
      } else if (fromIndex) {
        var index = sortedIndex(array, value);
        return array[index] === value ? index : -1;
      }
      return baseIndexOf(array, value, fromIndex);
    }

    /**
     * Gets all but the last element or last `n` elements of an array. If a
     * callback is provided elements at the end of the array are excluded from
     * the result as long as the callback returns truey. The callback is bound
     * to `thisArg` and invoked with three arguments; (value, index, array).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to query.
     * @param {Function|Object|number|string} [callback=1] The function called
     *  per element or the number of elements to exclude. If a property name or
     *  object is provided it will be used to create a "_.pluck" or "_.where"
     *  style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a slice of `array`.
     * @example
     *
     * _.initial([1, 2, 3]);
     * // => [1, 2]
     *
     * _.initial([1, 2, 3], 2);
     * // => [1]
     *
     * _.initial([1, 2, 3], function(num) {
     *   return num > 1;
     * });
     * // => [1]
     *
     * var characters = [
     *   { 'name': 'barney',  'blocked': false, 'employer': 'slate' },
     *   { 'name': 'fred',    'blocked': true,  'employer': 'slate' },
     *   { 'name': 'pebbles', 'blocked': true,  'employer': 'na' }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.initial(characters, 'blocked');
     * // => [{ 'name': 'barney',  'blocked': false, 'employer': 'slate' }]
     *
     * // using "_.where" callback shorthand
     * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
     * // => ['barney', 'fred']
     */
    function initial(array, callback, thisArg) {
      var n = 0,
          length = array ? array.length : 0;

      if (typeof callback != 'number' && callback != null) {
        var index = length;
        callback = lodash.createCallback(callback, thisArg, 3);
        while (index-- && callback(array[index], index, array)) {
          n++;
        }
      } else {
        n = (callback == null || thisArg) ? 1 : callback || n;
      }
      return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
    }

    /**
     * Creates an array of unique values present in all provided arrays using
     * strict equality for comparisons, i.e. `===`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {...Array} [array] The arrays to inspect.
     * @returns {Array} Returns an array of shared values.
     * @example
     *
     * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
     * // => [1, 2]
     */
    function intersection() {
      var args = [],
          argsIndex = -1,
          argsLength = arguments.length,
          caches = getArray(),
          indexOf = getIndexOf(),
          trustIndexOf = indexOf === baseIndexOf,
          seen = getArray();

      while (++argsIndex < argsLength) {
        var value = arguments[argsIndex];
        if (isArray(value) || isArguments(value)) {
          args.push(value);
          caches.push(trustIndexOf && value.length >= largeArraySize &&
            createCache(argsIndex ? args[argsIndex] : seen));
        }
      }
      var array = args[0],
          index = -1,
          length = array ? array.length : 0,
          result = [];

      outer:
      while (++index < length) {
        var cache = caches[0];
        value = array[index];

        if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
          argsIndex = argsLength;
          (cache || seen).push(value);
          while (--argsIndex) {
            cache = caches[argsIndex];
            if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
              continue outer;
            }
          }
          result.push(value);
        }
      }
      while (argsLength--) {
        cache = caches[argsLength];
        if (cache) {
          releaseObject(cache);
        }
      }
      releaseArray(caches);
      releaseArray(seen);
      return result;
    }

    /**
     * Gets the last element or last `n` elements of an array. If a callback is
     * provided elements at the end of the array are returned as long as the
     * callback returns truey. The callback is bound to `thisArg` and invoked
     * with three arguments; (value, index, array).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to query.
     * @param {Function|Object|number|string} [callback] The function called
     *  per element or the number of elements to return. If a property name or
     *  object is provided it will be used to create a "_.pluck" or "_.where"
     *  style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {*} Returns the last element(s) of `array`.
     * @example
     *
     * _.last([1, 2, 3]);
     * // => 3
     *
     * _.last([1, 2, 3], 2);
     * // => [2, 3]
     *
     * _.last([1, 2, 3], function(num) {
     *   return num > 1;
     * });
     * // => [2, 3]
     *
     * var characters = [
     *   { 'name': 'barney',  'blocked': false, 'employer': 'slate' },
     *   { 'name': 'fred',    'blocked': true,  'employer': 'slate' },
     *   { 'name': 'pebbles', 'blocked': true,  'employer': 'na' }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.pluck(_.last(characters, 'blocked'), 'name');
     * // => ['fred', 'pebbles']
     *
     * // using "_.where" callback shorthand
     * _.last(characters, { 'employer': 'na' });
     * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
     */
    function last(array, callback, thisArg) {
      var n = 0,
          length = array ? array.length : 0;

      if (typeof callback != 'number' && callback != null) {
        var index = length;
        callback = lodash.createCallback(callback, thisArg, 3);
        while (index-- && callback(array[index], index, array)) {
          n++;
        }
      } else {
        n = callback;
        if (n == null || thisArg) {
          return array ? array[length - 1] : undefined;
        }
      }
      return slice(array, nativeMax(0, length - n));
    }

    /**
     * Gets the index at which the last occurrence of `value` is found using strict
     * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
     * as the offset from the end of the collection.
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to search.
     * @param {*} value The value to search for.
     * @param {number} [fromIndex=array.length-1] The index to search from.
     * @returns {number} Returns the index of the matched value or `-1`.
     * @example
     *
     * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
     * // => 4
     *
     * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
     * // => 1
     */
    function lastIndexOf(array, value, fromIndex) {
      var index = array ? array.length : 0;
      if (typeof fromIndex == 'number') {
        index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
      }
      while (index--) {
        if (array[index] === value) {
          return index;
        }
      }
      return -1;
    }

    /**
     * Removes all provided values from the given array using strict equality for
     * comparisons, i.e. `===`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to modify.
     * @param {...*} [value] The values to remove.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [1, 2, 3, 1, 2, 3];
     * _.pull(array, 2, 3);
     * console.log(array);
     * // => [1, 1]
     */
    function pull(array) {
      var args = arguments,
          argsIndex = 0,
          argsLength = args.length,
          length = array ? array.length : 0;

      while (++argsIndex < argsLength) {
        var index = -1,
            value = args[argsIndex];
        while (++index < length) {
          if (array[index] === value) {
            splice.call(array, index--, 1);
            length--;
          }
        }
      }
      return array;
    }

    /**
     * Creates an array of numbers (positive and/or negative) progressing from
     * `start` up to but not including `end`. If `start` is less than `stop` a
     * zero-length range is created unless a negative `step` is specified.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {number} [start=0] The start of the range.
     * @param {number} end The end of the range.
     * @param {number} [step=1] The value to increment or decrement by.
     * @returns {Array} Returns a new range array.
     * @example
     *
     * _.range(4);
     * // => [0, 1, 2, 3]
     *
     * _.range(1, 5);
     * // => [1, 2, 3, 4]
     *
     * _.range(0, 20, 5);
     * // => [0, 5, 10, 15]
     *
     * _.range(0, -4, -1);
     * // => [0, -1, -2, -3]
     *
     * _.range(1, 4, 0);
     * // => [1, 1, 1]
     *
     * _.range(0);
     * // => []
     */
    function range(start, end, step) {
      start = +start || 0;
      step = typeof step == 'number' ? step : (+step || 1);

      if (end == null) {
        end = start;
        start = 0;
      }
      // use `Array(length)` so engines like Chakra and V8 avoid slower modes
      // http://youtu.be/XAqIpGU8ZZk#t=17m25s
      var index = -1,
          length = nativeMax(0, ceil((end - start) / (step || 1))),
          result = Array(length);

      while (++index < length) {
        result[index] = start;
        start += step;
      }
      return result;
    }

    /**
     * Removes all elements from an array that the callback returns truey for
     * and returns an array of removed elements. The callback is bound to `thisArg`
     * and invoked with three arguments; (value, index, array).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to modify.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a new array of removed elements.
     * @example
     *
     * var array = [1, 2, 3, 4, 5, 6];
     * var evens = _.remove(array, function(num) { return num % 2 == 0; });
     *
     * console.log(array);
     * // => [1, 3, 5]
     *
     * console.log(evens);
     * // => [2, 4, 6]
     */
    function remove(array, callback, thisArg) {
      var index = -1,
          length = array ? array.length : 0,
          result = [];

      callback = lodash.createCallback(callback, thisArg, 3);
      while (++index < length) {
        var value = array[index];
        if (callback(value, index, array)) {
          result.push(value);
          splice.call(array, index--, 1);
          length--;
        }
      }
      return result;
    }

    /**
     * The opposite of `_.initial` this method gets all but the first element or
     * first `n` elements of an array. If a callback function is provided elements
     * at the beginning of the array are excluded from the result as long as the
     * callback returns truey. The callback is bound to `thisArg` and invoked
     * with three arguments; (value, index, array).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias drop, tail
     * @category Arrays
     * @param {Array} array The array to query.
     * @param {Function|Object|number|string} [callback=1] The function called
     *  per element or the number of elements to exclude. If a property name or
     *  object is provided it will be used to create a "_.pluck" or "_.where"
     *  style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a slice of `array`.
     * @example
     *
     * _.rest([1, 2, 3]);
     * // => [2, 3]
     *
     * _.rest([1, 2, 3], 2);
     * // => [3]
     *
     * _.rest([1, 2, 3], function(num) {
     *   return num < 3;
     * });
     * // => [3]
     *
     * var characters = [
     *   { 'name': 'barney',  'blocked': true,  'employer': 'slate' },
     *   { 'name': 'fred',    'blocked': false,  'employer': 'slate' },
     *   { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
     * ];
     *
     * // using "_.pluck" callback shorthand
     * _.pluck(_.rest(characters, 'blocked'), 'name');
     * // => ['fred', 'pebbles']
     *
     * // using "_.where" callback shorthand
     * _.rest(characters, { 'employer': 'slate' });
     * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
     */
    function rest(array, callback, thisArg) {
      if (typeof callback != 'number' && callback != null) {
        var n = 0,
            index = -1,
            length = array ? array.length : 0;

        callback = lodash.createCallback(callback, thisArg, 3);
        while (++index < length && callback(array[index], index, array)) {
          n++;
        }
      } else {
        n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
      }
      return slice(array, n);
    }

    /**
     * Uses a binary search to determine the smallest index at which a value
     * should be inserted into a given sorted array in order to maintain the sort
     * order of the array. If a callback is provided it will be executed for
     * `value` and each element of `array` to compute their sort ranking. The
     * callback is bound to `thisArg` and invoked with one argument; (value).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to inspect.
     * @param {*} value The value to evaluate.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * _.sortedIndex([20, 30, 50], 40);
     * // => 2
     *
     * // using "_.pluck" callback shorthand
     * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
     * // => 2
     *
     * var dict = {
     *   'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
     * };
     *
     * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
     *   return dict.wordToNumber[word];
     * });
     * // => 2
     *
     * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
     *   return this.wordToNumber[word];
     * }, dict);
     * // => 2
     */
    function sortedIndex(array, value, callback, thisArg) {
      var low = 0,
          high = array ? array.length : low;

      // explicitly reference `identity` for better inlining in Firefox
      callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
      value = callback(value);

      while (low < high) {
        var mid = (low + high) >>> 1;
        (callback(array[mid]) < value)
          ? low = mid + 1
          : high = mid;
      }
      return low;
    }

    /**
     * Creates an array of unique values, in order, of the provided arrays using
     * strict equality for comparisons, i.e. `===`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {...Array} [array] The arrays to inspect.
     * @returns {Array} Returns an array of combined values.
     * @example
     *
     * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
     * // => [1, 2, 3, 5, 4]
     */
    function union() {
      return baseUniq(baseFlatten(arguments, true, true));
    }

    /**
     * Creates a duplicate-value-free version of an array using strict equality
     * for comparisons, i.e. `===`. If the array is sorted, providing
     * `true` for `isSorted` will use a faster algorithm. If a callback is provided
     * each element of `array` is passed through the callback before uniqueness
     * is computed. The callback is bound to `thisArg` and invoked with three
     * arguments; (value, index, array).
     *
     * If a property name is provided for `callback` the created "_.pluck" style
     * callback will return the property value of the given element.
     *
     * If an object is provided for `callback` the created "_.where" style callback
     * will return `true` for elements that have the properties of the given object,
     * else `false`.
     *
     * @static
     * @memberOf _
     * @alias unique
     * @category Arrays
     * @param {Array} array The array to process.
     * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
     * @param {Function|Object|string} [callback=identity] The function called
     *  per iteration. If a property name or object is provided it will be used
     *  to create a "_.pluck" or "_.where" style callback, respectively.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns a duplicate-value-free array.
     * @example
     *
     * _.uniq([1, 2, 1, 3, 1]);
     * // => [1, 2, 3]
     *
     * _.uniq([1, 1, 2, 2, 3], true);
     * // => [1, 2, 3]
     *
     * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
     * // => ['A', 'b', 'C']
     *
     * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
     * // => [1, 2.5, 3]
     *
     * // using "_.pluck" callback shorthand
     * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 1 }, { 'x': 2 }]
     */
    function uniq(array, isSorted, callback, thisArg) {
      // juggle arguments
      if (typeof isSorted != 'boolean' && isSorted != null) {
        thisArg = callback;
        callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted;
        isSorted = false;
      }
      if (callback != null) {
        callback = lodash.createCallback(callback, thisArg, 3);
      }
      return baseUniq(array, isSorted, callback);
    }

    /**
     * Creates an array excluding all provided values using strict equality for
     * comparisons, i.e. `===`.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {Array} array The array to filter.
     * @param {...*} [value] The values to exclude.
     * @returns {Array} Returns a new array of filtered values.
     * @example
     *
     * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
     * // => [2, 3, 4]
     */
    function without(array) {
      return baseDifference(array, slice(arguments, 1));
    }

    /**
     * Creates an array that is the symmetric difference of the provided arrays.
     * See http://en.wikipedia.org/wiki/Symmetric_difference.
     *
     * @static
     * @memberOf _
     * @category Arrays
     * @param {...Array} [array] The arrays to inspect.
     * @returns {Array} Returns an array of values.
     * @example
     *
     * _.xor([1, 2, 3], [5, 2, 1, 4]);
     * // => [3, 5, 4]
     *
     * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
     * // => [1, 4, 5]
     */
    function xor() {
      var index = -1,
          length = arguments.length;

      while (++index < length) {
        var array = arguments[index];
        if (isArray(array) || isArguments(array)) {
          var result = result
            ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result)))
            : array;
        }
      }
      return result || [];
    }

    /**
     * Creates an array of grouped elements, the first of which contains the first
     * elements of the given arrays, the second of which contains the second
     * elements of the given arrays, and so on.
     *
     * @static
     * @memberOf _
     * @alias unzip
     * @category Arrays
     * @param {...Array} [array] Arrays to process.
     * @returns {Array} Returns a new array of grouped elements.
     * @example
     *
     * _.zip(['fred', 'barney'], [30, 40], [true, false]);
     * // => [['fred', 30, true], ['barney', 40, false]]
     */
    function zip() {
      var array = arguments.length > 1 ? arguments : arguments[0],
          index = -1,
          length = array ? max(pluck(array, 'length')) : 0,
          result = Array(length < 0 ? 0 : length);

      while (++index < length) {
        result[index] = pluck(array, index);
      }
      return result;
    }

    /**
     * Creates an object composed from arrays of `keys` and `values`. Provide
     * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
     * or two arrays, one of `keys` and one of corresponding `values`.
     *
     * @static
     * @memberOf _
     * @alias object
     * @category Arrays
     * @param {Array} keys The array of keys.
     * @param {Array} [values=[]] The array of values.
     * @returns {Object} Returns an object composed of the given keys and
     *  corresponding values.
     * @example
     *
     * _.zipObject(['fred', 'barney'], [30, 40]);
     * // => { 'fred': 30, 'barney': 40 }
     */
    function zipObject(keys, values) {
      var index = -1,
          length = keys ? keys.length : 0,
          result = {};

      if (!values && length && !isArray(keys[0])) {
        values = [];
      }
      while (++index < length) {
        var key = keys[index];
        if (values) {
          result[key] = values[index];
        } else if (key) {
          result[key[0]] = key[1];
        }
      }
      return result;
    }

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

    /**
     * Creates a function that executes `func`, with  the `this` binding and
     * arguments of the created function, only after being called `n` times.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {number} n The number of times the function must be called before
     *  `func` is executed.
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * var saves = ['profile', 'settings'];
     *
     * var done = _.after(saves.length, function() {
     *   console.log('Done saving!');
     * });
     *
     * _.forEach(saves, function(type) {
     *   asyncSave({ 'type': type, 'complete': done });
     * });
     * // => logs 'Done saving!', after all saves have completed
     */
    function after(n, func) {
      if (!isFunction(func)) {
        throw new TypeError;
      }
      return function() {
        if (--n < 1) {
          return func.apply(this, arguments);
        }
      };
    }

    /**
     * Creates a function that, when called, invokes `func` with the `this`
     * binding of `thisArg` and prepends any additional `bind` arguments to those
     * provided to the bound function.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to bind.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {...*} [arg] Arguments to be partially applied.
     * @returns {Function} Returns the new bound function.
     * @example
     *
     * var func = function(greeting) {
     *   return greeting + ' ' + this.name;
     * };
     *
     * func = _.bind(func, { 'name': 'fred' }, 'hi');
     * func();
     * // => 'hi fred'
     */
    function bind(func, thisArg) {
      return arguments.length > 2
        ? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
        : createWrapper(func, 1, null, null, thisArg);
    }

    /**
     * Binds methods of an object to the object itself, overwriting the existing
     * method. Method names may be specified as individual arguments or as arrays
     * of method names. If no method names are provided all the function properties
     * of `object` will be bound.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Object} object The object to bind and assign the bound methods to.
     * @param {...string} [methodName] The object method names to
     *  bind, specified as individual method names or arrays of method names.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var view = {
     *   'label': 'docs',
     *   'onClick': function() { console.log('clicked ' + this.label); }
     * };
     *
     * _.bindAll(view);
     * jQuery('#docs').on('click', view.onClick);
     * // => logs 'clicked docs', when the button is clicked
     */
    function bindAll(object) {
      var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
          index = -1,
          length = funcs.length;

      while (++index < length) {
        var key = funcs[index];
        object[key] = createWrapper(object[key], 1, null, null, object);
      }
      return object;
    }

    /**
     * Creates a function that, when called, invokes the method at `object[key]`
     * and prepends any additional `bindKey` arguments to those provided to the bound
     * function. This method differs from `_.bind` by allowing bound functions to
     * reference methods that will be redefined or don't yet exist.
     * See http://michaux.ca/articles/lazy-function-definition-pattern.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Object} object The object the method belongs to.
     * @param {string} key The key of the method.
     * @param {...*} [arg] Arguments to be partially applied.
     * @returns {Function} Returns the new bound function.
     * @example
     *
     * var object = {
     *   'name': 'fred',
     *   'greet': function(greeting) {
     *     return greeting + ' ' + this.name;
     *   }
     * };
     *
     * var func = _.bindKey(object, 'greet', 'hi');
     * func();
     * // => 'hi fred'
     *
     * object.greet = function(greeting) {
     *   return greeting + 'ya ' + this.name + '!';
     * };
     *
     * func();
     * // => 'hiya fred!'
     */
    function bindKey(object, key) {
      return arguments.length > 2
        ? createWrapper(key, 19, slice(arguments, 2), null, object)
        : createWrapper(key, 3, null, null, object);
    }

    /**
     * Creates a function that is the composition of the provided functions,
     * where each function consumes the return value of the function that follows.
     * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
     * Each function is executed with the `this` binding of the composed function.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {...Function} [func] Functions to compose.
     * @returns {Function} Returns the new composed function.
     * @example
     *
     * var realNameMap = {
     *   'pebbles': 'penelope'
     * };
     *
     * var format = function(name) {
     *   name = realNameMap[name.toLowerCase()] || name;
     *   return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
     * };
     *
     * var greet = function(formatted) {
     *   return 'Hiya ' + formatted + '!';
     * };
     *
     * var welcome = _.compose(greet, format);
     * welcome('pebbles');
     * // => 'Hiya Penelope!'
     */
    function compose() {
      var funcs = arguments,
          length = funcs.length;

      while (length--) {
        if (!isFunction(funcs[length])) {
          throw new TypeError;
        }
      }
      return function() {
        var args = arguments,
            length = funcs.length;

        while (length--) {
          args = [funcs[length].apply(this, args)];
        }
        return args[0];
      };
    }

    /**
     * Creates a function which accepts one or more arguments of `func` that when
     * invoked either executes `func` returning its result, if all `func` arguments
     * have been provided, or returns a function that accepts one or more of the
     * remaining `func` arguments, and so on. The arity of `func` can be specified
     * if `func.length` is not sufficient.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to curry.
     * @param {number} [arity=func.length] The arity of `func`.
     * @returns {Function} Returns the new curried function.
     * @example
     *
     * var curried = _.curry(function(a, b, c) {
     *   console.log(a + b + c);
     * });
     *
     * curried(1)(2)(3);
     * // => 6
     *
     * curried(1, 2)(3);
     * // => 6
     *
     * curried(1, 2, 3);
     * // => 6
     */
    function curry(func, arity) {
      arity = typeof arity == 'number' ? arity : (+arity || func.length);
      return createWrapper(func, 4, null, null, null, arity);
    }

    /**
     * Creates a function that will delay the execution of `func` until after
     * `wait` milliseconds have elapsed since the last time it was invoked.
     * Provide an options object to indicate that `func` should be invoked on
     * the leading and/or trailing edge of the `wait` timeout. Subsequent calls
     * to the debounced function will return the result of the last `func` call.
     *
     * Note: If `leading` and `trailing` options are `true` `func` will be called
     * on the trailing edge of the timeout only if the the debounced function is
     * invoked more than once during the `wait` timeout.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to debounce.
     * @param {number} wait The number of milliseconds to delay.
     * @param {Object} [options] The options object.
     * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
     * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
     * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
     * @returns {Function} Returns the new debounced function.
     * @example
     *
     * // avoid costly calculations while the window size is in flux
     * var lazyLayout = _.debounce(calculateLayout, 150);
     * jQuery(window).on('resize', lazyLayout);
     *
     * // execute `sendMail` when the click event is fired, debouncing subsequent calls
     * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
     *   'leading': true,
     *   'trailing': false
     * });
     *
     * // ensure `batchLog` is executed once after 1 second of debounced calls
     * var source = new EventSource('/stream');
     * source.addEventListener('message', _.debounce(batchLog, 250, {
     *   'maxWait': 1000
     * }, false);
     */
    function debounce(func, wait, options) {
      var args,
          maxTimeoutId,
          result,
          stamp,
          thisArg,
          timeoutId,
          trailingCall,
          lastCalled = 0,
          maxWait = false,
          trailing = true;

      if (!isFunction(func)) {
        throw new TypeError;
      }
      wait = nativeMax(0, wait) || 0;
      if (options === true) {
        var leading = true;
        trailing = false;
      } else if (isObject(options)) {
        leading = options.leading;
        maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
        trailing = 'trailing' in options ? options.trailing : trailing;
      }
      var delayed = function() {
        var remaining = wait - (now() - stamp);
        if (remaining <= 0) {
          if (maxTimeoutId) {
            clearTimeout(maxTimeoutId);
          }
          var isCalled = trailingCall;
          maxTimeoutId = timeoutId = trailingCall = undefined;
          if (isCalled) {
            lastCalled = now();
            result = func.apply(thisArg, args);
            if (!timeoutId && !maxTimeoutId) {
              args = thisArg = null;
            }
          }
        } else {
          timeoutId = setTimeout(delayed, remaining);
        }
      };

      var maxDelayed = function() {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        maxTimeoutId = timeoutId = trailingCall = undefined;
        if (trailing || (maxWait !== wait)) {
          lastCalled = now();
          result = func.apply(thisArg, args);
          if (!timeoutId && !maxTimeoutId) {
            args = thisArg = null;
          }
        }
      };

      return function() {
        args = arguments;
        stamp = now();
        thisArg = this;
        trailingCall = trailing && (timeoutId || !leading);

        if (maxWait === false) {
          var leadingCall = leading && !timeoutId;
        } else {
          if (!maxTimeoutId && !leading) {
            lastCalled = stamp;
          }
          var remaining = maxWait - (stamp - lastCalled),
              isCalled = remaining <= 0;

          if (isCalled) {
            if (maxTimeoutId) {
              maxTimeoutId = clearTimeout(maxTimeoutId);
            }
            lastCalled = stamp;
            result = func.apply(thisArg, args);
          }
          else if (!maxTimeoutId) {
            maxTimeoutId = setTimeout(maxDelayed, remaining);
          }
        }
        if (isCalled && timeoutId) {
          timeoutId = clearTimeout(timeoutId);
        }
        else if (!timeoutId && wait !== maxWait) {
          timeoutId = setTimeout(delayed, wait);
        }
        if (leadingCall) {
          isCalled = true;
          result = func.apply(thisArg, args);
        }
        if (isCalled && !timeoutId && !maxTimeoutId) {
          args = thisArg = null;
        }
        return result;
      };
    }

    /**
     * Defers executing the `func` function until the current call stack has cleared.
     * Additional arguments will be provided to `func` when it is invoked.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to defer.
     * @param {...*} [arg] Arguments to invoke the function with.
     * @returns {number} Returns the timer id.
     * @example
     *
     * _.defer(function(text) { console.log(text); }, 'deferred');
     * // logs 'deferred' after one or more milliseconds
     */
    function defer(func) {
      if (!isFunction(func)) {
        throw new TypeError;
      }
      var args = slice(arguments, 1);
      return setTimeout(function() { func.apply(undefined, args); }, 1);
    }

    /**
     * Executes the `func` function after `wait` milliseconds. Additional arguments
     * will be provided to `func` when it is invoked.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to delay.
     * @param {number} wait The number of milliseconds to delay execution.
     * @param {...*} [arg] Arguments to invoke the function with.
     * @returns {number} Returns the timer id.
     * @example
     *
     * _.delay(function(text) { console.log(text); }, 1000, 'later');
     * // => logs 'later' after one second
     */
    function delay(func, wait) {
      if (!isFunction(func)) {
        throw new TypeError;
      }
      var args = slice(arguments, 2);
      return setTimeout(function() { func.apply(undefined, args); }, wait);
    }

    /**
     * Creates a function that memoizes the result of `func`. If `resolver` is
     * provided it will be used to determine the cache key for storing the result
     * based on the arguments provided to the memoized function. By default, the
     * first argument provided to the memoized function is used as the cache key.
     * The `func` is executed with the `this` binding of the memoized function.
     * The result cache is exposed as the `cache` property on the memoized function.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to have its output memoized.
     * @param {Function} [resolver] A function used to resolve the cache key.
     * @returns {Function} Returns the new memoizing function.
     * @example
     *
     * var fibonacci = _.memoize(function(n) {
     *   return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
     * });
     *
     * fibonacci(9)
     * // => 34
     *
     * var data = {
     *   'fred': { 'name': 'fred', 'age': 40 },
     *   'pebbles': { 'name': 'pebbles', 'age': 1 }
     * };
     *
     * // modifying the result cache
     * var get = _.memoize(function(name) { return data[name]; }, _.identity);
     * get('pebbles');
     * // => { 'name': 'pebbles', 'age': 1 }
     *
     * get.cache.pebbles.name = 'penelope';
     * get('pebbles');
     * // => { 'name': 'penelope', 'age': 1 }
     */
    function memoize(func, resolver) {
      if (!isFunction(func)) {
        throw new TypeError;
      }
      var memoized = function() {
        var cache = memoized.cache,
            key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];

        return hasOwnProperty.call(cache, key)
          ? cache[key]
          : (cache[key] = func.apply(this, arguments));
      }
      memoized.cache = {};
      return memoized;
    }

    /**
     * Creates a function that is restricted to execute `func` once. Repeat calls to
     * the function will return the value of the first call. The `func` is executed
     * with the `this` binding of the created function.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * var initialize = _.once(createApplication);
     * initialize();
     * initialize();
     * // `initialize` executes `createApplication` once
     */
    function once(func) {
      var ran,
          result;

      if (!isFunction(func)) {
        throw new TypeError;
      }
      return function() {
        if (ran) {
          return result;
        }
        ran = true;
        result = func.apply(this, arguments);

        // clear the `func` variable so the function may be garbage collected
        func = null;
        return result;
      };
    }

    /**
     * Creates a function that, when called, invokes `func` with any additional
     * `partial` arguments prepended to those provided to the new function. This
     * method is similar to `_.bind` except it does **not** alter the `this` binding.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to partially apply arguments to.
     * @param {...*} [arg] Arguments to be partially applied.
     * @returns {Function} Returns the new partially applied function.
     * @example
     *
     * var greet = function(greeting, name) { return greeting + ' ' + name; };
     * var hi = _.partial(greet, 'hi');
     * hi('fred');
     * // => 'hi fred'
     */
    function partial(func) {
      return createWrapper(func, 16, slice(arguments, 1));
    }

    /**
     * This method is like `_.partial` except that `partial` arguments are
     * appended to those provided to the new function.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to partially apply arguments to.
     * @param {...*} [arg] Arguments to be partially applied.
     * @returns {Function} Returns the new partially applied function.
     * @example
     *
     * var defaultsDeep = _.partialRight(_.merge, _.defaults);
     *
     * var options = {
     *   'variable': 'data',
     *   'imports': { 'jq': $ }
     * };
     *
     * defaultsDeep(options, _.templateSettings);
     *
     * options.variable
     * // => 'data'
     *
     * options.imports
     * // => { '_': _, 'jq': $ }
     */
    function partialRight(func) {
      return createWrapper(func, 32, null, slice(arguments, 1));
    }

    /**
     * Creates a function that, when executed, will only call the `func` function
     * at most once per every `wait` milliseconds. Provide an options object to
     * indicate that `func` should be invoked on the leading and/or trailing edge
     * of the `wait` timeout. Subsequent calls to the throttled function will
     * return the result of the last `func` call.
     *
     * Note: If `leading` and `trailing` options are `true` `func` will be called
     * on the trailing edge of the timeout only if the the throttled function is
     * invoked more than once during the `wait` timeout.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {Function} func The function to throttle.
     * @param {number} wait The number of milliseconds to throttle executions to.
     * @param {Object} [options] The options object.
     * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
     * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
     * @returns {Function} Returns the new throttled function.
     * @example
     *
     * // avoid excessively updating the position while scrolling
     * var throttled = _.throttle(updatePosition, 100);
     * jQuery(window).on('scroll', throttled);
     *
     * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
     * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
     *   'trailing': false
     * }));
     */
    function throttle(func, wait, options) {
      var leading = true,
          trailing = true;

      if (!isFunction(func)) {
        throw new TypeError;
      }
      if (options === false) {
        leading = false;
      } else if (isObject(options)) {
        leading = 'leading' in options ? options.leading : leading;
        trailing = 'trailing' in options ? options.trailing : trailing;
      }
      debounceOptions.leading = leading;
      debounceOptions.maxWait = wait;
      debounceOptions.trailing = trailing;

      return debounce(func, wait, debounceOptions);
    }

    /**
     * Creates a function that provides `value` to the wrapper function as its
     * first argument. Additional arguments provided to the function are appended
     * to those provided to the wrapper function. The wrapper is executed with
     * the `this` binding of the created function.
     *
     * @static
     * @memberOf _
     * @category Functions
     * @param {*} value The value to wrap.
     * @param {Function} wrapper The wrapper function.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var p = _.wrap(_.escape, function(func, text) {
     *   return '<p>' + func(text) + '</p>';
     * });
     *
     * p('Fred, Wilma, & Pebbles');
     * // => '<p>Fred, Wilma, &amp; Pebbles</p>'
     */
    function wrap(value, wrapper) {
      return createWrapper(wrapper, 16, [value]);
    }

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

    /**
     * Creates a function that returns `value`.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {*} value The value to return from the new function.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var object = { 'name': 'fred' };
     * var getter = _.constant(object);
     * getter() === object;
     * // => true
     */
    function constant(value) {
      return function() {
        return value;
      };
    }

    /**
     * Produces a callback bound to an optional `thisArg`. If `func` is a property
     * name the created callback will return the property value for a given element.
     * If `func` is an object the created callback will return `true` for elements
     * that contain the equivalent object properties, otherwise it will return `false`.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {*} [func=identity] The value to convert to a callback.
     * @param {*} [thisArg] The `this` binding of the created callback.
     * @param {number} [argCount] The number of arguments the callback accepts.
     * @returns {Function} Returns a callback function.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * // wrap to create custom callback shorthands
     * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
     *   var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
     *   return !match ? func(callback, thisArg) : function(object) {
     *     return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
     *   };
     * });
     *
     * _.filter(characters, 'age__gt38');
     * // => [{ 'name': 'fred', 'age': 40 }]
     */
    function createCallback(func, thisArg, argCount) {
      var type = typeof func;
      if (func == null || type == 'function') {
        return baseCreateCallback(func, thisArg, argCount);
      }
      // handle "_.pluck" style callback shorthands
      if (type != 'object') {
        return property(func);
      }
      var props = keys(func),
          key = props[0],
          a = func[key];

      // handle "_.where" style callback shorthands
      if (props.length == 1 && a === a && !isObject(a)) {
        // fast path the common case of providing an object with a single
        // property containing a primitive value
        return function(object) {
          var b = object[key];
          return a === b && (a !== 0 || (1 / a == 1 / b));
        };
      }
      return function(object) {
        var length = props.length,
            result = false;

        while (length--) {
          if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
            break;
          }
        }
        return result;
      };
    }

    /**
     * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
     * corresponding HTML entities.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {string} string The string to escape.
     * @returns {string} Returns the escaped string.
     * @example
     *
     * _.escape('Fred, Wilma, & Pebbles');
     * // => 'Fred, Wilma, &amp; Pebbles'
     */
    function escape(string) {
      return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
    }

    /**
     * This method returns the first argument provided to it.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {*} value Any value.
     * @returns {*} Returns `value`.
     * @example
     *
     * var object = { 'name': 'fred' };
     * _.identity(object) === object;
     * // => true
     */
    function identity(value) {
      return value;
    }

    /**
     * Adds function properties of a source object to the destination object.
     * If `object` is a function methods will be added to its prototype as well.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {Function|Object} [object=lodash] object The destination object.
     * @param {Object} source The object of functions to add.
     * @param {Object} [options] The options object.
     * @param {boolean} [options.chain=true] Specify whether the functions added are chainable.
     * @example
     *
     * function capitalize(string) {
     *   return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
     * }
     *
     * _.mixin({ 'capitalize': capitalize });
     * _.capitalize('fred');
     * // => 'Fred'
     *
     * _('fred').capitalize().value();
     * // => 'Fred'
     *
     * _.mixin({ 'capitalize': capitalize }, { 'chain': false });
     * _('fred').capitalize();
     * // => 'Fred'
     */
    function mixin(object, source, options) {
      var chain = true,
          methodNames = source && functions(source);

      if (!source || (!options && !methodNames.length)) {
        if (options == null) {
          options = source;
        }
        ctor = lodashWrapper;
        source = object;
        object = lodash;
        methodNames = functions(source);
      }
      if (options === false) {
        chain = false;
      } else if (isObject(options) && 'chain' in options) {
        chain = options.chain;
      }
      var ctor = object,
          isFunc = isFunction(ctor);

      forEach(methodNames, function(methodName) {
        var func = object[methodName] = source[methodName];
        if (isFunc) {
          ctor.prototype[methodName] = function() {
            var chainAll = this.__chain__,
                value = this.__wrapped__,
                args = [value];

            push.apply(args, arguments);
            var result = func.apply(object, args);
            if (chain || chainAll) {
              if (value === result && isObject(result)) {
                return this;
              }
              result = new ctor(result);
              result.__chain__ = chainAll;
            }
            return result;
          };
        }
      });
    }

    /**
     * Reverts the '_' variable to its previous value and returns a reference to
     * the `lodash` function.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @returns {Function} Returns the `lodash` function.
     * @example
     *
     * var lodash = _.noConflict();
     */
    function noConflict() {
      context._ = oldDash;
      return this;
    }

    /**
     * A no-operation function.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @example
     *
     * var object = { 'name': 'fred' };
     * _.noop(object) === undefined;
     * // => true
     */
    function noop() {
      // no operation performed
    }

    /**
     * Gets the number of milliseconds that have elapsed since the Unix epoch
     * (1 January 1970 00:00:00 UTC).
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @example
     *
     * var stamp = _.now();
     * _.defer(function() { console.log(_.now() - stamp); });
     * // => logs the number of milliseconds it took for the deferred function to be called
     */
    var now = isNative(now = Date.now) && now || function() {
      return new Date().getTime();
    };

    /**
     * Converts the given value into an integer of the specified radix.
     * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
     * `value` is a hexadecimal, in which case a `radix` of `16` is used.
     *
     * Note: This method avoids differences in native ES3 and ES5 `parseInt`
     * implementations. See http://es5.github.io/#E.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {string} value The value to parse.
     * @param {number} [radix] The radix used to interpret the value to parse.
     * @returns {number} Returns the new integer value.
     * @example
     *
     * _.parseInt('08');
     * // => 8
     */
    var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
      // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt`
      return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
    };

    /**
     * Creates a "_.pluck" style function, which returns the `key` value of a
     * given object.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {string} key The name of the property to retrieve.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var characters = [
     *   { 'name': 'fred',   'age': 40 },
     *   { 'name': 'barney', 'age': 36 }
     * ];
     *
     * var getName = _.property('name');
     *
     * _.map(characters, getName);
     * // => ['barney', 'fred']
     *
     * _.sortBy(characters, getName);
     * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred',   'age': 40 }]
     */
    function property(key) {
      return function(object) {
        return object[key];
      };
    }

    /**
     * Produces a random number between `min` and `max` (inclusive). If only one
     * argument is provided a number between `0` and the given number will be
     * returned. If `floating` is truey or either `min` or `max` are floats a
     * floating-point number will be returned instead of an integer.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {number} [min=0] The minimum possible value.
     * @param {number} [max=1] The maximum possible value.
     * @param {boolean} [floating=false] Specify returning a floating-point number.
     * @returns {number} Returns a random number.
     * @example
     *
     * _.random(0, 5);
     * // => an integer between 0 and 5
     *
     * _.random(5);
     * // => also an integer between 0 and 5
     *
     * _.random(5, true);
     * // => a floating-point number between 0 and 5
     *
     * _.random(1.2, 5.2);
     * // => a floating-point number between 1.2 and 5.2
     */
    function random(min, max, floating) {
      var noMin = min == null,
          noMax = max == null;

      if (floating == null) {
        if (typeof min == 'boolean' && noMax) {
          floating = min;
          min = 1;
        }
        else if (!noMax && typeof max == 'boolean') {
          floating = max;
          noMax = true;
        }
      }
      if (noMin && noMax) {
        max = 1;
      }
      min = +min || 0;
      if (noMax) {
        max = min;
        min = 0;
      } else {
        max = +max || 0;
      }
      if (floating || min % 1 || max % 1) {
        var rand = nativeRandom();
        return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max);
      }
      return baseRandom(min, max);
    }

    /**
     * Resolves the value of property `key` on `object`. If `key` is a function
     * it will be invoked with the `this` binding of `object` and its result returned,
     * else the property value is returned. If `object` is falsey then `undefined`
     * is returned.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {Object} object The object to inspect.
     * @param {string} key The name of the property to resolve.
     * @returns {*} Returns the resolved value.
     * @example
     *
     * var object = {
     *   'cheese': 'crumpets',
     *   'stuff': function() {
     *     return 'nonsense';
     *   }
     * };
     *
     * _.result(object, 'cheese');
     * // => 'crumpets'
     *
     * _.result(object, 'stuff');
     * // => 'nonsense'
     */
    function result(object, key) {
      if (object) {
        var value = object[key];
        return isFunction(value) ? object[key]() : value;
      }
    }

    /**
     * A micro-templating method that handles arbitrary delimiters, preserves
     * whitespace, and correctly escapes quotes within interpolated code.
     *
     * Note: In the development build, `_.template` utilizes sourceURLs for easier
     * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
     *
     * For more information on precompiling templates see:
     * https://lodash.com/custom-builds
     *
     * For more information on Chrome extension sandboxes see:
     * http://developer.chrome.com/stable/extensions/sandboxingEval.html
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {string} text The template text.
     * @param {Object} data The data object used to populate the text.
     * @param {Object} [options] The options object.
     * @param {RegExp} [options.escape] The "escape" delimiter.
     * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
     * @param {Object} [options.imports] An object to import into the template as local variables.
     * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
     * @param {string} [sourceURL] The sourceURL of the template's compiled source.
     * @param {string} [variable] The data object variable name.
     * @returns {Function|string} Returns a compiled function when no `data` object
     *  is given, else it returns the interpolated text.
     * @example
     *
     * // using the "interpolate" delimiter to create a compiled template
     * var compiled = _.template('hello <%= name %>');
     * compiled({ 'name': 'fred' });
     * // => 'hello fred'
     *
     * // using the "escape" delimiter to escape HTML in data property values
     * _.template('<b><%- value %></b>', { 'value': '<script>' });
     * // => '<b>&lt;script&gt;</b>'
     *
     * // using the "evaluate" delimiter to generate HTML
     * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
     * _.template(list, { 'people': ['fred', 'barney'] });
     * // => '<li>fred</li><li>barney</li>'
     *
     * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
     * _.template('hello ${ name }', { 'name': 'pebbles' });
     * // => 'hello pebbles'
     *
     * // using the internal `print` function in "evaluate" delimiters
     * _.template('<% print("hello " + name); %>!', { 'name': 'barney' });
     * // => 'hello barney!'
     *
     * // using a custom template delimiters
     * _.templateSettings = {
     *   'interpolate': /{{([\s\S]+?)}}/g
     * };
     *
     * _.template('hello {{ name }}!', { 'name': 'mustache' });
     * // => 'hello mustache!'
     *
     * // using the `imports` option to import jQuery
     * var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
     * _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
     * // => '<li>fred</li><li>barney</li>'
     *
     * // using the `sourceURL` option to specify a custom sourceURL for the template
     * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
     * compiled(data);
     * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
     *
     * // using the `variable` option to ensure a with-statement isn't used in the compiled template
     * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
     * compiled.source;
     * // => function(data) {
     *   var __t, __p = '', __e = _.escape;
     *   __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
     *   return __p;
     * }
     *
     * // using the `source` property to inline compiled templates for meaningful
     * // line numbers in error messages and a stack trace
     * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
     *   var JST = {\
     *     "main": ' + _.template(mainText).source + '\
     *   };\
     * ');
     */
    function template(text, data, options) {
      // based on John Resig's `tmpl` implementation
      // http://ejohn.org/blog/javascript-micro-templating/
      // and Laura Doktorova's doT.js
      // https://github.com/olado/doT
      var settings = lodash.templateSettings;
      text = String(text || '');

      // avoid missing dependencies when `iteratorTemplate` is not defined
      options = defaults({}, options, settings);

      var imports = defaults({}, options.imports, settings.imports),
          importsKeys = keys(imports),
          importsValues = values(imports);

      var isEvaluating,
          index = 0,
          interpolate = options.interpolate || reNoMatch,
          source = "__p += '";

      // compile the regexp to match each delimiter
      var reDelimiters = RegExp(
        (options.escape || reNoMatch).source + '|' +
        interpolate.source + '|' +
        (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
        (options.evaluate || reNoMatch).source + '|$'
      , 'g');

      text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
        interpolateValue || (interpolateValue = esTemplateValue);

        // escape characters that cannot be included in string literals
        source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);

        // replace delimiters with snippets
        if (escapeValue) {
          source += "' +\n__e(" + escapeValue + ") +\n'";
        }
        if (evaluateValue) {
          isEvaluating = true;
          source += "';\n" + evaluateValue + ";\n__p += '";
        }
        if (interpolateValue) {
          source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
        }
        index = offset + match.length;

        // the JS engine embedded in Adobe products requires returning the `match`
        // string in order to produce the correct `offset` value
        return match;
      });

      source += "';\n";

      // if `variable` is not specified, wrap a with-statement around the generated
      // code to add the data object to the top of the scope chain
      var variable = options.variable,
          hasVariable = variable;

      if (!hasVariable) {
        variable = 'obj';
        source = 'with (' + variable + ') {\n' + source + '\n}\n';
      }
      // cleanup code by stripping empty strings
      source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
        .replace(reEmptyStringMiddle, '$1')
        .replace(reEmptyStringTrailing, '$1;');

      // frame code as the function body
      source = 'function(' + variable + ') {\n' +
        (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
        "var __t, __p = '', __e = _.escape" +
        (isEvaluating
          ? ', __j = Array.prototype.join;\n' +
            "function print() { __p += __j.call(arguments, '') }\n"
          : ';\n'
        ) +
        source +
        'return __p\n}';

      // Use a sourceURL for easier debugging.
      // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
      var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';

      try {
        var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
      } catch(e) {
        e.source = source;
        throw e;
      }
      if (data) {
        return result(data);
      }
      // provide the compiled function's source by its `toString` method, in
      // supported environments, or the `source` property as a convenience for
      // inlining compiled templates during the build process
      result.source = source;
      return result;
    }

    /**
     * Executes the callback `n` times, returning an array of the results
     * of each callback execution. The callback is bound to `thisArg` and invoked
     * with one argument; (index).
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {number} n The number of times to execute the callback.
     * @param {Function} callback The function called per iteration.
     * @param {*} [thisArg] The `this` binding of `callback`.
     * @returns {Array} Returns an array of the results of each `callback` execution.
     * @example
     *
     * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
     * // => [3, 6, 4]
     *
     * _.times(3, function(n) { mage.castSpell(n); });
     * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
     *
     * _.times(3, function(n) { this.cast(n); }, mage);
     * // => also calls `mage.castSpell(n)` three times
     */
    function times(n, callback, thisArg) {
      n = (n = +n) > -1 ? n : 0;
      var index = -1,
          result = Array(n);

      callback = baseCreateCallback(callback, thisArg, 1);
      while (++index < n) {
        result[index] = callback(index);
      }
      return result;
    }

    /**
     * The inverse of `_.escape` this method converts the HTML entities
     * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their
     * corresponding characters.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {string} string The string to unescape.
     * @returns {string} Returns the unescaped string.
     * @example
     *
     * _.unescape('Fred, Barney &amp; Pebbles');
     * // => 'Fred, Barney & Pebbles'
     */
    function unescape(string) {
      return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
    }

    /**
     * Generates a unique ID. If `prefix` is provided the ID will be appended to it.
     *
     * @static
     * @memberOf _
     * @category Utilities
     * @param {string} [prefix] The value to prefix the ID with.
     * @returns {string} Returns the unique ID.
     * @example
     *
     * _.uniqueId('contact_');
     * // => 'contact_104'
     *
     * _.uniqueId();
     * // => '105'
     */
    function uniqueId(prefix) {
      var id = ++idCounter;
      return String(prefix == null ? '' : prefix) + id;
    }

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

    /**
     * Creates a `lodash` object that wraps the given value with explicit
     * method chaining enabled.
     *
     * @static
     * @memberOf _
     * @category Chaining
     * @param {*} value The value to wrap.
     * @returns {Object} Returns the wrapper object.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney',  'age': 36 },
     *   { 'name': 'fred',    'age': 40 },
     *   { 'name': 'pebbles', 'age': 1 }
     * ];
     *
     * var youngest = _.chain(characters)
     *     .sortBy('age')
     *     .map(function(chr) { return chr.name + ' is ' + chr.age; })
     *     .first()
     *     .value();
     * // => 'pebbles is 1'
     */
    function chain(value) {
      value = new lodashWrapper(value);
      value.__chain__ = true;
      return value;
    }

    /**
     * Invokes `interceptor` with the `value` as the first argument and then
     * returns `value`. The purpose of this method is to "tap into" a method
     * chain in order to perform operations on intermediate results within
     * the chain.
     *
     * @static
     * @memberOf _
     * @category Chaining
     * @param {*} value The value to provide to `interceptor`.
     * @param {Function} interceptor The function to invoke.
     * @returns {*} Returns `value`.
     * @example
     *
     * _([1, 2, 3, 4])
     *  .tap(function(array) { array.pop(); })
     *  .reverse()
     *  .value();
     * // => [3, 2, 1]
     */
    function tap(value, interceptor) {
      interceptor(value);
      return value;
    }

    /**
     * Enables explicit method chaining on the wrapper object.
     *
     * @name chain
     * @memberOf _
     * @category Chaining
     * @returns {*} Returns the wrapper object.
     * @example
     *
     * var characters = [
     *   { 'name': 'barney', 'age': 36 },
     *   { 'name': 'fred',   'age': 40 }
     * ];
     *
     * // without explicit chaining
     * _(characters).first();
     * // => { 'name': 'barney', 'age': 36 }
     *
     * // with explicit chaining
     * _(characters).chain()
     *   .first()
     *   .pick('age')
     *   .value();
     * // => { 'age': 36 }
     */
    function wrapperChain() {
      this.__chain__ = true;
      return this;
    }

    /**
     * Produces the `toString` result of the wrapped value.
     *
     * @name toString
     * @memberOf _
     * @category Chaining
     * @returns {string} Returns the string result.
     * @example
     *
     * _([1, 2, 3]).toString();
     * // => '1,2,3'
     */
    function wrapperToString() {
      return String(this.__wrapped__);
    }

    /**
     * Extracts the wrapped value.
     *
     * @name valueOf
     * @memberOf _
     * @alias value
     * @category Chaining
     * @returns {*} Returns the wrapped value.
     * @example
     *
     * _([1, 2, 3]).valueOf();
     * // => [1, 2, 3]
     */
    function wrapperValueOf() {
      return this.__wrapped__;
    }

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

    // add functions that return wrapped values when chaining
    lodash.after = after;
    lodash.assign = assign;
    lodash.at = at;
    lodash.bind = bind;
    lodash.bindAll = bindAll;
    lodash.bindKey = bindKey;
    lodash.chain = chain;
    lodash.compact = compact;
    lodash.compose = compose;
    lodash.constant = constant;
    lodash.countBy = countBy;
    lodash.create = create;
    lodash.createCallback = createCallback;
    lodash.curry = curry;
    lodash.debounce = debounce;
    lodash.defaults = defaults;
    lodash.defer = defer;
    lodash.delay = delay;
    lodash.difference = difference;
    lodash.filter = filter;
    lodash.flatten = flatten;
    lodash.forEach = forEach;
    lodash.forEachRight = forEachRight;
    lodash.forIn = forIn;
    lodash.forInRight = forInRight;
    lodash.forOwn = forOwn;
    lodash.forOwnRight = forOwnRight;
    lodash.functions = functions;
    lodash.groupBy = groupBy;
    lodash.indexBy = indexBy;
    lodash.initial = initial;
    lodash.intersection = intersection;
    lodash.invert = invert;
    lodash.invoke = invoke;
    lodash.keys = keys;
    lodash.map = map;
    lodash.mapValues = mapValues;
    lodash.max = max;
    lodash.memoize = memoize;
    lodash.merge = merge;
    lodash.min = min;
    lodash.omit = omit;
    lodash.once = once;
    lodash.pairs = pairs;
    lodash.partial = partial;
    lodash.partialRight = partialRight;
    lodash.pick = pick;
    lodash.pluck = pluck;
    lodash.property = property;
    lodash.pull = pull;
    lodash.range = range;
    lodash.reject = reject;
    lodash.remove = remove;
    lodash.rest = rest;
    lodash.shuffle = shuffle;
    lodash.sortBy = sortBy;
    lodash.tap = tap;
    lodash.throttle = throttle;
    lodash.times = times;
    lodash.toArray = toArray;
    lodash.transform = transform;
    lodash.union = union;
    lodash.uniq = uniq;
    lodash.values = values;
    lodash.where = where;
    lodash.without = without;
    lodash.wrap = wrap;
    lodash.xor = xor;
    lodash.zip = zip;
    lodash.zipObject = zipObject;

    // add aliases
    lodash.collect = map;
    lodash.drop = rest;
    lodash.each = forEach;
    lodash.eachRight = forEachRight;
    lodash.extend = assign;
    lodash.methods = functions;
    lodash.object = zipObject;
    lodash.select = filter;
    lodash.tail = rest;
    lodash.unique = uniq;
    lodash.unzip = zip;

    // add functions to `lodash.prototype`
    mixin(lodash);

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

    // add functions that return unwrapped values when chaining
    lodash.clone = clone;
    lodash.cloneDeep = cloneDeep;
    lodash.contains = contains;
    lodash.escape = escape;
    lodash.every = every;
    lodash.find = find;
    lodash.findIndex = findIndex;
    lodash.findKey = findKey;
    lodash.findLast = findLast;
    lodash.findLastIndex = findLastIndex;
    lodash.findLastKey = findLastKey;
    lodash.has = has;
    lodash.identity = identity;
    lodash.indexOf = indexOf;
    lodash.isArguments = isArguments;
    lodash.isArray = isArray;
    lodash.isBoolean = isBoolean;
    lodash.isDate = isDate;
    lodash.isElement = isElement;
    lodash.isEmpty = isEmpty;
    lodash.isEqual = isEqual;
    lodash.isFinite = isFinite;
    lodash.isFunction = isFunction;
    lodash.isNaN = isNaN;
    lodash.isNull = isNull;
    lodash.isNumber = isNumber;
    lodash.isObject = isObject;
    lodash.isPlainObject = isPlainObject;
    lodash.isRegExp = isRegExp;
    lodash.isString = isString;
    lodash.isUndefined = isUndefined;
    lodash.lastIndexOf = lastIndexOf;
    lodash.mixin = mixin;
    lodash.noConflict = noConflict;
    lodash.noop = noop;
    lodash.now = now;
    lodash.parseInt = parseInt;
    lodash.random = random;
    lodash.reduce = reduce;
    lodash.reduceRight = reduceRight;
    lodash.result = result;
    lodash.runInContext = runInContext;
    lodash.size = size;
    lodash.some = some;
    lodash.sortedIndex = sortedIndex;
    lodash.template = template;
    lodash.unescape = unescape;
    lodash.uniqueId = uniqueId;

    // add aliases
    lodash.all = every;
    lodash.any = some;
    lodash.detect = find;
    lodash.findWhere = find;
    lodash.foldl = reduce;
    lodash.foldr = reduceRight;
    lodash.include = contains;
    lodash.inject = reduce;

    mixin(function() {
      var source = {}
      forOwn(lodash, function(func, methodName) {
        if (!lodash.prototype[methodName]) {
          source[methodName] = func;
        }
      });
      return source;
    }(), false);

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

    // add functions capable of returning wrapped and unwrapped values when chaining
    lodash.first = first;
    lodash.last = last;
    lodash.sample = sample;

    // add aliases
    lodash.take = first;
    lodash.head = first;

    forOwn(lodash, function(func, methodName) {
      var callbackable = methodName !== 'sample';
      if (!lodash.prototype[methodName]) {
        lodash.prototype[methodName]= function(n, guard) {
          var chainAll = this.__chain__,
              result = func(this.__wrapped__, n, guard);

          return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
            ? result
            : new lodashWrapper(result, chainAll);
        };
      }
    });

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

    /**
     * The semantic version number.
     *
     * @static
     * @memberOf _
     * @type string
     */
    lodash.VERSION = '2.4.2';

    // add "Chaining" functions to the wrapper
    lodash.prototype.chain = wrapperChain;
    lodash.prototype.toString = wrapperToString;
    lodash.prototype.value = wrapperValueOf;
    lodash.prototype.valueOf = wrapperValueOf;

    // add `Array` functions that return unwrapped values
    forEach(['join', 'pop', 'shift'], function(methodName) {
      var func = arrayRef[methodName];
      lodash.prototype[methodName] = function() {
        var chainAll = this.__chain__,
            result = func.apply(this.__wrapped__, arguments);

        return chainAll
          ? new lodashWrapper(result, chainAll)
          : result;
      };
    });

    // add `Array` functions that return the existing wrapped value
    forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
      var func = arrayRef[methodName];
      lodash.prototype[methodName] = function() {
        func.apply(this.__wrapped__, arguments);
        return this;
      };
    });

    // add `Array` functions that return new wrapped values
    forEach(['concat', 'slice', 'splice'], function(methodName) {
      var func = arrayRef[methodName];
      lodash.prototype[methodName] = function() {
        return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
      };
    });

    return lodash;
  }

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

  // expose Lo-Dash
  var _ = runInContext();

  // some AMD build optimizers like r.js check for condition patterns like the following:
  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
    // Expose Lo-Dash to the global object even when an AMD loader is present in
    // case Lo-Dash is loaded with a RequireJS shim config.
    // See http://requirejs.org/docs/api.html#config-shim
    root._ = _;

    // define as an anonymous module so, through path mapping, it can be
    // referenced as the "underscore" module
    define(function() {
      return _;
    });
  }
  // check for `exports` after `define` in case a build optimizer adds an `exports` object
  else if (freeExports && freeModule) {
    // in Node.js or RingoJS
    if (moduleExports) {
      (freeModule.exports = _)._ = _;
    }
    // in Narwhal or Rhino -require
    else {
      freeExports._ = _;
    }
  }
  else {
    // in a browser or Rhino
    root._ = _;
  }
}.call(this));

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{}],15:[function(require,module,exports){
(function (root, factory) {
		"use strict";

		if (typeof exports === 'object') {
			module.exports = factory();
		} else if (typeof define === 'function' && define.amd) {
			define(factory);
		} else {
			root.UltraDeepClone = factory();
		}
	}(this, function () {

		var functionPropertyFilter = [
			"caller",
			"arguments"
		];

		// Node.js has a lot of silly enumeral properties on its "TypedArray" implementation
		var typedArrayPropertyFilter = [
			'BYTES_PER_ELEMENT',
			'get',
			'set',
			'slice',
			'subarray',
			'buffer',
			'length',
			'byteOffset',
			'byteLength'
		];

		var primitiveCloner  = makeCloner(clonePrimitive);
		var typedArrayCloner = makeRecursiveCloner(makeCloner(cloneTypedArray), typedArrayPropertyFilter);

		function typeString (type) {
			return '[object ' + type + ']';
		}

		var cloneFunctions = {};

		cloneFunctions[typeString('RegExp')] = makeCloner(cloneRegExp);
		cloneFunctions[typeString('Date')] = makeCloner(cloneDate);
		cloneFunctions[typeString('Function')] = makeRecursiveCloner(makeCloner(cloneFunction), functionPropertyFilter);
		cloneFunctions[typeString('Object')] = makeRecursiveCloner(makeCloner(cloneObject));
		cloneFunctions[typeString('Array')] = makeRecursiveCloner(makeCloner(cloneArray));

		['Null', 'Undefined', 'Number', 'String', 'Boolean']
			.map(typeString)
			.forEach(function (type) {
				cloneFunctions[type] = primitiveCloner;
			});

		['Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array',
		 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array']
			.map(typeString)
			.forEach(function (type) {
				cloneFunctions[type] = typedArrayCloner;
			});

		function makeArguments (numberOfArgs) {
			var letters = [];
			for ( var i = 1; i <= numberOfArgs; i++ ) letters.push("arg" + i);
			return letters;
		}

		function wrapFunctionWithArity (callback) {
			var argList = makeArguments(callback.length);
			var functionCode = 'return false || function ';
			functionCode += callback.name + '(';
			functionCode += argList.join(', ') + ') {\n';
			functionCode += 'return fn.apply(this, arguments);\n';
			functionCode += '};'

			return Function("fn", functionCode)(callback);
		}

		function makeCloner (cloneThing) {
			return function(thing, thingStack, copyStack) {
				thingStack.push(thing);
				var copy = cloneThing(thing);
				copyStack.push(copy);
				return copy;
			};
		}

		function clonePrimitive (primitive) {
			return primitive;
		}

		function cloneRegExp (regexp) {
			return new RegExp(regexp);
		}

		function cloneDate (date) {
			return new Date(date.getTime());
		}

		// We can't really clone functions but we can wrap them in a new function that will
		// recieve clones of any properties the original function may have had
		function cloneFunction (fn) {
			return wrapFunctionWithArity(fn);
		}

		// This will not properly clone `constructed` objects because
		// it is impossible to know with what arguments the constructor
		// was originally invoked.
		function cloneObject (object) {
			return Object.create(Object.getPrototypeOf(object));
		}

		function cloneArray (array) {
			return [];
		}

		function cloneTypedArray (typedArray) {
			var len = typedArray.length;
			return new typedArray.constructor(len);
		}

		function makeRecursiveCloner (cloneThing, propertyFilter) {
			return function(thing, thingStack, copyStack) {
				var clone = this;

				return Object.getOwnPropertyNames(thing)
					.filter(function(prop){
						return !propertyFilter || propertyFilter.indexOf(prop) === -1;
					})
					.reduce(function(copy, prop) {
						var thingOffset = thingStack.indexOf(thing[prop]);

						if (thingOffset === -1) {
							copy[prop] = clone(thing[prop]);
						} else {
							copy[prop] = copyStack[thingOffset];
						}

						return copy;
					}, cloneThing(thing, thingStack, copyStack));
			};
		}

		return function _ultraDeepClone (source) {

			var thingStack = [];
			var copyStack = [];

			function clone (thing) {
				var typeOfThing = Object.prototype.toString.call(thing);
				return cloneFunctions[typeOfThing].call(clone, thing, thingStack, copyStack);
			};

			return clone(source);
		};
}));

},{}],16:[function(require,module,exports){
module.exports = extend

function extend() {
    var target = {}

    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i]

        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key]
            }
        }
    }

    return target
}

},{}],17:[function(require,module,exports){
WYMeditor.EXTERNAL_MODULES.ObjectHistory = require("object-history");

},{"object-history":1}]},{},[17])(17)
});
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9ncnVudC1icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJub2RlX21vZHVsZXMvb2JqZWN0LWhpc3RvcnkvbGliL2luZGV4LmpzIiwibm9kZV9tb2R1bGVzL29iamVjdC1oaXN0b3J5L2xpYi9wcm90b3R5cGUvYWRkLmpzIiwibm9kZV9tb2R1bGVzL29iamVjdC1oaXN0b3J5L2xpYi9wcm90b3R5cGUvYmFja3dhcmQuanMiLCJub2RlX21vZHVsZXMvb2JqZWN0LWhpc3RvcnkvbGliL3Byb3RvdHlwZS9mb3JnZXQtYWxsLWJhY2t3YXJkLmpzIiwibm9kZV9tb2R1bGVzL29iamVjdC1oaXN0b3J5L2xpYi9wcm90b3R5cGUvZm9yZ2V0LWFsbC1mb3J3YXJkLmpzIiwibm9kZV9tb2R1bGVzL29iamVjdC1oaXN0b3J5L2xpYi9wcm90b3R5cGUvZm9yZ2V0LWFsbC1pbi1kaXJlY3Rpb24uanMiLCJub2RlX21vZHVsZXMvb2JqZWN0LWhpc3RvcnkvbGliL3Byb3RvdHlwZS9mb3J3YXJkLmpzIiwibm9kZV9tb2R1bGVzL29iamVjdC1oaXN0b3J5L2xpYi9wcm90b3R5cGUvZ2V0LmpzIiwibm9kZV9tb2R1bGVzL29iamVjdC1oaXN0b3J5L2xpYi9wcm90b3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ge307XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGlmIChpIDwgbGVuIC0gMSkge1xuICAgICAgICAgICAgICBwdHIgPSBwdHJbcHJvcF07XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICBwdHJbcHJvcF0gPSBjaC52YWx1ZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9KTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBvYmogPSBjaC52YWx1ZTtcbiAgICAgICAgfVxuICAgICAgICBicmVhaztcblxuICAgICAgY2FzZSAnZGVsJzpcbiAgICAgICAgcHRyID0gb2JqO1xuICAgICAgICBrZXlzID0gY2gua2V5O1xuICAgICAgICBsZW4gPSBrZXlzLmxlbmd0aDtcbiAgICAgICAgaWYgKGxlbikge1xuICAgICAgICAgIGtleXMuZm9yRWFjaChmdW5jdGlvbiAocHJvcCwgaSkge1xuICAgICAgICAgICAgaWYgKCEocHJvcCBpbiBwdHIpKSB7XG4gICAgICAgICAgICAgIHB0cltwcm9wXSA9IHt9O1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBpZiAoaSA8IGxlbiAtIDEpIHtcbiAgICAgICAgICAgICAgcHRyID0gcHRyW3Byb3BdO1xuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgZGVsZXRlIHB0cltwcm9wXTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9KTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBvYmogPSBudWxsO1xuICAgICAgICB9XG4gICAgICAgIGJyZWFrO1xuICAgIH1cbiAgfSk7XG4gIHJldHVybiBvYmo7XG59XG4iLCIvLyAgICAgVW5kZXJzY29yZS5qcyAxLjQuNFxuLy8gICAgIGh0dHA6Ly91bmRlcnNjb3JlanMub3JnXG4vLyAgICAgKGMpIDIwMDktMjAxMyBKZXJlbXkgQXNoa2VuYXMsIERvY3VtZW50Q2xvdWQgSW5jLlxuLy8gICAgIFVu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JpbmREYXRhKTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIC8vIGV4aXQgZWFybHkgaWYgdGhlcmUgYXJlIG5vIGB0aGlzYCByZWZlcmVuY2VzIG9yIGBmdW5jYCBpcyBib3VuZFxuICAgICAgaWYgKGJpbmREYXRhID09PSBmYWxzZSB8fCAoYmluZERhdGEgIT09IHRydWUgJiYgYmluZERhdGFbMV0gJiAxKSkge1xuICAgICAgICByZXR1cm4gZnVuYztcbiAgICAgIH1cbiAgICAgIHN3aXRjaCAoYXJnQ291bnQpIHtcbiAgICAgICAgY2FzZSAxOiByZXR1cm4gZnVuY3Rpb24odmFsdWUpIHtcbiAgICAgICAgICByZXR1cm4gZnVuYy5jYWxsKHRoaXNBcmcsIHZhbHVlKTtcbiAgICAgICAgfTtcbiAgICAgICAgY2FzZSAyOiByZXR1cm4gZnVuY3Rpb24oYSwgYikge1xuICAgICAgICAgIHJldHVybiBmdW5jLmNhbGwodGhpc0FyZywgYSwgYik7XG4gICAgICAgIH07XG4gICAgICAgIGNhc2UgMzogcmV0dXJuIGZ1bmN0aW9uKHZhbHVlLCBpbmRleCwgY29sbGVjdGlvbikge1xuICAgICAgICAgIHJldHVybiBmdW5jLmNhbGwodGhpc0FyZywgdmFsdWUsIGluZGV4LCBjb2xsZWN0aW9uKTtcbiAgICAgICAgfTtcbiAgICAgICAgY2FzZSA0OiByZXR1cm4gZnVuY3Rpb24oYWNjdW11bGF0b3IsIHZhbHVlLCBpbmRleCwgY29sbGVjdGlvbikge1xuICAgICAgICAgIHJldHVybiBmdW5jLmNhbGwodGhpc0FyZywgYWNjdW11bGF0b3IsIHZhbHVlLCBpbmRleCwgY29sbGVjdGlvbik7XG4gICAgICAgIH07XG4gICAgICB9XG4gICAgICByZXR1cm4gYmluZChmdW5jLCB0aGlzQXJnKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUaGUgYmFzZSBpbXBsZW1lbnRhdGlvbiBvZiBgY3Jl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gICAgaWYgKHBhcnRpYWxSaWdodEFyZ3MgfHwgaXNDdXJyeSkge1xuICAgICAgICAgIGFyZ3MgfHwgKGFyZ3MgPSBzbGljZShhcmd1bWVudHMpKTtcbiAgICAgICAgICBpZiAocGFydGlhbFJpZ2h0QXJncykge1xuICAgICAgICAgICAgcHVzaC5hcHBseShhcmdzLCBwYXJ0aWFsUmlnaHRBcmdzKTtcbiAgICAgICAgICB9XG4gICAgICAgICAgaWYgKGlzQ3VycnkgJiYgYXJncy5sZW5ndGggPCBhcml0eSkge1xuICAgICAgICAgICAgYml0bWFzayB8PSAxNiAmIH4zMjtcbiAgICAgICAgICAgIHJldHVybiBiYXNlQ3JlYXRlV3JhcHBlcihbZnVuYywgKGlzQ3VycnlCb3VuZCA/IGJpdG1hc2sgOiBiaXRtYXNrICYgfjMpLCBhcmdzLCBudWxsLCB0aGlzQXJnLCBhcml0eV0pO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBhcmdzIHx8IChhcmdzID0gYXJndW1lbnRzKTtcbiAgICAgICAgaWYgKGlzQmluZEtleSkge1xuICAgICAgICAgIGZ1bmMgPSB0aGlzQmluZGluZ1trZXldO1xuICAgICAgICB9XG4gICAgICAgIGlmICh0aGlzIGluc3RhbmNlb2YgYm91bmQpIHtcbiAgICAgICAgICB0aGlzQmluZGluZyA9IGJhc2VDcmVhdGUoZnVuYy5wcm90b3R5cGUpO1xuICAgICAgICAgIHZhciByZXN1bHQgPSBmdW5jLmFwcGx5KHRoaXNCaW5kaW5nLCBhcmdzKTtcbiAgICAgICAgICByZXR1cm4gaXNPYmplY3QocmVzdWx0KSA/IHJlc3VsdCA6IHRoaXNCaW5kaW5nO1xuICAgICAgICB9XG4gICAgICAgIHJldHVybiBmdW5jLmFwcGx5KHRoaXNCaW5kaW5nLCBhcmdzKTtcbiAgICAgIH1cbiAgICAgIHNldEJpbmREYXRhKGJvdW5kLCBiaW5kRGF0YSk7XG4gICAgICByZXR1cm4gYm91bmQ7XG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gc3RhY2tCKSk7XG4gICAgICAgICAgfVxuICAgICAgICB9KTtcblxuICAgICAgICBpZiAocmVzdWx0ICYmICFpc1doZXJlKSB7XG4gICAgICAgICAgLy8gZW5zdXJlIGJvdGggb2JqZWN0cyBoYXZlIHRoZSBzYW1lIG51bWJlciBvZiBwcm9wZXJ0aWVzXG4gICAgICAgICAgZm9ySW4oYSwgZnVuY3Rpb24odmFsdWUsIGtleSwgYSkge1xuICAgICAgICAgICAgaWYgKGhhc093blByb3BlcnR5LmNhbGwoYSwga2V5KSkge1xuICAgICAgICAgICAgICAvLyBgc2l6ZWAgd2lsbCBiZSBgLTFgIGlmIGBhYCBoYXMgbW9yZSBwcm9wZXJ0aWVzIHRoYW4gYGJgXG4gICAgICAgICAgICAgIHJldHVybiAocmVzdWx0ID0gLS1zaXplID4gLTEpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgICBzdGFja0EucG9wKCk7XG4gICAgICBzdGFja0IucG9wKCk7XG5cbiAgICAgIGlmIChpbml0ZWRTdGFjaykge1xuICAgICAgICByZWxlYXNlQXJyYXkoc3RhY2tBKTtcbiAgICAgICAgcmVsZWFzZUFycmF5KHN0YWNrQik7XG4gICAgICB9XG4gICAgICByZXR1cm4gcmVzdWx0O1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRoZSBiYXNlIGltcGxlbWVudGF0aW9uIG9mIGBfLm1lcmdlYCB3aXRob3V0IGFyZ3VtZW50IGp1Z2dsaW5nIG9yIHN1cHBvcnRcbiAgICAgKiBmb3IgYHRoaXNBcmdgIGJpbmRpbmcuXG4gICAgICpcbiAgICAgKiBAcHJpdmF0ZVxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSBvYmplY3QgVGhlIGRlc3RpbmF0aW9uIG9iamVjdC5cbiAgICAgKiBAcGFyYW0ge09iamVjdH0gc291cmNlIFRoZSBzb3VyY2Ugb2JqZWN0LlxuICAgICAqIEBwYXJhbS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fVxuICAgICAgICAgIH1cbiAgICAgICAgICBpZiAoIWZvdW5kKSB7XG4gICAgICAgICAgICB2YXIgaXNTaGFsbG93O1xuICAgICAgICAgICAgaWYgKGNhbGxiYWNrKSB7XG4gICAgICAgICAgICAgIHJlc3VsdCA9IGNhbGxiYWNrKHZhbHVlLCBzb3VyY2UpO1xuICAgICAgICAgICAgICBpZiAoKGlzU2hhbGxvdyA9IHR5cGVvZiByZXN1bHQgIT0gJ3VuZGVmaW5lZCcpKSB7XG4gICAgICAgICAgICAgICAgdmFsdWUgPSByZXN1bHQ7XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGlmICghaXNTaGFsbG93KSB7XG4gICAgICAgICAgICAgIHZhbHVlID0gaXNBcnJcbiAgICAgICAgICAgICAgICA/IChpc0FycmF5KHZhbHVlKSA/IHZhbHVlIDogW10pXG4gICAgICAgICAgICAgICAgOiAoaXNQbGFpbk9iamVjdCh2YWx1ZSkgPyB2YWx1ZSA6IHt9KTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIC8vIGFkZCBgc291cmNlYCBhbmQgYXNzb2NpYXRlZCBgdmFsdWVgIHRvIHRoZSBzdGFjayBvZiB0cmF2ZXJzZWQgb2JqZWN0c1xuICAgICAgICAgICAgc3RhY2tBLnB1c2goc291cmNlKTtcbiAgICAgICAgICAgIHN0YWNrQi5wdXNoKHZhbHVlKTtcblxuICAgICAgICAgICAgLy8gcmVjdXJzaXZlbHkgbWVyZ2Ugb2JqZWN0cyBhbmQgYXJyYXlzIChzdXNjZXB0aWJsZSB0byBjYWxsIHN0YWNrIGxpbWl0cylcbiAgICAgICAgICAgIGlmICghaXNTaGFsbG93KSB7XG4gICAgICAgICAgICAgIGJhc2VNZXJnZSh2YWx1ZSwgc291cmNlLCBjYWxsYmFjaywgc3RhY2tBLCBzdGFja0IpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBlbHNlI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ICAgIGlmIChpc1BhcnRpYWxSaWdodCAmJiAhcGFydGlhbFJpZ2h0QXJncy5sZW5ndGgpIHtcbiAgICAgICAgYml0bWFzayAmPSB+MzI7XG4gICAgICAgIGlzUGFydGlhbFJpZ2h0ID0gcGFydGlhbFJpZ2h0QXJncyA9IGZhbHNlO1xuICAgICAgfVxuICAgICAgdmFyIGJpbmREYXRhID0gZnVuYyAmJiBmdW5jLl9fYmluZERhdGFfXztcbiAgICAgIGlmIChiaW5kRGF0YSAmJiBiaW5kRGF0YSAhPT0gdHJ1ZSkge1xuICAgICAgICAvLyBjbG9uZSBgYmluZERhdGFgXG4gICAgICAgIGJpbmREYXRhID0gc2xpY2UoYmluZERhdGEpO1xuICAgICAgICBpZiAoYmluZERhdGFbMl0pIHtcbiAgICAgICAgICBiaW5kRGF0YVsyXSA9IHNsaWNlKGJpbmREYXRhWzJdKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAoYmluZERhdGFbM10pIHtcbiAgICAgICAgICBiaW5kRGF0YVszXSA9IHNsaWNlKGJpbmREYXRhWzNdKTtcbiAgICAgICAgfVxuICAgICAgICAvLyBzZXQgYHRoaXNCaW5kaW5nYCBpcyBub3QgcHJldmlvdXNseSBib3VuZFxuICAgICAgICBpZiAoaXNCaW5kICYmICEoYmluZERhdGFbMV0gJiAxKSkge1xuICAgICAgICAgIGJpbmREYXRhWzRdID0gdGhpc0FyZztcbiAgICAgICAgfVxuICAgICAgICAvLyBzZXQgaWYgcHJldmlvdXNseSBib3VuZCBidXQgbm90IGN1cnJlbnRseSAoc3Vic2VxdWVudCBjdXJyaWVkIGZ1bmN0aW9ucylcbiAgICAgICAgaWYgKCFpc0JpbmQgJiYgYmluZERhdGFbMV0gJiAxKSB7XG4gICAgICAgICAgYml0bWFzayB8PSA4O1xuICAgICAgICB9XG4gICAgICAgIC8vIHNldCBjdXJyaWVkIGFyaXR5IGlmIG5vdCB5ZXQgc2V0XG4gICAgICAgIGlmIChpc0N1cnJ5ICYmICEoYm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4gICAgICogQHBhcmFtIHsqfSBbdGhpc0FyZ10gVGhlIGB0aGlzYCBiaW5kaW5nIG9mIGBjYWxsYmFja2AuXG4gICAgICogQHJldHVybnMge0FycmF5fSBSZXR1cm5zIGEgbmV3IGFycmF5IG9mIHJlbW92ZWQgZWxlbWVudHMuXG4gICAgICogQGV4YW1wbGVcbiAgICAgKlxuICAgICAqIHZhciBhcnJheSA9IFsxLCAyLCAzLCA0LCA1LCA2XTtcbiAgICAgKiB2YXIgZXZlbnMgPSBfLnJlbW92ZShhcnJheSwgZnVuY3Rpb24obnVtKSB7IHJldHVybiBudW0gJSAyID09IDA7IH0pO1xuICAgICAqXG4gICAgICogY29uc29sZS5sb2coYXJyYXkpO1xuICAgICAqIC8vID0+IFsxLCAzLCA1XVxuICAgICAqXG4gICAgICogY29uc29sZS5sb2coZXZlbnMpO1xuICAgICAqIC8vID0+IFsyLCA0LCA2XVxuICAgICAqL1xuICAgIGZ1bmN0aW9uIHJlbW92ZShhcnJheSwgY2FsbGJhY2ssIHRoaXNBcmcpIHtcbiAgICAgIHZhciBpbmRleCA9IC0xLFxuICAgICAgICAgIGxlbmd0aCA9IGFycmF5ID8gYXJyYXkubGVuZ3RoIDogMCxcbiAgICAgICAgICByZXN1bHQgPSBbXTtcblxuICAgICAgY2FsbGJhY2sgPSBsb2Rhc2guY3JlYXRlQ2FsbGJhY2soY2FsbGJhY2ssIHRoaXNBcmcsIDMpO1xuICAgICAgd2hpbGUgKCsraW5kZXggPCBsZW5ndGgpIHtcbiAgICAgICAgdmFyIHZhbHVlID0gYXJyYXlbaW5kZXhdO1xuICAgICAgICBpZiAoY2FsbGJhY2sodmFsdWUsIGluZGV4LCBhcnJheSkpIHtcbiAgICAgICAgICByZXN1bHQucHVzaCh2YWx1ZSk7XG4gICAgICAgICAgc3BsaWNlLmNhbGwoYXJyYXksIGluZGV4LS0sIDEpO1xuICAgICAgICAgIGxlbmd0aC0tO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgICByZX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gICBsYXN0Q2FsbGVkID0gbm93KCk7XG4gICAgICAgICAgICByZXN1bHQgPSBmdW5jLmFwcGx5KHRoaXNBcmcsIGFyZ3MpO1xuICAgICAgICAgICAgaWYgKCF0aW1lb3V0SWQgJiYgIW1heFRpbWVvdXRJZCkge1xuICAgICAgICAgICAgICBhcmdzID0gdGhpc0FyZyA9IG51bGw7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIHRpbWVvdXRJZCA9IHNldFRpbWVvdXQoZGVsYXllZCwgcmVtYWluaW5nKTtcbiAgICAgICAgfVxuICAgICAgfTtcblxuICAgICAgdmFyIG1heERlbGF5ZWQgPSBmdW5jdGlvbigpIHtcbiAgICAgICAgaWYgKHRpbWVvdXRJZCkge1xuICAgICAgICAgIGNsZWFyVGltZW91dCh0aW1lb3V0SWQpO1xuICAgICAgICB9XG4gICAgICAgIG1heFRpbWVvdXRJZCA9IHRpbWVvdXRJZCA9IHRyYWlsaW5nQ2FsbCA9IHVuZGVmaW5lZDtcbiAgICAgICAgaWYgKHRyYWlsaW5nIHx8IChtYXhXYWl0ICE9PSB3YWl0KSkge1xuICAgICAgICAgIGxhc3RDYWxsZWQgPSBub3coKTtcbiAgICAgICAgICByZXN1bHQgPSBmdW5jLmFwcGx5KHRoaXNBcmcsIGFyZ3MpO1xuICAgICAgICAgIGlmICghdGltZW91dElkICYmICFtYXhUaW1lb3V0SWQpIHtcbiAgICAgICAgICAgIGFyZ3MgPSB0aGlzQXJnID0gbnVsbDtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH07XG5cbiAgICAgIHJldHVybiBmdW5jdGlvbigpIHtcbiAgICAgICAgYXJncyA9IGFyZ3VtZW50cztcbiAgICAgICAgc3RhbXAgPSBub3coKTtcbiAgICAgICAgdGhpc0FyZyA9IHRoaXM7XG4gICAgICAgIHRyYWlsaW5nQ2FsbCA9IHRyYWlsaW5nICYmICh0aW1lb3V0SWQgfHwgIWxlYWRpbmcpO1xuXG4gICAgICAgIGlmIChtYXhXYWl0ID09PSBmYWxzZSkge1xuICAgICAgICAgIHZhciBsZWFkaW5nQ2FsbCA9IGxlYWRpbmcgJiYgIXRpbWVvdXRJZDtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBpZiAoIW1heFRpbWVvdXRJZCAmJiAhbGVhZGluZykge1xuICAgICAgICAgICAgbGFzdENhbGxlZCA9IHN0YW1wO1xuICAgICAgICAgIH1cbiAgICAgICAgICB2YXIgcmVtYWluaW5nID0gbWF4V2FpdCAtIChzdGFtcCAtIGxhc3RDYWxsZWQpLFxuICAgICAgICAgICAgICBpc0NhbGxlZCA9IHJlbWFpbmluZyA8PSAwO1xuXG4gICAgICAgICAgaWYgKGlzQ2FsbGVkKSB7XG4gICAgICAgICAgICBpZiAobWF4VGltZW91dElkKSB7XG4gICAgICAgICAgICAgIG1heFRpbWVvdXRJZCA9IGNsZWFyVGltZW91dChtYXhUaW1lb3V0SWQpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgbGFzdENhbGxlZCA9IHN0YW1wO1xuICAgICAgICAgICAgcmVzdWx0ID0gZnVuYy5hcHBseSh0aGlzQXJnLCBhcmdzKTtcbiAgICAgICAgICB9XG4gICAgICAgICAgZWxzZSBpZiAoIW1heFRpbWVvdXRJZCkge1xuICAgICAgICAgICAgbWF4VGltZW91dElkID0gc2V0VGltZW91dChtYXhEZWxheWVkLCByZW1haW5pbmcpO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBpZiAoaXNDYWxsZWQgJiYgdGltZW91dElkKSB7XG4gICAgICAgICAgdGltZW91dElkID0gY2xlYXJUaW1lb3V0KHRpbWVvdXRJZCk7XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoIXRpbWVvdXRJZCAmJiB3YWl0ICE9PSBtYXhXYWl0KSB7XG4gICAgICAgICAgdGltZW91dElkID0gc2V0VGltZW91dChkZWxheWVkLCB3YWl0K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XygnZnJlZCcpLmNhcGl0YWxpemUoKTtcbiAgICAgKiAvLyA9PiAnRnJlZCdcbiAgICAgKi9cbiAgICBmdW5jdGlvbiBtaXhpbihvYmplY3QsIHNvdXJjZSwgb3B0aW9ucykge1xuICAgICAgdmFyIGNoYWluID0gdHJ1ZSxcbiAgICAgICAgICBtZXRob2ROYW1lcyA9IHNvdXJjZSAmJiBmdW5jdGlvbnMoc291cmNlKTtcblxuICAgICAgaWYgKCFzb3VyY2UgfHwgKCFvcHRpb25zICYmICFtZXRob2ROYW1lcy5sZW5ndGgpKSB7XG4gICAgICAgIGlmIChvcHRpb25zID09IG51bGwpIHtcbiAgICAgICAgICBvcHRpb25zID0gc291cmNlO1xuICAgICAgICB9XG4gICAgICAgIGN0b3IgPSBsb2Rhc2hXcmFwcGVyO1xuICAgICAgICBzb3VyY2UgPSBvYmplY3Q7XG4gICAgICAgIG9iamVjdCA9IGxvZGFzaDtcbiAgICAgICAgbWV0aG9kTmFtZXMgPSBmdW5jdGlvbnMoc291cmNlKTtcbiAgICAgIH1cbiAgICAgIGlmIChvcHRpb25zID09PSBmYWxzZSkge1xuICAgICAgICBjaGFpbiA9IGZhbHNlO1xuICAgICAgfSBlbHNlIGlmIChpc09iamVjdChvcHRpb25zKSAmJiAnY2hhaW4nIGluIG9wdGlvbnMpIHtcbiAgICAgICAgY2hhaW4gPSBvcHRpb25zLmNoYWluO1xuICAgICAgfVxuICAgICAgdmFyIGN0b3IgPSBvYmplY3QsXG4gICAgICAgICAgaXNGdW5jID0gaXNGdW5jdGlvbihjdG9yKTtcblxuICAgICAgZm9yRWFjaChtZXRob2ROYW1lcywgZnVuY3Rpb24obWV0aG9kTmFtZSkge1xuICAgICAgICB2YXIgZnVuYyA9IG9iamVjdFttZXRob2ROYW1lXSA9IHNvdXJjZVttZXRob2ROYW1lXTtcbiAgICAgICAgaWYgKGlzRnVuYykge1xuICAgICAgICAgIGN0b3IucHJvdG90eXBlW21ldGhvZE5hbWVdID0gZnVuY3Rpb24oKSB7XG4gICAgICAgICAgICB2YXIgY2hhaW5BbGwgPSB0aGlzLl9fY2hhaW5fXyxcbiAgICAgICAgICAgICAgICB2YWx1ZSA9IHRoaXMuX193cmFwcGVkX18sXG4gICAgICAgICAgICAgICAgYXJncyA9IFt2YWx1ZV07XG5cbiAgICAgICAgICAgIHB1c2guYXBwbHkoYXJncywgYXJndW1lbnRzKTtcbiAgICAgICAgICAgIHZhciByZXN1bHQgPSBmdW5jLmFwcGx5KG9iamVjdCwgYXJncyk7XG4gICAgICAgICAgICBpZiAoY2hhaW4gfHwgY2hhaW5BbGwpIHtcbiAgICAgICAgICAgICAgaWYgKHZhbHVlID09PSByZXN1bHQgJiYgaXNPYmplY3QocmVzdWx0KSkge1xuICAgICAgICAgICAgICAgIHJldHVybiB0aGlzO1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgIHJlc3VsdCA9IG5ldyBjdG9yKHJlc3VsdCk7XG4gICAgICAgICAgICAgIHJlc3VsdC5fX2NoYWluX18gPSBjaGFpbkFsbDtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIHJldHVybiByZXN1bHQ7XG4gICAgICAgICAgfTtcbiAgICAgICAgfVxuICAgICAgfSk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogUmV2ZXJ0cyB0aGUgJ18nIHZhcmlhYmxlIHRvIGl0cyBwcmV2aW91cyB2YWx1ZSBhbmQgcmV0dXJucyBhIHJlZmVyZW5jZSB0b1xuICAgICAqIHRoZSBgbG9kYXNoYCBmdW5jdGlvbi5cbiAgICAgKlxuICAgICAqIEBzdGF0aWNcbiAgICAgKiBAbWVtYmVyT2YgX1xuICAgICAqIEBjYXRlZ29yeSBVdGlsaXRpZXNcbiAgICAgKiBAcmV0dXJucyB7RnVuY3Rpb259IFJldHVybnMgdGhlIGBsb2Rhc2hgIGZ1bmN0aW9uLlxuICAgICAqIEBleGFtcGxlXG4gICAgICpcbiAgICAgKiB2YXIgbG9kYXNoID0gXy5ub0N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bG9uZShzb3VyY2UpO1xyXG5cdFx0fTtcclxufSkpO1xyXG4iLCJtb2R1bGUuZXhwb3J0cyA9IGV4dGVuZFxuXG5mdW5jdGlvbiBleHRlbmQoKSB7XG4gICAgdmFyIHRhcmdldCA9IHt9XG5cbiAgICBmb3IgKHZhciBpID0gMDsgaSA8IGFyZ3VtZW50cy5sZW5ndGg7IGkrKykge1xuICAgICAgICB2YXIgc291cmNlID0gYXJndW1lbnRzW2ldXG5cbiAgICAgICAgZm9yICh2YXIga2V5IGluIHNvdXJjZSkge1xuICAgICAgICAgICAgaWYgKHNvdXJjZS5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICAgICAgICAgICAgdGFyZ2V0W2tleV0gPSBzb3VyY2Vba2V5XVxuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgfVxuXG4gICAgcmV0dXJuIHRhcmdldFxufVxuIiwiV1lNZWRpdG9yLkVYVEVSTkFMX01PRFVMRVMuT2JqZWN0SGlzdG9yeSA9IHJlcXVpcmUoXCJvYmplY3QtaGlzdG9yeVwiKTtcbiJdfQ==

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.foo = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

module.exports = function (element) {
  var self = this
  var Combokeys = self.constructor

  /**
   * a list of all the callbacks setup via Combokeys.bind()
   *
   * @type {Object}
   */
  self.callbacks = {}

  /**
   * direct map of string combinations to callbacks used for trigger()
   *
   * @type {Object}
   */
  self.directMap = {}

  /**
   * keeps track of what level each sequence is at since multiple
   * sequences can start out with the same sequence
   *
   * @type {Object}
   */
  self.sequenceLevels = {}

  /**
   * variable to store the setTimeout call
   *
   * @type {null|number}
   */
  self.resetTimer

  /**
   * temporary state where we will ignore the next keyup
   *
   * @type {boolean|string}
   */
  self.ignoreNextKeyup = false

  /**
   * temporary state where we will ignore the next keypress
   *
   * @type {boolean}
   */
  self.ignoreNextKeypress = false

  /**
   * are we currently inside of a sequence?
   * type of action ("keyup" or "keydown" or "keypress") or false
   *
   * @type {boolean|string}
   */
  self.nextExpectedAction = false

  self.element = element

  self.addEvents()

  Combokeys.instances.push(self)
  return self
}

module.exports.prototype.bind = require('./prototype/bind')
module.exports.prototype.bindMultiple = require('./prototype/bindMultiple')
module.exports.prototype.unbind = require('./prototype/unbind')
module.exports.prototype.trigger = require('./prototype/trigger')
module.exports.prototype.reset = require('./prototype/reset.js')
module.exports.prototype.stopCallback = require('./prototype/stopCallback')
module.exports.prototype.handleKey = require('./prototype/handleKey')
module.exports.prototype.addEvents = require('./prototype/addEvents')
module.exports.prototype.bindSingle = require('./prototype/bindSingle')
module.exports.prototype.getKeyInfo = require('./prototype/getKeyInfo')
module.exports.prototype.pickBestAction = require('./prototype/pickBestAction')
module.exports.prototype.getReverseMap = require('./prototype/getReverseMap')
module.exports.prototype.getMatches = require('./prototype/getMatches')
module.exports.prototype.resetSequences = require('./prototype/resetSequences')
module.exports.prototype.fireCallback = require('./prototype/fireCallback')
module.exports.prototype.bindSequence = require('./prototype/bindSequence')
module.exports.prototype.resetSequenceTimer = require('./prototype/resetSequenceTimer')
module.exports.prototype.detach = require('./prototype/detach')

module.exports.instances = []
module.exports.reset = require('./reset')

/**
 * variable to store the flipped version of MAP from above
 * needed to check if we should use keypress or not when no action
 * is specified
 *
 * @type {Object|undefined}
 */
module.exports.REVERSE_MAP = null

},{"./prototype/addEvents":2,"./prototype/bind":3,"./prototype/bindMultiple":4,"./prototype/bindSequence":5,"./prototype/bindSingle":6,"./prototype/detach":7,"./prototype/fireCallback":8,"./prototype/getKeyInfo":9,"./prototype/getMatches":10,"./prototype/getReverseMap":11,"./prototype/handleKey":12,"./prototype/pickBestAction":15,"./prototype/reset.js":16,"./prototype/resetSequenceTimer":17,"./prototype/resetSequences":18,"./prototype/stopCallback":19,"./prototype/trigger":20,"./prototype/unbind":21,"./reset":22}],2:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
module.exports = function () {
  var self = this
  var on = require('dom-event')
  var element = self.element

  self.eventHandler = require('./handleKeyEvent').bind(self)

  on(element, 'keypress', self.eventHandler)
  on(element, 'keydown', self.eventHandler)
  on(element, 'keyup', self.eventHandler)
}

},{"./handleKeyEvent":13,"dom-event":33}],3:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * binds an event to Combokeys
 *
 * can be a single key, a combination of keys separated with +,
 * an array of keys, or a sequence of keys separated by spaces
 *
 * be sure to list the modifier keys first to make sure that the
 * correct key ends up getting bound (the last key in the pattern)
 *
 * @param {string|Array} keys
 * @param {Function} callback
 * @param {string=} action - "keypress", "keydown", or "keyup"
 * @returns void
 */
module.exports = function (keys, callback, action) {
  var self = this

  keys = keys instanceof Array ? keys : [keys]
  self.bindMultiple(keys, callback, action)
  return self
}

},{}],4:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * binds multiple combinations to the same callback
 *
 * @param {Array} combinations
 * @param {Function} callback
 * @param {string|undefined} action
 * @returns void
 */
module.exports = function (combinations, callback, action) {
  var self = this

  for (var j = 0; j < combinations.length; ++j) {
    self.bindSingle(combinations[j], callback, action)
  }
}

},{}],5:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * binds a key sequence to an event
 *
 * @param {string} combo - combo specified in bind call
 * @param {Array} keys
 * @param {Function} callback
 * @param {string=} action
 * @returns void
 */
module.exports = function (combo, keys, callback, action) {
  var self = this

  // start off by adding a sequence level record for this combination
  // and setting the level to 0
  self.sequenceLevels[combo] = 0

  /**
   * callback to increase the sequence level for this sequence and reset
   * all other sequences that were active
   *
   * @param {string} nextAction
   * @returns {Function}
   */
  function increaseSequence (nextAction) {
    return function () {
      self.nextExpectedAction = nextAction
      ++self.sequenceLevels[combo]
      self.resetSequenceTimer()
    }
  }

  /**
   * wraps the specified callback inside of another function in order
   * to reset all sequence counters as soon as this sequence is done
   *
   * @param {Event} e
   * @returns void
   */
  function callbackAndReset (e) {
    var characterFromEvent
    self.fireCallback(callback, e, combo)

    // we should ignore the next key up if the action is key down
    // or keypress.  this is so if you finish a sequence and
    // release the key the final key will not trigger a keyup
    if (action !== 'keyup') {
      characterFromEvent = require('../../helpers/characterFromEvent')
      self.ignoreNextKeyup = characterFromEvent(e)
    }

    // weird race condition if a sequence ends with the key
    // another sequence begins with
    setTimeout(
      function () {
        self.resetSequences()
      },
      10
    )
  }

  // loop through keys one at a time and bind the appropriate callback
  // function.  for any key leading up to the final one it should
  // increase the sequence. after the final, it should reset all sequences
  //
  // if an action is specified in the original bind call then that will
  // be used throughout.  otherwise we will pass the action that the
  // next key in the sequence should match.  this allows a sequence
  // to mix and match keypress and keydown events depending on which
  // ones are better suited to the key provided
  for (var j = 0; j < keys.length; ++j) {
    var isFinal = j + 1 === keys.length
    var wrappedCallback = isFinal ? callbackAndReset : increaseSequence(action || self.getKeyInfo(keys[j + 1]).action)
    self.bindSingle(keys[j], wrappedCallback, action, combo, j)
  }
}

},{"../../helpers/characterFromEvent":23}],6:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * binds a single keyboard combination
 *
 * @param {string} combination
 * @param {Function} callback
 * @param {string=} action
 * @param {string=} sequenceName - name of sequence if part of sequence
 * @param {number=} level - what part of the sequence the command is
 * @returns void
 */
module.exports = function (combination, callback, action, sequenceName, level) {
  var self = this

  // store a direct mapped reference for use with Combokeys.trigger
  self.directMap[combination + ':' + action] = callback

  // make sure multiple spaces in a row become a single space
  combination = combination.replace(/\s+/g, ' ')

  var sequence = combination.split(' ')
  var info

  // if this pattern is a sequence of keys then run through this method
  // to reprocess each pattern one key at a time
  if (sequence.length > 1) {
    self.bindSequence(combination, sequence, callback, action)
    return
  }

  info = self.getKeyInfo(combination, action)

  // make sure to initialize array if this is the first time
  // a callback is added for this key
  self.callbacks[info.key] = self.callbacks[info.key] || []

  // remove an existing match if there is one
  self.getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level)

  // add this call back to the array
  // if it is a sequence put it at the beginning
  // if not put it at the end
  //
  // this is important because the way these are processed expects
  // the sequence ones to come first
  self.callbacks[info.key][sequenceName ? 'unshift' : 'push']({
    callback: callback,
    modifiers: info.modifiers,
    action: info.action,
    seq: sequenceName,
    level: level,
    combo: combination
  })
}

},{}],7:[function(require,module,exports){
var off = require('dom-event').off
module.exports = function () {
  var self = this
  var element = self.element

  off(element, 'keypress', self.eventHandler)
  off(element, 'keydown', self.eventHandler)
  off(element, 'keyup', self.eventHandler)
}

},{"dom-event":33}],8:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * actually calls the callback function
 *
 * if your callback function returns false this will use the jquery
 * convention - prevent default and stop propogation on the event
 *
 * @param {Function} callback
 * @param {Event} e
 * @returns void
 */
module.exports = function (callback, e, combo, sequence) {
  var self = this
  var preventDefault
  var stopPropagation

  // if this event should not happen stop here
  if (self.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
    return
  }

  if (callback(e, combo) === false) {
    preventDefault = require('../../helpers/preventDefault')
    preventDefault(e)
    stopPropagation = require('../../helpers/stopPropagation')
    stopPropagation(e)
  }
}

},{"../../helpers/preventDefault":27,"../../helpers/stopPropagation":32}],9:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * Gets info for a specific key combination
 *
 * @param  {string} combination key combination ("command+s" or "a" or "*")
 * @param  {string=} action
 * @returns {Object}
 */
module.exports = function (combination, action) {
  var self = this
  var keysFromString
  var keys
  var key
  var j
  var modifiers = []
  var SPECIAL_ALIASES
  var SHIFT_MAP
  var isModifier

  keysFromString = require('../../helpers/keysFromString')
  // take the keys from this pattern and figure out what the actual
  // pattern is all about
  keys = keysFromString(combination)

  SPECIAL_ALIASES = require('../../helpers/special-aliases')
  SHIFT_MAP = require('../../helpers/shift-map')
  isModifier = require('../../helpers/isModifier')
  for (j = 0; j < keys.length; ++j) {
    key = keys[j]

    // normalize key names
    if (SPECIAL_ALIASES[key]) {
      key = SPECIAL_ALIASES[key]
    }

    // if this is not a keypress event then we should
    // be smart about using shift keys
    // this will only work for US keyboards however
    if (action && action !== 'keypress' && SHIFT_MAP[key]) {
      key = SHIFT_MAP[key]
      modifiers.push('shift')
    }

    // if this key is a modifier then add it to the list of modifiers
    if (isModifier(key)) {
      modifiers.push(key)
    }
  }

  // depending on what the key combination is
  // we will try to pick the best event for it
  action = self.pickBestAction(key, modifiers, action)

  return {
    key: key,
    modifiers: modifiers,
    action: action
  }
}

},{"../../helpers/isModifier":25,"../../helpers/keysFromString":26,"../../helpers/shift-map":28,"../../helpers/special-aliases":29}],10:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * finds all callbacks that match based on the keycode, modifiers,
 * and action
 *
 * @param {string} character
 * @param {Array} modifiers
 * @param {Event|Object} e
 * @param {string=} sequenceName - name of the sequence we are looking for
 * @param {string=} combination
 * @param {number=} level
 * @returns {Array}
 */
module.exports = function (character, modifiers, e, sequenceName, combination, level) {
  var self = this
  var j
  var callback
  var matches = []
  var action = e.type
  var isModifier
  var modifiersMatch

  if (action === 'keypress') {
    // 'any-character' callbacks are only on `keypress`
    var anyCharCallbacks = self.callbacks['any-character'] || []
    anyCharCallbacks.forEach(function (callback) {
      matches.push(callback)
    })
  }

  if (!self.callbacks[character]) {return matches}

  isModifier = require('../../helpers/isModifier')
  // if a modifier key is coming up on its own we should allow it
  if (action === 'keyup' && isModifier(character)) {
    modifiers = [character]
  }

  // loop through all callbacks for the key that was pressed
  // and see if any of them match
  for (j = 0; j < self.callbacks[character].length; ++j) {
    callback = self.callbacks[character][j]

    // if a sequence name is not specified, but this is a sequence at
    // the wrong level then move onto the next match
    if (!sequenceName && callback.seq && self.sequenceLevels[callback.seq] !== callback.level) {
      continue
    }

    // if the action we are looking for doesn't match the action we got
    // then we should keep going
    if (action !== callback.action) {
      continue
    }

    // if this is a keypress event and the meta key and control key
    // are not pressed that means that we need to only look at the
    // character, otherwise check the modifiers as well
    //
    // chrome will not fire a keypress if meta or control is down
    // safari will fire a keypress if meta or meta+shift is down
    // firefox will fire a keypress if meta or control is down
    modifiersMatch = require('./modifiersMatch')
    if ((action === 'keypress' && !e.metaKey && !e.ctrlKey) || modifiersMatch(modifiers, callback.modifiers)) {
      // when you bind a combination or sequence a second time it
      // should overwrite the first one.  if a sequenceName or
      // combination is specified in this call it does just that
      //
      // @todo make deleting its own method?
      var deleteCombo = !sequenceName && callback.combo === combination
      var deleteSequence = sequenceName && callback.seq === sequenceName && callback.level === level
      if (deleteCombo || deleteSequence) {
        self.callbacks[character].splice(j, 1)
      }

      matches.push(callback)
    }
  }

  return matches
}

},{"../../helpers/isModifier":25,"./modifiersMatch":14}],11:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * reverses the map lookup so that we can look for specific keys
 * to see what can and can't use keypress
 *
 * @return {Object}
 */
module.exports = function () {
  var self = this
  var constructor = self.constructor
  var SPECIAL_KEYS_MAP

  if (!constructor.REVERSE_MAP) {
    constructor.REVERSE_MAP = {}
    SPECIAL_KEYS_MAP = require('../../helpers/special-keys-map')
    for (var key in SPECIAL_KEYS_MAP) {
      // pull out the numeric keypad from here cause keypress should
      // be able to detect the keys from the character
      if (key > 95 && key < 112) {
        continue
      }

      if (SPECIAL_KEYS_MAP.hasOwnProperty(key)) {
        constructor.REVERSE_MAP[SPECIAL_KEYS_MAP[key]] = key
      }
    }
  }
  return constructor.REVERSE_MAP
}

},{"../../helpers/special-keys-map":31}],12:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * handles a character key event
 *
 * @param {string} character
 * @param {Array} modifiers
 * @param {Event} e
 * @returns void
 */
module.exports = function (character, modifiers, e) {
  var self = this
  var callbacks
  var j
  var doNotReset = {}
  var maxLevel = 0
  var processedSequenceCallback = false
  var isModifier
  var ignoreThisKeypress

  callbacks = self.getMatches(character, modifiers, e)
  // Calculate the maxLevel for sequences so we can only execute the longest callback sequence
  for (j = 0; j < callbacks.length; ++j) {
    if (callbacks[j].seq) {
      maxLevel = Math.max(maxLevel, callbacks[j].level)
    }
  }

  // loop through matching callbacks for this key event
  for (j = 0; j < callbacks.length; ++j) {
    // fire for all sequence callbacks
    // this is because if for example you have multiple sequences
    // bound such as "g i" and "g t" they both need to fire the
    // callback for matching g cause otherwise you can only ever
    // match the first one
    if (callbacks[j].seq) {
      // only fire callbacks for the maxLevel to prevent
      // subsequences from also firing
      //
      // for example 'a option b' should not cause 'option b' to fire
      // even though 'option b' is part of the other sequence
      //
      // any sequences that do not match here will be discarded
      // below by the resetSequences call
      if (callbacks[j].level !== maxLevel) {
        continue
      }

      processedSequenceCallback = true

      // keep a list of which sequences were matches for later
      doNotReset[callbacks[j].seq] = 1
      self.fireCallback(callbacks[j].callback, e, callbacks[j].combo, callbacks[j].seq)
      continue
    }

    // if there were no sequence matches but we are still here
    // that means this is a regular match so we should fire that
    if (!processedSequenceCallback) {
      self.fireCallback(callbacks[j].callback, e, callbacks[j].combo)
    }
  }

  // if the key you pressed matches the type of sequence without
  // being a modifier (ie "keyup" or "keypress") then we should
  // reset all sequences that were not matched by this event
  //
  // this is so, for example, if you have the sequence "h a t" and you
  // type "h e a r t" it does not match.  in this case the "e" will
  // cause the sequence to reset
  //
  // modifier keys are ignored because you can have a sequence
  // that contains modifiers such as "enter ctrl+space" and in most
  // cases the modifier key will be pressed before the next key
  //
  // also if you have a sequence such as "ctrl+b a" then pressing the
  // "b" key will trigger a "keypress" and a "keydown"
  //
  // the "keydown" is expected when there is a modifier, but the
  // "keypress" ends up matching the nextExpectedAction since it occurs
  // after and that causes the sequence to reset
  //
  // we ignore keypresses in a sequence that directly follow a keydown
  // for the same character
  ignoreThisKeypress = e.type === 'keypress' && self.ignoreNextKeypress
  isModifier = require('../../helpers/isModifier')
  if (e.type === self.nextExpectedAction && !isModifier(character) && !ignoreThisKeypress) {
    self.resetSequences(doNotReset)
  }

  self.ignoreNextKeypress = processedSequenceCallback && e.type === 'keydown'
}

},{"../../helpers/isModifier":25}],13:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * handles a keydown event
 *
 * @param {Event} e
 * @returns void
 */
module.exports = function (e) {
  var self = this
  var characterFromEvent
  var eventModifiers

  // normalize e.which for key events
  // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  if (typeof e.which !== 'number') {
    e.which = e.keyCode
  }
  characterFromEvent = require('../../helpers/characterFromEvent')
  var character = characterFromEvent(e)

  // no character found then stop
  if (!character) {
    return
  }

  // need to use === for the character check because the character can be 0
  if (e.type === 'keyup' && self.ignoreNextKeyup === character) {
    self.ignoreNextKeyup = false
    return
  }

  eventModifiers = require('../../helpers/eventModifiers')
  self.handleKey(character, eventModifiers(e), e)
}

},{"../../helpers/characterFromEvent":23,"../../helpers/eventModifiers":24}],14:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * checks if two arrays are equal
 *
 * @param {Array} modifiers1
 * @param {Array} modifiers2
 * @returns {boolean}
 */
module.exports = function (modifiers1, modifiers2) {
  return modifiers1.sort().join(',') === modifiers2.sort().join(',')
}

},{}],15:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * picks the best action based on the key combination
 *
 * @param {string} key - character for key
 * @param {Array} modifiers
 * @param {string=} action passed in
 */
module.exports = function (key, modifiers, action) {
  var self = this

  // if no action was picked in we should try to pick the one
  // that we think would work best for this key
  if (!action) {
    action = self.getReverseMap()[key] ? 'keydown' : 'keypress'
  }

  // modifier keys don't work as expected with keypress,
  // switch to keydown
  if (action === 'keypress' && modifiers.length) {
    action = 'keydown'
  }

  return action
}

},{}],16:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * resets the library back to its initial state. This is useful
 * if you want to clear out the current keyboard shortcuts and bind
 * new ones - for example if you switch to another page
 *
 * @returns void
 */
module.exports = function () {
  var self = this
  self.callbacks = {}
  self.directMap = {}
  return this
}

},{}],17:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * called to set a 1 second timeout on the specified sequence
 *
 * this is so after each key press in the sequence you have 1 second
 * to press the next key before you have to start over
 *
 * @returns void
 */
module.exports = function () {
  var self = this

  clearTimeout(self.resetTimer)
  self.resetTimer = setTimeout(
    function () {
      self.resetSequences()
    },
    1000
  )
}

},{}],18:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * resets all sequence counters except for the ones passed in
 *
 * @param {Object} doNotReset
 * @returns void
 */
module.exports = function (doNotReset) {
  var self = this

  doNotReset = doNotReset || {}

  var activeSequences = false
  var key

  for (key in self.sequenceLevels) {
    if (doNotReset[key]) {
      activeSequences = true
      continue
    }
    self.sequenceLevels[key] = 0
  }

  if (!activeSequences) {
    self.nextExpectedAction = false
  }
}

},{}],19:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
* should we stop this event before firing off callbacks
*
* @param {Event} e
* @param {Element} element
* @return {boolean}
*/
module.exports = function (e, element) {
  // if the element has the class "combokeys" then no need to stop
  if ((' ' + element.className + ' ').indexOf(' combokeys ') > -1) {
    return false
  }

  var tagName = element.tagName.toLowerCase()

  // stop for input, select, and textarea
  return tagName === 'input' || tagName === 'select' || tagName === 'textarea' || element.isContentEditable
}

},{}],20:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * triggers an event that has already been bound
 *
 * @param {string} keys
 * @param {string=} action
 * @returns void
 */
module.exports = function (keys, action) {
  var self = this
  if (self.directMap[keys + ':' + action]) {
    self.directMap[keys + ':' + action]({}, keys)
  }
  return this
}

},{}],21:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * unbinds an event to Combokeys
 *
 * the unbinding sets the callback function of the specified key combo
 * to an empty function and deletes the corresponding key in the
 * directMap dict.
 *
 * TODO: actually remove this from the callbacks dictionary instead
 * of binding an empty function
 *
 * the keycombo+action has to be exactly the same as
 * it was defined in the bind method
 *
 * @param {string|Array} keys
 * @param {string} action
 * @returns void
 */
module.exports = function (keys, action) {
  var self = this

  return self.bind(keys, function () {}, action)
}

},{}],22:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

module.exports = function () {
  var self = this

  self.instances.forEach(function (combokeys) {
    combokeys.reset()
  })
}

},{}],23:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * takes the event and returns the key character
 *
 * @param {Event} e
 * @return {string}
 */
module.exports = function (e) {
  var SPECIAL_KEYS_MAP,
  SPECIAL_CHARACTERS_MAP
  SPECIAL_KEYS_MAP = require('./special-keys-map')
  SPECIAL_CHARACTERS_MAP = require('./special-characters-map')

  // for keypress events we should return the character as is
  if (e.type === 'keypress') {
    var character = String.fromCharCode(e.which)

    // if the shift key is not pressed then it is safe to assume
    // that we want the character to be lowercase.  this means if
    // you accidentally have caps lock on then your key bindings
    // will continue to work
    //
    // the only side effect that might not be desired is if you
    // bind something like 'A' cause you want to trigger an
    // event when capital A is pressed caps lock will no longer
    // trigger the event.  shift+a will though.
    if (!e.shiftKey) {
      character = character.toLowerCase()
    }

    return character
  }

  // for non keypress events the special maps are needed
  if (SPECIAL_KEYS_MAP[e.which]) {
    return SPECIAL_KEYS_MAP[e.which]
  }

  if (SPECIAL_CHARACTERS_MAP[e.which]) {
    return SPECIAL_CHARACTERS_MAP[e.which]
  }

  // if it is not in the special map

  // with keydown and keyup events the character seems to always
  // come in as an uppercase character whether you are pressing shift
  // or not.  we should make sure it is always lowercase for comparisons
  return String.fromCharCode(e.which).toLowerCase()
}

},{"./special-characters-map":30,"./special-keys-map":31}],24:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * takes a key event and figures out what the modifiers are
 *
 * @param {Event} e
 * @returns {Array}
 */
module.exports = function (e) {
  var modifiers = []

  if (e.shiftKey) {
    modifiers.push('shift')
  }

  if (e.altKey) {
    modifiers.push('alt')
  }

  if (e.ctrlKey) {
    modifiers.push('ctrl')
  }

  if (e.metaKey) {
    modifiers.push('meta')
  }

  return modifiers
}

},{}],25:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * determines if the keycode specified is a modifier key or not
 *
 * @param {string} key
 * @returns {boolean}
 */
module.exports = function (key) {
  return key === 'shift' || key === 'ctrl' || key === 'alt' || key === 'meta'
}

},{}],26:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * Converts from a string key combination to an array
 *
 * @param  {string} combination like "command+shift+l"
 * @return {Array}
 */
module.exports = function (combination) {
  if (combination === '+') {
    return ['+']
  }

  return combination.split('+')
}

},{}],27:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * prevents default for this event
 *
 * @param {Event} e
 * @returns void
 */
module.exports = function (e) {
  if (e.preventDefault) {
    e.preventDefault()
    return
  }

  e.returnValue = false
}

},{}],28:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * this is a mapping of keys that require shift on a US keypad
 * back to the non shift equivelents
 *
 * this is so you can use keyup events with these keys
 *
 * note that this will only work reliably on US keyboards
 *
 * @type {Object}
 */
module.exports = {
  '~': '`',
  '!': '1',
  '@': '2',
  '#': '3',
  '$': '4',
  '%': '5',
  '^': '6',
  '&': '7',
  '*': '8',
  '(': '9',
  ')': '0',
  '_': '-',
  '+': '=',
  ':': ';',
  '"': "'",
  '<': ',',
  '>': '.',
  '?': '/',
  '|': '\\'
}

},{}],29:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * this is a list of special strings you can use to map
 * to modifier keys when you specify your keyboard shortcuts
 *
 * @type {Object}
 */
module.exports = {
  'option': 'alt',
  'command': 'meta',
  'return': 'enter',
  'escape': 'esc',
  'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
}

},{}],30:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * mapping for special characters so they can support
 *
 * this dictionary is only used incase you want to bind a
 * keyup or keydown event to one of these keys
 *
 * @type {Object}
 */
module.exports = {
  106: '*',
  107: '+',
  109: '-',
  110: '.',
  111: '/',
  186: ';',
  187: '=',
  188: ',',
  189: '-',
  190: '.',
  191: '/',
  192: '`',
  219: '[',
  220: '\\',
  221: ']',
  222: "'"
}

},{}],31:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'
/**
 * mapping of special keycodes to their corresponding keys
 *
 * everything in this dictionary cannot use keypress events
 * so it has to be here to map to the correct keycodes for
 * keyup/keydown events
 *
 * @type {Object}
 */
module.exports = {
  8: 'backspace',
  9: 'tab',
  13: 'enter',
  16: 'shift',
  17: 'ctrl',
  18: 'alt',
  20: 'capslock',
  27: 'esc',
  32: 'space',
  33: 'pageup',
  34: 'pagedown',
  35: 'end',
  36: 'home',
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  45: 'ins',
  46: 'del',
  91: 'meta',
  93: 'meta',
  187: 'plus',
  189: 'minus',
  224: 'meta'
}

/**
 * loop through the f keys, f1 to f19 and add them to the map
 * programatically
 */
for (var i = 1; i < 20; ++i) {
  module.exports[111 + i] = 'f' + i
}

/**
 * loop through to map numbers on the numeric keypad
 */
for (i = 0; i <= 9; ++i) {
  module.exports[i + 96] = i
}

},{}],32:[function(require,module,exports){
/* eslint-env node, browser */
'use strict'

/**
 * stops propogation for this event
 *
 * @param {Event} e
 * @returns void
 */
module.exports = function (e) {
  if (e.stopPropagation) {
    e.stopPropagation()
    return
  }

  e.cancelBubble = true
}

},{}],33:[function(require,module,exports){
module.exports = on;
module.exports.on = on;
module.exports.off = off;

function on (element, event, callback, capture) {
  !element.addEventListener && (event = 'on' + event);
  (element.addEventListener || element.attachEvent).call(element, event, callback, capture);
  return callback;
}

function off (element, event, callback, capture) {
  !element.removeEventListener && (event = 'on' + event);
  (element.removeEventListener || element.detachEvent).call(element, event, callback, capture);
  return callback;
}

},{}],34:[function(require,module,exports){
WYMeditor.EXTERNAL_MODULES.Combokeys = require("combokeys");

},{"combokeys":1}]},{},[34])(34)
});
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9ncnVudC1icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJub2RlX21vZHVsZXMvY29tYm9rZXlzL0NvbWJva2V5cy9pbmRleC5qcyIsIm5vZGVfbW9kdWxlcy9jb21ib2tleXMvQ29tYm9rZXlzL3Byb3RvdHlwZS9hZGRFdmVudHMuanMiLCJub2RlX21vZHVsZXMvY29tYm9rZXlzL0NvbWJva2V5cy9wcm90b3R5cGUvYmluZC5qcyIsIm5vZGVfbW9kdWxlcy9jb21ib2tleXMvQ29tYm9rZXlzL3Byb3RvdHlwZS9iaW5kTXVsdGlwbGUuanMiLCJub2RlX21vZHVsZXMvY29tYm9rZXlzL0NvbWJva2V5cy9wcm90b3R5cGUvYmluZFNlcXVlbmNlLmpzIiwibm9kZV9tb2R1bGVzL2NvbWJva2V5cy9Db21ib2tleXMvcHJvdG90eXBlL2JpbmRTaW5nbGUuanMiLCJub2RlX21vZHVsZXMvY29tYm9rZXlzL0NvbWJva2V5cy9wcm90b3R5cGUvZGV0YWNoLmpzIiwibm9kZV9tb2R1bGVzL2NvbWJva2V5cy9Db21ib2tleXMvcHJvdG90eXBlL2ZpcmVDYWxsYmFjay5qcyIsIm5vZGVfbW9kdWxlcy9jb21ib2tleXMvQ29tYm9rZXlzL3Byb3RvdHlwZS9nZXRLZXlJbmZvLmpzIiwibm9kZV9tb2R1bGVzL2NvbWJva2V5cy9Db21ib2tleXMvcHJvdG90eXBlL2dldE1hdGNoZXMu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GNhbGxiYWNrLCBjYXB0dXJlKTtcbiAgcmV0dXJuIGNhbGxiYWNrO1xufVxuXG5mdW5jdGlvbiBvZmYgKGVsZW1lbnQsIGV2ZW50LCBjYWxsYmFjaywgY2FwdHVyZSkge1xuICAhZWxlbWVudC5yZW1vdmVFdmVudExpc3RlbmVyICYmIChldmVudCA9ICdvbicgKyBldmVudCk7XG4gIChlbGVtZW50LnJlbW92ZUV2ZW50TGlzdGVuZXIgfHwgZWxlbWVudC5kZXRhY2hFdmVudCkuY2FsbChlbGVtZW50LCBldmVudCwgY2FsbGJhY2ssIGNhcHR1cmUpO1xuICByZXR1cm4gY2FsbGJhY2s7XG59XG4iLCJXWU1lZGl0b3IuRVhURVJOQUxfTU9EVUxFUy5Db21ib2tleXMgPSByZXF1aXJlKFwiY29tYm9rZXlzXCIpO1xuIl19

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.foo = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict'

module.exports = function (element, onSensible, onAny) {
  var self = this

  if (typeof onSensible !== 'function') {
    throw new Error('Expected a function')
  }
  self.element = element
  self.onSensible = onSensible
  self.onAny = onAny
  self.listen()

  return self
}

module.exports.prototype.listen = require('./prototype/listen')
module.exports.prototype.discern = require('./prototype/discern')
module.exports.prototype.reset = require('./prototype/reset')
module.exports.prototype.detach = require('./prototype/detach')
module.exports.prototype.callbackSensible = require('./prototype/callback-sensible')
module.exports.prototype.callbackAny = require('./prototype/callback-any')

},{"./prototype/callback-any":2,"./prototype/callback-sensible":3,"./prototype/detach":4,"./prototype/discern":5,"./prototype/listen":6,"./prototype/reset":7}],2:[function(require,module,exports){
'use strict'

module.exports = function () {
  var self = this
  ;(self.onAny || function () {}).call(self)
}

},{}],3:[function(require,module,exports){
'use strict'

module.exports = function () {
  var self = this
  self.onSensible()
}

},{}],4:[function(require,module,exports){
'use strict'

var off = require('dom-events').off
var TEXT_ALTERING_EVENT_TYPES = require('../../text-altering-event-types')

module.exports = function () {
  var self = this

  TEXT_ALTERING_EVENT_TYPES.forEach(function (type) {
    off(self.element, type, self.listener)
  })
}

},{"../../text-altering-event-types":8,"dom-events":11}],5:[function(require,module,exports){
'use strict'
var getType = require('../../textEditType')

module.exports = function (e) {
  var self = this
  var type = getType(e)
  if (!type) {
    // will not cause native edit
    return
  }
  self.callbackAny()
  self.previousEditType = self.lastEditType
  self.lastEditType = type
  if (!self.previousEditType) return
  if (
    self.lastEditType !== self.previousEditType ||
    self.lastEditType === 'paste' ||
    self.lastEditType === 'drop'
  ) {
    self.callbackSensible()
  }
}

},{"../../textEditType":9}],6:[function(require,module,exports){
'use strict'
var on
var TEXT_ALTERING_EVENT_TYPES

on = require('add-event-handler')
TEXT_ALTERING_EVENT_TYPES = require('../../text-altering-event-types')

module.exports = function () {
  var self = this

  self.listener = function (e) {
    self.discern(e)
  }

  TEXT_ALTERING_EVENT_TYPES.forEach(function (type) {
    on(self.element, type, self.listener)
  })
}

},{"../../text-altering-event-types":8,"add-event-handler":10}],7:[function(require,module,exports){
'use strict'

module.exports = function () {
  var self = this
  delete self.lastEditType
}

},{}],8:[function(require,module,exports){
'use strict'
module.exports = [
  'keydown',
  'paste',
  'drop'
]

},{}],9:[function(require,module,exports){
'use strict'
var BACKWARDS_REMOVAL_KEYS = [
  'backspace'
]
var FORWARD_REMOVAL_KEYS = [
  'del',
  'delete'
]
var EDIT_PREVENTING_PROPS = [
  'altKey',
  'ctrlKey',
  'metaKey'
]
var keycode = require('keycode')

module.exports = function (e) {
  if (e.type === 'keydown') {
    var noEdit
    EDIT_PREVENTING_PROPS.forEach(function (prop) {
      if (e[prop]) {
        // will not cause native edit
        noEdit = true
      }
    })
    if (noEdit) {
      return false
    }
    var key = keycode(e)
    if (BACKWARDS_REMOVAL_KEYS.indexOf(key) > -1) {
      return 'backwardsRemoval'
    }
    if (FORWARD_REMOVAL_KEYS.indexOf(key) > -1) {
      return 'forwardRemoval'
    }
    if (key === 'space') {
      return key
    }
    if (key === 'enter') {
      return key
    }
    return 'characterAddition'
  }
  if (e.type === 'paste') {
    return e.type
  }
  if (e.type === 'drop') {
    return e.type
  }
  throw new Error('Shouldn\'t get this far')
}

},{"keycode":15}],10:[function(require,module,exports){
/* eslint-env node, browser */
"use strict";

module.exports = function(element, type, handler) {
    if (element.addEventListener) {
        return element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
        return element.attachEvent("on" + type, handler);
    } else {
        throw "No event handler adding interface found";
    }
};

},{}],11:[function(require,module,exports){

var synth = require('synthetic-dom-events');

var on = function(element, name, fn, capture) {
    return element.addEventListener(name, fn, capture || false);
};

var off = function(element, name, fn, capture) {
    return element.removeEventListener(name, fn, capture || false);
};

var once = function (element, name, fn, capture) {
    function tmp (ev) {
        off(element, name, tmp, capture);
        fn(ev);
    }
    on(element, name, tmp, capture);
};

var emit = function(element, name, opt) {
    var ev = synth(name, opt);
    element.dispatchEvent(ev);
};

if (!document.addEventListener) {
    on = function(element, name, fn) {
        return element.attachEvent('on' + name, fn);
    };
}

if (!document.removeEventListener) {
    off = function(element, name, fn) {
        return element.detachEvent('on' + name, fn);
    };
}

if (!document.dispatchEvent) {
    emit = function(element, name, opt) {
        var ev = synth(name, opt);
        return element.fireEvent('on' + ev.type, ev);
    };
}

module.exports = {
    on: on,
    off: off,
    once: once,
    emit: emit
};

},{"synthetic-dom-events":12}],12:[function(require,module,exports){

// for compression
var win = window;
var doc = document || {};
var root = doc.documentElement || {};

// detect if we need to use firefox KeyEvents vs KeyboardEvents
var use_key_event = true;
try {
    doc.createEvent('KeyEvents');
}
catch (err) {
    use_key_event = false;
}

// Workaround for https://bugs.webkit.org/show_bug.cgi?id=16735
function check_kb(ev, opts) {
    if (ev.ctrlKey != (opts.ctrlKey || false) ||
        ev.altKey != (opts.altKey || false) ||
        ev.shiftKey != (opts.shiftKey || false) ||
        ev.metaKey != (opts.metaKey || false) ||
        ev.keyCode != (opts.keyCode || 0) ||
        ev.charCode != (opts.charCode || 0)) {

        ev = document.createEvent('Event');
        ev.initEvent(opts.type, opts.bubbles, opts.cancelable);
        ev.ctrlKey  = opts.ctrlKey || false;
        ev.altKey   = opts.altKey || false;
        ev.shiftKey = opts.shiftKey || false;
        ev.metaKey  = opts.metaKey || false;
        ev.keyCode  = opts.keyCode || 0;
        ev.charCode = opts.charCode || 0;
    }

    return ev;
}

// modern browsers, do a proper dispatchEvent()
var modern = function(type, opts) {
    opts = opts || {};

    // which init fn do we use
    var family = typeOf(type);
    var init_fam = family;
    if (family === 'KeyboardEvent' && use_key_event) {
        family = 'KeyEvents';
        init_fam = 'KeyEvent';
    }

    var ev = doc.createEvent(family);
    var init_fn = 'init' + init_fam;
    var init = typeof ev[init_fn] === 'function' ? init_fn : 'initEvent';

    var sig = initSignatures[init];
    var args = [];
    var used = {};

    opts.type = type;
    for (var i = 0; i < sig.length; ++i) {
        var key = sig[i];
        var val = opts[key];
        // if no user specified value, then use event default
        if (val === undefined) {
            val = ev[key];
        }
        used[key] = true;
        args.push(val);
    }
    ev[init].apply(ev, args);

    // webkit key event issue workaround
    if (family === 'KeyboardEvent') {
        ev = check_kb(ev, opts);
    }

    // attach remaining unused options to the object
    for (var key in opts) {
        if (!used[key]) {
            ev[key] = opts[key];
        }
    }

    return ev;
};

var legacy = function (type, opts) {
    opts = opts || {};
    var ev = doc.createEventObject();

    ev.type = type;
    for (var key in opts) {
        if (opts[key] !== undefined) {
            ev[key] = opts[key];
        }
    }

    return ev;
};

// expose either the modern version of event generation or legacy
// depending on what we support
// avoids if statements in the code later
module.exports = doc.createEvent ? modern : legacy;

var initSignatures = require('./init.json');
var types = require('./types.json');
var typeOf = (function () {
    var typs = {};
    for (var key in types) {
        var ts = types[key];
        for (var i = 0; i < ts.length; i++) {
            typs[ts[i]] = key;
        }
    }

    return function (name) {
        return typs[name] || 'Event';
    };
})();

},{"./init.json":13,"./types.json":14}],13:[function(require,module,exports){
module.exports={
  "initEvent" : [
    "type",
    "bubbles",
    "cancelable"
  ],
  "initUIEvent" : [
    "type",
    "bubbles",
    "cancelable",
    "view",
    "detail"
  ],
  "initMouseEvent" : [
    "type",
    "bubbles",
    "cancelable",
    "view",
    "detail",
    "screenX",
    "screenY",
    "clientX",
    "clientY",
    "ctrlKey",
    "altKey",
    "shiftKey",
    "metaKey",
    "button",
    "relatedTarget"
  ],
  "initMutationEvent" : [
    "type",
    "bubbles",
    "cancelable",
    "relatedNode",
    "prevValue",
    "newValue",
    "attrName",
    "attrChange"
  ],
  "initKeyboardEvent" : [
    "type",
    "bubbles",
    "cancelable",
    "view",
    "ctrlKey",
    "altKey",
    "shiftKey",
    "metaKey",
    "keyCode",
    "charCode"
  ],
  "initKeyEvent" : [
    "type",
    "bubbles",
    "cancelable",
    "view",
    "ctrlKey",
    "altKey",
    "shiftKey",
    "metaKey",
    "keyCode",
    "charCode"
  ]
}

},{}],14:[function(require,module,exports){
module.exports={
  "MouseEvent" : [
    "click",
    "mousedown",
    "mouseup",
    "mouseover",
    "mousemove",
    "mouseout"
  ],
  "KeyboardEvent" : [
    "keydown",
    "keyup",
    "keypress"
  ],
  "MutationEvent" : [
    "DOMSubtreeModified",
    "DOMNodeInserted",
    "DOMNodeRemoved",
    "DOMNodeRemovedFromDocument",
    "DOMNodeInsertedIntoDocument",
    "DOMAttrModified",
    "DOMCharacterDataModified"
  ],
  "HTMLEvents" : [
    "load",
    "unload",
    "abort",
    "error",
    "select",
    "change",
    "submit",
    "reset",
    "focus",
    "blur",
    "resize",
    "scroll"
  ],
  "UIEvent" : [
    "DOMFocusIn",
    "DOMFocusOut",
    "DOMActivate"
  ]
}

},{}],15:[function(require,module,exports){
// Source: http://jsfiddle.net/vWx8V/
// http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes



/**
 * Conenience method returns corresponding value for given keyName or keyCode.
 *
 * @param {Mixed} keyCode {Number} or keyName {String}
 * @return {Mixed}
 * @api public
 */

exports = module.exports = function(searchInput) {
  // Keyboard Events
  if (searchInput && 'object' === typeof searchInput) {
    var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode
    if (hasKeyCode) searchInput = hasKeyCode
  }

  // Numbers
  if ('number' === typeof searchInput) return names[searchInput]

  // Everything else (cast to string)
  var search = String(searchInput)

  // check codes
  var foundNamedKey = codes[search.toLowerCase()]
  if (foundNamedKey) return foundNamedKey

  // check aliases
  var foundNamedKey = aliases[search.toLowerCase()]
  if (foundNamedKey) return foundNamedKey

  // weird character?
  if (search.length === 1) return search.charCodeAt(0)

  return undefined
}

/**
 * Get by name
 *
 *   exports.code['enter'] // => 13
 */

var codes = exports.code = exports.codes = {
  'backspace': 8,
  'tab': 9,
  'enter': 13,
  'shift': 16,
  'ctrl': 17,
  'alt': 18,
  'pause/break': 19,
  'caps lock': 20,
  'esc': 27,
  'space': 32,
  'page up': 33,
  'page down': 34,
  'end': 35,
  'home': 36,
  'left': 37,
  'up': 38,
  'right': 39,
  'down': 40,
  'insert': 45,
  'delete': 46,
  'command': 91,
  'right click': 93,
  'numpad *': 106,
  'numpad +': 107,
  'numpad -': 109,
  'numpad .': 110,
  'numpad /': 111,
  'num lock': 144,
  'scroll lock': 145,
  'my computer': 182,
  'my calculator': 183,
  ';': 186,
  '=': 187,
  ',': 188,
  '-': 189,
  '.': 190,
  '/': 191,
  '`': 192,
  '[': 219,
  '\\': 220,
  ']': 221,
  "'": 222,
}

// Helper aliases

var aliases = exports.aliases = {
  'windows': 91,
  '⇧': 16,
  '⌥': 18,
  '⌃': 17,
  '⌘': 91,
  'ctl': 17,
  'control': 17,
  'option': 18,
  'pause': 19,
  'break': 19,
  'caps': 20,
  'return': 13,
  'escape': 27,
  'spc': 32,
  'pgup': 33,
  'pgdn': 33,
  'ins': 45,
  'del': 46,
  'cmd': 91
}


/*!
 * Programatically add the following
 */

// lower case chars
for (i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32

// numbers
for (var i = 48; i < 58; i++) codes[i - 48] = i

// function keys
for (i = 1; i < 13; i++) codes['f'+i] = i + 111

// numpad keys
for (i = 0; i < 10; i++) codes['numpad '+i] = i + 96

/**
 * Get by code
 *
 *   exports.name[13] // => 'Enter'
 */

var names = exports.names = exports.title = {} // title for backward compat

// Create reverse mapping
for (i in codes) names[codes[i]] = i

// Add aliases
for (var alias in aliases) {
  codes[alias] = aliases[alias]
}

},{}],16:[function(require,module,exports){
WYMeditor.EXTERNAL_MODULES.Edited = require("edited");

},{"edited":1}]},{},[16])(16)
});
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9ncnVudC1icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJub2RlX21vZHVsZXMvZWRpdGVkL2xpYi9FZGl0ZWQvaW5kZXguanMiLCJub2RlX21vZHVsZXMvZWRpdGVkL2xpYi9FZGl0ZWQvcHJvdG90eXBlL2NhbGxiYWNrLWFueS5qcyIsIm5vZGVfbW9kdWxlcy9lZGl0ZWQvbGliL0VkaXRlZC9wcm90b3R5cGUvY2FsbGJhY2stc2Vuc2libGUuanMiLCJub2RlX21vZHVsZXMvZWRpdGVkL2xpYi9FZGl0ZWQvcHJvdG90eXBlL2RldGFjaC5qcyIsIm5vZGVfbW9kdWxlcy9lZGl0ZWQvbGliL0Vk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FkICcraV0gPSBpICsgOTZcblxuLyoqXG4gKiBHZXQgYnkgY29kZVxuICpcbiAqICAgZXhwb3J0cy5uYW1lWzEzXSAvLyA9PiAnRW50ZXInXG4gKi9cblxudmFyIG5hbWVzID0gZXhwb3J0cy5uYW1lcyA9IGV4cG9ydHMudGl0bGUgPSB7fSAvLyB0aXRsZSBmb3IgYmFja3dhcmQgY29tcGF0XG5cbi8vIENyZWF0ZSByZXZlcnNlIG1hcHBpbmdcbmZvciAoaSBpbiBjb2RlcykgbmFtZXNbY29kZXNbaV1dID0gaVxuXG4vLyBBZGQgYWxpYXNlc1xuZm9yICh2YXIgYWxpYXMgaW4gYWxpYXNlcykge1xuICBjb2Rlc1thbGlhc10gPSBhbGlhc2VzW2FsaWFzXVxufVxuIiwiV1lNZWRpdG9yLkVYVEVSTkFMX01PRFVMRVMuRWRpdGVkID0gcmVxdWlyZShcImVkaXRlZFwiKTtcbiJdfQ==

/* global
    rangy
*/
"use strict";

/*
 * Undo/Redo
 */

/**
    WYMeditor.UndoRedo
    ==================

    Constructs an undoRedo mechanism for a provided editor.

    Also sets keyboard shortcuts for undo and redo.

    @param wym An editor instance.
*/
WYMeditor.UndoRedo = function (wym) {
    var undoRedo = this;

    undoRedo.wym = wym;

    wym.keyboard.combokeys.bind(
        "mod+z",
        function () {
            wym.undoRedo.undo();
            // Prevents native action. Caution: not covered by tests.
            return false;
        }
    );
    wym.keyboard.combokeys.bind(
        ["shift+meta+z", "mod+y"],
        function () {
            wym.undoRedo.redo();
            // Prevents native action. Caution: not covered by tests.
            return false;
        }
    );
};

/**
    WYMeditor.UndoRedo._onBodyFocus
    ===============================

    This method should be called on focus of the document's body.

    It makes sure that the first undo point contains a selection.

    After the editor's instantiation there is no selection. The first
    selection is made along with the first focus.

    This method will run before the native action (in which the selection
    is made). Therefore the instantiation of object-history is called using
    `setTimeout`, which is after the selection happens.
*/
WYMeditor.UndoRedo.prototype._onBodyFocus = function () {
    var undoRedo = this,
        wym = undoRedo.wym;

    if (undoRedo.history) {
        return;
    }

    setTimeout(function () {
        undoRedo._instantiateHistory(wym.getCurrentState());
    }, 0);
};

/**
    WYMeditor.UndoRedo._add
    =======================

    Adds a history point.
*/

WYMeditor.UndoRedo.prototype._add = function () {
    var undoRedo = this,
        wym = undoRedo.wym;

    if (!undoRedo.history) {
        // history was not instantiated yet
        return;
    }

    undoRedo.history.add(wym.getCurrentState());
    undoRedo.hasUnregisteredModification = false;
};

/**
    WYMeditor.UndoRedo._do
    ======================

    Performs either undo or redo.

    @param what One of two possible constants:
        * `WYMeditor.UndoRedo.UN`
        * `WYMeditor.UndoRedo.RE`
*/
WYMeditor.UndoRedo.prototype._do = function (what) {
    var undoRedo = this,
        wym = undoRedo.wym,
        history = undoRedo.history,
        state,
        postEventName;

    if (!undoRedo.history) {
        // history was not instantiated yet
        return;
    }

    if (what === WYMeditor.UndoRedo.UN) {
        if (history.lengthBackward() === 0) {
            return;
        }
        if (undoRedo.hasUnregisteredModification) {
            // in order to be able to 'redo' to this yet unregistered state
            undoRedo._add();
        }
        history.backward();
        postEventName = 'postUndo';
    } else if (what === WYMeditor.UndoRedo.RE) {
        if (history.lengthForward() === 0) {
            return;
        }
        history.forward();
        postEventName = 'postRedo';
    } else {
        throw "Single parameter must be either `'un'` or `'re'` " +
            "(there are constants for those).";
    }

    state = history.get();
    wym.rawHtml(state.html);

    if (state.savedSelection) {
        // The `contentWindow` and `document` (`win` and `doc` properties) were
        // deleted before the state was saved. See `editor.getCurrentState`
        // code comments to understand why.
        //
        // Restore them now.
        state.savedSelection.win = wym._iframe.contentWindow;
        state.savedSelection.doc = wym._doc;
        rangy.restoreSelection(state.savedSelection);
    }

    jQuery(wym.element).trigger(WYMeditor.EVENTS[postEventName]);
};
WYMeditor.UndoRedo.UN = 'un';
WYMeditor.UndoRedo.RE = 're';

/**
    WYMeditor.UndoRedo.redo
    =======================
*/
WYMeditor.UndoRedo.prototype.redo = function () {
    var undoRedo = this;

    undoRedo._do(WYMeditor.UndoRedo.RE);
};

/**
    WYMeditor.UndoRedo.undo
    =======================
*/
WYMeditor.UndoRedo.prototype.undo = function () {
    var undoRedo = this;

    undoRedo._do(WYMeditor.UndoRedo.UN);
};

/**
    WYMeditor.UndoRedo.reset
    ========================

    Forgets all changes.
*/
WYMeditor.UndoRedo.prototype.reset = function () {
    var undoRedo = this,
        wym = undoRedo.wym;

    undoRedo._instantiateHistory(wym.getCurrentState());

    undoRedo.hasUnregisteredModification = null;
};

/**
    WYMeditor.UndoRedo._instantiateHistory
    ======================================

    Instantiates object-history[1] to keep track of undo/redo
    history.

    @param WymState initialState Initial editor state.
        Obtained with `wym.getCurrentState()`.

    1. https://github.com/PolicyStat/object-history
*/
WYMeditor.UndoRedo.prototype._instantiateHistory = function (initialState) {
    var undoRedo = this;

    undoRedo.history = new WYMeditor.EXTERNAL_MODULES
        .ObjectHistory(
            initialState,
            {limit: 100} // hard coded undo limit
        );
};

"use strict";
WYMeditor.Keyboard = function (wym) {
    var keyboard = this;

    keyboard._wym = wym;

    keyboard.combokeys = new WYMeditor.EXTERNAL_MODULES.Combokeys(wym._doc);

    return keyboard;
};

WYMeditor.Keyboard.DEFAULT_KEYBOARD_SHORTCUTS = [
    {
        combo: "mod+b",
        cb: function () {
            var wym = this;
            wym.exec(WYMeditor.EXEC_COMMANDS.BOLD);
            // Prevents native action. Caution: not covered by tests.
            return false;
        }
    },
    {
        combo: "mod+i",
        cb: function () {
            var wym = this;
            wym.exec(WYMeditor.EXEC_COMMANDS.ITALIC);
            // Prevents native action. Caution: not covered by tests.
            return false;
        }
    },
    {
        combo: "mod+k",
        cb: function () {
            var wym = this;
            wym.dialog(WYMeditor.DIALOGS.CreateLink);
            // Prevents native action. Caution: not covered by tests.
            return false;
        }
    },
    {
        combo: "tab",
        cb: function () {
            // Default action of WebKit and Blink is to create a span.
            // See https://stackoverflow.com/q/22404724
            // For consistency across browsers, prevent the default action in
            // them all
            return false;
        }
    }
];

/**
    WYMeditor.keyboard._attachDefaultKeyboardShortcuts
    ================================================

    Binds the default keyboard shortcuts.
*/
WYMeditor.Keyboard.prototype._attachDefaultKeyboardShortcuts = function () {
    var keyboard = this,
        wym = keyboard._wym,
        SHORTCUTS = keyboard.constructor.DEFAULT_KEYBOARD_SHORTCUTS,
        shortcut,
        i;

    for (i = 0; i < SHORTCUTS.length; i++) {
        shortcut = SHORTCUTS[i];
        keyboard.combokeys.bind(
            shortcut.combo,
            // With `Function.prototype.bind` available, the expression below
            // can be simply `shortcut.cb.bind(wym)`.
            /* jshint loopfunc:true */
            (function (cb) {
                return function () {
                    // This return statement is for Combokeys to receive the
                    // `false` value of callbacks, for preventing default
                    // actions.
                    return cb.call(wym);
                };
            }(shortcut.cb))
            /* jshint loopfunc:false */
        );
    }
};

"use strict";

/*
 * Native edits
 */

/**
    WYMeditor.NativeEditRegistration
    ================================

    Constructs a native edits registration mechanism for a provided editor.
*/
WYMeditor.NativeEditRegistration = function (wym) {
    var nativeEditRegistration = this;

    nativeEditRegistration.wym = wym;


    // https:/github.com/mightyiam/edited
    nativeEditRegistration.edited = new WYMeditor.EXTERNAL_MODULES.Edited(
        wym._doc.body,
        nativeEditRegistration._onSensibleNativeEdit
            .bind(nativeEditRegistration),
        nativeEditRegistration._onAnyNativeEdit
            .bind(nativeEditRegistration)
    );
};

/**
    WYMeditor.NativeEditRegistration._onSensibleNativeEdit
    ======================================================

    Handles "sensible" native edits.
    Sensible according to https://github.com/PolicyStat/edited
*/
WYMeditor.NativeEditRegistration.prototype
    ._onSensibleNativeEdit = function () {

    var nativeEditRegistration = this;
    nativeEditRegistration.wym.registerModification(true);
};

/**
    WYMeditor.NativeEditRegistration._onAnyNativeEdit
    =================================================

    Handles all native edits.
*/
WYMeditor.NativeEditRegistration.prototype._onAnyNativeEdit = function () {
    var nativeEditRegistration = this,
        undoRedo = nativeEditRegistration.wym.undoRedo;

    // remove redo points
    if (undoRedo.history) {
        undoRedo.history.forgetAllForward();
    }

    // Non-native modifications are registered when they are performed.
    // Contrary to those, native edits (e.g. typing) aren't registered 
    // until word boundaries are reached (space, enter) or edit actions 
    // (backspace, delete, cut, paste, etc). 
    // This handles an undo after e.g. only part of word is typed.
    //
    // A state with unregistered modifications will be lost upon an undo
    // and redo because it was never registered.
    // The last registered state doesn't include it and that will be the result
    // of the undo and redo operation.
    // This flag lets the undo operation know that it should add the current
    // state as a history point (register it) before undoing.
    // Then the next redo will revert to this state.
    undoRedo.hasUnregisteredModification = true;
};

// GLOBALS
WYMeditor.LEXER_ENTER = 1;
WYMeditor.LEXER_MATCHED = 2;
WYMeditor.LEXER_UNMATCHED = 3;
WYMeditor.LEXER_EXIT = 4;
WYMeditor.LEXER_SPECIAL = 5;


/**
*    Accepts text and breaks it into tokens.
*    Some optimisation to make the sure the
*    content is only scanned by the PHP regex
*    parser once. Lexer modes must not start
*    with leading underscores.
*
*    Sets up the lexer in case insensitive matching
*    by default.
*    @param Parser parser  Handling strategy by reference.
*    @param string start            Starting handler.
*    @param boolean case            True for case sensitive.
*    @access public
*    @author Marcus Baker (http://lastcraft.com)
*    @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.Lexer = function(parser, start, case_sensitive)
{
    start = start || 'accept';
    this._case = case_sensitive || false;
    this._regexes = {};
    this._parser = parser;
    this._mode = new WYMeditor.StateStack(start);
    this._mode_handlers = {};
    this._mode_handlers[start] = start;
    return this;
};

/**
*    Adds a token search pattern for a particular
*    parsing mode. The pattern does not change the
*    current mode.
*    @param string pattern      Perl style regex, but ( and )
*                                lose the usual meaning.
*    @param string mode         Should only apply this
*                                pattern when dealing with
*                                this type of input.
*    @access public
*/
WYMeditor.Lexer.prototype.addPattern = function(pattern, mode)
{
    mode = mode || "accept";
    if (typeof this._regexes[mode] == 'undefined') {
        this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
    }
    this._regexes[mode].addPattern(pattern);
    if (typeof this._mode_handlers[mode] == 'undefined') {
        this._mode_handlers[mode] = mode;
    }
};

/**
*    Adds a pattern that will enter a new parsing
*    mode. Useful for entering parenthesis, strings,
*    tags, etc.
*    @param string pattern      Perl style regex, but ( and )
*                                lose the usual meaning.
*    @param string mode         Should only apply this
*                                pattern when dealing with
*                                this type of input.
*    @param string new_mode     Change parsing to this new
*                                nested mode.
*    @access public
*/
WYMeditor.Lexer.prototype.addEntryPattern = function(pattern, mode, new_mode)
{
    if (typeof this._regexes[mode] == 'undefined') {
        this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
    }
    this._regexes[mode].addPattern(pattern, new_mode);
    if (typeof this._mode_handlers[new_mode] == 'undefined') {
        this._mode_handlers[new_mode] = new_mode;
    }
};

/**
*    Adds a pattern that will exit the current mode
*    and re-enter the previous one.
*    @param string pattern      Perl style regex, but ( and )
*                                lose the usual meaning.
*    @param string mode         Mode to leave.
*    @access public
*/
WYMeditor.Lexer.prototype.addExitPattern = function(pattern, mode)
{
    if (typeof this._regexes[mode] == 'undefined') {
        this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
    }
    this._regexes[mode].addPattern(pattern, "__exit");
    if (typeof this._mode_handlers[mode] == 'undefined') {
        this._mode_handlers[mode] = mode;
    }
};

/**
*    Adds a pattern that has a special mode. Acts as an entry
*    and exit pattern in one go, effectively calling a special
*    parser handler for this token only.
*    @param string pattern      Perl style regex, but ( and )
*                                lose the usual meaning.
*    @param string mode         Should only apply this
*                                pattern when dealing with
*                                this type of input.
*    @param string special      Use this mode for this one token.
*    @access public
*/
WYMeditor.Lexer.prototype.addSpecialPattern =  function(pattern, mode, special)
{
    if (typeof this._regexes[mode] == 'undefined') {
        this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
    }
    this._regexes[mode].addPattern(pattern, '_'+special);
    if (typeof this._mode_handlers[special] == 'undefined') {
        this._mode_handlers[special] = special;
    }
};

/**
*    Adds a mapping from a mode to another handler.
*    @param string mode        Mode to be remapped.
*    @param string handler     New target handler.
*    @access public
*/
WYMeditor.Lexer.prototype.mapHandler = function(mode, handler)
{
    this._mode_handlers[mode] = handler;
};

/**
*    Splits the page text into tokens. Will fail
*    if the handlers report an error or if no
*    content is consumed. If successful then each
*    unparsed and parsed token invokes a call to the
*    held listener.
*    @param string raw        Raw HTML text.
*    @return boolean           True on success, else false.
*    @access public
*/
WYMeditor.Lexer.prototype.parse = function(raw) {
    if (typeof this._parser == 'undefined') {
        return false;
    }

    var length = raw.length;
    var parsed;
    while (typeof (parsed = this._reduce(raw)) == 'object') {
        raw = parsed[0];
        var unmatched = parsed[1];
        var matched = parsed[2];
        var mode = parsed[3];

        if (! this._dispatchTokens(unmatched, matched, mode)) {
            return false;
        }

        if (raw === '') {
            return true;
        }
        if (raw.length == length) {
            return false;
        }
        length = raw.length;
    }
    if (! parsed ) {
        return false;
    }

    return this._invokeParser(raw, WYMeditor.LEXER_UNMATCHED);
};

/**
*    Sends the matched token and any leading unmatched
*    text to the parser changing the lexer to a new
*    mode if one is listed.
*    @param string unmatched    Unmatched leading portion.
*    @param string matched      Actual token match.
*    @param string mode         Mode after match. A boolean
*                                false mode causes no change.
*    @return boolean             False if there was any error
*                                from the parser.
*    @access private
*/
WYMeditor.Lexer.prototype._dispatchTokens = function(unmatched, matched, mode) {
    mode = mode || false;

    if (! this._invokeParser(unmatched, WYMeditor.LEXER_UNMATCHED)) {
        return false;
    }

    if (typeof mode == 'boolean') {
        return this._invokeParser(matched, WYMeditor.LEXER_MATCHED);
    }
    if (this._isModeEnd(mode)) {
        if (! this._invokeParser(matched, WYMeditor.LEXER_EXIT)) {
            return false;
        }
        return this._mode.leave();
    }
    if (this._isSpecialMode(mode)) {
        this._mode.enter(this._decodeSpecial(mode));
        if (! this._invokeParser(matched, WYMeditor.LEXER_SPECIAL)) {
            return false;
        }
        return this._mode.leave();
    }
    this._mode.enter(mode);

    return this._invokeParser(matched, WYMeditor.LEXER_ENTER);
};

/**
*    Tests to see if the new mode is actually to leave
*    the current mode and pop an item from the matching
*    mode stack.
*    @param string mode    Mode to test.
*    @return boolean        True if this is the exit mode.
*    @access private
*/
WYMeditor.Lexer.prototype._isModeEnd = function(mode) {
    return (mode === "__exit");
};

/**
*    Test to see if the mode is one where this mode
*    is entered for this token only and automatically
*    leaves immediately afterwoods.
*    @param string mode    Mode to test.
*    @return boolean        True if this is the exit mode.
*    @access private
*/
WYMeditor.Lexer.prototype._isSpecialMode = function(mode) {
    return (mode.substring(0,1) == "_");
};

/**
*    Strips the magic underscore marking single token
*    modes.
*    @param string mode    Mode to decode.
*    @return string         Underlying mode name.
*    @access private
*/
WYMeditor.Lexer.prototype._decodeSpecial = function(mode) {
    return mode.substring(1);
};

/**
*    Calls the parser method named after the current
*    mode. Empty content will be ignored. The lexer
*    has a parser handler for each mode in the lexer.
*    @param string content        Text parsed.
*    @param boolean is_match      Token is recognised rather
*                                  than unparsed data.
*    @access private
*/
WYMeditor.Lexer.prototype._invokeParser = function(content, is_match) {
    if (content === '') {
        return true;
    }
    var current = this._mode.getCurrent();
    var handler = this._mode_handlers[current];
    var result = this._parser[handler](content, is_match);
    return result;
};

/**
*    Tries to match a chunk of text and if successful
*    removes the recognised chunk and any leading
*    unparsed data. Empty strings will not be matched.
*    @param string raw         The subject to parse. This is the
*                               content that will be eaten.
*    @return array/boolean      Three item list of unparsed
*                               content followed by the
*                               recognised token and finally the
*                               action the parser is to take.
*                               True if no match, false if there
*                               is a parsing error.
*    @access private
*/
WYMeditor.Lexer.prototype._reduce = function(raw) {
    var matched = this._regexes[this._mode.getCurrent()].match(raw);
    var match = matched[1];
    var action = matched[0];
    if (action) {
        var unparsed_character_count = raw.indexOf(match);
        var unparsed = raw.substr(0, unparsed_character_count);
        raw = raw.substring(unparsed_character_count + match.length);
        return [raw, unparsed, match, action];
    }
    return true;
};


/**
*    Compounded regular expression. Any of
*    the contained patterns could match and
*    when one does, it's label is returned.
*
*    Constructor. Starts with no patterns.
*    @param boolean case    True for case sensitive, false
*                            for insensitive.
*    @access public
*    @author Marcus Baker (http://lastcraft.com)
*    @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.ParallelRegex = function(case_sensitive)
{
    this._case = case_sensitive;
    this._patterns = [];
    this._labels = [];
    this._regex = null;
    return this;
};


/**
*    Adds a pattern with an optional label.
*    @param string pattern      Perl style regex, but ( and )
*                                lose the usual meaning.
*    @param string label        Label of regex to be returned
*                                on a match.
*    @access public
*/
WYMeditor.ParallelRegex.prototype.addPattern = function(pattern, label)
{
    label = label || true;
    var count = this._patterns.length;
    this._patterns[count] = pattern;
    this._labels[count] = label;
    this._regex = null;
};

/**
*    Attempts to match all patterns at once against
*    a string.
*    @param string subject      String to match against.
*
*    @return boolean             True on success.
*    @return string match         First matched portion of
*                                subject.
*    @access public
*/
WYMeditor.ParallelRegex.prototype.match = function(subject)
{
    if (this._patterns.length === 0) {
        return [false, ''];
    }
    var matches = subject.match(this._getCompoundedRegex());

    if(!matches){
        return [false, ''];
    }
    var match = matches[0];
    for (var i = 1; i < matches.length; i++) {
        if (matches[i]) {
            return [this._labels[i-1], match];
        }
    }
    return [true, matches[0]];
};

/**
*    Compounds the patterns into a single
*    regular expression separated with the
*    "or" operator. Caches the regex.
*    Will automatically escape (, ) and / tokens.
*    @param array patterns    List of patterns in order.
*    @access private
*/
WYMeditor.ParallelRegex.prototype._getCompoundedRegex = function()
{
    if (this._regex === null) {
        for (var i = 0, count = this._patterns.length; i < count; i++) {
            this._patterns[i] = '(' + this._untokenizeRegex(this._tokenizeRegex(this._patterns[i]).replace(/([\/\(\)])/g,'\\$1')) + ')';
        }
        this._regex = new RegExp(this._patterns.join("|") ,this._getPerlMatchingFlags());
    }
    return this._regex;
};

/**
* Escape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._tokenizeRegex = function(regex)
{
    return regex.
    replace(/\(\?(i|m|s|x|U)\)/,     '~~~~~~Tk1\$1~~~~~~').
    replace(/\(\?(\-[i|m|s|x|U])\)/, '~~~~~~Tk2\$1~~~~~~').
    replace(/\(\?\=(.*)\)/,          '~~~~~~Tk3\$1~~~~~~').
    replace(/\(\?\!(.*)\)/,          '~~~~~~Tk4\$1~~~~~~').
    replace(/\(\?\<\=(.*)\)/,        '~~~~~~Tk5\$1~~~~~~').
    replace(/\(\?\<\!(.*)\)/,        '~~~~~~Tk6\$1~~~~~~').
    replace(/\(\?\:(.*)\)/,          '~~~~~~Tk7\$1~~~~~~');
};

/**
* Unscape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._untokenizeRegex = function(regex)
{
    return regex.
    replace(/~~~~~~Tk1(.{1})~~~~~~/,    "(?\$1)").
    replace(/~~~~~~Tk2(.{2})~~~~~~/,    "(?\$1)").
    replace(/~~~~~~Tk3(.*)~~~~~~/,      "(?=\$1)").
    replace(/~~~~~~Tk4(.*)~~~~~~/,      "(?!\$1)").
    replace(/~~~~~~Tk5(.*)~~~~~~/,      "(?<=\$1)").
    replace(/~~~~~~Tk6(.*)~~~~~~/,      "(?<!\$1)").
    replace(/~~~~~~Tk7(.*)~~~~~~/,      "(?:\$1)");
};


/**
*    Accessor for perl regex mode flags to use.
*    @return string       Perl regex flags.
*    @access private
*/
WYMeditor.ParallelRegex.prototype._getPerlMatchingFlags = function()
{
    return (this._case ? "m" : "mi");
};


/**
*    States for a stack machine.
*
*    Constructor. Starts in named state.
*    @param string start        Starting state name.
*    @access public
*    @author Marcus Baker (http://lastcraft.com)
*    @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.StateStack = function(start)
{
    this._stack = [start];
    return this;
};

/**
*    Accessor for current state.
*    @return string       State.
*    @access public
*/
WYMeditor.StateStack.prototype.getCurrent = function()
{
    return this._stack[this._stack.length - 1];
};

/**
*    Adds a state to the stack and sets it
*    to be the current state.
*    @param string state        New state.
*    @access public
*/
WYMeditor.StateStack.prototype.enter = function(state)
{
    this._stack.push(state);
};

/**
*    Leaves the current state and reverts
*    to the previous one.
*    @return boolean    False if we drop off
*                       the bottom of the list.
*    @access public
*/
WYMeditor.StateStack.prototype.leave = function()
{
    if (this._stack.length == 1) {
        return false;
    }
    this._stack.pop();
    return true;
};


/**
* This are the rules for breaking the XHTML code into events
* handled by the provided parser.
*
*    @author Marcus Baker (http://lastcraft.com)
*    @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlLexer = function(parser) {
    jQuery.extend(this, new WYMeditor.Lexer(parser, 'Text'));

    this.mapHandler('Text', 'Text');

    this.addTokens();

    this.init();

    return this;
};


WYMeditor.XhtmlLexer.prototype.init = function() {
};

WYMeditor.XhtmlLexer.prototype.addTokens = function() {
    this.addCommentTokens('Text');
    this.addScriptTokens('Text');
    this.addCssTokens('Text');
    this.addTagTokens('Text');
};

WYMeditor.XhtmlLexer.prototype.addCommentTokens = function(scope) {
    this.addEntryPattern("<!--", scope, 'Comment');
    this.addExitPattern("-->", 'Comment');
};

WYMeditor.XhtmlLexer.prototype.addScriptTokens = function(scope) {
    this.addEntryPattern("<script", scope, 'Script');
    this.addExitPattern("</script>", 'Script');
};

WYMeditor.XhtmlLexer.prototype.addCssTokens = function(scope) {
    this.addEntryPattern("<style", scope, 'Css');
    this.addExitPattern("</style>", 'Css');
};

WYMeditor.XhtmlLexer.prototype.addTagTokens = function(scope) {
    this.addSpecialPattern("<\\s*[a-z0-9:\-]+\\s*/>", scope, 'SelfClosingTag');
    this.addSpecialPattern("<\\s*[a-z0-9:\-]+\\s*>", scope, 'OpeningTag');
    this.addEntryPattern("<[a-z0-9:\-]+"+'[\\\/ \\\>]+', scope, 'OpeningTag');
    this.addInTagDeclarationTokens('OpeningTag');

    this.addSpecialPattern("</\\s*[a-z0-9:\-]+\\s*>", scope, 'ClosingTag');

};

WYMeditor.XhtmlLexer.prototype.addInTagDeclarationTokens = function(scope) {
    this.addSpecialPattern('\\s+', scope, 'Ignore');

    this.addAttributeTokens(scope);

    this.addExitPattern('/>', scope);
    this.addExitPattern('>', scope);

};

WYMeditor.XhtmlLexer.prototype.addAttributeTokens = function(scope) {
    this.addSpecialPattern("\\s*[a-z-_0-9]*:?[a-z-_0-9]+\\s*(?=\=)\\s*", scope, 'TagAttributes');

    this.addEntryPattern('=\\s*"', scope, 'DoubleQuotedAttribute');
    this.addPattern("\\\\\"", 'DoubleQuotedAttribute');
    this.addExitPattern('"', 'DoubleQuotedAttribute');

    this.addEntryPattern("=\\s*'", scope, 'SingleQuotedAttribute');
    this.addPattern("\\\\'", 'SingleQuotedAttribute');
    this.addExitPattern("'", 'SingleQuotedAttribute');

    this.addSpecialPattern('=\\s*[^>\\s]*', scope, 'UnquotedAttribute');
};


/**
* XHTML Parser.
*
* This XHTML parser will trigger the events available on on
* current SaxListener
*
*    @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlParser = function(Listener, mode) {
    mode = mode || 'Text';
    this._Lexer = new WYMeditor.XhtmlLexer(this);
    this._Listener = Listener;
    this._mode = mode;
    this._matches = [];
    this._last_match = '';
    this._current_match = '';

    return this;
};

WYMeditor.XhtmlParser.prototype.parse = function(raw) {
    this._Lexer.parse(this.beforeParsing(raw));
    return this.afterParsing(this._Listener.getResult());
};

WYMeditor.XhtmlParser.prototype.beforeParsing = function(raw) {
    if (raw.match(/class="MsoNormal"/) || raw.match(/ns = "urn:schemas-microsoft-com/)) {
        // Useful for cleaning up content pasted from other sources (MSWord)
        this._Listener.avoidStylingTagsAndAttributes();
    }

    return this._Listener.beforeParsing(raw);
};

WYMeditor.XhtmlParser.prototype.afterParsing = function(parsed) {
    if (this._Listener._avoiding_tags_implicitly) {
        this._Listener.allowStylingTagsAndAttributes();
    }
    return this._Listener.afterParsing(parsed);
};


WYMeditor.XhtmlParser.prototype.Ignore = function(match, state) {
    return true;
};

WYMeditor.XhtmlParser.prototype.Text = function(text) {
    this._Listener.addContent(text);
    return true;
};

WYMeditor.XhtmlParser.prototype.Comment = function(match, status) {
    return this._addNonTagBlock(match, status, 'addComment');
};

WYMeditor.XhtmlParser.prototype.Script = function(match, status) {
    return this._addNonTagBlock(match, status, 'addScript');
};

WYMeditor.XhtmlParser.prototype.Css = function(match, status) {
    return this._addNonTagBlock(match, status, 'addCss');
};

WYMeditor.XhtmlParser.prototype._addNonTagBlock = function(match, state, type) {
    switch (state) {
        case WYMeditor.LEXER_ENTER:
            this._non_tag = match;
            break;
        case WYMeditor.LEXER_UNMATCHED:
            this._non_tag += match;
            break;
        case WYMeditor.LEXER_EXIT:
            switch(type) {
                case 'addComment':
                    this._Listener.addComment(this._non_tag+match);
                    break;
                case 'addScript':
                    this._Listener.addScript(this._non_tag+match);
                    break;
                case 'addCss':
                    this._Listener.addCss(this._non_tag+match);
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
    return true;
};

WYMeditor.XhtmlParser.prototype.SelfClosingTag = function(match, state) {
    var result = this.OpeningTag(match, state);
    var tag = this.normalizeTag(match);
    return this.ClosingTag(match, state);
};

WYMeditor.XhtmlParser.prototype.OpeningTag = function(match, state) {
    switch (state){
        case WYMeditor.LEXER_ENTER:
            this._tag = this.normalizeTag(match);
            this._tag_attributes = {};
            break;
        case WYMeditor.LEXER_SPECIAL:
            this._callOpenTagListener(this.normalizeTag(match));
            break;
        case WYMeditor.LEXER_EXIT:
            this._callOpenTagListener(this._tag, this._tag_attributes);
            break;
        default:
            break;
    }
    return true;
};

WYMeditor.XhtmlParser.prototype.ClosingTag = function(match, state) {
    this._callCloseTagListener(this.normalizeTag(match));
    return true;
};

WYMeditor.XhtmlParser.prototype._callOpenTagListener = function(tag, attributes) {
    attributes = attributes || {};
    this.autoCloseUnclosedBeforeNewOpening(tag);

    if (this._Listener.isBlockTag(tag)) {
        this._Listener._tag_stack.push(tag);
        this._Listener.fixNestingBeforeOpeningBlockTag(tag, attributes);
        this._Listener.openBlockTag(tag, attributes);
        this._increaseOpenTagCounter(tag);
    } else if (this._Listener.isInlineTag(tag)) {
        this._Listener.inlineTag(tag, attributes);
    } else {
        this._Listener.openUnknownTag(tag, attributes);
        this._increaseOpenTagCounter(tag);
    }
    this._Listener.last_tag = tag;
    this._Listener.last_tag_opened = true;
    this._Listener.last_tag_attributes = attributes;
};

WYMeditor.XhtmlParser.prototype._callCloseTagListener = function(tag) {
    if (this._decreaseOpenTagCounter(tag)) {
        this.autoCloseUnclosedBeforeTagClosing(tag);

        if (this._Listener.isBlockTag(tag)) {
            var expected_tag = this._Listener._tag_stack.pop();
            if (expected_tag === false) {
                return;
            } else if (expected_tag !== tag) {
                // If we are expecting extra block closing tags, put the
                // expected tag back on the tag stack.
                if (this._Listener._extraBlockClosingTags) {
                    this._Listener._tag_stack.push(expected_tag);
                    this._Listener.removedExtraBlockClosingTag();
                    return;
                }

                tag = expected_tag;
            }
            this._Listener.closeBlockTag(tag);
        }
    } else {
        if(!this._Listener.isInlineTag(tag)) {
            this._Listener.closeUnopenedTag(tag);
        }
    }

    this._Listener.last_tag = tag;
    this._Listener.last_tag_opened = false;
};

WYMeditor.XhtmlParser.prototype._increaseOpenTagCounter = function(tag) {
    this._Listener._open_tags[tag] = this._Listener._open_tags[tag] || 0;
    this._Listener._open_tags[tag]++;
};

WYMeditor.XhtmlParser.prototype._decreaseOpenTagCounter = function(tag) {
    if (this._Listener._open_tags[tag]) {
        this._Listener._open_tags[tag]--;
        if (this._Listener._open_tags[tag] === 0) {
            this._Listener._open_tags[tag] = undefined;
        }
        return true;
    }
    return false;
};

WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeNewOpening = function(new_tag) {
    this._autoCloseUnclosed(new_tag, false);
};

WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeTagClosing = function(tag) {
    this._autoCloseUnclosed(tag, true);
};

WYMeditor.XhtmlParser.prototype._autoCloseUnclosed = function(new_tag, closing) {
    closing = closing || false;
    if (this._Listener._open_tags) {
        for (var tag in this._Listener._open_tags) {
            if (this._Listener.shouldCloseTagAutomatically(tag, new_tag, closing)) {
                this._callCloseTagListener(tag, true);
            }
        }
    }
};

WYMeditor.XhtmlParser.prototype.getTagReplacements = function() {
    return this._Listener.getTagReplacements();
};

WYMeditor.XhtmlParser.prototype.normalizeTag = function(tag) {
    tag = tag.replace(/^([\s<\/>]*)|([\s<\/>]*)$/gm,'').toLowerCase();
    var tags = this._Listener.getTagReplacements();
    if (tags[tag]) {
        return tags[tag];
    }
    return tag;
};

WYMeditor.XhtmlParser.prototype.TagAttributes = function(match, state) {
    if (WYMeditor.LEXER_SPECIAL == state) {
        this._current_attribute = match;
    }
    return true;
};

WYMeditor.XhtmlParser.prototype.DoubleQuotedAttribute = function(match, state) {
    if (WYMeditor.LEXER_UNMATCHED == state) {
        this._tag_attributes[this._current_attribute] = match;
    }
    return true;
};

WYMeditor.XhtmlParser.prototype.SingleQuotedAttribute = function(match, state) {
    if (WYMeditor.LEXER_UNMATCHED == state) {
        this._tag_attributes[this._current_attribute] = match;
    }
    return true;
};

WYMeditor.XhtmlParser.prototype.UnquotedAttribute = function(match, state) {
    this._tag_attributes[this._current_attribute] = match.replace(/^=/,'');
    return true;
};


/**
* XHTML Sax parser.
*
*    @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlSaxListener = function() {
    this.output = '';
    this.helper = new WYMeditor.XmlHelper();
    this._open_tags = {};
    this.validator = WYMeditor.XhtmlValidator;
    this._tag_stack = [];
    this.avoided_tags = [];
    this._insert_before_closing = [];
    this._insert_after_closing = [];
    this._last_node_was_text = false;
    this._consecutive_brs = 0;

    // A string of the tag name of the last open tag added to the output.
    this._lastAddedOpenTag = '';

    // A boolean that should be set to true when the parser is within a list
    // item and that should be set to false when the parser is no longer
    // withing a list item.
    this._insideLI = false;

    // An array of tags that should have their contents unwrapped if the tag is
    // within a list item.
    this.tagsToUnwrapInLists =
        WYMeditor.DocumentStructureManager.VALID_DEFAULT_ROOT_CONTAINERS;

    // If any of these inline tags is found in the root, just remove them.
    this._rootInlineTagsToRemove = ['br'];

    // A counter to keep track of the number of extra block closing tags that
    // should be expected by the parser because of the removal of that
    // element's opening tag.
    this._extraBlockClosingTags = 0;

    this._insideTagToRemove = false;
    // A boolean that indicates if a spacer line break should be added before
    // the next element in a list item to preserve spacing because of the
    // unwrapping of a block tag before the element.
    this._addSpacerBeforeElementInLI = false;

    // This flag is set to true if the parser is currently inside a tag flagged
    // for removal. Nothing will be added to the output while this flag is set
    // to true.
    this._insideTagToRemove = false;

    // If the last tag was not added to the output, this flag is set to true.
    // This is needed because if we are trying to fix an invalid tag by nesting
    // it in the last outputted tag as in the case of some invalid lists, if
    // the last tag was removed, the invalid tag should just be removed as well
    // instead of trying to fix it by nesting it in a tag that was already
    // removed from the output.
    this._lastTagRemoved = false;

    // When correcting invalid list nesting, situations can occur that will
    // result in an extra closing LI tags coming up later in the parser. When
    // one of these situations occurs, this counter is incremented so that it
    // can be referenced to find how many extra LI closing tags to expect. This
    // counter should be decremented everytime one of these extra LI closing
    // tags is removed.
    this._extraLIClosingTags = 0;

    // This is for storage of a tag's index in the tag stack so that the
    // Listener can use it to check for when the tag has been closed (i.e. when
    // the top of the tag stack is at the stored index again).
    this._removedTagStackIndex = 0;

    this.entities = {
        '&nbsp;':'&#160;','&iexcl;':'&#161;','&cent;':'&#162;',
        '&pound;':'&#163;','&curren;':'&#164;','&yen;':'&#165;',
        '&brvbar;':'&#166;','&sect;':'&#167;','&uml;':'&#168;',
        '&copy;':'&#169;','&ordf;':'&#170;','&laquo;':'&#171;',
        '&not;':'&#172;','&shy;':'&#173;','&reg;':'&#174;',
        '&macr;':'&#175;','&deg;':'&#176;','&plusmn;':'&#177;',
        '&sup2;':'&#178;','&sup3;':'&#179;','&acute;':'&#180;',
        '&micro;':'&#181;','&para;':'&#182;','&middot;':'&#183;',
        '&cedil;':'&#184;','&sup1;':'&#185;','&ordm;':'&#186;',
        '&raquo;':'&#187;','&frac14;':'&#188;','&frac12;':'&#189;',
        '&frac34;':'&#190;','&iquest;':'&#191;','&Agrave;':'&#192;',
        '&Aacute;':'&#193;','&Acirc;':'&#194;','&Atilde;':'&#195;',
        '&Auml;':'&#196;','&Aring;':'&#197;','&AElig;':'&#198;',
        '&Ccedil;':'&#199;','&Egrave;':'&#200;','&Eacute;':'&#201;',
        '&Ecirc;':'&#202;','&Euml;':'&#203;','&Igrave;':'&#204;',
        '&Iacute;':'&#205;','&Icirc;':'&#206;','&Iuml;':'&#207;',
        '&ETH;':'&#208;','&Ntilde;':'&#209;','&Ograve;':'&#210;',
        '&Oacute;':'&#211;','&Ocirc;':'&#212;','&Otilde;':'&#213;',
        '&Ouml;':'&#214;','&times;':'&#215;','&Oslash;':'&#216;',
        '&Ugrave;':'&#217;','&Uacute;':'&#218;','&Ucirc;':'&#219;',
        '&Uuml;':'&#220;','&Yacute;':'&#221;','&THORN;':'&#222;',
        '&szlig;':'&#223;','&agrave;':'&#224;','&aacute;':'&#225;',
        '&acirc;':'&#226;','&atilde;':'&#227;','&auml;':'&#228;',
        '&aring;':'&#229;','&aelig;':'&#230;','&ccedil;':'&#231;',
        '&egrave;':'&#232;','&eacute;':'&#233;','&ecirc;':'&#234;',
        '&euml;':'&#235;','&igrave;':'&#236;','&iacute;':'&#237;',
        '&icirc;':'&#238;','&iuml;':'&#239;','&eth;':'&#240;',
        '&ntilde;':'&#241;','&ograve;':'&#242;','&oacute;':'&#243;',
        '&ocirc;':'&#244;','&otilde;':'&#245;','&ouml;':'&#246;',
        '&divide;':'&#247;','&oslash;':'&#248;','&ugrave;':'&#249;',
        '&uacute;':'&#250;','&ucirc;':'&#251;','&uuml;':'&#252;',
        '&yacute;':'&#253;','&thorn;':'&#254;','&yuml;':'&#255;',
        '&OElig;':'&#338;','&oelig;':'&#339;','&Scaron;':'&#352;',
        '&scaron;':'&#353;','&Yuml;':'&#376;','&fnof;':'&#402;',
        '&circ;':'&#710;','&tilde;':'&#732;','&Alpha;':'&#913;',
        '&Beta;':'&#914;','&Gamma;':'&#915;','&Delta;':'&#916;',
        '&Epsilon;':'&#917;','&Zeta;':'&#918;','&Eta;':'&#919;',
        '&Theta;':'&#920;','&Iota;':'&#921;','&Kappa;':'&#922;',
        '&Lambda;':'&#923;','&Mu;':'&#924;','&Nu;':'&#925;',
        '&Xi;':'&#926;','&Omicron;':'&#927;','&Pi;':'&#928;',
        '&Rho;':'&#929;','&Sigma;':'&#931;','&Tau;':'&#932;',
        '&Upsilon;':'&#933;','&Phi;':'&#934;','&Chi;':'&#935;',
        '&Psi;':'&#936;','&Omega;':'&#937;','&alpha;':'&#945;',
        '&beta;':'&#946;','&gamma;':'&#947;','&delta;':'&#948;',
        '&epsilon;':'&#949;','&zeta;':'&#950;','&eta;':'&#951;',
        '&theta;':'&#952;','&iota;':'&#953;','&kappa;':'&#954;',
        '&lambda;':'&#955;','&mu;':'&#956;','&nu;':'&#957;',
        '&xi;':'&#958;','&omicron;':'&#959;','&pi;':'&#960;',
        '&rho;':'&#961;','&sigmaf;':'&#962;','&sigma;':'&#963;',
        '&tau;':'&#964;','&upsilon;':'&#965;','&phi;':'&#966;',
        '&chi;':'&#967;','&psi;':'&#968;','&omega;':'&#969;',
        '&thetasym;':'&#977;','&upsih;':'&#978;','&piv;':'&#982;',
        '&ensp;':'&#8194;','&emsp;':'&#8195;','&thinsp;':'&#8201;',
        '&zwnj;':'&#8204;','&zwj;':'&#8205;','&lrm;':'&#8206;',
        '&rlm;':'&#8207;','&ndash;':'&#8211;','&mdash;':'&#8212;',
        '&lsquo;':'&#8216;','&rsquo;':'&#8217;','&sbquo;':'&#8218;',
        '&ldquo;':'&#8220;','&rdquo;':'&#8221;','&bdquo;':'&#8222;',
        '&dagger;':'&#8224;','&Dagger;':'&#8225;','&bull;':'&#8226;',
        '&hellip;':'&#8230;','&permil;':'&#8240;','&prime;':'&#8242;',
        '&Prime;':'&#8243;','&lsaquo;':'&#8249;','&rsaquo;':'&#8250;',
        '&oline;':'&#8254;','&frasl;':'&#8260;','&euro;':'&#8364;',
        '&image;':'&#8465;','&weierp;':'&#8472;','&real;':'&#8476;',
        '&trade;':'&#8482;','&alefsym;':'&#8501;','&larr;':'&#8592;',
        '&uarr;':'&#8593;','&rarr;':'&#8594;','&darr;':'&#8595;',
        '&harr;':'&#8596;','&crarr;':'&#8629;','&lArr;':'&#8656;',
        '&uArr;':'&#8657;','&rArr;':'&#8658;','&dArr;':'&#8659;',
        '&hArr;':'&#8660;','&forall;':'&#8704;','&part;':'&#8706;',
        '&exist;':'&#8707;','&empty;':'&#8709;','&nabla;':'&#8711;',
        '&isin;':'&#8712;','&notin;':'&#8713;','&ni;':'&#8715;',
        '&prod;':'&#8719;','&sum;':'&#8721;','&minus;':'&#8722;',
        '&lowast;':'&#8727;','&radic;':'&#8730;','&prop;':'&#8733;',
        '&infin;':'&#8734;','&ang;':'&#8736;','&and;':'&#8743;',
        '&or;':'&#8744;','&cap;':'&#8745;','&cup;':'&#8746;',
        '&int;':'&#8747;','&there4;':'&#8756;','&sim;':'&#8764;',
        '&cong;':'&#8773;','&asymp;':'&#8776;','&ne;':'&#8800;',
        '&equiv;':'&#8801;','&le;':'&#8804;','&ge;':'&#8805;',
        '&sub;':'&#8834;','&sup;':'&#8835;','&nsub;':'&#8836;',
        '&sube;':'&#8838;','&supe;':'&#8839;','&oplus;':'&#8853;',
        '&otimes;':'&#8855;','&perp;':'&#8869;','&sdot;':'&#8901;',
        '&lceil;':'&#8968;','&rceil;':'&#8969;','&lfloor;':'&#8970;',
        '&rfloor;':'&#8971;','&lang;':'&#9001;','&rang;':'&#9002;',
        '&loz;':'&#9674;','&spades;':'&#9824;','&clubs;':'&#9827;',
        '&hearts;':'&#9829;','&diams;':'&#9830;'};

    this.block_tags = [
        "a", "abbr", "acronym", "address", "area", "b",
        "base", "bdo", "big", "blockquote", "body", "button",
        "caption", "cite", "code", "colgroup", "dd", "del", "div",
        "dfn", "dl", "dt", "em", "fieldset", "form", "head", "h1", "h2",
        "h3", "h4", "h5", "h6", "html", "i", "iframe", "ins",
        "kbd", "label", "legend", "li", "map", "noscript",
        "object", "ol", "optgroup", "option", "p", "param", "pre", "q",
        "samp", "script", "select", "small", "span", "strong", "style",
        "sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th",
        "thead", "title", "tr", "tt", "ul", "var", "extends"];


    this.inline_tags = ["br", "col", "hr", "img", "input"];

    return this;
};

WYMeditor.XhtmlSaxListener.prototype.shouldCloseTagAutomatically = function(tag, now_on_tag, closing) {
    if (tag != 'td' && tag != 'option') {
        // We only attempt auto-closing for these tags
        return false;
    }
    var openCount = this._open_tags[tag];
    if (!openCount) {
        /// If there are no open tags, it would be pretty silly to try and close the tag
        return false;
    }

    if (tag == 'td') {
        var openTrCount = this._open_tags['tr'] || 0;
        // We use count instead of existence to handle nested tables/rows
        if (!closing && now_on_tag === 'td' && openCount >= openTrCount) {
            return true;
        }
        if (closing && now_on_tag == 'tr' && openCount > openTrCount) {
            return true;
        }
    } else if (tag == 'option') {
        if ((closing && now_on_tag == 'select') || (!closing && now_on_tag == 'option')) {
            return true;
        }
    }
    return false;
};

WYMeditor.XhtmlSaxListener.prototype.beforeParsing = function(raw) {
    this.output = '';

    // Reset attributes that might bleed over between parsing
    this._insert_before_closing = [];
    this._insert_after_closing = [];
    this._open_tags = {};
    this._tag_stack = [];
    this._last_node_was_text = false;
    this._lastTagRemoved = false;
    this._insideTagToRemove = false;
    this.last_tag = null;

    return raw;
};

WYMeditor.XhtmlSaxListener.prototype.afterParsing = function(xhtml) {
    xhtml = this.replaceNamedEntities(xhtml);
    xhtml = this.joinRepeatedEntities(xhtml);
    xhtml = this.removeEmptyTags(xhtml);
    xhtml = this.removeBrInPre(xhtml);

    return xhtml;
};

WYMeditor.XhtmlSaxListener.prototype.replaceNamedEntities = function(xhtml) {
    for (var entity in this.entities) {
        xhtml = xhtml.replace(new RegExp(entity, 'g'), this.entities[entity]);
    }
    return xhtml;
};

WYMeditor.XhtmlSaxListener.prototype.joinRepeatedEntities = function(xhtml) {
    var tags = 'em|strong|sub|sup|acronym|pre|del|address';
    return xhtml.replace(new RegExp('<\/('+tags+')><\\1>' ,''), '').
            replace(
                new RegExp('(\s*<('+tags+')>\s*){2}(.*)(\s*<\/\\2>\s*){2}' ,''),
                '<\$2>\$3<\$2>');
};

WYMeditor.XhtmlSaxListener.prototype.removeEmptyTags = function(xhtml) {
    return xhtml.replace(
            new RegExp(
                '<('+this.block_tags.join("|").
                    replace(/\|td/,'').
                    replace(/\|th/, '') +
                ')>(<br \/>|&#160;|&nbsp;|\\s)*<\/\\1>' ,'g'),
            '');
};

WYMeditor.XhtmlSaxListener.prototype.removeBrInPre = function(xhtml) {
    var matches = xhtml.match(new RegExp('<pre[^>]*>(.*?)<\/pre>','gmi'));
    if (matches) {
        for (var i=0; i<matches.length; i++) {
            xhtml = xhtml.replace(
                matches[i],
                matches[i].replace(new RegExp('<br \/>', 'g'), String.fromCharCode(13,10)));
        }
    }
    return xhtml;
};

WYMeditor.XhtmlSaxListener.prototype.getResult = function() {
    return this.output;
};

WYMeditor.XhtmlSaxListener.prototype.getTagReplacements = function() {
    return {'b':'strong', 'i':'em'};
};

WYMeditor.XhtmlSaxListener.prototype.getTagForStyle = function (style) {
    if (/sub/.test(style)) {
        return 'sub';
    } else if (/super/.test(style)) {
        return 'sup';
    } else if (/bold/.test(style)) {
        return 'strong';
    } else if (/italic/.test(style)) {
        return 'em';
    }

    return false;
};

WYMeditor.XhtmlSaxListener.prototype.addContent = function(text) {
    if (this.last_tag && this.last_tag == 'li') {
        // We should strip trailing newlines from text inside li tags because
        // IE adds random significant newlines inside nested lists
        text = text.replace(/(\r|\n|\r\n)+$/g, '');

        // Let's also normalize multiple newlines down to a single space
        text = text.replace(/(\r|\n|\r\n)+/g, ' ');
    }
    if (text.replace(/^\s+|\s+$/g, '').length > 0) {
        // Don't count it as text if it's empty
        this._last_node_was_text = true;
        if (this._addSpacerBeforeElementInLI) {
            this.output += '<br />';
            this._addSpacerBeforeElementInLI = false;
        }
    }
    if (!this._insideTagToRemove) {
        this.output += text;
    }
};

WYMeditor.XhtmlSaxListener.prototype.addComment = function(text) {
    if (this.remove_comments || this._insideTagToRemove) {
        return;
    }
    this.output += text;
};

WYMeditor.XhtmlSaxListener.prototype.addScript = function(text) {
    if (this.remove_scripts || this._insideTagToRemove) {
        return;
    }
    this.output += text;
};

WYMeditor.XhtmlSaxListener.prototype.addCss = function(text) {
    if (this.remove_embeded_styles || this._insideTagToRemove) {
        return;
    }
    this.output += text;
};

WYMeditor.XhtmlSaxListener.prototype.openBlockTag = function(tag, attributes) {
    var lastNodeWasText = this._last_node_was_text;
    this._last_node_was_text = false;

    if (this._insideTagToRemove) {
        // If we're currently in a block marked for removal, don't add it to
        // the output.
        return;
    }
    if (this._shouldRemoveTag(tag, attributes)) {
        // If this tag is marked for removal, set a flag signifying that
        // we're in a tag to remove and mark the position in the tag stack
        // of this tag so that we know when we've reached the end of it.
        this._insideTagToRemove = true;
        this._removedTagStackIndex = this._tag_stack.length - 1;
        return;
    }

    // If we're currently inside an LI and this tag is not allowed inside
    // an LI, unwrap the tag by not adding it to the output.
    if (this._insideLI && jQuery.inArray(tag, this.tagsToUnwrapInLists) > -1) {
        if (this._lastAddedOpenTag !== 'li' || lastNodeWasText) {
            // If there was content inside the LI before this unwrapped block,
            // insert a line break so that the content retains its spacing.
            this.output += '<br />';
            this._addSpacerBeforeElementInLI = false;
        }
        this._tag_stack.pop();
        this._extraBlockClosingTags++;
        return;
    }

    // Add a line break spacer before adding the open block tag if necessary
    // and if the tag is not a list element.
    if (this._addSpacerBeforeElementInLI &&
            tag !== 'li' &&
            jQuery.inArray(tag, WYMeditor.LIST_TYPE_ELEMENTS) === -1) {
        this.output += '<br />';
        this._addSpacerBeforeElementInLI = false;
    }

    attributes = this.validator.getValidTagAttributes(tag, attributes);
    attributes = this.removeUnwantedClasses(attributes);

    // Handle Mozilla and Safari styled spans
    if (tag === 'span' && attributes.style) {
        var new_tag = this.getTagForStyle(attributes.style);
        if (new_tag) {
            tag = new_tag;
            this._tag_stack.pop();
            this._tag_stack.push(tag);
            attributes.style = '';
        }
    }

    if (tag === 'li') {
        this._insideLI = true;
        this._addSpacerBeforeElementInLI = false;
    }

    this.output += this.helper.tag(tag, attributes, true);
    this._lastAddedOpenTag = tag;
    this._lastTagRemoved = false;
};

WYMeditor.XhtmlSaxListener.prototype.inlineTag = function(tag, attributes) {
    if (this._insideTagToRemove || this._shouldRemoveTag(tag, attributes)) {
        // If we're currently in a block marked for removal or if this tag is
        // marked for removal, don't add it to the output.
        return;
    }
    this._last_node_was_text = false;

    attributes = this.validator.getValidTagAttributes(tag, attributes);
    attributes = this.removeUnwantedClasses(attributes);
    this.output += this.helper.tag(tag, attributes);
    this._lastTagRemoved = false;
};

WYMeditor.XhtmlSaxListener.prototype.openUnknownTag = function(tag, attributes) {
    //this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.XhtmlSaxListener.prototype.closeBlockTag = function(tag) {
    this._last_node_was_text = false;
    if (this._insideTagToRemove) {
        if (this._tag_stack.length === this._removedTagStackIndex) {
            // If we've reached the index in the tag stack were the tag to be
            // removed started, we're no longer inside that tag and can turn
            // the insideTagToRemove flag off.
            this._insideTagToRemove = false;
        }
        this._lastTagRemoved = true;
        return;
    }

    if (tag === 'li') {
        this._insideLI = false;
        this._addSpacerBeforeElementInLI = false;
    }
    if (jQuery.inArray(tag, WYMeditor.LIST_TYPE_ELEMENTS) > -1) {
        this._insideLI = false;
    }

    this.output = this.output +
        this._getClosingTagContent('before', tag) +
        "</"+tag+">" +
        this._getClosingTagContent('after', tag);
};

WYMeditor.XhtmlSaxListener.prototype.removedExtraBlockClosingTag = function () {
    this._extraBlockClosingTags--;
    this._addSpacerBeforeElementInLI = true;
    this._last_node_was_text = false;
};

WYMeditor.XhtmlSaxListener.prototype.closeUnknownTag = function(tag) {
    //this.output += "</"+tag+">";
};

WYMeditor.XhtmlSaxListener.prototype.closeUnopenedTag = function(tag) {
    this._last_node_was_text = false;
    if (this._insideTagToRemove) {
        return;
    }

    if (tag === 'li' && this._extraLIClosingTags) {
        this._extraLIClosingTags--;
    } else {
        this.output += "</" + tag + ">";
    }
};

WYMeditor.XhtmlSaxListener.prototype.avoidStylingTagsAndAttributes = function() {
    this.avoided_tags = ['div','span'];
    this.validator.skiped_attributes = ['style'];
    this.validator.skiped_attribute_values = ['MsoNormal','main1']; // MS Word attributes for class
    this._avoiding_tags_implicitly = true;
};

WYMeditor.XhtmlSaxListener.prototype.allowStylingTagsAndAttributes = function() {
    this.avoided_tags = [];
    this.validator.skiped_attributes = [];
    this.validator.skiped_attribute_values = [];
    this._avoiding_tags_implicitly = false;
};

WYMeditor.XhtmlSaxListener.prototype.isBlockTag = function(tag) {
    return !WYMeditor.Helper.arrayContains(this.avoided_tags, tag) &&
            WYMeditor.Helper.arrayContains(this.block_tags, tag);
};

WYMeditor.XhtmlSaxListener.prototype.isInlineTag = function(tag) {
    return !WYMeditor.Helper.arrayContains(this.avoided_tags, tag) &&
            WYMeditor.Helper.arrayContains(this.inline_tags, tag);
};

WYMeditor.XhtmlSaxListener.prototype.insertContentAfterClosingTag = function(tag, content) {
    this._insertContentWhenClosingTag('after', tag, content);
};

WYMeditor.XhtmlSaxListener.prototype.insertContentBeforeClosingTag = function(tag, content) {
    this._insertContentWhenClosingTag('before', tag, content);
};

/*
    removeUnwantedClasses
    =====================

    Removes the unwanted classes specified in the
    WYMeditor.CLASSES_REMOVED_BY_PARSER constant from the passed attributes
    object and returns the attributes object after the removals. The passed
    attributes object should be in a format with attribute names as properties
    and those attributes' values as those properties' values. The class
    matching for removal is case insensitive.
*/
WYMeditor.XhtmlSaxListener.prototype.removeUnwantedClasses = function(attributes) {
    var pattern,
        i;

    if (!attributes["class"]) {
        return attributes;
    }

    for (i = 0; i < WYMeditor.CLASSES_REMOVED_BY_PARSER.length; ++i) {
        pattern = new RegExp('(^|\\s)' + WYMeditor.CLASSES_REMOVED_BY_PARSER[i] +
                             '($|\\s)', 'gi');
        attributes["class"] = attributes["class"].replace(pattern, '$1');
    }

    // Remove possible trailing space that could have been left over if the
    // last class was removed
    attributes["class"] = attributes["class"].replace(/\s$/, '');
    return attributes;
};

WYMeditor.XhtmlSaxListener.prototype.fixNestingBeforeOpeningBlockTag = function(tag, attributes) {
    if (!this._last_node_was_text && (tag == 'ul' || tag == 'ol') && this.last_tag &&
            !this.last_tag_opened && this.last_tag == 'li') {
        // We have a <li></li><ol>... situation. The new list should be a
        // child of the li tag. Not a sibling.

        if (this._lastTagRemoved) {
            // If the previous li tag was removed, the new list should be
            // removed with it.
            this._insideTagToRemove = true;
            this._removedTagStackIndex = this._tag_stack.length - 1;
        } else if (!this._shouldRemoveTag(tag, attributes)){
            // If this tag is not going to be removed, remove the last closing
            // li tag
            this.output = this.output.replace(/<\/li>\s*$/, '');
            this.insertContentAfterClosingTag(tag, '</li>');
        }
    } else if ((tag == 'ul' || tag == 'ol') && this.last_tag &&
            this.last_tag_opened && (this.last_tag == 'ul' || this.last_tag == 'ol')) {
        // We have a <ol|ul><ol|ul>... situation. The new list should be have
        // a li tag parent and shouldn't be directly nested.

        // If this tag is not going to be removed, add an opening li tag before
        // and after this tag
        if (!this._shouldRemoveTag(tag, attributes)) {
            this.output += this.helper.tag('li', {}, true);
            this.insertContentAfterClosingTag(tag, '</li>');
        }
        this._last_node_was_text = false;
    } else if (tag == 'li') {
        // Closest open tag that's not this tag
        if (this._tag_stack.length >= 2) {
            var closestOpenTag = this._tag_stack[this._tag_stack.length - 2];
            if (closestOpenTag == 'li' && !this._shouldRemoveTag(tag, attributes)){
                // Pop the tag off of the stack to indicate we closed it
                this._open_tags.li -= 1;
                if (this._open_tags.li === 0) {
                    this._open_tags.li = undefined;
                }
                this._tag_stack.splice(this._tag_stack.length - 2, 1);
                this._last_node_was_text = false;

                if (!this._insideTagToRemove) {
                    // If not inside a tag to remove, close the outer LI now
                    // before adding the LI that was nested within it to the
                    // output.
                    this.output += '</li>';
                } else if (this._tag_stack.length - 1 ===
                           this._removedTagStackIndex) {
                    // If the outer LI was the start of a block to be removed,
                    // reset the flag for removing a tag.
                    this._insideTagToRemove = false;
                    this._lastTagRemoved = true;
                    this._extraLIClosingTags++;
                }
            }
        }
        // Opening a new li tag while another li tag is still open.
        // LI tags aren't allowed to be nested within eachother
        // It probably means we forgot to close the last LI tag
        //return true;
    }
};

WYMeditor.XhtmlSaxListener.prototype._insertContentWhenClosingTag = function(position, tag, content) {
    if (!this['_insert_'+position+'_closing']) {
        this['_insert_'+position+'_closing'] = [];
    }
    if (!this['_insert_'+position+'_closing'][tag]) {
        this['_insert_'+position+'_closing'][tag] = [];
    }
    this['_insert_'+position+'_closing'][tag].push(content);
};

WYMeditor.XhtmlSaxListener.prototype._getClosingTagContent = function(position, tag) {
    if (this['_insert_'+position+'_closing'] &&
            this['_insert_'+position+'_closing'][tag] &&
            this['_insert_'+position+'_closing'][tag].length > 0) {
        return this['_insert_'+position+'_closing'][tag].pop();
    }
    return '';
};

/*
    _shouldRemoveTag
    ================

    Specifies if the passed tag with the passed attributes should be removed
    from the output or not, based on the current state.
*/
WYMeditor.XhtmlSaxListener.prototype._shouldRemoveTag = function(tag, attributes) {
    if (this._isEditorOnlyTag(tag, attributes)) {
        return true;
    }
    if (this._isRootInlineTagToRemove(tag, attributes, this._tag_stack)) {
        return true;
    }
    if (this._isThirdConsecutiveBrWithNoAttributes(tag, attributes)) {
        return true;
    }

    return false;
};

/*
    _isEditorOnlyTag
    ================

    Is the passed-in tag, as evaluated in the current state, a tag that should
    only exist in the editor, but not in the final output. Editor-only tags
    exist to aid with manipulation and browser-bug workarounds, but aren't
    actual content that should be kept in the authoritative HTML.
*/
WYMeditor.XhtmlSaxListener.prototype._isEditorOnlyTag = function(tag, attributes) {
    var classes;

    if (!attributes["class"]) {
        return false;
    }

    classes = attributes["class"].split(" ");
    if (WYMeditor.Helper.arrayContains(classes, WYMeditor.EDITOR_ONLY_CLASS)) {
        return true;
    }
    return false;
};

/*
    Is this tag one of the tags that should be removed if found at the root.
*/
WYMeditor.XhtmlSaxListener.prototype._isRootInlineTagToRemove = function(
    tag, attributes, currentTagStack
) {
    if (!this.isInlineTag(tag)) {
        return false;
    }
    if (currentTagStack.length > 0) {
        // We're not at the root
        return false;
    }

    if (WYMeditor.Helper.arrayContains(this._rootInlineTagsToRemove, tag)) {
        return true;
    }
    return false;
};

/*
    Is this tag a third consecutive `br` element that has no attributes.
*/
WYMeditor.XhtmlSaxListener.prototype
    ._isThirdConsecutiveBrWithNoAttributes = function (tag, attributes) {
    var key;
    if (tag !== 'br') {
        this._consecutive_brs = 0;
        return false;
    }
    if (
        this._consecutive_brs !== 0 &&
        this._last_node_was_text
    ) {
        this._consecutive_brs = 0;
        return false;
    }
    for (key in attributes) {
        if (attributes.hasOwnProperty(key)) {
            this._consecutive_brs = 0;
            return false;
        }
    }
    this._consecutive_brs ++;
    if (this._consecutive_brs > 2) {
        return true;
    }
    return false;
};

/**
* XhtmlValidator for validating tag attributes
*
* @author Bermi Ferrer - http://bermi.org
*/
WYMeditor.XhtmlValidator = {
    "_attributes":
    {
        "core":
        {
            "except":[
            "base",
            "head",
            "html",
            "meta",
            "param",
            "script",
            "style",
            "title"
            ],
            "attributes":[
            "class",
            "id",
            "title",
            "accesskey",
            "tabindex",
            "/^data-.*/"
            ]
        },
        "styleAttr":
        {
            "except":[
            "img"
            ],
            "attributes":[
            "style"
            ]
        },
        "language":
        {
            "except":[
            "base",
            "br",
            "hr",
            "iframe",
            "param",
            "script"
            ],
            "attributes":
            {
                "dir":[
                "ltr",
                "rtl"
                ],
                "0":"lang",
                "1":"xml:lang"
            }
        },
        "keyboard":
        {
            "attributes":
            {
                "accesskey":/^(\w){1}$/,
                "tabindex":/^(\d)+$/
            }
        }
    },
    "_events":
    {
        "window":
        {
            "only":[
            "body"
            ],
            "attributes":[
            "onload",
            "onunload"
            ]
        },
        "form":
        {
            "only":[
            "form",
            "input",
            "textarea",
            "select",
            "a",
            "label",
            "button"
            ],
            "attributes":[
            "onchange",
            "onsubmit",
            "onreset",
            "onselect",
            "onblur",
            "onfocus"
            ]
        },
        "keyboard":
        {
            "except":[
            "base",
            "bdo",
            "br",
            "frame",
            "frameset",
            "head",
            "html",
            "iframe",
            "meta",
            "param",
            "script",
            "style",
            "title"
            ],
            "attributes":[
            "onkeydown",
            "onkeypress",
            "onkeyup"
            ]
        },
        "mouse":
        {
            "except":[
            "base",
            "bdo",
            "br",
            "head",
            "html",
            "meta",
            "param",
            "script",
            "style",
            "title"
            ],
            "attributes":[
            "onclick",
            "ondblclick",
            "onmousedown",
            "onmousemove",
            "onmouseover",
            "onmouseout",
            "onmouseup"
            ]
        }
    },
    "_tags":
    {
        "a":
        {
            "attributes":
            {
                "0":"charset",
                "1":"coords",
                "2":"href",
                "3":"hreflang",
                "4":"name",
                "5":"rel",
                "6":"rev",
                "shape":/^(rect|rectangle|circ|circle|poly|polygon)$/,
                "7":"type"
            }
        },
        "0":"abbr",
        "1":"acronym",
        "2":"address",
        "area":
        {
            "attributes":
            {
                "0":"alt",
                "1":"coords",
                "2":"href",
                "nohref":/^(true|false)$/,
                "shape":/^(rect|rectangle|circ|circle|poly|polygon)$/
            },
            "required":[
            "alt"
            ]
        },
        "3":"b",
        "base":
        {
            "attributes":[
            "href"
            ],
            "required":[
            "href"
            ]
        },
        "bdo":
        {
            "attributes":
            {
                "dir":/^(ltr|rtl)$/
            },
            "required":[
            "dir"
            ]
        },
        "4":"big",
        "blockquote":
        {
            "attributes":[
            "cite"
            ]
        },
        "5":"body",
        "6":"br",
        "button":
        {
            "attributes":
            {
                "disabled":/^(disabled)$/,
                "type":/^(button|reset|submit)$/,
                "0":"value"
            },
            "inside":"form"
        },
        "7":"caption",
        "8":"cite",
        "9":"code",
        "col":
        {
            "attributes":
            {
                "align":/^(right|left|center|justify)$/,
                "0":"char",
                "1":"charoff",
                "span":/^(\d)+$/,
                "valign":/^(top|middle|bottom|baseline)$/,
                "2":"width"
            },
            "inside":"colgroup"
        },
        "colgroup":
        {
            "attributes":
            {
                "align":/^(right|left|center|justify)$/,
                "0":"char",
                "1":"charoff",
                "span":/^(\d)+$/,
                "valign":/^(top|middle|bottom|baseline)$/,
                "2":"width"
            }
        },
        "10":"dd",
        "del":
        {
            "attributes":
            {
                "0":"cite",
                "datetime":/^([0-9]){8}/
            }
        },
        "11":"div",
        "12":"dfn",
        "13":"dl",
        "14":"dt",
        "15":"em",
        "fieldset":
        {
            "inside":"form"
        },
        "form":
        {
            "attributes":
            {
                "0":"action",
                "1":"accept",
                "2":"accept-charset",
                "3":"enctype",
                "method":/^(get|post)$/
            },
            "required":[
            "action"
            ]
        },
        "head":
        {
            "attributes":[
            "profile"
            ]
        },
        "16":"h1",
        "17":"h2",
        "18":"h3",
        "19":"h4",
        "20":"h5",
        "21":"h6",
        "22":"hr",
        "html":
        {
            "attributes":[
            "xmlns"
            ]
        },
        "23":"i",
        "img":
        {
            "attributes":[
            "alt",
            "src",
            "height",
            "ismap",
            "longdesc",
            "usemap",
            "width"
            ],
            "required":[
            "alt",
            "src"
            ]
        },
        "input":
        {
            "attributes":
            {
                "0":"accept",
                "1":"alt",
                "checked":/^(checked)$/,
                "disabled":/^(disabled)$/,
                "maxlength":/^(\d)+$/,
                "2":"name",
                "readonly":/^(readonly)$/,
                "size":/^(\d)+$/,
                "3":"src",
                "type":/^(button|checkbox|file|hidden|image|password|radio|reset|submit|text)$/,
                "4":"value"
            },
            "inside":"form"
        },
        "ins":
        {
            "attributes":
            {
                "0":"cite",
                "datetime":/^([0-9]){8}/
            }
        },
        "24":"kbd",
        "label":
        {
            "attributes":[
            "for"
            ],
            "inside":"form"
        },
        "25":"legend",
        "26":"li",
        "link":
        {
            "attributes":
            {
                "0":"charset",
                "1":"href",
                "2":"hreflang",
                "media":/^(all|braille|print|projection|screen|speech|,|;| )+$/i,
                //next comment line required by Opera!
                /*"rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,*/
                "rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
                "rev":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
                "3":"type"
            },
            "inside":"head"
        },
        "map":
        {
            "attributes":[
            "id",
            "name"
            ],
            "required":[
            "id"
            ]
        },
        "meta":
        {
            "attributes":
            {
                "0":"content",
                "http-equiv":/^(content\-type|expires|refresh|set\-cookie)$/i,
                "1":"name",
                "2":"scheme"
            },
            "required":[
            "content"
            ]
        },
        "27":"noscript",
        "object":
        {
            "attributes":[
            "archive",
            "classid",
            "codebase",
            "codetype",
            "data",
            "declare",
            "height",
            "name",
            "standby",
            "type",
            "usemap",
            "width"
            ]
        },
        "28":"ol",
        "optgroup":
        {
            "attributes":
            {
                "0":"label",
                "disabled": /^(disabled)$/
            },
            "required":[
            "label"
            ]
        },
        "option":
        {
            "attributes":
            {
                "0":"label",
                "disabled":/^(disabled)$/,
                "selected":/^(selected)$/,
                "1":"value"
            },
            "inside":"select"
        },
        "29":"p",
        "param":
        {
            "attributes":
            {
                "0":"type",
                "valuetype":/^(data|ref|object)$/,
                "1":"valuetype",
                "2":"value"
            },
            "required":[
            "name"
            ]
        },
        "30":"pre",
        "q":
        {
            "attributes":[
            "cite"
            ]
        },
        "31":"samp",
        "script":
        {
            "attributes":
            {
                "type":/^(text\/ecmascript|text\/javascript|text\/jscript|text\/vbscript|text\/vbs|text\/xml)$/,
                "0":"charset",
                "defer":/^(defer)$/,
                "1":"src"
            },
            "required":[
            "type"
            ]
        },
        "select":
        {
            "attributes":
            {
                "disabled":/^(disabled)$/,
                "multiple":/^(multiple)$/,
                "0":"name",
                "1":"size"
            },
            "inside":"form"
        },
        "32":"small",
        "33":"span",
        "34":"strong",
        "style":
        {
            "attributes":
            {
                "0":"type",
                "media":/^(screen|tty|tv|projection|handheld|print|braille|aural|all)$/
            },
            "required":[
            "type"
            ]
        },
        "35":"sub",
        "36":"sup",
        "table":
        {
            "attributes":
            {
                "0":"border",
                "1":"cellpadding",
                "2":"cellspacing",
                "frame":/^(void|above|below|hsides|lhs|rhs|vsides|box|border)$/,
                "rules":/^(none|groups|rows|cols|all)$/,
                "3":"summary",
                "4":"width"
            }
        },
        "tbody":
        {
            "attributes":
            {
                "align":/^(right|left|center|justify)$/,
                "0":"char",
                "1":"charoff",
                "valign":/^(top|middle|bottom|baseline)$/
            }
        },
        "td":
        {
            "attributes":
            {
                "0":"abbr",
                "align":/^(left|right|center|justify|char)$/,
                "1":"axis",
                "2":"char",
                "3":"charoff",
                "colspan":/^(\d)+$/,
                "4":"headers",
                "rowspan":/^(\d)+$/,
                "scope":/^(col|colgroup|row|rowgroup)$/,
                "valign":/^(top|middle|bottom|baseline)$/
            }
        },
        "textarea":
        {
            "attributes":[
            "cols",
            "rows",
            "disabled",
            "name",
            "readonly"
            ],
            "required":[
            "cols",
            "rows"
            ],
            "inside":"form"
        },
        "tfoot":
        {
            "attributes":
            {
                "align":/^(right|left|center|justify)$/,
                "0":"char",
                "1":"charoff",
                "valign":/^(top|middle|bottom)$/,
                "2":"baseline"
            }
        },
        "th":
        {
            "attributes":
            {
                "0":"abbr",
                "align":/^(left|right|center|justify|char)$/,
                "1":"axis",
                "2":"char",
                "3":"charoff",
                "colspan":/^(\d)+$/,
                "4":"headers",
                "rowspan":/^(\d)+$/,
                "scope":/^(col|colgroup|row|rowgroup)$/,
                "valign":/^(top|middle|bottom|baseline)$/
            }
        },
        "thead":
        {
            "attributes":
            {
                "align":/^(right|left|center|justify)$/,
                "0":"char",
                "1":"charoff",
                "valign":/^(top|middle|bottom|baseline)$/
            }
        },
        "37":"title",
        "tr":
        {
            "attributes":
            {
                "align":/^(right|left|center|justify|char)$/,
                "0":"char",
                "1":"charoff",
                "valign":/^(top|middle|bottom|baseline)$/
            }
        },
        "38":"tt",
        "39":"ul",
        "40":"var"
    },

    // Temporary skiped attributes
    skiped_attributes : [],
    skiped_attribute_values : [],

    getValidTagAttributes: function(tag, attributes)
    {
        var valid_attributes = {};
        var possible_attributes = this.getPossibleTagAttributes(tag);
        for(var attribute in attributes) {
            var value = attributes[attribute];
            attribute = attribute.toLowerCase(); // ie8 uses colSpan
            var h = WYMeditor.Helper;
            if(!h.arrayContains(this.skiped_attributes, attribute) && !h.arrayContains(this.skiped_attribute_values, value)){
                if (typeof value != 'function' && h.arrayContains(possible_attributes, attribute)) {
                    if (this.doesAttributeNeedsValidation(tag, attribute)) {
                        if(this.validateAttribute(tag, attribute, value)){
                            valid_attributes[attribute] = value;
                        }
                    }else{
                        valid_attributes[attribute] = value;
                    }
                } else {
                    jQuery.each(possible_attributes, function() {
                        if(this.match(/\/(.*)\//)) {
                            regex = new RegExp(this.match(/\/(.*)\//)[1]);
                            if(regex.test(attribute)) {
                                valid_attributes[attribute] = value;
                            }
                        }
                    });
                }
            }
        }
        return valid_attributes;
    },
    getUniqueAttributesAndEventsForTag : function(tag)
    {
        var result = [];

        if (this._tags[tag] && this._tags[tag].attributes) {
            for (var k in this._tags[tag].attributes) {
                result.push(parseInt(k, 10) == k ? this._tags[tag].attributes[k] : k);
            }
        }
        return result;
    },
getDefaultAttributesAndEventsForTags : function()
{
    var result = [];
    for (var key in this._events){
        result.push(this._events[key]);
    }
    for (key in this._attributes){
        result.push(this._attributes[key]);
    }
    return result;
},
isValidTag : function(tag)
{
    if(this._tags[tag]){
        return true;
    }
    for(var key in this._tags){
        if(this._tags[key] == tag){
            return true;
        }
    }
    return false;
},
getDefaultAttributesAndEventsForTag : function(tag)
{
    var default_attributes = [];
    if (this.isValidTag(tag)) {
        var default_attributes_and_events = this.getDefaultAttributesAndEventsForTags();

    for(var key in default_attributes_and_events) {
        var defaults = default_attributes_and_events[key];
        if(typeof defaults == 'object'){
            var h = WYMeditor.Helper;
            if ((defaults['except'] && h.arrayContains(defaults['except'], tag)) || (defaults['only'] && !h.arrayContains(defaults['only'], tag))) {
                continue;
            }

    var tag_defaults = defaults['attributes'] ? defaults['attributes'] : defaults['events'];
    for(var k in tag_defaults) {
        default_attributes.push(typeof tag_defaults[k] != 'string' ? k : tag_defaults[k]);
    }
}
}
}
return default_attributes;
},
doesAttributeNeedsValidation: function(tag, attribute)
{
    return this._tags[tag] && ((this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute]) || (this._tags[tag]['required'] &&
        WYMeditor.Helper.arrayContains(this._tags[tag]['required'], attribute)));
},
validateAttribute : function(tag, attribute, value)
{
    if ( this._tags[tag] &&
        (this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute] && value.length > 0 && !value.match(this._tags[tag]['attributes'][attribute])) || // invalid format
        (this._tags[tag] && this._tags[tag]['required'] && WYMeditor.Helper.arrayContains(this._tags[tag]['required'], attribute) && value.length === 0)) // required attribute
    {
        return false;
    }
    return typeof this._tags[tag] != 'undefined';
},
getPossibleTagAttributes : function(tag)
{
    if (!this._possible_tag_attributes) {
        this._possible_tag_attributes = {};
    }
    if (!this._possible_tag_attributes[tag]) {
        this._possible_tag_attributes[tag] = this.getUniqueAttributesAndEventsForTag(tag).concat(this.getDefaultAttributesAndEventsForTag(tag));
    }
    return this._possible_tag_attributes[tag];
}
};


/********** XHTML LEXER/PARSER **********/

/*
* @name xml
* @description Use these methods to generate XML and XHTML compliant tags and
* escape tag attributes correctly
* @author Bermi Ferrer - http://bermi.org
* @author David Heinemeier Hansson http://loudthinking.com
*/
WYMeditor.XmlHelper = function()
{
    this._entitiesDiv = document.createElement('div');
    return this;
};


/*
* @name tag
* @description
* Returns an empty HTML tag of type *name* which by default is XHTML
* compliant. Setting *open* to true will create an open tag compatible
* with HTML 4.0 and below. Add HTML attributes by passing an attributes
* array to *options*. For attributes with no value like (disabled and
* readonly), give it a value of true in the *options* array.
*
* Examples:
*
*   this.tag('br')
*    # => <br />
*   this.tag ('br', false, true)
*    # => <br>
*   this.tag ('input', jQuery({type:'text',disabled:true }) )
*    # => <input type="text" disabled="disabled" />
*/
WYMeditor.XmlHelper.prototype.tag = function(name, options, open)
{
    options = options || false;
    open = open || false;
    return '<'+name+(options ? this.tagOptions(options) : '')+(open ? '>' : ' />');
};

/*
* @name contentTag
* @description
* Returns a XML block tag of type *name* surrounding the *content*. Add
* XML attributes by passing an attributes array to *options*. For attributes
* with no value like (disabled and readonly), give it a value of true in
* the *options* array. You can use symbols or strings for the attribute names.
*
*   this.contentTag ('p', 'Hello world!' )
*    # => <p>Hello world!</p>
*   this.contentTag('div', this.contentTag('p', "Hello world!"), jQuery({class : "strong"}))
*    # => <div class="strong"><p>Hello world!</p></div>
*   this.contentTag("select", options, jQuery({multiple : true}))
*    # => <select multiple="multiple">...options...</select>
*/
WYMeditor.XmlHelper.prototype.contentTag = function(name, content, options)
{
    options = options || false;
    return '<'+name+(options ? this.tagOptions(options) : '')+'>'+content+'</'+name+'>';
};

/*
* @name cdataSection
* @description
* Returns a CDATA section for the given +content+.  CDATA sections
* are used to escape blocks of text containing characters which would
* otherwise be recognized as markup. CDATA sections begin with the string
* <tt>&lt;![CDATA[</tt> and } with (and may not contain) the string
* <tt>]]></tt>.
*/
WYMeditor.XmlHelper.prototype.cdataSection = function(content)
{
    return '<![CDATA['+content+']]>';
};


/*
* @name escapeOnce
* @description
* Returns the escaped +xml+ without affecting existing escaped entities.
*
*  this.escapeOnce( "1 > 2 &amp; 3")
*    # => "1 &gt; 2 &amp; 3"
*/
WYMeditor.XmlHelper.prototype.escapeOnce = function(xml)
{
    return this._fixDoubleEscape(this.escapeEntities(xml));
};

/*
* @name _fixDoubleEscape
* @description
* Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc.
*/
WYMeditor.XmlHelper.prototype._fixDoubleEscape = function(escaped)
{
    return escaped.replace(/&amp;([a-z]+|(#\d+));/ig, "&$1;");
};

/*
* @name tagOptions
* @description
* Takes an array like the one generated by Tag.parseAttributes
*  [["src", "http://www.editam.com/?a=b&c=d&amp;f=g"], ["title", "Editam, <Simplified> CMS"]]
* or an object like {src:"http://www.editam.com/?a=b&c=d&amp;f=g", title:"Editam, <Simplified> CMS"}
* and returns a string properly escaped like
* ' src = "http://www.editam.com/?a=b&amp;c=d&amp;f=g" title = "Editam, &lt;Simplified&gt; CMS"'
* which is valid for strict XHTML
*/
WYMeditor.XmlHelper.prototype.tagOptions = function(options)
{
    var xml = this;
    xml._formated_options = '';

    for (var key in options) {
        var formated_options = '';
        var value = options[key];
        if(typeof value != 'function' && value.length > 0) {

    if(parseInt(key, 10) == key && typeof value == 'object'){
        key = value.shift();
        value = value.pop();
    }
    if(key !== '' && value !== ''){
        xml._formated_options += ' '+key+'="'+xml.escapeOnce(value)+'"';
    }
}
}
return xml._formated_options;
};

/*
* @name escapeEntities
* @description
* Escapes XML/HTML entities <, >, & and ". If seccond parameter is set to false it
* will not escape ". If set to true it will also escape '
*/
WYMeditor.XmlHelper.prototype.escapeEntities = function(string, escape_quotes)
{
    this._entitiesDiv.innerHTML = string;
    this._entitiesDiv.textContent = string;
    var result = this._entitiesDiv.innerHTML;
    if(typeof escape_quotes == 'undefined'){
        if(escape_quotes !== false) result = result.replace('"', '&quot;');
        if(escape_quotes === true)  result = result.replace('"', '&#039;');
    }
    return result;
};

/*
* Parses a string conatining tag attributes and values an returns an array formated like
*  [["src", "http://www.editam.com"], ["title", "Editam, Simplified CMS"]]
*/
WYMeditor.XmlHelper.prototype.parseAttributes = function(tag_attributes)
{
    // Use a compounded regex to match single quoted, double quoted and unquoted attribute pairs
    var result = [];
    var matches = tag_attributes.split(/((=\s*")(")("))|((=\s*\')(\')(\'))|((=\s*[^>\s]*))/g);
    if(matches.toString() != tag_attributes){
        for (var k in matches) {
            var v = matches[k];
            if(typeof v != 'function' && v.length !== 0){
                var re = new RegExp('(\\w+)\\s*'+v);
                var match = tag_attributes.match(re);
                if(match) {
                    var value = v.replace(/^[\s=]+/, "");
                    var delimiter = value.charAt(0);
                    delimiter = delimiter == '"' ? '"' : (delimiter=="'"?"'":'');
                    if(delimiter !== ''){
                        value = delimiter == '"' ? value.replace(/^"|"+$/g, '') :  value.replace(/^'|'+$/g, '');
                    }
                    tag_attributes = tag_attributes.replace(match[0],'');
                    result.push([match[1] , value]);
                }
            }
        }
    }
    return result;
};

WYMeditor.STRINGS.bg = {
    Strong:           'Получер',
    Emphasis:         'Курсив',
    Superscript:      'Горен индекс',
    Subscript:        'Долен индекс',
    Ordered_List:     'Подреден списък',
    Unordered_List:   'Неподреден списък',
    Indent:           'Блок навътре',
    Outdent:          'Блок навън',
    Undo:             'Стъпка назад',
    Redo:             'Стъпка напред',
    Link:             'Създай хипервръзка',
    Unlink:           'Премахни хипервръзката',
    Image:            'Изображение',
    Table:            'Таблица',
    HTML:             'HTML',
    Paragraph:        'Абзац',
    Heading_1:        'Заглавие 1',
    Heading_2:        'Заглавие 2',
    Heading_3:        'Заглавие 3',
    Heading_4:        'Заглавие 4',
    Heading_5:        'Заглавие 5',
    Heading_6:        'Заглавие 6',
    Preformatted:     'Преформатиран',
    Blockquote:       'Цитат',
    Table_Header:     'Заглавие на таблицата',
    URL:              'URL',
    Title:            'Заглавие',
    Alternative_Text: 'Алтернативен текст',
    Caption:          'Етикет',
    Summary:          'Общо',
    Number_Of_Rows:   'Брой редове',
    Number_Of_Cols:   'Брой колони',
    Submit:           'Изпрати',
    Cancel:           'Отмени',
    Choose:           'Затвори',
    Preview:          'Предварителен преглед',
    Paste_From_Word:  'Вмъкни от MS WORD',
    Tools:            'Инструменти',
    Containers:       'Контейнери',
    Classes:          'Класове',
    Status:           'Статус',
    Source_Code:      'Източник, код'
};


WYMeditor.STRINGS.ca = {
    Strong:           'Ressaltar',
    Emphasis:         'Emfatitzar',
    Superscript:      'Superindex',
    Subscript:        'Subindex',
    Ordered_List:     'Llistat ordenat',
    Unordered_List:   'Llistat sense ordenar',
    Indent:           'Indentat',
    Outdent:          'Sense indentar',
    Undo:             'Desfer',
    Redo:             'Refer',
    Link:             'Enllaçar',
    Unlink:           'Eliminar enllaç',
    Image:            'Imatge',
    Table:            'Taula',
    HTML:             'HTML',
    Paragraph:        'Paràgraf',
    Heading_1:        'Capçalera 1',
    Heading_2:        'Capçalera 2',
    Heading_3:        'Capçalera 3',
    Heading_4:        'Capçalera 4',
    Heading_5:        'Capçalera 5',
    Heading_6:        'Capçalera 6',
    Preformatted:     'Pre-formatejat',
    Blockquote:       'Cita',
    Table_Header:     'Capçalera de la taula',
    URL:              'URL',
    Title:            'Títol',
    Alternative_Text: 'Text alternatiu',
    Caption:          'Llegenda',
    Summary:          'Summary',
    Number_Of_Rows:   'Nombre de files',
    Number_Of_Cols:   'Nombre de columnes',
    Submit:           'Enviar',
    Cancel:           'Cancel·lar',
    Choose:           'Triar',
    Preview:          'Vista prèvia',
    Paste_From_Word:  'Pegar des de Word',
    Tools:            'Eines',
    Containers:       'Contenidors',
    Classes:          'Classes',
    Status:           'Estat',
    Source_Code:      'Codi font'
};


WYMeditor.STRINGS.cs = {
    Strong:           'Tučné',
    Emphasis:         'Kurzíva',
    Superscript:      'Horní index',
    Subscript:        'Dolní index',
    Ordered_List:     'Číslovaný seznam',
    Unordered_List:   'Nečíslovaný seznam',
    Indent:           'Zvětšit odsazení',
    Outdent:          'Zmenšit odsazení',
    Undo:             'Zpět',
    Redo:             'Znovu',
    Link:             'Vytvořit odkaz',
    Unlink:           'Zrušit odkaz',
    Image:            'Obrázek',
    Table:            'Tabulka',
    HTML:             'HTML',
    Paragraph:        'Odstavec',
    Heading_1:        'Nadpis 1. úrovně',
    Heading_2:        'Nadpis 2. úrovně',
    Heading_3:        'Nadpis 3. úrovně',
    Heading_4:        'Nadpis 4. úrovně',
    Heading_5:        'Nadpis 5. úrovně',
    Heading_6:        'Nadpis 6. úrovně',
    Preformatted:     'Předformátovaný text',
    Blockquote:       'Citace',
    Table_Header:     'Hlavičková buňka tabulky',
    URL:              'Adresa',
    Title:            'Text po najetí myší',
    Alternative_Text: 'Text pro případ nezobrazení obrázku',
    Caption:          'Titulek tabulky',
    Summary:          'Shrnutí obsahu',
    Number_Of_Rows:   'Počet řádek',
    Number_Of_Cols:   'Počet sloupců',
    Submit:           'Vytvořit',
    Cancel:           'Zrušit',
    Choose:           'Vybrat',
    Preview:          'Náhled',
    Paste_From_Word:  'Vložit z Wordu',
    Tools:            'Nástroje',
    Containers:       'Typy obsahu',
    Classes:          'Třídy',
    Status:           'Stav',
    Source_Code:      'Zdrojový kód'
};


WYMeditor.STRINGS.cy = {
    Strong:           'Bras',
    Emphasis:         'Italig',
    Superscript:      'Uwchsgript',
    Subscript:        'Is-sgript',
    Ordered_List:     'Rhestr mewn Trefn',
    Unordered_List:   'Pwyntiau Bwled',
    Indent:           'Mewnoli',
    Outdent:          'Alloli',
    Undo:             'Dadwneud',
    Redo:             'Ailwneud',
    Link:             'Cysylltu',
    Unlink:           'Datgysylltu',
    Image:            'Delwedd',
    Table:            'Tabl',
    HTML:             'HTML',
    Paragraph:        'Paragraff',
    Heading_1:        'Pennawd 1',
    Heading_2:        'Pennawd 2',
    Heading_3:        'Pennawd 3',
    Heading_4:        'Pennawd 4',
    Heading_5:        'Pennawd 5',
    Heading_6:        'Pennawd 6',
    Preformatted:     'Rhagfformat',
    Blockquote:       'Bloc Dyfyniad',
    Table_Header:     'Pennyn Tabl',
    URL:              'URL',
    Title:            'Teitl',
    Alternative_Text: 'Testun Amgen',
    Caption:          'Pennawd',
    Summary:          'Crynodeb',
    Number_Of_Rows:   'Nifer y rhesi',
    Number_Of_Cols:   'Nifer y colofnau',
    Submit:           'Anfon',
    Cancel:           'Diddymu',
    Choose:           'Dewis',
    Preview:          'Rhagolwg',
    Paste_From_Word:  'Gludo o Word',
    Tools:            'Offer',
    Containers:       'Cynhwysyddion',
    Classes:          'Dosbarthiadau',
    Status:           'Statws',
    Source_Code:      'Cod ffynhonnell'
};


WYMeditor.STRINGS['da'] = {
    Strong:           'Fed',
    Emphasis:         'Skrå',
    Superscript:      'Superscript',
    Subscript:        'Subscript',
    Ordered_List:     'Ordnet liste',
    Unordered_List:   'Uordnet liste',
    Indent:           'Indrykke',
    Outdent:          'Udrykke',
    Undo:             'Fortryd',
    Redo:             'Fortryd',
    Link:             'Link',
    Unlink:           'Fjern link',
    Image:            'Billede',
    Table:            'Tabel',
    HTML:             'HTML',
    Paragraph:        'Paragraf',
    Heading_1:        'Overskrift 1',
    Heading_2:        'Overskrift 2',
    Heading_3:        'Overskrift 3',
    Heading_4:        'Overskrift 4',
    Heading_5:        'Overskrift 5',
    Heading_6:        'Overskrift 6',
    Preformatted:     'Forudformateret',
    Blockquote:       'Citat',
    Table_Header:     'Tabel Overskrift',
    URL:              'URL',
    Title:            'Titel',
    Alternative_Text: 'Alternativ tekst',
    Caption:          'Billedtekst',
    Summary:          'Resumé',
    Number_Of_Rows:   'Antal rækker',
    Number_Of_Cols:   'Antal kolonner',
    Submit:           'Indsend',
    Cancel:           'Afbryd',
    Choose:           'Vælg',
    Preview:          'Forhåndsvisning',
    Paste_From_Word:  'Indsæt fra Word',
    Tools:            'Værktøjer',
    Containers:       'Containere',
    Classes:          'Klasser',
    Status:           'Status',
    Source_Code:      'Kildekode'
};


WYMeditor.STRINGS.de = {
    Strong:           'Fett',
    Emphasis:         'Kursiv',
    Superscript:      'Text hochstellen',
    Subscript:        'Text tiefstellen',
    Ordered_List:     'Geordnete Liste einfügen',
    Unordered_List:   'Ungeordnete Liste einfügen',
    Indent:           'Einzug erhöhen',
    Outdent:          'Einzug vermindern',
    Undo:             'Befehle rückgängig machen',
    Redo:             'Befehle wiederherstellen',
    Link:             'Hyperlink einfügen',
    Unlink:           'Hyperlink entfernen',
    Image:            'Bild einfügen',
    Table:            'Tabelle einfügen',
    HTML:             'HTML anzeigen/verstecken',
    Paragraph:        'Absatz',
    Heading_1:        'Überschrift 1',
    Heading_2:        'Überschrift 2',
    Heading_3:        'Überschrift 3',
    Heading_4:        'Überschrift 4',
    Heading_5:        'Überschrift 5',
    Heading_6:        'Überschrift 6',
    Preformatted:     'Vorformatiert',
    Blockquote:       'Zitat',
    Table_Header:     'Tabellenüberschrift',
    URL:              'URL',
    Title:            'Titel',
    Alternative_Text: 'Alternativer Text',
    Caption:          'Tabellenüberschrift',
    Summary:          'Summary',
    Number_Of_Rows:   'Anzahl Zeilen',
    Number_Of_Cols:   'Anzahl Spalten',
    Submit:           'Absenden',
    Cancel:           'Abbrechen',
    Choose:           'Auswählen',
    Preview:          'Vorschau',
    Paste_From_Word:  'Aus Word einfügen',
    Tools:            'Werkzeuge',
    Containers:       'Inhaltstyp',
    Classes:          'Klassen',
    Status:           'Status',
    Source_Code:      'Quellcode'
};


WYMeditor.STRINGS.en = {
    Strong:           'Strong',
    Emphasis:         'Emphasis',
    Superscript:      'Superscript',
    Subscript:        'Subscript',
    Ordered_List:     'Ordered List',
    Unordered_List:   'Unordered List',
    Indent:           'Indent',
    Outdent:          'Outdent',
    Undo:             'Undo',
    Redo:             'Redo',
    Link:             'Link',
    Unlink:           'Unlink',
    Image:            'Image',
    Table:            'Table',
    HTML:             'HTML',
    Paragraph:        'Paragraph',
    Heading_1:        'Heading 1',
    Heading_2:        'Heading 2',
    Heading_3:        'Heading 3',
    Heading_4:        'Heading 4',
    Heading_5:        'Heading 5',
    Heading_6:        'Heading 6',
    Preformatted:     'Preformatted',
    Blockquote:       'Blockquote',
    Table_Header:     'Table Header',
    URL:              'URL',
    Title:            'Title',
    Relationship:     'Relationship',
    Alternative_Text: 'Alternative text',
    Caption:          'Caption',
    Summary:          'Summary',
    Number_Of_Rows:   'Number of rows',
    Number_Of_Cols:   'Number of cols',
    Submit:           'Submit',
    Cancel:           'Cancel',
    Choose:           'Choose',
    Preview:          'Preview',
    Paste_From_Word:  'Paste from Word',
    Tools:            'Tools',
    Containers:       'Formatting',
    Classes:          'Style',
    Status:           'Status',
    Source_Code:      'Source code'
};

WYMeditor.STRINGS.es = {
    Strong:           'Resaltar',
    Emphasis:         'Enfatizar',
    Superscript:      'Superindice',
    Subscript:        'Subindice',
    Ordered_List:     'Lista ordenada',
    Unordered_List:   'Lista sin ordenar',
    Indent:           'Indentado',
    Outdent:          'Sin indentar',
    Undo:             'Deshacer',
    Redo:             'Rehacer',
    Link:             'Enlazar',
    Unlink:           'Eliminar enlace',
    Image:            'Imagen',
    Table:            'Tabla',
    HTML:             'HTML',
    Paragraph:        'Párrafo',
    Heading_1:        'Cabecera 1',
    Heading_2:        'Cabecera 2',
    Heading_3:        'Cabecera 3',
    Heading_4:        'Cabecera 4',
    Heading_5:        'Cabecera 5',
    Heading_6:        'Cabecera 6',
    Preformatted:     'Preformateado',
    Blockquote:       'Cita',
    Table_Header:     'Cabecera de la tabla',
    URL:              'URL',
    Title:            'Título',
    Alternative_Text: 'Texto alternativo',
    Caption:          'Leyenda',
    Summary:          'Summary',
    Number_Of_Rows:   'Número de filas',
    Number_Of_Cols:   'Número de columnas',
    Submit:           'Enviar',
    Cancel:           'Cancelar',
    Choose:           'Seleccionar',
    Preview:          'Vista previa',
    Paste_From_Word:  'Pegar desde Word',
    Tools:            'Herramientas',
    Containers:       'Contenedores',
    Classes:          'Clases',
    Status:           'Estado',
    Source_Code:      'Código fuente'
};


//Translation To Persian: Ghassem Tofighi (http://ght.ir)
WYMeditor.STRINGS.fa = {
    Strong:           'پررنگ',//Strong
    Emphasis:         'ایتالیک',//Emphasis
    Superscript:      'بالانويس‌ ',//Superscript
    Subscript:        'زيرنويس‌',//Subscript
    Ordered_List:     'لیست مرتب',//Ordered List
    Unordered_List:   'لیست نامرتب',//Unordered List
    Indent:           'افزودن دندانه',//Indent
    Outdent:          'کاهش دندانه',//Outdent
    Undo:             'واگردانی',//Undo
    Redo:             'تکرار',//Redo
    Link:             'ساختن پیوند',//Link
    Unlink:           'برداشتن پیوند',//Unlink
    Image:            'تصویر',//Image
    Table:            'جدول',//Table
    HTML:             'HTML',//HTML
    Paragraph:        'پاراگراف',//Paragraph
    Heading_1:        'سرتیتر ۱',//Heading 1
    Heading_2:        'سرتیتر ۲',//Heading 2
    Heading_3:        'سرتیتر ۳',//Heading 3
    Heading_4:        'سرتیتر ۴',//Heading 4
    Heading_5:        'سرتیتر ۵',//Heading 5
    Heading_6:        'سرتیتر ۶',//Heading 6
    Preformatted:     'قالب آماده',//Preformatted
    Blockquote:       'نقل قول',//Blockquote
    Table_Header:     'سرجدول',//Table Header
    URL:              'آدرس اینترنتی',//URL
    Title:            'عنوان',//Title
    Alternative_Text: 'متن جایگزین',//Alternative text
    Caption:          'عنوان',//Caption
    Summary:          'Summary',
    Number_Of_Rows:   'تعداد سطرها',//Number of rows
    Number_Of_Cols:   'تعداد ستون‌ها',//Number of cols
    Submit:           'فرستادن',//Submit
    Cancel:           'لغو',//Cancel
    Choose:           'انتخاب',//Choose
    Preview:          'پیش‌نمایش',//Preview
    Paste_From_Word:  'انتقال از ورد',//Paste from Word
    Tools:            'ابزار',//Tools
    Containers:       '‌قالب‌ها',//Containers
    Classes:          'کلاس‌ها',//Classes
    Status:           'وضعیت',//Status
    Source_Code:      'کد مبدأ'//Source code
};


WYMeditor.STRINGS.fi = {
    Strong:           'Lihavoitu',
    Emphasis:         'Korostus',
    Superscript:      'Yläindeksi',
    Subscript:        'Alaindeksi',
    Ordered_List:     'Numeroitu lista',
    Unordered_List:   'Luettelomerkit',
    Indent:           'Suurenna sisennystä',
    Outdent:          'Pienennä sisennystä',
    Undo:             'Kumoa',
    Redo:             'Toista',
    Link:             'Linkitä',
    Unlink:           'Poista linkitys',
    Image:            'Kuva',
    Table:            'Taulukko',
    HTML:             'HTML',
    Paragraph:        'Kappale',
    Heading_1:        'Otsikko 1',
    Heading_2:        'Otsikko 2',
    Heading_3:        'Otsikko 3',
    Heading_4:        'Otsikko 4',
    Heading_5:        'Otsikko 5',
    Heading_6:        'Otsikko 6',
    Preformatted:     'Esimuotoilu',
    Blockquote:       'Sitaatti',
    Table_Header:     'Taulukon otsikko',
    URL:              'URL',
    Title:            'Otsikko',
    Alternative_Text: 'Vaihtoehtoinen teksti',
    Caption:          'Kuvateksti',
    Summary:          'Yhteenveto',
    Number_Of_Rows:   'Rivien määrä',
    Number_Of_Cols:   'Palstojen määrä',
    Submit:           'Lähetä',
    Cancel:           'Peruuta',
    Choose:           'Valitse',
    Preview:          'Esikatsele',
    Paste_From_Word:  'Tuo Wordista',
    Tools:            'Työkalut',
    Containers:       'Muotoilut',
    Classes:          'Luokat',
    Status:           'Tila',
    Source_Code:      'Lähdekoodi'
};

WYMeditor.STRINGS.fr = {
    Strong:           'Mise en évidence',
    Emphasis:         'Emphase',
    Superscript:      'Exposant',
    Subscript:        'Indice',
    Ordered_List:     'Liste Ordonnée',
    Unordered_List:   'Liste Non-Ordonnée',
    Indent:           'Imbriqué',
    Outdent:          'Non-imbriqué',
    Undo:             'Annuler',
    Redo:             'Rétablir',
    Link:             'Lien',
    Unlink:           'Supprimer le Lien',
    Image:            'Image',
    Table:            'Tableau',
    HTML:             'HTML',
    Paragraph:        'Paragraphe',
    Heading_1:        'Titre 1',
    Heading_2:        'Titre 2',
    Heading_3:        'Titre 3',
    Heading_4:        'Titre 4',
    Heading_5:        'Titre 5',
    Heading_6:        'Titre 6',
    Preformatted:     'Pré-formatté',
    Blockquote:       'Citation',
    Table_Header:     'Cellule de titre',
    URL:              'URL',
    Title:            'Titre',
    Alternative_Text: 'Texte alternatif',
    Caption:          'Légende',
    Summary:          'Résumé',
    Number_Of_Rows:   'Nombre de lignes',
    Number_Of_Cols:   'Nombre de colonnes',
    Submit:           'Envoyer',
    Cancel:           'Annuler',
    Choose:           'Choisir',
    Preview:          'Prévisualisation',
    Paste_From_Word:  'Copier depuis Word',
    Tools:            'Outils',
    Containers:       'Type de texte',
    Classes:          'Type de contenu',
    Status:           'Infos',
    Source_Code:      'Code source'
};


WYMeditor.STRINGS.gl = {
    Strong:           'Moita énfase',
    Emphasis:         'Énfase',
    Superscript:      'Superíndice',
    Subscript:        'Subíndice',
    Ordered_List:     'Lista ordenada',
    Unordered_List:   'Lista sen ordenar',
    Indent:           'Aniñar',
    Outdent:          'Desaniñar',
    Undo:             'Desfacer',
    Redo:             'Refacer',
    Link:             'Ligazón',
    Unlink:           'Desligar',
    Image:            'Imaxe',
    Table:            'Táboa',
    HTML:             'HTML',
    Paragraph:        'Parágrafo',
    Heading_1:        'Título 1',
    Heading_2:        'Título 2',
    Heading_3:        'Título 3',
    Heading_4:        'Título 4',
    Heading_5:        'Título 5',
    Heading_6:        'Título 6',
    Preformatted:     'Preformatado',
    Blockquote:       'Cita en parágrafo',
    Table_Header:     'Cabeceira da táboa',
    URL:              'URL',
    Title:            'Título',
    Alternative_Text: 'Texto alternativo',
    Caption:          'Título',
    Summary:          'Resumo',
    Number_Of_Rows:   'Número de filas',
    Number_Of_Cols:   'Número de columnas',
    Submit:           'Enviar',
    Cancel:           'Cancelar',
    Choose:           'Escoller',
    Preview:          'Previsualizar',
    Paste_From_Word:  'Colar dende Word',
    Tools:            'Ferramentas',
    Containers:       'Contenedores',
    Classes:          'Clases',
    Status:           'Estado',
    Source_Code:      'Código fonte'
};


WYMeditor.STRINGS.he = {
    Strong:           'חזק',
    Emphasis:         'מובלט',
    Superscript:      'כתב עילי',
    Subscript:        'כתב תחתי',
    Ordered_List:     'רשימה ממוספרת',
    Unordered_List:   'רשימה לא ממוספרת',
    Indent:           'הזחה פנימה',
    Outdent:          'הזחה החוצה',
    Undo:             'בטל פעולה',
    Redo:             'בצע מחדש פעולה',
    Link:             'קישור',
    Unlink:           'בטל קישור',
    Image:            'תמונה',
    Table:            'טבלה',
    HTML:             'קוד HTML',
    Paragraph:        'פסקה',
    Heading_1:        'כותרת 1 ; תג &lt;h1&gt;',
    Heading_2:        'כותרת 2 ; תג &lt;h2&gt;',
    Heading_3:        'כותרת 3 ; תג &lt;h3&gt;',
    Heading_4:        'כותרת 4 ; תג &lt;h4&gt;',
    Heading_5:        'כותרת 5 ; תג &lt;h5&gt;',
    Heading_6:        'כותרת 6 ; תג &lt;h6&gt;',
    Preformatted:     'משמר רווחים',
    Blockquote:       'ציטוט',
    Table_Header:     'כותרת טבלה',
    URL:              'קישור (URL)',
    Title:            'כותרת',
    Alternative_Text: 'טקסט חלופי',
    Caption:          'כותרת',
    Summary:          'סיכום',
    Number_Of_Rows:   'מספר שורות',
    Number_Of_Cols:   'מספר טורים',
    Submit:           'שלח',
    Cancel:           'בטל',
    Choose:           'בחר',
    Preview:          'תצוגה מקדימה',
    Paste_From_Word:  'העתק מ-Word',
    Tools:            'כלים',
    Containers:       'מיכלים',
    Classes:          'מחלקות',
    Status:           'מצב',
    Source_Code:      'קוד מקור'
};


WYMeditor.STRINGS.hr = {
    Strong:           'Podebljano',
    Emphasis:         'Naglašeno',
    Superscript:      'Iznad',
    Subscript:        'Ispod',
    Ordered_List:     'Pobrojana lista',
    Unordered_List:   'Nepobrojana lista',
    Indent:           'Uvuci',
    Outdent:          'Izvuci',
    Undo:             'Poništi promjenu',
    Redo:             'Ponovno promjeni',
    Link:             'Hiperveza',
    Unlink:           'Ukloni hipervezu',
    Image:            'Slika',
    Table:            'Tablica',
    HTML:             'HTML',
    Paragraph:        'Paragraf',
    Heading_1:        'Naslov 1',
    Heading_2:        'Naslov 2',
    Heading_3:        'Naslov 3',
    Heading_4:        'Naslov 4',
    Heading_5:        'Naslov 5',
    Heading_6:        'Naslov 6',
    Preformatted:     'Unaprijed formatirano',
    Blockquote:       'Citat',
    Table_Header:     'Zaglavlje tablice',
    URL:              'URL',
    Title:            'Naslov',
    Alternative_Text: 'Alternativni tekst',
    Caption:          'Zaglavlje',
    Summary:          'Sažetak',
    Number_Of_Rows:   'Broj redova',
    Number_Of_Cols:   'Broj kolona',
    Submit:           'Snimi',
    Cancel:           'Odustani',
    Choose:           'Izaberi',
    Preview:          'Pregled',
    Paste_From_Word:  'Zalijepi iz Word-a',
    Tools:            'Alati',
    Containers:       'Kontejneri',
    Classes:          'Klase',
    Status:           'Status',
    Source_Code:      'Izvorni kod'
};


WYMeditor.STRINGS.hu = {
    Strong:           'Félkövér',
    Emphasis:         'Kiemelt',
    Superscript:      'Felső index',
    Subscript:        'Alsó index',
    Ordered_List:     'Rendezett lista',
    Unordered_List:   'Rendezetlen lista',
    Indent:           'Bekezdés',
    Outdent:          'Bekezdés törlése',
    Undo:             'Visszavon',
    Redo:             'Visszaállít',
    Link:             'Link',
    Unlink:           'Link törlése',
    Image:            'Kép',
    Table:            'Tábla',
    HTML:             'HTML',
    Paragraph:        'Bekezdés',
    Heading_1:        'Címsor 1',
    Heading_2:        'Címsor 2',
    Heading_3:        'Címsor 3',
    Heading_4:        'Címsor 4',
    Heading_5:        'Címsor 5',
    Heading_6:        'Címsor 6',
    Preformatted:     'Előformázott',
    Blockquote:       'Idézet',
    Table_Header:     'Tábla Fejléc',
    URL:              'Webcím',
    Title:            'Megnevezés',
    Alternative_Text: 'Alternatív szöveg',
    Caption:          'Fejléc',
    Summary:          'Summary',
    Number_Of_Rows:   'Sorok száma',
    Number_Of_Cols:   'Oszlopok száma',
    Submit:           'Elküld',
    Cancel:           'Mégsem',
    Choose:           'Választ',
    Preview:          'Előnézet',
    Paste_From_Word:  'Másolás Word-ból',
    Tools:            'Eszközök',
    Containers:       'Tartalmak',
    Classes:          'Osztályok',
    Status:           'Állapot',
    Source_Code:      'Forráskód'
};


WYMeditor.STRINGS.it = {
    Strong:           'Grassetto',
    Emphasis:         'Corsetto',
    Superscript:      'Apice',
    Subscript:        'Pedice',
    Ordered_List:     'Lista Ordinata',
    Unordered_List:   'Lista Puntata',
    Indent:           'Indenta',
    Outdent:          'Caccia',
    Undo:             'Indietro',
    Redo:             'Avanti',
    Link:             'Inserisci Link',
    Unlink:           'Togli Link',
    Image:            'Inserisci Immagine',
    Table:            'Inserisci Tabella',
    HTML:             'HTML',
    Paragraph:        'Paragrafo',
    Heading_1:        'Heading 1',
    Heading_2:        'Heading 2',
    Heading_3:        'Heading 3',
    Heading_4:        'Heading 4',
    Heading_5:        'Heading 5',
    Heading_6:        'Heading 6',
    Preformatted:     'Preformattato',
    Blockquote:       'Blockquote',
    Table_Header:     'Header Tabella',
    URL:              'Indirizzo',
    Title:            'Titolo',
    Alternative_Text: 'Testo Alternativo',
    Caption:          'Caption',
    Summary:          'Summary',
    Number_Of_Rows:   'Numero di Righe',
    Number_Of_Cols:   'Numero di Colonne',
    Submit:           'Invia',
    Cancel:           'Cancella',
    Choose:           'Scegli',
    Preview:          'Anteprima',
    Paste_From_Word:  'Incolla',
    Tools:            'Tools',
    Containers:       'Contenitori',
    Classes:          'Classi',
    Status:           'Stato',
    Source_Code:      'Codice Sorgente'
};


WYMeditor.STRINGS.ja = {
    Strong: '強調<strong>',
    Emphasis: '強調<em>',
    Superscript: '上付き',
    Subscript: '下付き',
    Ordered_List: '番号付きリスト',
    Unordered_List: '番号無リスト',
    Indent: 'インデントを増やす',
    Outdent: 'インデントを減らす',
    Undo: '元に戻す',
    Redo: 'やり直す',
    Link: 'リンク',
    Unlink: 'リンク取消',
    Image: '画像',
    Table: 'テーブル',
    HTML: 'HTML',
    Paragraph: '段落',
    Heading_1: '見出し 1',
    Heading_2: '見出し 2',
    Heading_3: '見出し 3',
    Heading_4: '見出し 4',
    Heading_5: '見出し 5',
    Heading_6: '見出し 6',
    Preformatted: '整形済みテキスト',
    Blockquote: '引用文',
    Table_Header: '表見出し',
    URL: 'URL',
    Title: 'タイトル',
    Alternative_Text: '代替テキスト',
    Caption: 'キャプション',
    Summary: 'サマリー',
    Number_Of_Rows: '行数',
    Number_Of_Cols: '列数',
    Submit: '送信',
    Cancel: 'キャンセル',
    Choose: '選択',
    Preview: 'プレビュー',
    Paste_From_Word: '貼り付け',
    Tools: 'ツール',
    Containers: 'コンテナ',
    Classes: 'クラス',
    Status: 'ステータス',
    Source_Code: 'ソースコード'
};

WYMeditor.STRINGS.lt = {
    Strong:           'Pusjuodis',
    Emphasis:         'Kursyvas',
    Superscript:      'Viršutinis indeksas',
    Subscript:        'Apatinis indeksas',
    Ordered_List:     'Numeruotas sąrašas',
    Unordered_List:   'Suženklintas sąrašas',
    Indent:           'Padidinti įtrauką',
    Outdent:          'Sumažinti įtrauką',
    Undo:             'Atšaukti',
    Redo:             'Atstatyti',
    Link:             'Nuoroda',
    Unlink:           'Panaikinti nuorodą',
    Image:            'Vaizdas',
    Table:            'Lentelė',
    HTML:             'HTML',
    Paragraph:        'Paragrafas',
    Heading_1:        'Antraštinis 1',
    Heading_2:        'Antraštinis 2',
    Heading_3:        'Antraštinis 3',
    Heading_4:        'Antraštinis 4',
    Heading_5:        'Antraštinis 5',
    Heading_6:        'Antraštinis 6',
    Preformatted:     'Formuotas',
    Blockquote:       'Citata',
    Table_Header:     'Lentelės antraštė',
    URL:              'URL',
    Title:            'Antraštinis tekstas',
    Relationship:     'Sąryšis',
    Alternative_Text: 'Alternatyvus tekstas',
    Caption:          'Antraštė',
    Summary:          'Santrauka',
    Number_Of_Rows:   'Eilučių skaičius',
    Number_Of_Cols:   'Stulpelių skaičius',
    Submit:           'Išsaugoti',
    Cancel:           'Nutraukti',
    Choose:           'Rinktis',
    Preview:          'Peržiūra',
    Paste_From_Word:  'Įkelti iš MS Word',
    Tools:            'Įrankiai',
    Containers:       'Stiliai',
    Classes:          'Klasės',
    Status:           'Statusas',
    Source_Code:      'Išeities tekstas'
};
WYMeditor.STRINGS.nb = {
    Strong:           'Fet',
    Emphasis:         'Uthevet',
    Superscript:      'Opphøyet',
    Subscript:        'Nedsenket',
    Ordered_List:     'Nummerert liste',
    Unordered_List:   'Punktliste',
    Indent:           'Rykk inn',
    Outdent:          'Rykk ut',
    Undo:             'Angre',
    Redo:             'Gjenta',
    Link:             'Lenke',
    Unlink:           'Ta bort lenken',
    Image:            'Bilde',
    Table:            'Tabell',
    HTML:             'HTML',
    Paragraph:        'Avsnitt',
    Heading_1:        'Overskrift 1',
    Heading_2:        'Overskrift 2',
    Heading_3:        'Overskrift 3',
    Heading_4:        'Overskrift 4',
    Heading_5:        'Overskrift 5',
    Heading_6:        'Overskrift 6',
    Preformatted:     'Preformatert',
    Blockquote:       'Sitat',
    Table_Header:     'Tabelloverskrift',
    URL:              'URL',
    Title:            'Tittel',
    Alternative_Text: 'Alternativ tekst',
    Caption:          'Overskrift',
    Summary:          'Sammendrag',
    Number_Of_Rows:   'Antall rader',
    Number_Of_Cols:   'Antall kolonner',
    Submit:           'Ok',
    Cancel:           'Avbryt',
    Choose:           'Velg',
    Preview:          'Forhåndsvis',
    Paste_From_Word:  'Lim inn fra Word',
    Tools:            'Verktøy',
    Containers:       'Formatering',
    Classes:          'Klasser',
    Status:           'Status',
    Source_Code:      'Kildekode'
};


WYMeditor.STRINGS.nl = {
    Strong:           'Sterk benadrukken',
    Emphasis:         'Benadrukken',
    Superscript:      'Bovenschrift',
    Subscript:        'Onderschrift',
    Ordered_List:     'Geordende lijst',
    Unordered_List:   'Ongeordende lijst',
    Indent:           'Inspringen',
    Outdent:          'Terugspringen',
    Undo:             'Ongedaan maken',
    Redo:             'Opnieuw uitvoeren',
    Link:             'Linken',
    Unlink:           'Ontlinken',
    Image:            'Afbeelding',
    Table:            'Tabel',
    HTML:             'HTML',
    Paragraph:        'Paragraaf',
    Heading_1:        'Kop 1',
    Heading_2:        'Kop 2',
    Heading_3:        'Kop 3',
    Heading_4:        'Kop 4',
    Heading_5:        'Kop 5',
    Heading_6:        'Kop 6',
    Preformatted:     'Voorgeformatteerd',
    Blockquote:       'Citaat',
    Table_Header:     'Tabel-kop',
    URL:              'URL',
    Title:            'Titel',
    Relationship:     'Relatie',
    Alternative_Text: 'Alternatieve tekst',
    Caption:          'Bijschrift',
    Summary:          'Summary',
    Number_Of_Rows:   'Aantal rijen',
    Number_Of_Cols:   'Aantal kolommen',
    Submit:           'Versturen',
    Cancel:           'Annuleren',
    Choose:           'Kiezen',
    Preview:          'Voorbeeld bekijken',
    Paste_From_Word:  'Plakken uit Word',
    Tools:            'Hulpmiddelen',
    Containers:       'Teksttypes',
    Classes:          'Klassen',
    Status:           'Status',
    Source_Code:      'Broncode'
};
WYMeditor.STRINGS.nn = {
    Strong:           'Feit',
    Emphasis:         'Utheva',
    Superscript:      'Opphøgd',
    Subscript:        'Nedsenka',
    Ordered_List:     'Nummerert liste',
    Unordered_List:   'Punktliste',
    Indent:           'Rykk inn',
    Outdent:          'Rykk ut',
    Undo:             'Angre',
    Redo:             'Gjentaka',
    Link:             'Lenkje',
    Unlink:           'Ta bort lenkja',
    Image:            'Bilete',
    Table:            'Tabell',
    HTML:             'HTML',
    Paragraph:        'Avsnitt',
    Heading_1:        'Overskrift 1',
    Heading_2:        'Overskrift 2',
    Heading_3:        'Overskrift 3',
    Heading_4:        'Overskrift 4',
    Heading_5:        'Overskrift 5',
    Heading_6:        'Overskrift 6',
    Preformatted:     'Preformatert',
    Blockquote:       'Sitat',
    Table_Header:     'Tabelloverskrift',
    URL:              'URL',
    Title:            'Tittel',
    Alternative_Text: 'Alternativ tekst',
    Caption:          'Overskrift',
    Summary:          'Samandrag',
    Number_Of_Rows:   'Tal på rader',
    Number_Of_Cols:   'Tal på kolonnar',
    Submit:           'Ok',
    Cancel:           'Avbryt',
    Choose:           'Vel',
    Preview:          'Førehandsvis',
    Paste_From_Word:  'Lim inn frå Word',
    Tools:            'Verkty',
    Containers:       'Formatering',
    Classes:          'Klassar',
    Status:           'Status',
    Source_Code:      'Kjeldekode'
};


WYMeditor.STRINGS.pl = {
    Strong:           'Nacisk',
    Emphasis:         'Emfaza',
    Superscript:      'Indeks górny',
    Subscript:        'Indeks dolny',
    Ordered_List:     'Lista numerowana',
    Unordered_List:   'Lista wypunktowana',
    Indent:           'Zwiększ wcięcie',
    Outdent:          'Zmniejsz wcięcie',
    Undo:             'Cofnij',
    Redo:             'Ponów',
    Link:             'Wstaw link',
    Unlink:           'Usuń link',
    Image:            'Obraz',
    Table:            'Tabela',
    HTML:             'Źródło HTML',
    Paragraph:        'Akapit',
    Heading_1:        'Nagłówek 1',
    Heading_2:        'Nagłówek 2',
    Heading_3:        'Nagłówek 3',
    Heading_4:        'Nagłówek 4',
    Heading_5:        'Nagłówek 5',
    Heading_6:        'Nagłówek 6',
    Preformatted:     'Preformatowany',
    Blockquote:       'Cytat blokowy',
    Table_Header:     'Nagłówek tabeli',
    URL:              'URL',
    Title:            'Tytuł',
    Alternative_Text: 'Tekst alternatywny',
    Caption:          'Tytuł tabeli',
    Summary:          'Summary',
    Number_Of_Rows:   'Liczba wierszy',
    Number_Of_Cols:   'Liczba kolumn',
    Submit:           'Wyślij',
    Cancel:           'Anuluj',
    Choose:           'Wybierz',
    Preview:          'Podgląd',
    Paste_From_Word:  'Wklej z Worda',
    Tools:            'Narzędzia',
    Containers:       'Format',
    Classes:          'Styl',
    Status:           'Status',
    Source_Code:      'Kod źródłowy'
};


WYMeditor.STRINGS['pt-br'] = {
    Strong:           'Resaltar',
    Emphasis:         'Enfatizar',
    Superscript:      'Sobre escrito',
    Subscript:        'Sub escrito ',
    Ordered_List:     'Lista ordenada',
    Unordered_List:   'Lista desordenada',
    Indent:           'Indentado',
    Outdent:          'Desidentar',
    Undo:             'Desfazer',
    Redo:             'Refazer',
    Link:             'Link',
    Unlink:           'Remover Link',
    Image:            'Imagem',
    Table:            'Tabela',
    HTML:             'HTML',
    Paragraph:        'Parágrafo',
    Heading_1:        'Título 1',
    Heading_2:        'Título 2',
    Heading_3:        'Título 3',
    Heading_4:        'Título 4',
    Heading_5:        'Título 5',
    Heading_6:        'Título 6',
    Preformatted:     'Preformatado',
    Blockquote:       'Citação',
    Table_Header:     'Título de tabela',
    URL:              'URL',
    Title:            'Título',
    Alternative_Text: 'Texto alternativo',
    Caption:          'Legenda',
    Summary:          'Summary',
    Number_Of_Rows:   'Número de linhas',
    Number_Of_Cols:   'Número de colunas',
    Submit:           'Enviar',
    Cancel:           'Cancelar',
    Choose:           'Selecionar',
    Preview:          'Previsualizar',
    Paste_From_Word:  'Copiar do Word',
    Tools:            'Ferramentas',
    Containers:       'Conteneiners',
    Classes:          'Classes',
    Status:           'Estado',
    Source_Code:      'Código fonte'
};


WYMeditor.STRINGS.pt = {
    Strong:           'Negrito',
    Emphasis:         'Itálico',
    Superscript:      'Sobrescrito',
    Subscript:        'Subsescrito',
    Ordered_List:     'Lista Numerada',
    Unordered_List:   'Lista Marcada',
    Indent:           'Aumentar Indentaçã',
    Outdent:          'Diminuir Indentaçã',
    Undo:             'Desfazer',
    Redo:             'Restaurar',
    Link:             'Link',
    Unlink:           'Tirar link',
    Image:            'Imagem',
    Table:            'Tabela',
    HTML:             'HTML',
    Paragraph:        'Parágrafo',
    Heading_1:        'Título 1',
    Heading_2:        'Título 2',
    Heading_3:        'Título 3',
    Heading_4:        'Título 4',
    Heading_5:        'Título 5',
    Heading_6:        'Título 6',
    Preformatted:     'Pré-formatado',
    Blockquote:       'Citação',
    Table_Header:     'Cabeçalho Tabela',
    URL:              'URL',
    Title:            'Título',
    Alternative_Text: 'Texto Alterativo',
    Caption:          'Título Tabela',
    Summary:          'Summary',
    Number_Of_Rows:   'Número de Linhas',
    Number_Of_Cols:   'Número de Colunas',
    Submit:           'Enviar',
    Cancel:           'Cancelar',
    Choose:           'Escolha',
    Preview:          'Prever',
    Paste_From_Word:  'Colar do Word',
    Tools:            'Ferramentas',
    Containers:       'Containers',
    Classes:          'Classes',
    Status:           'Status',
    Source_Code:      'Código Fonte'
};


WYMeditor.STRINGS.ru = {
    Strong:           'Жирный',
    Emphasis:         'Наклонный',
    Superscript:      'Надстрочный',
    Subscript:        'Подстрочный',
    Ordered_List:     'Нумерованый список',
    Unordered_List:   'Ненумерованый список',
    Indent:           'Увеличить отступ',
    Outdent:          'Уменьшить отступ',
    Undo:             'Отменить',
    Redo:             'Повторить',
    Link:             'Ссылка',
    Unlink:           'Удалить ссылку',
    Image:            'Изображение',
    Table:            'Таблица',
    HTML:             'Править HTML',
    Paragraph:        'Параграф',
    Heading_1:        'Заголовок 1',
    Heading_2:        'Заголовок 2',
    Heading_3:        'Заголовок 3',
    Heading_4:        'Заголовок 4',
    Heading_5:        'Заголовок 5',
    Heading_6:        'Заголовок 6',
    Preformatted:     'Preformatted',
    Blockquote:       'Цитата',
    Table_Header:     'Заголовок таблицы',
    URL:              'URL',
    Title:            'Заголовок',
    Alternative_Text: 'Альтернативный текст',
    Caption:          'Надпись',
    Summary:          'Summary',
    Number_Of_Rows:   'Кол-во строк',
    Number_Of_Cols:   'Кол-во столбцов',
    Submit:           'Отправить',
    Cancel:           'Отмена',
    Choose:           'Выбор',
    Preview:          'Просмотр',
    Paste_From_Word:  'Вставить из Word',
    Tools:            'Инструменты',
    Containers:       'Контейнеры',
    Classes:          'Классы',
    Status:           'Статус',
    Source_Code:      'Исходный код'
};


WYMeditor.STRINGS.sk = {
    Strong:           'Tučné',
    Emphasis:         'Kurzíva',
    Superscript:      'Horný index',
    Subscript:        'Dolný index',
    Ordered_List:     'Číslovaný zoznam',
    Unordered_List:   'Nečíslovaný zoznam',
    Indent:           'Zväčšiť odsadenie',
    Outdent:          'Zmenšiť odsadenie',
    Undo:             'Vrátiť',
    Redo:             'Opakovať',
    Link:             'Vytvoriť odkaz',
    Unlink:           'Zrušiť odkaz',
    Image:            'Obrázok',
    Table:            'Tabuľka',
    HTML:             'HTML',
    Paragraph:        'Odstavec',
    Heading_1:        'Nadpis 1. úrovne',
    Heading_2:        'Nadpis 2. úrovne',
    Heading_3:        'Nadpis 3. úrovne',
    Heading_4:        'Nadpis 4. úrovne',
    Heading_5:        'Nadpis 5. úrovne',
    Heading_6:        'Nadpis 6. úrovne',
    Preformatted:     'Predformátovaný text',
    Blockquote:       'Citácia',
    Table_Header:     'Hlavička tabuľky',
    URL:              'URL adresa',
    Title:            'Titulok',
    Alternative_Text: 'Alternatívny text',
    Caption:          'Titulok tabuľky',
    Summary:          'Zhrnutie obsahu',
    Number_Of_Rows:   'Počet riadkov',
    Number_Of_Cols:   'Počet stĺpcov',
    Submit:           'Odoslať',
    Cancel:           'Zrušiť',
    Choose:           'Vybrať',
    Preview:          'Náhľad',
    Paste_From_Word:  'Vložiť z Wordu',
    Tools:            'Nástroje',
    Containers:       'Typy obsahu',
    Classes:          'Triedy',
    Status:           'Stav',
    Source_Code:      'Zdrojový kód'
};


WYMeditor.STRINGS.sv = {
    Strong:           'Viktigt',
    Emphasis:         'Betoning',
    Superscript:      'Upphöjt',
    Subscript:        'Nedsänkt',
    Ordered_List:     'Nummerlista',
    Unordered_List:   'Punktlista',
    Indent:           'Indrag',
    Outdent:          'Utdrag',
    Undo:             'Ångra',
    Redo:             'Gör om',
    Link:             'Länk',
    Unlink:           'Ta bort länk',
    Image:            'Bild',
    Table:            'Tabell',
    HTML:             'HTML',
    Paragraph:        'Paragraf',
    Heading_1:        'Rubrik 1',
    Heading_2:        'Rubrik 2',
    Heading_3:        'Rubrik 3',
    Heading_4:        'Rubrik 4',
    Heading_5:        'Rubrik 5',
    Heading_6:        'Rubrik 6',
    Preformatted:     'Förformaterad',
    Blockquote:       'Blockcitat',
    Table_Header:     'Tabellrubrik',
    URL:              'URL',
    Title:            'Titel',
    Relationship:     'Relation',
    Alternative_Text: 'Alternativ text',
    Caption:          'Överskrift',
    Summary:          'Summary',
    Number_Of_Rows:   'Antal rader',
    Number_Of_Cols:   'Antal kolumner',
    Submit:           'Skicka',
    Cancel:           'Avbryt',
    Choose:           'Välj',
    Preview:          'Förhandsgranska',
    Paste_From_Word:  'Klistra in från Word',
    Tools:            'Verktyg',
    Containers:       'Formatering',
    Classes:          'Klasser',
    Status:           'Status',
    Source_Code:      'Källkod'
};


WYMeditor.STRINGS.tr = {
    Strong: 'Kalın',
    Emphasis: 'Vurgu',
    Superscript: 'Üstsimge',
    Subscript: 'Altsimge',
    Ordered_List: 'Sıralı List',
    Unordered_List: 'Sırasız List',
    Indent: 'Girintile',
    Outdent: 'Çıkıntıla',
    Undo: 'Geri Al',
    Redo: 'Yinele',
    Link: 'Bağlantı',
    Unlink: 'Bağlantıyı Kaldır',
    Image: 'Resim',
    Table: 'Tablo',
    HTML: 'HTML',
    Paragraph: 'Parağraf',
    Heading_1: 'Başlık 1',
    Heading_2: 'Başlık 2',
    Heading_3: 'Başlık 3',
    Heading_4: 'Başlık 4',
    Heading_5: 'Başlık 5',
    Heading_6: 'Başlık 6',
    Preformatted: 'Önceden Formatlı',
    Blockquote: 'Alıntı',
    Table_Header: 'Tablo Başlığı',
    URL: 'URL',
    Title: 'Başlık',
    Alternative_Text: 'Alternatif Metin',
    Caption: 'Etiket',
    Summary: 'Özet',
    Number_Of_Rows: 'Satır sayısı',
    Number_Of_Cols: 'Sütun sayısı',
    Submit: 'Gönder',
    Cancel: 'İptal',
    Choose: 'Seç',
    Preview: 'Önizleme',
    Paste_From_Word: 'Word\'den yapıştır',
    Tools: 'Araçlar',
    Containers: 'Kapsayıcılar',
    Classes: 'Sınıflar',
    Status: 'Durum',
    Source_Code: 'Kaynak Kodu'
};


WYMeditor.STRINGS.zh_cn = {
    Strong: '加粗',
    Emphasis: '斜体',
    Superscript: '上标',
    Subscript: '下标',
    Ordered_List: '有序列表',
    Unordered_List: '无序列表',
    Indent: '增加缩进',
    Outdent: '减少缩进',
    Undo: '撤消',
    Redo: '重做',
    Link: '链接',
    Unlink: '取消链接',
    Image: '图片',
    Table: '表格',
    HTML: 'HTML源代码',
    Paragraph: '段落',
    Heading_1: '标题 1',
    Heading_2: '标题 2',
    Heading_3: '标题 3',
    Heading_4: '标题 4',
    Heading_5: '标题 5',
    Heading_6: '标题 6',
    Preformatted: '原始文本',
    Blockquote: '引语',
    Table_Header: '表头',
    URL: '地址',
    Title: '提示文字',
    Alternative_Text: '失效文字',
    Caption: '标题',
    Summary: 'Summary',
    Number_Of_Rows: '行数',
    Number_Of_Cols: '列数',
    Submit: '提交',
    Cancel: '放弃',
    Choose: '选择',
    Preview: '预览',
    Paste_From_Word: '从Word粘贴纯文本',
    Tools: '工具',
    Containers: '容器',
    Classes: '预定义样式',
    Status: '状态',
    Source_Code: '源代码',
    Attachment: '附件',
    NewParagraph: '新段落'
};


WYMeditor.STRINGS.zh_tw = {
    Strong: '加粗',
    Emphasis: '斜體',
    Superscript: '上標',
    Subscript: '下標',
    Ordered_List: '有序列表',
    Unordered_List: '無序列表',
    Indent: '增加縮排',
    Outdent: '減少縮排',
    Undo: '取消',
    Redo: '重做',
    Link: '鏈結',
    Unlink: '取消鏈結',
    Image: '圖片',
    Table: '表格',
    HTML: 'HTML 源代碼',
    Paragraph: '段落',
    Heading_1: '標題 1',
    Heading_2: '標題 2',
    Heading_3: '標題 3',
    Heading_4: '標題 4',
    Heading_5: '標題 5',
    Heading_6: '標題 6',
    Preformatted: '原始文本',
    Blockquote: '引語',
    Table_Header: '表格頂部',
    URL: '地址',
    Title: '提示文字',
    Alternative_Text: '失效文字',
    Caption: '主題',
    Summary: '大綱',
    Number_Of_Rows: '行數',
    Number_Of_Cols: '列數',
    Submit: '提交',
    Cancel: '放棄',
    Choose: '選擇',
    Preview: '預覽',
    Paste_From_Word: '從Word複制純文本',
    Tools: '工具',
    Containers: '容器',
    Classes: '預定義樣式',
    Status: '狀態',
    Source_Code: '源代碼',
    Attachment: '附件',
    NewParagraph: '新段落'
};

/**
 * @license Rangy, a cross-browser JavaScript range and selection library
 * http://code.google.com/p/rangy/
 *
 * Copyright 2011, Tim Down
 * Licensed under the MIT license.
 * Version: 1.2.2
 * Build date: 13 November 2011
 */
window['rangy'] = (function() {


    var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined";

    var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
        "commonAncestorContainer", "START_TO_START", "START_TO_END", "END_TO_START", "END_TO_END"];

    var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore",
        "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents",
        "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"];

    var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"];

    // Subset of TextRange's full set of methods that we're interested in
    var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "getBookmark", "moveToBookmark",
        "moveToElementText", "parentElement", "pasteHTML", "select", "setEndPoint", "getBoundingClientRect"];

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

    // Trio of functions taken from Peter Michaux's article:
    // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
    function isHostMethod(o, p) {
        var t = typeof o[p];
        return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown";
    }

    function isHostObject(o, p) {
        return !!(typeof o[p] == OBJECT && o[p]);
    }

    function isHostProperty(o, p) {
        return typeof o[p] != UNDEFINED;
    }

    // Creates a convenience function to save verbose repeated calls to tests functions
    function createMultiplePropertyTest(testFunc) {
        return function(o, props) {
            var i = props.length;
            while (i--) {
                if (!testFunc(o, props[i])) {
                    return false;
                }
            }
            return true;
        };
    }

    // Next trio of functions are a convenience to save verbose repeated calls to previous two functions
    var areHostMethods = createMultiplePropertyTest(isHostMethod);
    var areHostObjects = createMultiplePropertyTest(isHostObject);
    var areHostProperties = createMultiplePropertyTest(isHostProperty);

    function isTextRange(range) {
        return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);
    }

    var api = {
        version: "1.2.2",
        initialized: false,
        supported: true,

        util: {
            isHostMethod: isHostMethod,
            isHostObject: isHostObject,
            isHostProperty: isHostProperty,
            areHostMethods: areHostMethods,
            areHostObjects: areHostObjects,
            areHostProperties: areHostProperties,
            isTextRange: isTextRange
        },

        features: {},

        modules: {},
        config: {
            alertOnWarn: false,
            preferTextRange: false
        }
    };

    function fail(reason) {
        window.alert("Rangy not supported in your browser. Reason: " + reason);
        api.initialized = true;
        api.supported = false;
    }

    api.fail = fail;

    function warn(msg) {
        var warningMessage = "Rangy warning: " + msg;
        if (api.config.alertOnWarn) {
            window.alert(warningMessage);
        } else if (typeof window.console != UNDEFINED && typeof window.console.log != UNDEFINED) {
            window.console.log(warningMessage);
        }
    }

    api.warn = warn;

    if ({}.hasOwnProperty) {
        api.util.extend = function(o, props) {
            for (var i in props) {
                if (props.hasOwnProperty(i)) {
                    o[i] = props[i];
                }
            }
        };
    } else {
        fail("hasOwnProperty not supported");
    }

    var initListeners = [];
    var moduleInitializers = [];

    // Initialization
    function init() {
        if (api.initialized) {
            return;
        }
        var testRange;
        var implementsDomRange = false, implementsTextRange = false;

        // First, perform basic feature tests

        if (isHostMethod(document, "createRange")) {
            testRange = document.createRange();
            if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {
                implementsDomRange = true;
            }
            testRange.detach();
        }

        var body = isHostObject(document, "body") ? document.body : document.getElementsByTagName("body")[0];

        if (body && isHostMethod(body, "createTextRange")) {
            testRange = body.createTextRange();
            if (isTextRange(testRange)) {
                implementsTextRange = true;
            }
        }

        if (!implementsDomRange && !implementsTextRange) {
            fail("Neither Range nor TextRange are implemented");
        }

        api.initialized = true;
        api.features = {
            implementsDomRange: implementsDomRange,
            implementsTextRange: implementsTextRange
        };

        // Initialize modules and call init listeners
        var allListeners = moduleInitializers.concat(initListeners);
        for (var i = 0, len = allListeners.length; i < len; ++i) {
            try {
                allListeners[i](api);
            } catch (ex) {
                if (isHostObject(window, "console") && isHostMethod(window.console, "log")) {
                    window.console.log("Init listener threw an exception. Continuing.", ex);
                }

            }
        }
    }

    // Allow external scripts to initialize this library in case it's loaded after the document has loaded
    api.init = init;

    // Execute listener immediately if already initialized
    api.addInitListener = function(listener) {
        if (api.initialized) {
            listener(api);
        } else {
            initListeners.push(listener);
        }
    };

    var createMissingNativeApiListeners = [];

    api.addCreateMissingNativeApiListener = function(listener) {
        createMissingNativeApiListeners.push(listener);
    };

    function createMissingNativeApi(win) {
        win = win || window;
        init();

        // Notify listeners
        for (var i = 0, len = createMissingNativeApiListeners.length; i < len; ++i) {
            createMissingNativeApiListeners[i](win);
        }
    }

    api.createMissingNativeApi = createMissingNativeApi;

    /**
     * @constructor
     */
    function Module(name) {
        this.name = name;
        this.initialized = false;
        this.supported = false;
    }

    Module.prototype.fail = function(reason) {
        this.initialized = true;
        this.supported = false;

        throw new Error("Module '" + this.name + "' failed to load: " + reason);
    };

    Module.prototype.warn = function(msg) {
        api.warn("Module " + this.name + ": " + msg);
    };

    Module.prototype.createError = function(msg) {
        return new Error("Error in Rangy " + this.name + " module: " + msg);
    };

    api.createModule = function(name, initFunc) {
        var module = new Module(name);
        api.modules[name] = module;

        moduleInitializers.push(function(api) {
            initFunc(api, module);
            module.initialized = true;
            module.supported = true;
        });
    };

    api.requireModules = function(modules) {
        for (var i = 0, len = modules.length, module, moduleName; i < len; ++i) {
            moduleName = modules[i];
            module = api.modules[moduleName];
            if (!module || !(module instanceof Module)) {
                throw new Error("Module '" + moduleName + "' not found");
            }
            if (!module.supported) {
                throw new Error("Module '" + moduleName + "' not supported");
            }
        }
    };

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

    // Wait for document to load before running tests

    var docReady = false;

    var loadHandler = function(e) {

        if (!docReady) {
            docReady = true;
            if (!api.initialized) {
                init();
            }
        }
    };

    // Test whether we have window and document objects that we will need
    if (typeof window == UNDEFINED) {
        fail("No window found");
        return;
    }
    if (typeof document == UNDEFINED) {
        fail("No document found");
        return;
    }

    if (isHostMethod(document, "addEventListener")) {
        document.addEventListener("DOMContentLoaded", loadHandler, false);
    }

    // Add a fallback in case the DOMContentLoaded event isn't supported
    if (isHostMethod(window, "addEventListener")) {
        window.addEventListener("load", loadHandler, false);
    } else if (isHostMethod(window, "attachEvent")) {
        window.attachEvent("onload", loadHandler);
    } else {
        fail("Window does not have required addEventListener or attachEvent method");
    }

    return api;
})();
rangy.createModule("DomUtil", function(api, module) {

    var UNDEF = "undefined";
    var util = api.util;

    // Perform feature tests
    if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) {
        module.fail("document missing a Node creation method");
    }

    if (!util.isHostMethod(document, "getElementsByTagName")) {
        module.fail("document missing getElementsByTagName method");
    }

    var el = document.createElement("div");
    if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] ||
            !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) {
        module.fail("Incomplete Element implementation");
    }

    // innerHTML is required for Range's createContextualFragment method
    if (!util.isHostProperty(el, "innerHTML")) {
        module.fail("Element is missing innerHTML property");
    }

    var textNode = document.createTextNode("test");
    if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] ||
            !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) ||
            !util.areHostProperties(textNode, ["data"]))) {
        module.fail("Incomplete Text Node implementation");
    }

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

    // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been
    // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that
    // contains just the document as a single element and the value searched for is the document.
    var arrayContains = /*Array.prototype.indexOf ?
        function(arr, val) {
            return arr.indexOf(val) > -1;
        }:*/

        function(arr, val) {
            var i = arr.length;
            while (i--) {
                if (arr[i] === val) {
                    return true;
                }
            }
            return false;
        };

    // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI
    function isHtmlNamespace(node) {
        var ns;
        return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml");
    }

    function parentElement(node) {
        var parent = node.parentNode;
        return (parent.nodeType == 1) ? parent : null;
    }

    function getNodeIndex(node) {
        var i = 0;
        while( (node = node.previousSibling) ) {
            i++;
        }
        return i;
    }

    function getNodeLength(node) {
        var childNodes;
        return isCharacterDataNode(node) ? node.length : ((childNodes = node.childNodes) ? childNodes.length : 0);
    }

    function getCommonAncestor(node1, node2) {
        var ancestors = [], n;
        for (n = node1; n; n = n.parentNode) {
            ancestors.push(n);
        }

        for (n = node2; n; n = n.parentNode) {
            if (arrayContains(ancestors, n)) {
                return n;
            }
        }

        return null;
    }

    function isAncestorOf(ancestor, descendant, selfIsAncestor) {
        var n = selfIsAncestor ? descendant : descendant.parentNode;
        while (n) {
            if (n === ancestor) {
                return true;
            } else {
                n = n.parentNode;
            }
        }
        return false;
    }

    function getClosestAncestorIn(node, ancestor, selfIsAncestor) {
        var p, n = selfIsAncestor ? node : node.parentNode;
        while (n) {
            p = n.parentNode;
            if (p === ancestor) {
                return n;
            }
            n = p;
        }
        return null;
    }

    function isCharacterDataNode(node) {
        var t = node.nodeType;
        return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment
    }

    function insertAfter(node, precedingNode) {
        var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
        if (nextNode) {
            parent.insertBefore(node, nextNode);
        } else {
            parent.appendChild(node);
        }
        return node;
    }

    // Note that we cannot use splitText() because it is bugridden in IE 9.
    function splitDataNode(node, index) {
        var newNode = node.cloneNode(false);
        newNode.deleteData(0, index);
        node.deleteData(index, node.length - index);
        insertAfter(newNode, node);
        return newNode;
    }

    function getDocument(node) {
        if (node.nodeType == 9) {
            return node;
        } else if (typeof node.ownerDocument != UNDEF) {
            return node.ownerDocument;
        } else if (typeof node.document != UNDEF) {
            return node.document;
        } else if (node.parentNode) {
            return getDocument(node.parentNode);
        } else {
            throw new Error("getDocument: no document found for node");
        }
    }

    function getWindow(node) {
        var doc = getDocument(node);
        if (typeof doc.defaultView != UNDEF) {
            return doc.defaultView;
        } else if (typeof doc.parentWindow != UNDEF) {
            return doc.parentWindow;
        } else {
            throw new Error("Cannot get a window object for node");
        }
    }

    function getIframeDocument(iframeEl) {
        if (typeof iframeEl.contentDocument != UNDEF) {
            return iframeEl.contentDocument;
        } else if (typeof iframeEl.contentWindow != UNDEF) {
            return iframeEl.contentWindow.document;
        } else {
            throw new Error("getIframeWindow: No Document object found for iframe element");
        }
    }

    function getIframeWindow(iframeEl) {
        if (typeof iframeEl.contentWindow != UNDEF) {
            return iframeEl.contentWindow;
        } else if (typeof iframeEl.contentDocument != UNDEF) {
            return iframeEl.contentDocument.defaultView;
        } else {
            throw new Error("getIframeWindow: No Window object found for iframe element");
        }
    }

    function getBody(doc) {
        return util.isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0];
    }

    function getRootContainer(node) {
        var parent;
        while ( (parent = node.parentNode) ) {
            node = parent;
        }
        return node;
    }

    function comparePoints(nodeA, offsetA, nodeB, offsetB) {
        // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing
        var nodeC, root, childA, childB, n;
        if (nodeA == nodeB) {

            // Case 1: nodes are the same
            return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;
        } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {

            // Case 2: node C (container B or an ancestor) is a child node of A
            return offsetA <= getNodeIndex(nodeC) ? -1 : 1;
        } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {

            // Case 3: node C (container A or an ancestor) is a child node of B
            return getNodeIndex(nodeC) < offsetB  ? -1 : 1;
        } else {

            // Case 4: containers are siblings or descendants of siblings
            root = getCommonAncestor(nodeA, nodeB);
            childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);
            childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);

            if (childA === childB) {
                // This shouldn't be possible

                throw new Error("comparePoints got to case 4 and childA and childB are the same!");
            } else {
                n = root.firstChild;
                while (n) {
                    if (n === childA) {
                        return -1;
                    } else if (n === childB) {
                        return 1;
                    }
                    n = n.nextSibling;
                }
                throw new Error("Should not be here!");
            }
        }
    }

    function fragmentFromNodeChildren(node) {
        var fragment = getDocument(node).createDocumentFragment(), child;
        while ( (child = node.firstChild) ) {
            fragment.appendChild(child);
        }
        return fragment;
    }

    function inspectNode(node) {
        if (!node) {
            return "[No node]";
        }
        if (isCharacterDataNode(node)) {
            return '"' + node.data + '"';
        } else if (node.nodeType == 1) {
            var idAttr = node.id ? ' id="' + node.id + '"' : "";
            return "<" + node.nodeName + idAttr + ">[" + node.childNodes.length + "]";
        } else {
            return node.nodeName;
        }
    }

    /**
     * @constructor
     */
    function NodeIterator(root) {
        this.root = root;
        this._next = root;
    }

    NodeIterator.prototype = {
        _current: null,

        hasNext: function() {
            return !!this._next;
        },

        next: function() {
            var n = this._current = this._next;
            var child, next;
            if (this._current) {
                child = n.firstChild;
                if (child) {
                    this._next = child;
                } else {
                    next = null;
                    while ((n !== this.root) && !(next = n.nextSibling)) {
                        n = n.parentNode;
                    }
                    this._next = next;
                }
            }
            return this._current;
        },

        detach: function() {
            this._current = this._next = this.root = null;
        }
    };

    function createIterator(root) {
        return new NodeIterator(root);
    }

    /**
     * @constructor
     */
    function DomPosition(node, offset) {
        this.node = node;
        this.offset = offset;
    }

    DomPosition.prototype = {
        equals: function(pos) {
            return this.node === pos.node & this.offset == pos.offset;
        },

        inspect: function() {
            return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]";
        }
    };

    /**
     * @constructor
     */
    function DOMException(codeName) {
        this.code = this[codeName];
        this.codeName = codeName;
        this.message = "DOMException: " + this.codeName;
    }

    DOMException.prototype = {
        INDEX_SIZE_ERR: 1,
        HIERARCHY_REQUEST_ERR: 3,
        WRONG_DOCUMENT_ERR: 4,
        NO_MODIFICATION_ALLOWED_ERR: 7,
        NOT_FOUND_ERR: 8,
        NOT_SUPPORTED_ERR: 9,
        INVALID_STATE_ERR: 11
    };

    DOMException.prototype.toString = function() {
        return this.message;
    };

    api.dom = {
        arrayContains: arrayContains,
        isHtmlNamespace: isHtmlNamespace,
        parentElement: parentElement,
        getNodeIndex: getNodeIndex,
        getNodeLength: getNodeLength,
        getCommonAncestor: getCommonAncestor,
        isAncestorOf: isAncestorOf,
        getClosestAncestorIn: getClosestAncestorIn,
        isCharacterDataNode: isCharacterDataNode,
        insertAfter: insertAfter,
        splitDataNode: splitDataNode,
        getDocument: getDocument,
        getWindow: getWindow,
        getIframeWindow: getIframeWindow,
        getIframeDocument: getIframeDocument,
        getBody: getBody,
        getRootContainer: getRootContainer,
        comparePoints: comparePoints,
        inspectNode: inspectNode,
        fragmentFromNodeChildren: fragmentFromNodeChildren,
        createIterator: createIterator,
        DomPosition: DomPosition
    };

    api.DOMException = DOMException;
});rangy.createModule("DomRange", function(api, module) {
    api.requireModules( ["DomUtil"] );


    var dom = api.dom;
    var DomPosition = dom.DomPosition;
    var DOMException = api.DOMException;
    
    /*----------------------------------------------------------------------------------------------------------------*/

    // Utility functions

    function isNonTextPartiallySelected(node, range) {
        return (node.nodeType != 3) &&
               (dom.isAncestorOf(node, range.startContainer, true) || dom.isAncestorOf(node, range.endContainer, true));
    }

    function getRangeDocument(range) {
        return dom.getDocument(range.startContainer);
    }

    function dispatchEvent(range, type, args) {
        var listeners = range._listeners[type];
        if (listeners) {
            for (var i = 0, len = listeners.length; i < len; ++i) {
                listeners[i].call(range, {target: range, args: args});
            }
        }
    }

    function getBoundaryBeforeNode(node) {
        return new DomPosition(node.parentNode, dom.getNodeIndex(node));
    }

    function getBoundaryAfterNode(node) {
        return new DomPosition(node.parentNode, dom.getNodeIndex(node) + 1);
    }

    function insertNodeAtPosition(node, n, o) {
        var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;
        if (dom.isCharacterDataNode(n)) {
            if (o == n.length) {
                dom.insertAfter(node, n);
            } else {
                n.parentNode.insertBefore(node, o == 0 ? n : dom.splitDataNode(n, o));
            }
        } else if (o >= n.childNodes.length) {
            n.appendChild(node);
        } else {
            n.insertBefore(node, n.childNodes[o]);
        }
        return firstNodeInserted;
    }

    function cloneSubtree(iterator) {
        var partiallySelected;
        for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
            partiallySelected = iterator.isPartiallySelectedSubtree();

            node = node.cloneNode(!partiallySelected);
            if (partiallySelected) {
                subIterator = iterator.getSubtreeIterator();
                node.appendChild(cloneSubtree(subIterator));
                subIterator.detach(true);
            }

            if (node.nodeType == 10) { // DocumentType
                throw new DOMException("HIERARCHY_REQUEST_ERR");
            }
            frag.appendChild(node);
        }
        return frag;
    }

    function iterateSubtree(rangeIterator, func, iteratorState) {
        var it, n;
        iteratorState = iteratorState || { stop: false };
        for (var node, subRangeIterator; node = rangeIterator.next(); ) {
            //log.debug("iterateSubtree, partially selected: " + rangeIterator.isPartiallySelectedSubtree(), nodeToString(node));
            if (rangeIterator.isPartiallySelectedSubtree()) {
                // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of the
                // node selected by the Range.
                if (func(node) === false) {
                    iteratorState.stop = true;
                    return;
                } else {
                    subRangeIterator = rangeIterator.getSubtreeIterator();
                    iterateSubtree(subRangeIterator, func, iteratorState);
                    subRangeIterator.detach(true);
                    if (iteratorState.stop) {
                        return;
                    }
                }
            } else {
                // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its
                // descendant
                it = dom.createIterator(node);
                while ( (n = it.next()) ) {
                    if (func(n) === false) {
                        iteratorState.stop = true;
                        return;
                    }
                }
            }
        }
    }

    function deleteSubtree(iterator) {
        var subIterator;
        while (iterator.next()) {
            if (iterator.isPartiallySelectedSubtree()) {
                subIterator = iterator.getSubtreeIterator();
                deleteSubtree(subIterator);
                subIterator.detach(true);
            } else {
                iterator.remove();
            }
        }
    }

    function extractSubtree(iterator) {

        for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {


            if (iterator.isPartiallySelectedSubtree()) {
                node = node.cloneNode(false);
                subIterator = iterator.getSubtreeIterator();
                node.appendChild(extractSubtree(subIterator));
                subIterator.detach(true);
            } else {
                iterator.remove();
            }
            if (node.nodeType == 10) { // DocumentType
                throw new DOMException("HIERARCHY_REQUEST_ERR");
            }
            frag.appendChild(node);
        }
        return frag;
    }

    function getNodesInRange(range, nodeTypes, filter) {
        //log.info("getNodesInRange, " + nodeTypes.join(","));
        var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;
        var filterExists = !!filter;
        if (filterNodeTypes) {
            regex = new RegExp("^(" + nodeTypes.join("|") + ")$");
        }

        var nodes = [];
        iterateSubtree(new RangeIterator(range, false), function(node) {
            if ((!filterNodeTypes || regex.test(node.nodeType)) && (!filterExists || filter(node))) {
                nodes.push(node);
            }
        });
        return nodes;
    }

    function inspect(range) {
        var name = (typeof range.getName == "undefined") ? "Range" : range.getName();
        return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " +
                dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]";
    }

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

    // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)

    /**
     * @constructor
     */
    function RangeIterator(range, clonePartiallySelectedTextNodes) {
        this.range = range;
        this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;



        if (!range.collapsed) {
            this.sc = range.startContainer;
            this.so = range.startOffset;
            this.ec = range.endContainer;
            this.eo = range.endOffset;
            var root = range.commonAncestorContainer;

            if (this.sc === this.ec && dom.isCharacterDataNode(this.sc)) {
                this.isSingleCharacterDataNode = true;
                this._first = this._last = this._next = this.sc;
            } else {
                this._first = this._next = (this.sc === root && !dom.isCharacterDataNode(this.sc)) ?
                    this.sc.childNodes[this.so] : dom.getClosestAncestorIn(this.sc, root, true);
                this._last = (this.ec === root && !dom.isCharacterDataNode(this.ec)) ?
                    this.ec.childNodes[this.eo - 1] : dom.getClosestAncestorIn(this.ec, root, true);
            }

        }
    }

    RangeIterator.prototype = {
        _current: null,
        _next: null,
        _first: null,
        _last: null,
        isSingleCharacterDataNode: false,

        reset: function() {
            this._current = null;
            this._next = this._first;
        },

        hasNext: function() {
            return !!this._next;
        },

        next: function() {
            // Move to next node
            var current = this._current = this._next;
            if (current) {
                this._next = (current !== this._last) ? current.nextSibling : null;

                // Check for partially selected text nodes
                if (dom.isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {
                    if (current === this.ec) {

                        (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);
                    }
                    if (this._current === this.sc) {

                        (current = current.cloneNode(true)).deleteData(0, this.so);
                    }
                }
            }

            return current;
        },

        remove: function() {
            var current = this._current, start, end;

            if (dom.isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {
                start = (current === this.sc) ? this.so : 0;
                end = (current === this.ec) ? this.eo : current.length;
                if (start != end) {
                    current.deleteData(start, end - start);
                }
            } else {
                if (current.parentNode) {
                    current.parentNode.removeChild(current);
                } else {

                }
            }
        },

        // Checks if the current node is partially selected
        isPartiallySelectedSubtree: function() {
            var current = this._current;
            return isNonTextPartiallySelected(current, this.range);
        },

        getSubtreeIterator: function() {
            var subRange;
            if (this.isSingleCharacterDataNode) {
                subRange = this.range.cloneRange();
                subRange.collapse();
            } else {
                subRange = new Range(getRangeDocument(this.range));
                var current = this._current;
                var startContainer = current, startOffset = 0, endContainer = current, endOffset = dom.getNodeLength(current);

                if (dom.isAncestorOf(current, this.sc, true)) {
                    startContainer = this.sc;
                    startOffset = this.so;
                }
                if (dom.isAncestorOf(current, this.ec, true)) {
                    endContainer = this.ec;
                    endOffset = this.eo;
                }

                updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);
            }
            return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);
        },

        detach: function(detachRange) {
            if (detachRange) {
                this.range.detach();
            }
            this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;
        }
    };

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

    // Exceptions

    /**
     * @constructor
     */
    function RangeException(codeName) {
        this.code = this[codeName];
        this.codeName = codeName;
        this.message = "RangeException: " + this.codeName;
    }

    RangeException.prototype = {
        BAD_BOUNDARYPOINTS_ERR: 1,
        INVALID_NODE_TYPE_ERR: 2
    };

    RangeException.prototype.toString = function() {
        return this.message;
    };

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

    /**
     * Currently iterates through all nodes in the range on creation until I think of a decent way to do it
     * TODO: Look into making this a proper iterator, not requiring preloading everything first
     * @constructor
     */
    function RangeNodeIterator(range, nodeTypes, filter) {
        this.nodes = getNodesInRange(range, nodeTypes, filter);
        this._next = this.nodes[0];
        this._position = 0;
    }

    RangeNodeIterator.prototype = {
        _current: null,

        hasNext: function() {
            return !!this._next;
        },

        next: function() {
            this._current = this._next;
            this._next = this.nodes[ ++this._position ];
            return this._current;
        },

        detach: function() {
            this._current = this._next = this.nodes = null;
        }
    };

    var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];
    var rootContainerNodeTypes = [2, 9, 11];
    var readonlyNodeTypes = [5, 6, 10, 12];
    var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];
    var surroundNodeTypes = [1, 3, 4, 5, 7, 8];

    function createAncestorFinder(nodeTypes) {
        return function(node, selfIsAncestor) {
            var t, n = selfIsAncestor ? node : node.parentNode;
            while (n) {
                t = n.nodeType;
                if (dom.arrayContains(nodeTypes, t)) {
                    return n;
                }
                n = n.parentNode;
            }
            return null;
        };
    }

    var getRootContainer = dom.getRootContainer;
    var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );
    var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);
    var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );

    function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {
        if (getDocTypeNotationEntityAncestor(node, allowSelf)) {
            throw new RangeException("INVALID_NODE_TYPE_ERR");
        }
    }

    function assertNotDetached(range) {
        if (!range.startContainer) {
            throw new DOMException("INVALID_STATE_ERR");
        }
    }

    function assertValidNodeType(node, invalidTypes) {
        if (!dom.arrayContains(invalidTypes, node.nodeType)) {
            throw new RangeException("INVALID_NODE_TYPE_ERR");
        }
    }

    function assertValidOffset(node, offset) {
        if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) {
            throw new DOMException("INDEX_SIZE_ERR");
        }
    }

    function assertSameDocumentOrFragment(node1, node2) {
        if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {
            throw new DOMException("WRONG_DOCUMENT_ERR");
        }
    }

    function assertNodeNotReadOnly(node) {
        if (getReadonlyAncestor(node, true)) {
            throw new DOMException("NO_MODIFICATION_ALLOWED_ERR");
        }
    }

    function assertNode(node, codeName) {
        if (!node) {
            throw new DOMException(codeName);
        }
    }

    function isOrphan(node) {
        return !dom.arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true);
    }

    function isValidOffset(node, offset) {
        return offset <= (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length);
    }

    function assertRangeValid(range) {
        assertNotDetached(range);
        if (isOrphan(range.startContainer) || isOrphan(range.endContainer) ||
                !isValidOffset(range.startContainer, range.startOffset) ||
                !isValidOffset(range.endContainer, range.endOffset)) {
            throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")");
        }
    }

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

    // Test the browser's innerHTML support to decide how to implement createContextualFragment
    var styleEl = document.createElement("style");
    var htmlParsingConforms = false;
    try {
        styleEl.innerHTML = "<b>x</b>";
        htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node
    } catch (e) {
        // IE 6 and 7 throw
    }

    api.features.htmlParsingConforms = htmlParsingConforms;

    var createContextualFragment = htmlParsingConforms ?

        // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See
        // discussion and base code for this implementation at issue 67.
        // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface
        // Thanks to Aleks Williams.
        function(fragmentStr) {
            // "Let node the context object's start's node."
            var node = this.startContainer;
            var doc = dom.getDocument(node);

            // "If the context object's start's node is null, raise an INVALID_STATE_ERR
            // exception and abort these steps."
            if (!node) {
                throw new DOMException("INVALID_STATE_ERR");
            }

            // "Let element be as follows, depending on node's interface:"
            // Document, Document Fragment: null
            var el = null;

            // "Element: node"
            if (node.nodeType == 1) {
                el = node;

            // "Text, Comment: node's parentElement"
            } else if (dom.isCharacterDataNode(node)) {
                el = dom.parentElement(node);
            }

            // "If either element is null or element's ownerDocument is an HTML document
            // and element's local name is "html" and element's namespace is the HTML
            // namespace"
            if (el === null || (
                el.nodeName == "HTML"
                && dom.isHtmlNamespace(dom.getDocument(el).documentElement)
                && dom.isHtmlNamespace(el)
            )) {

            // "let element be a new Element with "body" as its local name and the HTML
            // namespace as its namespace.""
                el = doc.createElement("body");
            } else {
                el = el.cloneNode(false);
            }

            // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm."
            // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm."
            // "In either case, the algorithm must be invoked with fragment as the input
            // and element as the context element."
            el.innerHTML = fragmentStr;

            // "If this raises an exception, then abort these steps. Otherwise, let new
            // children be the nodes returned."

            // "Let fragment be a new DocumentFragment."
            // "Append all new children to fragment."
            // "Return fragment."
            return dom.fragmentFromNodeChildren(el);
        } :

        // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that
        // previous versions of Rangy used (with the exception of using a body element rather than a div)
        function(fragmentStr) {
            assertNotDetached(this);
            var doc = getRangeDocument(this);
            var el = doc.createElement("body");
            el.innerHTML = fragmentStr;

            return dom.fragmentFromNodeChildren(el);
        };

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

    var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
        "commonAncestorContainer"];

    var s2s = 0, s2e = 1, e2e = 2, e2s = 3;
    var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;

    function RangePrototype() {}

    RangePrototype.prototype = {
        attachListener: function(type, listener) {
            this._listeners[type].push(listener);
        },

        compareBoundaryPoints: function(how, range) {
            assertRangeValid(this);
            assertSameDocumentOrFragment(this.startContainer, range.startContainer);

            var nodeA, offsetA, nodeB, offsetB;
            var prefixA = (how == e2s || how == s2s) ? "start" : "end";
            var prefixB = (how == s2e || how == s2s) ? "start" : "end";
            nodeA = this[prefixA + "Container"];
            offsetA = this[prefixA + "Offset"];
            nodeB = range[prefixB + "Container"];
            offsetB = range[prefixB + "Offset"];
            return dom.comparePoints(nodeA, offsetA, nodeB, offsetB);
        },

        insertNode: function(node) {
            assertRangeValid(this);
            assertValidNodeType(node, insertableNodeTypes);
            assertNodeNotReadOnly(this.startContainer);

            if (dom.isAncestorOf(node, this.startContainer, true)) {
                throw new DOMException("HIERARCHY_REQUEST_ERR");
            }

            // No check for whether the container of the start of the Range is of a type that does not allow
            // children of the type of node: the browser's DOM implementation should do this for us when we attempt
            // to add the node

            var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);
            this.setStartBefore(firstNodeInserted);
        },

        cloneContents: function() {
            assertRangeValid(this);

            var clone, frag;
            if (this.collapsed) {
                return getRangeDocument(this).createDocumentFragment();
            } else {
                if (this.startContainer === this.endContainer && dom.isCharacterDataNode(this.startContainer)) {
                    clone = this.startContainer.cloneNode(true);
                    clone.data = clone.data.slice(this.startOffset, this.endOffset);
                    frag = getRangeDocument(this).createDocumentFragment();
                    frag.appendChild(clone);
                    return frag;
                } else {
                    var iterator = new RangeIterator(this, true);
                    clone = cloneSubtree(iterator);
                    iterator.detach();
                }
                return clone;
            }
        },

        canSurroundContents: function() {
            assertRangeValid(this);
            assertNodeNotReadOnly(this.startContainer);
            assertNodeNotReadOnly(this.endContainer);

            // Check if the contents can be surrounded. Specifically, this means whether the range partially selects
            // no non-text nodes.
            var iterator = new RangeIterator(this, true);
            var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
                    (iterator._last && isNonTextPartiallySelected(iterator._last, this)));
            iterator.detach();
            return !boundariesInvalid;
        },

        surroundContents: function(node) {
            assertValidNodeType(node, surroundNodeTypes);

            if (!this.canSurroundContents()) {
                throw new RangeException("BAD_BOUNDARYPOINTS_ERR");
            }

            // Extract the contents
            var content = this.extractContents();

            // Clear the children of the node
            if (node.hasChildNodes()) {
                while (node.lastChild) {
                    node.removeChild(node.lastChild);
                }
            }

            // Insert the new node and add the extracted contents
            insertNodeAtPosition(node, this.startContainer, this.startOffset);
            node.appendChild(content);

            this.selectNode(node);
        },

        cloneRange: function() {
            assertRangeValid(this);
            var range = new Range(getRangeDocument(this));
            var i = rangeProperties.length, prop;
            while (i--) {
                prop = rangeProperties[i];
                range[prop] = this[prop];
            }
            return range;
        },

        toString: function() {
            assertRangeValid(this);
            var sc = this.startContainer;
            if (sc === this.endContainer && dom.isCharacterDataNode(sc)) {
                return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : "";
            } else {
                var textBits = [], iterator = new RangeIterator(this, true);

                iterateSubtree(iterator, function(node) {
                    // Accept only text or CDATA nodes, not comments

                    if (node.nodeType == 3 || node.nodeType == 4) {
                        textBits.push(node.data);
                    }
                });
                iterator.detach();
                return textBits.join("");
            }
        },

        // The methods below are all non-standard. The following batch were introduced by Mozilla but have since
        // been removed from Mozilla.

        compareNode: function(node) {
            assertRangeValid(this);

            var parent = node.parentNode;
            var nodeIndex = dom.getNodeIndex(node);

            if (!parent) {
                throw new DOMException("NOT_FOUND_ERR");
            }

            var startComparison = this.comparePoint(parent, nodeIndex),
                endComparison = this.comparePoint(parent, nodeIndex + 1);

            if (startComparison < 0) { // Node starts before
                return (endComparison > 0) ? n_b_a : n_b;
            } else {
                return (endComparison > 0) ? n_a : n_i;
            }
        },

        comparePoint: function(node, offset) {
            assertRangeValid(this);
            assertNode(node, "HIERARCHY_REQUEST_ERR");
            assertSameDocumentOrFragment(node, this.startContainer);

            if (dom.comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {
                return -1;
            } else if (dom.comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {
                return 1;
            }
            return 0;
        },

        createContextualFragment: createContextualFragment,

        toHtml: function() {
            assertRangeValid(this);
            var container = getRangeDocument(this).createElement("div");
            container.appendChild(this.cloneContents());
            return container.innerHTML;
        },

        // touchingIsIntersecting determines whether this method considers a node that borders a range intersects
        // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)
        intersectsNode: function(node, touchingIsIntersecting) {
            assertRangeValid(this);
            assertNode(node, "NOT_FOUND_ERR");
            if (dom.getDocument(node) !== getRangeDocument(this)) {
                return false;
            }

            var parent = node.parentNode, offset = dom.getNodeIndex(node);
            assertNode(parent, "NOT_FOUND_ERR");

            var startComparison = dom.comparePoints(parent, offset, this.endContainer, this.endOffset),
                endComparison = dom.comparePoints(parent, offset + 1, this.startContainer, this.startOffset);

            return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
        },


        isPointInRange: function(node, offset) {
            assertRangeValid(this);
            assertNode(node, "HIERARCHY_REQUEST_ERR");
            assertSameDocumentOrFragment(node, this.startContainer);

            return (dom.comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&
                   (dom.comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);
        },

        // The methods below are non-standard and invented by me.

        // Sharing a boundary start-to-end or end-to-start does not count as intersection.
        intersectsRange: function(range, touchingIsIntersecting) {
            assertRangeValid(this);

            if (getRangeDocument(range) != getRangeDocument(this)) {
                throw new DOMException("WRONG_DOCUMENT_ERR");
            }

            var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.endContainer, range.endOffset),
                endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.startContainer, range.startOffset);

            return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
        },

        intersection: function(range) {
            if (this.intersectsRange(range)) {
                var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),
                    endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);

                var intersectionRange = this.cloneRange();

                if (startComparison == -1) {
                    intersectionRange.setStart(range.startContainer, range.startOffset);
                }
                if (endComparison == 1) {
                    intersectionRange.setEnd(range.endContainer, range.endOffset);
                }
                return intersectionRange;
            }
            return null;
        },

        union: function(range) {
            if (this.intersectsRange(range, true)) {
                var unionRange = this.cloneRange();
                if (dom.comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {
                    unionRange.setStart(range.startContainer, range.startOffset);
                }
                if (dom.comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {
                    unionRange.setEnd(range.endContainer, range.endOffset);
                }
                return unionRange;
            } else {
                throw new RangeException("Ranges do not intersect");
            }
        },

        containsNode: function(node, allowPartial) {
            if (allowPartial) {
                return this.intersectsNode(node, false);
            } else {
                return this.compareNode(node) == n_i;
            }
        },

        containsNodeContents: function(node) {
            return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, dom.getNodeLength(node)) <= 0;
        },

        containsRange: function(range) {
            return this.intersection(range).equals(range);
        },

        containsNodeText: function(node) {
            var nodeRange = this.cloneRange();
            nodeRange.selectNode(node);
            var textNodes = nodeRange.getNodes([3]);
            if (textNodes.length > 0) {
                nodeRange.setStart(textNodes[0], 0);
                var lastTextNode = textNodes.pop();
                nodeRange.setEnd(lastTextNode, lastTextNode.length);
                var contains = this.containsRange(nodeRange);
                nodeRange.detach();
                return contains;
            } else {
                return this.containsNodeContents(node);
            }
        },

        createNodeIterator: function(nodeTypes, filter) {
            assertRangeValid(this);
            return new RangeNodeIterator(this, nodeTypes, filter);
        },

        getNodes: function(nodeTypes, filter) {
            assertRangeValid(this);
            return getNodesInRange(this, nodeTypes, filter);
        },

        getDocument: function() {
            return getRangeDocument(this);
        },

        collapseBefore: function(node) {
            assertNotDetached(this);

            this.setEndBefore(node);
            this.collapse(false);
        },

        collapseAfter: function(node) {
            assertNotDetached(this);

            this.setStartAfter(node);
            this.collapse(true);
        },

        getName: function() {
            return "DomRange";
        },

        equals: function(range) {
            return Range.rangesEqual(this, range);
        },

        inspect: function() {
            return inspect(this);
        }
    };

    function copyComparisonConstantsToObject(obj) {
        obj.START_TO_START = s2s;
        obj.START_TO_END = s2e;
        obj.END_TO_END = e2e;
        obj.END_TO_START = e2s;

        obj.NODE_BEFORE = n_b;
        obj.NODE_AFTER = n_a;
        obj.NODE_BEFORE_AND_AFTER = n_b_a;
        obj.NODE_INSIDE = n_i;
    }

    function copyComparisonConstants(constructor) {
        copyComparisonConstantsToObject(constructor);
        copyComparisonConstantsToObject(constructor.prototype);
    }

    function createRangeContentRemover(remover, boundaryUpdater) {
        return function() {
            assertRangeValid(this);

            var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;

            var iterator = new RangeIterator(this, true);

            // Work out where to position the range after content removal
            var node, boundary;
            if (sc !== root) {
                node = dom.getClosestAncestorIn(sc, root, true);
                boundary = getBoundaryAfterNode(node);
                sc = boundary.node;
                so = boundary.offset;
            }

            // Check none of the range is read-only
            iterateSubtree(iterator, assertNodeNotReadOnly);

            iterator.reset();

            // Remove the content
            var returnValue = remover(iterator);
            iterator.detach();

            // Move to the new position
            boundaryUpdater(this, sc, so, sc, so);

            return returnValue;
        };
    }

    function createPrototypeRange(constructor, boundaryUpdater, detacher) {
        function createBeforeAfterNodeSetter(isBefore, isStart) {
            return function(node) {
                assertNotDetached(this);
                assertValidNodeType(node, beforeAfterNodeTypes);
                assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);

                var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);
                (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);
            };
        }

        function setRangeStart(range, node, offset) {
            var ec = range.endContainer, eo = range.endOffset;
            if (node !== range.startContainer || offset !== range.startOffset) {
                // Check the root containers of the range and the new boundary, and also check whether the new boundary
                // is after the current end. In either case, collapse the range to the new position
                if (getRootContainer(node) != getRootContainer(ec) || dom.comparePoints(node, offset, ec, eo) == 1) {
                    ec = node;
                    eo = offset;
                }
                boundaryUpdater(range, node, offset, ec, eo);
            }
        }

        function setRangeEnd(range, node, offset) {
            var sc = range.startContainer, so = range.startOffset;
            if (node !== range.endContainer || offset !== range.endOffset) {
                // Check the root containers of the range and the new boundary, and also check whether the new boundary
                // is after the current end. In either case, collapse the range to the new position
                if (getRootContainer(node) != getRootContainer(sc) || dom.comparePoints(node, offset, sc, so) == -1) {
                    sc = node;
                    so = offset;
                }
                boundaryUpdater(range, sc, so, node, offset);
            }
        }

        function setRangeStartAndEnd(range, node, offset) {
            if (node !== range.startContainer || offset !== range.startOffset || node !== range.endContainer || offset !== range.endOffset) {
                boundaryUpdater(range, node, offset, node, offset);
            }
        }

        constructor.prototype = new RangePrototype();

        api.util.extend(constructor.prototype, {
            setStart: function(node, offset) {
                assertNotDetached(this);
                assertNoDocTypeNotationEntityAncestor(node, true);
                assertValidOffset(node, offset);

                setRangeStart(this, node, offset);
            },

            setEnd: function(node, offset) {
                assertNotDetached(this);
                assertNoDocTypeNotationEntityAncestor(node, true);
                assertValidOffset(node, offset);

                setRangeEnd(this, node, offset);
            },

            setStartBefore: createBeforeAfterNodeSetter(true, true),
            setStartAfter: createBeforeAfterNodeSetter(false, true),
            setEndBefore: createBeforeAfterNodeSetter(true, false),
            setEndAfter: createBeforeAfterNodeSetter(false, false),

            collapse: function(isStart) {
                assertRangeValid(this);
                if (isStart) {
                    boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);
                } else {
                    boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);
                }
            },

            selectNodeContents: function(node) {
                // This doesn't seem well specified: the spec talks only about selecting the node's contents, which
                // could be taken to mean only its children. However, browsers implement this the same as selectNode for
                // text nodes, so I shall do likewise
                assertNotDetached(this);
                assertNoDocTypeNotationEntityAncestor(node, true);

                boundaryUpdater(this, node, 0, node, dom.getNodeLength(node));
            },

            selectNode: function(node) {
                assertNotDetached(this);
                assertNoDocTypeNotationEntityAncestor(node, false);
                assertValidNodeType(node, beforeAfterNodeTypes);

                var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);
                boundaryUpdater(this, start.node, start.offset, end.node, end.offset);
            },

            extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),

            deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),

            canSurroundContents: function() {
                assertRangeValid(this);
                assertNodeNotReadOnly(this.startContainer);
                assertNodeNotReadOnly(this.endContainer);

                // Check if the contents can be surrounded. Specifically, this means whether the range partially selects
                // no non-text nodes.
                var iterator = new RangeIterator(this, true);
                var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
                        (iterator._last && isNonTextPartiallySelected(iterator._last, this)));
                iterator.detach();
                return !boundariesInvalid;
            },

            detach: function() {
                detacher(this);
            },

            splitBoundaries: function() {
                assertRangeValid(this);


                var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
                var startEndSame = (sc === ec);

                if (dom.isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {
                    dom.splitDataNode(ec, eo);

                }

                if (dom.isCharacterDataNode(sc) && so > 0 && so < sc.length) {

                    sc = dom.splitDataNode(sc, so);
                    if (startEndSame) {
                        eo -= so;
                        ec = sc;
                    } else if (ec == sc.parentNode && eo >= dom.getNodeIndex(sc)) {
                        eo++;
                    }
                    so = 0;

                }
                boundaryUpdater(this, sc, so, ec, eo);
            },

            normalizeBoundaries: function() {
                assertRangeValid(this);

                var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;

                var mergeForward = function(node) {
                    var sibling = node.nextSibling;
                    if (sibling && sibling.nodeType == node.nodeType) {
                        ec = node;
                        eo = node.length;
                        node.appendData(sibling.data);
                        sibling.parentNode.removeChild(sibling);
                    }
                };

                var mergeBackward = function(node) {
                    var sibling = node.previousSibling;
                    if (sibling && sibling.nodeType == node.nodeType) {
                        sc = node;
                        var nodeLength = node.length;
                        so = sibling.length;
                        node.insertData(0, sibling.data);
                        sibling.parentNode.removeChild(sibling);
                        if (sc == ec) {
                            eo += so;
                            ec = sc;
                        } else if (ec == node.parentNode) {
                            var nodeIndex = dom.getNodeIndex(node);
                            if (eo == nodeIndex) {
                                ec = node;
                                eo = nodeLength;
                            } else if (eo > nodeIndex) {
                                eo--;
                            }
                        }
                    }
                };

                var normalizeStart = true;

                if (dom.isCharacterDataNode(ec)) {
                    if (ec.length == eo) {
                        mergeForward(ec);
                    }
                } else {
                    if (eo > 0) {
                        var endNode = ec.childNodes[eo - 1];
                        if (endNode && dom.isCharacterDataNode(endNode)) {
                            mergeForward(endNode);
                        }
                    }
                    normalizeStart = !this.collapsed;
                }

                if (normalizeStart) {
                    if (dom.isCharacterDataNode(sc)) {
                        if (so == 0) {
                            mergeBackward(sc);
                        }
                    } else {
                        if (so < sc.childNodes.length) {
                            var startNode = sc.childNodes[so];
                            if (startNode && dom.isCharacterDataNode(startNode)) {
                                mergeBackward(startNode);
                            }
                        }
                    }
                } else {
                    sc = ec;
                    so = eo;
                }

                boundaryUpdater(this, sc, so, ec, eo);
            },

            collapseToPoint: function(node, offset) {
                assertNotDetached(this);

                assertNoDocTypeNotationEntityAncestor(node, true);
                assertValidOffset(node, offset);

                setRangeStartAndEnd(this, node, offset);
            }
        });

        copyComparisonConstants(constructor);
    }

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

    // Updates commonAncestorContainer and collapsed after boundary change
    function updateCollapsedAndCommonAncestor(range) {
        range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
        range.commonAncestorContainer = range.collapsed ?
            range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);
    }

    function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {
        var startMoved = (range.startContainer !== startContainer || range.startOffset !== startOffset);
        var endMoved = (range.endContainer !== endContainer || range.endOffset !== endOffset);

        range.startContainer = startContainer;
        range.startOffset = startOffset;
        range.endContainer = endContainer;
        range.endOffset = endOffset;

        updateCollapsedAndCommonAncestor(range);
        dispatchEvent(range, "boundarychange", {startMoved: startMoved, endMoved: endMoved});
    }

    function detach(range) {
        assertNotDetached(range);
        range.startContainer = range.startOffset = range.endContainer = range.endOffset = null;
        range.collapsed = range.commonAncestorContainer = null;
        dispatchEvent(range, "detach", null);
        range._listeners = null;
    }

    /**
     * @constructor
     */
    function Range(doc) {
        this.startContainer = doc;
        this.startOffset = 0;
        this.endContainer = doc;
        this.endOffset = 0;
        this._listeners = {
            boundarychange: [],
            detach: []
        };
        updateCollapsedAndCommonAncestor(this);
    }

    createPrototypeRange(Range, updateBoundaries, detach);

    api.rangePrototype = RangePrototype.prototype;

    Range.rangeProperties = rangeProperties;
    Range.RangeIterator = RangeIterator;
    Range.copyComparisonConstants = copyComparisonConstants;
    Range.createPrototypeRange = createPrototypeRange;
    Range.inspect = inspect;
    Range.getRangeDocument = getRangeDocument;
    Range.rangesEqual = function(r1, r2) {
        return r1.startContainer === r2.startContainer &&
               r1.startOffset === r2.startOffset &&
               r1.endContainer === r2.endContainer &&
               r1.endOffset === r2.endOffset;
    };

    api.DomRange = Range;
    api.RangeException = RangeException;
});rangy.createModule("WrappedRange", function(api, module) {
    api.requireModules( ["DomUtil", "DomRange"] );

    /**
     * @constructor
     */
    var WrappedRange;
    var dom = api.dom;
    var DomPosition = dom.DomPosition;
    var DomRange = api.DomRange;



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

    /*
    This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()
    method. For example, in the following (where pipes denote the selection boundaries):

    <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul>

    var range = document.selection.createRange();
    alert(range.parentElement().id); // Should alert "ul" but alerts "b"

    This method returns the common ancestor node of the following:
    - the parentElement() of the textRange
    - the parentElement() of the textRange after calling collapse(true)
    - the parentElement() of the textRange after calling collapse(false)
     */
    function getTextRangeContainerElement(textRange) {
        var parentEl = textRange.parentElement();

        var range = textRange.duplicate();
        range.collapse(true);
        var startEl = range.parentElement();
        range = textRange.duplicate();
        range.collapse(false);
        var endEl = range.parentElement();
        var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);

        return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);
    }

    function textRangeIsCollapsed(textRange) {
        return textRange.compareEndPoints("StartToEnd", textRange) == 0;
    }

    // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started out as
    // an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) but has
    // grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange bugs, handling
    // for inputs and images, plus optimizations.
    function getTextRangeBoundaryPosition(textRange, wholeRangeContainerElement, isStart, isCollapsed) {
        var workingRange = textRange.duplicate();

        workingRange.collapse(isStart);
        var containerElement = workingRange.parentElement();

        // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so
        // check for that
        // TODO: Find out when. Workaround for wholeRangeContainerElement may break this
        if (!dom.isAncestorOf(wholeRangeContainerElement, containerElement, true)) {
            containerElement = wholeRangeContainerElement;

        }



        // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and
        // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx
        if (!containerElement.canHaveHTML) {
            return new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));
        }

        var workingNode = dom.getDocument(containerElement).createElement("span");
        var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd";
        var previousNode, nextNode, boundaryPosition, boundaryNode;

        // Move the working range through the container's children, starting at the end and working backwards, until the
        // working range reaches or goes past the boundary we're interested in
        do {
            containerElement.insertBefore(workingNode, workingNode.previousSibling);
            workingRange.moveToElementText(workingNode);
        } while ( (comparison = workingRange.compareEndPoints(workingComparisonType, textRange)) > 0 &&
                workingNode.previousSibling);

        // We've now reached or gone past the boundary of the text range we're interested in
        // so have identified the node we want
        boundaryNode = workingNode.nextSibling;

        if (comparison == -1 && boundaryNode && dom.isCharacterDataNode(boundaryNode)) {
            // This is a character data node (text, comment, cdata). The working range is collapsed at the start of the
            // node containing the text range's boundary, so we move the end of the working range to the boundary point
            // and measure the length of its text to get the boundary's offset within the node.
            workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange);


            var offset;

            if (/[\r\n]/.test(boundaryNode.data)) {
                /*
                For the particular case of a boundary within a text node containing line breaks (within a <pre> element,
                for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts:

                - Each line break is represented as \r in the text node's data/nodeValue properties
                - Each line break is represented as \r\n in the TextRange's 'text' property
                - The 'text' property of the TextRange does not contain trailing line breaks

                To get round the problem presented by the final fact above, we can use the fact that TextRange's
                moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily
                the same as the number of characters it was instructed to move. The simplest approach is to use this to
                store the characters moved when moving both the start and end of the range to the start of the document
                body and subtracting the start offset from the end offset (the "move-negative-gazillion" method).
                However, this is extremely slow when the document is large and the range is near the end of it. Clearly
                doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same
                problem.

                Another approach that works is to use moveStart() to move the start boundary of the range up to the end
                boundary one character at a time and incrementing a counter with the value returned by the moveStart()
                call. However, the check for whether the start boundary has reached the end boundary is expensive, so
                this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of
                the range within the document).

                The method below is a hybrid of the two methods above. It uses the fact that a string containing the
                TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the
                text of the TextRange, so the start of the range is moved that length initially and then a character at
                a time to make up for any trailing line breaks not contained in the 'text' property. This has good
                performance in most situations compared to the previous two methods.
                */
                var tempRange = workingRange.duplicate();
                var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length;

                offset = tempRange.moveStart("character", rangeLength);
                while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) {
                    offset++;
                    tempRange.moveStart("character", 1);
                }
            } else {
                offset = workingRange.text.length;
            }
            boundaryPosition = new DomPosition(boundaryNode, offset);
        } else {


            // If the boundary immediately follows a character data node and this is the end boundary, we should favour
            // a position within that, and likewise for a start boundary preceding a character data node
            previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;
            nextNode = (isCollapsed || isStart) && workingNode.nextSibling;



            if (nextNode && dom.isCharacterDataNode(nextNode)) {
                boundaryPosition = new DomPosition(nextNode, 0);
            } else if (previousNode && dom.isCharacterDataNode(previousNode)) {
                boundaryPosition = new DomPosition(previousNode, previousNode.length);
            } else {
                boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));
            }
        }

        // Clean up
        workingNode.parentNode.removeChild(workingNode);

        return boundaryPosition;
    }

    // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that node.
    // This function started out as an optimized version of code found in Tim Cameron Ryan's IERange
    // (http://code.google.com/p/ierange/)
    function createBoundaryTextRange(boundaryPosition, isStart) {
        var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;
        var doc = dom.getDocument(boundaryPosition.node);
        var workingNode, childNodes, workingRange = doc.body.createTextRange();
        var nodeIsDataNode = dom.isCharacterDataNode(boundaryPosition.node);

        if (nodeIsDataNode) {
            boundaryNode = boundaryPosition.node;
            boundaryParent = boundaryNode.parentNode;
        } else {
            childNodes = boundaryPosition.node.childNodes;
            boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;
            boundaryParent = boundaryPosition.node;
        }

        // Position the range immediately before the node containing the boundary
        workingNode = doc.createElement("span");

        // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within the
        // element rather than immediately before or after it, which is what we want
        workingNode.innerHTML = "&#feff;";

        // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report
        // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12
        if (boundaryNode) {
            boundaryParent.insertBefore(workingNode, boundaryNode);
        } else {
            boundaryParent.appendChild(workingNode);
        }

        workingRange.moveToElementText(workingNode);
        workingRange.collapse(!isStart);

        // Clean up
        boundaryParent.removeChild(workingNode);

        // Move the working range to the text offset, if required
        if (nodeIsDataNode) {
            workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset);
        }

        return workingRange;
    }

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

    if (api.features.implementsDomRange && (!api.features.implementsTextRange || !api.config.preferTextRange)) {
        // This is a wrapper around the browser's native DOM Range. It has two aims:
        // - Provide workarounds for specific browser bugs
        // - provide convenient extensions, which are inherited from Rangy's DomRange

        (function() {
            var rangeProto;
            var rangeProperties = DomRange.rangeProperties;
            var canSetRangeStartAfterEnd;

            function updateRangeProperties(range) {
                var i = rangeProperties.length, prop;
                while (i--) {
                    prop = rangeProperties[i];
                    range[prop] = range.nativeRange[prop];
                }
            }

            function updateNativeRange(range, startContainer, startOffset, endContainer,endOffset) {
                var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);
                var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);

                // Always set both boundaries for the benefit of IE9 (see issue 35)
                if (startMoved || endMoved) {
                    range.setEnd(endContainer, endOffset);
                    range.setStart(startContainer, startOffset);
                }
            }

            function detach(range) {
                range.nativeRange.detach();
                range.detached = true;
                var i = rangeProperties.length, prop;
                while (i--) {
                    prop = rangeProperties[i];
                    range[prop] = null;
                }
            }

            var createBeforeAfterNodeSetter;

            WrappedRange = function(range) {
                if (!range) {
                    throw new Error("Range must be specified");
                }
                this.nativeRange = range;
                updateRangeProperties(this);
            };

            DomRange.createPrototypeRange(WrappedRange, updateNativeRange, detach);

            rangeProto = WrappedRange.prototype;

            rangeProto.selectNode = function(node) {
                this.nativeRange.selectNode(node);
                updateRangeProperties(this);
            };

            rangeProto.deleteContents = function() {
                this.nativeRange.deleteContents();
                updateRangeProperties(this);
            };

            rangeProto.extractContents = function() {
                var frag = this.nativeRange.extractContents();
                updateRangeProperties(this);
                return frag;
            };

            rangeProto.cloneContents = function() {
                return this.nativeRange.cloneContents();
            };

            // TODO: Until I can find a way to programmatically trigger the Firefox bug (apparently long-standing, still
            // present in 3.6.8) that throws "Index or size is negative or greater than the allowed amount" for
            // insertNode in some circumstances, all browsers will have to use the Rangy's own implementation of
            // insertNode, which works but is almost certainly slower than the native implementation.
/*
            rangeProto.insertNode = function(node) {
                this.nativeRange.insertNode(node);
                updateRangeProperties(this);
            };
*/

            rangeProto.surroundContents = function(node) {
                this.nativeRange.surroundContents(node);
                updateRangeProperties(this);
            };

            rangeProto.collapse = function(isStart) {
                this.nativeRange.collapse(isStart);
                updateRangeProperties(this);
            };

            rangeProto.cloneRange = function() {
                return new WrappedRange(this.nativeRange.cloneRange());
            };

            rangeProto.refresh = function() {
                updateRangeProperties(this);
            };

            rangeProto.toString = function() {
                return this.nativeRange.toString();
            };

            // Create test range and node for feature detection

            var testTextNode = document.createTextNode("test");
            dom.getBody(document).appendChild(testTextNode);
            var range = document.createRange();

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

            // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and
            // correct for it

            range.setStart(testTextNode, 0);
            range.setEnd(testTextNode, 0);

            try {
                range.setStart(testTextNode, 1);
                canSetRangeStartAfterEnd = true;

                rangeProto.setStart = function(node, offset) {
                    this.nativeRange.setStart(node, offset);
                    updateRangeProperties(this);
                };

                rangeProto.setEnd = function(node, offset) {
                    this.nativeRange.setEnd(node, offset);
                    updateRangeProperties(this);
                };

                createBeforeAfterNodeSetter = function(name) {
                    return function(node) {
                        this.nativeRange[name](node);
                        updateRangeProperties(this);
                    };
                };

            } catch(ex) {


                canSetRangeStartAfterEnd = false;

                rangeProto.setStart = function(node, offset) {
                    try {
                        this.nativeRange.setStart(node, offset);
                    } catch (ex) {
                        this.nativeRange.setEnd(node, offset);
                        this.nativeRange.setStart(node, offset);
                    }
                    updateRangeProperties(this);
                };

                rangeProto.setEnd = function(node, offset) {
                    try {
                        this.nativeRange.setEnd(node, offset);
                    } catch (ex) {
                        this.nativeRange.setStart(node, offset);
                        this.nativeRange.setEnd(node, offset);
                    }
                    updateRangeProperties(this);
                };

                createBeforeAfterNodeSetter = function(name, oppositeName) {
                    return function(node) {
                        try {
                            this.nativeRange[name](node);
                        } catch (ex) {
                            this.nativeRange[oppositeName](node);
                            this.nativeRange[name](node);
                        }
                        updateRangeProperties(this);
                    };
                };
            }

            rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore");
            rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter");
            rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore");
            rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter");

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

            // Test for and correct Firefox 2 behaviour with selectNodeContents on text nodes: it collapses the range to
            // the 0th character of the text node
            range.selectNodeContents(testTextNode);
            if (range.startContainer == testTextNode && range.endContainer == testTextNode &&
                    range.startOffset == 0 && range.endOffset == testTextNode.length) {
                rangeProto.selectNodeContents = function(node) {
                    this.nativeRange.selectNodeContents(node);
                    updateRangeProperties(this);
                };
            } else {
                rangeProto.selectNodeContents = function(node) {
                    this.setStart(node, 0);
                    this.setEnd(node, DomRange.getEndOffset(node));
                };
            }

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

            // Test for WebKit bug that has the beahviour of compareBoundaryPoints round the wrong way for constants
            // START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738

            range.selectNodeContents(testTextNode);
            range.setEnd(testTextNode, 3);

            var range2 = document.createRange();
            range2.selectNodeContents(testTextNode);
            range2.setEnd(testTextNode, 4);
            range2.setStart(testTextNode, 2);

            if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &
                    range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {
                // This is the wrong way round, so correct for it


                rangeProto.compareBoundaryPoints = function(type, range) {
                    range = range.nativeRange || range;
                    if (type == range.START_TO_END) {
                        type = range.END_TO_START;
                    } else if (type == range.END_TO_START) {
                        type = range.START_TO_END;
                    }
                    return this.nativeRange.compareBoundaryPoints(type, range);
                };
            } else {
                rangeProto.compareBoundaryPoints = function(type, range) {
                    return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);
                };
            }

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

            // Test for existence of createContextualFragment and delegate to it if it exists
            if (api.util.isHostMethod(range, "createContextualFragment")) {
                rangeProto.createContextualFragment = function(fragmentStr) {
                    return this.nativeRange.createContextualFragment(fragmentStr);
                };
            }

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

            // Clean up
            dom.getBody(document).removeChild(testTextNode);
            range.detach();
            range2.detach();
        })();

        api.createNativeRange = function(doc) {
            doc = doc || document;
            return doc.createRange();
        };
    } else if (api.features.implementsTextRange) {
        // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a
        // prototype

        WrappedRange = function(textRange) {
            this.textRange = textRange;
            this.refresh();
        };

        WrappedRange.prototype = new DomRange(document);

        WrappedRange.prototype.refresh = function() {
            var start, end;

            // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.
            var rangeContainerElement = getTextRangeContainerElement(this.textRange);

            if (textRangeIsCollapsed(this.textRange)) {
                end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true);
            } else {

                start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);
                end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false);
            }

            this.setStart(start.node, start.offset);
            this.setEnd(end.node, end.offset);
        };

        DomRange.copyComparisonConstants(WrappedRange);

        // Add WrappedRange as the Range property of the global object to allow expression like Range.END_TO_END to work
        var globalObj = (function() { return this; })();
        if (typeof globalObj.Range == "undefined") {
            globalObj.Range = WrappedRange;
        }

        api.createNativeRange = function(doc) {
            doc = doc || document;
            return doc.body.createTextRange();
        };
    }

    if (api.features.implementsTextRange) {
        WrappedRange.rangeToTextRange = function(range) {
            if (range.collapsed) {
                var tr = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);



                return tr;

                //return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
            } else {
                var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
                var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);
                var textRange = dom.getDocument(range.startContainer).body.createTextRange();
                textRange.setEndPoint("StartToStart", startRange);
                textRange.setEndPoint("EndToEnd", endRange);
                return textRange;
            }
        };
    }

    WrappedRange.prototype.getName = function() {
        return "WrappedRange";
    };

    api.WrappedRange = WrappedRange;

    api.createRange = function(doc) {
        doc = doc || document;
        return new WrappedRange(api.createNativeRange(doc));
    };

    api.createRangyRange = function(doc) {
        doc = doc || document;
        return new DomRange(doc);
    };

    api.createIframeRange = function(iframeEl) {
        return api.createRange(dom.getIframeDocument(iframeEl));
    };

    api.createIframeRangyRange = function(iframeEl) {
        return api.createRangyRange(dom.getIframeDocument(iframeEl));
    };

    api.addCreateMissingNativeApiListener(function(win) {
        var doc = win.document;
        if (typeof doc.createRange == "undefined") {
            doc.createRange = function() {
                return api.createRange(this);
            };
        }
        doc = win = null;
    });
});rangy.createModule("WrappedSelection", function(api, module) {
    // This will create a selection object wrapper that follows the Selection object found in the WHATWG draft DOM Range
    // spec (http://html5.org/specs/dom-range.html)

    api.requireModules( ["DomUtil", "DomRange", "WrappedRange"] );

    api.config.checkSelectionRanges = true;

    var BOOLEAN = "boolean",
        windowPropertyName = "_rangySelection",
        dom = api.dom,
        util = api.util,
        DomRange = api.DomRange,
        WrappedRange = api.WrappedRange,
        DOMException = api.DOMException,
        DomPosition = dom.DomPosition,
        getSelection,
        selectionIsCollapsed,
        CONTROL = "Control";



    function getWinSelection(winParam) {
        return (winParam || window).getSelection();
    }

    function getDocSelection(winParam) {
        return (winParam || window).document.selection;
    }

    // Test for the Range/TextRange and Selection features required
    // Test for ability to retrieve selection
    var implementsWinGetSelection = api.util.isHostMethod(window, "getSelection"),
        implementsDocSelection = api.util.isHostObject(document, "selection");

    var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);

    if (useDocumentSelection) {
        getSelection = getDocSelection;
        api.isSelectionValid = function(winParam) {
            var doc = (winParam || window).document, nativeSel = doc.selection;

            // Check whether the selection TextRange is actually contained within the correct document
            return (nativeSel.type != "None" || dom.getDocument(nativeSel.createRange().parentElement()) == doc);
        };
    } else if (implementsWinGetSelection) {
        getSelection = getWinSelection;
        api.isSelectionValid = function() {
            return true;
        };
    } else {
        module.fail("Neither document.selection or window.getSelection() detected.");
    }

    api.getNativeSelection = getSelection;

    var testSelection = getSelection();
    var testRange = api.createNativeRange(document);
    var body = dom.getBody(document);

    // Obtaining a range from a selection
    var selectionHasAnchorAndFocus = util.areHostObjects(testSelection, ["anchorNode", "focusNode"] &&
                                     util.areHostProperties(testSelection, ["anchorOffset", "focusOffset"]));
    api.features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;

    // Test for existence of native selection extend() method
    var selectionHasExtend = util.isHostMethod(testSelection, "extend");
    api.features.selectionHasExtend = selectionHasExtend;

    // Test if rangeCount exists
    var selectionHasRangeCount = (typeof testSelection.rangeCount == "number");
    api.features.selectionHasRangeCount = selectionHasRangeCount;

    var selectionSupportsMultipleRanges = false;
    var collapsedNonEditableSelectionsSupported = true;

    if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) &&
            typeof testSelection.rangeCount == "number" && api.features.implementsDomRange) {

        (function() {
            var iframe = document.createElement("iframe");
            body.appendChild(iframe);

            var iframeDoc = dom.getIframeDocument(iframe);
            iframeDoc.open();
            iframeDoc.write("<html><head></head><body>12</body></html>");
            iframeDoc.close();

            var sel = dom.getIframeWindow(iframe).getSelection();
            var docEl = iframeDoc.documentElement;
            var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild;

            // Test whether the native selection will allow a collapsed selection within a non-editable element
            var r1 = iframeDoc.createRange();
            r1.setStart(textNode, 1);
            r1.collapse(true);
            sel.addRange(r1);
            collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
            sel.removeAllRanges();

            // Test whether the native selection is capable of supporting multiple ranges
            var r2 = r1.cloneRange();
            r1.setStart(textNode, 0);
            r2.setEnd(textNode, 2);
            sel.addRange(r1);
            sel.addRange(r2);

            selectionSupportsMultipleRanges = (sel.rangeCount == 2);

            // Clean up
            r1.detach();
            r2.detach();

            body.removeChild(iframe);
        })();
    }

    api.features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;
    api.features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;

    // ControlRanges
    var implementsControlRange = false, testControlRange;

    if (body && util.isHostMethod(body, "createControlRange")) {
        testControlRange = body.createControlRange();
        if (util.areHostProperties(testControlRange, ["item", "add"])) {
            implementsControlRange = true;
        }
    }
    api.features.implementsControlRange = implementsControlRange;

    // Selection collapsedness
    if (selectionHasAnchorAndFocus) {
        selectionIsCollapsed = function(sel) {
            return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;
        };
    } else {
        selectionIsCollapsed = function(sel) {
            return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;
        };
    }

    function updateAnchorAndFocusFromRange(sel, range, backwards) {
        var anchorPrefix = backwards ? "end" : "start", focusPrefix = backwards ? "start" : "end";
        sel.anchorNode = range[anchorPrefix + "Container"];
        sel.anchorOffset = range[anchorPrefix + "Offset"];
        sel.focusNode = range[focusPrefix + "Container"];
        sel.focusOffset = range[focusPrefix + "Offset"];
    }

    function updateAnchorAndFocusFromNativeSelection(sel) {
        var nativeSel = sel.nativeSelection;
        sel.anchorNode = nativeSel.anchorNode;
        sel.anchorOffset = nativeSel.anchorOffset;
        sel.focusNode = nativeSel.focusNode;
        sel.focusOffset = nativeSel.focusOffset;
    }

    function updateEmptySelection(sel) {
        sel.anchorNode = sel.focusNode = null;
        sel.anchorOffset = sel.focusOffset = 0;
        sel.rangeCount = 0;
        sel.isCollapsed = true;
        sel._ranges.length = 0;
    }

    function getNativeRange(range) {
        var nativeRange;
        if (range instanceof DomRange) {
            nativeRange = range._selectionNativeRange;
            if (!nativeRange) {
                nativeRange = api.createNativeRange(dom.getDocument(range.startContainer));
                nativeRange.setEnd(range.endContainer, range.endOffset);
                nativeRange.setStart(range.startContainer, range.startOffset);
                range._selectionNativeRange = nativeRange;
                range.attachListener("detach", function() {

                    this._selectionNativeRange = null;
                });
            }
        } else if (range instanceof WrappedRange) {
            nativeRange = range.nativeRange;
        } else if (api.features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {
            nativeRange = range;
        }
        return nativeRange;
    }

    function rangeContainsSingleElement(rangeNodes) {
        if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {
            return false;
        }
        for (var i = 1, len = rangeNodes.length; i < len; ++i) {
            if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {
                return false;
            }
        }
        return true;
    }

    function getSingleElementFromRange(range) {
        var nodes = range.getNodes();
        if (!rangeContainsSingleElement(nodes)) {
            throw new Error("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element");
        }
        return nodes[0];
    }

    function isTextRange(range) {
        return !!range && typeof range.text != "undefined";
    }

    function updateFromTextRange(sel, range) {
        // Create a Range from the selected TextRange
        var wrappedRange = new WrappedRange(range);
        sel._ranges = [wrappedRange];

        updateAnchorAndFocusFromRange(sel, wrappedRange, false);
        sel.rangeCount = 1;
        sel.isCollapsed = wrappedRange.collapsed;
    }

    function updateControlSelection(sel) {
        // Update the wrapped selection based on what's now in the native selection
        sel._ranges.length = 0;
        if (sel.docSelection.type == "None") {
            updateEmptySelection(sel);
        } else {
            var controlRange = sel.docSelection.createRange();
            if (isTextRange(controlRange)) {
                // This case (where the selection type is "Control" and calling createRange() on the selection returns
                // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected
                // ControlRange have been removed from the ControlRange and removed from the document.
                updateFromTextRange(sel, controlRange);
            } else {
                sel.rangeCount = controlRange.length;
                var range, doc = dom.getDocument(controlRange.item(0));
                for (var i = 0; i < sel.rangeCount; ++i) {
                    range = api.createRange(doc);
                    range.selectNode(controlRange.item(i));
                    sel._ranges.push(range);
                }
                sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;
                updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);
            }
        }
    }

    function addRangeToControlSelection(sel, range) {
        var controlRange = sel.docSelection.createRange();
        var rangeElement = getSingleElementFromRange(range);

        // Create a new ControlRange containing all the elements in the selected ControlRange plus the element
        // contained by the supplied range
        var doc = dom.getDocument(controlRange.item(0));
        var newControlRange = dom.getBody(doc).createControlRange();
        for (var i = 0, len = controlRange.length; i < len; ++i) {
            newControlRange.add(controlRange.item(i));
        }
        try {
            newControlRange.add(rangeElement);
        } catch (ex) {
            throw new Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)");
        }
        newControlRange.select();

        // Update the wrapped selection based on what's now in the native selection
        updateControlSelection(sel);
    }

    var getSelectionRangeAt;

    if (util.isHostMethod(testSelection,  "getRangeAt")) {
        getSelectionRangeAt = function(sel, index) {
            try {
                return sel.getRangeAt(index);
            } catch(ex) {
                return null;
            }
        };
    } else if (selectionHasAnchorAndFocus) {
        getSelectionRangeAt = function(sel) {
            var doc = dom.getDocument(sel.anchorNode);
            var range = api.createRange(doc);
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);

            // Handle the case when the selection was selected backwards (from the end to the start in the
            // document)
            if (range.collapsed !== this.isCollapsed) {
                range.setStart(sel.focusNode, sel.focusOffset);
                range.setEnd(sel.anchorNode, sel.anchorOffset);
            }

            return range;
        };
    }

    /**
     * @constructor
     */
    function WrappedSelection(selection, docSelection, win) {
        this.nativeSelection = selection;
        this.docSelection = docSelection;
        this._ranges = [];
        this.win = win;
        this.refresh();
    }

    api.getSelection = function(win) {
        win = win || window;
        var sel = win[windowPropertyName];
        var nativeSel = getSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;
        if (sel) {
            sel.nativeSelection = nativeSel;
            sel.docSelection = docSel;
            sel.refresh(win);
        } else {
            sel = new WrappedSelection(nativeSel, docSel, win);
            win[windowPropertyName] = sel;
        }
        return sel;
    };

    api.getIframeSelection = function(iframeEl) {
        return api.getSelection(dom.getIframeWindow(iframeEl));
    };

    var selProto = WrappedSelection.prototype;

    function createControlSelection(sel, ranges) {
        // Ensure that the selection becomes of type "Control"
        var doc = dom.getDocument(ranges[0].startContainer);
        var controlRange = dom.getBody(doc).createControlRange();
        for (var i = 0, el; i < rangeCount; ++i) {
            el = getSingleElementFromRange(ranges[i]);
            try {
                controlRange.add(el);
            } catch (ex) {
                throw new Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)");
            }
        }
        controlRange.select();

        // Update the wrapped selection based on what's now in the native selection
        updateControlSelection(sel);
    }

    // Selecting a range
    if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) {
        selProto.removeAllRanges = function() {
            this.nativeSelection.removeAllRanges();
            updateEmptySelection(this);
        };

        var addRangeBackwards = function(sel, range) {
            var doc = DomRange.getRangeDocument(range);
            var endRange = api.createRange(doc);
            endRange.collapseToPoint(range.endContainer, range.endOffset);
            sel.nativeSelection.addRange(getNativeRange(endRange));
            sel.nativeSelection.extend(range.startContainer, range.startOffset);
            sel.refresh();
        };

        if (selectionHasRangeCount) {
            selProto.addRange = function(range, backwards) {
                if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
                    addRangeToControlSelection(this, range);
                } else {
                    if (backwards && selectionHasExtend) {
                        addRangeBackwards(this, range);
                    } else {
                        var previousRangeCount;
                        if (selectionSupportsMultipleRanges) {
                            previousRangeCount = this.rangeCount;
                        } else {
                            this.removeAllRanges();
                            previousRangeCount = 0;
                        }
                        this.nativeSelection.addRange(getNativeRange(range));

                        // Check whether adding the range was successful
                        this.rangeCount = this.nativeSelection.rangeCount;

                        if (this.rangeCount == previousRangeCount + 1) {
                            // The range was added successfully

                            // Check whether the range that we added to the selection is reflected in the last range extracted from
                            // the selection
                            if (api.config.checkSelectionRanges) {
                                var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);
                                if (nativeRange && !DomRange.rangesEqual(nativeRange, range)) {
                                    // Happens in WebKit with, for example, a selection placed at the start of a text node
                                    range = new WrappedRange(nativeRange);
                                }
                            }
                            this._ranges[this.rangeCount - 1] = range;
                            updateAnchorAndFocusFromRange(this, range, selectionIsBackwards(this.nativeSelection));
                            this.isCollapsed = selectionIsCollapsed(this);
                        } else {
                            // The range was not added successfully. The simplest thing is to refresh
                            this.refresh();
                        }
                    }
                }
            };
        } else {
            selProto.addRange = function(range, backwards) {
                if (backwards && selectionHasExtend) {
                    addRangeBackwards(this, range);
                } else {
                    this.nativeSelection.addRange(getNativeRange(range));
                    this.refresh();
                }
            };
        }

        selProto.setRanges = function(ranges) {
            if (implementsControlRange && ranges.length > 1) {
                createControlSelection(this, ranges);
            } else {
                this.removeAllRanges();
                for (var i = 0, len = ranges.length; i < len; ++i) {
                    this.addRange(ranges[i]);
                }
            }
        };
    } else if (util.isHostMethod(testSelection, "empty") && util.isHostMethod(testRange, "select") &&
               implementsControlRange && useDocumentSelection) {

        selProto.removeAllRanges = function() {
            // Added try/catch as fix for issue #21
            try {
                this.docSelection.empty();

                // Check for empty() not working (issue #24)
                if (this.docSelection.type != "None") {
                    // Work around failure to empty a control selection by instead selecting a TextRange and then
                    // calling empty()
                    var doc;
                    if (this.anchorNode) {
                        doc = dom.getDocument(this.anchorNode);
                    } else if (this.docSelection.type == CONTROL) {
                        var controlRange = this.docSelection.createRange();
                        if (controlRange.length) {
                            doc = dom.getDocument(controlRange.item(0)).body.createTextRange();
                        }
                    }
                    if (doc) {
                        var textRange = doc.body.createTextRange();
                        textRange.select();
                        this.docSelection.empty();
                    }
                }
            } catch(ex) {}
            updateEmptySelection(this);
        };

        selProto.addRange = function(range) {
            if (this.docSelection.type == CONTROL) {
                addRangeToControlSelection(this, range);
            } else {
                WrappedRange.rangeToTextRange(range).select();
                this._ranges[0] = range;
                this.rangeCount = 1;
                this.isCollapsed = this._ranges[0].collapsed;
                updateAnchorAndFocusFromRange(this, range, false);
            }
        };

        selProto.setRanges = function(ranges) {
            this.removeAllRanges();
            var rangeCount = ranges.length;
            if (rangeCount > 1) {
                createControlSelection(this, ranges);
            } else if (rangeCount) {
                this.addRange(ranges[0]);
            }
        };
    } else {
        module.fail("No means of selecting a Range or TextRange was found");
        return false;
    }

    selProto.getRangeAt = function(index) {
        if (index < 0 || index >= this.rangeCount) {
            throw new DOMException("INDEX_SIZE_ERR");
        } else {
            return this._ranges[index];
        }
    };

    var refreshSelection;

    if (useDocumentSelection) {
        refreshSelection = function(sel) {
            var range;
            if (api.isSelectionValid(sel.win)) {
                range = sel.docSelection.createRange();
            } else {
                range = dom.getBody(sel.win.document).createTextRange();
                range.collapse(true);
            }


            if (sel.docSelection.type == CONTROL) {
                updateControlSelection(sel);
            } else if (isTextRange(range)) {
                updateFromTextRange(sel, range);
            } else {
                updateEmptySelection(sel);
            }
        };
    } else if (util.isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == "number") {
        refreshSelection = function(sel) {
            if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {
                updateControlSelection(sel);
            } else {
                sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;
                if (sel.rangeCount) {
                    for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                        sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));
                    }
                    updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackwards(sel.nativeSelection));
                    sel.isCollapsed = selectionIsCollapsed(sel);
                } else {
                    updateEmptySelection(sel);
                }
            }
        };
    } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && api.features.implementsDomRange) {
        refreshSelection = function(sel) {
            var range, nativeSel = sel.nativeSelection;
            if (nativeSel.anchorNode) {
                range = getSelectionRangeAt(nativeSel, 0);
                sel._ranges = [range];
                sel.rangeCount = 1;
                updateAnchorAndFocusFromNativeSelection(sel);
                sel.isCollapsed = selectionIsCollapsed(sel);
            } else {
                updateEmptySelection(sel);
            }
        };
    } else {
        module.fail("No means of obtaining a Range or TextRange from the user's selection was found");
        return false;
    }

    selProto.refresh = function(checkForChanges) {
        var oldRanges = checkForChanges ? this._ranges.slice(0) : null;
        refreshSelection(this);
        if (checkForChanges) {
            var i = oldRanges.length;
            if (i != this._ranges.length) {
                return false;
            }
            while (i--) {
                if (!DomRange.rangesEqual(oldRanges[i], this._ranges[i])) {
                    return false;
                }
            }
            return true;
        }
    };

    // Removal of a single range
    var removeRangeManually = function(sel, range) {
        var ranges = sel.getAllRanges(), removed = false;
        sel.removeAllRanges();
        for (var i = 0, len = ranges.length; i < len; ++i) {
            if (removed || range !== ranges[i]) {
                sel.addRange(ranges[i]);
            } else {
                // According to the draft WHATWG Range spec, the same range may be added to the selection multiple
                // times. removeRange should only remove the first instance, so the following ensures only the first
                // instance is removed
                removed = true;
            }
        }
        if (!sel.rangeCount) {
            updateEmptySelection(sel);
        }
    };

    if (implementsControlRange) {
        selProto.removeRange = function(range) {
            if (this.docSelection.type == CONTROL) {
                var controlRange = this.docSelection.createRange();
                var rangeElement = getSingleElementFromRange(range);

                // Create a new ControlRange containing all the elements in the selected ControlRange minus the
                // element contained by the supplied range
                var doc = dom.getDocument(controlRange.item(0));
                var newControlRange = dom.getBody(doc).createControlRange();
                var el, removed = false;
                for (var i = 0, len = controlRange.length; i < len; ++i) {
                    el = controlRange.item(i);
                    if (el !== rangeElement || removed) {
                        newControlRange.add(controlRange.item(i));
                    } else {
                        removed = true;
                    }
                }
                newControlRange.select();

                // Update the wrapped selection based on what's now in the native selection
                updateControlSelection(this);
            } else {
                removeRangeManually(this, range);
            }
        };
    } else {
        selProto.removeRange = function(range) {
            removeRangeManually(this, range);
        };
    }

    // Detecting if a selection is backwards
    var selectionIsBackwards;
    if (!useDocumentSelection && selectionHasAnchorAndFocus && api.features.implementsDomRange) {
        selectionIsBackwards = function(sel) {
            var backwards = false;
            if (sel.anchorNode) {
                backwards = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);
            }
            return backwards;
        };

        selProto.isBackwards = function() {
            return selectionIsBackwards(this);
        };
    } else {
        selectionIsBackwards = selProto.isBackwards = function() {
            return false;
        };
    }

    // Selection text
    // This is conformant to the new WHATWG DOM Range draft spec but differs from WebKit and Mozilla's implementation
    selProto.toString = function() {

        var rangeTexts = [];
        for (var i = 0, len = this.rangeCount; i < len; ++i) {
            rangeTexts[i] = "" + this._ranges[i];
        }
        return rangeTexts.join("");
    };

    function assertNodeInSameDocument(sel, node) {
        if (sel.anchorNode && (dom.getDocument(sel.anchorNode) !== dom.getDocument(node))) {
            throw new DOMException("WRONG_DOCUMENT_ERR");
        }
    }

    // No current browsers conform fully to the HTML 5 draft spec for this method, so Rangy's own method is always used
    selProto.collapse = function(node, offset) {
        assertNodeInSameDocument(this, node);
        var range = api.createRange(dom.getDocument(node));
        range.collapseToPoint(node, offset);
        this.removeAllRanges();
        this.addRange(range);
        this.isCollapsed = true;
    };

    selProto.collapseToStart = function() {
        if (this.rangeCount) {
            var range = this._ranges[0];
            this.collapse(range.startContainer, range.startOffset);
        } else {
            throw new DOMException("INVALID_STATE_ERR");
        }
    };

    selProto.collapseToEnd = function() {
        if (this.rangeCount) {
            var range = this._ranges[this.rangeCount - 1];
            this.collapse(range.endContainer, range.endOffset);
        } else {
            throw new DOMException("INVALID_STATE_ERR");
        }
    };

    // The HTML 5 spec is very specific on how selectAllChildren should be implemented so the native implementation is
    // never used by Rangy.
    selProto.selectAllChildren = function(node) {
        assertNodeInSameDocument(this, node);
        var range = api.createRange(dom.getDocument(node));
        range.selectNodeContents(node);
        this.removeAllRanges();
        this.addRange(range);
    };

    selProto.deleteFromDocument = function() {
        // Sepcial behaviour required for Control selections
        if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
            var controlRange = this.docSelection.createRange();
            var element;
            while (controlRange.length) {
                element = controlRange.item(0);
                controlRange.remove(element);
                element.parentNode.removeChild(element);
            }
            this.refresh();
        } else if (this.rangeCount) {
            var ranges = this.getAllRanges();
            this.removeAllRanges();
            for (var i = 0, len = ranges.length; i < len; ++i) {
                ranges[i].deleteContents();
            }
            // The HTML5 spec says nothing about what the selection should contain after calling deleteContents on each
            // range. Firefox moves the selection to where the final selected range was, so we emulate that
            this.addRange(ranges[len - 1]);
        }
    };

    // The following are non-standard extensions
    selProto.getAllRanges = function() {
        return this._ranges.slice(0);
    };

    selProto.setSingleRange = function(range) {
        this.setRanges( [range] );
    };

    selProto.containsNode = function(node, allowPartial) {
        for (var i = 0, len = this._ranges.length; i < len; ++i) {
            if (this._ranges[i].containsNode(node, allowPartial)) {
                return true;
            }
        }
        return false;
    };

    selProto.toHtml = function() {
        var html = "";
        if (this.rangeCount) {
            var container = DomRange.getRangeDocument(this._ranges[0]).createElement("div");
            for (var i = 0, len = this._ranges.length; i < len; ++i) {
                container.appendChild(this._ranges[i].cloneContents());
            }
            html = container.innerHTML;
        }
        return html;
    };

    function inspect(sel) {
        var rangeInspects = [];
        var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);
        var focus = new DomPosition(sel.focusNode, sel.focusOffset);
        var name = (typeof sel.getName == "function") ? sel.getName() : "Selection";

        if (typeof sel.rangeCount != "undefined") {
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));
            }
        }
        return "[" + name + "(Ranges: " + rangeInspects.join(", ") +
                ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]";

    }

    selProto.getName = function() {
        return "WrappedSelection";
    };

    selProto.inspect = function() {
        return inspect(this);
    };

    selProto.detach = function() {
        this.win[windowPropertyName] = null;
        this.win = this.anchorNode = this.focusNode = null;
    };

    WrappedSelection.inspect = inspect;

    api.Selection = WrappedSelection;

    api.selectionPrototype = selProto;

    api.addCreateMissingNativeApiListener(function(win) {
        if (typeof win.getSelection == "undefined") {
            win.getSelection = function() {
                return api.getSelection(this);
            };
        }
        win = null;
    });
});

/**
 * @license Selection save and restore module for Rangy.
 * Saves and restores user selections using marker invisible elements in the DOM.
 *
 * Part of Rangy, a cross-browser JavaScript range and selection library
 * http://code.google.com/p/rangy/
 *
 * Depends on Rangy core.
 *
 * Copyright 2011, Tim Down
 * Licensed under the MIT license.
 * Version: 1.2.2
 * Build date: 13 November 2011
 */
rangy.createModule("SaveRestore", function(api, module) {
    api.requireModules( ["DomUtil", "DomRange", "WrappedRange"] );

    var dom = api.dom;

    var markerTextChar = "\ufeff";

    function gEBI(id, doc) {
        return (doc || document).getElementById(id);
    }

    function insertRangeBoundaryMarker(range, atStart) {
        var markerId = "selectionBoundary_" + (+new Date()) + "_" + ("" + Math.random()).slice(2);
        var markerEl;
        var doc = dom.getDocument(range.startContainer);

        // Clone the Range and collapse to the appropriate boundary point
        var boundaryRange = range.cloneRange();
        boundaryRange.collapse(atStart);

        // Create the marker element containing a single invisible character using DOM methods and insert it
        markerEl = doc.createElement("span");
        markerEl.id = markerId;
        markerEl.style.lineHeight = "0";
        markerEl.style.display = "none";
        markerEl.className = "rangySelectionBoundary";
        markerEl.appendChild(doc.createTextNode(markerTextChar));

        boundaryRange.insertNode(markerEl);
        boundaryRange.detach();
        return markerEl;
    }

    function setRangeBoundary(doc, range, markerId, atStart) {
        var markerEl = gEBI(markerId, doc);
        if (markerEl) {
            range[atStart ? "setStartBefore" : "setEndBefore"](markerEl);
            markerEl.parentNode.removeChild(markerEl);
        } else {
            module.warn("Marker element has been removed. Cannot restore selection.");
        }
    }

    function compareRanges(r1, r2) {
        return r2.compareBoundaryPoints(r1.START_TO_START, r1);
    }

    function saveSelection(win) {
        win = win || window;
        var doc = win.document;
        if (!api.isSelectionValid(win)) {
            module.warn("Cannot save selection. This usually happens when the selection is collapsed and the selection document has lost focus.");
            return;
        }
        var sel = api.getSelection(win);
        var ranges = sel.getAllRanges();
        var rangeInfos = [], startEl, endEl, range;

        // Order the ranges by position within the DOM, latest first
        ranges.sort(compareRanges);

        for (var i = 0, len = ranges.length; i < len; ++i) {
            range = ranges[i];
            if (range.collapsed) {
                endEl = insertRangeBoundaryMarker(range, false);
                rangeInfos.push({
                    markerId: endEl.id,
                    collapsed: true
                });
            } else {
                endEl = insertRangeBoundaryMarker(range, false);
                startEl = insertRangeBoundaryMarker(range, true);

                rangeInfos[i] = {
                    startMarkerId: startEl.id,
                    endMarkerId: endEl.id,
                    collapsed: false,
                    backwards: ranges.length == 1 && sel.isBackwards()
                };
            }
        }

        // Now that all the markers are in place and DOM manipulation over, adjust each range's boundaries to lie
        // between its markers
        for (i = len - 1; i >= 0; --i) {
            range = ranges[i];
            if (range.collapsed) {
                range.collapseBefore(gEBI(rangeInfos[i].markerId, doc));
            } else {
                range.setEndBefore(gEBI(rangeInfos[i].endMarkerId, doc));
                range.setStartAfter(gEBI(rangeInfos[i].startMarkerId, doc));
            }
        }

        // Ensure current selection is unaffected
        sel.setRanges(ranges);
        return {
            win: win,
            doc: doc,
            rangeInfos: rangeInfos,
            restored: false
        };
    }

    function restoreSelection(savedSelection, preserveDirection) {
        if (!savedSelection.restored) {
            var rangeInfos = savedSelection.rangeInfos;
            var sel = api.getSelection(savedSelection.win);
            var ranges = [];

            // Ranges are in reverse order of appearance in the DOM. We want to restore earliest first to avoid
            // normalization affecting previously restored ranges.
            for (var len = rangeInfos.length, i = len - 1, rangeInfo, range; i >= 0; --i) {
                rangeInfo = rangeInfos[i];
                range = api.createRange(savedSelection.doc);
                if (rangeInfo.collapsed) {
                    var markerEl = gEBI(rangeInfo.markerId, savedSelection.doc);
                    if (markerEl) {
                        markerEl.style.display = "inline";
                        var previousNode = markerEl.previousSibling;

                        // Workaround for issue 17
                        if (previousNode && previousNode.nodeType == 3) {
                            markerEl.parentNode.removeChild(markerEl);
                            range.collapseToPoint(previousNode, previousNode.length);
                        } else {
                            range.collapseBefore(markerEl);
                            markerEl.parentNode.removeChild(markerEl);
                        }
                    } else {
                        module.warn("Marker element has been removed. Cannot restore selection.");
                    }
                } else {
                    setRangeBoundary(savedSelection.doc, range, rangeInfo.startMarkerId, true);
                    setRangeBoundary(savedSelection.doc, range, rangeInfo.endMarkerId, false);
                }

                // Normalizing range boundaries is only viable if the selection contains only one range. For example,
                // if the selection contained two ranges that were both contained within the same single text node,
                // both would alter the same text node when restoring and break the other range.
                if (len == 1) {
                    range.normalizeBoundaries();
                }
                ranges[i] = range;
            }
            if (len == 1 && preserveDirection && api.features.selectionHasExtend && rangeInfos[0].backwards) {
                sel.removeAllRanges();
                sel.addRange(ranges[0], true);
            } else {
                sel.setRanges(ranges);
            }

            savedSelection.restored = true;
        }
    }

    function removeMarkerElement(doc, markerId) {
        var markerEl = gEBI(markerId, doc);
        if (markerEl) {
            markerEl.parentNode.removeChild(markerEl);
        }
    }

    function removeMarkers(savedSelection) {
        var rangeInfos = savedSelection.rangeInfos;
        for (var i = 0, len = rangeInfos.length, rangeInfo; i < len; ++i) {
            rangeInfo = rangeInfos[i];
            if (rangeInfo.collapsed) {
                removeMarkerElement(savedSelection.doc, rangeInfo.markerId);
            } else {
                removeMarkerElement(savedSelection.doc, rangeInfo.startMarkerId);
                removeMarkerElement(savedSelection.doc, rangeInfo.endMarkerId);
            }
        }
    }

    api.saveSelection = saveSelection;
    api.restoreSelection = restoreSelection;
    api.removeMarkerElement = removeMarkerElement;
    api.removeMarkers = removeMarkers;
});

/* globals -$ */
"use strict";

WYMeditor.SKINS.compact = {
    init: function(wym) {
        // Move the containers panel to the top area
        jQuery(wym._options.containersSelector + ', ' +
            wym._options.classesSelector, wym._box)
          .appendTo( jQuery("div.wym_area_top", wym._box) )
          .addClass("wym_dropdown")
          .css({"margin-right": "10px", "width": "120px", "float": "left"});

        // Render following sections as buttons
        jQuery(wym._options.toolsSelector, wym._box)
          .addClass("wym_buttons")
          .css({"margin-right": "10px", "float": "left"});

        // Make hover work under IE < 7
        jQuery(".wym_section", wym._box).hover(function(){
          jQuery(this).addClass("hover");
        },function(){
          jQuery(this).removeClass("hover");
        });

        var postInit = wym._options.postInit;
        wym._options.postInit = function(wym) {
            if (postInit) {
                postInit.call(wym, wym);
            }

            wym.$body().css('background-color', '#f0f0f0');
        };
    }
};

"use strict";

WYMeditor.SKINS['default'] = {
    init: function (wym) {
        //render following sections as panels
        jQuery(wym._box).find(wym._options.classesSelector)
          .addClass("wym_panel");

        //render following sections as buttons
        jQuery(wym._box).find(wym._options.toolsSelector)
          .addClass("wym_buttons");

        //render following sections as dropdown menus
        jQuery(wym._box).find(wym._options.containersSelector)
          .addClass("wym_dropdown")
          .find(WYMeditor.H2)
          .append("<span> ></span>");

        // auto add some margin to the main area sides if left area
        // or right area are not empty (if they contain sections)
        jQuery(wym._box).find("div.wym_area_right ul")
          .parents("div.wym_area_right").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-right": "155px"});

        jQuery(wym._box).find("div.wym_area_left ul")
          .parents("div.wym_area_left").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-left": "155px"});

        //make hover work under IE < 7
        jQuery(wym._box).find(".wym_section").hover(
            function () {
                jQuery(this).addClass("hover");
            },
            function () {
                jQuery(this).removeClass("hover");
            }
        );
    }
};

"use strict";

WYMeditor.SKINS.legacy = {
    init: function (wym) {
        //render following sections as panels
        jQuery(wym._box).find(wym._options.classesSelector)
          .addClass("wym_panel");

        //render following sections as buttons
        jQuery(wym._box).find(wym._options.toolsSelector)
          .addClass("wym_buttons");

        //render following sections as dropdown menus
        jQuery(wym._box).find(wym._options.containersSelector)
          .addClass("wym_dropdown")
          .find(WYMeditor.H2)
          .append("<span> ></span>");

        // auto add some margin to the main area sides if left area
        // or right area are not empty (if they contain sections)
        jQuery(wym._box).find("div.wym_area_right ul")
          .parents("div.wym_area_right").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-right": "155px"});

        jQuery(wym._box).find("div.wym_area_left ul")
          .parents("div.wym_area_left").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-left": "155px"});

        //make hover work under IE < 7
        jQuery(wym._box).find(".wym_section").hover(
            function () {
                jQuery(this).addClass("hover");
            },
            function () {
                jQuery(this).removeClass("hover");
            }
        );
    }
};

jQuery.fn.selectify = function() {
    var $elements = this;
    return $elements.each(function() {
        var element = this;
        jQuery(element).hover(
            function() {
                var element = this;
                jQuery("h2", element).css("background-position", "0px -18px");
                jQuery("ul", element).fadeIn("fast");
            },
            function() {
                var element = this;
                jQuery("h2", element).css("background-position", "");
                jQuery("ul", element).fadeOut("fast");
            }
        );
    });
};

WYMeditor.SKINS.minimal = {
    //placeholder for the skin JS, if needed

    //init the skin
    //wym is the WYMeditor.editor instance
    init: function(wym) {

        //render following sections as dropdown menus
        jQuery(wym._box).find(wym._options.toolsSelector + ', ' + wym._options.containersSelector + ', ' + wym._options.classesSelector)
          .addClass("wym_dropdown")
          .selectify();


    }
};

/* globals -$ */
"use strict";

// Add classes to an element based on its current location relative to top and
// or bottom offsets.
// Useful for affixing an element on the page within a certain vertical range.
// Based largely off of the bootstrap affix plugin
// https://github.com/twbs/bootstrap/blob/master/js/affix.js
(function ($) {
    var Affix = function (element, options) {
        this.options = $.extend({}, $.fn.wymAffix.defaults, options);
        this.$window = $(window);

        this.$window.bind(
            'scroll.affix.data-api',
            $.proxy(this.checkPosition, this)
        );
        this.$window.bind(
            'click.affix.data-api',
            $.proxy(
                function () {
                    setTimeout(
                        $.proxy(this.checkPosition, this),
                        1
                    );
                },
                this
            )
        );
        this.$element = $(element);
        this.checkPosition();
    };

    Affix.prototype.checkPosition = function () {
        var scrollTop = this.$window.scrollTop()
          , offset = this.options.offset
          , offsetBottom = offset.bottom
          , offsetTop = offset.top
          , reset = 'affix affix-top affix-bottom'
          , desiredAffixType
          , isBelowTop = true
          , isAboveBottom = true;

        if (typeof offset !== 'object') {
            offsetBottom = offsetTop = offset;
        }
        if (typeof offsetTop === 'function') {
            offsetTop = offset.top();
        }
        if (typeof offsetBottom === 'function') {
            offsetBottom = offset.bottom();
        }

        if (offsetTop !== null) {
            isBelowTop = scrollTop > offsetTop;
        }
        if (offsetBottom !== null) {
            isAboveBottom = scrollTop + this.$element.height() < offsetBottom;
        }

        if (isBelowTop && isAboveBottom) {
            desiredAffixType = 'affix';
        } else if (isAboveBottom === false) {
            // We're below the bottom offset
            desiredAffixType = 'affix-bottom';
        } else {
            desiredAffixType = 'affix-top';
        }

        if (this.currentAffixType === desiredAffixType) {
            // We're already properly-affixed. No changes required.
            return;
        }

        this.$element.removeClass(reset).addClass(desiredAffixType);

        this.currentAffixType = desiredAffixType;
    };


 /* AFFIX PLUGIN DEFINITION
  * ======================= */

    $.fn.wymAffix = function (option) {
        var $elements = this;
        return $elements.each(function () {
            var element = this,
                $element = $(element)
                , data = $element.data('affix')
                , options = typeof option === 'object' && option;

            if (!data) {
                $element.data(
                    'affix',
                    (data = new Affix(element, options))
                );
            }
            if (typeof option === 'string') {
                data[option]();
            }
        });
    };

    $.fn.wymAffix.Constructor = Affix;

    $.fn.wymAffix.defaults = {
        offset: 0
    };
}(jQuery));

WYMeditor.SKINS.seamless = {
    OPTS: {
        iframeHtml: [""
        , '<div class="wym_iframe wym_section">'
            , '<iframe src="' + WYMeditor.IFRAME_BASE_PATH + 'wymiframe.html" '
                , 'frameborder="0" '
                , 'border="0" '
                , 'scrolling="no" '
                , 'marginheight="0px" '
                , 'marginwidth="0px" '
                , '>'
            , '</iframe>'
        , '</div>'
        ].join(""),
        // After Iframe initialization, check if we're ready to perform the
        // first resize every this many ms
        initIframeCheckFrequency: 50,
        // After load or after images are inserted, check every this many ms to
        // see if they've properly set their height.
        imagesLoadedCheckFrequency: 300,
        // After this many ms, give up on images finishing loading. Some images
        // might never load due to network connectivity or bad links.
        imagesLoadedCheckTimeout: 5000
    },
    init: function (wym) {
        var This = WYMeditor.SKINS.seamless;

        // TODO: Find a unified strategy for dealing with loading polyfills
        // This is a polyfill for old IE
        if (!Date.now) {
            Date.now = function now() {
                return new Date().getTime();
            };
        }

        wym.seamlessSkinOpts = jQuery.extend(
            This.OPTS,
            {
                initialIframeResizeTimer: null,
                resizeAfterImagesLoadTimer: null,
                _imagesLoadedCheckStartedTime: 0,
                minimumHeight: jQuery(wym.element).height()
            }
        );
        This.initUIChrome(wym);

        // The Iframe isn't initialized at this point, so we'll need to wait
        // until it is before attempting to use it.
        jQuery(wym.element).bind(
            WYMeditor.EVENTS.postIframeInitialization,
            This.postIframeInit
        );
    },
    postIframeInit: function (e, wym) {
        var This = WYMeditor.SKINS.seamless;

        // Perform an initial resize, if necessary
        This.resizeIframeOnceBodyExists(wym);

        // Detect possible Block creation so that we can always keep the iframe
        // properly resized and the current container in view
        jQuery(wym.element).bind(
            WYMeditor.EVENTS.postBlockMaybeCreated,
            function () {
                This.resizeAndScrollIfNeeded(wym);
            }
        );
    },
    initUIChrome: function (wym) {
        // Initialize the toolbar and classes/containers selectors

        // The classes and containers sections are dropdowns to the right of
        // the toolbar at the top
        var This = WYMeditor.SKINS.seamless,
            $dropdowns = jQuery(
            [
                wym._options.containersSelector
                , wym._options.classesSelector
            ].join(', '),
            wym._box
        ),
            $toolbar,
            $areaTop;

        $areaTop = jQuery("div.wym_area_top", wym._box);

        $dropdowns.appendTo($areaTop);
        $dropdowns.addClass("wym_dropdown");
        // Make dropdowns also work on click, for mobile devices
        jQuery(".wym_dropdown", wym._box).click(
            function () {
                var dropDown = this;
                jQuery(dropDown).toggleClass("hover");
            }
        );

        // The toolbar uses buttons
        $toolbar = jQuery(wym._options.toolsSelector, wym._box);
        $toolbar.addClass("wym_buttons");

        This.affixTopControls(wym);

    },
    affixTopControls: function (wym) {
        // Affix the top area, which contains the toolbar and containers, to
        // the top of the screen so that we can see it, even if we're scrolled
        // down.
        var $areaTop,
            $offsetWrapper,
            earlyScrollPixels = 5,
            usePlaceholderWidth,
            $placeholder;

        $areaTop = jQuery("div.wym_area_top", wym._box);

        // Use a wrapper so we can keep the toolbar styling consistent
        $offsetWrapper = jQuery(
            '<div class="wym_skin_seamless wym_area_top_wrapper">'
        );
        $areaTop.wrap($offsetWrapper);
        $offsetWrapper = $areaTop.parent();

        // Add another, non-affixed wrapper to stick around and hold vertical
        // space. This avoids the "jump" when the toolbar switches to being
        // affixed
        $offsetWrapper.wrap('<div class="wym_area_top_affix_placeholder">');
        $placeholder = $offsetWrapper.parent();
        $placeholder.height($areaTop.height());

        usePlaceholderWidth = function () {
            // Hard-code the offsetWrapper width so that when this floats to
            // the top, it doesn't expand to take up all of the room to the
            // right
            $offsetWrapper.width($placeholder.width());
        };
        usePlaceholderWidth();
        jQuery(window).resize(usePlaceholderWidth);

        $offsetWrapper.wymAffix({
            offset: {
                top: function () {
                    return $placeholder.offset().top - earlyScrollPixels;
                },
                bottom: function () {
                    return $placeholder.offset().top +
                        wym.seamlessSkinIframeHeight;
                }
            }
        });
    },
    resizeIframeOnceBodyExists: function (wym) {
        // In IE, the wym._doc DOMLoaded event doesn't mean the iframe will
        // actually have a body. We need to wait until the body actually exists
        // before trying to set the initial hight of the iframe, so we hack
        // this together with setTimeout.
        var This = WYMeditor.SKINS.seamless,
            scrollHeightCalcFix;

        if (wym.seamlessSkinOpts.initialIframeResizeTimer) {
            // We're handling a timer, clear it
            window.clearTimeout(
                wym.seamlessSkinOpts.initialIframeResizeTimer
            );
            wym.seamlessSkinOpts.initialIframeResizeTimer = null;
        }

        if (typeof wym._doc.body === "undefined" || wym._doc.body === null) {
            // Body isn't ready
            wym.seamlessSkinOpts.initialIframeResizeTimer = window.setTimeout(
                function () {
                    This.resizeIframeOnceBodyExists(wym);
                },
                wym.seamlessSkinOpts.initIframeCheckFrequency
            );
            return;
        }
        // The body is ready, so let's get to resizing
        // For some reason, at least IE7 requires at least one access to the
        // scrollHeight before it gives a real value. I was unable to find any
        // kind of feature detection that would work here and the fix of adding
        // an extra access here doesn't have any real negative impact on the
        // other browsers, but does fix IE7's behavior.
        scrollHeightCalcFix = wym._doc.body.scrollHeight;
        This.resizeIframe(wym);
        This.resizeIframeOnceImagesLoaded(wym);
    },
    resizeIframeOnceImagesLoaded: function (wym) {
        // Even though the body may be "loaded" from a DOM even standpoint,
        // that doesn't mean that images have yet been retrieved or that their
        // heights have been determined. If an image's height pops in after
        // we've calculated the iframe height, the iframe will be too short.
        var This = WYMeditor.SKINS.seamless,
            images,
            imagesLength,
            i = 0,
            allImagesLoaded = true,
            skinOpts = wym.seamlessSkinOpts,
            timeWaited;

        if (typeof skinOpts._imagesLoadedCheckStartedTime === "undefined" ||
                skinOpts._imagesLoadedCheckStartedTime === 0) {
            skinOpts._imagesLoadedCheckStartedTime = Date.now();
        }

        if (skinOpts.resizeAfterImagesLoadTimer !== null) {
            // We're handling a timer, clear it
            window.clearTimeout(
                skinOpts.resizeAfterImagesLoadTimer
            );
            skinOpts.resizeAfterImagesLoadTimer = null;
        }

        images = wym.$body().find('img');
        imagesLength = images.length;

        if (imagesLength === 0) {
            // No images. No need to worry about resizing based on them.
            return;
        }

        for (i = 0; i < imagesLength; i += 1) {
            if (!This._imageIsLoaded(images[i])) {
                // If any image isn't loaded, we're not done
                allImagesLoaded = false;
                break;
            }
        }
        // Even if all of the images haven't loaded, we can still be more
        // correct by accounting for any that have.
        This.resizeAndScrollIfNeeded(wym);

        if (allImagesLoaded === true) {
            // Clean up the timeout timer for subsequent calls
            skinOpts._imagesLoadedCheckStartedTime = 0;
            return;
        }

        timeWaited = Date.now() - skinOpts._imagesLoadedCheckStartedTime;
        if (timeWaited > skinOpts.imagesLoadedCheckTimeout) {
            // Clean up the timeout timer for subsequent calls
            skinOpts._imagesLoadedCheckStartedTime = 0;
            // We've waited long enough. The images might never load.
            // Don't set another timer.
            return;
        }

        // Let's check again in after a delay
        skinOpts.resizeAfterImagesLoadTimer = window.setTimeout(
            function () {
                This.resizeIframeOnceImagesLoaded(wym);
            },
            skinOpts.imagesLoadedCheckFrequency
        );
    },
    _imageIsLoaded: function (img) {
        if (img.complete !== true) {
            return false;
        }

        if (typeof img.naturalWidth !== "undefined" &&
                img.naturalWidth === 0) {
            return false;
        }

        return true;
    },
    _getIframeHeightStrategy: function (wym) {
        // For some browsers (IE8+ and FF), the scrollHeight of the body
        // doesn't seem to include the top and bottom margins of the body
        // relative to the HTML. This leaves the editing "window" smaller
        // than required, which results in weird overlaps at the start/end.
        // For those browsers, the HTML element's scrollHeight is more
        // reliable.
        // Let's detect which kind of browser we're dealing with one time
        // so we can just do the right thing in the future.
        var bodyScrollHeight,
            $htmlElement,
            htmlElementHeight,
            htmlElementScrollHeight,
            heightStrategy;

        $htmlElement = jQuery(wym._doc).children().eq(0);

        bodyScrollHeight = wym._doc.body.scrollHeight;
        htmlElementHeight = $htmlElement.height();
        htmlElementScrollHeight = $htmlElement[0].scrollHeight;

        if (WYMeditor.isInternetExplorerPre11()) {
            // The htmlElementScrollHeight is fairly reliable,
            // but doesn't shrink when content is removed.
            heightStrategy = function (wym) {
                var $htmlElement = jQuery(wym._doc).children().eq(0),
                    htmlElementScrollHeight = $htmlElement[0].scrollHeight;

                // Without the 10px reduction in height, every possible action
                // adds 10 pixels of height.
                // TODO: Figure out why this happens and if we can make the
                // 10px number not magic (actually derived from a
                // margin/padding etc).
                return htmlElementScrollHeight - 10;
            };

            return heightStrategy;
        } else if (htmlElementHeight >= bodyScrollHeight) {
            // Well-behaving browsers like FF and Chrome let us rely on the
            // HTML element's jQuery height() in every case. Hooray!
            heightStrategy = function (wym) {
                var $htmlElement = jQuery(wym._doc).children().eq(0),
                    htmlElementHeight = $htmlElement.height();

                return htmlElementHeight;
            };

            return heightStrategy;
        } else if (bodyScrollHeight > htmlElementScrollHeight) {
            // This is probably IE7, where the only thing reliable is the
            // bodyScrollHeight
            heightStrategy = function (wym) {
                return wym._doc.body.scrollHeight;
            };

            return heightStrategy;
        } else {
            throw new Error('unsupported browser');
        }
    },
    resizeIframe: function (wym) {
        var This = WYMeditor.SKINS.seamless,
            desiredHeight,
            $iframe = jQuery(wym._iframe),
            currentHeight = $iframe.height();

        if (typeof WYMeditor.IFRAME_HEIGHT_GETTER === "undefined") {
            WYMeditor.IFRAME_HEIGHT_GETTER = This._getIframeHeightStrategy(
                wym
            );
        }

        desiredHeight = WYMeditor.IFRAME_HEIGHT_GETTER(wym);

        // Don't let the height drop below the WYMeditor textarea. This allows
        // folks to use their favorite height-setting method on the textarea,
        // without needing to pass options on to WYMeditor.
        if (desiredHeight < wym.seamlessSkinOpts.minimumHeight) {
            desiredHeight = wym.seamlessSkinOpts.minimumHeight;
        }

        if (currentHeight !== desiredHeight) {
            $iframe.height(desiredHeight);
            wym.seamlessSkinIframeHeight = desiredHeight;

            return true;
        }
        return false;
    },
    scrollIfNeeded: function (wym) {
        var iframeOffset = jQuery(wym._iframe).offset(),
            iframeOffsetTop = iframeOffset.top,
            $container = jQuery(wym.selectedContainer()),
            containerOffset = $container.offset(),
            viewportLowestY,
            containerLowestY,
            newScrollTop,
            extraScroll = 20,
            scrollDiff,
            $window = jQuery(window),
            $body = jQuery(document.body);

        if ($container.length === 0) {
            // With nothing selected, there's no need to scroll
            return;
        }
        containerLowestY = iframeOffsetTop + containerOffset.top;
        containerLowestY += $container.outerHeight();
        viewportLowestY = $window.scrollTop() + $window.height();
        scrollDiff = containerLowestY - viewportLowestY;
        if (scrollDiff > 0) {
            // Part of our selected container isn't
            // visible, so we need to scroll down.
            newScrollTop = $body.scrollTop() + scrollDiff + extraScroll;
            $body.scrollTop(newScrollTop);
        }
    },
    resizeAndScrollIfNeeded: function (wym) {
        // Scroll the page so that our current selection
        // within the iframe is actually in view.
        var This = WYMeditor.SKINS.seamless,
            resizeOccurred = This.resizeIframe(wym);
        if (resizeOccurred !== true) {
            return;
        }
        This.scrollIfNeeded(wym);
    }
};

/* This file is part of the Silver skin for WYMeditor by Scott Edwin Lewis */

jQuery.fn.selectify = function() {
    var $elements = this;
    return $elements.each(function() {
        var element = this;
        jQuery(element).hover(
            function() {
                var element = this;
                jQuery("h2", element).css("background-position", "0px -18px");
                jQuery("ul", element).fadeIn("fast");
            },
            function() {
                var element = this;
                jQuery("h2", element).css("background-position", "");
                jQuery("ul", element).fadeOut("fast");
            }
        );
    });
};

WYMeditor.SKINS.silver = {

    init: function(wym) {

        //add some elements to improve the rendering
        jQuery(wym._box)
          .append('<div class="clear"></div>')
          .wrapInner('<div class="wym_inner"></div>');

        //render following sections as panels
        jQuery(wym._box).find(wym._options.classesSelector)
          .addClass("wym_panel");

        //render following sections as buttons
        jQuery(wym._box).find(wym._options.toolsSelector)
          .addClass("wym_buttons");

        //render following sections as dropdown menus
        jQuery(wym._box).find(wym._options.containersSelector)
          .addClass("wym_dropdown")
          .selectify();

        // auto add some margin to the main area sides if left area
        // or right area are not empty (if they contain sections)
        jQuery(wym._box).find("div.wym_area_right ul")
          .parents("div.wym_area_right").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-right": "155px"});

        jQuery(wym._box).find("div.wym_area_left ul")
          .parents("div.wym_area_left").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-left": "155px"});

        //make hover work under IE < 7
        jQuery(wym._box).find(".wym_section").hover(function(){
          var section = this;
          jQuery(section).addClass("hover");
        },function(){
          var section = this;
          jQuery(section).removeClass("hover");
        });
    }
};

WYMeditor.SKINS.twopanels = {

    init: function(wym) {

        //move the containers panel to the left area
        jQuery(wym._box).find(wym._options.containersSelector)
          .appendTo("div.wym_area_left");

        //render following sections as panels
        jQuery(wym._box).find(wym._options.classesSelector + ', ' +
          wym._options.containersSelector)
          .addClass("wym_panel");

        //render following sections as buttons
        jQuery(wym._box).find(wym._options.toolsSelector)
          .addClass("wym_buttons");

        // auto add some margin to the main area sides if left area
        // or right area are not empty (if they contain sections)
        jQuery(wym._box).find("div.wym_area_right ul")
          .parents("div.wym_area_right").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-right": "155px"});

        jQuery(wym._box).find("div.wym_area_left ul")
          .parents("div.wym_area_left").show()
          .parents(wym._options.boxSelector)
          .find("div.wym_area_main")
          .css({"margin-left": "115px"});

        //make hover work under IE < 7
        jQuery(wym._box).find(".wym_section").hover(function(){
          jQuery(this).addClass("hover");
        },function(){
          jQuery(this).removeClass("hover");
        });
    }
};
