/*
    json2.js
    2012-10-08

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, regexp: true */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (typeof JSON !== 'object') {
    JSON = {};
}

(function () {
    'use strict';

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf())
                ? this.getUTCFullYear()     + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate())      + 'T' +
                    f(this.getUTCHours())     + ':' +
                    f(this.getUTCMinutes())   + ':' +
                    f(this.getUTCSeconds())   + 'Z'
                : null;
        };

        String.prototype.toJSON      =
            Number.prototype.toJSON  =
            Boolean.prototype.toJSON = function (key) {
                return this.valueOf();
            };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string'
                ? c
                : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0
                    ? '[]'
                    : gap
                    ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                    : '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0
                ? '{}'
                : gap
                ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
                : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function'
                    ? walk({'': j}, '')
                    : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());/**
 * History.js Native Adapter
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

// Closure
(function(window,undefined){
	"use strict";

	// Localise Globals
	var History = window.History = window.History||{};

	// Check Existence
	if ( typeof History.Adapter !== 'undefined' ) {
		throw new Error('History.js Adapter has already been loaded...');
	}

	// Add the Adapter
	History.Adapter = {
		/**
		 * History.Adapter.handlers[uid][eventName] = Array
		 */
		handlers: {},

		/**
		 * History.Adapter._uid
		 * The current element unique identifier
		 */
		_uid: 1,

		/**
		 * History.Adapter.uid(element)
		 * @param {Element} element
		 * @return {String} uid
		 */
		uid: function(element){
			return element._uid || (element._uid = History.Adapter._uid++);
		},

		/**
		 * History.Adapter.bind(el,event,callback)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Function} callback
		 * @return
		 */
		bind: function(element,eventName,callback){
			// Prepare
			var uid = History.Adapter.uid(element);

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
			History.Adapter.handlers[uid][eventName].push(callback);

			// Bind Global Listener
			element['on'+eventName] = (function(element,eventName){
				return function(event){
					History.Adapter.trigger(element,eventName,event);
				};
			})(element,eventName);
		},

		/**
		 * History.Adapter.trigger(el,event)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Object} event - a object of event data
		 * @return
		 */
		trigger: function(element,eventName,event){
			// Prepare
			event = event || {};
			var uid = History.Adapter.uid(element),
				i,n;

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];

			// Fire Listeners
			for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i<n; ++i ) {
				History.Adapter.handlers[uid][eventName][i].apply(this,[event]);
			}
		},

		/**
		 * History.Adapter.extractEventData(key,event,extra)
		 * @param {String} key - key for the event data to extract
		 * @param {String} event - custom and standard events
		 * @return {mixed}
		 */
		extractEventData: function(key,event){
			var result = (event && event[key]) || undefined;
			return result;
		},

		/**
		 * History.Adapter.onDomLoad(callback)
		 * @param {Function} callback
		 * @return
		 */
		onDomLoad: function(callback) {
			var timeout = window.setTimeout(function(){
				callback();
			},2000);
			window.onload = function(){
				clearTimeout(timeout);
				callback();
			};
		}
	};

	// Try to Initialise History
	if ( typeof History.init !== 'undefined' ) {
		History.init();
	}

})(window);
/**
 * History.js HTML4 Support
 * Depends on the HTML5 Support
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

(function(window,undefined){
	"use strict";

	// ========================================================================
	// Initialise

	// Localise Globals
	var
		document = window.document, // Make sure we are using the correct document
		setTimeout = window.setTimeout||setTimeout,
		clearTimeout = window.clearTimeout||clearTimeout,
		setInterval = window.setInterval||setInterval,
		History = window.History = window.History||{}; // Public History Object

	// Check Existence
	if ( typeof History.initHtml4 !== 'undefined' ) {
		throw new Error('History.js HTML4 Support has already been loaded...');
	}


	// ========================================================================
	// Initialise HTML4 Support

	// Initialise HTML4 Support
	History.initHtml4 = function(){
		// Initialise
		if ( typeof History.initHtml4.initialized !== 'undefined' ) {
			// Already Loaded
			return false;
		}
		else {
			History.initHtml4.initialized = true;
		}


		// ====================================================================
		// Properties

		/**
		 * History.enabled
		 * Is History enabled?
		 */
		History.enabled = true;


		// ====================================================================
		// Hash Storage

		/**
		 * History.savedHashes
		 * Store the hashes in an array
		 */
		History.savedHashes = [];

		/**
		 * History.isLastHash(newHash)
		 * Checks if the hash is the last hash
		 * @param {string} newHash
		 * @return {boolean} true
		 */
		History.isLastHash = function(newHash){
			// Prepare
			var oldHash = History.getHashByIndex(),
				isLast;

			// Check
			isLast = newHash === oldHash;

			// Return isLast
			return isLast;
		};

		/**
		 * History.isHashEqual(newHash, oldHash)
		 * Checks to see if two hashes are functionally equal
		 * @param {string} newHash
		 * @param {string} oldHash
		 * @return {boolean} true
		 */
		History.isHashEqual = function(newHash, oldHash){
			newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
			oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
			return newHash === oldHash;
		};

		/**
		 * History.saveHash(newHash)
		 * Push a Hash
		 * @param {string} newHash
		 * @return {boolean} true
		 */
		History.saveHash = function(newHash){
			// Check Hash
			if ( History.isLastHash(newHash) ) {
				return false;
			}

			// Push the Hash
			History.savedHashes.push(newHash);

			// Return true
			return true;
		};

		/**
		 * History.getHashByIndex()
		 * Gets a hash by the index
		 * @param {integer} index
		 * @return {string}
		 */
		History.getHashByIndex = function(index){
			// Prepare
			var hash = null;

			// Handle
			if ( typeof index === 'undefined' ) {
				// Get the last inserted
				hash = History.savedHashes[History.savedHashes.length-1];
			}
			else if ( index < 0 ) {
				// Get from the end
				hash = History.savedHashes[History.savedHashes.length+index];
			}
			else {
				// Get from the beginning
				hash = History.savedHashes[index];
			}

			// Return hash
			return hash;
		};


		// ====================================================================
		// Discarded States

		/**
		 * History.discardedHashes
		 * A hashed array of discarded hashes
		 */
		History.discardedHashes = {};

		/**
		 * History.discardedStates
		 * A hashed array of discarded states
		 */
		History.discardedStates = {};

		/**
		 * History.discardState(State)
		 * Discards the state by ignoring it through History
		 * @param {object} State
		 * @return {true}
		 */
		History.discardState = function(discardedState,forwardState,backState){
			//History.debug('History.discardState', arguments);
			// Prepare
			var discardedStateHash = History.getHashByState(discardedState),
				discardObject;

			// Create Discard Object
			discardObject = {
				'discardedState': discardedState,
				'backState': backState,
				'forwardState': forwardState
			};

			// Add to DiscardedStates
			History.discardedStates[discardedStateHash] = discardObject;

			// Return true
			return true;
		};

		/**
		 * History.discardHash(hash)
		 * Discards the hash by ignoring it through History
		 * @param {string} hash
		 * @return {true}
		 */
		History.discardHash = function(discardedHash,forwardState,backState){
			//History.debug('History.discardState', arguments);
			// Create Discard Object
			var discardObject = {
				'discardedHash': discardedHash,
				'backState': backState,
				'forwardState': forwardState
			};

			// Add to discardedHash
			History.discardedHashes[discardedHash] = discardObject;

			// Return true
			return true;
		};

		/**
		 * History.discardedState(State)
		 * Checks to see if the state is discarded
		 * @param {object} State
		 * @return {bool}
		 */
		History.discardedState = function(State){
			// Prepare
			var StateHash = History.getHashByState(State),
				discarded;

			// Check
			discarded = History.discardedStates[StateHash]||false;

			// Return true
			return discarded;
		};

		/**
		 * History.discardedHash(hash)
		 * Checks to see if the state is discarded
		 * @param {string} State
		 * @return {bool}
		 */
		History.discardedHash = function(hash){
			// Check
			var discarded = History.discardedHashes[hash]||false;

			// Return true
			return discarded;
		};

		/**
		 * History.recycleState(State)
		 * Allows a discarded state to be used again
		 * @param {object} data
		 * @param {string} title
		 * @param {string} url
		 * @return {true}
		 */
		History.recycleState = function(State){
			//History.debug('History.recycleState', arguments);
			// Prepare
			var StateHash = History.getHashByState(State);

			// Remove from DiscardedStates
			if ( History.discardedState(State) ) {
				delete History.discardedStates[StateHash];
			}

			// Return true
			return true;
		};


		// ====================================================================
		// HTML4 HashChange Support

		if ( History.emulated.hashChange ) {
			/*
			 * We must emulate the HTML4 HashChange Support by manually checking for hash changes
			 */

			/**
			 * History.hashChangeInit()
			 * Init the HashChange Emulation
			 */
			History.hashChangeInit = function(){
				// Define our Checker Function
				History.checkerFunction = null;

				// Define some variables that will help in our checker function
				var lastDocumentHash = '',
					iframeId, iframe,
					lastIframeHash, checkerRunning,
					startedWithHash = Boolean(History.getHash());

				// Handle depending on the browser
				if ( History.isInternetExplorer() ) {
					// IE6 and IE7
					// We need to use an iframe to emulate the back and forward buttons

					// Create iFrame
					iframeId = 'historyjs-iframe';
					iframe = document.createElement('iframe');

					// Adjust iFarme
					// IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
					// "This page contains both secure and nonsecure items" warning.
					iframe.setAttribute('id', iframeId);
					iframe.setAttribute('src', '#');
					iframe.style.display = 'none';

					// Append iFrame
					document.body.appendChild(iframe);

					// Create initial history entry
					iframe.contentWindow.document.open();
					iframe.contentWindow.document.close();

					// Define some variables that will help in our checker function
					lastIframeHash = '';
					checkerRunning = false;

					// Define the checker function
					History.checkerFunction = function(){
						// Check Running
						if ( checkerRunning ) {
							return false;
						}

						// Update Running
						checkerRunning = true;

						// Fetch
						var
							documentHash = History.getHash(),
							iframeHash = History.getHash(iframe.contentWindow.document);

						// The Document Hash has changed (application caused)
						if ( documentHash !== lastDocumentHash ) {
							// Equalise
							lastDocumentHash = documentHash;

							// Create a history entry in the iframe
							if ( iframeHash !== documentHash ) {
								//History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);

								// Equalise
								lastIframeHash = iframeHash = documentHash;

								// Create History Entry
								iframe.contentWindow.document.open();
								iframe.contentWindow.document.close();

								// Update the iframe's hash
								iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
							}

							// Trigger Hashchange Event
							History.Adapter.trigger(window,'hashchange');
						}

						// The iFrame Hash has changed (back button caused)
						else if ( iframeHash !== lastIframeHash ) {
							//History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);

							// Equalise
							lastIframeHash = iframeHash;
							
							// If there is no iframe hash that means we're at the original
							// iframe state.
							// And if there was a hash on the original request, the original
							// iframe state was replaced instantly, so skip this state and take
							// the user back to where they came from.
							if (startedWithHash && iframeHash === '') {
								History.back();
							}
							else {
								// Update the Hash
								History.setHash(iframeHash,false);
							}
						}

						// Reset Running
						checkerRunning = false;

						// Return true
						return true;
					};
				}
				else {
					// We are not IE
					// Firefox 1 or 2, Opera

					// Define the checker function
					History.checkerFunction = function(){
						// Prepare
						var documentHash = History.getHash()||'';

						// The Document Hash has changed (application caused)
						if ( documentHash !== lastDocumentHash ) {
							// Equalise
							lastDocumentHash = documentHash;

							// Trigger Hashchange Event
							History.Adapter.trigger(window,'hashchange');
						}

						// Return true
						return true;
					};
				}

				// Apply the checker function
				History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));

				// Done
				return true;
			}; // History.hashChangeInit

			// Bind hashChangeInit
			History.Adapter.onDomLoad(History.hashChangeInit);

		} // History.emulated.hashChange


		// ====================================================================
		// HTML5 State Support

		// Non-Native pushState Implementation
		if ( History.emulated.pushState ) {
			/*
			 * We must emulate the HTML5 State Management by using HTML4 HashChange
			 */

			/**
			 * History.onHashChange(event)
			 * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
			 */
			History.onHashChange = function(event){
				//History.debug('History.onHashChange', arguments);

				// Prepare
				var currentUrl = ((event && event.newURL) || History.getLocationHref()),
					currentHash = History.getHashByUrl(currentUrl),
					currentState = null,
					currentStateHash = null,
					currentStateHashExits = null,
					discardObject;

				// Check if we are the same state
				if ( History.isLastHash(currentHash) ) {
					// There has been no change (just the page's hash has finally propagated)
					//History.debug('History.onHashChange: no change');
					History.busy(false);
					return false;
				}

				// Reset the double check
				History.doubleCheckComplete();

				// Store our location for use in detecting back/forward direction
				History.saveHash(currentHash);

				// Expand Hash
				if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
					//History.debug('History.onHashChange: traditional anchor', currentHash);
					// Traditional Anchor Hash
					History.Adapter.trigger(window,'anchorchange');
					History.busy(false);
					return false;
				}

				// Create State
				currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);

				// Check if we are the same state
				if ( History.isLastSavedState(currentState) ) {
					//History.debug('History.onHashChange: no change');
					// There has been no change (just the page's hash has finally propagated)
					History.busy(false);
					return false;
				}

				// Create the state Hash
				currentStateHash = History.getHashByState(currentState);

				// Check if we are DiscardedState
				discardObject = History.discardedState(currentState);
				if ( discardObject ) {
					// Ignore this state as it has been discarded and go back to the state before it
					if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
						// We are going backwards
						//History.debug('History.onHashChange: go backwards');
						History.back(false);
					} else {
						// We are going forwards
						//History.debug('History.onHashChange: go forwards');
						History.forward(false);
					}
					return false;
				}

				// Push the new HTML5 State
				//History.debug('History.onHashChange: success hashchange');
				History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);

				// End onHashChange closure
				return true;
			};
			History.Adapter.bind(window,'hashchange',History.onHashChange);

			/**
			 * History.pushState(data,title,url)
			 * Add a new State to the history object, become it, and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.pushState = function(data,title,url,queue){
				//History.debug('History.pushState: called', arguments);

				// We assume that the URL passed in is URI-encoded, but this makes
				// sure that it's fully URI encoded; any '%'s that are encoded are
				// converted back into '%'s
				url = encodeURI(url).replace(/%25/g, "%");

				// Check the State
				if ( History.getHashByUrl(url) ) {
					throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.pushState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.pushState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy
				History.busy(true);

				// Fetch the State Object
				var newState = History.createStateObject(data,title,url),
					newStateHash = History.getHashByState(newState),
					oldState = History.getState(false),
					oldStateHash = History.getHashByState(oldState),
					html4Hash = History.getHash(),
					wasExpected = History.expectedStateId == newState.id;

				// Store the newState
				History.storeState(newState);
				History.expectedStateId = newState.id;

				// Recycle the State
				History.recycleState(newState);

				// Force update of the title
				History.setTitle(newState);

				// Check if we are the same State
				if ( newStateHash === oldStateHash ) {
					//History.debug('History.pushState: no change', newStateHash);
					History.busy(false);
					return false;
				}

				// Update HTML5 State
				History.saveState(newState);

				// Fire HTML5 Event
				if(!wasExpected)
					History.Adapter.trigger(window,'statechange');

				// Update HTML4 Hash
				if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
					History.setHash(newStateHash,false);
				}
				
				History.busy(false);

				// End pushState closure
				return true;
			};

			/**
			 * History.replaceState(data,title,url)
			 * Replace the State and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.replaceState = function(data,title,url,queue){
				//History.debug('History.replaceState: called', arguments);

				// We assume that the URL passed in is URI-encoded, but this makes
				// sure that it's fully URI encoded; any '%'s that are encoded are
				// converted back into '%'s
				url = encodeURI(url).replace(/%25/g, "%");

				// Check the State
				if ( History.getHashByUrl(url) ) {
					throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.replaceState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.replaceState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy
				History.busy(true);

				// Fetch the State Objects
				var newState        = History.createStateObject(data,title,url),
					newStateHash = History.getHashByState(newState),
					oldState        = History.getState(false),
					oldStateHash = History.getHashByState(oldState),
					previousState   = History.getStateByIndex(-2);

				// Discard Old State
				History.discardState(oldState,newState,previousState);

				// If the url hasn't changed, just store and save the state
				// and fire a statechange event to be consistent with the
				// html 5 api
				if ( newStateHash === oldStateHash ) {
					// Store the newState
					History.storeState(newState);
					History.expectedStateId = newState.id;
	
					// Recycle the State
					History.recycleState(newState);
	
					// Force update of the title
					History.setTitle(newState);
					
					// Update HTML5 State
					History.saveState(newState);

					// Fire HTML5 Event
					//History.debug('History.pushState: trigger popstate');
					History.Adapter.trigger(window,'statechange');
					History.busy(false);
				}
				else {
					// Alias to PushState
					History.pushState(newState.data,newState.title,newState.url,false);
				}

				// End replaceState closure
				return true;
			};

		} // History.emulated.pushState



		// ====================================================================
		// Initialise

		// Non-Native pushState Implementation
		if ( History.emulated.pushState ) {
			/**
			 * Ensure initial state is handled correctly
			 */
			if ( History.getHash() && !History.emulated.hashChange ) {
				History.Adapter.onDomLoad(function(){
					History.Adapter.trigger(window,'hashchange');
				});
			}

		} // History.emulated.pushState

	}; // History.initHtml4

	// Try to Initialise History
	if ( typeof History.init !== 'undefined' ) {
		History.init();
	}

})(window);
/**
 * History.js Core
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

(function(window,undefined){
	"use strict";

	// ========================================================================
	// Initialise

	// Localise Globals
	var
		console = window.console||undefined, // Prevent a JSLint complain
		document = window.document, // Make sure we are using the correct document
		navigator = window.navigator, // Make sure we are using the correct navigator
		sessionStorage = window.sessionStorage||false, // sessionStorage
		setTimeout = window.setTimeout,
		clearTimeout = window.clearTimeout,
		setInterval = window.setInterval,
		clearInterval = window.clearInterval,
		JSON = window.JSON,
		alert = window.alert,
		History = window.History = window.History||{}, // Public History Object
		history = window.history; // Old History Object

	try {
		sessionStorage.setItem('TEST', '1');
		sessionStorage.removeItem('TEST');
	} catch(e) {
		sessionStorage = false;
	}

	// MooTools Compatibility
	JSON.stringify = JSON.stringify||JSON.encode;
	JSON.parse = JSON.parse||JSON.decode;

	// Check Existence
	if ( typeof History.init !== 'undefined' ) {
		throw new Error('History.js Core has already been loaded...');
	}

	// Initialise History
	History.init = function(options){
		// Check Load Status of Adapter
		if ( typeof History.Adapter === 'undefined' ) {
			return false;
		}

		// Check Load Status of Core
		if ( typeof History.initCore !== 'undefined' ) {
			History.initCore();
		}

		// Check Load Status of HTML4 Support
		if ( typeof History.initHtml4 !== 'undefined' ) {
			History.initHtml4();
		}

		// Return true
		return true;
	};


	// ========================================================================
	// Initialise Core

	// Initialise Core
	History.initCore = function(options){
		// Initialise
		if ( typeof History.initCore.initialized !== 'undefined' ) {
			// Already Loaded
			return false;
		}
		else {
			History.initCore.initialized = true;
		}


		// ====================================================================
		// Options

		/**
		 * History.options
		 * Configurable options
		 */
		History.options = History.options||{};

		/**
		 * History.options.hashChangeInterval
		 * How long should the interval be before hashchange checks
		 */
		History.options.hashChangeInterval = History.options.hashChangeInterval || 100;

		/**
		 * History.options.safariPollInterval
		 * How long should the interval be before safari poll checks
		 */
		History.options.safariPollInterval = History.options.safariPollInterval || 500;

		/**
		 * History.options.doubleCheckInterval
		 * How long should the interval be before we perform a double check
		 */
		History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;

		/**
		 * History.options.disableSuid
		 * Force History not to append suid
		 */
		History.options.disableSuid = History.options.disableSuid || false;

		/**
		 * History.options.storeInterval
		 * How long should we wait between store calls
		 */
		History.options.storeInterval = History.options.storeInterval || 1000;

		/**
		 * History.options.busyDelay
		 * How long should we wait between busy events
		 */
		History.options.busyDelay = History.options.busyDelay || 250;

		/**
		 * History.options.debug
		 * If true will enable debug messages to be logged
		 */
		History.options.debug = History.options.debug || false;

		/**
		 * History.options.initialTitle
		 * What is the title of the initial state
		 */
		History.options.initialTitle = History.options.initialTitle || document.title;

		/**
		 * History.options.html4Mode
		 * If true, will force HTMl4 mode (hashtags)
		 */
		History.options.html4Mode = History.options.html4Mode || false;

		/**
		 * History.options.delayInit
		 * Want to override default options and call init manually.
		 */
		History.options.delayInit = History.options.delayInit || false;


		// ====================================================================
		// Interval record

		/**
		 * History.intervalList
		 * List of intervals set, to be cleared when document is unloaded.
		 */
		History.intervalList = [];

		/**
		 * History.clearAllIntervals
		 * Clears all setInterval instances.
		 */
		History.clearAllIntervals = function(){
			var i, il = History.intervalList;
			if (typeof il !== "undefined" && il !== null) {
				for (i = 0; i < il.length; i++) {
					clearInterval(il[i]);
				}
				History.intervalList = null;
			}
		};


		// ====================================================================
		// Debug

		/**
		 * History.debug(message,...)
		 * Logs the passed arguments if debug enabled
		 */
		History.debug = function(){
			if ( (History.options.debug||false) ) {
				History.log.apply(History,arguments);
			}
		};

		/**
		 * History.log(message,...)
		 * Logs the passed arguments
		 */
		History.log = function(){
			// Prepare
			var
				consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
				textarea = document.getElementById('log'),
				message,
				i,n,
				args,arg
				;

			// Write to Console
			if ( consoleExists ) {
				args = Array.prototype.slice.call(arguments);
				message = args.shift();
				if ( typeof console.debug !== 'undefined' ) {
					console.debug.apply(console,[message,args]);
				}
				else {
					console.log.apply(console,[message,args]);
				}
			}
			else {
				message = ("\n"+arguments[0]+"\n");
			}

			// Write to log
			for ( i=1,n=arguments.length; i<n; ++i ) {
				arg = arguments[i];
				if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) {
					try {
						arg = JSON.stringify(arg);
					}
					catch ( Exception ) {
						// Recursive Object
					}
				}
				message += "\n"+arg+"\n";
			}

			// Textarea
			if ( textarea ) {
				textarea.value += message+"\n-----\n";
				textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
			}
			// No Textarea, No Console
			else if ( !consoleExists ) {
				alert(message);
			}

			// Return true
			return true;
		};


		// ====================================================================
		// Emulated Status

		/**
		 * History.getInternetExplorerMajorVersion()
		 * Get's the major version of Internet Explorer
		 * @return {integer}
		 * @license Public Domain
		 * @author Benjamin Arthur Lupton <contact@balupton.com>
		 * @author James Padolsey <https://gist.github.com/527683>
		 */
		History.getInternetExplorerMajorVersion = function(){
			var result = History.getInternetExplorerMajorVersion.cached =
					(typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
				?	History.getInternetExplorerMajorVersion.cached
				:	(function(){
						var v = 3,
								div = document.createElement('div'),
								all = div.getElementsByTagName('i');
						while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
						return (v > 4) ? v : false;
					})()
				;
			return result;
		};

		/**
		 * History.isInternetExplorer()
		 * Are we using Internet Explorer?
		 * @return {boolean}
		 * @license Public Domain
		 * @author Benjamin Arthur Lupton <contact@balupton.com>
		 */
		History.isInternetExplorer = function(){
			var result =
				History.isInternetExplorer.cached =
				(typeof History.isInternetExplorer.cached !== 'undefined')
					?	History.isInternetExplorer.cached
					:	Boolean(History.getInternetExplorerMajorVersion())
				;
			return result;
		};

		/**
		 * History.emulated
		 * Which features require emulating?
		 */

		if (History.options.html4Mode) {
			History.emulated = {
				pushState : true,
				hashChange: true
			};
		}

		else {

			History.emulated = {
				pushState: !Boolean(
					window.history && window.history.pushState && window.history.replaceState
					&& !(
						(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
						|| (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
					)
				),
				hashChange: Boolean(
					!(('onhashchange' in window) || ('onhashchange' in document))
					||
					(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
				)
			};
		}

		/**
		 * History.enabled
		 * Is History enabled?
		 */
		History.enabled = !History.emulated.pushState;

		/**
		 * History.bugs
		 * Which bugs are present
		 */
		History.bugs = {
			/**
			 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
			 * https://bugs.webkit.org/show_bug.cgi?id=56249
			 */
			setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),

			/**
			 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
			 * https://bugs.webkit.org/show_bug.cgi?id=42940
			 */
			safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),

			/**
			 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
			 */
			ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),

			/**
			 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
			 */
			hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
		};

		/**
		 * History.isEmptyObject(obj)
		 * Checks to see if the Object is Empty
		 * @param {Object} obj
		 * @return {boolean}
		 */
		History.isEmptyObject = function(obj) {
			for ( var name in obj ) {
				if ( obj.hasOwnProperty(name) ) {
					return false;
				}
			}
			return true;
		};

		/**
		 * History.cloneObject(obj)
		 * Clones a object and eliminate all references to the original contexts
		 * @param {Object} obj
		 * @return {Object}
		 */
		History.cloneObject = function(obj) {
			var hash,newObj;
			if ( obj ) {
				hash = JSON.stringify(obj);
				newObj = JSON.parse(hash);
			}
			else {
				newObj = {};
			}
			return newObj;
		};


		// ====================================================================
		// URL Helpers

		/**
		 * History.getRootUrl()
		 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
		 * @return {String} rootUrl
		 */
		History.getRootUrl = function(){
			// Create
			var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
			if ( document.location.port||false ) {
				rootUrl += ':'+document.location.port;
			}
			rootUrl += '/';

			// Return
			return rootUrl;
		};

		/**
		 * History.getBaseHref()
		 * Fetches the `href` attribute of the `<base href="...">` element if it exists
		 * @return {String} baseHref
		 */
		History.getBaseHref = function(){
			// Create
			var
				baseElements = document.getElementsByTagName('base'),
				baseElement = null,
				baseHref = '';

			// Test for Base Element
			if ( baseElements.length === 1 ) {
				// Prepare for Base Element
				baseElement = baseElements[0];
				baseHref = baseElement.href.replace(/[^\/]+$/,'');
			}

			// Adjust trailing slash
			baseHref = baseHref.replace(/\/+$/,'');
			if ( baseHref ) baseHref += '/';

			// Return
			return baseHref;
		};

		/**
		 * History.getBaseUrl()
		 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
		 * @return {String} baseUrl
		 */
		History.getBaseUrl = function(){
			// Create
			var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();

			// Return
			return baseUrl;
		};

		/**
		 * History.getPageUrl()
		 * Fetches the URL of the current page
		 * @return {String} pageUrl
		 */
		History.getPageUrl = function(){
			// Fetch
			var
				State = History.getState(false,false),
				stateUrl = (State||{}).url||History.getLocationHref(),
				pageUrl;

			// Create
			pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
				return (/\./).test(part) ? part : part+'/';
			});

			// Return
			return pageUrl;
		};

		/**
		 * History.getBasePageUrl()
		 * Fetches the Url of the directory of the current page
		 * @return {String} basePageUrl
		 */
		History.getBasePageUrl = function(){
			// Create
			var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
				return (/[^\/]$/).test(part) ? '' : part;
			}).replace(/\/+$/,'')+'/';

			// Return
			return basePageUrl;
		};

		/**
		 * History.getFullUrl(url)
		 * Ensures that we have an absolute URL and not a relative URL
		 * @param {string} url
		 * @param {Boolean} allowBaseHref
		 * @return {string} fullUrl
		 */
		History.getFullUrl = function(url,allowBaseHref){
			// Prepare
			var fullUrl = url, firstChar = url.substring(0,1);
			allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;

			// Check
			if ( /[a-z]+\:\/\//.test(url) ) {
				// Full URL
			}
			else if ( firstChar === '/' ) {
				// Root URL
				fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
			}
			else if ( firstChar === '#' ) {
				// Anchor URL
				fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
			}
			else if ( firstChar === '?' ) {
				// Query URL
				fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
			}
			else {
				// Relative URL
				if ( allowBaseHref ) {
					fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
				} else {
					fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
				}
				// We have an if condition above as we do not want hashes
				// which are relative to the baseHref in our URLs
				// as if the baseHref changes, then all our bookmarks
				// would now point to different locations
				// whereas the basePageUrl will always stay the same
			}

			// Return
			return fullUrl.replace(/\#$/,'');
		};

		/**
		 * History.getShortUrl(url)
		 * Ensures that we have a relative URL and not a absolute URL
		 * @param {string} url
		 * @return {string} url
		 */
		History.getShortUrl = function(url){
			// Prepare
			var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();

			// Trim baseUrl
			if ( History.emulated.pushState ) {
				// We are in a if statement as when pushState is not emulated
				// The actual url these short urls are relative to can change
				// So within the same session, we the url may end up somewhere different
				shortUrl = shortUrl.replace(baseUrl,'');
			}

			// Trim rootUrl
			shortUrl = shortUrl.replace(rootUrl,'/');

			// Ensure we can still detect it as a state
			// if ( History.isTraditionalAnchor(shortUrl) ) {
			// 	shortUrl = './'+shortUrl;
			// }

            shortUrl = './' + shortUrl;

			// Clean It
			shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');

			// Return
			return shortUrl;
		};

		/**
		 * History.getLocationHref(document)
		 * Returns a normalized version of document.location.href
		 * accounting for browser inconsistencies, etc.
		 *
		 * This URL will be URI-encoded and will include the hash
		 *
		 * @param {object} document
		 * @return {string} url
		 */
		History.getLocationHref = function(doc) {
			doc = doc || document;

			// most of the time, this will be true
			if (doc.URL === doc.location.href)
				return doc.location.href;

			// some versions of webkit URI-decode document.location.href
			// but they leave document.URL in an encoded state
			if (doc.location.href === decodeURIComponent(doc.URL))
				return doc.URL;

			// FF 3.6 only updates document.URL when a page is reloaded
			// document.location.href is updated correctly
			if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
				return doc.location.href;

			if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
				return doc.location.href;
			
			return doc.URL || doc.location.href;
		};


		// ====================================================================
		// State Storage

		/**
		 * History.store
		 * The store for all session specific data
		 */
		History.store = {};

		/**
		 * History.idToState
		 * 1-1: State ID to State Object
		 */
		History.idToState = History.idToState||{};

		/**
		 * History.stateToId
		 * 1-1: State String to State ID
		 */
		History.stateToId = History.stateToId||{};

		/**
		 * History.urlToId
		 * 1-1: State URL to State ID
		 */
		History.urlToId = History.urlToId||{};

		/**
		 * History.storedStates
		 * Store the states in an array
		 */
		History.storedStates = History.storedStates||[];

		/**
		 * History.savedStates
		 * Saved the states in an array
		 */
		History.savedStates = History.savedStates||[];

		/**
		 * History.noramlizeStore()
		 * Noramlize the store by adding necessary values
		 */
		History.normalizeStore = function(){
			History.store.idToState = History.store.idToState||{};
			History.store.urlToId = History.store.urlToId||{};
			History.store.stateToId = History.store.stateToId||{};
		};

		/**
		 * History.getState()
		 * Get an object containing the data, title and url of the current state
		 * @param {Boolean} friendly
		 * @param {Boolean} create
		 * @return {Object} State
		 */
		History.getState = function(friendly,create){
			// Prepare
			if ( typeof friendly === 'undefined' ) { friendly = true; }
			if ( typeof create === 'undefined' ) { create = true; }

			// Fetch
			var State = History.getLastSavedState();

			// Create
			if ( !State && create ) {
				State = History.createStateObject();
			}

			// Adjust
			if ( friendly ) {
				State = History.cloneObject(State);
				State.url = State.cleanUrl||State.url;
			}

			// Return
			return State;
		};

		/**
		 * History.getIdByState(State)
		 * Gets a ID for a State
		 * @param {State} newState
		 * @return {String} id
		 */
		History.getIdByState = function(newState){

			// Fetch ID
			var id = History.extractId(newState.url),
				str;

			if ( !id ) {
				// Find ID via State String
				str = History.getStateString(newState);
				if ( typeof History.stateToId[str] !== 'undefined' ) {
					id = History.stateToId[str];
				}
				else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
					id = History.store.stateToId[str];
				}
				else {
					// Generate a new ID
					while ( true ) {
						id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
						if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
							break;
						}
					}

					// Apply the new State to the ID
					History.stateToId[str] = id;
					History.idToState[id] = newState;
				}
			}

			// Return ID
			return id;
		};

		/**
		 * History.normalizeState(State)
		 * Expands a State Object
		 * @param {object} State
		 * @return {object}
		 */
		History.normalizeState = function(oldState){
			// Variables
			var newState, dataNotEmpty;

			// Prepare
			if ( !oldState || (typeof oldState !== 'object') ) {
				oldState = {};
			}

			// Check
			if ( typeof oldState.normalized !== 'undefined' ) {
				return oldState;
			}

			// Adjust
			if ( !oldState.data || (typeof oldState.data !== 'object') ) {
				oldState.data = {};
			}

			// ----------------------------------------------------------------

			// Create
			newState = {};
			newState.normalized = true;
			newState.title = oldState.title||'';
			newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
			newState.hash = History.getShortUrl(newState.url);
			newState.data = History.cloneObject(oldState.data);

			// Fetch ID
			newState.id = History.getIdByState(newState);

			// ----------------------------------------------------------------

			// Clean the URL
			newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
			newState.url = newState.cleanUrl;

			// Check to see if we have more than just a url
			dataNotEmpty = !History.isEmptyObject(newState.data);

			// Apply
			if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
				// Add ID to Hash
				newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
				if ( !/\?/.test(newState.hash) ) {
					newState.hash += '?';
				}
				newState.hash += '&_suid='+newState.id;
			}

			// Create the Hashed URL
			newState.hashedUrl = History.getFullUrl(newState.hash);

			// ----------------------------------------------------------------

			// Update the URL if we have a duplicate
			if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
				newState.url = newState.hashedUrl;
			}

			// ----------------------------------------------------------------

			// Return
			return newState;
		};

		/**
		 * History.createStateObject(data,title,url)
		 * Creates a object based on the data, title and url state params
		 * @param {object} data
		 * @param {string} title
		 * @param {string} url
		 * @return {object}
		 */
		History.createStateObject = function(data,title,url){
			// Hashify
			var State = {
				'data': data,
				'title': title,
				'url': url
			};

			// Expand the State
			State = History.normalizeState(State);

			// Return object
			return State;
		};

		/**
		 * History.getStateById(id)
		 * Get a state by it's UID
		 * @param {String} id
		 */
		History.getStateById = function(id){
			// Prepare
			id = String(id);

			// Retrieve
			var State = History.idToState[id] || History.store.idToState[id] || undefined;

			// Return State
			return State;
		};

		/**
		 * Get a State's String
		 * @param {State} passedState
		 */
		History.getStateString = function(passedState){
			// Prepare
			var State, cleanedState, str;

			// Fetch
			State = History.normalizeState(passedState);

			// Clean
			cleanedState = {
				data: State.data,
				title: passedState.title,
				url: passedState.url
			};

			// Fetch
			str = JSON.stringify(cleanedState);

			// Return
			return str;
		};

		/**
		 * Get a State's ID
		 * @param {State} passedState
		 * @return {String} id
		 */
		History.getStateId = function(passedState){
			// Prepare
			var State, id;

			// Fetch
			State = History.normalizeState(passedState);

			// Fetch
			id = State.id;

			// Return
			return id;
		};

		/**
		 * History.getHashByState(State)
		 * Creates a Hash for the State Object
		 * @param {State} passedState
		 * @return {String} hash
		 */
		History.getHashByState = function(passedState){
			// Prepare
			var State, hash;

			// Fetch
			State = History.normalizeState(passedState);

			// Hash
			hash = State.hash;

			// Return
			return hash;
		};

		/**
		 * History.extractId(url_or_hash)
		 * Get a State ID by it's URL or Hash
		 * @param {string} url_or_hash
		 * @return {string} id
		 */
		History.extractId = function ( url_or_hash ) {
			// Prepare
			var id,parts,url, tmp;

			// Extract
			
			// If the URL has a #, use the id from before the #
			if (url_or_hash.indexOf('#') != -1)
			{
				tmp = url_or_hash.split("#")[0];
			}
			else
			{
				tmp = url_or_hash;
			}
			
			parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
			url = parts ? (parts[1]||url_or_hash) : url_or_hash;
			id = parts ? String(parts[2]||'') : '';

			// Return
			return id||false;
		};

		/**
		 * History.isTraditionalAnchor
		 * Checks to see if the url is a traditional anchor or not
		 * @param {String} url_or_hash
		 * @return {Boolean}
		 */
		History.isTraditionalAnchor = function(url_or_hash){
			// Check
			var isTraditional = !(/[\/\\.]/.test(url_or_hash));

			// Return
			return isTraditional;
		};

		/**
		 * History.extractState
		 * Get a State by it's URL or Hash
		 * @param {String} url_or_hash
		 * @return {State|null}
		 */
		History.extractState = function(url_or_hash,create){
			// Prepare
			var State = null, id, url;
			create = create||false;

			// Fetch SUID
			id = History.extractId(url_or_hash);
			if ( id ) {
				State = History.getStateById(id);
			}

			// Fetch SUID returned no State
			if ( !State ) {
				// Fetch URL
				url = History.getFullUrl(url_or_hash);

				// Check URL
				id = History.getIdByUrl(url)||false;
				if ( id ) {
					State = History.getStateById(id);
				}

				// Create State
				if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
					State = History.createStateObject(null,null,url);
				}
			}

			// Return
			return State;
		};

		/**
		 * History.getIdByUrl()
		 * Get a State ID by a State URL
		 */
		History.getIdByUrl = function(url){
			// Fetch
			var id = History.urlToId[url] || History.store.urlToId[url] || undefined;

			// Return
			return id;
		};

		/**
		 * History.getLastSavedState()
		 * Get an object containing the data, title and url of the current state
		 * @return {Object} State
		 */
		History.getLastSavedState = function(){
			return History.savedStates[History.savedStates.length-1]||undefined;
		};

		/**
		 * History.getLastStoredState()
		 * Get an object containing the data, title and url of the current state
		 * @return {Object} State
		 */
		History.getLastStoredState = function(){
			return History.storedStates[History.storedStates.length-1]||undefined;
		};

		/**
		 * History.hasUrlDuplicate
		 * Checks if a Url will have a url conflict
		 * @param {Object} newState
		 * @return {Boolean} hasDuplicate
		 */
		History.hasUrlDuplicate = function(newState) {
			// Prepare
			var hasDuplicate = false,
				oldState;

			// Fetch
			oldState = History.extractState(newState.url);

			// Check
			hasDuplicate = oldState && oldState.id !== newState.id;

			// Return
			return hasDuplicate;
		};

		/**
		 * History.storeState
		 * Store a State
		 * @param {Object} newState
		 * @return {Object} newState
		 */
		History.storeState = function(newState){
			// Store the State
			History.urlToId[newState.url] = newState.id;

			// Push the State
			History.storedStates.push(History.cloneObject(newState));

			// Return newState
			return newState;
		};

		/**
		 * History.isLastSavedState(newState)
		 * Tests to see if the state is the last state
		 * @param {Object} newState
		 * @return {boolean} isLast
		 */
		History.isLastSavedState = function(newState){
			// Prepare
			var isLast = false,
				newId, oldState, oldId;

			// Check
			if ( History.savedStates.length ) {
				newId = newState.id;
				oldState = History.getLastSavedState();
				oldId = oldState.id;

				// Check
				isLast = (newId === oldId);
			}

			// Return
			return isLast;
		};

		/**
		 * History.saveState
		 * Push a State
		 * @param {Object} newState
		 * @return {boolean} changed
		 */
		History.saveState = function(newState){
			// Check Hash
			if ( History.isLastSavedState(newState) ) {
				return false;
			}

			// Push the State
			History.savedStates.push(History.cloneObject(newState));

			// Return true
			return true;
		};

		/**
		 * History.getStateByIndex()
		 * Gets a state by the index
		 * @param {integer} index
		 * @return {Object}
		 */
		History.getStateByIndex = function(index){
			// Prepare
			var State = null;

			// Handle
			if ( typeof index === 'undefined' ) {
				// Get the last inserted
				State = History.savedStates[History.savedStates.length-1];
			}
			else if ( index < 0 ) {
				// Get from the end
				State = History.savedStates[History.savedStates.length+index];
			}
			else {
				// Get from the beginning
				State = History.savedStates[index];
			}

			// Return State
			return State;
		};
		
		/**
		 * History.getCurrentIndex()
		 * Gets the current index
		 * @return (integer)
		*/
		History.getCurrentIndex = function(){
			// Prepare
			var index = null;
			
			// No states saved
			if(History.savedStates.length < 1) {
				index = 0;
			}
			else {
				index = History.savedStates.length-1;
			}
			return index;
		};

		// ====================================================================
		// Hash Helpers

		/**
		 * History.getHash()
		 * @param {Location=} location
		 * Gets the current document hash
		 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
		 * @return {string}
		 */
		History.getHash = function(doc){
			var url = History.getLocationHref(doc),
				hash;
			hash = History.getHashByUrl(url);
			return hash;
		};

		/**
		 * History.unescapeHash()
		 * normalize and Unescape a Hash
		 * @param {String} hash
		 * @return {string}
		 */
		History.unescapeHash = function(hash){
			// Prepare
			var result = History.normalizeHash(hash);

			// Unescape hash
			result = decodeURIComponent(result);

			// Return result
			return result;
		};

		/**
		 * History.normalizeHash()
		 * normalize a hash across browsers
		 * @return {string}
		 */
		History.normalizeHash = function(hash){
			// Prepare
			var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');

			// Return result
			return result;
		};

		/**
		 * History.setHash(hash)
		 * Sets the document hash
		 * @param {string} hash
		 * @return {History}
		 */
		History.setHash = function(hash,queue){
			// Prepare
			var State, pageUrl;

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.setHash: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.setHash,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Log
			//History.debug('History.setHash: called',hash);

			// Make Busy + Continue
			History.busy(true);

			// Check if hash is a state
			State = History.extractState(hash,true);
			if ( State && !History.emulated.pushState ) {
				// Hash is a state so skip the setHash
				//History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);

				// PushState
				History.pushState(State.data,State.title,State.url,false);
			}
			else if ( History.getHash() !== hash ) {
				// Hash is a proper hash, so apply it

				// Handle browser bugs
				if ( History.bugs.setHash ) {
					// Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249

					// Fetch the base page
					pageUrl = History.getPageUrl();

					// Safari hash apply
					History.pushState(null,null,pageUrl+'#'+hash,false);
				}
				else {
					// Normal hash apply
					document.location.hash = hash;
				}
			}

			// Chain
			return History;
		};

		/**
		 * History.escape()
		 * normalize and Escape a Hash
		 * @return {string}
		 */
		History.escapeHash = function(hash){
			// Prepare
			var result = History.normalizeHash(hash);

			// Escape hash
			result = window.encodeURIComponent(result);

			// IE6 Escape Bug
			if ( !History.bugs.hashEscape ) {
				// Restore common parts
				result = result
					.replace(/\%21/g,'!')
					.replace(/\%26/g,'&')
					.replace(/\%3D/g,'=')
					.replace(/\%3F/g,'?');
			}

			// Return result
			return result;
		};

		/**
		 * History.getHashByUrl(url)
		 * Extracts the Hash from a URL
		 * @param {string} url
		 * @return {string} url
		 */
		History.getHashByUrl = function(url){
			// Extract the hash
			var hash = String(url)
				.replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
				;

			// Unescape hash
			hash = History.unescapeHash(hash);

			// Return hash
			return hash;
		};

		/**
		 * History.setTitle(title)
		 * Applies the title to the document
		 * @param {State} newState
		 * @return {Boolean}
		 */
		History.setTitle = function(newState){
			// Prepare
			var title = newState.title,
				firstState;

			// Initial
			if ( !title ) {
				firstState = History.getStateByIndex(0);
				if ( firstState && firstState.url === newState.url ) {
					title = firstState.title||History.options.initialTitle;
				}
			}

			// Apply
			try {
				document.getElementsByTagName('title')[0].innerHTML = title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
			}
			catch ( Exception ) { }
			document.title = title;

			// Chain
			return History;
		};


		// ====================================================================
		// Queueing

		/**
		 * History.queues
		 * The list of queues to use
		 * First In, First Out
		 */
		History.queues = [];

		/**
		 * History.busy(value)
		 * @param {boolean} value [optional]
		 * @return {boolean} busy
		 */
		History.busy = function(value){
			// Apply
			if ( typeof value !== 'undefined' ) {
				//History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
				History.busy.flag = value;
			}
			// Default
			else if ( typeof History.busy.flag === 'undefined' ) {
				History.busy.flag = false;
			}

			// Queue
			if ( !History.busy.flag ) {
				// Execute the next item in the queue
				clearTimeout(History.busy.timeout);
				var fireNext = function(){
					var i, queue, item;
					if ( History.busy.flag ) return;
					for ( i=History.queues.length-1; i >= 0; --i ) {
						queue = History.queues[i];
						if ( queue.length === 0 ) continue;
						item = queue.shift();
						History.fireQueueItem(item);
						History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
					}
				};
				History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
			}

			// Return
			return History.busy.flag;
		};

		/**
		 * History.busy.flag
		 */
		History.busy.flag = false;

		/**
		 * History.fireQueueItem(item)
		 * Fire a Queue Item
		 * @param {Object} item
		 * @return {Mixed} result
		 */
		History.fireQueueItem = function(item){
			return item.callback.apply(item.scope||History,item.args||[]);
		};

		/**
		 * History.pushQueue(callback,args)
		 * Add an item to the queue
		 * @param {Object} item [scope,callback,args,queue]
		 */
		History.pushQueue = function(item){
			// Prepare the queue
			History.queues[item.queue||0] = History.queues[item.queue||0]||[];

			// Add to the queue
			History.queues[item.queue||0].push(item);

			// Chain
			return History;
		};

		/**
		 * History.queue (item,queue), (func,queue), (func), (item)
		 * Either firs the item now if not busy, or adds it to the queue
		 */
		History.queue = function(item,queue){
			// Prepare
			if ( typeof item === 'function' ) {
				item = {
					callback: item
				};
			}
			if ( typeof queue !== 'undefined' ) {
				item.queue = queue;
			}

			// Handle
			if ( History.busy() ) {
				History.pushQueue(item);
			} else {
				History.fireQueueItem(item);
			}

			// Chain
			return History;
		};

		/**
		 * History.clearQueue()
		 * Clears the Queue
		 */
		History.clearQueue = function(){
			History.busy.flag = false;
			History.queues = [];
			return History;
		};


		// ====================================================================
		// IE Bug Fix

		/**
		 * History.stateChanged
		 * States whether or not the state has changed since the last double check was initialised
		 */
		History.stateChanged = false;

		/**
		 * History.doubleChecker
		 * Contains the timeout used for the double checks
		 */
		History.doubleChecker = false;

		/**
		 * History.doubleCheckComplete()
		 * Complete a double check
		 * @return {History}
		 */
		History.doubleCheckComplete = function(){
			// Update
			History.stateChanged = true;

			// Clear
			History.doubleCheckClear();

			// Chain
			return History;
		};

		/**
		 * History.doubleCheckClear()
		 * Clear a double check
		 * @return {History}
		 */
		History.doubleCheckClear = function(){
			// Clear
			if ( History.doubleChecker ) {
				clearTimeout(History.doubleChecker);
				History.doubleChecker = false;
			}

			// Chain
			return History;
		};

		/**
		 * History.doubleCheck()
		 * Create a double check
		 * @return {History}
		 */
		History.doubleCheck = function(tryAgain){
			// Reset
			History.stateChanged = false;
			History.doubleCheckClear();

			// Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
			// Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
			if ( History.bugs.ieDoubleCheck ) {
				// Apply Check
				History.doubleChecker = setTimeout(
					function(){
						History.doubleCheckClear();
						if ( !History.stateChanged ) {
							//History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
							// Re-Attempt
							tryAgain();
						}
						return true;
					},
					History.options.doubleCheckInterval
				);
			}

			// Chain
			return History;
		};


		// ====================================================================
		// Safari Bug Fix

		/**
		 * History.safariStatePoll()
		 * Poll the current state
		 * @return {History}
		 */
		History.safariStatePoll = function(){
			// Poll the URL

			// Get the Last State which has the new URL
			var
				urlState = History.extractState(History.getLocationHref()),
				newState;

			// Check for a difference
			if ( !History.isLastSavedState(urlState) ) {
				newState = urlState;
			}
			else {
				return;
			}

			// Check if we have a state with that url
			// If not create it
			if ( !newState ) {
				//History.debug('History.safariStatePoll: new');
				newState = History.createStateObject();
			}

			// Apply the New State
			//History.debug('History.safariStatePoll: trigger');
			History.Adapter.trigger(window,'popstate');

			// Chain
			return History;
		};


		// ====================================================================
		// State Aliases

		/**
		 * History.back(queue)
		 * Send the browser history back one item
		 * @param {Integer} queue [optional]
		 */
		History.back = function(queue){
			//History.debug('History.back: called', arguments);

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.back: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.back,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Make Busy + Continue
			History.busy(true);

			// Fix certain browser bugs that prevent the state from changing
			History.doubleCheck(function(){
				History.back(false);
			});

			// Go back
			history.go(-1);

			// End back closure
			return true;
		};

		/**
		 * History.forward(queue)
		 * Send the browser history forward one item
		 * @param {Integer} queue [optional]
		 */
		History.forward = function(queue){
			//History.debug('History.forward: called', arguments);

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.forward: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.forward,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Make Busy + Continue
			History.busy(true);

			// Fix certain browser bugs that prevent the state from changing
			History.doubleCheck(function(){
				History.forward(false);
			});

			// Go forward
			history.go(1);

			// End forward closure
			return true;
		};

		/**
		 * History.go(index,queue)
		 * Send the browser history back or forward index times
		 * @param {Integer} queue [optional]
		 */
		History.go = function(index,queue){
			//History.debug('History.go: called', arguments);

			// Prepare
			var i;

			// Handle
			if ( index > 0 ) {
				// Forward
				for ( i=1; i<=index; ++i ) {
					History.forward(queue);
				}
			}
			else if ( index < 0 ) {
				// Backward
				for ( i=-1; i>=index; --i ) {
					History.back(queue);
				}
			}
			else {
				throw new Error('History.go: History.go requires a positive or negative integer passed.');
			}

			// Chain
			return History;
		};


		// ====================================================================
		// HTML5 State Support

		// Non-Native pushState Implementation
		if ( History.emulated.pushState ) {
			/*
			 * Provide Skeleton for HTML4 Browsers
			 */

			// Prepare
			var emptyFunction = function(){};
			History.pushState = History.pushState||emptyFunction;
			History.replaceState = History.replaceState||emptyFunction;
		} // History.emulated.pushState

		// Native pushState Implementation
		else {
			/*
			 * Use native HTML5 History API Implementation
			 */

			/**
			 * History.onPopState(event,extra)
			 * Refresh the Current State
			 */
			History.onPopState = function(event,extra){
				// Prepare
				var stateId = false, newState = false, currentHash, currentState;

				// Reset the double check
				History.doubleCheckComplete();

				// Check for a Hash, and handle apporiatly
				currentHash = History.getHash();
				if ( currentHash ) {
					// Expand Hash
					currentState = History.extractState(currentHash||History.getLocationHref(),true);
					if ( currentState ) {
						// We were able to parse it, it must be a State!
						// Let's forward to replaceState
						//History.debug('History.onPopState: state anchor', currentHash, currentState);
						History.replaceState(currentState.data, currentState.title, currentState.url, false);
					}
					else {
						// Traditional Anchor
						//History.debug('History.onPopState: traditional anchor', currentHash);
						History.Adapter.trigger(window,'anchorchange');
						History.busy(false);
					}

					// We don't care for hashes
					History.expectedStateId = false;
					return false;
				}

				// Ensure
				stateId = History.Adapter.extractEventData('state',event,extra) || false;

				// Fetch State
				if ( stateId ) {
					// Vanilla: Back/forward button was used
					newState = History.getStateById(stateId);
				}
				else if ( History.expectedStateId ) {
					// Vanilla: A new state was pushed, and popstate was called manually
					newState = History.getStateById(History.expectedStateId);
				}
				else {
					// Initial State
					newState = History.extractState(History.getLocationHref());
				}

				// The State did not exist in our store
				if ( !newState ) {
					// Regenerate the State
					newState = History.createStateObject(null,null,History.getLocationHref());
				}

				// Clean
				History.expectedStateId = false;

				// Check if we are the same state
				if ( History.isLastSavedState(newState) ) {
					// There has been no change (just the page's hash has finally propagated)
					//History.debug('History.onPopState: no change', newState, History.savedStates);
					History.busy(false);
					return false;
				}

				// Store the State
				History.storeState(newState);
				History.saveState(newState);

				// Force update of the title
				History.setTitle(newState);

				// Fire Our Event
				History.Adapter.trigger(window,'statechange');
				History.busy(false);

				// Return true
				return true;
			};
			History.Adapter.bind(window,'popstate',History.onPopState);

			/**
			 * History.pushState(data,title,url)
			 * Add a new State to the history object, become it, and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.pushState = function(data,title,url,queue){
				//History.debug('History.pushState: called', arguments);

				// Check the State
				if ( History.getHashByUrl(url) && History.emulated.pushState ) {
					throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.pushState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.pushState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy + Continue
				History.busy(true);

				// Create the newState
				var newState = History.createStateObject(data,title,url);

				// Check it
				if ( History.isLastSavedState(newState) ) {
					// Won't be a change
					History.busy(false);
				}
				else {
					// Store the newState
					History.storeState(newState);
					History.expectedStateId = newState.id;

					// Push the newState
					history.pushState(newState.id,newState.title,newState.url);

					// Fire HTML5 Event
					History.Adapter.trigger(window,'popstate');
				}

				// End pushState closure
				return true;
			};

			/**
			 * History.replaceState(data,title,url)
			 * Replace the State and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.replaceState = function(data,title,url,queue){
				//History.debug('History.replaceState: called', arguments);

				// Check the State
				if ( History.getHashByUrl(url) && History.emulated.pushState ) {
					throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.replaceState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.replaceState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy + Continue
				History.busy(true);

				// Create the newState
				var newState = History.createStateObject(data,title,url);

				// Check it
				if ( History.isLastSavedState(newState) ) {
					// Won't be a change
					History.busy(false);
				}
				else {
					// Store the newState
					History.storeState(newState);
					History.expectedStateId = newState.id;

					// Push the newState
					history.replaceState(newState.id,newState.title,newState.url);

					// Fire HTML5 Event
					History.Adapter.trigger(window,'popstate');
				}

				// End replaceState closure
				return true;
			};

		} // !History.emulated.pushState


		// ====================================================================
		// Initialise

		/**
		 * Load the Store
		 */
		if ( sessionStorage ) {
			// Fetch
			try {
				History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
			}
			catch ( err ) {
				History.store = {};
			}

			// Normalize
			History.normalizeStore();
		}
		else {
			// Default Load
			History.store = {};
			History.normalizeStore();
		}

		/**
		 * Clear Intervals on exit to prevent memory leaks
		 */
		History.Adapter.bind(window,"unload",History.clearAllIntervals);

		/**
		 * Create the initial State
		 */
		History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));

		/**
		 * Bind for Saving Store
		 */
		if ( sessionStorage ) {
			// When the page is closed
			History.onUnload = function(){
				// Prepare
				var	currentStore, item, currentStoreString;

				// Fetch
				try {
					currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
				}
				catch ( err ) {
					currentStore = {};
				}

				// Ensure
				currentStore.idToState = currentStore.idToState || {};
				currentStore.urlToId = currentStore.urlToId || {};
				currentStore.stateToId = currentStore.stateToId || {};

				// Sync
				for ( item in History.idToState ) {
					if ( !History.idToState.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.idToState[item] = History.idToState[item];
				}
				for ( item in History.urlToId ) {
					if ( !History.urlToId.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.urlToId[item] = History.urlToId[item];
				}
				for ( item in History.stateToId ) {
					if ( !History.stateToId.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.stateToId[item] = History.stateToId[item];
				}

				// Update
				History.store = currentStore;
				History.normalizeStore();

				// In Safari, going into Private Browsing mode causes the
				// Session Storage object to still exist but if you try and use
				// or set any property/function of it it throws the exception
				// "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
				// add something to storage that exceeded the quota." infinitely
				// every second.
				currentStoreString = JSON.stringify(currentStore);
				try {
					// Store
					sessionStorage.setItem('History.store', currentStoreString);
				}
				catch (e) {
					if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
						if (sessionStorage.length) {
							// Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
							// removing/resetting the storage can work.
							sessionStorage.removeItem('History.store');
							sessionStorage.setItem('History.store', currentStoreString);
						} else {
							// Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
						}
					} else {
						throw e;
					}
				}
			};

			// For Internet Explorer
			History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));

			// For Other Browsers
			History.Adapter.bind(window,'beforeunload',History.onUnload);
			History.Adapter.bind(window,'unload',History.onUnload);

			// Both are enabled for consistency
		}

		// Non-Native pushState Implementation
		if ( !History.emulated.pushState ) {
			// Be aware, the following is only for native pushState implementations
			// If you are wanting to include something for all browsers
			// Then include it above this if block

			/**
			 * Setup Safari Fix
			 */
			if ( History.bugs.safariPoll ) {
				History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
			}

			/**
			 * Ensure Cross Browser Compatibility
			 */
			if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
				/**
				 * Fix Safari HashChange Issue
				 */

				// Setup Alias
				History.Adapter.bind(window,'hashchange',function(){
					History.Adapter.trigger(window,'popstate');
				});

				// Initialise Alias
				if ( History.getHash() ) {
					History.Adapter.onDomLoad(function(){
						History.Adapter.trigger(window,'hashchange');
					});
				}
			}

		} // !History.emulated.pushState


	}; // History.initCore

	// Try to Initialise History
	if (!History.options || !History.options.delayInit) {
		History.init();
	}

})(window);
(function() {
  var DOMParser;

  DOMParser = (function() {
    function DOMParser() {}

    DOMParser.prototype.parse = function(html) {
      return this._get_parser()(html);
    };

    DOMParser.prototype._get_parser = function() {
      return this._document_parser != null ? this._document_parser : this._document_parser = this._parser_factory();
    };

    DOMParser.prototype._parser_factory = function() {
      var create_document_using_DOM, create_document_using_parser, create_document_using_write, e, ref, testDoc;
      create_document_using_parser = function(html) {
        return (new DOMParser).parseFromString(html, 'text/html');
      };
      create_document_using_DOM = function(html) {
        var doc;
        doc = document.implementation.createHTMLDocument('');
        doc.documentElement.innerHTML = html;
        return doc;
      };
      create_document_using_write = function(html) {
        var doc;
        doc = document.implementation.createHTMLDocument('');
        doc.open('replace');
        doc.write(html);
        doc.close();
        return doc;
      };
      try {
        if (window.DOMParser) {
          testDoc = create_document_using_parser('<html><body><p>test');
          return create_document_using_parser;
        }
      } catch (error) {
        e = error;
        testDoc = create_document_using_DOM('<html><body><p>test');
        return create_document_using_DOM;
      } finally {
        if ((testDoc != null ? (ref = testDoc.body) != null ? ref.childNodes.length : void 0 : void 0) !== 1) {
          return create_document_using_write;
        }
      }
    };

    return DOMParser;

  })();

  if (window._Wiselinks == null) {
    window._Wiselinks = {};
  }

  window._Wiselinks.DOMParser = DOMParser;

}).call(this);
(function() {
  var Response;

  Response = (function() {
    Response._document_parser = null;

    Response._get_document_parser = function() {
      return Response._document_parser != null ? Response._document_parser : Response._document_parser = new window._Wiselinks.DOMParser;
    };

    function Response(html, xhr, $target) {
      this.html = html;
      this.xhr = xhr;
      this.$target = $target;
    }

    Response.prototype.url = function() {
      return this.xhr.getResponseHeader('X-Wiselinks-Url');
    };

    Response.prototype.assets_digest = function() {
      if (this._is_full_document_response()) {
        return $('meta[name="assets-digest"]', this._get_doc()).attr('content');
      } else {
        return this.xhr.getResponseHeader('X-Wiselinks-Assets-Digest');
      }
    };

    Response.prototype.content = function() {
      return this._content != null ? this._content : this._content = this._extract_content();
    };

    Response.prototype.title = function() {
      return this._title != null ? this._title : this._title = this._extract_title();
    };

    Response.prototype._extract_title = function() {
      if (this._is_full_document_response()) {
        return $('title', this._get_doc()).text();
      } else {
        return this.xhr.getResponseHeader('X-Wiselinks-Title');
      }
    };

    Response.prototype.description = function() {
      return this._description != null ? this._description : this._description = this._extract_description();
    };

    Response.prototype._extract_description = function() {
      if (this._is_full_document_response()) {
        return $('meta[name="description"]', this._get_doc()).text();
      } else {
        return this.xhr.getResponseHeader('X-Wiselinks-Description');
      }
    };

    Response.prototype.canonical = function() {
      return this._canonical != null ? this._canonical : this._canonical = this._extract_canonical();
    };

    Response.prototype._extract_canonical = function() {
      if (this._is_full_document_response()) {
        return $('link[rel="canonical"]', this._get_doc()).text();
      } else {
        return this.xhr.getResponseHeader('X-Wiselinks-Canonical');
      }
    };

    Response.prototype.robots = function() {
      return this._robots != null ? this._robots : this._robots = this._extract_robots();
    };

    Response.prototype._extract_robots = function() {
      if (this._is_full_document_response()) {
        return $('meta[name="robots"]', this._get_doc()).text();
      } else {
        return this.xhr.getResponseHeader('X-Wiselinks-Robots');
      }
    };

    Response.prototype.link_rel_prev = function() {
      return this._link_rel_prev != null ? this._link_rel_prev : this._link_rel_prev = this._extract_link_rel_prev();
    };

    Response.prototype._extract_link_rel_prev = function() {
      if (this._is_full_document_response()) {
        return $('link[rel="prev"]', this._get_doc()).text();
      } else {
        return this.xhr.getResponseHeader('X-Wiselinks-LinkRelPrev');
      }
    };

    Response.prototype.link_rel_next = function() {
      return this._link_rel_next != null ? this._link_rel_next : this._link_rel_next = this._extract_link_rel_next();
    };

    Response.prototype._extract_link_rel_next = function() {
      if (this._is_full_document_response()) {
        return $('link[rel="next"]', this._get_doc()).text();
      } else {
        return this.xhr.getResponseHeader('X-Wiselinks-LinkRelNext');
      }
    };

    Response.prototype._extract_content = function() {
      if (this._is_full_document_response()) {
        return this._get_doc_target_node().html();
      } else {
        return this.html;
      }
    };

    Response.prototype._is_full_document_response = function() {
      return this._get_doc_target_node().length === 1;
    };

    Response.prototype._get_doc_target_node = function() {
      return this.$doc_target_node != null ? this.$doc_target_node : this.$doc_target_node = $(this.$target.selector, this._get_doc());
    };

    Response.prototype._get_doc = function() {
      return this._doc != null ? this._doc : this._doc = Response._get_document_parser().parse(this.html);
    };

    return Response;

  })();

  if (window._Wiselinks == null) {
    window._Wiselinks = {};
  }

  window._Wiselinks.Response = Response;

}).call(this);
(function() {
  var RequestManager;

  RequestManager = (function() {
    function RequestManager(options) {
      this.options = options != null ? options : {};
    }

    RequestManager.prototype.call = function($target, state) {
      var self;
      self = this;
      if (this.redirected != null) {
        this.redirected = null;
        return;
      }
      self._loading($target, state);
      return $.ajax({
        url: state.url,
        headers: {
          'X-Wiselinks': state.data.render,
          'X-Wiselinks-Referer': state.data.referer
        },
        dataType: "html"
      }).done(function(data, status, xhr) {
        return self._html_loaded($target, data, status, xhr);
      }).fail(function(xhr, status, error) {
        return self._fail($target, status, state, error, xhr.status, xhr.responseText);
      }).always(function(data_or_xhr, status, xhr_or_error) {
        return self._always($target, status, state);
      });
    };

    RequestManager.prototype._normalize = function(url) {
      if (url == null) {
        return;
      }
      url = url.replace(/\/+$/, '');
      return url;
    };

    RequestManager.prototype._assets_changed = function(assets_digest) {
      return (this.options.assets_digest != null) && this.options.assets_digest !== assets_digest;
    };

    RequestManager.prototype._redirect_to = function(url, $target, state, xhr) {
      if (xhr && xhr.readyState < 4) {
        xhr.onreadystatechange = $.noop;
        xhr.abort();
      }
      this.redirected = true;
      $(document).trigger('page:redirected', [$target, state.data.render, url]);
      return History.replaceState(state.data, document.title, url);
    };

    RequestManager.prototype._loading = function($target, state) {
      return $(document).trigger('page:loading', [$target, state.data.render, decodeURI(state.url)]);
    };

    RequestManager.prototype._done = function($target, status, state, data) {
      return $(document).trigger('page:done', [$target, status, decodeURI(state.url), data]);
    };

    RequestManager.prototype._html_loaded = function($target, data, status, xhr) {
      var assets_digest, response, state, url;
      response = new window._Wiselinks.Response(data, xhr, $target);
      url = this._normalize(response.url());
      assets_digest = response.assets_digest();
      if (this._assets_changed(assets_digest)) {
        return window.location.reload(true);
      } else {
        state = History.getState();
        if ((url != null) && (url !== this._normalize(state.url))) {
          this._redirect_to(url, $target, state, xhr);
        }
        return $target.html(response.content()).promise().done((function(_this) {
          return function() {
            _this._title(response.title());
            _this._description(response.description());
            _this._canonical(response.canonical());
            _this._robots(response.robots());
            _this._link_rel_prev(response.link_rel_prev());
            _this._link_rel_next(response.link_rel_next());
            return _this._done($target, status, state, response.content());
          };
        })(this));
      }
    };

    RequestManager.prototype._fail = function($target, status, state, error, code, data) {
      return $(document).trigger('page:fail', [$target, status, decodeURI(state.url), error, code, data]);
    };

    RequestManager.prototype._always = function($target, status, state) {
      return $(document).trigger('page:always', [$target, status, decodeURI(state.url)]);
    };

    RequestManager.prototype._title = function(value) {
      if (value != null) {
        $(document).trigger('page:title', decodeURI(value));
        return document.title = decodeURI(value);
      }
    };

    RequestManager.prototype._description = function(value) {
      if (value != null) {
        $(document).trigger('page:description', decodeURI(value));
        return $('meta[name="description"]').attr('content', decodeURI(value));
      }
    };

    RequestManager.prototype._canonical = function(value) {
      if (value != null) {
        $(document).trigger('page:canonical', decodeURI(value));
        return $('link[rel="canonical"]').attr('href', decodeURI(value));
      }
    };

    RequestManager.prototype._robots = function(value) {
      if (value != null) {
        $(document).trigger('page:robots', decodeURI(value));
        return $('meta[name="robots"]').attr('content', decodeURI(value));
      }
    };

    RequestManager.prototype._link_rel_prev = function(value) {
      if (value != null) {
        $(document).trigger('page:link_rel_prev', decodeURI(value));
        return $('link[rel="prev"]').attr('href', decodeURI(value));
      }
    };

    RequestManager.prototype._link_rel_next = function(value) {
      if (value != null) {
        $(document).trigger('page:link_rel_next', decodeURI(value));
        return $('link[rel="next"]').attr('href', decodeURI(value));
      }
    };

    return RequestManager;

  })();

  if (window._Wiselinks === void 0) {
    window._Wiselinks = {};
  }

  window._Wiselinks.RequestManager = RequestManager;

}).call(this);
(function() {
  var Page;

  Page = (function() {
    function Page($target1, options) {
      var self;
      this.$target = $target1;
      this.options = options;
      self = this;
      this.template_id = new Date().getTime();
      this.request_manager = new _Wiselinks.RequestManager(this.options);
      this.$target = self._wrap(this.$target);
      self._try_target(this.$target);
      if (History.emulated.pushState && this.options.html4 === true) {
        if (window.location.href.indexOf('#.') === -1 && this.options.html4_normalize_path === true && window.location.pathname !== this.options.html4_root_path) {
          window.location.href = window.location.protocol + "//" + window.location.host + this.options.html4_root_path + "#." + window.location.pathname;
        }
      }
      History.Adapter.bind(window, "statechange", function(event, data) {
        var state;
        state = History.getState();
        if (self._template_id_changed(state)) {
          return self._call(self._reset_state(state));
        } else {
          return self._call(state);
        }
      });
      $(document).on('click', 'a[data-push], a[data-replace]', function(event) {
        var link;
        if ((link = new _Wiselinks.Link(self, $(this))).allows_process(event)) {
          event.preventDefault();
          link.process();
          return false;
        }
      });
      $(document).on('submit', 'form[data-push], form[data-replace]', function(event) {
        var form;
        if ((form = new _Wiselinks.Form(self, $(this)))) {
          event.preventDefault();
          form.process();
          return false;
        }
      });
    }

    Page.prototype.load = function(url, target, render) {
      var $target, selector;
      if (render == null) {
        render = 'template';
      }
      if (render !== 'partial') {
        this.template_id = new Date().getTime();
      }
      selector = target != null ? ($target = this._wrap(target), this._try_target($target), $target.selector) : void 0;
      return History.pushState({
        timestamp: new Date().getTime(),
        template_id: this.template_id,
        render: render,
        target: selector,
        referer: window.location.href
      }, document.title, url);
    };

    Page.prototype.reload = function() {
      return History.replaceState({
        timestamp: new Date().getTime(),
        template_id: this.template_id,
        render: 'template',
        referer: window.location.href
      }, document.title, History.getState().url);
    };

    Page.prototype._call = function(state) {
      var $target;
      $target = state.data.target != null ? $(state.data.target) : this.$target;
      return this.request_manager.call($target, state);
    };

    Page.prototype._template_id_changed = function(state) {
      return (state.data.template_id == null) || state.data.template_id !== this.template_id;
    };

    Page.prototype._make_state = function(url, target, render, referer) {
      if (render == null) {
        render = 'template';
      }
      return {
        url: url,
        data: {
          target: target,
          render: render,
          referer: referer
        }
      };
    };

    Page.prototype._reset_state = function(state) {
      if (state.data == null) {
        state.data = {};
      }
      state.data.target = null;
      state.data.render = 'template';
      return state;
    };

    Page.prototype._try_target = function($target) {
      if ($target.length === 0 && this.options.target_missing === 'exception') {
        throw new Error("[Wiselinks] Target missing: `" + $target.selector + "`");
      }
    };

    Page.prototype._wrap = function(object) {
      return $(object);
    };

    return Page;

  })();

  if (window._Wiselinks === void 0) {
    window._Wiselinks = {};
  }

  window._Wiselinks.Page = Page;

}).call(this);
(function() {
  var Link;

  Link = (function() {
    function Link(page, $link) {
      this.page = page;
      this.$link = $link;
    }

    Link.prototype.allows_process = function(event) {
      return !(this._cross_origin_link(event.currentTarget) || this._non_standard_click(event));
    };

    Link.prototype.process = function() {
      var type;
      type = this.$link.data('push') === 'partial' ? 'partial' : 'template';
      return this.page.load(this.$link.attr("href"), this.$link.data('target'), type);
    };

    Link.prototype._cross_origin_link = function(link) {
      return this._different_protocol(link) || this._different_host(link) || this._different_port(link);
    };

    Link.prototype._different_protocol = function(link) {
      if (link.protocol === ':' || link.protocol === '') {
        return false;
      }
      return location.protocol !== link.protocol;
    };

    Link.prototype._different_host = function(link) {
      if (link.host === '') {
        return false;
      }
      return location.host.split(':')[0] !== link.host.split(':')[0];
    };

    Link.prototype._different_port = function(link) {
      var port_equals;
      port_equals = (location.port === link.port) || (location.port === '' && (link.port === "80" || link.port === "443"));
      return !port_equals;
    };

    Link.prototype._non_standard_click = function(event) {
      return event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
    };

    return Link;

  })();

  if (window._Wiselinks === void 0) {
    window._Wiselinks = {};
  }

  window._Wiselinks.Link = Link;

}).call(this);
(function() {
  var Form;

  Form = (function() {
    function Form(page, $form) {
      this.page = page;
      this.$form = $form;
    }

    Form.prototype.process = function() {
      var self;
      self = this;
      if (self._include_blank_url_params()) {
        return self.page.load(self._url(), self._target(), self._type());
      } else {
        return self._without_blank_url_params(function() {
          return self.page.load(self._url(), self._target(), self._type());
        });
      }
    };

    Form.prototype._without_blank_url_params = function(callback) {
      var $disable, selector;
      selector = 'select:not(:disabled),input:not(:disabled)';
      $disable = this.$form.find(selector).filter(function() {
        return !$(this).val();
      });
      $disable.attr('disabled', true);
      callback();
      return $disable.attr('disabled', false);
    };

    Form.prototype._params = function() {
      var hash, i, item, len, name, ref;
      hash = {};
      ref = this.$form.serializeArray();
      for (i = 0, len = ref.length; i < len; i++) {
        item = ref[i];
        if (item.name !== 'utf8') {
          name = item.name.indexOf('[]', item.name.length - '[]'.length) !== -1 ? item.name.substr(0, item.name.length - 2) : item.name;
          if (hash[name] != null) {
            hash[name] = hash[name] + ("," + item.value);
          } else {
            hash[name] = item.value;
          }
        }
      }
      return hash;
    };

    Form.prototype._include_blank_url_params = function() {
      return this.$form.data('include-blank-url-params') === true;
    };

    Form.prototype._optimize_url_params = function() {
      return this.$form.data('optimize-url-params') !== false;
    };

    Form.prototype._type = function() {
      if (this.$form.data('push') === 'partial') {
        return 'partial';
      } else {
        return 'template';
      }
    };

    Form.prototype._target = function() {
      return this.$form.data('target');
    };

    Form.prototype._url = function() {
      var key, params, self, serialized, url, value;
      self = this;
      serialized = (function() {
        var ref;
        if (self._optimize_url_params()) {
          params = [];
          ref = this._params();
          for (key in ref) {
            value = ref[key];
            params.push(key + "=" + (encodeURIComponent(value).replace(/%2C/g, ',')));
          }
          return params.join('&');
        } else {
          return this.$form.serialize();
        }
      }).call(this);
      url = this.$form.attr("action").replace(/\?.*$/, '');
      if (serialized.length > 0) {
        url += "?" + serialized;
      }
      return url;
    };

    return Form;

  })();

  if (window._Wiselinks == null) {
    window._Wiselinks = {};
  }

  window._Wiselinks.Form = Form;

}).call(this);
(function() {
  var Wiselinks;

  Wiselinks = (function() {
    function Wiselinks($target, options) {
      if ($target == null) {
        $target = $('body');
      }
      this.options = options != null ? options : {};
      this._try_jquery();
      this.options = $.extend(this._defaults(), this.options);
      if (this.enabled()) {
        if (this.options.disable_suid) {
          History.options.disableSuid = true;
        }
        this.page = new _Wiselinks.Page($target, this.options);
      }
    }

    Wiselinks.prototype.enabled = function() {
      return !History.emulated.pushState || this.options.html4 === true;
    };

    Wiselinks.prototype.load = function(url, target, render) {
      if (render == null) {
        render = 'template';
      }
      return this.page.load(url, target, render);
    };

    Wiselinks.prototype.reload = function() {
      return this.page.reload();
    };

    Wiselinks.prototype._defaults = function() {
      return {
        disable_suid: true,
        html4: true,
        html4_root_path: '/',
        html4_normalize_path: true,
        target_missing: null,
        assets_digest: $("meta[name='assets-digest']").attr("content")
      };
    };

    Wiselinks.prototype._try_jquery = function() {
      if (window.jQuery == null) {
        throw new Error("[Wiselinks] jQuery is not loaded");
      }
    };

    return Wiselinks;

  })();

  window.Wiselinks = Wiselinks;

}).call(this);
var Pledge = function(url) {
  this.url = url;
}

Pledge.prototype.createPledge = function(){
  $.post(this.url, this.data(), null, 'script');
}

Pledge.prototype.data = function() {
  var amount = $("input[type='radio'][name='donation[donation_amount]']:checked").val();
  if (amount == '-1' ){
    amount = $("#donation_donation_amount_custom_amount").val();
  }
  return {
    pledge: {
      amount: amount,
      targetable_type: $("#donation_form_targetable_type").val(),
      targetable_id: $("#donation_form_targetable_id").val(),
    }
  }
}

$(document).ready(function() {
  $('#pledge_button').on('click', function(e){
    e.preventDefault();
    new Pledge($(this).data('url')).createPledge();
    return false;
  });
});
/*
	Redactor 10.2.5
	Updated: October 1, 2015

	http://imperavi.com/redactor/

	Copyright (c) 2009-2015, Imperavi LLC.
	License: http://imperavi.com/redactor/license/

	Usage: $('#content').redactor();
*/


(function($)
{

	'use strict';

	if (!Function.prototype.bind)
	{
		Function.prototype.bind = function(scope)
		{
			var fn = this;
			return function()
			{
				return fn.apply(scope);
			};
		};
	}

	var uuid = 0;

	// Plugin
	$.fn.redactor = function(options)
	{
		var val = [];
		var args = Array.prototype.slice.call(arguments, 1);

		if (typeof options === 'string')
		{
			this.each(function()
			{
				var instance = $.data(this, 'redactor');
				var func;

				if (options.search(/\./) != '-1')
				{
					func = options.split('.');
					if (typeof instance[func[0]] != 'undefined')
					{
						func = instance[func[0]][func[1]];
					}
				}
				else
				{
					func = instance[options];
				}

				if (typeof instance !== 'undefined' && $.isFunction(func))
				{
					var methodVal = func.apply(instance, args);
					if (methodVal !== undefined && methodVal !== instance)
					{
						val.push(methodVal);
					}
				}
				else
				{
					$.error('No such method "' + options + '" for Redactor');
				}
			});
		}
		else
		{
			this.each(function()
			{
				$.data(this, 'redactor', {});
				$.data(this, 'redactor', Redactor(this, options));
			});
		}

		if (val.length === 0) return this;
		else if (val.length === 1) return val[0];
		else return val;

	};

	// Initialization
	function Redactor(el, options)
	{
		return new Redactor.prototype.init(el, options);
	}

	// Functionality
	$.Redactor = Redactor;
	$.Redactor.VERSION = '10.2.5';
	$.Redactor.modules = ['alignment', 'autosave', 'block', 'buffer', 'build', 'button',
						  'caret', 'clean', 'code', 'core', 'dropdown', 'file', 'focus',
						  'image', 'indent', 'inline', 'insert', 'keydown', 'keyup',
						  'lang', 'line', 'link', 'linkify', 'list', 'modal', 'observe', 'paragraphize',
						  'paste', 'placeholder', 'progress', 'selection', 'shortcuts',
						  'tabifier', 'tidy',  'toolbar', 'upload', 'utils'];

	$.Redactor.opts = {

		// settings
		lang: 'en',
		direction: 'ltr', // ltr or rtl

		plugins: false, // array

		focus: false,
		focusEnd: false,

		placeholder: false,

		visual: true,
		tabindex: false,

		minHeight: false,
		maxHeight: false,

		linebreaks: false,
		replaceDivs: true,
		paragraphize: true,
		cleanStyleOnEnter: false,
		enterKey: true,

		cleanOnPaste: true,
		cleanSpaces: true,
		pastePlainText: false,

		autosave: false, // false or url
		autosaveName: false,
		autosaveInterval: 60, // seconds
		autosaveOnChange: false,
		autosaveFields: false,

		linkTooltip: true,
		linkProtocol: 'http',
		linkNofollow: false,
		linkSize: 50,

		imageEditable: true,
		imageLink: true,
		imagePosition: true,
		imageFloatMargin: '10px',
		imageResizable: true,

		imageUpload: null,
		imageUploadParam: 'file',

		uploadImageField: false,

		dragImageUpload: true,

		fileUpload: null,
		fileUploadParam: 'file',

		dragFileUpload: true,

		s3: false,

		convertLinks: true,
		convertUrlLinks: true,
		convertImageLinks: true,
		convertVideoLinks: false,

		preSpaces: 4, // or false
		tabAsSpaces: false, // true or number of spaces
		tabKey: true,

		scrollTarget: false,

		toolbar: true,
		toolbarFixed: true,
		toolbarFixedTarget: document,
		toolbarFixedTopOffset: 0, // pixels
		toolbarExternal: false, // ID selector
		toolbarOverflow: false,

		source: true,
		buttons: ['html', 'formatting', 'bold', 'italic', 'deleted', 'unorderedlist', 'orderedlist',
				  'outdent', 'indent', 'image', 'file', 'link', 'alignment', 'horizontalrule'], // + 'underline'

		buttonsHide: [],
		buttonsHideOnMobile: [],

		formatting: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
		formattingAdd: false,

		tabifier: true,

		deniedTags: ['script', 'style'],
		allowedTags: false, // or array

		paragraphizeBlocks: ['table', 'div', 'pre', 'form', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'dl', 'blockquote', 'figcaption',
							'address', 'section', 'header', 'footer', 'aside', 'article', 'object', 'style', 'script', 'iframe', 'select', 'input', 'textarea',
							'button', 'option', 'map', 'area', 'math', 'hr', 'fieldset', 'legend', 'hgroup', 'nav', 'figure', 'details', 'menu', 'summary', 'p'],

		removeComments: false,
		replaceTags: [
			['strike', 'del'],
			['b', 'strong']
		],
		replaceStyles: [
            ['font-weight:\\s?bold', "strong"],
            ['font-style:\\s?italic', "em"],
            ['text-decoration:\\s?underline', "u"],
            ['text-decoration:\\s?line-through', 'del']
        ],
        removeDataAttr: false,

		removeAttr: false, // or multi array
		allowedAttr: false, // or multi array

		removeWithoutAttr: ['span'], // or false
		removeEmpty: ['p'], // or false;

		activeButtons: ['deleted', 'italic', 'bold', 'underline', 'unorderedlist', 'orderedlist',
						'alignleft', 'aligncenter', 'alignright', 'justify'],
		activeButtonsStates: {
			b: 'bold',
			strong: 'bold',
			i: 'italic',
			em: 'italic',
			del: 'deleted',
			strike: 'deleted',
			ul: 'unorderedlist',
			ol: 'orderedlist',
			u: 'underline'
		},

		shortcuts: {
			'ctrl+shift+m, meta+shift+m': { func: 'inline.removeFormat' },
			'ctrl+b, meta+b': { func: 'inline.format', params: ['bold'] },
			'ctrl+i, meta+i': { func: 'inline.format', params: ['italic'] },
			'ctrl+h, meta+h': { func: 'inline.format', params: ['superscript'] },
			'ctrl+l, meta+l': { func: 'inline.format', params: ['subscript'] },
			'ctrl+k, meta+k': { func: 'link.show' },
			'ctrl+shift+7':   { func: 'list.toggle', params: ['orderedlist'] },
			'ctrl+shift+8':   { func: 'list.toggle', params: ['unorderedlist'] }
		},
		shortcutsAdd: false,

		// private
		buffer: [],
		rebuffer: [],
		emptyHtml: '<p>&#x200b;</p>',
		invisibleSpace: '&#x200b;',
		imageTypes: ['image/png', 'image/jpeg', 'image/gif'],
		indentValue: 20,
		verifiedTags: 		['a', 'img', 'b', 'strong', 'sub', 'sup', 'i', 'em', 'u', 'small', 'strike', 'del', 'cite', 'ul', 'ol', 'li'], // and for span tag special rule
		inlineTags: 		['strong', 'b', 'u', 'em', 'i', 'code', 'del', 'ins', 'samp', 'kbd', 'sup', 'sub', 'mark', 'var', 'cite', 'small'],
		alignmentTags: 		['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6',  'DL', 'DT', 'DD', 'DIV', 'TD', 'BLOCKQUOTE', 'OUTPUT', 'FIGCAPTION', 'ADDRESS', 'SECTION', 'HEADER', 'FOOTER', 'ASIDE', 'ARTICLE'],
		blockLevelElements: ['PRE', 'UL', 'OL', 'LI'],
		highContrast: false,
		observe: {
			dropdowns: []
		},

		// lang
		langs: {
			en: {
				html: 'HTML',
				video: 'Insert Video',
				image: 'Insert Image',
				table: 'Table',
				link: 'Link',
				link_insert: 'Insert link',
				link_edit: 'Edit link',
				unlink: 'Unlink',
				formatting: 'Formatting',
				paragraph: 'Normal text',
				quote: 'Quote',
				code: 'Code',
				header1: 'Header 1',
				header2: 'Header 2',
				header3: 'Header 3',
				header4: 'Header 4',
				header5: 'Header 5',
				bold: 'Bold',
				italic: 'Italic',
				fontcolor: 'Font Color',
				backcolor: 'Back Color',
				unorderedlist: 'Unordered List',
				orderedlist: 'Ordered List',
				outdent: 'Outdent',
				indent: 'Indent',
				cancel: 'Cancel',
				insert: 'Insert',
				save: 'Save',
				_delete: 'Delete',
				insert_table: 'Insert Table',
				insert_row_above: 'Add Row Above',
				insert_row_below: 'Add Row Below',
				insert_column_left: 'Add Column Left',
				insert_column_right: 'Add Column Right',
				delete_column: 'Delete Column',
				delete_row: 'Delete Row',
				delete_table: 'Delete Table',
				rows: 'Rows',
				columns: 'Columns',
				add_head: 'Add Head',
				delete_head: 'Delete Head',
				title: 'Title',
				image_position: 'Position',
				none: 'None',
				left: 'Left',
				right: 'Right',
				center: 'Center',
				image_web_link: 'Image Web Link',
				text: 'Text',
				mailto: 'Email',
				web: 'URL',
				video_html_code: 'Video Embed Code or Youtube/Vimeo Link',
				file: 'Insert File',
				upload: 'Upload',
				download: 'Download',
				choose: 'Choose',
				or_choose: 'Or choose',
				drop_file_here: 'Drop file here',
				align_left: 'Align text to the left',
				align_center: 'Center text',
				align_right: 'Align text to the right',
				align_justify: 'Justify text',
				horizontalrule: 'Insert Horizontal Rule',
				deleted: 'Deleted',
				anchor: 'Anchor',
				link_new_tab: 'Open link in new tab',
				underline: 'Underline',
				alignment: 'Alignment',
				filename: 'Name (optional)',
				edit: 'Edit',
				upload_label: 'Drop file here or '
			}
		},

		linkify: {
			regexps: {
				youtube: /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w.\-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig,
				vimeo: /https?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/,
				image: /((https?|www)[^\s]+\.)(jpe?g|png|gif)(\?[^\s-]+)?/ig,
				url: /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/ig,
			}
		},

		codemirror: false
	};

	// Functionality
	Redactor.fn = $.Redactor.prototype = {

		keyCode: {
			BACKSPACE: 8,
			DELETE: 46,
			UP: 38,
			DOWN: 40,
			ENTER: 13,
			SPACE: 32,
			ESC: 27,
			TAB: 9,
			CTRL: 17,
			META: 91,
			SHIFT: 16,
			ALT: 18,
			RIGHT: 39,
			LEFT: 37,
			LEFT_WIN: 91
		},

		// Initialization
		init: function(el, options)
		{
			this.$element = $(el);
			this.uuid = uuid++;

			// if paste event detected = true
			this.rtePaste = false;
			this.$pasteBox = false;

			this.loadOptions(options);
			this.loadModules();

			// formatting storage
			this.formatting = {};

			// block level tags
			$.merge(this.opts.blockLevelElements, this.opts.alignmentTags);
			this.reIsBlock = new RegExp('^(' + this.opts.blockLevelElements.join('|' ) + ')$', 'i');

			// setup allowed and denied tags
			this.tidy.setupAllowed();

			// setup denied tags
			if (this.opts.deniedTags !== false)
			{
				var tags = ['html', 'head', 'link', 'body', 'meta', 'applet'];
				for (var i = 0; i < tags.length; i++)
				{
					this.opts.deniedTags.push(tags[i]);
				}
			}

			// load lang
			this.lang.load();

			// extend shortcuts
			$.extend(this.opts.shortcuts, this.opts.shortcutsAdd);

			// start callback
			this.core.setCallback('start');

			// build
			this.start = true;
			this.build.run();
		},

		loadOptions: function(options)
		{
			this.opts = $.extend(
				{},
				$.extend(true, {}, $.Redactor.opts),
				this.$element.data(),
				options
			);
		},
		getModuleMethods: function(object)
		{
			return Object.getOwnPropertyNames(object).filter(function(property)
			{
				return typeof object[property] == 'function';
			});
		},
		loadModules: function()
		{
			var len = $.Redactor.modules.length;
			for (var i = 0; i < len; i++)
			{
				this.bindModuleMethods($.Redactor.modules[i]);
			}
		},
		bindModuleMethods: function(module)
		{
			if (typeof this[module] == 'undefined') return;

			// init module
			this[module] = this[module]();

			var methods = this.getModuleMethods(this[module]);
			var len = methods.length;

			// bind methods
			for (var z = 0; z < len; z++)
			{
				this[module][methods[z]] = this[module][methods[z]].bind(this);
			}
		},
		alignment: function()
		{
			return {
				left: function()
				{
					this.alignment.set('');
				},
				right: function()
				{
					this.alignment.set('right');
				},
				center: function()
				{
					this.alignment.set('center');
				},
				justify: function()
				{
					this.alignment.set('justify');
				},
				set: function(type)
				{
					// focus
					if (!this.utils.browser('msie') && !this.opts.linebreaks)
					{
						this.$editor.focus();
					}

					this.buffer.set();
					this.selection.save();

					// get blocks
					this.alignment.blocks = this.selection.getBlocks();
					this.alignment.type = type;

					// set alignment
					if (this.alignment.isLinebreaksOrNoBlocks())
					{
						this.alignment.setText();
					}
					else
					{
						this.alignment.setBlocks();
					}

					// sync
					this.selection.restore();
					this.code.sync();
				},
				setText: function()
				{
					var wrapper = this.selection.wrap('div');
					$(wrapper).attr('data-tagblock', 'redactor').css('text-align', this.alignment.type);
					// If the next tag is a <br>, we want to remove it b/c we're adding a <div>
					// We need two next() calls b/c the first will be the .redactor-selection-marker
					var nextTag = $(wrapper).next().next();
					if(nextTag.prop('tagName') == 'BR')
						nextTag.remove();
				},
				setBlocks: function()
				{
					$.each(this.alignment.blocks, $.proxy(function(i, el)
					{
						var $el = this.utils.getAlignmentElement(el);
						if (!$el) return;

						if (this.alignment.isNeedReplaceElement($el))
						{
							this.alignment.replaceElement($el);
						}
						else
						{
							this.alignment.alignElement($el);
						}

					}, this));
				},
				isLinebreaksOrNoBlocks: function()
				{
					return (this.opts.linebreaks && this.alignment.blocks[0] === false);
				},
				isNeedReplaceElement: function($el)
				{
					return (this.alignment.type === '' && typeof($el.data('tagblock')) !== 'undefined');
				},
				replaceElement: function($el)
				{
					$el.replaceWith($el.html());
				},
				alignElement: function($el)
				{
					$el.css('text-align', this.alignment.type);
					this.utils.removeEmptyAttr($el, 'style');
				}
			};
		},
		autosave: function()
		{
			return {
				html: false,
				enable: function()
				{
					if (!this.opts.autosave) return;

					this.autosave.name = (this.opts.autosaveName) ? this.opts.autosaveName : this.$textarea.attr('name');

					if (this.opts.autosaveOnChange) return;
					this.autosaveInterval = setInterval(this.autosave.load, this.opts.autosaveInterval * 1000);
				},
				onChange: function()
				{
					if (!this.opts.autosaveOnChange) return;
					this.autosave.load();
				},
				load: function()
				{
					if (!this.opts.autosave) return;

					this.autosave.source = this.code.get();

					if (this.autosave.html === this.autosave.source) return;

					// data
					var data = {};
					data['name'] = this.autosave.name;
					data[this.autosave.name] = this.autosave.source;
					data = this.autosave.getHiddenFields(data);

					// ajax
					var jsxhr = $.ajax({
						url: this.opts.autosave,
						type: 'post',
						data: data
					});

					jsxhr.done(this.autosave.success);
				},
				getHiddenFields: function(data)
				{
					if (this.opts.autosaveFields === false || typeof this.opts.autosaveFields !== 'object')
					{
						return data;
					}

					$.each(this.opts.autosaveFields, $.proxy(function(k, v)
					{
						if (v !== null && v.toString().indexOf('#') === 0) v = $(v).val();
						data[k] = v;

					}, this));

					return data;

				},
				success: function(data)
				{
					var json;
					try
					{
						json = $.parseJSON(data);
					}
					catch(e)
					{
						//data has already been parsed
						json = data;
					}

					var callbackName = (typeof json.error == 'undefined') ? 'autosave' :  'autosaveError';

					this.core.setCallback(callbackName, this.autosave.name, json);
					this.autosave.html = this.autosave.source;
				},
				disable: function()
				{
					clearInterval(this.autosaveInterval);
				}
			};
		},
		block: function()
		{
			return {
				formatting: function(name)
				{
					this.block.clearStyle = false;
					var type, value;

					if (typeof this.formatting[name].data != 'undefined') type = 'data';
					else if (typeof this.formatting[name].attr != 'undefined') type = 'attr';
					else if (typeof this.formatting[name]['class'] != 'undefined') type = 'class';

					if (typeof this.formatting[name].clear != 'undefined')
					{
						this.block.clearStyle = true;
					}

					if (type) value = this.formatting[name][type];

					this.block.format(this.formatting[name].tag, type, value);

				},
				format: function(tag, type, value)
				{
					if (tag == 'quote') tag = 'blockquote';

					var formatTags = ['p', 'pre', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
					if ($.inArray(tag, formatTags) == -1) return;

					this.block.isRemoveInline = (tag == 'pre' || tag.search(/h[1-6]/i) != -1);

					// focus
					if (!this.utils.browser('msie')) this.$editor.focus();

					var html = $.trim(this.$editor.html());
					this.block.isEmpty = this.utils.isEmpty(html);

					// FF focus
					if (this.utils.browser('mozilla') && !this.focus.isFocused())
					{
						if (this.block.isEmpty)
						{
							var $first;
							if (!this.opts.linebreaks)
							{
								$first = this.$editor.children().first();
								this.caret.setEnd($first);
							}
						}
					}

					this.block.blocks = this.selection.getBlocks();

					this.block.blocksSize = this.block.blocks.length;
					this.block.type = type;
					this.block.value = value;

					this.buffer.set();
					this.selection.save();

					this.block.set(tag);

					this.selection.restore();
					this.code.sync();
					this.observe.load();

				},
				set: function(tag)
				{
					this.selection.get();
					this.block.containerTag = this.range.commonAncestorContainer.tagName;

					if (this.range.collapsed)
					{
						this.block.setCollapsed(tag);
					}
					else
					{
						this.block.setMultiple(tag);
					}
				},
				setCollapsed: function(tag)
				{
					if (this.opts.linebreaks && this.block.isEmpty && tag != 'p')
					{
						var node = document.createElement(tag);
						this.$editor.html(node);
						this.caret.setEnd(node);

						return;
					}

					var block = this.block.blocks[0];
					if (block === false) return;

					if (block.tagName == 'LI')
					{
						if (tag != 'blockquote') return;

						this.block.formatListToBlockquote();
						return;
					}

					var isContainerTable = (this.block.containerTag  == 'TD' || this.block.containerTag  == 'TH');
					if (isContainerTable && !this.opts.linebreaks)
					{
						document.execCommand('formatblock', false, '<' + tag + '>');

						block = this.selection.getBlock();
						this.block.toggle($(block));

					}
					else if (block.tagName.toLowerCase() != tag)
					{
						if (this.opts.linebreaks && tag == 'p')
						{
							$(block).append('<br>');
							this.utils.replaceWithContents(block);
						}
						else
						{
							var $formatted = this.utils.replaceToTag(block, tag);

							this.block.toggle($formatted);

							if (tag != 'p' && tag != 'blockquote') $formatted.find('img').remove();
							if (this.block.isRemoveInline) this.utils.removeInlineTags($formatted);
							if (tag == 'p' || this.block.headTag) $formatted.find('p').contents().unwrap();

							this.block.formatTableWrapping($formatted);
						}
					}
					else if (tag == 'blockquote' && block.tagName.toLowerCase() == tag)
					{
						// blockquote off
						if (this.opts.linebreaks)
						{
							$(block).append('<br>');
							this.utils.replaceWithContents(block);
						}
						else
						{
							var $el = this.utils.replaceToTag(block, 'p');
							this.block.toggle($el);
						}
					}
					else if (block.tagName.toLowerCase() == tag)
					{
						this.block.toggle($(block));
					}


					if (typeof this.block.type == 'undefined' && typeof this.block.value == 'undefined')
					{
						$(block).removeAttr('class').removeAttr('style');
					}
				},
				setMultiple: function(tag)
				{
					var block = this.block.blocks[0];

					var isContainerTable = (this.block.containerTag  == 'TD' || this.block.containerTag  == 'TH');

					if (block !== false && this.block.blocksSize === 1)
					{
						if (block.tagName.toLowerCase() == tag &&  tag == 'blockquote')
						{
							// blockquote off
							if (this.opts.linebreaks)
							{
								$(block).append('<br>');
								this.utils.replaceWithContents(block);
							}
							else
							{
								var $el = this.utils.replaceToTag(block, 'p');
								this.block.toggle($el);
							}
						}
						else if (block.tagName == 'LI')
						{
							if (tag != 'blockquote') return;

							this.block.formatListToBlockquote();
						}
						else if (this.block.containerTag == 'BLOCKQUOTE')
						{
							this.block.formatBlockquote(tag);
						}
						else if (this.opts.linebreaks && ((isContainerTable) || (this.range.commonAncestorContainer != block)))
						{
							this.block.formatWrap(tag);
						}
						else
						{
							if (this.opts.linebreaks && tag == 'p')
							{
								$(block).append('<br>');
								this.utils.replaceWithContents(block);
							}
							else if (block.tagName === 'TD')
							{
								this.block.formatWrap(tag);
							}
							else
							{
								var $formatted = this.utils.replaceToTag(block, tag);

								this.block.toggle($formatted);

								if (this.block.isRemoveInline) this.utils.removeInlineTags($formatted);
								if (tag == 'p' || this.block.headTag) $formatted.find('p').contents().unwrap();
							}
						}
					}
					else
					{
						if (this.opts.linebreaks || tag != 'p')
						{
							if (tag == 'blockquote')
							{
								var count = 0;
								for (var i = 0; i < this.block.blocksSize; i++)
								{
									if (this.block.blocks[i].tagName == 'BLOCKQUOTE') count++;
								}

								// only blockquote selected
								if (count == this.block.blocksSize)
								{
									$.each(this.block.blocks, $.proxy(function(i,s)
									{
										var $formatted = false;
										if (this.opts.linebreaks)
										{
											$(s).prepend('<br>').append('<br>');
											$formatted = this.utils.replaceWithContents(s);
										}
										else
										{
											$formatted = this.utils.replaceToTag(s, 'p');
										}

										if ($formatted && typeof this.block.type == 'undefined' && typeof this.block.value == 'undefined')
										{
											$formatted.removeAttr('class').removeAttr('style');
										}

									}, this));

									return;
								}

							}

							this.block.formatWrap(tag);
						}
						else
						{
							var classSize = 0;
							var toggleType = false;
							if (this.block.type == 'class')
							{
								toggleType = 'toggle';
								classSize = $(this.block.blocks).filter('.' + this.block.value).length;

								if (this.block.blocksSize == classSize) toggleType = 'toggle';
								else if (this.block.blocksSize > classSize) toggleType = 'set';
								else if (classSize === 0) toggleType = 'set';

							}

							var exceptTags = ['ul', 'ol', 'li', 'td', 'th', 'dl', 'dt', 'dd'];
							$.each(this.block.blocks, $.proxy(function(i,s)
							{
								if ($.inArray(s.tagName.toLowerCase(), exceptTags) != -1) return;

								var $formatted = this.utils.replaceToTag(s, tag);

								if (toggleType)
								{
									if (toggleType == 'toggle') this.block.toggle($formatted);
									else if (toggleType == 'remove') this.block.remove($formatted);
									else if (toggleType == 'set') this.block.setForce($formatted);
								}
								else this.block.toggle($formatted);

								if (tag != 'p' && tag != 'blockquote') $formatted.find('img').remove();
								if (this.block.isRemoveInline) this.utils.removeInlineTags($formatted);
								if (tag == 'p' || this.block.headTag) $formatted.find('p').contents().unwrap();

								if (typeof this.block.type == 'undefined' && typeof this.block.value == 'undefined')
								{
									$formatted.removeAttr('class').removeAttr('style');
								}


							}, this));
						}
					}
				},
				setForce: function($el)
				{
					// remove style and class if the specified setting
					if (this.block.clearStyle)
					{
						$el.removeAttr('class').removeAttr('style');
					}

					if (this.block.type == 'class')
					{
						$el.addClass(this.block.value);
						return;
					}
					else if (this.block.type == 'attr' || this.block.type == 'data')
					{
						$el.attr(this.block.value.name, this.block.value.value);
						return;
					}
				},
				toggle: function($el)
				{
					// remove style and class if the specified setting
					if (this.block.clearStyle)
					{
						$el.removeAttr('class').removeAttr('style');
					}

					if (this.block.type == 'class')
					{
						$el.toggleClass(this.block.value);
						return;
					}
					else if (this.block.type == 'attr' || this.block.type == 'data')
					{
						if ($el.attr(this.block.value.name) == this.block.value.value)
						{
							$el.removeAttr(this.block.value.name);
						}
						else
						{
							$el.attr(this.block.value.name, this.block.value.value);
						}

						return;
					}
					else
					{
						$el.removeAttr('style class');
						return;
					}
				},
				remove: function($el)
				{
					$el.removeClass(this.block.value);
				},
				formatListToBlockquote: function()
				{
					var block = $(this.block.blocks[0]).closest('ul, ol', this.$editor[0]);

					$(block).find('ul, ol').contents().unwrap();
					$(block).find('li').append($('<br>')).contents().unwrap();

					var $el = this.utils.replaceToTag(block, 'blockquote');
					this.block.toggle($el);
				},
				formatBlockquote: function(tag)
				{
					document.execCommand('outdent');
					document.execCommand('formatblock', false, tag);

					this.clean.clearUnverified();
					this.$editor.find('p:empty').remove();

					var formatted = this.selection.getBlock();

					if (tag != 'p')
					{
						$(formatted).find('img').remove();
					}

					if (!this.opts.linebreaks)
					{
						this.block.toggle($(formatted));
					}

					this.$editor.find('ul, ol, tr, blockquote, p').each($.proxy(this.utils.removeEmpty, this));

					if (this.opts.linebreaks && tag == 'p')
					{
						this.utils.replaceWithContents(formatted);
					}

				},
				formatWrap: function(tag)
				{
					if (this.block.containerTag == 'UL' || this.block.containerTag == 'OL')
					{
						if (tag == 'blockquote')
						{
							this.block.formatListToBlockquote();
						}
						else
						{
							return;
						}
					}

					var formatted = this.selection.wrap(tag);
					if (formatted === false) return;

					var $formatted = $(formatted);

					this.block.formatTableWrapping($formatted);

					var $elements = $formatted.find(this.opts.blockLevelElements.join(',') + ', td, table, thead, tbody, tfoot, th, tr');

					$elements.contents().unwrap();

					if (tag != 'p' && tag != 'blockquote') $formatted.find('img').remove();

					$.each(this.block.blocks, $.proxy(this.utils.removeEmpty, this));

					$formatted.append(this.selection.getMarker(2));

					if (!this.opts.linebreaks)
					{
						this.block.toggle($formatted);
					}

					this.$editor.find('ul, ol, tr, blockquote, p').each($.proxy(this.utils.removeEmpty, this));
					$formatted.find('blockquote:empty').remove();

					if (this.block.isRemoveInline)
					{
						this.utils.removeInlineTags($formatted);
					}

					if (this.opts.linebreaks && tag == 'p')
					{
						this.utils.replaceWithContents($formatted);
					}

					if (this.opts.linebreaks)
					{
						var $next = $formatted.next().next();
						if ($next.size() != 0 && $next[0].tagName === 'BR')
						{
							$next.remove();
						}
					}



				},
				formatTableWrapping: function($formatted)
				{
					if ($formatted.closest('table', this.$editor[0]).length === 0) return;

					if ($formatted.closest('tr', this.$editor[0]).length === 0) $formatted.wrap('<tr>');
					if ($formatted.closest('td', this.$editor[0]).length === 0 && $formatted.closest('th').length === 0)
					{
						$formatted.wrap('<td>');
					}
				},
				removeData: function(name, value)
				{
					var blocks = this.selection.getBlocks();
					$(blocks).removeAttr('data-' + name);

					this.code.sync();
				},
				setData: function(name, value)
				{
					var blocks = this.selection.getBlocks();
					$(blocks).attr('data-' + name, value);

					this.code.sync();
				},
				toggleData: function(name, value)
				{
					var blocks = this.selection.getBlocks();
					$.each(blocks, function()
					{
						if ($(this).attr('data-' + name))
						{
							$(this).removeAttr('data-' + name);
						}
						else
						{
							$(this).attr('data-' + name, value);
						}
					});
				},
				removeAttr: function(attr, value)
				{
					var blocks = this.selection.getBlocks();
					$(blocks).removeAttr(attr);

					this.code.sync();
				},
				setAttr: function(attr, value)
				{
					var blocks = this.selection.getBlocks();
					$(blocks).attr(attr, value);

					this.code.sync();
				},
				toggleAttr: function(attr, value)
				{
					var blocks = this.selection.getBlocks();
					$.each(blocks, function()
					{
						if ($(this).attr(name))
						{
							$(this).removeAttr(name);
						}
						else
						{
							$(this).attr(name, value);
						}
					});
				},
				removeClass: function(className)
				{
					var blocks = this.selection.getBlocks();
					$(blocks).removeClass(className);

					this.utils.removeEmptyAttr(blocks, 'class');

					this.code.sync();
				},
				setClass: function(className)
				{
					var blocks = this.selection.getBlocks();
					$(blocks).addClass(className);

					this.code.sync();
				},
				toggleClass: function(className)
				{
					var blocks = this.selection.getBlocks();
					$(blocks).toggleClass(className);

					this.code.sync();
				}
			};
		},
		buffer: function()
		{
			return {
				set: function(type)
				{
					if (typeof type == 'undefined' || type == 'undo')
					{
						this.buffer.setUndo();
					}
					else
					{
						this.buffer.setRedo();
					}
				},
				setUndo: function()
				{
					this.selection.save();
					this.opts.buffer.push(this.$editor.html());
					this.selection.restore();
				},
				setRedo: function()
				{
					this.selection.save();
					this.opts.rebuffer.push(this.$editor.html());
					this.selection.restore();
				},
				getUndo: function()
				{
					this.$editor.html(this.opts.buffer.pop());
				},
				getRedo: function()
				{
					this.$editor.html(this.opts.rebuffer.pop());
				},
				add: function()
				{
					this.opts.buffer.push(this.$editor.html());
				},
				undo: function()
				{
					if (this.opts.buffer.length === 0) return;

					this.buffer.set('redo');
					this.buffer.getUndo();

					this.selection.restore();
					this.code.sync();

					setTimeout($.proxy(this.observe.load, this), 50);
				},
				redo: function()
				{
					if (this.opts.rebuffer.length === 0) return;

					this.buffer.set('undo');
					this.buffer.getRedo();

					this.selection.restore();
					this.code.sync();

					setTimeout($.proxy(this.observe.load, this), 50);
				}
			};
		},
		build: function()
		{
			return {
				focused: false,
				blured: true,
				run: function()
				{
					this.build.createContainerBox();
					this.build.loadContent();
					this.build.loadEditor();
					this.build.enableEditor();
					this.build.setCodeAndCall();
				},
				isTextarea: function()
				{
					return (this.$element[0].tagName === 'TEXTAREA');
				},
				createContainerBox: function()
				{
					this.$box = $('<div class="redactor-box" role="application" />');
				},
				createTextarea: function()
				{
					this.$textarea = $('<textarea />').attr('name', this.build.getTextareaName());
				},
				getTextareaName: function()
				{
					return ((typeof(name) == 'undefined')) ? 'content-' + this.uuid : this.$element.attr('id');
				},
				loadContent: function()
				{
					var func = (this.build.isTextarea()) ? 'val' : 'html';
					this.content = $.trim(this.$element[func]());
				},
				enableEditor: function()
				{
					this.$editor.attr({ 'contenteditable': true, 'dir': this.opts.direction });
				},
				loadEditor: function()
				{
					var func = (this.build.isTextarea()) ? 'fromTextarea' : 'fromElement';
					this.build[func]();
				},
				fromTextarea: function()
				{
					this.$editor = $('<div />');
					this.$textarea = this.$element;
					this.$box.insertAfter(this.$element).append(this.$editor).append(this.$element);
					this.$editor.addClass('redactor-editor');

					this.$element.hide();
				},
				fromElement: function()
				{
					this.$editor = this.$element;
					this.build.createTextarea();
					this.$box.insertAfter(this.$editor).append(this.$editor).append(this.$textarea);
					this.$editor.addClass('redactor-editor');

					this.$textarea.hide();
				},
				setCodeAndCall: function()
				{
					// set code
					this.code.set(this.content);

					this.build.setOptions();
					this.build.callEditor();

					// code mode
					if (this.opts.visual) return;
					setTimeout($.proxy(this.code.showCode, this), 200);
				},
				callEditor: function()
				{
					this.build.disableMozillaEditing();
					this.build.disableIeLinks();
					this.build.setEvents();
					this.build.setHelpers();

					// load toolbar
					if (this.opts.toolbar)
					{
						this.opts.toolbar = this.toolbar.init();
						this.toolbar.build();
					}

					// modal templates init
					this.modal.loadTemplates();

					// plugins
					this.build.plugins();

					// observers
					setTimeout($.proxy(this.observe.load, this), 4);

					// init callback
					this.core.setCallback('init');
				},
				setOptions: function()
				{
					// textarea direction
					$(this.$textarea).attr('dir', this.opts.direction);

					if (this.opts.linebreaks) this.$editor.addClass('redactor-linebreaks');

					if (this.opts.tabindex) this.$editor.attr('tabindex', this.opts.tabindex);

					if (this.opts.minHeight) this.$editor.css('minHeight', this.opts.minHeight);
					if (this.opts.maxHeight) this.$editor.css('maxHeight', this.opts.maxHeight);

				},
				setEventDropUpload: function(e)
				{
					e.preventDefault();

					if (!this.opts.dragImageUpload && !this.opts.dragFileUpload) return;
					if (this.opts.imageUpload === null && this.opts.fileUpload === null) return;

					var files = e.dataTransfer.files;
					this.upload.directUpload(files[0], e);
				},
				setEventDrop: function(e)
				{
					this.code.sync();
					setTimeout(this.clean.clearUnverified, 1);
					this.core.setCallback('drop', e);
				},
				setEvents: function()
				{
					// drop
					this.$editor.on('dragover.redactor dragenter.redactor', function(e)
					{
						e.preventDefault();
						e.stopPropagation();
				    });

					this.$editor.on('drop.redactor', $.proxy(function(e)
					{
						e = e.originalEvent || e;

						if (window.FormData === undefined || !e.dataTransfer) return true;

						if (e.dataTransfer.files.length === 0)
						{
							return this.build.setEventDrop(e);
						}
						else
						{
							this.build.setEventDropUpload(e);
						}

						setTimeout(this.clean.clearUnverified, 1);
						this.core.setCallback('drop', e);

					}, this));


					// click
					this.$editor.on('click.redactor', $.proxy(function(e)
					{
						var event = this.core.getEvent();
						var type = (event == 'click' || event == 'arrow') ? false : 'click';

						this.core.addEvent(type);
						this.utils.disableSelectAll();
						this.core.setCallback('click', e);

					}, this));

					// paste
					this.$editor.on('paste.redactor', $.proxy(this.paste.init, this));

					// cut
					this.$editor.on('cut.redactor', $.proxy(this.code.sync, this));

					// keydown
					this.$editor.on('keydown.redactor', $.proxy(this.keydown.init, this));

					// keyup
					this.$editor.on('keyup.redactor', $.proxy(this.keyup.init, this));

					// textarea keydown
					if ($.isFunction(this.opts.codeKeydownCallback))
					{
						this.$textarea.on('keydown.redactor-textarea', $.proxy(this.opts.codeKeydownCallback, this));
					}

					// textarea keyup
					if ($.isFunction(this.opts.codeKeyupCallback))
					{
						this.$textarea.on('keyup.redactor-textarea', $.proxy(this.opts.codeKeyupCallback, this));
					}

					// focus
					this.$editor.on('focus.redactor', $.proxy(function(e)
					{
						if ($.isFunction(this.opts.focusCallback))
						{
							this.core.setCallback('focus', e);
						}

						this.build.focused = true;
						this.build.blured = false;

						if (this.selection.getCurrent() === false)
						{
							this.selection.get();
							this.range.setStart(this.$editor[0], 0);
							this.range.setEnd(this.$editor[0], 0);
							this.selection.addRange();
						}


					}, this));


					// blur
					$(document).on('mousedown.redactor-blur.' + this.uuid, $.proxy(function(e)
					{
						if (this.start) return;
						if (this.rtePaste) return;

						if ($(e.target).closest('.redactor-editor, .redactor-toolbar, .redactor-dropdown').size() !== 0)
						{
							return;
						}

						this.utils.disableSelectAll();
						if (!this.build.blured && $.isFunction(this.opts.blurCallback))
						{
							this.core.setCallback('blur', e);
						}

						this.build.focused = false;
						this.build.blured = true;

					}, this));

				},
				setHelpers: function()
				{
					// linkify
					if (this.linkify.isEnabled())
					{
						this.linkify.format();
					}

					// placeholder
					this.placeholder.enable();

					// focus
					if (this.opts.focus) setTimeout(this.focus.setStart, 100);
					if (this.opts.focusEnd) setTimeout(this.focus.setEnd, 100);

				},
				plugins: function()
				{
					if (!this.opts.plugins) return;

					$.each(this.opts.plugins, $.proxy(function(i, s)
					{
						var func = (typeof RedactorPlugins !== 'undefined' && typeof RedactorPlugins[s] !== 'undefined') ? RedactorPlugins : Redactor.fn;

						if (!$.isFunction(func[s]))
						{
							return;
						}

						this[s] = func[s]();

						// get methods
						var methods = this.getModuleMethods(this[s]);
						var len = methods.length;

						// bind methods
						for (var z = 0; z < len; z++)
						{
							this[s][methods[z]] = this[s][methods[z]].bind(this);
						}

						if ($.isFunction(this[s].init))
						{
							this[s].init();
						}


					}, this));

				},
				disableMozillaEditing: function()
				{
					if (!this.utils.browser('mozilla')) return;

					// FF fix
					try {
						document.execCommand('enableObjectResizing', false, false);
						document.execCommand('enableInlineTableEditing', false, false);
					} catch (e) {}
				},
				disableIeLinks: function()
				{
					if (!this.utils.browser('msie')) return;

					// IE prevent converting links
					document.execCommand("AutoUrlDetect", false, false);
				}
			};
		},
		button: function()
		{
			return {
				build: function(btnName, btnObject)
				{
					var $button = $('<a href="#" class="re-icon re-' + btnName + '" rel="' + btnName + '" />').attr({'role': 'button', 'aria-label': btnObject.title, 'tabindex': '-1'});

					// click
					if (btnObject.func || btnObject.command || btnObject.dropdown)
					{
						this.button.setEvent($button, btnName, btnObject);
					}

					// dropdown
					if (btnObject.dropdown)
					{
						$button.addClass('redactor-toolbar-link-dropdown').attr('aria-haspopup', true);

						var $dropdown = $('<div class="redactor-dropdown redactor-dropdown-' + this.uuid + ' redactor-dropdown-box-' + btnName + '" style="display: none;">');
						$button.data('dropdown', $dropdown);
						this.dropdown.build(btnName, $dropdown, btnObject.dropdown);
					}

					// tooltip
					if (this.utils.isDesktop())
					{
						this.button.createTooltip($button, btnName, btnObject.title);
					}

					return $button;
				},
				setEvent: function($button, btnName, btnObject)
				{
					$button.on('touchstart click', $.proxy(function(e)
					{
						if ($button.hasClass('redactor-button-disabled')) return false;

						var type = 'func';
						var callback = btnObject.func;

						if (btnObject.command)
						{
							type = 'command';
							callback = btnObject.command;
						}
						else if (btnObject.dropdown)
						{
							type = 'dropdown';
							callback = false;
						}

						this.button.onClick(e, btnName, type, callback);

					}, this));
				},
				createTooltip: function($button, name, title)
				{
					var $tooltip = $('<span>').addClass('redactor-toolbar-tooltip redactor-toolbar-tooltip-' + this.uuid + ' redactor-toolbar-tooltip-' + name).hide().html(title);
					$tooltip.appendTo('body');

					$button.on('mouseover', function()
					{
						if ($(this).hasClass('redactor-button-disabled'))
						{
							return;
						}

						var pos = $button.offset();

						$tooltip.css({
							top: (pos.top + $button.innerHeight()) + 'px',
							left: (pos.left + $button.innerWidth()/2 - $tooltip.innerWidth()/2) + 'px'
						});
						$tooltip.show();

					});

					$button.on('mouseout', function()
					{
						$tooltip.hide();
					});

				},
				onClick: function(e, btnName, type, callback)
				{
					this.button.caretOffset = this.caret.getOffset();

					e.preventDefault();

					$(document).find('.redactor-toolbar-tooltip').hide();

					if (this.utils.browser('msie')) e.returnValue = false;

					if (type == 'command') this.inline.format(callback);
					else if (type == 'dropdown') this.dropdown.show(e, btnName);
					else this.button.onClickCallback(e, callback, btnName);
				},
				onClickCallback: function(e, callback, btnName)
				{
					var func;

					if ($.isFunction(callback)) callback.call(this, btnName);
					else if (callback.search(/\./) != '-1')
					{
						func = callback.split('.');
						if (typeof this[func[0]] == 'undefined') return;

						this[func[0]][func[1]](btnName);
					}
					else this[callback](btnName);

					this.observe.buttons(e, btnName);
				},
				get: function(key)
				{
					return this.$toolbar.find('a.re-' + key);
				},
				setActive: function(key)
				{
					this.button.get(key).addClass('redactor-act');
				},
				setInactive: function(key)
				{
					this.button.get(key).removeClass('redactor-act');
				},
				setInactiveAll: function(key)
				{
					if (typeof key === 'undefined')
					{
						this.$toolbar.find('a.re-icon').removeClass('redactor-act');
					}
					else
					{
						this.$toolbar.find('a.re-icon').not('.re-' + key).removeClass('redactor-act');
					}
				},
				setActiveInVisual: function()
				{
					this.$toolbar.find('a.re-icon').not('a.re-html, a.re-fullscreen').removeClass('redactor-button-disabled');
				},
				setInactiveInCode: function()
				{
					this.$toolbar.find('a.re-icon').not('a.re-html, a.re-fullscreen').addClass('redactor-button-disabled');
				},
				changeIcon: function(key, classname)
				{
					this.button.get(key).addClass('re-' + classname);
				},
				removeIcon: function(key, classname)
				{
					this.button.get(key).removeClass('re-' + classname);
				},
				setAwesome: function(key, name, text)
				{
					var $button = this.button.get(key);
					$button.removeClass('redactor-btn-image').addClass('fa-redactor-btn');
					$button.html('<i class="fa ' + name + '"></i> '+ '<span class="body-text">' + text + '</span>' );
				},
				addCallback: function($btn, callback)
				{
					if ($btn == "buffer") return;

					var type = (callback == 'dropdown') ? 'dropdown' : 'func';
					var key = $btn.attr('rel');
					$btn.on('touchstart click', $.proxy(function(e)
					{
						if ($btn.hasClass('redactor-button-disabled')) return false;
						this.button.onClick(e, key, type, callback);

					}, this));
				},
				addDropdown: function($btn, dropdown)
				{
					$btn.addClass('redactor-toolbar-link-dropdown').attr('aria-haspopup', true);

					var key = $btn.attr('rel');
					this.button.addCallback($btn, 'dropdown');

					var $dropdown = $('<div class="redactor-dropdown redactor-dropdown-' + this.uuid + ' redactor-dropdown-box-' + key + '" style="display: none;">');
					$btn.data('dropdown', $dropdown);

					// build dropdown
					if (dropdown) this.dropdown.build(key, $dropdown, dropdown);

					return $dropdown;
				},
				add: function(key, title)
				{
					if (!this.opts.toolbar) return;

					if (this.button.isMobileUndoRedo(key)) return "buffer";

					var btn = this.button.build(key, { title: title });
					btn.addClass('redactor-btn-image');

					this.$toolbar.append($('<li>').append(btn));

					return btn;
				},
				addFirst: function(key, title)
				{
					if (!this.opts.toolbar) return;

					if (this.button.isMobileUndoRedo(key)) return "buffer";

					var btn = this.button.build(key, { title: title });
					btn.addClass('redactor-btn-image');
					this.$toolbar.prepend($('<li>').append(btn));

					return btn;
				},
				addAfter: function(afterkey, key, title)
				{
					if (!this.opts.toolbar) return;

					if (this.button.isMobileUndoRedo(key)) return "buffer";

					var btn = this.button.build(key, { title: title });
					btn.addClass('redactor-btn-image');
					var $btn = this.button.get(afterkey);

					if ($btn.length !== 0) $btn.parent().after($('<li>').append(btn));
					else this.$toolbar.append($('<li>').append(btn));

					return btn;
				},
				addBefore: function(beforekey, key, title)
				{
					if (!this.opts.toolbar) return;

					if (this.button.isMobileUndoRedo(key)) return "buffer";

					var btn = this.button.build(key, { title: title });
					btn.addClass('redactor-btn-image');
					var $btn = this.button.get(beforekey);

					if ($btn.length !== 0) $btn.parent().before($('<li>').append(btn));
					else this.$toolbar.append($('<li>').append(btn));

					return btn;
				},
				remove: function(key)
				{
					this.button.get(key).remove();
				},
				isMobileUndoRedo: function(key)
				{
					return (key == "undo" || key == "redo") && !this.utils.isDesktop();
				}
			};
		},
		caret: function()
		{
			return {
				setStart: function(node)
				{
					// inline tag
					if (!this.utils.isBlock(node))
					{
						var space = this.utils.createSpaceElement();

						$(node).prepend(space);
						this.caret.setEnd(space);
					}
					else
					{
						this.caret.set(node, 0, node, 0);
					}
				},
				setEnd: function(node)
				{
					node = node[0] || node;
					if (node.lastChild.nodeType == 1)
					{
						return this.caret.setAfter(node.lastChild);
					}

					this.caret.set(node, 1, node, 1);

				},
				set: function(orgn, orgo, focn, foco)
				{
					// focus
					// disabled in 10.0.7
					// if (!this.utils.browser('msie')) this.$editor.focus();

					orgn = orgn[0] || orgn;
					focn = focn[0] || focn;

					if (this.utils.isBlockTag(orgn.tagName) && orgn.innerHTML === '')
					{
						orgn.innerHTML = this.opts.invisibleSpace;
					}

					if (orgn.tagName == 'BR' && this.opts.linebreaks === false)
					{
						var parent = $(this.opts.emptyHtml)[0];
						$(orgn).replaceWith(parent);
						orgn = parent;
						focn = orgn;
					}

					this.selection.get();

					try
					{
						this.range.setStart(orgn, orgo);
						this.range.setEnd(focn, foco);
					}
					catch (e) {}

					this.selection.addRange();
				},
				setAfter: function(node)
				{
					try
					{
						var tag = $(node)[0].tagName;

						// inline tag
						if (tag != 'BR' && !this.utils.isBlock(node))
						{
							var space = this.utils.createSpaceElement();

							$(node).after(space);
							this.caret.setEnd(space);
						}
						else
						{
							if (tag != 'BR' && this.utils.browser('msie'))
							{
								this.caret.setStart($(node).next());
							}
							else
							{
								this.caret.setAfterOrBefore(node, 'after');
							}
						}
					}
					catch (e)
					{
						var space = this.utils.createSpaceElement();
						$(node).after(space);
						this.caret.setEnd(space);
					}
				},
				setBefore: function(node)
				{
					// block tag
					if (this.utils.isBlock(node))
					{
						this.caret.setEnd($(node).prev());
					}
					else
					{
						this.caret.setAfterOrBefore(node, 'before');
					}
				},
				setAfterOrBefore: function(node, type)
				{
					// focus
					if (!this.utils.browser('msie')) this.$editor.focus();

					node = node[0] || node;

					this.selection.get();

					if (type == 'after')
					{
						try {

							this.range.setStartAfter(node);
							this.range.setEndAfter(node);
						}
						catch (e) {}
					}
					else
					{
						try {
							this.range.setStartBefore(node);
							this.range.setEndBefore(node);
						}
						catch (e) {}
					}


					this.range.collapse(false);
					this.selection.addRange();
				},
				getOffsetOfElement: function(node)
				{
					node = node[0] || node;

					this.selection.get();

					var cloned = this.range.cloneRange();
					cloned.selectNodeContents(node);
					cloned.setEnd(this.range.endContainer, this.range.endOffset);

					return $.trim(cloned.toString()).length;
				},
				getOffset: function()
				{
					var offset = 0;
				    var sel = window.getSelection();

				    if (sel.rangeCount > 0)
				    {
				        var range = window.getSelection().getRangeAt(0);
				        var caretRange = range.cloneRange();
				        caretRange.selectNodeContents(this.$editor[0]);
				        caretRange.setEnd(range.endContainer, range.endOffset);
				        offset = caretRange.toString().length;
				    }

					return offset;
				},
				setOffset: function(start, end)
				{
					if (typeof end == 'undefined') end = start;
					if (!this.focus.isFocused()) this.focus.setStart();

					var sel = this.selection.get();
					var node, offset = 0;
					var walker = document.createTreeWalker(this.$editor[0], NodeFilter.SHOW_TEXT, null, null);

					while (node = walker.nextNode())
					{
						offset += node.nodeValue.length;
						if (offset > start)
						{
							this.range.setStart(node, node.nodeValue.length + start - offset);
							start = Infinity;
						}

						if (offset >= end)
						{
							this.range.setEnd(node, node.nodeValue.length + end - offset);
							break;
						}
					}

					this.range.collapse(false);
					this.selection.addRange();
				},
				// deprecated
				setToPoint: function(start, end)
				{
					this.caret.setOffset(start, end);
				},
				getCoords: function()
				{
					return this.caret.getOffset();
				}
			};
		},
		clean: function()
		{
			return {
				onSet: function(html)
				{
					html = this.clean.savePreCode(html);

					// convert script tag
					html = html.replace(/<script(.*?[^>]?)>([\w\W]*?)<\/script>/gi, '<pre class="redactor-script-tag" style="display: none;" $1>$2</pre>');

					// replace dollar sign to entity
					html = html.replace(/\$/g, '&#36;');

					// replace special characters in links
					html = html.replace(/<a href="(.*?[^>]?)®(.*?[^>]?)">/gi, '<a href="$1&reg$2">');

					if (this.opts.replaceDivs && !this.opts.linebreaks) html = this.clean.replaceDivs(html);
					if (this.opts.linebreaks)  html = this.clean.replaceParagraphsToBr(html);

					// save form tag
					html = this.clean.saveFormTags(html);

					// convert font tag to span
					var $div = $('<div>');
					$div.html(html);
					var fonts = $div.find('font[style]');
					if (fonts.length !== 0)
					{
						fonts.replaceWith(function()
						{
							var $el = $(this);
							var $span = $('<span>').attr('style', $el.attr('style'));
							return $span.append($el.contents());
						});

						html = $div.html();
					}

					$div.remove();

					// remove font tag
					html = html.replace(/<font(.*?)>/gi, '');
					html = html.replace(/<\/font>/gi, '');

					// tidy html
					html = this.tidy.load(html);

					// paragraphize
					if (this.opts.paragraphize) html = this.paragraphize.load(html);

					// verified
					html = this.clean.setVerified(html);

					// convert inline tags
					html = this.clean.convertInline(html);

					html = html.replace(/&amp;/g, '&');

					return html;
				},
				onSync: function(html)
				{
					// remove spaces
					html = html.replace(/\u200B/g, '');
					html = html.replace(/&#x200b;/gi, '');

					if (this.opts.cleanSpaces)
					{
						html = html.replace(/&nbsp;/gi, ' ');
					}

					if (html.search(/^<p>(||\s||<br\s?\/?>||&nbsp;)<\/p>$/i) != -1)
					{
						return '';
					}

					// reconvert script tag
					html = html.replace(/<pre class="redactor-script-tag" style="display: none;"(.*?[^>]?)>([\w\W]*?)<\/pre>/gi, '<script$1>$2</script>');

					// restore form tag
					html = this.clean.restoreFormTags(html);

					var chars = {
						'\u2122': '&trade;',
						'\u00a9': '&copy;',
						'\u2026': '&hellip;',
						'\u2014': '&mdash;',
						'\u2010': '&dash;'
					};
					// replace special characters
					$.each(chars, function(i,s)
					{
						html = html.replace(new RegExp(i, 'g'), s);
					});

					// remove last br in FF
					if (this.utils.browser('mozilla'))
					{
						html = html.replace(/<br\s?\/?>$/gi, '');
					}

					// remove br in|of li tags
					html = html.replace(new RegExp('<br\\s?/?></li>', 'gi'), '</li>');
					html = html.replace(new RegExp('</li><br\\s?/?>', 'gi'), '</li>');

					// remove empty attributes
					html = html.replace(/<(.*?)rel="\s*?"(.*?[^>]?)>/gi, '<$1$2">');
					html = html.replace(/<(.*?)style="\s*?"(.*?[^>]?)>/gi, '<$1$2">');
					html = html.replace(/="">/gi, '>');
					html = html.replace(/""">/gi, '">');
					html = html.replace(/"">/gi, '">');

					// remove verified
					html = html.replace(/<div(.*?)data-tagblock="redactor"(.*?[^>])>/gi, '<div$1$2>');
					html = html.replace(/<(.*?) data-verified="redactor"(.*?[^>])>/gi, '<$1$2>');

					var $div = $("<div/>").html($.parseHTML(html, document, true));
					$div.find("span").removeAttr("rel");

					$div.find('pre .redactor-invisible-space').each(function()
					{
						$(this).contents().unwrap();
					});

					html = $div.html();

					// remove rel attribute from img
					html = html.replace(/<img(.*?[^>])rel="(.*?[^>])"(.*?[^>])>/gi, '<img$1$3>');
					html = html.replace(/<span class="redactor-invisible-space">(.*?)<\/span>/gi, '$1');

					html = html.replace(/ data-save-url="(.*?[^>])"/gi, '');

					// remove image resize
					html = html.replace(/<span(.*?)id="redactor-image-box"(.*?[^>])>([\w\W]*?)<img(.*?)><\/span>/gi, '$3<img$4>');
					html = html.replace(/<span(.*?)id="redactor-image-resizer"(.*?[^>])>(.*?)<\/span>/gi, '');
					html = html.replace(/<span(.*?)id="redactor-image-editter"(.*?[^>])>(.*?)<\/span>/gi, '');

					// remove font tag
					html = html.replace(/<font(.*?)>/gi, '');
					html = html.replace(/<\/font>/gi, '');

					// tidy html
					html = this.tidy.load(html);

					// link nofollow
					if (this.opts.linkNofollow)
					{
						html = html.replace(/<a(.*?)rel="nofollow"(.*?[^>])>/gi, '<a$1$2>');
						html = html.replace(/<a(.*?[^>])>/gi, '<a$1 rel="nofollow">');
					}

					// reconvert inline
					html = html.replace(/\sdata-redactor-(tag|class|style)="(.*?[^>])"/gi, '');
					html = html.replace(new RegExp('<(.*?) data-verified="redactor"(.*?[^>])>', 'gi'), '<$1$2>');
					html = html.replace(new RegExp('<(.*?) data-verified="redactor">', 'gi'), '<$1>');

					html = html.replace(/&amp;/g, '&');

					return html;
				},
				onPaste: function(html, setMode)
				{
					html = $.trim(html);
					html = html.replace(/\$/g, '&#36;');

					// convert dirty spaces
					html = html.replace(/<span class="s[0-9]">/gi, '<span>');
					html = html.replace(/<span class="Apple-converted-space">&nbsp;<\/span>/gi, ' ');
					html = html.replace(/<span class="Apple-tab-span"[^>]*>\t<\/span>/gi, '\t');
					html = html.replace(/<span[^>]*>(\s|&nbsp;)<\/span>/gi, ' ');

					if (this.opts.pastePlainText)
					{
						return this.clean.getPlainText(html);
					}

					if (!this.utils.isSelectAll() && typeof setMode == 'undefined')
					{
						if (this.utils.isCurrentOrParent(['FIGCAPTION', 'A']))
						{
							return this.clean.getPlainText(html, false);
						}

						if (this.utils.isCurrentOrParent('PRE'))
						{
							html = html.replace(/”/g, '"');
							html = html.replace(/“/g, '"');
							html = html.replace(/‘/g, '\'');
							html = html.replace(/’/g, '\'');

							return this.clean.getPreCode(html);
						}

						if (this.utils.isCurrentOrParent(['BLOCKQUOTE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6']))
						{
							html = this.clean.getOnlyImages(html);

							if (!this.utils.browser('msie'))
							{
								var block = this.selection.getBlock();
								if (block && block.tagName == 'P')
								{
									html = html.replace(/<img(.*?)>/gi, '<p><img$1></p>');
								}
							}

							return html;
						}

						if (this.utils.isCurrentOrParent(['TD']))
						{
							html = this.clean.onPasteTidy(html, 'td');

							if (this.opts.linebreaks) html = this.clean.replaceParagraphsToBr(html);

							html = this.clean.replaceDivsToBr(html);

							return html;
						}


						if (this.utils.isCurrentOrParent(['LI']))
						{
							return this.clean.onPasteTidy(html, 'li');
						}
					}


					html = this.clean.isSingleLine(html, setMode);

					if (!this.clean.singleLine)
					{
						if (this.opts.linebreaks)  html = this.clean.replaceParagraphsToBr(html);
						if (this.opts.replaceDivs) html = this.clean.replaceDivs(html);

						html = this.clean.saveFormTags(html);
					}


					html = this.clean.onPasteWord(html);
					html = this.clean.onPasteExtra(html);

					html = this.clean.onPasteTidy(html, 'all');


					// paragraphize
					if (!this.clean.singleLine && this.opts.paragraphize)
					{
						html = this.paragraphize.load(html);
					}

					html = this.clean.removeDirtyStyles(html);
					html = this.clean.onPasteRemoveSpans(html);
					html = this.clean.onPasteRemoveEmpty(html);


					html = this.clean.convertInline(html);

					return html;
				},
				onPasteWord: function(html)
				{
					// comments
					html = html.replace(/<!--[\s\S]*?-->/gi, '');

					// style
					html = html.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');

					// op
					html = html.replace(/<o\:p[^>]*>[\s\S]*?<\/o\:p>/gi, '');

					if (html.match(/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i))
					{
						// comments
						html = html.replace(/<!--[\s\S]+?-->/gi, '');

						// scripts
						html = html.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '');

						// Convert <s> into <strike>
						html = html.replace(/<(\/?)s>/gi, "<$1strike>");

						// Replace nbsp entites to char since it's easier to handle
						html = html.replace(/ /gi, ' ');

						// Convert <span style="mso-spacerun:yes">___</span> to string of alternating
						// breaking/non-breaking spaces of same length
						html = html.replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function(str, spaces) {
							return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : '';
						});

						html = this.clean.onPasteIeFixLinks(html);

						// shapes
						html = html.replace(/<img(.*?)v:shapes=(.*?)>/gi, '');
						html = html.replace(/src="file\:\/\/(.*?)"/, 'src=""');

						// lists
						var $div = $("<div/>").html(html);

						var lastList = false;
						var lastLevel = 1;
						var listsIds = [];

						$div.find("p[style]").each(function()
						{
							var matches = $(this).attr('style').match(/mso\-list\:l([0-9]+)\slevel([0-9]+)/);

							if (matches)
							{
								var currentList = parseInt(matches[1]);
								var currentLevel = parseInt(matches[2]);
								var listType = $(this).html().match(/^[\w]+\./) ? "ol" : "ul";

								var $li = $("<li/>").html($(this).html());

								$li.html($li.html().replace(/^([\w\.]+)</, '<'));
								$li.find("span:first").remove();

								if (currentLevel == 1 && $.inArray(currentList, listsIds) == -1)
								{
									var $list = $("<" + listType + "/>").attr({"data-level": currentLevel,
																			   "data-list": currentList})
																	  .html($li);

									$(this).replaceWith($list);

									lastList = currentList;
									listsIds.push(currentList);
								}
								else
								{
									if (currentLevel > lastLevel)
									{
										var $prevList = $div.find('[data-level="' + lastLevel + '"][data-list="' + lastList + '"]');

										var $lastList = $prevList;

										for(var i = lastLevel; i < currentLevel; i++)
										{
											$list = $("<" + listType + "/>");

											$list.appendTo($lastList.find("li").last());

											$lastList = $list;
										}

										$lastList.attr({"data-level": currentLevel,
														"data-list": currentList})
												 .html($li);

									}
									else
									{
										var $prevList = $div.find('[data-level="' + currentLevel + '"][data-list="' + currentList + '"]').last();

										$prevList.append($li);
									}

									lastLevel = currentLevel;
									lastList = currentList;

									$(this).remove();
								}
							}
						});

						$div.find('[data-level][data-list]').removeAttr('data-level data-list');
						html = $div.html();

						// remove ms word's bullet
						html = html.replace(/·/g, '');
						html = html.replace(/<p class="Mso(.*?)"/gi, '<p');

						// classes
						html = html.replace(/ class=\"(mso[^\"]*)\"/gi,	"");
						html = html.replace(/ class=(mso\w+)/gi, "");

						// remove ms word tags
						html = html.replace(/<o:p(.*?)>([\w\W]*?)<\/o:p>/gi, '$2');

						// ms word break lines
						html = html.replace(/\n/g, ' ');

						// ms word lists break lines
						html = html.replace(/<p>\n?<li>/gi, '<li>');
					}

					return html;
				},
				onPasteExtra: function(html)
				{
					// remove google docs markers
					html = html.replace(/<b\sid="internal-source-marker(.*?)">([\w\W]*?)<\/b>/gi, "$2");
					html = html.replace(/<b(.*?)id="docs-internal-guid(.*?)">([\w\W]*?)<\/b>/gi, "$3");

					// google docs styles
			 		html = html.replace(/<span[^>]*(font-style: italic; font-weight: bold|font-weight: bold; font-style: italic)[^>]*>/gi, '<span style="font-weight: bold;"><span style="font-style: italic;">');
			 		html = html.replace(/<span[^>]*font-style: italic[^>]*>/gi, '<span style="font-style: italic;">');
					html = html.replace(/<span[^>]*font-weight: bold[^>]*>/gi, '<span style="font-weight: bold;">');
					html = html.replace(/<span[^>]*text-decoration: underline[^>]*>/gi, '<span style="text-decoration: underline;">');

					html = html.replace(/<img>/gi, '');
					html = html.replace(/\n{3,}/gi, '\n');
					html = html.replace(/<font(.*?)>([\w\W]*?)<\/font>/gi, '$2');

					// remove dirty p
					html = html.replace(/<p><p>/gi, '<p>');
					html = html.replace(/<\/p><\/p>/gi, '</p>');
					html = html.replace(/<li>(\s*|\t*|\n*)<p>/gi, '<li>');
					html = html.replace(/<\/p>(\s*|\t*|\n*)<\/li>/gi, '</li>');

					// remove space between paragraphs
					html = html.replace(/<\/p>\s<p/gi, '<\/p><p');

					// remove safari local images
					html = html.replace(/<img src="webkit-fake-url\:\/\/(.*?)"(.*?)>/gi, '');

					// bullets
					html = html.replace(/<p>•([\w\W]*?)<\/p>/gi, '<li>$1</li>');

					// FF fix
					if (this.utils.browser('mozilla'))
					{
						html = html.replace(/<br\s?\/?>$/gi, '');
					}

					return html;
				},
				onPasteTidy: function(html, type)
				{
					// remove all tags except these
					var tags = ['span', 'a', 'pre', 'blockquote', 'small', 'em', 'strong', 'code', 'kbd', 'mark', 'address', 'cite', 'var', 'samp', 'dfn', 'sup', 'sub', 'b', 'i', 'u', 'del',
								'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'p', 'br', 'video', 'audio', 'iframe', 'embed', 'param', 'object', 'img', 'table',
								'td', 'th', 'tr', 'tbody', 'tfoot', 'thead', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
					var tagsEmpty = false;
					var attrAllowed =  [
							['a', '*'],
							['img', ['src', 'alt']],
							['span', ['class', 'rel', 'data-verified']],
							['iframe', '*'],
							['video', '*'],
							['audio', '*'],
							['embed', '*'],
							['object', '*'],
							['param', '*'],
							['source', '*']
						];

					if (type == 'all')
					{
						tagsEmpty = ['p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
						attrAllowed =  [
							['table', 'class'],
							['td', ['colspan', 'rowspan']],
							['a', '*'],
							['img', ['src', 'alt', 'data-redactor-inserted-image']],
							['span', ['class', 'rel', 'data-verified']],
							['iframe', '*'],
							['video', '*'],
							['audio', '*'],
							['embed', '*'],
							['object', '*'],
							['param', '*'],
							['source', '*']
						];
					}
					else if (type == 'td')
					{
						// remove all tags except these and remove all table tags: tr, td etc
						tags = ['ul', 'ol', 'li', 'span', 'a', 'small', 'em', 'strong', 'code', 'kbd', 'mark', 'cite', 'var', 'samp', 'dfn', 'sup', 'sub', 'b', 'i', 'u', 'del',
								'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'br', 'iframe', 'video', 'audio', 'embed', 'param', 'object', 'img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];

					}
					else if (type == 'li')
					{
						// only inline tags and ul, ol, li
						tags = ['ul', 'ol', 'li', 'span', 'a', 'small', 'em', 'strong', 'code', 'kbd', 'mark', 'cite', 'var', 'samp', 'dfn', 'sup', 'sub', 'b', 'i', 'u', 'del', 'br',
								'iframe', 'video', 'audio', 'embed', 'param', 'object', 'img'];
					}

					var options = {
						deniedTags: (this.opts.deniedTags) ? this.opts.deniedTags : false,
						allowedTags: (this.opts.allowedTags) ? this.opts.allowedTags : tags,
						removeComments: true,
						removePhp: true,
						removeAttr: (this.opts.removeAttr) ? this.opts.removeAttr : false,
						allowedAttr: (this.opts.allowedAttr) ? this.opts.allowedAttr : attrAllowed,
						removeEmpty: tagsEmpty
					};

					return this.tidy.load(html, options);
				},
				onPasteRemoveEmpty: function(html)
				{
					html = html.replace(/<(p|h[1-6])>(|\s|\n|\t|<br\s?\/?>)<\/(p|h[1-6])>/gi, '');

					// remove br in the end
					if (!this.opts.linebreaks) html = html.replace(/<br>$/i, '');

					return html;
				},
				onPasteRemoveSpans: function(html)
				{
					html = html.replace(/<span>(.*?)<\/span>/gi, '$1');
					html = html.replace(/<span[^>]*>\s|&nbsp;<\/span>/gi, ' ');

					return html;
				},
				onPasteIeFixLinks: function(html)
				{
					if (!this.utils.browser('msie')) return html;

					var tmp = $.trim(html);
					if (tmp.search(/^<a(.*?)>(.*?)<\/a>$/i) === 0)
					{
						html = html.replace(/^<a(.*?)>(.*?)<\/a>$/i, "$2");
					}

					return html;
				},
				isSingleLine: function(html, setMode)
				{
					this.clean.singleLine = false;

					if (!this.utils.isSelectAll() && typeof setMode == 'undefined')
					{
						var blocks = this.opts.blockLevelElements.join('|').replace('P|', '').replace('DIV|', '');

						var matchBlocks = html.match(new RegExp('</(' + blocks + ')>', 'gi'));
						var matchContainers = html.match(/<\/(p|div)>/gi);

						if (!matchBlocks && (matchContainers === null || (matchContainers && matchContainers.length <= 1)))
						{
							var matchBR = html.match(/<br\s?\/?>/gi);
							//var matchIMG = html.match(/<img(.*?[^>])>/gi);
							if (!matchBR)
							{
								this.clean.singleLine = true;
								html = html.replace(/<\/?(p|div)(.*?)>/gi, '');
							}
						}
					}

					return html;
				},
				stripTags: function(input, allowed)
				{
				    allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
				    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;

				    return input.replace(tags, function ($0, $1) {
				        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
				    });
				},
				savePreCode: function(html)
				{
					html = this.clean.savePreFormatting(html);
					html = this.clean.saveCodeFormatting(html);

					html = this.clean.restoreSelectionMarker(html);

					return html;
				},
				savePreFormatting: function(html)
				{
					var pre = html.match(/<pre(.*?)>([\w\W]*?)<\/pre>/gi);

					if (pre !== null)
					{
						$.each(pre, $.proxy(function(i,s)
						{
							var arr = s.match(/<pre(.*?)>([\w\W]*?)<\/pre>/i);

							arr[2] = arr[2].replace(/<br\s?\/?>/g, '\n');
							arr[2] = arr[2].replace(/&nbsp;/g, ' ');

							if (this.opts.preSpaces)
							{
								arr[2] = arr[2].replace(/\t/g, Array(this.opts.preSpaces + 1).join(' '));
							}

							arr[2] = this.clean.encodeEntities(arr[2]);

							// $ fix
							arr[2] = arr[2].replace(/\$/g, '&#36;');

							html = html.replace(s, '<pre' + arr[1] + '>' + arr[2] + '</pre>');

						}, this));
					}

					return html;
				},
				saveCodeFormatting: function(html)
				{
					var code = html.match(/<code(.*?)>([\w\W]*?)<\/code>/gi);

					if (code !== null)
					{
						$.each(code, $.proxy(function(i,s)
						{
							var arr = s.match(/<code(.*?)>([\w\W]*?)<\/code>/i);

							arr[2] = arr[2].replace(/&nbsp;/g, ' ');
							arr[2] = this.clean.encodeEntities(arr[2]);
							arr[2] = arr[2].replace(/\$/g, '&#36;');

							html = html.replace(s, '<code' + arr[1] + '>' + arr[2] + '</code>');
						}, this));
					}

					return html;
				},
				restoreSelectionMarker: function(html)
				{
					html = html.replace(/&lt;span id=&quot;selection-marker-([0-9])&quot; class=&quot;redactor-selection-marker&quot; data-verified=&quot;redactor&quot;&gt;​&lt;\/span&gt;/g, '<span id="selection-marker-$1" class="redactor-selection-marker" data-verified="redactor">​</span>');

					return html;
				},
				getTextFromHtml: function(html)
				{
					html = html.replace(/<br\s?\/?>|<\/H[1-6]>|<\/p>|<\/div>|<\/li>|<\/td>/gi, '\n');

					var tmp = document.createElement('div');
					tmp.innerHTML = html;
					html = tmp.textContent || tmp.innerText;

					return $.trim(html);
				},
				getPlainText: function(html, paragraphize)
				{
					html = this.clean.getTextFromHtml(html);
					html = html.replace(/\n\s*\n/g, "\n");
					html = html.replace(/\n\n/g, "\n");
					html = html.replace(/\n/g, '<br />');

					if (this.opts.paragraphize && typeof paragraphize == 'undefined' && !this.utils.browser('mozilla'))
					{
						html = this.paragraphize.load(html);
					}

					return html;
				},
				getPreCode: function(html)
				{
					html = html.replace(/<img(.*?) style="(.*?)"(.*?[^>])>/gi, '<img$1$3>');
					html = html.replace(/<img(.*?)>/gi, '&lt;img$1&gt;');
					html = this.clean.getTextFromHtml(html);

					if (this.opts.preSpaces)
					{
						html = html.replace(/\t/g, Array(this.opts.preSpaces + 1).join(' '));
					}

					html = this.clean.encodeEntities(html);

					return html;
				},
				getOnlyImages: function(html)
				{
					html = html.replace(/<img(.*?)>/gi, '[img$1]');

					// remove all tags
					html = html.replace(/<([Ss]*?)>/gi, '');

					html = html.replace(/\[img(.*?)\]/gi, '<img$1>');

					return html;
				},
				getOnlyLinksAndImages: function(html)
				{
					html = html.replace(/<a(.*?)href="(.*?)"(.*?)>([\w\W]*?)<\/a>/gi, '[a href="$2"]$4[/a]');
					html = html.replace(/<img(.*?)>/gi, '[img$1]');

					// remove all tags
					html = html.replace(/<(.*?)>/gi, '');

					html = html.replace(/\[a href="(.*?)"\]([\w\W]*?)\[\/a\]/gi, '<a href="$1">$2</a>');
					html = html.replace(/\[img(.*?)\]/gi, '<img$1>');

					return html;
				},
				encodeEntities: function(str)
				{
					str = String(str).replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"');
					return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
				},
				removeDirtyStyles: function(html)
				{
					if (this.utils.browser('msie')) return html;

					var div = document.createElement('div');
					div.innerHTML = html;

					this.clean.clearUnverifiedRemove($(div));

					html = div.innerHTML;
					$(div).remove();

					return html;
				},
				clearUnverified: function()
				{
					if (this.utils.browser('msie')) return;

					this.clean.clearUnverifiedRemove(this.$editor);

					// [DM-1449] These three lines caused styles applied to header tags to be
					// removed when backspace was clicked.  I believe it also has to do with
					// the change made in DM-1355.
					// var headers = this.$editor.find('h1, h2, h3, h4, h5, h6');
					// headers.find('span').removeAttr('style');
					// headers.find(this.opts.verifiedTags.join(', ')).removeAttr('style');

					this.code.sync();
				},
				clearUnverifiedRemove: function($editor)
				{
					$editor.find(this.opts.verifiedTags.join(', ')).removeAttr('style');
					$editor.find('span').not('[data-verified="redactor"]').removeAttr('style');

					$editor.find('span[data-verified="redactor"], img[data-verified="redactor"]').each(function(i, s)
					{
						var $s = $(s);
						$s.attr('style', $s.attr('rel'));
					});

				},
				cleanEmptyParagraph: function()
				{

				},
				setVerified: function(html)
				{
					if (this.utils.browser('msie')) return html;

					html = html.replace(new RegExp('<img(.*?[^>])>', 'gi'), '<img$1 data-verified="redactor">');
					html = html.replace(new RegExp('<span(.*?[^>])>', 'gi'), '<span$1 data-verified="redactor">');

					var matches = html.match(new RegExp('<(span|img)(.*?)style="(.*?)"(.*?[^>])>', 'gi'));

					if (matches)
					{
						var len = matches.length;
						for (var i = 0; i < len; i++)
						{
							try {

								var newTag = matches[i].replace(/style="(.*?)"/i, 'style="$1" rel="$1"');
								html = html.replace(matches[i], newTag);

							}
							catch (e) {}
						}
					}

					return html;
				},
				convertInline: function(html)
				{
					var $div = $('<div />').html(html);

					var tags = this.opts.inlineTags;
					tags.push('span');

					$div.find(tags.join(',')).each(function()
					{
						var $el = $(this);
						var tag = this.tagName.toLowerCase();
						$el.attr('data-redactor-tag', tag);

						if (tag == 'span')
						{
							if ($el.attr('style')) $el.attr('data-redactor-style', $el.attr('style'));
							else if ($el.attr('class')) $el.attr('data-redactor-class', $el.attr('class'));
						}

					});

					html = $div.html();
					$div.remove();

					return html;
				},
				normalizeLists: function()
				{
					this.$editor.find('li').each(function(i,s)
					{
						var $next = $(s).next();
						if ($next.length !== 0 && ($next[0].tagName == 'UL' || $next[0].tagName == 'OL'))
						{
							$(s).append($next);
						}

					});
				},
				removeSpaces: function(html)
				{
					html = html.replace(/\n/g, '');
					html = html.replace(/[\t]*/g, '');
					html = html.replace(/\n\s*\n/g, "\n");
					html = html.replace(/^[\s\n]*/g, ' ');
					html = html.replace(/[\s\n]*$/g, ' ');
					html = html.replace( />\s{2,}</g, '> <'); // between inline tags can be only one space
					html = html.replace(/\n\n/g, "\n");
					html = html.replace(/\u200B/g, '');

					return html;
				},
				replaceDivs: function(html)
				{
					if (this.opts.linebreaks)
					{
						html = html.replace(/<div><br\s?\/?><\/div>/gi, '<br />');
						html = html.replace(/<div(.*?)>([\w\W]*?)<\/div>/gi, '$2<br />');
					}
					else
					{
						html = html.replace(/<div(.*?)>([\w\W]*?)<\/div>/gi, '<p$1>$2</p>');
					}

					html = html.replace(/<div(.*?[^>])>/gi, '');
					html = html.replace(/<\/div>/gi, '');

					return html;
				},
				replaceDivsToBr: function(html)
				{
					html = html.replace(/<div\s(.*?)>/gi, '<p>');
					html = html.replace(/<div><br\s?\/?><\/div>/gi, '<br /><br />');
					html = html.replace(/<div>([\w\W]*?)<\/div>/gi, '$1<br /><br />');

					return html;
				},
				replaceParagraphsToBr: function(html)
				{
					html = html.replace(/<p\s(.*?)>/gi, '<p>');
					html = html.replace(/<p><br\s?\/?><\/p>/gi, '<br />');
					html = html.replace(/<p>([\w\W]*?)<\/p>/gi, '$1<br /><br />');
					html = html.replace(/(<br\s?\/?>){1,}\n?<\/blockquote>/gi, '</blockquote>');

					return html;
				},
				saveFormTags: function(html)
				{
					return html.replace(/<form(.*?)>([\w\W]*?)<\/form>/gi, '<section$1 rel="redactor-form-tag">$2</section>');
				},
				restoreFormTags: function(html)
				{
					return html.replace(/<section(.*?) rel="redactor-form-tag"(.*?)>([\w\W]*?)<\/section>/gi, '<form$1$2>$3</form>');
				}
			};
		},
		code: function()
		{
			return {
				set: function(html)
				{
					html = $.trim(html.toString());

					// clean
					html = this.clean.onSet(html);


					if (this.utils.browser('msie'))
					{
						html = html.replace(/<span(.*?)id="selection-marker-(1|2)"(.*?)><\/span>/gi, '');
					}

					this.$editor.html(html);
					this.code.sync();

					if (html !== '') this.placeholder.remove();

					setTimeout($.proxy(this.buffer.add, this), 15);
					if (this.start === false) this.observe.load();

				},
				get: function()
				{
					var code = this.$textarea.val();

					if (this.opts.replaceDivs) code = this.clean.replaceDivs(code);
					if (this.opts.linebreaks) code = this.clean.replaceParagraphsToBr(code);

					// indent code
					code = this.tabifier.get(code);

					return code;
				},
				sync: function()
				{
					setTimeout($.proxy(this.code.startSync, this), 10);
				},
				startSync: function()
				{
					var html = this.$editor.html();

					// is there a need to synchronize
					if (this.code.syncCode && this.code.syncCode == html || (this.start && html == '' ))
					{
						// do not sync
						return;
					}

					// save code
					this.code.syncCode = html;

					// before clean callback
					html = this.core.setCallback('syncBefore', html);

					// clean
					html = this.clean.onSync(html);

					// set code
					this.$textarea.val(html);

					// after sync callback
					this.core.setCallback('sync', html);

					if (this.start === false)
					{
						this.core.setCallback('change', html);
					}

					this.start = false;

					if (this.autosave.html == false)
					{
						this.autosave.html = this.code.get();
					}

					if (this.opts.codemirror)
					{
						this.$textarea.next('.CodeMirror').each(function(i, el)
						{
							el.CodeMirror.setValue(html);
						});
					}

					//autosave
					this.autosave.onChange();
					this.autosave.enable();
				},
				toggle: function()
				{
					if (this.opts.visual)
					{
						this.code.showCode();
					}
					else
					{
						this.code.showVisual();
					}
				},
				showCode: function()
				{
					this.selection.save();

					this.code.offset = this.caret.getOffset();
					var scroll = $(window).scrollTop();

					var	width = this.$editor.innerWidth(),
						height = this.$editor.innerHeight();

					this.$editor.hide();

					var html = this.$textarea.val();

					this.modified = this.clean.removeSpaces(html);

					// indent code
					html = this.tabifier.get(html);

					// caret position sync
					var start = 0, end = 0;
					var $editorDiv = $("<div/>").append($.parseHTML(this.clean.onSync(this.$editor.html()), document, true));
					var $selectionMarkers = $editorDiv.find("span.redactor-selection-marker");

					if ($selectionMarkers.length > 0)
					{
						var editorHtml = this.tabifier.get($editorDiv.html()).replace(/&amp;/g, '&');

						if ($selectionMarkers.length == 1)
						{
							start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML"));
							end   = start;
						}
						else if ($selectionMarkers.length == 2)
						{
							start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML"));
							end	 = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-2").prop("outerHTML")) - $editorDiv.find("#selection-marker-1").prop("outerHTML").toString().length;
						}
					}

					this.selection.removeMarkers();
					this.$textarea.val(html);

					if (this.opts.codemirror)
					{
						this.$textarea.next('.CodeMirror').each(function(i, el)
						{
							$(el).show();
							el.CodeMirror.setValue(html);
							el.CodeMirror.setSize('100%', height);
							el.CodeMirror.refresh();

							if (start == end)
							{
								el.CodeMirror.setCursor(el.CodeMirror.posFromIndex(start).line, el.CodeMirror.posFromIndex(end).ch);
							}
							else
							{
								el.CodeMirror.setSelection({line: el.CodeMirror.posFromIndex(start).line,
															ch: el.CodeMirror.posFromIndex(start).ch},
														  {line: el.CodeMirror.posFromIndex(end).line,
														   ch:  el.CodeMirror.posFromIndex(end).ch});
							}

							el.CodeMirror.focus();
						});
					}
					else
					{
						this.$textarea.height(height).show().focus();
						this.$textarea.on('keydown.redactor-textarea-indenting', this.code.textareaIndenting);

						$(window).scrollTop(scroll);

						if (this.$textarea[0].setSelectionRange)
						{
							this.$textarea[0].setSelectionRange(start, end);
						}

						this.$textarea[0].scrollTop = 0;
					}

					this.opts.visual = false;

					this.button.setInactiveInCode();
					this.button.setActive('html');
					this.core.setCallback('source', html);
				},
				showVisual: function()
				{
					var html;

					if (this.opts.visual) return;

					var start = 0, end = 0;

					if (this.opts.codemirror)
					{
						var selection;

						this.$textarea.next('.CodeMirror').each(function(i, el)
						{
							selection = el.CodeMirror.listSelections();

							start = el.CodeMirror.indexFromPos(selection[0].anchor);
							end = el.CodeMirror.indexFromPos(selection[0].head);

							html = el.CodeMirror.getValue();
						});
					}
					else
					{
						start = this.$textarea.get(0).selectionStart;
						end = this.$textarea.get(0).selectionEnd;

						html = this.$textarea.hide().val();
					}

					// if selection starts from end
					if (start > end && end > 0)
					{
						var tempStart = end;
						var tempEnd = start;

						start = tempStart;
						end = tempEnd;
					}

					start = this.code.enlargeOffset(html, start);
					end = this.code.enlargeOffset(html, end);

					html = html.substr(0, start) + this.selection.getMarkerAsHtml(1) + html.substr(start);

					if (end > start)
					{
						var markerLength = this.selection.getMarkerAsHtml(1).toString().length;

						html = html.substr(0, end + markerLength) + this.selection.getMarkerAsHtml(2) + html.substr(end + markerLength);
					}



					if (this.modified !== this.clean.removeSpaces(html))
					{
						this.code.set(html);

					}

					if (this.opts.codemirror)
					{
						this.$textarea.next('.CodeMirror').hide();
					}

					this.$editor.show();

					if (!this.utils.isEmpty(html))
					{
						this.placeholder.remove();
					}

					this.selection.restore();

					this.$textarea.off('keydown.redactor-textarea-indenting');

					this.button.setActiveInVisual();
					this.button.setInactive('html');
					this.observe.load();
					this.opts.visual = true;
					this.core.setCallback('visual', html);
				},
				textareaIndenting: function(e)
				{
					if (e.keyCode !== 9) return true;

					var $el = this.$textarea;
					var start = $el.get(0).selectionStart;
					$el.val($el.val().substring(0, start) + "\t" + $el.val().substring($el.get(0).selectionEnd));
					$el.get(0).selectionStart = $el.get(0).selectionEnd = start + 1;

					return false;
				},
				enlargeOffset: function(html, offset)
				{
					var htmlLength = html.length;
					var c = 0;

					if (html[offset] == '>')
					{
						c++;
					}
					else
					{
						for(var i = offset; i <= htmlLength; i++)
						{
							c++;

							if (html[i] == '>')
							{
								break;
							}
							else if (html[i] == '<' || i == htmlLength)
							{
								c = 0;
								break;
							}
						}
					}

					return offset + c;
				}
			};
		},
		core: function()
		{
			return {
				getObject: function()
				{
					return $.extend({}, this);
				},
				getEditor: function()
				{
					return this.$editor;
				},
				getBox: function()
				{
					return this.$box;
				},
				getElement: function()
				{
					return this.$element;
				},
				getTextarea: function()
				{
					return this.$textarea;
				},
				getToolbar: function()
				{
					return (this.$toolbar) ? this.$toolbar : false;
				},
				addEvent: function(name)
				{
					this.core.event = name;
				},
				getEvent: function()
				{
					return this.core.event;
				},
				setCallback: function(type, e, data)
				{
					var eventName = type + 'Callback';
					var eventNamespace = 'redactor';
					var callback = this.opts[eventName];

					if (this.$textarea)
					{
						var returnValue = false;
						var events = $._data(this.$textarea[0], 'events');

						if (typeof events != 'undefined' && typeof events[eventName] != 'undefined')
						{
							$.each(events[eventName], $.proxy(function(key, value)
							{
								if (value['namespace'] == eventNamespace)
								{
									var data = (typeof data == 'undefined') ? [e] : [e, data];

									returnValue = (typeof data == 'undefined') ? value.handler.call(this, e) : value.handler.call(this, e, data);
								}
							}, this));
						}

						if (returnValue) return returnValue;
					}

					if ($.isFunction(callback))
					{
						return (typeof data == 'undefined') ? callback.call(this, e) : callback.call(this, e, data);
					}
					else
					{
						return (typeof data == 'undefined') ? e : data;
					}
				},
				destroy: function()
				{
					this.opts.destroyed = true;

					this.core.setCallback('destroy');

					// off events and remove data
					this.$element.off('.redactor').removeData('redactor');
					this.$editor.off('.redactor');

					$(document).off('mousedown.redactor-blur.' + this.uuid);
					$(document).off('mousedown.redactor.' + this.uuid);
					$(document).off('click.redactor-image-delete.' + this.uuid);
					$(document).off('click.redactor-image-resize-hide.' + this.uuid);
					$(document).off('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid);
					$("body").off('scroll.redactor.' + this.uuid);
					$(this.opts.toolbarFixedTarget).off('scroll.redactor.' + this.uuid);

					// common
					this.$editor.removeClass('redactor-editor redactor-linebreaks redactor-placeholder');
					this.$editor.removeAttr('contenteditable');

					var html = this.code.get();

					if (this.opts.toolbar)
					{
						// dropdowns off
						this.$toolbar.find('a').each(function()
						{
							var $el = $(this);
							if ($el.data('dropdown'))
							{
								$el.data('dropdown').remove();
								$el.data('dropdown', {});
							}
						});
					}

					if (this.build.isTextarea())
					{
						this.$box.after(this.$element);
						this.$box.remove();
						this.$element.val(html).show();
					}
					else
					{
						this.$box.after(this.$editor);
						this.$box.remove();
						this.$element.html(html).show();
					}

					// paste box
					if (this.$pasteBox) this.$pasteBox.remove();

					// modal
					if (this.$modalBox) this.$modalBox.remove();
					if (this.$modalOverlay) this.$modalOverlay.remove();

					// buttons tooltip
					$('.redactor-toolbar-tooltip-' + this.uuid).remove();

					// autosave
					clearInterval(this.autosaveInterval);
				}
			};
		},
		dropdown: function()
		{
			return {
				build: function(name, $dropdown, dropdownObject)
				{
					if (name == 'formatting' && this.opts.formattingAdd)
					{
						$.each(this.opts.formattingAdd, $.proxy(function(i,s)
						{
							var name = s.tag,
								func;

							if (typeof s['class'] != 'undefined')
							{
								name = name + '-' + s['class'];
							}

							s.type = (this.utils.isBlockTag(s.tag)) ? 'block' : 'inline';

							if (typeof s.func !== "undefined")
							{
								func = s.func;
							}
							else
							{
								func = (s.type == 'inline') ? 'inline.formatting' : 'block.formatting';
							}

							if (this.opts.linebreaks && s.type == 'block' && s.tag == 'p') return;

							this.formatting[name] = {
								tag: s.tag,
								style: s.style,
								'class': s['class'],
								attr: s.attr,
								data: s.data,
								clear: s.clear
							};

							dropdownObject[name] = {
								func: func,
								title: s.title
							};

						}, this));
					}

					$.each(dropdownObject, $.proxy(function(btnName, btnObject)
					{
						var $item = $('<a href="#" class="redactor-dropdown-' + btnName + '" role="button">' + btnObject.title + '</a>');
						if (name == 'formatting') $item.addClass('redactor-formatting-' + btnName);

						$item.on('click', $.proxy(function(e)
						{
							e.preventDefault();

							var type = 'func';
							var callback = btnObject.func;
							if (btnObject.command)
							{
								type = 'command';
								callback = btnObject.command;
							}
							else if (btnObject.dropdown)
							{
								type = 'dropdown';
								callback = btnObject.dropdown;
							}

							if ($(e.target).hasClass('redactor-dropdown-link-inactive')) return;

							this.button.onClick(e, btnName, type, callback);
							this.dropdown.hideAll();

						}, this));

						this.observe.addDropdown($item, btnName, btnObject);

						$dropdown.append($item);

					}, this));
				},
				show: function(e, key)
				{
					if (!this.opts.visual)
					{
						e.preventDefault();
						return false;
					}

					var $button = this.button.get(key);

					// Always re-append it to the end of <body> so it always has the highest sub-z-index.
					var $dropdown = $button.data('dropdown').appendTo(document.body);

					if (this.opts.highContrast)
					{
						$dropdown.addClass("redactor-dropdown-contrast");
					}

					if ($button.hasClass('dropact'))
					{
						this.dropdown.hideAll();
					}
					else
					{
						this.dropdown.hideAll();
						this.observe.dropdowns();

						this.core.setCallback('dropdownShow', { dropdown: $dropdown, key: key, button: $button });

						this.button.setActive(key);

						$button.addClass('dropact');

						var keyPosition = $button.offset();

						// fix right placement
						var dropdownWidth = $dropdown.width();
						if ((keyPosition.left + dropdownWidth) > $(document).width())
						{
							keyPosition.left = Math.max(0, keyPosition.left - dropdownWidth);
						}

						var left = keyPosition.left + 'px';
						if (this.$toolbar.hasClass('toolbar-fixed-box'))
						{
							var top = this.$toolbar.innerHeight() + this.opts.toolbarFixedTopOffset;
							var position = 'fixed';
							if (this.opts.toolbarFixedTarget !== document)
							{
								top = (this.$toolbar.innerHeight() + this.$toolbar.offset().top) + this.opts.toolbarFixedTopOffset;
								position = 'absolute';
							}

							$dropdown.css({ position: position, left: left, top: top + 'px' }).show();
						}
						else
						{
							var top = ($button.innerHeight() + keyPosition.top) + 'px';

							$dropdown.css({ position: 'absolute', left: left, top: top }).show();
						}

						this.core.setCallback('dropdownShown', { dropdown: $dropdown, key: key, button: $button });

						this.$dropdown = $dropdown;
					}


					$(document).one('click.redactor-dropdown', $.proxy(this.dropdown.hide, this));
					this.$editor.one('click.redactor-dropdown', $.proxy(this.dropdown.hide, this));
					$(document).one('keyup.redactor-dropdown', $.proxy(this.dropdown.closeHandler, this));

					// disable scroll whan dropdown scroll
					$dropdown.on('mouseover.redactor-dropdown', $.proxy(this.utils.disableBodyScroll, this)).on('mouseout.redactor-dropdown', $.proxy(this.utils.enableBodyScroll, this));

					e.stopPropagation();
				},
				closeHandler: function(e)
				{
					if (e.which != this.keyCode.ESC) return;

					this.dropdown.hideAll();
					this.$editor.focus();
				},
				hideAll: function()
				{
					this.$toolbar.find('a.dropact').removeClass('redactor-act').removeClass('dropact');

					this.utils.enableBodyScroll();

					$('.redactor-dropdown-' + this.uuid).hide();
					$('.redactor-dropdown-link-selected').removeClass('redactor-dropdown-link-selected');


					if (this.$dropdown)
					{
						this.$dropdown.off('.redactor-dropdown');
						this.core.setCallback('dropdownHide', this.$dropdown);

						this.$dropdown = false;
					}
				},
				hide: function (e)
				{
					var $dropdown = $(e.target);

					if (!$dropdown.hasClass('dropact') && !$dropdown.hasClass('redactor-dropdown-link-inactive'))
					{
						if ($dropdown.hasClass('redactor-dropdown'))
						{
							$dropdown.removeClass('dropact');
							$dropdown.off('mouseover mouseout');
						}

						this.dropdown.hideAll();
					}
				}
			};
		},
		file: function()
		{
			return {
				show: function()
				{
					this.modal.load('file', this.lang.get('file'), 700);
					this.upload.init(this.$modal.find('#redactor-modal-file-upload'), this.opts.fileUpload, this.file.insert);

					this.selection.save();

					this.selection.get();
					var text = this.sel.toString();

					this.$modal.find('#redactor-filename').val(text);

					this.modal.show();
				},
				insert: function(json, direct, e)
				{
					// error callback
					if (typeof json.error != 'undefined')
					{
						this.modal.close();
						this.selection.restore();
						this.core.setCallback('fileUploadError', json);
						return;
					}

					var link;
					if (typeof json == 'string')
					{
						link = json;
					}
					else
					{
						var text = this.$modal.find('#redactor-filename').val();
						if (typeof text == 'undefined' || text === '') text = json.filename;

						link = '<a href="' + json.filelink + '" id="filelink-marker">' + text + '</a>';
					}

					if (direct)
					{
						this.selection.removeMarkers();
						var marker = this.selection.getMarker();
						this.insert.nodeToCaretPositionFromPoint(e, marker);
					}
					else
					{
						this.modal.close();
					}

					this.selection.restore();
					this.buffer.set();

					this.insert.htmlWithoutClean(link);

					if (typeof json == 'string') return;

					var linkmarker = $(this.$editor.find('a#filelink-marker'));
					if (linkmarker.length !== 0)
					{
						linkmarker.removeAttr('id').removeAttr('style');
					}
					else linkmarker = false;

					this.core.setCallback('fileUpload', linkmarker, json);

				}
			};
		},
		focus: function()
		{
			return {
				setStart: function()
				{
					this.$editor.focus();

					var first = this.$editor.children().first();

					if (first.length === 0) return;
					if (first[0].length === 0 || first[0].tagName == 'BR' || first[0].nodeType == 3)
					{
						return;
					}

					if (first[0].tagName == 'UL' || first[0].tagName == 'OL')
					{
						var child = first.find('li').first();
						if (!this.utils.isBlock(child) && child.text() === '')
						{
							// empty inline tag in li
							this.caret.setStart(child);
							return;
						}
					}

					if (this.opts.linebreaks && !this.utils.isBlockTag(first[0].tagName))
					{
						this.selection.get();
						this.range.setStart(this.$editor[0], 0);
						this.range.setEnd(this.$editor[0], 0);
						this.selection.addRange();

						return;
					}

					// if node is tag
					this.caret.setStart(first);
				},
				setEnd: function()
				{
					var last = this.$editor.children().last();
					this.$editor.focus();

					if (last.size() === 0) return;
					if (this.utils.isEmpty(this.$editor.html()))
					{

						this.selection.get();
						this.range.collapse(true);
						this.range.setStartAfter(last[0]);
						this.range.setEnd(last[0], 0);
						this.selection.addRange();
					}
					else
					{
						this.selection.get();
						this.range.selectNodeContents(last[0]);
						this.range.collapse(false);
						this.selection.addRange();

					}
				},
				isFocused: function()
				{
					return this.$editor[0] === document.activeElement;
				}
			};
		},
		image: function()
		{
			return {
				show: function()
				{
					this.modal.load('image', this.lang.get('image'), 700);
					this.upload.init(this.$modal.find('#redactor-modal-image-droparea'), this.opts.imageUpload, this.image.insert);

					this.selection.save();
					this.modal.show();

				},
				showEdit: function($image)
				{
					var $link = $image.closest('a', this.$editor[0]);

					this.modal.load('imageEdit', this.lang.get('edit'), 705);

					this.modal.createCancelButton();
					this.image.buttonDelete = this.modal.createDeleteButton(this.lang.get('_delete'));
					this.image.buttonSave = this.modal.createActionButton(this.lang.get('save'));

					this.image.buttonDelete.on('click', $.proxy(function()
					{
						this.image.remove($image);

					}, this));

					this.image.buttonSave.on('click', $.proxy(function()
					{
						this.image.update($image);

					}, this));

					// hide link's tooltip
					$('.redactor-link-tooltip').remove();

					this.$modal.find('#redactor-image-title').val($image.attr('alt'));

					if (!this.opts.imageLink) this.$modal.find('.redactor-image-link-option').hide();
					else
					{
						var $redactorImageLink = this.$modal.find('#redactor-image-link');

						$redactorImageLink.attr('href', $image.attr('src'));
						if ($link.length !== 0)
						{
							$redactorImageLink.val($link.attr('href'));
							if ($link.attr('target') == '_blank') this.$modal.find('#redactor-image-link-blank').prop('checked', true);
						}
					}

					if (!this.opts.imagePosition) this.$modal.find('.redactor-image-position-option').hide();
					else
					{
						var floatValue = ($image.css('display') == 'block' && $image.css('float') == 'none') ? 'center' : $image.attr('align');
						this.$modal.find('#redactor-image-align').val(floatValue);
					}

					this.modal.show();
					this.$modal.find('#redactor-image-title').focus();

				},
				setFloating: function($image)
				{
					var floating = this.$modal.find('#redactor-image-align').val();

					var imageFloat = '';
					var imageDisplay = '';
					var imageMargin = '';

					switch (floating)
					{
						case 'left':
							imageFloat = 'left';
							imageMargin = '0 ' + this.opts.imageFloatMargin + ' ' + this.opts.imageFloatMargin + ' 0';
						break;
						case 'right':
							imageFloat = 'right';
							imageMargin = '0 0 ' + this.opts.imageFloatMargin + ' ' + this.opts.imageFloatMargin;
						break;
						case 'center':
							imageDisplay = 'block';
							imageMargin = 'auto';
						break;
					}

					$image.css({ display: imageDisplay, margin: imageMargin });
					$image.attr('align', imageFloat);
					$image.attr('rel', $image.attr('style'));
				},
				update: function($image)
				{
					this.image.hideResize();
					this.buffer.set();

					var $link = $image.closest('a', this.$editor[0]);

					var title = this.$modal.find('#redactor-image-title').val().replace(/(<([^>]+)>)/ig,"");
					$image.attr('alt', title);

					this.image.setFloating($image);

					// as link
					var link = $.trim(this.$modal.find('#redactor-image-link').val());
					var link = link.replace(/(<([^>]+)>)/ig,"");
					if (link !== '')
					{
						// test url (add protocol)
						var pattern = '((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}';
						var re = new RegExp('^(http|ftp|https)://' + pattern, 'i');
						var re2 = new RegExp('^' + pattern, 'i');

						if (link.search(re) == -1 && link.search(re2) === 0 && this.opts.linkProtocol)
						{
							link = this.opts.linkProtocol + '://' + link;
						}

						var target = (this.$modal.find('#redactor-image-link-blank').prop('checked')) ? true : false;

						if ($link.length === 0)
						{
							var a = $('<a href="' + link + '">' + this.utils.getOuterHtml($image) + '</a>');
							if (target) a.attr('target', '_blank');

							$image.replaceWith(a);
						}
						else
						{
							$link.attr('href', link);
							if (target)
							{
								$link.attr('target', '_blank');
							}
							else
							{
								$link.removeAttr('target');
							}
						}
					}
					else if ($link.length !== 0)
					{
						$link.replaceWith(this.utils.getOuterHtml($image));

					}

					this.modal.close();
					this.observe.images();
					this.code.sync();


				},
				setEditable: function($image)
				{
					if (this.opts.imageEditable)
					{
						$image.on('dragstart', $.proxy(this.image.onDrag, this));
					}

					var handler = $.proxy(function(e)
					{

						this.observe.image = $image;

						this.image.resizer = this.image.loadEditableControls($image);

						$(document).on('mousedown.redactor-image-resize-hide.' + this.uuid, $.proxy(this.image.hideResize, this));

						// resize
						if (!this.opts.imageResizable) return;

						this.image.resizer.on('mousedown.redactor touchstart.redactor', $.proxy(function(e)
						{
							this.image.setResizable(e, $image);
						}, this));

					}, this);


					$image.off('mousedown.redactor').on('mousedown.redactor', $.proxy(this.image.hideResize, this));
					$image.off('click.redactor touchstart.redactor').on('click.redactor touchstart.redactor', handler);
				},
				setResizable: function(e, $image)
				{
					e.preventDefault();

				    this.image.resizeHandle = {
				        x : e.pageX,
				        y : e.pageY,
				        el : $image,
				        ratio: $image.width() / $image.height(),
				        h: $image.height()
				    };

				    e = e.originalEvent || e;

				    if (e.targetTouches)
				    {
				         this.image.resizeHandle.x = e.targetTouches[0].pageX;
				         this.image.resizeHandle.y = e.targetTouches[0].pageY;
				    }

					this.image.startResize();


				},
				startResize: function()
				{
					$(document).on('mousemove.redactor-image-resize touchmove.redactor-image-resize', $.proxy(this.image.moveResize, this));
					$(document).on('mouseup.redactor-image-resize touchend.redactor-image-resize', $.proxy(this.image.stopResize, this));
				},
				moveResize: function(e)
				{
					e.preventDefault();

					e = e.originalEvent || e;

					var height = this.image.resizeHandle.h;

		            if (e.targetTouches) height += (e.targetTouches[0].pageY -  this.image.resizeHandle.y);
		            else height += (e.pageY -  this.image.resizeHandle.y);

					var width = Math.round(height * this.image.resizeHandle.ratio);

					if (height < 50 || width < 100) return;

					var height = Math.round(this.image.resizeHandle.el.width() / this.image.resizeHandle.ratio);

					this.image.resizeHandle.el.attr({width: width, height: height});
		            this.image.resizeHandle.el.width(width);
		            this.image.resizeHandle.el.height(height);

		            this.code.sync();
				},
				stopResize: function()
				{
					this.handle = false;
					$(document).off('.redactor-image-resize');

					this.image.hideResize();
				},
				onDrag: function(e)
				{
					if (this.$editor.find('#redactor-image-box').length !== 0)
					{
						e.preventDefault();
						return false;
					}

					this.$editor.on('drop.redactor-image-inside-drop', $.proxy(function()
					{
						setTimeout($.proxy(this.image.onDrop, this), 1);

					}, this));
				},
				onDrop: function()
				{
					this.image.fixImageSourceAfterDrop();
					this.observe.images();
					this.$editor.off('drop.redactor-image-inside-drop');
					this.clean.clearUnverified();
					this.code.sync();
				},
				fixImageSourceAfterDrop: function()
				{
					this.$editor.find('img[data-save-url]').each(function()
					{
						var $el = $(this);
						$el.attr('src', $el.attr('data-save-url'));
						$el.removeAttr('data-save-url');
					});
				},
				hideResize: function(e)
				{
					if (e && $(e.target).closest('#redactor-image-box', this.$editor[0]).length !== 0) return;
					if (e && e.target.tagName == 'IMG')
					{
						var $image = $(e.target);
						$image.attr('data-save-url', $image.attr('src'));
					}

					var imageBox = this.$editor.find('#redactor-image-box');
					if (imageBox.length === 0) return;

					$('#redactor-image-editter').remove();
					$('#redactor-image-resizer').remove();

					imageBox.find('img').css({
						marginTop: imageBox[0].style.marginTop,
						marginBottom: imageBox[0].style.marginBottom,
						marginLeft: imageBox[0].style.marginLeft,
						marginRight: imageBox[0].style.marginRight
					});

					imageBox.css('margin', '');
					imageBox.find('img').css('opacity', '');
					imageBox.replaceWith(function()
					{
						return $(this).contents();
					});

					$(document).off('mousedown.redactor-image-resize-hide.' + this.uuid);


					if (typeof this.image.resizeHandle !== 'undefined')
					{
						this.image.resizeHandle.el.attr('rel', this.image.resizeHandle.el.attr('style'));
					}

					this.code.sync();

				},
				loadResizableControls: function($image, imageBox)
				{
					if (this.opts.imageResizable && !this.utils.isMobile())
					{
						var imageResizer = $('<span id="redactor-image-resizer" data-redactor="verified"></span>');

						if (!this.utils.isDesktop())
						{
							imageResizer.css({ width: '15px', height: '15px' });
						}

						imageResizer.attr('contenteditable', false);
						imageBox.append(imageResizer);
						imageBox.append($image);

						return imageResizer;
					}
					else
					{
						imageBox.append($image);
						return false;
					}
				},
				loadEditableControls: function($image)
				{
					var imageBox = $('<span id="redactor-image-box" data-redactor="verified">');
					imageBox.css('float', $image.css('float')).attr('contenteditable', false);

					if ($image[0].style.margin != 'auto')
					{
						imageBox.css({
							marginTop: $image[0].style.marginTop,
							marginBottom: $image[0].style.marginBottom,
							marginLeft: $image[0].style.marginLeft,
							marginRight: $image[0].style.marginRight
						});

						$image.css('margin', '');
					}
					else
					{
						imageBox.css({ 'display': 'block', 'margin': 'auto' });
					}

					$image.css('opacity', '.5').after(imageBox);


					if (this.opts.imageEditable)
					{
						// editter
						this.image.editter = $('<span id="redactor-image-editter" data-redactor="verified">' + this.lang.get('edit') + '</span>');
						this.image.editter.attr('contenteditable', false);
						this.image.editter.on('click', $.proxy(function()
						{
							this.image.showEdit($image);
						}, this));

						imageBox.append(this.image.editter);

						// position correction
						var editerWidth = this.image.editter.innerWidth();
						this.image.editter.css('margin-left', '-' + editerWidth/2 + 'px');
					}

					return this.image.loadResizableControls($image, imageBox);

				},
				remove: function(image)
				{
					var $image = $(image);
					var $link = $image.closest('a', this.$editor[0]);
					var $figure = $image.closest('figure', this.$editor[0]);
					var $parent = $image.parent();
					if ($('#redactor-image-box').length !== 0)
					{
						$parent = $('#redactor-image-box').parent();
					}

					var $next;
					if ($figure.length !== 0)
					{
						$next = $figure.next();
						$figure.remove();
					}
					else if ($link.length !== 0)
					{
						$parent = $link.parent();
						$link.remove();
					}
					else
					{
						$image.remove();
					}

					$('#redactor-image-box').remove();

					if ($figure.length !== 0)
					{
						this.caret.setStart($next);
					}
					else
					{
						this.caret.setStart($parent);
					}

					// delete callback
					this.core.setCallback('imageDelete', $image[0].src, $image);

					this.modal.close();
					this.code.sync();
				},
				insert: function(json, direct, e)
				{
					// error callback
					if (typeof json.error != 'undefined')
					{
						this.modal.close();
						this.selection.restore();
						this.core.setCallback('imageUploadError', json);
						return;
					}

					var $img;
					if (typeof json == 'string')
					{
						$img = $(json).attr('data-redactor-inserted-image', 'true');
					}
					else
					{
						$img = $('<img>');
						$img.attr('src', json.filelink).attr('data-redactor-inserted-image', 'true');
					}


					var node = $img;
					var isP = this.utils.isCurrentOrParent('P');
					if (isP)
					{
						// will replace
						node = $('<blockquote />').append($img);
					}

					if (direct)
					{
						this.selection.removeMarkers();
						var marker = this.selection.getMarker();
						this.insert.nodeToCaretPositionFromPoint(e, marker);
					}
					else
					{
						var modal = this.modal.getModal()
						var linkUrl = modal.find('#redactor_image_link_url').val();
						var linkTarget;
						if(modal.find('#redactor_image_link_target_blank').is(':checked'))
							linkTarget = '_blank';
						$img.attr('data-link-url', linkUrl);
						$img.attr('data-link-target', linkTarget);
						this.modal.close();
					}

					this.selection.restore();
					this.buffer.set();

					this.insert.html(this.utils.getOuterHtml(node), false);

					var $image = this.$editor.find('img[data-redactor-inserted-image=true]').removeAttr('data-redactor-inserted-image');

					if (isP)
					{
						$image.parent().contents().unwrap().wrap('<p />');
					}
					else if (this.opts.linebreaks)
					{
						if (!this.utils.isEmpty(this.code.get()))
						{
							$image.before('<br>');
						}

						$image.after('<br>');
					}

					if (typeof json == 'string') return;

					this.core.setCallback('imageUpload', $image, json);

				}
			};
		},
		indent: function()
		{
			return {
				increase: function()
				{
					// focus
					if (!this.utils.browser('msie')) this.$editor.focus();

					this.buffer.set();
					this.selection.save();

					var block = this.selection.getBlock();

					if (block && block.tagName == 'LI')
					{
						this.indent.increaseLists();
					}
					else if (block === false && this.opts.linebreaks)
					{
						this.indent.increaseText();
					}
					else
					{
						this.indent.increaseBlocks();
					}

					this.selection.restore();
					this.code.sync();
				},
				increaseLists: function()
				{
					document.execCommand('indent');

					this.indent.fixEmptyIndent();
					this.clean.normalizeLists();
					this.clean.clearUnverified();
				},
				increaseBlocks: function()
				{
					$.each(this.selection.getBlocks(), $.proxy(function(i, elem)
					{
						if (elem.tagName === 'TD' || elem.tagName === 'TH') return;

						var $el = this.utils.getAlignmentElement(elem);

						var left = this.utils.normalize($el.css('margin-left')) + this.opts.indentValue;
						$el.css('margin-left', left + 'px');

					}, this));
				},
				increaseText: function()
				{
					var wrapper = this.selection.wrap('div');
					$(wrapper).attr('data-tagblock', 'redactor');
					$(wrapper).css('margin-left', this.opts.indentValue + 'px');
					// If the next tag is a <br>, we want to remove it b/c we're adding a <div>
					// We need two next() calls b/c the first will be the .redactor-selection-marker
					var nextTag = $(wrapper).next().next();
					if(nextTag.prop('tagName') == 'BR')
						nextTag.remove();
				},
				decrease: function()
				{
					this.buffer.set();
					this.selection.save();

					var block = this.selection.getBlock();
					if (block && block.tagName == 'LI')
					{
						this.indent.decreaseLists();
					}
					else
					{
						this.indent.decreaseBlocks();
					}

					this.selection.restore();
					this.code.sync();
				},
				decreaseLists: function()
				{
					document.execCommand('outdent');

					var current = this.selection.getCurrent();
					var $item = $(current).closest('li', this.$editor[0]);

					this.indent.fixEmptyIndent();

					if (!this.opts.linebreaks && $item.length === 0)
					{
						document.execCommand('formatblock', false, 'p');
						this.$editor.find('ul, ol, blockquote, p').each($.proxy(this.utils.removeEmpty, this));
					}

					this.clean.clearUnverified();
				},
				decreaseBlocks: function()
				{
					$.each(this.selection.getBlocks(), $.proxy(function(i, elem)
					{
						var $el = this.utils.getAlignmentElement(elem);
						var left = this.utils.normalize($el.css('margin-left')) - this.opts.indentValue;

						if (left <= 0)
						{
							if (this.opts.linebreaks && typeof($el.data('tagblock')) !== 'undefined')
							{
								$el.replaceWith($el.html() + '<br />');
							}
							else
							{
								$el.css('margin-left', '');
								this.utils.removeEmptyAttr($el, 'style');
							}
						}
						else
						{
							$el.css('margin-left', left + 'px');
						}

					}, this));
				},
				fixEmptyIndent: function()
				{
					var block = this.selection.getBlock();

					if (this.range.collapsed && block && block.tagName == 'LI' && this.utils.isEmpty($(block).text()))
					{
						var $block = $(block);
						$block.find('span').not('.redactor-selection-marker').contents().unwrap();
						$block.append('<br>');
					}
				}
			};
		},
		inline: function()
		{
			return {
				formatting: function(name)
				{
					var type, value;

					if (typeof this.formatting[name].style != 'undefined') type = 'style';
					else if (typeof this.formatting[name]['class'] != 'undefined') type = 'class';

					if (type) value = this.formatting[name][type];

					this.inline.format(this.formatting[name].tag, type, value);

				},
				format: function(tag, type, value)
				{
					var current = this.selection.getCurrent();
					if (current && current.tagName === 'TR') return;

					// Stop formatting pre and headers
					// [DM-1355] The this.utils.isCurrentOrParentHeader() condition prevents headers
					// from being formatted - text color, italics, etc.
					// http://stackoverflow.com/questions/32088397/can-i-customise-the-header-tagsh1-h2-h3-in-redactor-editor
					// if (this.utils.isCurrentOrParent('PRE') || this.utils.isCurrentOrParentHeader()) return;
					if (this.utils.isCurrentOrParent('PRE')) return;


					var tags = ['b', 'bold', 'i', 'italic', 'underline', 'strikethrough', 'deleted', 'superscript', 'subscript'];
					var replaced = ['strong', 'strong', 'em', 'em', 'u', 'del', 'del', 'sup', 'sub'];

					for (var i = 0; i < tags.length; i++)
					{
						if (tag == tags[i]) tag = replaced[i];
					}


					if (this.opts.allowedTags)
					{
						if ($.inArray(tag, this.opts.allowedTags) == -1) return;
					}
					else
					{
						if ($.inArray(tag, this.opts.deniedTags) !== -1) return;
					}

					this.inline.type = type || false;
					this.inline.value = value || false;

					this.buffer.set();

					if (!this.utils.browser('msie') && !this.opts.linebreaks)
					{
						this.$editor.focus();
					}

					this.selection.get();

					if (this.range.collapsed)
					{
						this.inline.formatCollapsed(tag);
					}
					else
					{
						this.inline.formatMultiple(tag);
					}
				},
				formatCollapsed: function(tag)
				{
					var current = this.selection.getCurrent();
					var $parent = $(current).closest(tag + '[data-redactor-tag=' + tag + ']', this.$editor[0]);

					// inline there is
					if ($parent.length !== 0 && (this.inline.type != 'style' && $parent[0].tagName != 'SPAN'))
					{
						// remove empty
						if (this.utils.isEmpty($parent.text()))
						{
							this.caret.setAfter($parent[0]);

							$parent.remove();
							this.code.sync();
						}
						else if (this.utils.isEndOfElement($parent))
						{
							this.caret.setAfter($parent[0]);
						}

						return;
					}

					// create empty inline
					var node = $('<' + tag + '>').attr('data-verified', 'redactor').attr('data-redactor-tag', tag);
					node.html(this.opts.invisibleSpace);

					node = this.inline.setFormat(node);

					var node = this.insert.node(node);
					this.caret.setEnd(node);

					this.code.sync();
				},
				formatMultiple: function(tag)
				{
					this.inline.formatConvert(tag);

					// [DM-2989] Removed b/c selecting text then bolding or doing other inline style
					// changes wasn't working.
					// this.selection.save();
					document.execCommand('strikethrough');

					this.$editor.find('strike').each($.proxy(function(i,s)
					{
						var $el = $(s);

						this.inline.formatRemoveSameChildren($el, tag);

						var $span;
						if (this.inline.type)
						{
							$span = $('<span>').attr('data-redactor-tag', tag).attr('data-verified', 'redactor');
							$span = this.inline.setFormat($span);
						}
						else
						{
							$span = $('<' + tag + '>').attr('data-redactor-tag', tag).attr('data-verified', 'redactor');
						}

						$el.replaceWith($span.html($el.contents()));
						var $parent = $span.parent();

						// remove U tag if selected link + node
						if ($span[0].tagName === 'A' && $parent && $parent[0].tagName === 'U')
						{
							$span.parent().replaceWith($span);
						}

						if (tag == 'span')
						{
							if ($parent && $parent[0].tagName === 'SPAN' && this.inline.type === 'style')
							{
								var arr = this.inline.value.split(';');

								for (var z = 0; z < arr.length; z++)
								{
									if (arr[z] === '') return;
									var style = arr[z].split(':');
									$parent.css(style[0], '');

									if (this.utils.removeEmptyAttr($parent, 'style'))
									{
										$parent.replaceWith($parent.contents());
									}

								}

							}
						}

					}, this));

					// clear text decoration
					if (tag != 'span')
					{
						this.$editor.find(this.opts.inlineTags.join(', ')).each($.proxy(function(i,s)
						{
							var $el = $(s);


							if (s.tagName === 'U' && s.attributes.length === 0)
							{
								$el.replaceWith($el.contents());
								return;
							}

							var property = $el.css('text-decoration');
							if (property === 'line-through')
							{
								$el.css('text-decoration', '');
								this.utils.removeEmptyAttr($el, 'style');
							}
						}, this));
					}

					if (tag != 'del')
					{
						var _this = this;
						this.$editor.find('inline').each(function(i,s)
						{
							_this.utils.replaceToTag(s, 'del');
						});
					}

					if (tag != 'u')
					{
						var _this = this;
						this.$editor.find('unline').each(function(i,s)
						{
							_this.utils.replaceToTag(s, 'u');
						});
					}

					this.selection.restore();
					this.code.sync();

				},
				formatRemoveSameChildren: function($el, tag)
				{
					var self = this;
					$el.children(tag).each(function()
					{
						var $child = $(this);

						if (!$child.hasClass('redactor-selection-marker'))
						{
							if (self.inline.type == 'style')
							{
								var arr = self.inline.value.split(';');

								for (var z = 0; z < arr.length; z++)
								{
									if (arr[z] === '') return;

									var style = arr[z].split(':');
									$child.css(style[0], '');

									if (self.utils.removeEmptyAttr($child , 'style'))
									{
										$child.replaceWith($child.contents());
									}

								}
							}
							else
							{
								$child.contents().unwrap();
							}
						}

					});
				},
				formatConvert: function(tag)
				{
					this.selection.save();

					var find = '';
					if (this.inline.type == 'class') find = '[data-redactor-class=' + this.inline.value + ']';
					else if (this.inline.type == 'style')
					{
						find = '[data-redactor-style="' + this.inline.value + '"]';
					}

					var self = this;
					if (tag != 'del')
					{
						this.$editor.find('del').each(function(i,s)
						{
							self.utils.replaceToTag(s, 'inline');
						});
					}

					if (tag != 'u')
					{
						this.$editor.find('u').each(function(i,s)
						{
							self.utils.replaceToTag(s, 'unline');
						});
					}

					if (tag != 'span')
					{
						this.$editor.find(tag).each(function()
						{
							var $el = $(this);
							$el.replaceWith($('<strike />').html($el.contents()));

						});
					}

					this.$editor.find('[data-redactor-tag="' + tag + '"]' + find).each(function()
					{
						if (find === '' && tag == 'span' && this.tagName.toLowerCase() == tag) return;

						var $el = $(this);
						$el.replaceWith($('<strike />').html($el.contents()));

					});

					this.selection.restore();
				},
				setFormat: function(node)
				{
					switch (this.inline.type)
					{
						case 'class':

							if (node.hasClass(this.inline.value))
							{
								node.removeClass(this.inline.value);
								node.removeAttr('data-redactor-class');
							}
							else
							{
								node.addClass(this.inline.value);
								node.attr('data-redactor-class', this.inline.value);
							}


						break;
						case 'style':

							node[0].style.cssText = this.inline.value;
							node.attr('data-redactor-style', this.inline.value);

						break;
					}

					return node;
				},
				removeStyle: function()
				{
					this.buffer.set();
					var current = this.selection.getCurrent();
					var nodes = this.selection.getInlines();

					this.selection.save();

					if (current && current.tagName === 'SPAN')
					{
						var $s = $(current);

						$s.removeAttr('style');
						if ($s[0].attributes.length === 0)
						{
							$s.replaceWith($s.contents());
						}
					}

					$.each(nodes, $.proxy(function(i,s)
					{
						var $s = $(s);
						if ($.inArray(s.tagName.toLowerCase(), this.opts.inlineTags) != -1 && !$s.hasClass('redactor-selection-marker'))
						{
							$s.removeAttr('style');
							if ($s[0].attributes.length === 0)
							{
								$s.replaceWith($s.contents());
							}
						}
					}, this));

					this.selection.restore();
					this.code.sync();

				},
				removeStyleRule: function(name)
				{
					this.buffer.set();
					var parent = this.selection.getParent();
					var nodes = this.selection.getInlines();

					this.selection.save();

					if (parent && parent.tagName === 'SPAN')
					{
						var $s = $(parent);

						$s.css(name, '');
						this.utils.removeEmptyAttr($s, 'style');
						if ($s[0].attributes.length === 0)
						{
							$s.replaceWith($s.contents());
						}
					}

					$.each(nodes, $.proxy(function(i,s)
					{
						var $s = $(s);
						if ($.inArray(s.tagName.toLowerCase(), this.opts.inlineTags) != -1 && !$s.hasClass('redactor-selection-marker'))
						{
							$s.css(name, '');
							this.utils.removeEmptyAttr($s, 'style');
							if ($s[0].attributes.length === 0)
							{
								$s.replaceWith($s.contents());
							}
						}
					}, this));

					this.selection.restore();
					this.code.sync();
				},
				removeFormat: function()
				{
					this.buffer.set();
					var current = this.selection.getCurrent();

					this.selection.save();

					document.execCommand('removeFormat');

					if (current && current.tagName === 'SPAN')
					{
						$(current).replaceWith($(current).contents());
					}


					$.each(this.selection.getNodes(), $.proxy(function(i,s)
					{
						var $s = $(s);
						if ($.inArray(s.tagName.toLowerCase(), this.opts.inlineTags) != -1 && !$s.hasClass('redactor-selection-marker'))
						{
							$s.replaceWith($s.contents());
						}
					}, this));

					this.selection.restore();
					this.code.sync();

				},
				toggleClass: function(className)
				{
					this.inline.format('span', 'class', className);
				},
				toggleStyle: function(value)
				{
					this.inline.format('span', 'style', value);
				}
			};
		},
		insert: function()
		{
			return {
				set: function(html, clean)
				{
					this.placeholder.remove();

					html = this.clean.setVerified(html);

					if (typeof clean == 'undefined')
					{
						html = this.clean.onPaste(html, false);
					}

					this.$editor.html(html);
					this.selection.remove();
					this.focus.setEnd();
					this.clean.normalizeLists();
					this.code.sync();
					this.observe.load();

					if (typeof clean == 'undefined')
					{
						setTimeout($.proxy(this.clean.clearUnverified, this), 10);
					}
				},
				text: function(text)
				{
					this.placeholder.remove();

					text = text.toString();
					text = $.trim(text);
					text = this.clean.getPlainText(text, false);

					this.$editor.focus();

					if (this.utils.browser('msie'))
					{
						this.insert.htmlIe(text);
					}
					else
					{
						this.selection.get();

						this.range.deleteContents();
						var el = document.createElement("div");
						el.innerHTML = text;
						var frag = document.createDocumentFragment(), node, lastNode;
						while ((node = el.firstChild))
						{
							lastNode = frag.appendChild(node);
						}

						this.range.insertNode(frag);

						if (lastNode)
						{
							var range = this.range.cloneRange();
							range.setStartAfter(lastNode);
							range.collapse(true);
							this.sel.removeAllRanges();
							this.sel.addRange(range);
						}
					}

					this.code.sync();
					this.clean.clearUnverified();
				},
				htmlWithoutClean: function(html)
				{
					this.insert.html(html, false);
				},
				html: function(html, clean)
				{
					this.placeholder.remove();

					if (typeof clean == 'undefined') clean = true;

					if (!this.opts.linebreaks)
					{
						this.$editor.focus();
					}

					html = this.clean.setVerified(html);

					if (clean)
					{
						html = this.clean.onPaste(html);
					}

					if (this.utils.browser('msie'))
					{
						this.insert.htmlIe(html);
					}
					else
					{
						if (this.clean.singleLine) this.insert.execHtml(html);
						else document.execCommand('insertHTML', false, html);

						this.insert.htmlFixMozilla();

					}

					this.clean.normalizeLists();

					// remove empty paragraphs finaly
					if (!this.opts.linebreaks)
					{
						this.$editor.find('p').each($.proxy(this.utils.removeEmpty, this));
					}

					this.code.sync();
					this.observe.load();

					if (clean)
					{
						this.clean.clearUnverified();
					}

				},
				htmlFixMozilla: function()
				{
					// FF inserts empty p when content was selected dblclick
					if (!this.utils.browser('mozilla')) return;

					var $next = $(this.selection.getBlock()).next();
					if ($next.length > 0 && $next[0].tagName == 'P' && $next.html() === '')
					{
						$next.remove();
					}

				},
				htmlIe: function(html)
				{
					if (this.utils.isIe11() || this.utils.isEdge())
					{
						var parent = this.utils.isCurrentOrParent('P');
						var $html = $('<div>').append(html);
						var blocksMatch = $html.contents().is('p, :header, dl, ul, ol, div, table, td, blockquote, pre, address, section, header, footer, aside, article');

						if (parent && blocksMatch) this.insert.ie11FixInserting(parent, html);
						else this.insert.ie11PasteFrag(html);

						return;
					}

					document.selection.createRange().pasteHTML(html);

				},
				execHtml: function(html)
				{
					html = this.clean.setVerified(html);

					this.selection.get();

					this.range.deleteContents();

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

					var frag = document.createDocumentFragment(), node, lastNode;
					while ((node = el.firstChild))
					{
						lastNode = frag.appendChild(node);
					}

					this.range.insertNode(frag);

					this.range.collapse(true);
					this.caret.setAfter(lastNode);

				},
				node: function(node, deleteContents)
				{
					node = node[0] || node;

					var offset = this.caret.getOffset();
					var html = this.utils.getOuterHtml(node);
					html = this.clean.setVerified(html);

					if (html.match(/</g) !== null)
					{
						node = $(html)[0];
					}

					this.selection.get();

					if (deleteContents !== false)
					{
						this.range.deleteContents();
					}

					this.range.insertNode(node);
					this.range.collapse(false);
					this.selection.addRange();

					this.caret.setOffset(offset);

					return node;
				},
				nodeToPoint: function(node, x, y)
				{
					node = node[0] || node;

					this.selection.get();

					var range;
					if (document.caretPositionFromPoint)
					{
					    var pos = document.caretPositionFromPoint(x, y);

					    this.range.setStart(pos.offsetNode, pos.offset);
					    this.range.collapse(true);
					    this.range.insertNode(node);
					}
					else if (document.caretRangeFromPoint)
					{
					    range = document.caretRangeFromPoint(x, y);
					    range.insertNode(node);
					}
					else if (typeof document.body.createTextRange != "undefined")
					{
				        range = document.body.createTextRange();
				        range.moveToPoint(x, y);
				        var endRange = range.duplicate();
				        endRange.moveToPoint(x, y);
				        range.setEndPoint("EndToEnd", endRange);
				        range.select();
					}
				},
				nodeToCaretPositionFromPoint: function(e, node)
				{
					node = node[0] || node;

					var range;
					var x = e.clientX, y = e.clientY;
					if (document.caretPositionFromPoint)
					{
					    var pos = document.caretPositionFromPoint(x, y);
					    var sel = document.getSelection();
					    range = sel.getRangeAt(0);
					    range.setStart(pos.offsetNode, pos.offset);
					    range.collapse(true);
					    range.insertNode(node);
					}
					else if (document.caretRangeFromPoint)
					{
					    range = document.caretRangeFromPoint(x, y);
					    range.insertNode(node);
					}
					else if (typeof document.body.createTextRange != "undefined")
					{
				        range = document.body.createTextRange();
				        range.moveToPoint(x, y);
				        var endRange = range.duplicate();
				        endRange.moveToPoint(x, y);
				        range.setEndPoint("EndToEnd", endRange);
				        range.select();
					}

				},
				ie11FixInserting: function(parent, html)
				{
					var node = document.createElement('span');
					node.className = 'redactor-ie-paste';
					this.insert.node(node);

					var parHtml = $(parent).html();

					parHtml = '<p>' + parHtml.replace(/<span class="redactor-ie-paste"><\/span>/gi, '</p>' + html + '<p>') + '</p>';
					parHtml = parHtml.replace(/<p><\/p>/gi, '');
					$(parent).replaceWith(parHtml);
				},
				ie11PasteFrag: function(html)
				{
					this.selection.get();
					this.range.deleteContents();

					var el = document.createElement("div");
					el.innerHTML = html;

					var frag = document.createDocumentFragment(), node, lastNode;
					while ((node = el.firstChild))
					{
						lastNode = frag.appendChild(node);
					}

					this.range.insertNode(frag);
					this.range.collapse(false);
					this.selection.addRange();
				}
			};
		},
		keydown: function()
		{
			return {
				init: function(e)
				{
					if (this.rtePaste) return;

					var key = e.which;
					var arrow = (key >= 37 && key <= 40);

					this.keydown.ctrl = e.ctrlKey || e.metaKey;
					this.keydown.current = this.selection.getCurrent();
					this.keydown.parent = this.selection.getParent();
					this.keydown.block = this.selection.getBlock();

			        // detect tags
					this.keydown.pre = this.utils.isTag(this.keydown.current, 'pre');
					this.keydown.blockquote = this.utils.isTag(this.keydown.current, 'blockquote');
					this.keydown.figcaption = this.utils.isTag(this.keydown.current, 'figcaption');

					// shortcuts setup
					this.shortcuts.init(e, key);

					if (this.utils.isDesktop())
					{
						this.keydown.checkEvents(arrow, key);
						this.keydown.setupBuffer(e, key);
					}

					this.keydown.addArrowsEvent(arrow);
					this.keydown.setupSelectAll(e, key);

					// callback
					var keydownStop = this.core.setCallback('keydown', e);
					if (keydownStop === false)
					{
						e.preventDefault();
						return false;
					}

					// ie and ff exit from table
					if (this.opts.enterKey && (this.utils.browser('msie') || this.utils.browser('mozilla')) && (key === this.keyCode.DOWN || key === this.keyCode.RIGHT))
					{
						var isEndOfTable = false;
						var $table = false;
						if (this.keydown.block && this.keydown.block.tagName === 'TD')
						{
							$table = $(this.keydown.block).closest('table', this.$editor[0]);
						}

						if ($table && $table.find('td').last()[0] === this.keydown.block)
						{
							isEndOfTable = true;
						}

						if (this.utils.isEndOfElement() && isEndOfTable)
						{
							var node = $(this.opts.emptyHtml);
							$table.after(node);
							this.caret.setStart(node);
						}
					}

					// down
					if (this.opts.enterKey && key === this.keyCode.DOWN)
					{
						this.keydown.onArrowDown();
					}

					// turn off enter key
					if (!this.opts.enterKey && key === this.keyCode.ENTER)
					{
						e.preventDefault();
						// remove selected
						if (!this.range.collapsed) this.range.deleteContents();
						return;
					}

					// on enter
					if (key == this.keyCode.ENTER && !e.shiftKey && !e.ctrlKey && !e.metaKey)
					{
						var stop = this.core.setCallback('enter', e);
						if (stop === false)
						{
							e.preventDefault();
							return false;
						}

						if (this.keydown.blockquote && this.keydown.exitFromBlockquote(e) === true)
						{
							return false;
						}

						var current, $next;
						if (this.keydown.pre)
						{
							return this.keydown.insertNewLine(e);
						}
						else if (this.keydown.blockquote || this.keydown.figcaption)
						{
							current = this.selection.getCurrent();
							$next = $(current).next();

							if ($next.length !== 0 && $next[0].tagName == 'BR')
							{
								return this.keydown.insertBreakLine(e);
							}
							else if (this.utils.isEndOfElement() && (current && current != 'SPAN'))
							{
								return this.keydown.insertDblBreakLine(e);
							}
							else
							{
								return this.keydown.insertBreakLine(e);
							}
						}
						else if (this.opts.linebreaks && !this.keydown.block)
						{
							current = this.selection.getCurrent();
							$next = $(this.keydown.current).next();

							if ($next.length !== 0 && $next[0].tagName == 'BR')
							{
								return this.keydown.insertBreakLine(e);
							}
							else if (current !== false && $(current).hasClass('redactor-invisible-space'))
							{
								this.caret.setAfter(current);
								$(current).contents().unwrap();

								return this.keydown.insertDblBreakLine(e);
							}
							else
							{
								if (this.utils.isEndOfEditor())
								{
									return this.keydown.insertDblBreakLine(e);
								}
								else if ($next.length === 0 && current === false && typeof $next.context != 'undefined')
								{
									return this.keydown.insertBreakLine(e);
								}

								return this.keydown.insertBreakLine(e);
							}

						}
						else if (this.opts.linebreaks && this.keydown.block)
						{
							setTimeout($.proxy(this.keydown.replaceDivToBreakLine, this), 1);
						}
						// paragraphs
						else if (!this.opts.linebreaks && this.keydown.block)
						{
							setTimeout($.proxy(this.keydown.replaceDivToParagraph, this), 1);

							if (this.keydown.block.tagName === 'LI')
							{
								current = this.selection.getCurrent();
								var $parent = $(current).closest('li', this.$editor[0]);
								var $list = $parent.closest('ul,ol', this.$editor[0]);

								if ($parent.length !== 0 && this.utils.isEmpty($parent.html()) && $list.next().length === 0 && this.utils.isEmpty($list.find("li").last().html()))
								{
									$list.find("li").last().remove();

									var node = $(this.opts.emptyHtml);
									$list.after(node);
									this.caret.setStart(node);

									return false;
								}
							}
						}
						else if (!this.opts.linebreaks && !this.keydown.block)
						{
							return this.keydown.insertParagraph(e);
						}
					}

					// Shift+Enter or Ctrl+Enter
					if (key === this.keyCode.ENTER && (e.ctrlKey || e.shiftKey))
					{
						return this.keydown.onShiftEnter(e);
					}


					// tab or cmd + [
					if (key === this.keyCode.TAB || e.metaKey && key === 221 || e.metaKey && key === 219)
					{
						return this.keydown.onTab(e, key);
					}

					// image delete and backspace
					if (key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE)
					{
						var nodes = this.selection.getNodes();

						if (nodes)
						{
							var len = nodes.length;
							var last;
							for (var i = 0; i < len; i++)
							{
								var children = $(nodes[i]).children('img');
								if (children.length !== 0)
								{
									var self = this;
									$.each(children, function(z,s)
									{
										var $s = $(s);
										if ($s.css('float') != 'none') return;

										// image delete callback
										self.core.setCallback('imageDelete', s.src, $s);
										last = s;
									});
								}
								else if (nodes[i].tagName == 'IMG')
								{
									if (last != nodes[i])
									{
										// image delete callback
										this.core.setCallback('imageDelete', nodes[i].src, $(nodes[i]));
										last = nodes[i];
									}
								}
							}
						}
					}

					// backspace
					if (key === this.keyCode.BACKSPACE)
					{
						// backspace as outdent
						var block = this.selection.getBlock();
						var indented = ($(block).css('margin-left') !== '0px');
						if (block && indented && this.range.collapsed && this.utils.isStartOfElement())
						{
							this.indent.decrease();
							e.preventDefault();
							return;
						}

						// remove hr in FF
						if (this.utils.browser('mozilla'))
						{
							var prev = this.selection.getPrev();
							var prev2 = $(prev).prev()[0];
							if (prev && prev.tagName === 'HR') $(prev).remove();
							if (prev2 && prev2.tagName === 'HR') $(prev2).remove();
						}

						this.keydown.removeInvisibleSpace();
						this.keydown.removeEmptyListInTable(e);
					}

					this.code.sync();
				},
				checkEvents: function(arrow, key)
				{
					if (!arrow && (this.core.getEvent() == 'click' || this.core.getEvent() == 'arrow'))
					{
						this.core.addEvent(false);

						if (this.keydown.checkKeyEvents(key))
						{
							this.buffer.set();
						}
					}
				},
				checkKeyEvents: function(key)
				{
					var k = this.keyCode;
					var keys = [k.BACKSPACE, k.DELETE, k.ENTER, k.ESC, k.TAB, k.CTRL, k.META, k.ALT, k.SHIFT];

					return ($.inArray(key, keys) == -1) ? true : false;

				},
				addArrowsEvent: function(arrow)
				{
					if (!arrow) return;

					if ((this.core.getEvent() == 'click' || this.core.getEvent() == 'arrow'))
					{
						this.core.addEvent(false);
						return;
					}

				    this.core.addEvent('arrow');
				},
				setupBuffer: function(e, key)
				{
					if (this.keydown.ctrl && key === 90 && !e.shiftKey && !e.altKey && this.opts.buffer.length) // z key
					{
						e.preventDefault();
						this.buffer.undo();
						return;
					}
					// undo
					else if (this.keydown.ctrl && key === 90 && e.shiftKey && !e.altKey && this.opts.rebuffer.length !== 0)
					{
						e.preventDefault();
						this.buffer.redo();
						return;
					}
					else if (!this.keydown.ctrl)
					{
						if (key == this.keyCode.BACKSPACE || key == this.keyCode.DELETE || (key == this.keyCode.ENTER && !e.ctrlKey && !e.shiftKey))
						{
							this.buffer.set();
						}
					}
				},
				setupSelectAll: function(e, key)
				{
					if (this.keydown.ctrl && key === 65)
					{
						this.utils.enableSelectAll();
					}
					else if (key != this.keyCode.LEFT_WIN && !this.keydown.ctrl)
					{
						this.utils.disableSelectAll();
					}
				},
				onArrowDown: function()
				{
					var tags = [this.keydown.blockquote, this.keydown.pre, this.keydown.figcaption];

					for (var i = 0; i < tags.length; i++)
					{
						if (tags[i])
						{
							this.keydown.insertAfterLastElement(tags[i]);
							return false;
						}
					}
				},
				onShiftEnter: function(e)
				{
					this.buffer.set();

					if (this.utils.isEndOfElement())
					{
						return this.keydown.insertDblBreakLine(e);
					}

					return this.keydown.insertBreakLine(e);
				},
				onTab: function(e, key)
				{
					if (!this.opts.tabKey) return true;
					if (this.utils.isEmpty(this.code.get()) && this.opts.tabAsSpaces === false) return true;

					e.preventDefault();

					var node;
					if (this.keydown.pre && !e.shiftKey)
					{
						node = (this.opts.preSpaces) ? document.createTextNode(Array(this.opts.preSpaces + 1).join('\u00a0')) : document.createTextNode('\t');
						this.insert.node(node);
						this.code.sync();
					}
					else if (this.opts.tabAsSpaces !== false)
					{
						node = document.createTextNode(Array(this.opts.tabAsSpaces + 1).join('\u00a0'));
						this.insert.node(node);
						this.code.sync();
					}
					else
					{
						if (e.metaKey && key === 219) this.indent.decrease();
						else if (e.metaKey && key === 221) this.indent.increase();
						else if (!e.shiftKey) this.indent.increase();
						else this.indent.decrease();
					}

					return false;
				},
				replaceDivToBreakLine: function()
				{
					var blockElem = this.selection.getBlock();
					var blockHtml = blockElem.innerHTML.replace(/<br\s?\/?>/gi, '');
					if ((blockElem.tagName === 'DIV' || blockElem.tagName === 'P') && blockHtml === '' && !$(blockElem).hasClass('redactor-editor'))
					{
						var br = document.createElement('br');

						$(blockElem).replaceWith(br);
						this.caret.setBefore(br);

						this.code.sync();

						return false;
					}
				},
				replaceDivToParagraph: function()
				{
					var blockElem = this.selection.getBlock();
					var blockHtml = blockElem.innerHTML.replace(/<br\s?\/?>/gi, '');
					if (blockElem.tagName === 'DIV' && this.utils.isEmpty(blockHtml) && !$(blockElem).hasClass('redactor-editor'))
					{
						var p = document.createElement('p');
						p.innerHTML = this.opts.invisibleSpace;

						$(blockElem).replaceWith(p);
						this.caret.setStart(p);

						this.code.sync();

						return false;
					}
					else if (this.opts.cleanStyleOnEnter && blockElem.tagName == 'P')
					{
						$(blockElem).removeAttr('class').removeAttr('style');
					}
				},
				insertParagraph: function(e)
				{
					e.preventDefault();

					this.selection.get();

					var p = document.createElement('p');
					p.innerHTML = this.opts.invisibleSpace;

					this.range.deleteContents();
					this.range.insertNode(p);

					this.caret.setStart(p);

					this.code.sync();

					return false;
				},
				exitFromBlockquote: function(e)
				{
					if (!this.utils.isEndOfElement()) return;

					var tmp = $.trim($(this.keydown.block).html());
					if (tmp.search(/(<br\s?\/?>){2}$/i) != -1)
					{
						e.preventDefault();

						if (this.opts.linebreaks)
						{
							var br = document.createElement('br');
							$(this.keydown.blockquote).after(br);

							this.caret.setBefore(br);
							$(this.keydown.block).html(tmp.replace(/<br\s?\/?>$/i, ''));
						}
						else
						{
							var node = $(this.opts.emptyHtml);
							$(this.keydown.blockquote).after(node);
							this.caret.setStart(node);
						}

						return true;

					}

					return;

				},
				insertAfterLastElement: function(element)
				{
					if (!this.utils.isEndOfElement()) return;

					this.buffer.set();

					if (this.opts.linebreaks)
					{
						var contents = $('<div>').append($.trim(this.$editor.html())).contents();
						var last = contents.last()[0];
						if (last.tagName == 'SPAN' && last.innerHTML === '')
						{
							last = contents.prev()[0];
						}

						if (this.utils.getOuterHtml(last) != this.utils.getOuterHtml(element)) return;

						var br = document.createElement('br');
						$(element).after(br);
						this.caret.setAfter(br);

					}
					else
					{
						if (this.$editor.contents().last()[0] !== element) return;

						var node = $(this.opts.emptyHtml);
						$(element).after(node);
						this.caret.setStart(node);
					}
				},
				insertNewLine: function(e)
				{
					e.preventDefault();

					var node = document.createTextNode('\n');

					this.selection.get();

					this.range.deleteContents();
					this.range.insertNode(node);

					this.caret.setAfter(node);

					this.code.sync();

					return false;
				},
				insertBreakLine: function(e)
				{
					return this.keydown.insertBreakLineProcessing(e);
				},
				insertDblBreakLine: function(e)
				{
					return this.keydown.insertBreakLineProcessing(e, true);
				},
				insertBreakLineProcessing: function(e, dbl)
				{
					e.stopPropagation();

					this.selection.get();

					var br1 = document.createElement('br');

					if (this.utils.browser('msie'))
					{
						this.range.collapse(false);
						this.range.setEnd(this.range.endContainer, this.range.endOffset);
					}
					else
					{
						this.range.deleteContents();
					}

					this.range.insertNode(br1);

					// move br outside A tag
					var $parentA = $(br1).parent("a");

					if ($parentA.length > 0)
					{
						$parentA.find(br1).remove();
						$parentA.after(br1);
					}

					if (dbl === true)
					{
						var $next = $(br1).next();
						if ($next.length !== 0 && $next[0].tagName === 'BR' && this.utils.isEndOfEditor())
						{
							this.caret.setAfter(br1);
							this.code.sync();
							return false;
						}

						var br2 = document.createElement('br');

						this.range.insertNode(br2);
						this.caret.setAfter(br2);
					}
					else
					{
						// caret does not move after the br visual
						if (this.utils.browser('msie'))
						{
							var space = document.createElement('span');
							space.innerHTML = '&#x200b;';

							$(br1).after(space);

							this.range.setStartAfter(space);
							this.range.setEndAfter(space);
							$(space).remove();
						}
						else
						{
							var range = document.createRange();
							range.setStartAfter(br1);
							range.collapse(true);
							var selection = window.getSelection();
							selection.removeAllRanges();
							selection.addRange(range);
						}
					}

					this.code.sync();
					return false;
				},
				removeInvisibleSpace: function()
				{
					var $current = $(this.keydown.current);
					if ($current.text().search(/^\u200B$/g) === 0)
					{
						$current.remove();
					}
				},
				removeEmptyListInTable: function(e)
				{
					var $current = $(this.keydown.current);
					var $parent = $(this.keydown.parent);
					var td = $current.closest('td', this.$editor[0]);

					if (td.length !== 0 && $current.closest('li', this.$editor[0]) && $parent.children('li').length === 1)
					{
						if (!this.utils.isEmpty($current.text())) return;

						e.preventDefault();

						$current.remove();
						$parent.remove();

						this.caret.setStart(td);
					}
				}
			};
		},
		keyup: function()
		{
			return {
				init: function(e)
				{

					if (this.rtePaste) return;

					var key = e.which;

					this.keyup.current = this.selection.getCurrent();
					this.keyup.parent = this.selection.getParent();
					var $parent = this.utils.isRedactorParent($(this.keyup.parent).parent());

					// callback
					var keyupStop = this.core.setCallback('keyup', e);
					if (keyupStop === false)
					{
						e.preventDefault();
						return false;
					}

					// replace to p before / after the table or body
					if (!this.opts.linebreaks && this.keyup.current.nodeType === 3 && this.keyup.current.length <= 1 && (this.keyup.parent === false || this.keyup.parent.tagName == 'BODY'))
					{
						this.keyup.replaceToParagraph();
					}

					// replace div after lists
					if (!this.opts.linebreaks && this.utils.isRedactorParent(this.keyup.current) && this.keyup.current.tagName === 'DIV')
					{
						this.keyup.replaceToParagraph(false);
					}


					if (!this.opts.linebreaks && $(this.keyup.parent).hasClass('redactor-invisible-space') && ($parent === false || $parent[0].tagName == 'BODY'))
					{
						$(this.keyup.parent).contents().unwrap();
						this.keyup.replaceToParagraph();
					}

					// linkify
					if (this.linkify.isEnabled() && this.linkify.isKey(key)) this.linkify.format();

					if (key === this.keyCode.DELETE || key === this.keyCode.BACKSPACE)
					{
						if (this.utils.browser('mozilla'))
						{
							var td = $(this.keydown.current).closest('td', this.$editor[0]);
							if (td.size() !== 0 && td.text() !== '')
							{
								e.preventDefault();
								return false;
							}
						}

						// clear unverified
						this.clean.clearUnverified();

						if (this.observe.image)
						{
							e.preventDefault();

							this.image.hideResize();

							this.buffer.set();
							this.image.remove(this.observe.image);
							this.observe.image = false;

							return false;
						}

						// remove empty paragraphs
						this.$editor.find('p').each($.proxy(function(i, s)
						{
							this.utils.removeEmpty(i, $(s).html());
						}, this));

						// remove invisible space
						if (this.opts.linebreaks && this.keyup.current && this.keyup.current.tagName == 'DIV' && this.utils.isEmpty(this.keyup.current.innerHTML))
						{
							$(this.keyup.current).after(this.selection.getMarkerAsHtml());
							this.selection.restore();
							$(this.keyup.current).remove();
						}

						this.keyup.removeEmptyLists();

						// if empty
						return this.keyup.formatEmpty(e);
					}
				},
				replaceToParagraph: function(clone)
				{
					var $current = $(this.keyup.current);

					var node;
					if (clone === false)
					{
						node = $('<p>').append($current.html());
					}
					else
					{
						node = $('<p>').append($current.clone());
					}

					$current.replaceWith(node);
					var next = $(node).next();
					if (typeof(next[0]) !== 'undefined' && next[0].tagName == 'BR')
					{
						next.remove();
					}

					this.caret.setEnd(node);
				},
				removeEmptyLists: function()
				{
					var removeIt = function()
					{
						var html = $.trim(this.innerHTML).replace(/\/t\/n/g, '');
						if (html === '')
						{
							$(this).remove();
						}
					};

					this.$editor.find('li').each(removeIt);
					this.$editor.find('ul, ol').each(removeIt);
				},
				formatEmpty: function(e)
				{
					var html = $.trim(this.$editor.html());

					if (!this.utils.isEmpty(html)) return;

					e.preventDefault();

					if (this.opts.linebreaks)
					{
						this.$editor.html(this.selection.getMarkerAsHtml());
						this.selection.restore();
					}
					else
					{
						this.$editor.html(this.opts.emptyHtml);
						this.focus.setStart();
					}

					this.code.sync();

					return false;
				}
			};
		},
		lang: function()
		{
			return {
				load: function()
				{
					this.opts.curLang = this.opts.langs[this.opts.lang];
				},
				get: function(name)
				{
					return (typeof this.opts.curLang[name] != 'undefined') ? this.opts.curLang[name] : '';
				}
			};
		},
		line: function()
		{
			return {
				insert: function()
				{
					this.buffer.set();

					var blocks = this.selection.getBlocks();
 					if (blocks[0] !== false && this.line.isExceptLastOrFirst(blocks))
	 				{
	 					if (!this.utils.browser('msie')) this.$editor.focus();
	 					return;
					}

					if (this.utils.browser('msie'))
					{
						this.line.insertInIe();
					}
					else
					{
						this.line.insertInOthersBrowsers();
					}
				},
				isExceptLastOrFirst: function(blocks)
				{
					var exceptTags = ['li', 'td', 'th', 'blockquote', 'figcaption', 'pre', 'dl', 'dt', 'dd'];

					var first = blocks[0].tagName.toLowerCase();
					var last = this.selection.getLastBlock();

					last = (typeof last == 'undefined') ? first : last.tagName.toLowerCase();

					var firstFound = $.inArray(first, exceptTags) != -1;
					var lastFound = $.inArray(last, exceptTags) != -1;

					if ((firstFound && lastFound) || firstFound)
					{
						return true;
					}
				},
				insertInIe: function()
				{
					this.utils.saveScroll();
					this.buffer.set();

					this.insert.node(document.createElement('hr'));

					this.utils.restoreScroll();
					this.code.sync();
				},
				insertInOthersBrowsers: function()
				{
					this.buffer.set();

					var extra = '<p id="redactor-insert-line"><br /></p>';
					if (this.opts.linebreaks) extra = '<br id="redactor-insert-line">';

					document.execCommand('insertHtml', false, '<hr>' + extra);

					this.line.setFocus();
					this.code.sync();
				},
				setFocus: function()
				{
					var node = this.$editor.find('#redactor-insert-line');
					var next = $(node).next()[0];
					var target = next;
					if (this.utils.browser('mozilla') && next && next.innerHTML === '')
					{
						target = $(next).next()[0];
						$(next).remove();
					}

					if (target)
					{
						node.remove();

						if (!this.opts.linebreaks)
						{
							this.$editor.focus();
							this.line.setStart(target);
						}

					}
					else
					{

						node.removeAttr('id');
						this.line.setStart(node[0]);
					}
				},
				setStart: function(node)
				{
					if (typeof node === 'undefined') return;

					var textNode = document.createTextNode('\u200B');

					this.selection.get();
					this.range.setStart(node, 0);
					this.range.insertNode(textNode);
					this.range.collapse(true);
					this.selection.addRange();

				}
			};
		},
		link: function()
		{
			return {
				show: function(e)
				{
					if (typeof e != 'undefined' && e.preventDefault) e.preventDefault();

					if (!this.observe.isCurrent('a'))
					{
						this.modal.load('link', this.lang.get('link_insert'), 600);
					}
					else
					{
						this.modal.load('link', this.lang.get('link_edit'), 600);
					}

					this.modal.createCancelButton();

					var buttonText = !this.observe.isCurrent('a') ? this.lang.get('insert') : this.lang.get('edit');

					this.link.buttonInsert = this.modal.createActionButton(buttonText);

					this.selection.get();

					this.link.getData();
					this.link.cleanUrl();

					if (this.link.target == '_blank') this.$modal.find('#redactor-link-blank').prop('checked', true);

					this.link.$inputUrl = this.$modal.find('#redactor-link-url');
					this.link.$inputText = this.$modal.find('#redactor-link-url-text');

					this.link.$inputText.val(this.link.text);
					this.link.$inputUrl.val(this.link.url);

					this.link.buttonInsert.on('click', $.proxy(this.link.insert, this));

					// hide link's tooltip
					$('.redactor-link-tooltip').remove();

					// show modal
					this.selection.save();
					this.modal.show();
					this.link.$inputUrl.focus();
				},
				cleanUrl: function()
				{
					var thref = self.location.href.replace(/\/$/i, '');

					if (typeof this.link.url !== "undefined")
					{
						this.link.url = this.link.url.replace(thref, '');
						this.link.url = this.link.url.replace(/^\/#/, '#');
						this.link.url = this.link.url.replace('mailto:', '');

						// remove host from href
						if (!this.opts.linkProtocol)
						{
							var re = new RegExp('^(http|ftp|https)://' + self.location.host, 'i');
							this.link.url = this.link.url.replace(re, '');
						}
					}
				},
				getData: function()
				{
					this.link.$node = false;

					var $el = $(this.selection.getCurrent()).closest('a', this.$editor[0]);
					if ($el.length !== 0 && $el[0].tagName === 'A')
					{
						this.link.$node = $el;

						this.link.url = $el.attr('href');
						this.link.text = $el.text();
						this.link.target = $el.attr('target');
					}
					else
					{
						this.link.text = this.sel.toString();
						this.link.url = '';
						this.link.target = '';
					}

				},
				insert: function()
				{
					this.placeholder.remove();

					var target = '';
					var link = this.link.$inputUrl.val();
					var text = this.link.$inputText.val().replace(/(<([^>]+)>)/ig,"");

					if ($.trim(link) === '')
					{
						this.link.$inputUrl.addClass('redactor-input-error').on('keyup', function()
						{
							$(this).removeClass('redactor-input-error');
							$(this).off('keyup');

						});

						return;
					}

					// mailto
					if (link.search('@') != -1 && /(http|ftp|https):\/\//i.test(link) === false)
					{
						link = link.replace('mailto:', '');
						link = 'mailto:' + link;
					}
					// url, not anchor
					else if (link.search('#') !== 0)
					{
						if (this.$modal.find('#redactor-link-blank').prop('checked'))
						{
							target = '_blank';
						}

						// test url (add protocol)
						var pattern = '((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}';
						var re = new RegExp('^(http|ftp|https)://' + pattern, 'i');
						var re2 = new RegExp('^' + pattern, 'i');
						var re3 = new RegExp('\.(html|php)$', 'i');
						if (link.search(re) == -1 && link.search(re3) == -1 && link.search(re2) === 0 && this.opts.linkProtocol)
						{
							link = this.opts.linkProtocol + '://' + link;
						}
					}

					this.link.set(text, link, target);
					this.modal.close();
				},
				set: function(text, link, target)
				{
					text = $.trim(text.replace(/<|>/g, ''));

					this.selection.restore();
					var blocks = this.selection.getBlocks();

					if (text === '' && link === '') return;
					if (text === '' && link !== '') text = link;

					if (this.link.$node)
					{
						this.buffer.set();

						var $link = this.link.$node,
							$el   = $link.children();

						if ($el.length > 0)
						{
							while ($el.length)
							{
								$el = $el.children();
							}

							$el = $el.end();
						}
						else
						{
							$el = $link;
						}

						$link.attr('href', link);
						$el.text(text);

						if (target !== '')
						{
							$link.attr('target', target);
						}
						else
						{
							$link.removeAttr('target');
						}

						this.selection.selectElement($link);

						this.code.sync();
					}
					else
					{
						if (this.utils.browser('mozilla') && this.link.text === '')
						{
							var $a = $('<a />').attr('href', link).text(text);
							if (target !== '') $a.attr('target', target);

							$a = $(this.insert.node($a));

							if (this.opts.linebreaks)
							{
								$a.after('&nbsp;');
							}

							this.selection.selectElement($a);
						}
						else
						{
							var $a;
							if (this.utils.browser('msie'))
							{
								$a = $('<a href="' + link + '">').text(text);
								if (target !== '') $a.attr('target', target);

								$a = $(this.insert.node($a));

								if (this.selection.getText().match(/\s$/))
								{
									$a.after(" ");
								}

								this.selection.selectElement($a);
							}
							else
							{
								document.execCommand('createLink', false, link);

								$a = $(this.selection.getCurrent()).closest('a', this.$editor[0]);
								if (this.utils.browser('mozilla'))
								{
									$a = $('a[_moz_dirty=""]');
								}

								if (target !== '') $a.attr('target', target);
								$a.removeAttr('style').removeAttr('_moz_dirty');

								if (this.selection.getText().match(/\s$/))
								{
									$a.after(" ");
								}

								if (this.link.text !== '' || this.link.text != text)
								{
									if (!this.opts.linebreaks && blocks && blocks.length <= 1)
									{
										$a.text(text);
									}
									else if (this.opts.linebreaks)
									{
										$a.text(text);
									}

									this.selection.selectElement($a);
								}
							}
						}

						this.code.sync();
						this.core.setCallback('insertedLink', $a);

					}

					// link tooltip
					setTimeout($.proxy(function()
					{
						this.observe.links();

					}, this), 5);
				},
				unlink: function(e)
				{
					if (typeof e != 'undefined' && e.preventDefault)
					{
						e.preventDefault();
					}

					var nodes = this.selection.getNodes();
					if (!nodes) return;

					this.buffer.set();

					var len = nodes.length;
					var links = [];
					for (var i = 0; i < len; i++)
					{
						if (nodes[i].tagName === 'A')
						{
							links.push(nodes[i]);
						}

						var $node = $(nodes[i]).closest('a', this.$editor[0]);
						$node.replaceWith($node.contents());
					}

					this.core.setCallback('deletedLink', links);

					// hide link's tooltip
					$('.redactor-link-tooltip').remove();

					this.code.sync();

				},
				toggleClass: function(className)
				{
					this.link.setClass(className, 'toggleClass');
				},
				addClass: function(className)
				{
					this.link.setClass(className, 'addClass');
				},
				removeClass: function(className)
				{
					this.link.setClass(className, 'removeClass');
				},
				setClass: function(className, func)
				{
					var links = this.selection.getInlinesTags(['a']);
					if (links === false) return;

					$.each(links, function()
					{
						$(this)[func](className);
					});
				}
			};
		},
		linkify: function()
		{
			return {
				isKey: function(key)
				{
					return key == this.keyCode.ENTER || key == this.keyCode.SPACE;
				},
				isEnabled: function()
				{
					return this.opts.convertLinks && (this.opts.convertUrlLinks || this.opts.convertImageLinks || this.opts.convertVideoLinks) && !this.utils.isCurrentOrParent('PRE');
				},
				format: function()
				{
					var linkify = this.linkify,
						opts    = this.opts;

					this.$editor
						.find(":not(iframe,img,a,pre)")
						.addBack()
						.contents()
						.filter(function()
						{
							return this.nodeType === 3 && $.trim(this.nodeValue) != "" && !$(this).parent().is("pre") && (this.nodeValue.match(opts.linkify.regexps.youtube) || this.nodeValue.match(opts.linkify.regexps.vimeo) || this.nodeValue.match(opts.linkify.regexps.image) || this.nodeValue.match(opts.linkify.regexps.url));
						})
						.each(function()
						{
							var text = $(this).text(),
								html = text;

							if (opts.convertVideoLinks && (html.match(opts.linkify.regexps.youtube) || html.match(opts.linkify.regexps.vimeo)) )
							{
								html = linkify.convertVideoLinks(html);
							}
							else if (opts.convertImageLinks && html.match(opts.linkify.regexps.image))
							{
								html = linkify.convertImages(html);
							}
							else if (opts.convertUrlLinks)
							{
								html = linkify.convertLinks(html);
							}

							$(this).before(text.replace(text, html))
								   .remove();
						});


					var objects = this.$editor.find('.redactor-linkify-object').each(function()
					{
						var $el = $(this);
						$el.removeClass('redactor-linkify-object');
						if ($el.attr('class') === '') $el.removeAttr('class');

						return $el[0];

					});

					// callback
					setTimeout($.proxy(function()
					{
						this.observe.load();
						this.core.setCallback('linkify', objects);
					}, this), 100);

					// sync
					this.code.sync();
				},
				convertVideoLinks: function(html)
				{
					var iframeStart = '<iframe class="redactor-linkify-object" width="500" height="281" src="',
						iframeEnd = '" frameborder="0" allowfullscreen></iframe>';

					if (html.match(this.opts.linkify.regexps.youtube))
					{
						html = html.replace(this.opts.linkify.regexps.youtube, iframeStart + '//www.youtube.com/embed/$1' + iframeEnd);
					}

					if (html.match(this.opts.linkify.regexps.vimeo))
					{
						html = html.replace(this.opts.linkify.regexps.vimeo, iframeStart + '//player.vimeo.com/video/$2' + iframeEnd);
					}

					return html;
				},
				convertImages: function(html)
				{
					var matches = html.match(this.opts.linkify.regexps.image);

					if (matches)
					{
						html = html.replace(html, '<img src="' + matches + '" class="redactor-linkify-object" />');

						if (this.opts.linebreaks)
						{
							if (!this.utils.isEmpty(this.code.get()))
							{
								html = '<br>' + html;
							}
						}

						html += '<br>';
					}

					return html;
				},
				convertLinks: function(html)
				{
					var matches = html.match(this.opts.linkify.regexps.url);

					if (matches)
					{
						matches = $.grep(matches, function(v, k) { return $.inArray(v, matches) === k; });

						var length = matches.length;

						for (var i = 0; i < length; i++)
						{
							var href = matches[i],
								text = href,
								linkProtocol = this.opts.linkProtocol + '://';

							if (href.match(/(https?|ftp):\/\//i) !== null)
							{
								linkProtocol = "";
							}

							if (text.length > this.opts.linkSize)
							{
								text = text.substring(0, this.opts.linkSize) + '...';
							}

							if (text.search('%') === -1)
							{
								text = decodeURIComponent(text);
							}

							var regexB = "\\b";

							if ($.inArray(href.slice(-1), ["/", "&", "="]) != -1)
							{
								regexB = "";
							}

							// escaping url
							var regexp = new RegExp('(' + href.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + regexB + ')', 'g');

							html = html.replace(regexp, '<a href="' + linkProtocol + $.trim(href) + '" class="redactor-linkify-object">' + $.trim(text) + '</a>');
						}
					}

					return html;
				}
			};
		},
		list: function()
		{
			return {
				toggle: function(cmd)
				{
					this.placeholder.remove();

					if (!this.utils.browser('msie') && !this.opts.linebreaks)
					{
						this.$editor.focus();
					}

					this.buffer.set();
					this.selection.save();

					var parent = this.selection.getParent();
					var $list = $(parent).closest('ol, ul', this.$editor[0]);

					if (!this.utils.isRedactorParent($list) && $list.length !== 0)
					{
						$list = false;
					}

					var isUnorderedCmdOrdered, isOrderedCmdUnordered;
					var remove = false;
					if ($list && $list.length)
					{
						remove = true;
						var listTag = $list[0].tagName;

						isUnorderedCmdOrdered = (cmd === 'orderedlist' && listTag === 'UL');
						isOrderedCmdUnordered = (cmd === 'unorderedlist' && listTag === 'OL');
					}

					if (isUnorderedCmdOrdered)
					{
						this.utils.replaceToTag($list, 'ol');
					}
					else if (isOrderedCmdUnordered)
					{
						this.utils.replaceToTag($list, 'ul');
					}
					else
					{
						if (remove)
						{
							this.list.remove(cmd, $list);
						}
						else
						{
							this.list.insert(cmd);
						}
					}

					this.selection.restore();
					this.code.sync();

				},
				insert: function(cmd)
				{
					var current = this.selection.getCurrent();
					var $td = $(current).closest('td, th', this.$editor[0]);

					if (this.utils.browser('msie') && this.opts.linebreaks)
					{
						this.list.insertInIe(cmd);
					}
					else
					{
						document.execCommand('insert' + cmd);
					}

					var parent = this.selection.getParent();
					var $list = $(parent).closest('ol, ul', this.$editor[0]);
					if ($td.length !== 0)
					{
						var newTd = $td.clone();
						$td.after(newTd).remove('');
					}


					if (this.utils.isEmpty($list.find('li').text()))
					{
						var $children = $list.children('li');
						$children.find('br').remove();
						$children.append(this.selection.getMarkerAsHtml());

						if (this.opts.linebreaks && this.utils.browser('mozilla') && $children.size() == 2 && this.utils.isEmpty($children.eq(1).text()))
						{
							$children.eq(1).remove();
						}
					}

					if ($list.length)
					{
						// remove block-element list wrapper
						var $listParent = $list.parent();
						if (this.utils.isRedactorParent($listParent) && $listParent[0].tagName != 'LI' && this.utils.isBlock($listParent[0]))
						{
							$listParent.replaceWith($listParent.contents());
						}
					}

					if (!this.utils.browser('msie'))
					{
						this.$editor.focus();
					}


					this.clean.clearUnverified();
				},
				insertInIe: function(cmd)
				{
					var wrapper = this.selection.wrap('div');
					var wrapperHtml = $(wrapper).html();

					var tmpList = (cmd == 'orderedlist') ? $('<ol>') : $('<ul>');
					var tmpLi = $('<li>');

					if ($.trim(wrapperHtml) === '')
					{
						tmpLi.append(this.selection.getMarkerAsHtml());
						tmpList.append(tmpLi);
						this.$editor.find('#selection-marker-1').replaceWith(tmpList);
					}
					else
					{
						var items = wrapperHtml.split(/<br\s?\/?>/gi);
						if (items)
						{
							for (var i = 0; i < items.length; i++)
							{
								if ($.trim(items[i]) !== '')
								{
									tmpList.append($('<li>').html(items[i]));
								}
							}
						}
						else
						{
							tmpLi.append(wrapperHtml);
							tmpList.append(tmpLi);
						}

						$(wrapper).replaceWith(tmpList);
					}
				},
				remove: function(cmd, $list)
				{
					if ($.inArray('ul', this.selection.getBlocks())) cmd = 'unorderedlist';

					document.execCommand('insert' + cmd);

					var $current = $(this.selection.getCurrent());
					this.indent.fixEmptyIndent();

					if (!this.opts.linebreaks && $current.closest('li, th, td', this.$editor[0]).length === 0)
					{
						document.execCommand('formatblock', false, 'p');
						this.$editor.find('ul, ol, blockquote').each($.proxy(this.utils.removeEmpty, this));
					}

					var $table = $(this.selection.getCurrent()).closest('table', this.$editor[0]);
					var $prev = $table.prev();
					if (!this.opts.linebreaks && $table.length !== 0 && $prev.length !== 0 && $prev[0].tagName == 'BR')
					{
						$prev.remove();
					}

					this.clean.clearUnverified();


				}
			};
		},
		modal: function()
		{
			return {
				callbacks: {},
				loadTemplates: function()
				{
					this.opts.modal = {
						imageEdit: String()
						+ '<section id="redactor-modal-image-edit">'
							+ '<label>' + this.lang.get('title') + '</label>'
							+ '<input type="text" id="redactor-image-title" />'
							+ '<label class="redactor-image-link-option">' + this.lang.get('link') + '</label>'
							+ '<input type="text" id="redactor-image-link" class="redactor-image-link-option" aria-label="' + this.lang.get('link') + '" />'
							+ '<label class="redactor-image-link-option"><input type="checkbox" id="redactor-image-link-blank" aria-label="' + this.lang.get('link_new_tab') + '"> ' + this.lang.get('link_new_tab') + '</label>'
							+ '<label class="redactor-image-position-option">' + this.lang.get('image_position') + '</label>'
							+ '<select class="redactor-image-position-option" id="redactor-image-align" aria-label="' + this.lang.get('image_position') + '">'
								+ '<option value="none">' + this.lang.get('none') + '</option>'
								+ '<option value="left">' + this.lang.get('left') + '</option>'
								+ '<option value="center">' + this.lang.get('center') + '</option>'
								+ '<option value="right">' + this.lang.get('right') + '</option>'
							+ '</select>'
						+ '</section>',

						image: String()
						+ '<section id="redactor-modal-image-insert">'
							+ '<div id="redactor-modal-image-droparea"></div>'
 						+ '</section>',

						file: String()
						+ '<section id="redactor-modal-file-insert">'
							+ '<div id="redactor-modal-file-upload-box">'
								+ '<label>' + this.lang.get('filename') + '</label>'
								+ '<input type="text" id="redactor-filename" aria-label="' + this.lang.get('filename') + '" /><br><br>'
								+ '<div id="redactor-modal-file-upload"></div>'
							+ '</div>'
						+ '</section>',

						link: String()
						+ '<section id="redactor-modal-link-insert">'
							+ '<label>URL</label>'
							+ '<input type="url" id="redactor-link-url" aria-label="URL" />'
							+ '<label>' + this.lang.get('text') + '</label>'
							+ '<input type="text" id="redactor-link-url-text" aria-label="' + this.lang.get('text') + '" />'
							+ '<label><input type="checkbox" id="redactor-link-blank"> ' + this.lang.get('link_new_tab') + '</label>'
						+ '</section>'
					};


					$.extend(this.opts, this.opts.modal);

				},
				addCallback: function(name, callback)
				{
					this.modal.callbacks[name] = callback;
				},
				createTabber: function($modal)
				{
					this.modal.$tabber = $('<div>').attr('id', 'redactor-modal-tabber');

					$modal.prepend(this.modal.$tabber);
				},
				addTab: function(id, name, active)
				{
					var $tab = $('<a href="#" rel="tab' + id + '">').text(name);
					if (active)
					{
						$tab.addClass('active');
					}

					var self = this;
					$tab.on('click', function(e)
					{
						e.preventDefault();
						self.$modal.find('.redactor-tab').hide();
						self.$modal.find('.redactor-' + $(this).attr('rel')).show();

						self.modal.$tabber.find('a').removeClass('active');
						$(this).addClass('active');

					});

					this.modal.$tabber.append($tab);
				},
				addTemplate: function(name, template)
				{
					this.opts.modal[name] = template;
				},
				getTemplate: function(name)
				{
					return this.opts.modal[name];
				},
				getModal: function()
				{
					return this.$modalBody.find('section');
				},
				load: function(templateName, title, width)
				{
					this.modal.templateName = templateName;
					this.modal.width = width;

					this.modal.build();
					this.modal.enableEvents();
					this.modal.setTitle(title);
					this.modal.setDraggable();
					this.modal.setContent();

					// callbacks
					if (typeof this.modal.callbacks[templateName] != 'undefined')
					{
						this.modal.callbacks[templateName].call(this);
					}

				},
				show: function()
				{
					this.utils.disableBodyScroll();

					if (this.utils.isMobile())
					{
						this.modal.showOnMobile();
					}
					else
					{
						this.modal.showOnDesktop();
					}

					if (this.opts.highContrast)
					{
						this.$modalBox.addClass("redactor-modal-contrast");
					}

					this.$modalOverlay.show();
					this.$modalBox.show();

					this.$modal.attr('tabindex', '-1');
					this.$modal.focus();

					this.modal.setButtonsWidth();

					this.utils.saveScroll();

					// resize
					if (!this.utils.isMobile())
					{
						setTimeout($.proxy(this.modal.showOnDesktop, this), 0);
						$(window).on('resize.redactor-modal', $.proxy(this.modal.resize, this));
					}

					// modal shown callback
					this.core.setCallback('modalOpened', this.modal.templateName, this.$modal);

					// fix bootstrap modal focus
					$(document).off('focusin.modal');

					// enter
					this.$modal.find('input[type=text],input[type=url],input[type=email]').on('keydown.redactor-modal', $.proxy(this.modal.setEnter, this));
				},
				showOnDesktop: function()
				{
					var height = this.$modal.outerHeight();
					var windowHeight = $(window.top).height();
					var windowWidth = $(window.top).width();

					if (this.modal.width > windowWidth)
					{
						this.$modal.css({
							width: '96%',
							marginTop: (windowHeight/2 - height/2) + 'px'
						});
						return;
					}

					if (height > windowHeight)
					{
						this.$modal.css({
							width: this.modal.width + 'px',
							marginTop: '20px'
						});
					}
					else
					{
						this.$modal.css({
							width: this.modal.width + 'px',
							marginTop: (windowHeight/2 - height/2) + 'px'
						});
					}
				},
				showOnMobile: function()
				{
					this.$modal.css({
						width: '96%',
						marginTop: '2%'
					});

				},
				resize: function()
				{
					if (this.utils.isMobile())
					{
						this.modal.showOnMobile();
					}
					else
					{
						this.modal.showOnDesktop();
					}
				},
				setTitle: function(title)
				{
					this.$modalHeader.html(title);
				},
				setContent: function()
				{
					this.$modalBody.html(this.modal.getTemplate(this.modal.templateName));
				},
				setDraggable: function()
				{
					if (typeof $.fn.draggable === 'undefined') return;

					this.$modal.draggable({ handle: this.$modalHeader });
					this.$modalHeader.css('cursor', 'move');
				},
				setEnter: function(e)
				{
					if (e.which != 13) return;

					e.preventDefault();
					this.$modal.find('button.redactor-modal-action-btn').click();
				},
				createCancelButton: function()
				{
					var button = $('<button>').addClass('redactor-modal-btn redactor-modal-close-btn').html(this.lang.get('cancel'));
					button.on('click', $.proxy(this.modal.close, this));

					this.$modalFooter.append(button);
				},
				createDeleteButton: function(label)
				{
					return this.modal.createButton(label, 'delete');
				},
				createActionButton: function(label)
				{
					return this.modal.createButton(label, 'action');
				},
				createButton: function(label, className)
				{
					var button = $('<button>').addClass('redactor-modal-btn').addClass('redactor-modal-' + className + '-btn').html(label);
					this.$modalFooter.append(button);

					return button;
				},
				setButtonsWidth: function()
				{
					var buttons = this.$modalFooter.find('button');
					var buttonsSize = buttons.length;
					if (buttonsSize === 0) return;

					buttons.css('width', (100/buttonsSize) + '%');
				},
				build: function()
				{
					this.modal.buildOverlay();

					this.$modalBox = $('<div id="redactor-modal-box"/>').hide();
					this.$modal = $('<div id="redactor-modal" role="dialog" aria-labelledby="redactor-modal-header" />');
					this.$modalHeader = $('<header id="redactor-modal-header"/>');
					this.$modalClose = $('<button type="button" id="redactor-modal-close" tabindex="1" aria-label="Close" />').html('&times;');
					this.$modalBody = $('<div id="redactor-modal-body" />');
					this.$modalFooter = $('<footer />');

					this.$modal.append(this.$modalHeader);
					this.$modal.append(this.$modalClose);
					this.$modal.append(this.$modalBody);
					this.$modal.append(this.$modalFooter);
					this.$modalBox.append(this.$modal);
					this.$modalBox.appendTo(window.top.document.body);
				},
				buildOverlay: function()
				{
					this.$modalOverlay = $('<div id="redactor-modal-overlay">').hide();
					$(window.top.document.body).prepend(this.$modalOverlay);
				},
				enableEvents: function()
				{
					this.$modalClose.on('click.redactor-modal', $.proxy(this.modal.close, this));
					$(document).on('keyup.redactor-modal', $.proxy(this.modal.closeHandler, this));
					this.$editor.on('keyup.redactor-modal', $.proxy(this.modal.closeHandler, this));
					this.$modalBox.on('click.redactor-modal', $.proxy(this.modal.close, this));
				},
				disableEvents: function()
				{
					this.$modalClose.off('click.redactor-modal');
					$(document).off('keyup.redactor-modal');
					this.$editor.off('keyup.redactor-modal');
					this.$modalBox.off('click.redactor-modal');
					$(window).off('resize.redactor-modal');
				},
				closeHandler: function(e)
				{
					if (e.which != this.keyCode.ESC) return;

					this.modal.close(false);
				},
				close: function(e)
				{
					if (e)
					{
						if (!$(e.target).hasClass('redactor-modal-close-btn') && e.target != this.$modalClose[0] && e.target != this.$modalBox[0])
						{
							return;
						}

						e.preventDefault();
					}

					if (!this.$modalBox) return;

					this.modal.disableEvents();
					this.utils.enableBodyScroll();

					this.$modalOverlay.remove();

					this.$modalBox.fadeOut('fast', $.proxy(function()
					{
						this.$modalBox.remove();

						setTimeout($.proxy(this.utils.restoreScroll, this), 0);

						if (e !== undefined) this.selection.restore();

						$(document.body).css('overflow', this.modal.bodyOveflow);
						this.core.setCallback('modalClosed', this.modal.templateName);

					}, this));

				}
			};
		},
		observe: function()
		{
			return {
				load: function()
				{
					if (typeof this.opts.destroyed != "undefined") return;

					if (this.utils.browser('msie'))
					{
						var self = this;
						this.$editor.find('pre, code').on('mouseover',function()
						{
							self.$editor.attr('contenteditable', false);
							$(this).attr('contenteditable', true);

						}).on('mouseout',function()
						{
							self.$editor.attr('contenteditable', true);
							$(this).removeAttr('contenteditable');

						});
					}

					this.observe.images();
					this.observe.links();
				},
				toolbar: function(e, btnName)
				{
					this.observe.buttons(e, btnName);
					this.observe.dropdowns();
				},
				isCurrent: function($el, $current)
				{
					if (typeof $current == 'undefined')
					{
						var $current = $(this.selection.getCurrent());
					}

					return $current.is($el) || $current.parents($el).length > 0;
				},
				dropdowns: function()
				{
					var $current = $(this.selection.getCurrent());

					$.each(this.opts.observe.dropdowns, $.proxy(function(key, value)
					{
						var observe = value.observe,
							element = observe.element,
							$item   = value.item,
							inValues = typeof observe['in'] != 'undefined' ? observe['in'] : false,
							outValues = typeof observe['out'] != 'undefined' ? observe['out'] : false;

						if ($current.closest(element).size() > 0)
						{
							this.observe.setDropdownProperties($item, inValues, outValues);
						}
						else
						{
							this.observe.setDropdownProperties($item, outValues, inValues);
						}
					}, this));
				},
				setDropdownProperties: function($item, addProperties, deleteProperties)
				{
					if (deleteProperties && typeof deleteProperties['attr'] != 'undefined')
					{
						this.observe.setDropdownAttr($item, deleteProperties.attr, true);
					}

					if (typeof addProperties['attr'] != 'undefined')
					{
						this.observe.setDropdownAttr($item, addProperties.attr);
					}

					if (typeof addProperties['title'] != 'undefined')
					{
						$item.text(addProperties['title']);
					}
				},
				setDropdownAttr: function($item, properties, isDelete)
				{
					$.each(properties, function(key, value)
					{
						if (key == 'class')
						{
							if (!isDelete)
							{
								$item.addClass(value);
							}
							else
							{
								$item.removeClass(value);
							}
						}
						else
						{
							if (!isDelete)
							{
								$item.attr(key, value);
							}
							else
							{
								$item.removeAttr(key);
							}
						}
					});
				},
				addDropdown: function($item, btnName, btnObject)
				{
					if (typeof btnObject.observe == "undefined") return;

					btnObject.item = $item;

					this.opts.observe.dropdowns.push(btnObject);
				},
				buttons: function(e, btnName)
				{
					var current = this.selection.getCurrent();
					var parent = this.selection.getParent();

					if (e !== false)
					{
						this.button.setInactiveAll();
					}
					else
					{
						this.button.setInactiveAll(btnName);
					}

					if (e === false && btnName !== 'html')
					{
						if ($.inArray(btnName, this.opts.activeButtons) != -1) this.button.toggleActive(btnName);
						return;
					}

					//var linkButtonName = (this.utils.isCurrentOrParent('A')) ? this.lang.get('link_edit') : this.lang.get('link_insert');
					//$('body').find('a.redactor-dropdown-link').text(linkButtonName);

					$.each(this.opts.activeButtonsStates, $.proxy(function(key, value)
					{
						var parentEl = $(parent).closest(key, this.$editor[0]);
						var currentEl = $(current).closest(key, this.$editor[0]);

						if (parentEl.length !== 0 && !this.utils.isRedactorParent(parentEl)) return;
						if (!this.utils.isRedactorParent(currentEl)) return;
						if (parentEl.length !== 0 || currentEl.closest(key, this.$editor[0]).length !== 0)
						{
							this.button.setActive(value);
						}

					}, this));

					var $parent = $(parent).closest(this.opts.alignmentTags.toString().toLowerCase(), this.$editor[0]);
					if (this.utils.isRedactorParent(parent) && $parent.length)
					{
						var align = ($parent.css('text-align') === '') ? 'left' : $parent.css('text-align');
						this.button.setActive('align' + align);
					}
				},
				addButton: function(tag, btnName)
				{
					this.opts.activeButtons.push(btnName);
					this.opts.activeButtonsStates[tag] = btnName;
				},
				images: function()
				{
					this.$editor.find('img').each($.proxy(function(i, img)
					{
						var $img = $(img);

						// IE fix (when we clicked on an image and then press backspace IE does goes to image's url)
						$img.closest('a', this.$editor[0]).on('click', function(e) { e.preventDefault(); });

						if (this.utils.browser('msie')) $img.attr('unselectable', 'on');

						this.image.setEditable($img);

					}, this));

					$(document).on('click.redactor-image-delete.' + this.uuid, $.proxy(function(e)
					{
						this.observe.image = false;
						if (e.target.tagName == 'IMG' && this.utils.isRedactorParent(e.target))
						{
							this.observe.image = (this.observe.image && this.observe.image == e.target) ? false : e.target;
						}

					}, this));

				},
				links: function()
				{
					if (!this.opts.linkTooltip) return;

					this.$editor.find('a').on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.showTooltip, this));
					this.$editor.on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this));
					$(document).on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this));
				},
				getTooltipPosition: function($link)
				{
					return $link.offset();
				},
				showTooltip: function(e)
				{
					var $el = $(e.target);

					if ($el[0].tagName == 'IMG')
						return;

					if ($el[0].tagName !== 'A')
						$el = $el.closest('a', this.$editor[0]);

					if ($el[0].tagName !== 'A')
						return;

					var $link = $el;

					var pos = this.observe.getTooltipPosition($link);
					var tooltip = $('<span class="redactor-link-tooltip"></span>');

					var href = $link.attr('href');
					if (href === undefined)
					{
						href = '';
					}

					if (href.length > 24) href = href.substring(0, 24) + '...';

					var aLink = $('<a href="' + $link.attr('href') + '" target="_blank" />').html(href).addClass('redactor-link-tooltip-action');
					var aEdit = $('<a href="#" />').html(this.lang.get('edit')).on('click', $.proxy(this.link.show, this)).addClass('redactor-link-tooltip-action');
					var aUnlink = $('<a href="#" />').html(this.lang.get('unlink')).on('click', $.proxy(this.link.unlink, this)).addClass('redactor-link-tooltip-action');

					tooltip.append(aLink).append(' | ').append(aEdit).append(' | ').append(aUnlink);
					tooltip.css({
						top: (pos.top + parseInt($link.css('line-height'), 10)) + 'px',
						left: pos.left + 'px'
					});

					$('.redactor-link-tooltip').remove();
					$('body').append(tooltip);
				},
				closeTooltip: function(e)
				{
					e = e.originalEvent || e;

					var target = e.target;
					var $parent = $(target).closest('a', this.$editor[0]);
					if ($parent.length !== 0 && $parent[0].tagName === 'A' && target.tagName !== 'A')
					{
						return;
					}
					else if ((target.tagName === 'A' && this.utils.isRedactorParent(target)) || $(target).hasClass('redactor-link-tooltip-action'))
					{
						return;
					}

					$('.redactor-link-tooltip').remove();
				}

			};
		},
		paragraphize: function()
		{
			return {
				load: function(html)
				{
					if (this.opts.linebreaks) return html;
					if (html === '' || html === '<p></p>') return this.opts.emptyHtml;

					html = html + "\n";

					this.paragraphize.safes = [];
					this.paragraphize.z = 0;

					html = html.replace(/(<br\s?\/?>){1,}\n?<\/blockquote>/gi, '</blockquote>');

					html = this.paragraphize.getSafes(html);
					html = this.paragraphize.getSafesComments(html);
					html = this.paragraphize.replaceBreaksToNewLines(html);
					html = this.paragraphize.replaceBreaksToParagraphs(html);
					html = this.paragraphize.clear(html);
					html = this.paragraphize.restoreSafes(html);

					html = html.replace(new RegExp('<br\\s?/?>\n?<(' + this.opts.paragraphizeBlocks.join('|') + ')(.*?[^>])>', 'gi'), '<p><br /></p>\n<$1$2>');

					return $.trim(html);
				},
				getSafes: function(html)
				{
					var $div = $('<div />').append(html);

					// remove paragraphs in blockquotes
					$div.find('blockquote p').replaceWith(function()
					{
						return $(this).append('<br />').contents();
					});

					html = $div.html();

					$div.find(this.opts.paragraphizeBlocks.join(', ')).each($.proxy(function(i,s)
					{
						this.paragraphize.z++;
						this.paragraphize.safes[this.paragraphize.z] = s.outerHTML;
						html = html.replace(s.outerHTML, '\n{replace' + this.paragraphize.z + '}');

					}, this));

					return html;
				},
				getSafesComments: function(html)
				{
					var commentsMatches = html.match(/<!--([\w\W]*?)-->/gi);

					if (!commentsMatches) return html;

					$.each(commentsMatches, $.proxy(function(i,s)
					{
						this.paragraphize.z++;
						this.paragraphize.safes[this.paragraphize.z] = s;
						html = html.replace(s, '\n{replace' + this.paragraphize.z + '}');
					}, this));

					return html;
				},
				restoreSafes: function(html)
				{
					$.each(this.paragraphize.safes, function(i,s)
					{
						s = (typeof s !== 'undefined') ? s.replace(/\$/g, '&#36;') : s;
						html = html.replace('{replace' + i + '}', s);

					});

					return html;
				},
				replaceBreaksToParagraphs: function(html)
				{
					var htmls = html.split(new RegExp('\n', 'g'), -1);

					html = '';
					if (htmls)
					{
						var len = htmls.length;
						for (var i = 0; i < len; i++)
						{
							if (!htmls.hasOwnProperty(i)) return;

							if (htmls[i].search('{replace') == -1)
							{
								htmls[i] = htmls[i].replace(/<p>\n\t?<\/p>/gi, '');
								htmls[i] = htmls[i].replace(/<p><\/p>/gi, '');

								if (htmls[i] !== '')
								{
									html += '<p>' +  htmls[i].replace(/^\n+|\n+$/g, "") + "</p>";
								}
							}
							else html += htmls[i];
						}
					}

					return html;
				},
				replaceBreaksToNewLines: function(html)
				{
					html = html.replace(/<br \/>\s*<br \/>/gi, "\n\n");
					html = html.replace(/<br\s?\/?>\n?<br\s?\/?>/gi, "\n<br /><br />");

					html = html.replace(new RegExp("\r\n", 'g'), "\n");
					html = html.replace(new RegExp("\r", 'g'), "\n");
					html = html.replace(new RegExp("/\n\n+/"), 'g', "\n\n");

					return html;
				},
				clear: function(html)
				{
					html = html.replace(new RegExp('</blockquote></p>', 'gi'), '</blockquote>');
					html = html.replace(new RegExp('<p></blockquote>', 'gi'), '</blockquote>');
					html = html.replace(new RegExp('<p><blockquote>', 'gi'), '<blockquote>');
					html = html.replace(new RegExp('<blockquote></p>', 'gi'), '<blockquote>');

					html = html.replace(new RegExp('<p><p ', 'gi'), '<p ');
					html = html.replace(new RegExp('<p><p>', 'gi'), '<p>');
					html = html.replace(new RegExp('</p></p>', 'gi'), '</p>');
					html = html.replace(new RegExp('<p>\\s?</p>', 'gi'), '');
					html = html.replace(new RegExp("\n</p>", 'gi'), '</p>');
					html = html.replace(new RegExp('<p>\t?\t?\n?<p>', 'gi'), '<p>');
					html = html.replace(new RegExp('<p>\t*</p>', 'gi'), '');

					return html;
				}
			};
		},
		paste: function()
		{
			return {
				init: function(e)
				{
					if (!this.opts.cleanOnPaste)
					{
						setTimeout($.proxy(this.code.sync, this), 1);
						return;
					}

					this.rtePaste = true;

					this.buffer.set();
					this.selection.save();
					this.utils.saveScroll();

					this.paste.createPasteBox();

					$(window).on('scroll.redactor-freeze', $.proxy(function()
					{
						$(window).scrollTop(this.saveBodyScroll);

					}, this));

					setTimeout($.proxy(function()
					{
						var html = this.$pasteBox.html();

						this.$pasteBox.remove();

						this.selection.restore();
						this.utils.restoreScroll();

						this.paste.insert(html);

						$(window).off('scroll.redactor-freeze');

						if (this.linkify.isEnabled())
						{
							this.linkify.format();
						}

					}, this), 1);
				},
				createPasteBox: function()
				{
					this.$pasteBox = $('<div>').html('').attr('contenteditable', 'true').css({ position: 'fixed', width: 0, top: 0, left: '-9999px' });

					if (this.utils.browser('msie'))
					{
						this.$box.append(this.$pasteBox);
					}
					else
					{
						// bootstrap modal
						var $visibleModals = $('.modal-body:visible');
						if ($visibleModals.length > 0)
						{
							$visibleModals.append(this.$pasteBox);
						}
						else
						{
							$('body').append(this.$pasteBox);
						}
					}

					this.$pasteBox.get(0).focus();
				},
				insert: function(html)
				{
					html = this.core.setCallback('pasteBefore', html);

					// clean
					html = (this.utils.isSelectAll()) ? this.clean.onPaste(html, false) : this.clean.onPaste(html);

					html = this.core.setCallback('paste', html);

					if (this.utils.isSelectAll())
					{
						this.insert.set(html, false);
					}
					else
					{
						this.insert.html(html, false);
					}

					this.utils.disableSelectAll();
					this.rtePaste = false;

					setTimeout($.proxy(this.clean.clearUnverified, this), 10);

					// clean empty spans
					setTimeout($.proxy(function()
					{
						var spans = this.$editor.find('span');
						$.each(spans, function(i,s)
						{
							var html = s.innerHTML.replace(/\u200B/, '');
							if (html === '' && s.attributes.length === 0) $(s).remove();

						});

					}, this), 10);

				}
			};
		},
		placeholder: function()
		{
			return {
				enable: function()
				{
					if (!this.placeholder.is()) return;

					this.$editor.attr('placeholder', this.$element.attr('placeholder'));

					this.placeholder.toggle();
					this.$editor.on('keydown.redactor-placeholder', $.proxy(this.placeholder.toggle, this));
				},
				toggle: function()
				{
					setTimeout($.proxy(function()
					{
						var func = this.utils.isEmpty(this.$editor.html(), false) ? 'addClass' : 'removeClass';
						this.$editor[func]('redactor-placeholder');

					}, this), 5);
				},
				remove: function()
				{
					this.$editor.removeClass('redactor-placeholder');
				},
				is: function()
				{
					if (this.opts.placeholder)
					{
						return this.$element.attr('placeholder', this.opts.placeholder);
					}
					else
					{
						return !(typeof this.$element.attr('placeholder') == 'undefined' || this.$element.attr('placeholder') === '');
					}
				}
			};
		},
		progress: function()
		{
			return {
				show: function()
				{
					$(document.body).append($('<div id="redactor-progress"><span></span></div>'));
					$('#redactor-progress').fadeIn();
				},
				hide: function()
				{
					$('#redactor-progress').fadeOut(1500, function()
					{
						$(this).remove();
					});
				}

			};
		},
		selection: function()
		{
			return {
				get: function()
				{
					this.sel = document.getSelection();

					if (document.getSelection && this.sel.getRangeAt && this.sel.rangeCount)
					{
						this.range = this.sel.getRangeAt(0);
					}
					else
					{
						this.range = document.createRange();
					}
				},
				addRange: function()
				{
					try {
						this.sel.removeAllRanges();
					} catch (e) {}

					this.sel.addRange(this.range);
				},
				getCurrent: function()
				{
					var el = false;

					this.selection.get();

					if (this.sel && this.sel.rangeCount > 0)
					{
						el = this.sel.getRangeAt(0).startContainer;
					}

					return this.utils.isRedactorParent(el);
				},
				getParent: function(elem)
				{
					elem = elem || this.selection.getCurrent();
					if (elem)
					{
						return this.utils.isRedactorParent($(elem).parent()[0]);
					}

					return false;
				},
				getPrev: function()
				{
					return  window.getSelection().anchorNode.previousSibling;
				},
				getNext: function()
				{
					return window.getSelection().anchorNode.nextSibling;
				},
				getBlock: function(node)
				{
					node = node || this.selection.getCurrent();

					while (node)
					{
						if (this.utils.isBlockTag(node.tagName))
						{
							return ($(node).hasClass('redactor-editor')) ? false : node;
						}

						node = node.parentNode;
					}

					return false;
				},
				getInlines: function(nodes, tags)
				{
					this.selection.get();

					if (this.range && this.range.collapsed)
					{
						return false;
					}

					var inlines = [];
					nodes = (typeof nodes == 'undefined' || nodes === false) ? this.selection.getNodes() : nodes;
					var inlineTags = this.opts.inlineTags;
					inlineTags.push('span');

					if (typeof tags !== 'undefined')
					{
						for (var i = 0; i < tags.length; i++)
						{
							inlineTags.push(tags[i]);
						}
					}

					$.each(nodes, $.proxy(function(i,node)
					{
						if ($.inArray(node.tagName.toLowerCase(), inlineTags) != -1)
						{
							inlines.push(node);
						}

					}, this));

					return (inlines.length === 0) ? false : inlines;
				},
				getInlinesTags: function(tags)
				{
					this.selection.get();

					if (this.range && this.range.collapsed)
					{
						return false;
					}

					var inlines = [];
					var nodes =  this.selection.getNodes();
					$.each(nodes, $.proxy(function(i,node)
					{
						if ($.inArray(node.tagName.toLowerCase(), tags) != -1)
						{
							inlines.push(node);
						}

					}, this));

					return (inlines.length === 0) ? false : inlines;
				},
				getBlocks: function(nodes)
				{
					this.selection.get();

					if (this.range && this.range.collapsed)
					{
						return [this.selection.getBlock()];
					}

					var blocks = [];
					nodes = (typeof nodes == 'undefined') ? this.selection.getNodes() : nodes;

					$.each(nodes, $.proxy(function(i,node)
					{
						if (this.utils.isBlock(node))
						{
							blocks.push(node);
						}

					}, this));

					return (blocks.length === 0) ? [this.selection.getBlock()] : blocks;
				},
				getLastBlock: function()
				{
					return this.selection.lastBlock;
				},
				getNodes: function()
				{
					this.selection.get();

					var startNode = this.selection.getNodesMarker(1);
					var endNode = this.selection.getNodesMarker(2);

					if (this.range.collapsed === false)
					{
					   if (window.getSelection) {
					        var sel = window.getSelection();
					        if (sel.rangeCount > 0) {

					            var range = sel.getRangeAt(0);
					            var startPointNode = range.startContainer, startOffset = range.startOffset;

					            var boundaryRange = range.cloneRange();
					            boundaryRange.collapse(false);
					            boundaryRange.insertNode(endNode);
					            boundaryRange.setStart(startPointNode, startOffset);
					            boundaryRange.collapse(true);
					            boundaryRange.insertNode(startNode);

					            // Reselect the original text
					            range.setStartAfter(startNode);
					            range.setEndBefore(endNode);
					            sel.removeAllRanges();
					            sel.addRange(range);
					        }
					    }
					}
					else
					{
						this.selection.setNodesMarker(this.range, startNode, true);
						endNode = startNode;
					}

					var nodes = [];
					var counter = 0;

					var self = this;
					this.$editor.find('*').each(function()
					{
						if (this == startNode)
						{
							var parent = $(this).parent();
							if (parent.length !== 0 && parent[0].tagName != 'BODY' && self.utils.isRedactorParent(parent[0]))
							{
								nodes.push(parent[0]);
							}

							nodes.push(this);
							counter = 1;
						}
						else
						{
							if (counter > 0)
							{
								nodes.push(this);
								counter = counter + 1;
							}
						}

						if (this == endNode)
						{
							return false;
						}

					});

					var finalNodes = [];
					var len = nodes.length;
					for (var i = 0; i < len; i++)
					{
						if (nodes[i].id != 'nodes-marker-1' && nodes[i].id != 'nodes-marker-2')
						{
							finalNodes.push(nodes[i]);
						}
					}

					this.selection.removeNodesMarkers();

					return finalNodes;

				},
				getNodesMarker: function(num)
				{
					return $('<span id="nodes-marker-' + num + '" class="redactor-nodes-marker" data-verified="redactor">' + this.opts.invisibleSpace + '</span>')[0];
				},
				setNodesMarker: function(range, node, type)
				{
					var range = range.cloneRange();

					try {
						range.collapse(type);
						range.insertNode(node);
					}
					catch (e) {}
				},
				removeNodesMarkers: function()
				{
					$(document).find('span.redactor-nodes-marker').remove();
					this.$editor.find('span.redactor-nodes-marker').remove();
				},
				fromPoint: function(start, end)
				{
					this.caret.setOffset(start, end);
				},
				wrap: function(tag)
				{
					this.selection.get();

					if (this.range.collapsed) return false;

					var wrapper = document.createElement(tag);
					wrapper.appendChild(this.range.extractContents());
					this.range.insertNode(wrapper);

					return wrapper;
				},
				selectElement: function(node)
				{
					if (this.utils.browser('mozilla'))
					{
						node = node[0] || node;

						var range = document.createRange();
						range.selectNodeContents(node);
					}
					else
					{
						this.caret.set(node, 0, node, 1);
					}
				},
				selectAll: function()
				{
					this.selection.get();
					this.range.selectNodeContents(this.$editor[0]);
					this.selection.addRange();
				},
				remove: function()
				{
					this.selection.get();
					this.sel.removeAllRanges();
				},
				save: function()
				{
					this.selection.createMarkers();
				},
				createMarkers: function()
				{
					this.selection.get();

					var node1 = this.selection.getMarker(1);

					this.selection.setMarker(this.range, node1, true);
					if (this.range.collapsed === false)
					{
						var node2 = this.selection.getMarker(2);
						this.selection.setMarker(this.range, node2, false);
					}

					this.savedSel = this.$editor.html();
				},
				getMarker: function(num)
				{
					if (typeof num == 'undefined') num = 1;

					return $('<span id="selection-marker-' + num + '" class="redactor-selection-marker"  data-verified="redactor">' + this.opts.invisibleSpace + '</span>')[0];
				},
				getMarkerAsHtml: function(num)
				{
					return this.utils.getOuterHtml(this.selection.getMarker(num));
				},
				setMarker: function(range, node, type)
				{
					range = range.cloneRange();

					try {
						range.collapse(type);
						range.insertNode(node);

					}
					catch (e)
					{
						this.focus.setStart();
					}

				},
				restore: function()
				{
					var node1 = this.$editor.find('span#selection-marker-1');
					var node2 = this.$editor.find('span#selection-marker-2');

					if (this.utils.browser('mozilla'))
					{
						this.$editor.focus();
					}

					if (node1.length !== 0 && node2.length !== 0)
					{
						this.caret.set(node1, 0, node2, 0);
					}
					else if (node1.length !== 0)
					{
						this.caret.set(node1, 0, node1, 0);
					}
					else
					{
						this.$editor.focus();
					}

					this.selection.removeMarkers();
					this.savedSel = false;

				},
				removeMarkers: function()
				{
					this.$editor.find('span.redactor-selection-marker').each(function(i,s)
					{
						var text = $(s).text().replace(/\u200B/g, '');
						if (text === '') $(s).remove();
						else $(s).replaceWith(function() { return $(this).contents(); });
					});
				},
				getText: function()
				{
					this.selection.get();

					return this.sel.toString();
				},
				getHtml: function()
				{
					var html = '';

					this.selection.get();
					if (this.sel.rangeCount)
					{
						var container = document.createElement('div');
						var len = this.sel.rangeCount;
						for (var i = 0; i < len; ++i)
						{
							container.appendChild(this.sel.getRangeAt(i).cloneContents());
						}

						html = container.innerHTML;
					}

					return this.clean.onSync(html);
				},
				replaceSelection: function(html)
				{
					this.selection.get();
					this.range.deleteContents();
					var div = document.createElement("div");
					div.innerHTML = html;
					var frag = document.createDocumentFragment(), child;
					while ((child = div.firstChild)) {
						frag.appendChild(child);
					}

					this.range.insertNode(frag);
				},
				replaceWithHtml: function(html)
				{
					html = this.selection.getMarkerAsHtml(1) + html + this.selection.getMarkerAsHtml(2);

					this.selection.get();

					if (window.getSelection && window.getSelection().getRangeAt)
					{
						this.selection.replaceSelection(html);
					}
					else if (document.selection && document.selection.createRange)
					{
						this.range.pasteHTML(html);
					}

					this.selection.restore();
					this.code.sync();
				}
			};
		},
		shortcuts: function()
		{
			return {
				init: function(e, key)
				{
					// disable browser's hot keys for bold and italic
					if (!this.opts.shortcuts)
					{
						if ((e.ctrlKey || e.metaKey) && (key === 66 || key === 73)) e.preventDefault();
						return false;
					}

					$.each(this.opts.shortcuts, $.proxy(function(str, command)
					{
						var keys = str.split(',');
						var len = keys.length;
						for (var i = 0; i < len; i++)
						{
							if (typeof keys[i] === 'string')
							{
								this.shortcuts.handler(e, $.trim(keys[i]), $.proxy(function()
								{
									var func;
									if (command.func.search(/\./) != '-1')
									{
										func = command.func.split('.');
										if (typeof this[func[0]] != 'undefined')
										{
											this[func[0]][func[1]].apply(this, command.params);
										}
									}
									else
									{
										this[command.func].apply(this, command.params);
									}

								}, this));
							}

						}

					}, this));
				},
				handler: function(e, keys, origHandler)
				{
					// based on https://github.com/jeresig/jquery.hotkeys
					var hotkeysSpecialKeys =
					{
						8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
						20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
						37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=",
						96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
						104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
						112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
						120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=",
						188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"
					};


					var hotkeysShiftNums =
					{
						"`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&",
						"8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<",
						".": ">",  "/": "?",  "\\": "|"
					};

					keys = keys.toLowerCase().split(" ");
					var special = hotkeysSpecialKeys[e.keyCode],
						character = String.fromCharCode( e.which ).toLowerCase(),
						modif = "", possible = {};

					$.each([ "alt", "ctrl", "meta", "shift"], function(index, specialKey)
					{
						if (e[specialKey + 'Key'] && special !== specialKey)
						{
							modif += specialKey + '+';
						}
					});


					if (special) possible[modif + special] = true;
					if (character)
					{
						possible[modif + character] = true;
						possible[modif + hotkeysShiftNums[character]] = true;

						// "$" can be triggered as "Shift+4" or "Shift+$" or just "$"
						if (modif === "shift+")
						{
							possible[hotkeysShiftNums[character]] = true;
						}
					}

					for (var i = 0, len = keys.length; i < len; i++)
					{
						if (possible[keys[i]])
						{
							e.preventDefault();
							return origHandler.apply(this, arguments);
						}
					}
				}
			};
		},
		tabifier: function()
		{
			return {
				get: function(code)
				{
					if (!this.opts.tabifier) return code;

					// clean setup
					var ownLine = ['area', 'body', 'head', 'hr', 'i?frame', 'link', 'meta', 'noscript', 'style', 'script', 'table', 'tbody', 'thead', 'tfoot'];
					var contOwnLine = ['li', 'dt', 'dt', 'h[1-6]', 'option', 'script'];
					var newLevel = ['p', 'blockquote', 'div', 'dl', 'fieldset', 'form', 'frameset', 'map', 'ol', 'pre', 'select', 'td', 'th', 'tr', 'ul'];

					this.tabifier.lineBefore = new RegExp('^<(/?' + ownLine.join('|/?' ) + '|' + contOwnLine.join('|') + ')[ >]');
					this.tabifier.lineAfter = new RegExp('^<(br|/?' + ownLine.join('|/?' ) + '|/' + contOwnLine.join('|/') + ')[ >]');
					this.tabifier.newLevel = new RegExp('^</?(' + newLevel.join('|' ) + ')[ >]');

					var i = 0,
					codeLength = code.length,
					point = 0,
					start = null,
					end = null,
					tag = '',
					out = '',
					cont = '';

					this.tabifier.cleanlevel = 0;

					for (; i < codeLength; i++)
					{
						point = i;

						// if no more tags, copy and exit
						if (-1 == code.substr(i).indexOf( '<' ))
						{
							out += code.substr(i);

							return this.tabifier.finish(out);
						}

						// copy verbatim until a tag
						while (point < codeLength && code.charAt(point) != '<')
						{
							point++;
						}

						if (i != point)
						{
							cont = code.substr(i, point - i);
							if (!cont.match(/^\s{2,}$/g))
							{
								if ('\n' == out.charAt(out.length - 1)) out += this.tabifier.getTabs();
								else if ('\n' == cont.charAt(0))
								{
									out += '\n' + this.tabifier.getTabs();
									cont = cont.replace(/^\s+/, '');
								}

								out += cont;
							}

							if (cont.match(/\n/)) out += '\n' + this.tabifier.getTabs();
						}

						start = point;

						// find the end of the tag
						while (point < codeLength && '>' != code.charAt(point))
						{
							point++;
						}

						tag = code.substr(start, point - start);
						i = point;

						var t;

						if ('!--' == tag.substr(1, 3))
						{
							if (!tag.match(/--$/))
							{
								while ('-->' != code.substr(point, 3))
								{
									point++;
								}
								point += 2;
								tag = code.substr(start, point - start);
								i = point;
							}

							if ('\n' != out.charAt(out.length - 1)) out += '\n';

							out += this.tabifier.getTabs();
							out += tag + '>\n';
						}
						else if ('!' == tag[1])
						{
							out = this.tabifier.placeTag(tag + '>', out);
						}
						else if ('?' == tag[1])
						{
							out += tag + '>\n';
						}
						else if (t = tag.match(/^<(script|style|pre)/i))
						{
							t[1] = t[1].toLowerCase();
							tag = this.tabifier.cleanTag(tag);
							out = this.tabifier.placeTag(tag, out);
							end = String(code.substr(i + 1)).toLowerCase().indexOf('</' + t[1]);

							if (end)
							{
								cont = code.substr(i + 1, end);
								i += end;
								out += cont;
							}
						}
						else
						{
							tag = this.tabifier.cleanTag(tag);
							out = this.tabifier.placeTag(tag, out);
						}
					}

					return this.tabifier.finish(out);
				},
				getTabs: function()
				{
					var s = '';
					for ( var j = 0; j < this.tabifier.cleanlevel; j++ )
					{
						s += '\t';
					}

					return s;
				},
				finish: function(code)
				{
					code = code.replace(/\n\s*\n/g, '\n');
					code = code.replace(/^[\s\n]*/, '');
					code = code.replace(/[\s\n]*$/, '');
					code = code.replace(/<script(.*?)>\n<\/script>/gi, '<script$1></script>');

					this.tabifier.cleanlevel = 0;

					return code;
				},
				cleanTag: function (tag)
				{
					var tagout = '';
					tag = tag.replace(/\n/g, ' ');
					tag = tag.replace(/\s{2,}/g, ' ');
					tag = tag.replace(/^\s+|\s+$/g, ' ');

					var suffix = '';
					if (tag.match(/\/$/))
					{
						suffix = '/';
						tag = tag.replace(/\/+$/, '');
					}

					var m;
					while (m = /\s*([^= ]+)(?:=((['"']).*?\3|[^ ]+))?/.exec(tag))
					{
						if (m[2]) tagout += m[1].toLowerCase() + '=' + m[2];
						else if (m[1]) tagout += m[1].toLowerCase();

						tagout += ' ';
						tag = tag.substr(m[0].length);
					}

					return tagout.replace(/\s*$/, '') + suffix + '>';
				},
				placeTag: function (tag, out)
				{
					var nl = tag.match(this.tabifier.newLevel);

					if (tag.match(this.tabifier.lineBefore) || nl)
					{
						out = out.replace(/\s*$/, '');
						out += '\n';
					}

					if (nl && '/' == tag.charAt(1)) this.tabifier.cleanlevel--;
					if ('\n' == out.charAt(out.length - 1)) out += this.tabifier.getTabs();
					if (nl && '/' != tag.charAt(1)) this.tabifier.cleanlevel++;

					out += tag;

					if (tag.match(this.tabifier.lineAfter) || tag.match(this.tabifier.newLevel))
					{
						out = out.replace(/ *$/, '');
						//out += '\n';
					}

					return out;
				}
			};
		},
		tidy: function()
		{
			return {
				setupAllowed: function()
				{
					var index = $.inArray('span', this.opts.removeEmpty);
					if (index !== -1)
					{
						this.opts.removeEmpty.splice(index, 1);
					}

					if (this.opts.allowedTags) this.opts.deniedTags = false;
					if (this.opts.allowedAttr) this.opts.removeAttr = false;

					if (this.opts.linebreaks) return;

					var tags = ['p', 'section'];
					if (this.opts.allowedTags) this.tidy.addToAllowed(tags);
					if (this.opts.deniedTags) this.tidy.removeFromDenied(tags);

				},
				addToAllowed: function(tags)
				{
					var len = tags.length;
					for (var i = 0; i < len; i++)
					{
						if ($.inArray(tags[i], this.opts.allowedTags) == -1)
						{
							this.opts.allowedTags.push(tags[i]);
						}
					}
				},
				removeFromDenied: function(tags)
				{
					var len = tags.length;
					for (var i = 0; i < len; i++)
					{
						var pos = $.inArray(tags[i], this.opts.deniedTags);
						if (pos != -1)
						{
							this.opts.deniedTags.splice(pos, 1);
						}
					}
				},
				load: function(html, options)
				{
					this.tidy.settings = {
						deniedTags: this.opts.deniedTags,
						allowedTags: this.opts.allowedTags,
						removeComments: this.opts.removeComments,
						replaceTags: this.opts.replaceTags,
						replaceStyles: this.opts.replaceStyles,
						removeDataAttr: this.opts.removeDataAttr,
						removeAttr: this.opts.removeAttr,
						allowedAttr: this.opts.allowedAttr,
						removeWithoutAttr: this.opts.removeWithoutAttr,
						removeEmpty: this.opts.removeEmpty
					};

					$.extend(this.tidy.settings, options);

					html = this.tidy.removeComments(html);

					// create container
					this.tidy.$div = $('<div />').append(html);

					// clean
					this.tidy.replaceTags();
					this.tidy.replaceStyles();
					this.tidy.removeTags();

					this.tidy.removeAttr();
					this.tidy.removeEmpty();
					this.tidy.removeParagraphsInLists();
					this.tidy.removeDataAttr();
					this.tidy.removeWithoutAttr();

					html = this.tidy.$div.html();
					this.tidy.$div.remove();

					return html;
				},
				removeComments: function(html)
				{
					if (!this.tidy.settings.removeComments) return html;

					return html.replace(/<!--[\s\S]*?-->/gi, '');
				},
				replaceTags: function(html)
				{
					if (!this.tidy.settings.replaceTags) return html;

					var len = this.tidy.settings.replaceTags.length;
					var replacement = [], rTags = [];
					for (var i = 0; i < len; i++)
					{
						rTags.push(this.tidy.settings.replaceTags[i][1]);
						replacement.push(this.tidy.settings.replaceTags[i][0]);
					}

					$.each(replacement, $.proxy(function(key, value)
					{
						this.tidy.$div.find(value).replaceWith(function()
						{
							return $("<" + rTags[key] + " />", {html: $(this).html()});
						});
					}, this));
				},
				replaceStyles: function()
				{
					if (!this.tidy.settings.replaceStyles) return;

					var len = this.tidy.settings.replaceStyles.length;
					this.tidy.$div.find('span').each($.proxy(function(n,s)
					{
						var $el = $(s);
						var style = $el.attr('style');
						for (var i = 0; i < len; i++)
						{
							if (style && style.match(new RegExp('^' + this.tidy.settings.replaceStyles[i][0], 'i')))
							{
								var tagName = this.tidy.settings.replaceStyles[i][1];
								$el.replaceWith(function()
								{
									var tag = document.createElement(tagName);
									return $(tag).append($(this).contents());
								});
							}
						}

					}, this));

				},
				removeTags: function()
				{
					if (!this.tidy.settings.deniedTags && this.tidy.settings.allowedTags)
					{
						this.tidy.$div.find('*').not(this.tidy.settings.allowedTags.join(',')).each(function(i, s)
						{
							if (s.innerHTML === '') $(s).remove();
							else $(s).contents().unwrap();
						});
					}

					if (this.tidy.settings.deniedTags)
					{
						this.tidy.$div.find(this.tidy.settings.deniedTags.join(',')).each(function(i, s)
						{
							if ($(s).hasClass('redactor-script-tag') || $(s).hasClass('redactor-selection-marker')) return;

							if (s.innerHTML === '') $(s).remove();
							else $(s).contents().unwrap();
						});
					}
				},
				removeAttr: function()
				{
					var len;
					if (!this.tidy.settings.removeAttr && this.tidy.settings.allowedAttr)
					{

						var allowedAttrTags = [], allowedAttrData = [];
						len = this.tidy.settings.allowedAttr.length;
						for (var i = 0; i < len; i++)
						{
							allowedAttrTags.push(this.tidy.settings.allowedAttr[i][0]);
							allowedAttrData.push(this.tidy.settings.allowedAttr[i][1]);
						}


						this.tidy.$div.find('*').each($.proxy(function(n,s)
						{
							var $el = $(s);
							var pos = $.inArray($el[0].tagName.toLowerCase(), allowedAttrTags);
							var attributesRemove = this.tidy.removeAttrGetRemoves(pos, allowedAttrData, $el);

							if (attributesRemove)
							{
								$.each(attributesRemove, function(z,f) {
									$el.removeAttr(f);
								});
							}
						}, this));
					}

					if (this.tidy.settings.removeAttr)
					{
						len = this.tidy.settings.removeAttr.length;
						for (var i = 0; i < len; i++)
						{
							var attrs = this.tidy.settings.removeAttr[i][1];
							if ($.isArray(attrs)) attrs = attrs.join(' ');

							this.tidy.$div.find(this.tidy.settings.removeAttr[i][0]).removeAttr(attrs);
						}
					}

				},
				removeAttrGetRemoves: function(pos, allowed, $el)
				{
					var attributesRemove = [];

					// remove all attrs
					if (pos == -1)
					{
						$.each($el[0].attributes, function(i, item)
						{
							attributesRemove.push(item.name);
						});

					}
					// allow all attrs
					else if (allowed[pos] == '*')
					{
						attributesRemove = [];
					}
					// allow specific attrs
					else
					{
						$.each($el[0].attributes, function(i, item)
						{
							if ($.isArray(allowed[pos]))
							{
								if ($.inArray(item.name, allowed[pos]) == -1)
								{
									attributesRemove.push(item.name);
								}
							}
							else if (allowed[pos] != item.name)
							{
								attributesRemove.push(item.name);
							}

						});
					}

					return attributesRemove;
				},
				removeAttrs: function (el, regex)
				{
					regex = new RegExp(regex, "g");
					return el.each(function()
					{
						var self = $(this);
						var len = this.attributes.length - 1;
						for (var i = len; i >= 0; i--)
						{
							var item = this.attributes[i];
							if (item && item.specified && item.name.search(regex)>=0)
							{
								self.removeAttr(item.name);
							}
						}
					});
				},
				removeEmpty: function()
				{
					if (!this.tidy.settings.removeEmpty) return;

					this.tidy.$div.find(this.tidy.settings.removeEmpty.join(',')).each(function()
					{
						var $el = $(this);
						var text = $el.text();
						text = text.replace(/\u200B/g, '');
						text = text.replace(/&nbsp;/gi, '');
						text = text.replace(/\s/g, '');

		    	    	if (text === '' && $el.children().length === 0)
		    	    	{
			    	    	$el.remove();
		    	    	}
					});
				},
				removeParagraphsInLists: function()
				{
					this.tidy.$div.find('li p').contents().unwrap();
				},
				removeDataAttr: function()
				{
					if (!this.tidy.settings.removeDataAttr) return;

					var tags = this.tidy.settings.removeDataAttr;
					if ($.isArray(this.tidy.settings.removeDataAttr)) tags = this.tidy.settings.removeDataAttr.join(',');

					this.tidy.removeAttrs(this.tidy.$div.find(tags), '^(data-)');

				},
				removeWithoutAttr: function()
				{
					if (!this.tidy.settings.removeWithoutAttr) return;

					this.tidy.$div.find(this.tidy.settings.removeWithoutAttr.join(',')).each(function()
					{
						if (this.attributes.length === 0)
						{
							$(this).contents().unwrap();
						}
					});
				}
			};
		},
		toolbar: function()
		{
			return {
				init: function()
				{
					return {
						html:
						{
							title: this.lang.get('html'),
							func: 'code.toggle'
						},
						formatting:
						{
							title: this.lang.get('formatting'),
							dropdown:
							{
								p:
								{
									title: this.lang.get('paragraph'),
									func: 'block.format'
								},
								blockquote:
								{
									title: this.lang.get('quote'),
									func: 'block.format'
								},
								pre:
								{
									title: this.lang.get('code'),
									func: 'block.format'
								},
								h1:
								{
									title: this.lang.get('header1'),
									func: 'block.format'
								},
								h2:
								{
									title: this.lang.get('header2'),
									func: 'block.format'
								},
								h3:
								{
									title: this.lang.get('header3'),
									func: 'block.format'
								},
								h4:
								{
									title: this.lang.get('header4'),
									func: 'block.format'
								},
								h5:
								{
									title: this.lang.get('header5'),
									func: 'block.format'
								}
							}
						},
						bold:
						{
							title: this.lang.get('bold'),
							func: 'inline.format'
						},
						italic:
						{
							title: this.lang.get('italic'),
							func: 'inline.format'
						},
						deleted:
						{
							title: this.lang.get('deleted'),
							func: 'inline.format'
						},
						underline:
						{
							title: this.lang.get('underline'),
							func: 'inline.format'
						},
						unorderedlist:
						{
							title: '&bull; ' + this.lang.get('unorderedlist'),
							func: 'list.toggle'
						},
						orderedlist:
						{
							title: '1. ' + this.lang.get('orderedlist'),
							func: 'list.toggle'
						},
						outdent:
						{
							title: '< ' + this.lang.get('outdent'),
							func: 'indent.decrease'
						},
						indent:
						{
							title: '> ' + this.lang.get('indent'),
							func: 'indent.increase'
						},
						image:
						{
							title: this.lang.get('image'),
							func: 'image.show'
						},
						file:
						{
							title: this.lang.get('file'),
							func: 'file.show'
						},
						link:
						{
							title: this.lang.get('link'),
							dropdown:
							{
								link:
								{
									title: this.lang.get('link_insert'),
									func: 'link.show',
									observe: {
										element: 'a',
										in: {
											title: this.lang.get('link_edit'),
										},
										out: {
											title: this.lang.get('link_insert')
										}
									}
								},
								unlink:
								{
									title: this.lang.get('unlink'),
									func: 'link.unlink',
									observe: {
										element: 'a',
										out: {
											attr: {
												'class': 'redactor-dropdown-link-inactive',
												'aria-disabled': true
											}
										}
									}
								}
							}
						},
						alignment:
						{
							title: this.lang.get('alignment'),
							dropdown:
							{
								left:
								{
									title: this.lang.get('align_left'),
									func: 'alignment.left'
								},
								center:
								{
									title: this.lang.get('align_center'),
									func: 'alignment.center'
								},
								right:
								{
									title: this.lang.get('align_right'),
									func: 'alignment.right'
								},
								justify:
								{
									title: this.lang.get('align_justify'),
									func: 'alignment.justify'
								}
							}
						},
						horizontalrule:
						{
							title: this.lang.get('horizontalrule'),
							func: 'line.insert'
						}
					};
				},
				build: function()
				{
					this.toolbar.hideButtons();
					this.toolbar.hideButtonsOnMobile();
					this.toolbar.isButtonSourceNeeded();

					if (this.opts.buttons.length === 0) return;

					this.$toolbar = this.toolbar.createContainer();

					this.toolbar.setOverflow();
					this.toolbar.append();
					this.toolbar.setFormattingTags();
					this.toolbar.loadButtons();
					this.toolbar.setFixed();

					// buttons response
					if (this.opts.activeButtons)
					{
						this.$editor.on('mouseup.redactor keyup.redactor focus.redactor', $.proxy(this.observe.toolbar, this));
					}

				},
				createContainer: function()
				{
					return $('<ul>').addClass('redactor-toolbar').attr({'id': 'redactor-toolbar-' + this.uuid, 'role': 'toolbar'});
				},
				setFormattingTags: function()
				{
					$.each(this.opts.toolbar.formatting.dropdown, $.proxy(function (i, s)
					{
						if ($.inArray(i, this.opts.formatting) == -1) delete this.opts.toolbar.formatting.dropdown[i];
					}, this));

				},
				loadButtons: function()
				{
					$.each(this.opts.buttons, $.proxy(function(i, btnName)
					{
						if (!this.opts.toolbar[btnName]) return;

						if (btnName === 'file')
						{
							 if (this.opts.fileUpload === false) return;
							 else if (!this.opts.fileUpload && this.opts.s3 === false) return;
						}

						if (btnName === 'image')
						{
							 if (this.opts.imageUpload === false) return;
							 else if (!this.opts.imageUpload && this.opts.s3 === false) return;
						}

						var btnObject = this.opts.toolbar[btnName];
						this.$toolbar.append($('<li>').append(this.button.build(btnName, btnObject)));

					}, this));
				},
				append: function()
				{
					if (this.opts.toolbarExternal)
					{
						this.$toolbar.addClass('redactor-toolbar-external');
						$(this.opts.toolbarExternal).html(this.$toolbar);
					}
					else
					{
						this.$box.prepend(this.$toolbar);
					}
				},
				setFixed: function()
				{
					if (!this.utils.isDesktop()) return;
					if (this.opts.toolbarExternal) return;
					if (!this.opts.toolbarFixed) return;

					this.toolbar.observeScroll();
					$(this.opts.toolbarFixedTarget).on('scroll.redactor.' + this.uuid, $.proxy(this.toolbar.observeScroll, this));

				},
				setOverflow: function()
				{
					if (this.utils.isMobile() && this.opts.toolbarOverflow)
					{
						this.$toolbar.addClass('redactor-toolbar-overflow');
					}
				},
				isButtonSourceNeeded: function()
				{
					if (this.opts.source) return;

					var index = this.opts.buttons.indexOf('html');
					if (index !== -1)
					{
						this.opts.buttons.splice(index, 1);
					}
				},
				hideButtons: function()
				{
					if (this.opts.buttonsHide.length === 0) return;

					$.each(this.opts.buttonsHide, $.proxy(function(i, s)
					{
						var index = this.opts.buttons.indexOf(s);
						this.opts.buttons.splice(index, 1);

					}, this));
				},
				hideButtonsOnMobile: function()
				{
					if (!this.utils.isMobile() || this.opts.buttonsHideOnMobile.length === 0) return;

					$.each(this.opts.buttonsHideOnMobile, $.proxy(function(i, s)
					{
						var index = this.opts.buttons.indexOf(s);
						this.opts.buttons.splice(index, 1);

					}, this));
				},
				observeScroll: function()
				{
					var scrollTop = $(this.opts.toolbarFixedTarget).scrollTop();
					var boxTop = 1;

					if (this.opts.toolbarFixedTarget === document)
					{
						boxTop = this.$box.offset().top;
					}

					if ((scrollTop + this.opts.toolbarFixedTopOffset) > boxTop)
					{
						this.toolbar.observeScrollEnable(scrollTop, boxTop);
					}
					else
					{
						this.toolbar.observeScrollDisable();
					}
				},
				observeScrollEnable: function(scrollTop, boxTop)
				{
					var top = this.opts.toolbarFixedTopOffset + scrollTop - boxTop;
					var left = 0;
					var end = boxTop + this.$box.height() - 32;
					var width = this.$box.innerWidth();

					this.$toolbar.addClass('toolbar-fixed-box');
					this.$toolbar.css({
						position: 'absolute',
						width: width,
						top: top + 'px',
						left: left
					});

					if (scrollTop > end)
						$('.redactor-dropdown-' + this.uuid + ':visible').hide();

					this.toolbar.setDropdownsFixed();
					this.$toolbar.css('visibility', (scrollTop < end) ? 'visible' : 'hidden');
				},
				observeScrollDisable: function()
				{
					this.$toolbar.css({
						position: 'relative',
						width: 'auto',
						top: 0,
						left: 0,
						visibility: 'visible'
					});

					this.toolbar.unsetDropdownsFixed();
					this.$toolbar.removeClass('toolbar-fixed-box');
				},
				setDropdownsFixed: function()
				{
					var top = this.$toolbar.innerHeight() + this.opts.toolbarFixedTopOffset;
					var position = 'fixed';
					if (this.opts.toolbarFixedTarget !== document)
					{
						top = (this.$toolbar.innerHeight() + this.$toolbar.offset().top) + this.opts.toolbarFixedTopOffset;
						position = 'absolute';
					}

					$('.redactor-dropdown-' + this.uuid).each(function()
					{
						$(this).css({ position: position, top: top + 'px' });
					});
				},
				unsetDropdownsFixed: function()
				{
					var top = (this.$toolbar.innerHeight() + this.$toolbar.offset().top);
					$('.redactor-dropdown-' + this.uuid).each(function()
					{
						$(this).css({ position: 'absolute', top: top + 'px' });
					});
				}
			};
		},
		upload: function()
		{
			return {
				init: function(el, url, callback)
				{
					this.upload.direct = false;
					this.upload.callback = callback;
					this.upload.url = url;
					this.upload.$el = el;
					this.upload.$droparea = $('<div id="redactor-droparea" />');

					this.upload.$placeholdler = $('<div id="redactor-droparea-placeholder" />').text(this.lang.get('upload_label'));
					this.upload.$input = $('<input type="file" name="file" />');

					this.upload.$placeholdler.append(this.upload.$input);
					this.upload.$droparea.append(this.upload.$placeholdler);
					this.upload.$el.append(this.upload.$droparea);

					this.upload.$droparea.off('redactor.upload');
					this.upload.$input.off('redactor.upload');

					this.upload.$droparea.on('dragover.redactor.upload', $.proxy(this.upload.onDrag, this));
					this.upload.$droparea.on('dragleave.redactor.upload', $.proxy(this.upload.onDragLeave, this));

					// change
					this.upload.$input.on('change.redactor.upload', $.proxy(function(e)
					{
						e = e.originalEvent || e;
						this.upload.traverseFile(this.upload.$input[0].files[0], e);
					}, this));

					// drop
					this.upload.$droparea.on('drop.redactor.upload', $.proxy(function(e)
					{
						e.preventDefault();

						this.upload.$droparea.removeClass('drag-hover').addClass('drag-drop');
						this.upload.onDrop(e);

					}, this));
				},
				directUpload: function(file, e)
				{
					this.upload.direct = true;
					this.upload.traverseFile(file, e);
				},
				onDrop: function(e)
				{
					e = e.originalEvent || e;
					var files = e.dataTransfer.files;

					this.upload.traverseFile(files[0], e);
				},
				traverseFile: function(file, e)
				{
					if (this.opts.s3)
					{
						this.upload.setConfig(file);
						this.upload.s3uploadFile(file);
						return;
					}

					var formData = !!window.FormData ? new FormData() : null;
					if (window.FormData)
					{
						this.upload.setConfig(file);

						var name = (this.upload.type == 'image') ? this.opts.imageUploadParam : this.opts.fileUploadParam;
						formData.append(name, file);
					}

					this.progress.show();
					this.core.setCallback('uploadStart', e, formData);
					this.upload.sendData(formData, e);
				},
				setConfig: function(file)
				{
					this.upload.getType(file);

					if (this.upload.direct)
					{
						this.upload.url = (this.upload.type == 'image') ? this.opts.imageUpload : this.opts.fileUpload;
						this.upload.callback = (this.upload.type == 'image') ? this.image.insert : this.file.insert;
					}
				},
				getType: function(file)
				{
					this.upload.type = 'image';
					if (this.opts.imageTypes.indexOf(file.type) == -1)
					{
						this.upload.type = 'file';
					}

					if (this.opts.imageUpload === null && this.opts.fileUpload !== null)
					{
						this.upload.type = 'file';
					}

				},
				getHiddenFields: function(obj, fd)
				{
					if (obj === false || typeof obj !== 'object') return fd;

					$.each(obj, $.proxy(function(k, v)
					{
						if (v !== null && v.toString().indexOf('#') === 0) v = $(v).val();
						fd.append(k, v);

					}, this));

					return fd;

				},
				sendData: function(formData, e)
				{
					// append hidden fields
					if (this.upload.type == 'image')
					{
						formData = this.upload.getHiddenFields(this.opts.uploadImageFields, formData);
						formData = this.upload.getHiddenFields(this.upload.imageFields, formData);
					}
					else
					{
						formData = this.upload.getHiddenFields(this.opts.uploadFileFields, formData);
						formData = this.upload.getHiddenFields(this.upload.fileFields, formData);
					}

					var xhr = new XMLHttpRequest();
					xhr.open('POST', this.upload.url);
					xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

					// complete
					xhr.onreadystatechange = $.proxy(function()
					{
					    if (xhr.readyState == 4)
					    {
					        var data = xhr.responseText;

							data = data.replace(/^\[/, '');
							data = data.replace(/\]$/, '');

							var json;
							try
							{
								json = (typeof data === 'string' ? $.parseJSON(data) : data);
							}
							catch(err)
							{
								json = {
									error: true
								};
							}


							this.progress.hide();

							if (!this.upload.direct)
							{
								this.upload.$droparea.removeClass('drag-drop');
							}

							this.upload.callback(json, this.upload.direct, e);
					    }
					}, this);


					/*
					xhr.upload.onprogress = $.proxy(function(e)
					{
						if (e.lengthComputable)
						{
							var complete = (e.loaded / e.total * 100 | 0);
							//progress.value = progress.innerHTML = complete;
						}

					}, this);
					*/


					xhr.send(formData);
				},
				onDrag: function(e)
				{
					e.preventDefault();
					this.upload.$droparea.addClass('drag-hover');
				},
				onDragLeave: function(e)
				{
					e.preventDefault();
					this.upload.$droparea.removeClass('drag-hover');
				},
				clearImageFields: function()
				{
					this.upload.imageFields = {};
				},
				addImageFields: function(name, value)
				{
					this.upload.imageFields[name] = value;
				},
				removeImageFields: function(name)
				{
					delete this.upload.imageFields[name];
				},
				clearFileFields: function()
				{
					this.upload.fileFields = {};
				},
				addFileFields: function(name, value)
				{
					this.upload.fileFields[name] = value;
				},
				removeFileFields: function(name)
				{
					delete this.upload.fileFields[name];
				},


				// S3
				s3uploadFile: function(file)
				{
					this.upload.s3executeOnSignedUrl(file, $.proxy(function(signedURL)
					{
						this.upload.s3uploadToS3(file, signedURL);
					}, this));
				},
				s3executeOnSignedUrl: function(file, callback)
				{
					var xhr = new XMLHttpRequest();
					var mark = (this.opts.s3.search(/\?/) !== '-1') ? '?' : '&';

					xhr.open('GET', this.opts.s3 + mark + 'name=' + file.name + '&type=' + file.type, true);

					// Hack to pass bytes through unprocessed.
					if (xhr.overrideMimeType) xhr.overrideMimeType('text/plain; charset=x-user-defined');

					var that = this;
					xhr.onreadystatechange = function(e)
					{
						if (this.readyState == 4 && this.status == 200)
						{
							that.progress.show();
							callback(decodeURIComponent(this.responseText));
						}
						else if (this.readyState == 4 && this.status != 200)
						{
							//setProgress(0, 'Could not contact signing script. Status = ' + this.status);
						}
					};

					xhr.send();
				},
				s3createCORSRequest: function(method, url)
				{
					var xhr = new XMLHttpRequest();
					if ("withCredentials" in xhr)
					{
						xhr.open(method, url, true);
					}
					else if (typeof XDomainRequest != "undefined")
					{
						xhr = new XDomainRequest();
						xhr.open(method, url);
					}
					else
					{
						xhr = null;
					}

					return xhr;
				},
				s3uploadToS3: function(file, url)
				{
					var xhr = this.upload.s3createCORSRequest('PUT', url);
					if (!xhr)
					{
						//setProgress(0, 'CORS not supported');
					}
					else
					{
						xhr.onload = $.proxy(function()
						{
							if (xhr.status == 200)
							{
								//setProgress(100, 'Upload completed.');

								this.progress.hide();

								var s3file = url.split('?');

								if (!s3file[0])
								{
									 // url parsing is fail
									 return false;
								}


								if (!this.upload.direct)
								{
									this.upload.$droparea.removeClass('drag-drop');
								}

								var json = { filelink: s3file[0] };
								if (this.upload.type == 'file')
								{
									var arr = s3file[0].split('/');
									json.filename = arr[arr.length-1];
								}

								this.upload.callback(json, this.upload.direct, false);


							}
							else
							{
								//setProgress(0, 'Upload error: ' + xhr.status);
							}
						}, this);

						xhr.onerror = function() {};

						xhr.upload.onprogress = function(e) {};

						xhr.setRequestHeader('Content-Type', file.type);
						xhr.setRequestHeader('x-amz-acl', 'public-read');

						xhr.send(file);
					}
				}
			};
		},
		utils: function()
		{
			return {
				isMobile: function()
				{
					return /(iPhone|iPod|BlackBerry|Android)/.test(navigator.userAgent);
				},
				isDesktop: function()
				{
					return !/(iPhone|iPod|iPad|BlackBerry|Android)/.test(navigator.userAgent);
				},
				isString: function(obj)
				{
					return Object.prototype.toString.call(obj) == '[object String]';
				},
				isEmpty: function(html, removeEmptyTags)
				{
					html = html.replace(/[\u200B-\u200D\uFEFF]/g, '');
					html = html.replace(/&nbsp;/gi, '');
					html = html.replace(/<\/?br\s?\/?>/g, '');
					html = html.replace(/\s/g, '');
					html = html.replace(/^<p>[^\W\w\D\d]*?<\/p>$/i, '');
					html = html.replace(/<iframe(.*?[^>])>$/i, 'iframe');
					html = html.replace(/<source(.*?[^>])>$/i, 'source');

					// remove empty tags
					if (removeEmptyTags !== false)
					{
						html = html.replace(/<[^\/>][^>]*><\/[^>]+>/gi, '');
						html = html.replace(/<[^\/>][^>]*><\/[^>]+>/gi, '');
					}

					html = $.trim(html);

					return html === '';
				},
				normalize: function(str)
				{
					if (typeof(str) === 'undefined') return 0;
					return parseInt(str.replace('px',''), 10);
				},
				hexToRgb: function(hex)
				{
					if (typeof hex == 'undefined') return;
					if (hex.search(/^#/) == -1) return hex;

					var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
					hex = hex.replace(shorthandRegex, function(m, r, g, b)
					{
						return r + r + g + g + b + b;
					});

					var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
					return 'rgb(' + parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) + ')';
				},
				getOuterHtml: function(el)
				{
					return $('<div>').append($(el).eq(0).clone()).html();
				},
				getAlignmentElement: function(el)
				{
					if ($.inArray(el.tagName, this.opts.alignmentTags) !== -1)
					{
						return $(el);
					}
					else
					{
						return $(el).closest(this.opts.alignmentTags.toString().toLowerCase(), this.$editor[0]);
					}
				},
				removeEmptyAttr: function(el, attr)
				{
					var $el = $(el);
					if (typeof $el.attr(attr) == 'undefined')
					{
						return true;
					}

					if ($el.attr(attr) === '')
					{
						$el.removeAttr(attr);
						return true;
					}

					return false;
				},
				removeEmpty: function(i, s)
				{
					var $s = $($.parseHTML(s));

					$s.find('.redactor-invisible-space').removeAttr('style').removeAttr('class');

					if ($s.find('hr, br, img, iframe, source').length !== 0) return;
					var text = $.trim($s.text());

					if (this.utils.isEmpty(text, false))
					{
						$s.remove();
					}
				},

				// save and restore scroll
				saveScroll: function()
				{
					this.saveEditorScroll = this.$editor.scrollTop();
					this.saveBodyScroll = $(window).scrollTop();

					if (this.opts.scrollTarget) this.saveTargetScroll = $(this.opts.scrollTarget).scrollTop();
				},
				restoreScroll: function()
				{
					if (typeof this.saveScroll === 'undefined' && typeof this.saveBodyScroll === 'undefined') return;

					$(window).scrollTop(this.saveBodyScroll);
					this.$editor.scrollTop(this.saveEditorScroll);

					if (this.opts.scrollTarget) $(this.opts.scrollTarget).scrollTop(this.saveTargetScroll);
				},

				// get invisible space element
				createSpaceElement: function()
				{
					var space = document.createElement('span');
					space.className = 'redactor-invisible-space';
					space.innerHTML = this.opts.invisibleSpace;

					return space;
				},

				// replace
				removeInlineTags: function(node)
				{
					var tags = this.opts.inlineTags;
					tags.push('span');

					if (node.tagName == 'PRE') tags.push('a');

					$(node).find(tags.join(',')).not('span.redactor-selection-marker').contents().unwrap();
				},
				replaceWithContents: function(node, removeInlineTags)
				{
					var self = this;
					$(node).replaceWith(function()
					{
						if (removeInlineTags === true) self.utils.removeInlineTags(this);

						return $(this).contents();
					});

					return $(node);
				},
				replaceToTag: function(node, tag, removeInlineTags)
				{
					var replacement;
					var self = this;
					$(node).replaceWith(function()
					{
						replacement = $('<' + tag + ' />').append($(this).contents());

						for (var i = 0; i < this.attributes.length; i++)
						{
							replacement.attr(this.attributes[i].name, this.attributes[i].value);
						}

						if (removeInlineTags === true) self.utils.removeInlineTags(replacement);

						return replacement;
					});

					return replacement;
				},

				// start and end of element
				isStartOfElement: function()
				{
					var block = this.selection.getBlock();
					if (!block) return false;

					var offset = this.caret.getOffsetOfElement(block);

					return (offset === 0) ? true : false;
				},
				isEndOfElement: function(element)
				{
					if (typeof element == 'undefined')
					{
						var element = this.selection.getBlock();
						if (!element) return false;
					}

					var offset = this.caret.getOffsetOfElement(element);
					var text = $.trim($(element).text()).replace(/\n\r\n/g, '');

					return (offset == text.length) ? true : false;
				},
				isStartOfEditor: function()
				{
					var offset = this.caret.getOffsetOfElement(this.$editor[0]);

					return (offset === 0) ? true : false;
				},
				isEndOfEditor: function()
				{
					var block = this.$editor[0];

					var offset = this.caret.getOffsetOfElement(block);
					var text = $.trim($(block).html().replace(/(<([^>]+)>)/gi,''));

					return (offset == text.length) ? true : false;
				},

				// test blocks
				isBlock: function(block)
				{
					block = block[0] || block;

					return block && this.utils.isBlockTag(block.tagName);
				},
				isBlockTag: function(tag)
				{
					if (typeof tag == 'undefined') return false;

					return this.reIsBlock.test(tag);
				},

				// tag detection
				isTag: function(current, tag)
				{
					var element = $(current).closest(tag, this.$editor[0]);
					if (element.length == 1)
					{
						return element[0];
					}

					return false;
				},

				// select all
				isSelectAll: function()
				{
					return this.selectAll;
				},
				enableSelectAll: function()
				{
					this.selectAll = true;
				},
				disableSelectAll: function()
				{
					this.selectAll = false;
				},

				// parents detection
				isRedactorParent: function(el)
				{
					if (!el)
					{
						return false;
					}

					if ($(el).parents('.redactor-editor').length === 0 || $(el).hasClass('redactor-editor'))
					{
						return false;
					}

					return el;
				},
				isCurrentOrParentHeader: function()
				{
					return this.utils.isCurrentOrParent(['H1', 'H2', 'H3', 'H4', 'H5', 'H6']);
				},
				isCurrentOrParent: function(tagName)
				{
					var parent = this.selection.getParent();
					var current = this.selection.getCurrent();

					if ($.isArray(tagName))
					{
						var matched = 0;
						$.each(tagName, $.proxy(function(i, s)
						{
							if (this.utils.isCurrentOrParentOne(current, parent, s))
							{
								matched++;
							}
						}, this));

						return (matched === 0) ? false : true;
					}
					else
					{
						return this.utils.isCurrentOrParentOne(current, parent, tagName);
					}
				},
				isCurrentOrParentOne: function(current, parent, tagName)
				{
					tagName = tagName.toUpperCase();

					return parent && parent.tagName === tagName ? parent : current && current.tagName === tagName ? current : false;
				},


				// browsers detection
				isOldIe: function()
				{
					return (this.utils.browser('msie') && parseInt(this.utils.browser('version'), 10) < 9) ? true : false;
				},
				isLessIe10: function()
				{
					return (this.utils.browser('msie') && parseInt(this.utils.browser('version'), 10) < 10) ? true : false;
				},
				isIe11: function()
				{
					return !!navigator.userAgent.match(/Trident\/7\./);
				},
				isEdge: function()
				{
					return !!navigator.userAgent.match(/Edge\//);
				},
				browser: function(browser)
				{
					var ua = navigator.userAgent.toLowerCase();
					var match = /(opr)[\/]([\w.]+)/.exec( ua ) ||
						/(edge)[\/]([\w.]+)/.exec( ua ) ||
						/(chrome)[ \/]([\w.]+)/.exec( ua ) ||
						/(webkit)[ \/]([\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 ) ||
						[];

					if (browser == 'safari') return (typeof match[3] != 'undefined') ? match[3] == 'safari' : false;
					if (browser == 'version') return match[2];
					if (browser == 'webkit') return (match[1] == 'chrome' || match[1] == 'opr' || match[1] == 'webkit');
					if (match[1] == 'rv') return browser == 'msie';
					if (match[1] == 'edge') return browser == 'msie';
					if (match[1] == 'opr') return browser == 'webkit';

					return browser == match[1];
				},
				strpos: function(haystack, needle, offset)
				{
					var i = haystack.indexOf(needle, offset);
					return i >= 0 ? i : false;
				},
				disableBodyScroll: function()
				{

					var $body = $('html');
					var windowWidth = window.innerWidth;
					if (!windowWidth)
					{
						var documentElementRect = document.documentElement.getBoundingClientRect();
						windowWidth = documentElementRect.right - Math.abs(documentElementRect.left);
					}

					var isOverflowing = document.body.clientWidth < windowWidth;
					var scrollbarWidth = this.utils.measureScrollbar();

					$body.css('overflow', 'hidden');
					if (isOverflowing) $body.css('padding-right', scrollbarWidth);


				},
				measureScrollbar: function()
				{
					var $body = $('body');
					var scrollDiv = document.createElement('div');
					scrollDiv.className = 'redactor-scrollbar-measure';

					$body.append(scrollDiv);
					var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
					$body[0].removeChild(scrollDiv);
					return scrollbarWidth;
				},
				enableBodyScroll: function()
				{
					$('html').css({ 'overflow': '', 'padding-right': '' });
					$('body').remove('redactor-scrollbar-measure');
				}
			};
		}
	};

	$(window).on('load.tools.redactor', function()
	{
		$('[data-tools="redactor"]').redactor();
	});

	// constructor
	Redactor.prototype.init.prototype = Redactor.prototype;

})(jQuery);
// This function helps prevent MySQL errors caused by lengthy base64 encoded
// images copy/pasted into the editor.
function redactorPasteBeforeCallback(html) {
  if (html.indexOf('<img src="data:') !== -1) {
    alert("Sorry you can't copy/paste this content because it includes a base64 encoded image.")
    return '';
  }
  return html;
}

// Provides shared options for the Redactor initialize calls below.
function redactorSharedOptions() {
  var csrf_token = $('meta[name=csrf-token]').attr('content');
  var csrf_param = $('meta[name=csrf-param]').attr('content');
  var params;
  if (csrf_param !== undefined && csrf_token !== undefined) {
    params = csrf_param + "=" + encodeURIComponent(csrf_token);
  }

  return {
    imageUpload: "/redactor_rails/pictures?" + params,
    imageGetJson: "/redactor_rails/pictures",
    fileUpload: "/redactor_rails/documents?" + params,
    fileGetJson: "/redactor_rails/documents",
    convertDivs: false,
    replaceDivs: false,
    buttonSource: true,
    path: "/assets/redactor-rails",
    css: "style.css",
    toolbarFixed: false,
    formatting: ['p', 'blockquote', 'h2', 'h3'],
    buttons: ['html', 'formatting', 'bold', 'italic', 'deleted', 'underline', 'unorderedlist', 'orderedlist', 'image', 'video', 'table', 'link', 'alignment', 'horizontalrule'],
    plugins: ['fullscreen', 'fontsize', 'fontfamily', 'fontcolor', 'table', 'video'],
    pasteBeforeCallback: redactorPasteBeforeCallback
  }
}

function bindRedactor(el, format, include_dynamic_fundraiser_content_button) {
  var options = redactorSharedOptions();

  if (format != 'full') {
    options.buttons = ['bold', 'italic', 'link'];
    options.plugins = [];
    options.minHeight = 200;
  }

  if (include_dynamic_fundraiser_content_button !== undefined) {
    options.buttons = options.buttons.concat(['dynamic_fundraiser_content']);
    options.plugins = options.plugins.concat(['dynamic_fundraiser_content']);
  }

  el.redactor(options);
}

$(document).ready(function() {
  $('.redactor').redactor(
    redactorSharedOptions()
  );

  $('.redactor-without-media').redactor(
    $.extend({}, redactorSharedOptions(), {
      buttons: ['html', 'formatting', 'bold', 'italic', 'deleted', 'underline', 'unorderedlist', 'orderedlist', 'table', 'link', 'alignment', 'horizontalrule'],
      plugins: ['fullscreen', 'fontsize', 'fontfamily', 'fontcolor', 'table']
    })
  );

  $('.redactor-simple').redactor(
    $.extend({}, redactorSharedOptions(), {
      buttons: ['bold', 'italic', 'link'],
      plugins: [],
      minHeight: 200
    })
  );

  $('.redactor-for-onboarder').redactor(
    $.extend({}, redactorSharedOptions(), {
      buttons: ['bold', 'italic', 'unorderedlist', 'orderedlist', 'link'],
      plugins: [],
      minHeight: 200,
      changeCallback: function() {
        $('.redactor-for-onboarder').parents('form').trigger('checkform.areYouSure');
        if (!!this.$element.data('redactor-change-callback'))
          eval(this.$element.data('redactor-change-callback') + "(this);");
      }
    })
  );

  $('.redactor-for-onboarder-full').redactor(
    $.extend({}, redactorSharedOptions(), {
      plugins: [],
      minHeight: 200,
      changeCallback: function() {
        $('.redactor-for-onboarder').parents('form').trigger('checkform.areYouSure');
        if (!!this.$element.data('redactor-change-callback'))
          eval(this.$element.data('redactor-change-callback') + "(this);");
      }
    })
  );
});


if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
	RedactorPlugins.fullscreen = function()
	{
		return {
			init: function()
			{
				this.fullscreen.isOpen = false;

				var button = this.button.add('fullscreen', 'Fullscreen');
				this.button.addCallback(button, this.fullscreen.toggle);

				if (this.opts.fullscreen) this.fullscreen.toggle();
			},
			enable: function()
			{
				this.button.changeIcon('fullscreen', 'normalscreen');
				this.button.setActive('fullscreen');
				this.fullscreen.isOpen = true;

				if (this.opts.toolbarExternal)
				{
					this.fullscreen.toolcss = {};
					this.fullscreen.boxcss = {};
					this.fullscreen.toolcss.width = this.$toolbar.css('width');
					this.fullscreen.toolcss.top = this.$toolbar.css('top');
					this.fullscreen.toolcss.position = this.$toolbar.css('position');
					this.fullscreen.boxcss.top = this.$box.css('top');
				}

				this.fullscreen.height = this.$editor.height();

				if (this.opts.maxHeight) this.$editor.css('max-height', '');
				if (this.opts.minHeight) this.$editor.css('min-height', '');

				if (!this.$fullscreenPlaceholder) this.$fullscreenPlaceholder = $('<div/>');
				this.$fullscreenPlaceholder.insertAfter(this.$box);

				this.$box.appendTo(document.body);

				this.$box.addClass('redactor-box-fullscreen');
				$('body, html').css('overflow', 'hidden');

				this.fullscreen.resize();
				$(window).on('resize.redactor.fullscreen', $.proxy(this.fullscreen.resize, this));
				$(document).scrollTop(0, 0);

				$('.redactor-toolbar-tooltip').hide();
				this.$editor.focus();
				this.observe.load();
			},
			disable: function()
			{
				this.button.removeIcon('fullscreen', 'normalscreen');
				this.button.setInactive('fullscreen');
				this.fullscreen.isOpen = false;

				$(window).off('resize.redactor.fullscreen');
				$('body, html').css('overflow', '');

				this.$box.insertBefore(this.$fullscreenPlaceholder);
				this.$fullscreenPlaceholder.remove();

				this.$box.removeClass('redactor-box-fullscreen').css({ width: 'auto', height: 'auto' });

				this.code.sync();

				if (this.opts.toolbarExternal)
				{
					this.$box.css('top', this.fullscreen.boxcss.top);
					this.$toolbar.css({
						'width': this.fullscreen.toolcss.width,
						'top': this.fullscreen.toolcss.top,
						'position': this.fullscreen.toolcss.position
					});
				}

				if (this.opts.minHeight) this.$editor.css('minHeight', this.opts.minHeight);
				if (this.opts.maxHeight) this.$editor.css('maxHeight', this.opts.maxHeight);

				$('.redactor-toolbar-tooltip').hide();
				this.$editor.css('height', 'auto');
				this.$editor.focus();
				this.observe.load();
			},
			toggle: function()
			{
				if (this.fullscreen.isOpen)
				{
					this.fullscreen.disable();
				}
				else
				{
					this.fullscreen.enable();
				}
			},
			resize: function()
			{
				if (!this.fullscreen.isOpen) return;

				var toolbarHeight = this.$toolbar.height();

				var height = $(window).height() - toolbarHeight - this.utils.normalize(this.$editor.css('padding-top')) - this.utils.normalize(this.$editor.css('padding-bottom'));
				this.$box.width($(window).width()).height(height);

				if (this.opts.toolbarExternal)
				{
					this.$toolbar.css({
						'top': '0px',
						'position': 'absolute',
						'width': '100%'
					});

					this.$box.css('top', toolbarHeight + 'px');
				}

				this.$editor.height(height);
			}
		};
	};
})(jQuery);
if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
	RedactorPlugins.fontfamily = function()
	{
		return {
			init: function ()
			{
				var fonts = [ 'Arial', 'Helvetica', 'Georgia', 'Times New Roman', 'Monospace' ];
				var that = this;
				var dropdown = {};

				$.each(fonts, function(i, s)
				{
					dropdown['s' + i] = { title: s, func: function() { that.fontfamily.set(s); }};
				});

				dropdown.remove = { title: 'Remove Font Family', func: that.fontfamily.reset };

				var button = this.button.add('fontfamily', 'Change Font Family');
				this.button.addDropdown(button, dropdown);

			},
			set: function (value)
			{
				this.inline.format('span', 'style', 'font-family:' + value + ';');
			},
			reset: function()
			{
				this.inline.removeStyleRule('font-family');
			}
		};
	};
})(jQuery);
if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
	RedactorPlugins.fontsize = function()
	{
		return {
			init: function()
			{
				var fonts = [10, 11, 12, 14, 16, 18, 20, 24, 28, 30];
				var that = this;
				var dropdown = {};

				$.each(fonts, function(i, s)
				{
					dropdown['s' + i] = { title: s + 'px', func: function() { that.fontsize.set(s); } };
				});

				dropdown.remove = { title: 'Remove Font Size', func: that.fontsize.reset };

				var button = this.button.add('fontsize', 'Change Font Size');
				this.button.addDropdown(button, dropdown);
			},
			set: function(size)
			{
				this.inline.format('span', 'style', 'font-size: ' + size + 'px;');
			},
			reset: function()
			{
				this.inline.removeStyleRule('font-size');
			}
		};
	};
})(jQuery);
if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
	RedactorPlugins.fontcolor = function()
	{
		return {
			init: function()
			{
				var colors = [
					'#ffffff', '#000000', '#eeece1', '#1f497d', '#4f81bd', '#c0504d', '#9bbb59', '#8064a2', '#4bacc6', '#f79646', '#ffff00',
					'#f2f2f2', '#7f7f7f', '#ddd9c3', '#c6d9f0', '#dbe5f1', '#f2dcdb', '#ebf1dd', '#e5e0ec', '#dbeef3', '#fdeada', '#fff2ca',
					'#d8d8d8', '#595959', '#c4bd97', '#8db3e2', '#b8cce4', '#e5b9b7', '#d7e3bc', '#ccc1d9', '#b7dde8', '#fbd5b5', '#ffe694',
					'#bfbfbf', '#3f3f3f', '#938953', '#548dd4', '#95b3d7', '#d99694', '#c3d69b', '#b2a2c7', '#b7dde8', '#fac08f', '#f2c314',
					'#a5a5a5', '#262626', '#494429', '#17365d', '#366092', '#953734', '#76923c', '#5f497a', '#92cddc', '#e36c09', '#c09100',
					'#7f7f7f', '#0c0c0c', '#1d1b10', '#0f243e', '#244061', '#632423', '#4f6128', '#3f3151', '#31859b',  '#974806', '#7f6000'
				];

				var buttons = ['fontcolor', 'backcolor'];

				for (var i = 0; i < 2; i++)
				{
					var name = buttons[i];

					var button = this.button.add(name, this.lang.get(name));
					var $dropdown = this.button.addDropdown(button);

					$dropdown.width(242);
					this.fontcolor.buildPicker($dropdown, name, colors);

				}
			},
			buildPicker: function($dropdown, name, colors)
			{
				var rule = (name == 'backcolor') ? 'background-color' : 'color';

				var len = colors.length;
				var self = this;
				var func = function(e)
				{
					e.preventDefault();
					self.fontcolor.set($(this).data('rule'), $(this).attr('rel'));
				};

				for (var z = 0; z < len; z++)
				{
					var color = colors[z];

					var $swatch = $('<a rel="' + color + '" data-rule="' + rule +'" href="#" style="float: left; font-size: 0; border: 2px solid #fff; padding: 0; margin: 0; width: 22px; height: 22px;"></a>');
					$swatch.css('background-color', color);
					$swatch.on('click', func);

					$dropdown.append($swatch);
				}

				var $elNone = $('<a href="#" style="display: block; clear: both; padding: 5px; font-size: 12px; line-height: 1;"></a>').html(this.lang.get('none'));
				$elNone.on('click', $.proxy(function(e)
				{
					e.preventDefault();
					this.fontcolor.remove(rule);

				}, this));

				$dropdown.append($elNone);
			},
			set: function(rule, type)
			{
				this.inline.format('span', 'style', rule + ': ' + type + ';');
			},
			remove: function(rule)
			{
				this.inline.removeStyleRule(rule);
			}
		};
	};
})(jQuery);
if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
	RedactorPlugins.video = function()
	{
		return {
			reUrlYoutube: /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig,
			reUrlVimeo: /https?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/,
			getTemplate: function()
			{
				return String()
				+ '<section id="redactor-modal-video-insert">'
					+ '<label>' + this.lang.get('video_html_code') + '</label>'
					+ '<textarea id="redactor-insert-video-area" style="height: 160px;"></textarea>'
				+ '</section>';
			},
			init: function()
			{
				var button = this.button.addAfter('image', 'video', this.lang.get('video'));
				this.button.addCallback(button, this.video.show);
			},
			show: function()
			{
				this.modal.addTemplate('video', this.video.getTemplate());

				this.modal.load('video', this.lang.get('video'), 700);
				this.modal.createCancelButton();

				var button = this.modal.createActionButton(this.lang.get('insert'));
				button.on('click', this.video.insert);

				this.selection.save();
				this.modal.show();

				$('#redactor-insert-video-area').focus();

			},
			insert: function()
			{
				var data = $('#redactor-insert-video-area').val();

				if (!data.match(/<iframe|<video/gi))
				{
					data = this.clean.stripTags(data);

					// parse if it is link on youtube & vimeo
					var iframeStart = '<iframe style="width: 500px; height: 281px;" src="',
						iframeEnd = '" frameborder="0" allowfullscreen></iframe>';

					if (data.match(this.video.reUrlYoutube))
					{
						data = data.replace(this.video.reUrlYoutube, iframeStart + '//www.youtube.com/embed/$1' + iframeEnd);
					}
					else if (data.match(this.video.reUrlVimeo))
					{
						data = data.replace(this.video.reUrlVimeo, iframeStart + '//player.vimeo.com/video/$2' + iframeEnd);
					}
				}

				this.selection.restore();
				this.modal.close();

				var current = this.selection.getBlock() || this.selection.getCurrent();

				if (current) $(current).after(data);
				else
				{
					this.insert.html(data);
				}

				this.code.sync();
			}

		};
	};
})(jQuery);
if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
	RedactorPlugins.table = function()
	{
		return {
			getTemplate: function()
			{
				return String()
				+ '<section id="redactor-modal-table-insert">'
					+ '<label>' + this.lang.get('rows') + '</label>'
					+ '<input type="text" size="5" value="2" id="redactor-table-rows" />'
					+ '<label>' + this.lang.get('columns') + '</label>'
					+ '<input type="text" size="5" value="3" id="redactor-table-columns" />'
				+ '</section>';
			},
			init: function()
			{

				var dropdown = {};

				dropdown.insert_table = { title: this.lang.get('insert_table'), func: this.table.show };
				dropdown.insert_row_above = { title: this.lang.get('insert_row_above'), func: this.table.addRowAbove };
				dropdown.insert_row_below = { title: this.lang.get('insert_row_below'), func: this.table.addRowBelow };
				dropdown.insert_column_left = { title: this.lang.get('insert_column_left'), func: this.table.addColumnLeft };
				dropdown.insert_column_right = { title: this.lang.get('insert_column_right'), func: this.table.addColumnRight };
				dropdown.add_head = { title: this.lang.get('add_head'), func: this.table.addHead };
				dropdown.delete_head = { title: this.lang.get('delete_head'), func: this.table.deleteHead };
				dropdown.delete_column = { title: this.lang.get('delete_column'), func: this.table.deleteColumn };
				dropdown.delete_row = { title: this.lang.get('delete_row'), func: this.table.deleteRow };
				dropdown.delete_table = { title: this.lang.get('delete_table'), func: this.table.deleteTable };

				this.observe.addButton('td', 'table');
				this.observe.addButton('th', 'table');

				var button = this.button.addBefore('link', 'table', this.lang.get('table'));
				this.button.addDropdown(button, dropdown);
			},
			show: function()
			{
				this.modal.addTemplate('table', this.table.getTemplate());

				this.modal.load('table', this.lang.get('insert_table'), 300);
				this.modal.createCancelButton();

				var button = this.modal.createActionButton(this.lang.get('insert'));
				button.on('click', this.table.insert);

				this.selection.save();
				this.modal.show();

				$('#redactor-table-rows').focus();

			},
			insert: function()
			{

				var rows = $('#redactor-table-rows').val(),
					columns = $('#redactor-table-columns').val(),
					$tableBox = $('<div>'),
					tableId = Math.floor(Math.random() * 99999),
					$table = $('<table id="table' + tableId + '"><tbody></tbody></table>'),
					i, $row, z, $column;

				for (i = 0; i < rows; i++)
				{
					$row = $('<tr>');

					for (z = 0; z < columns; z++)
					{
						$column = $('<td>' + this.opts.invisibleSpace + '</td>');

						// set the focus to the first td
						if (i === 0 && z === 0)
						{
							$column.append(this.selection.getMarker());
						}

						$($row).append($column);
					}

					$table.append($row);
				}

				$tableBox.append($table);
				var html = $tableBox.html();


				this.modal.close();
				this.selection.restore();

				if (this.table.getTable()) return;

				this.buffer.set();

				var current = this.selection.getBlock() || this.selection.getCurrent();
				if (current && current.tagName != 'BODY')
				{
					if (current.tagName == 'LI') current = $(current).closest('ul, ol');
					$(current).after(html);
				}
				else
				{
					this.insert.html(html);
				}

				this.selection.restore();

				var table = this.$editor.find('#table' + tableId);

				if (!this.opts.linebreaks && (this.utils.browser('mozilla') || this.utils.browser('msie')))
				{
					var $next = table.next();
					if ($next.length === 0)
					{
						 table.after(this.opts.emptyHtml);
					}
				}

				this.observe.buttons();

				table.find('span.redactor-selection-marker').remove();
				table.removeAttr('id');

				this.code.sync();
				this.core.setCallback('insertedTable', table);
			},
			getTable: function()
			{
				var $table = $(this.selection.getParent()).closest('table');

				if (!this.utils.isRedactorParent($table)) return false;
				if ($table.size() === 0) return false;

				return $table;
			},
			restoreAfterDelete: function($table)
			{
				this.selection.restore();
				$table.find('span.redactor-selection-marker').remove();
				this.code.sync();
			},
			deleteTable: function()
			{
				var $table = this.table.getTable();
				if (!$table) return;

				this.buffer.set();


				var $next = $table.next();
				if (!this.opts.linebreaks && $next.length !== 0)
				{
					this.caret.setStart($next);
				}
				else
				{
					this.caret.setAfter($table);
				}


				$table.remove();

				this.code.sync();
			},
			deleteRow: function()
			{
			var $table = this.table.getTable();
			if (!$table) return;

			var $current = $(this.selection.getCurrent());

			this.buffer.set();

			var $current_tr = $current.closest('tr');
			var $focus_tr = $current_tr.prev().length ? $current_tr.prev() : $current_tr.next();
			if ($focus_tr.length)
			{
				var $focus_td = $focus_tr.children('td, th').first();
				if ($focus_td.length) $focus_td.prepend(this.selection.getMarker());
			}

			$current_tr.remove();
			this.table.restoreAfterDelete($table);
		},
			deleteColumn: function()
			{
			var $table = this.table.getTable();
			if (!$table) return;

			this.buffer.set();

			var $current = $(this.selection.getCurrent());
			var $current_td = $current.closest('td, th');
			var index = $current_td[0].cellIndex;

			$table.find('tr').each($.proxy(function(i, elem)
			{
				var $elem = $(elem);
				var focusIndex = index - 1 < 0 ? index + 1 : index - 1;
				if (i === 0) $elem.find('td, th').eq(focusIndex).prepend(this.selection.getMarker());

				$elem.find('td, th').eq(index).remove();

			}, this));

			this.table.restoreAfterDelete($table);
		},
			addHead: function()
			{
				var $table = this.table.getTable();
				if (!$table) return;

				this.buffer.set();

				if ($table.find('thead').size() !== 0)
				{
					this.table.deleteHead();
					return;
				}

				var tr = $table.find('tr').first().clone();
				tr.find('td').replaceWith($.proxy(function()
				{
					return $('<th>').html(this.opts.invisibleSpace);
				}, this));

				$thead = $('<thead></thead>').append(tr);
				$table.prepend($thead);

				this.code.sync();

			},
			deleteHead: function()
			{
				var $table = this.table.getTable();
				if (!$table) return;

				var $thead = $table.find('thead');
				if ($thead.size() === 0) return;

				this.buffer.set();

				$thead.remove();
				this.code.sync();
			},
			addRowAbove: function()
			{
				this.table.addRow('before');
			},
			addRowBelow: function()
			{
				this.table.addRow('after');
			},
			addColumnLeft: function()
			{
				this.table.addColumn('before');
			},
			addColumnRight: function()
			{
				this.table.addColumn('after');
			},
			addRow: function(type)
			{
				var $table = this.table.getTable();
				if (!$table) return;

				this.buffer.set();

				var $current = $(this.selection.getCurrent());
				var $current_tr = $current.closest('tr');
				var new_tr = $current_tr.clone();

				new_tr.find('th').replaceWith(function()
				{
					var $td = $('<td>');
					$td[0].attributes = this.attributes;

					return $td.append($(this).contents());
				});

				new_tr.find('td').html(this.opts.invisibleSpace);

				if (type == 'after')
				{
					$current_tr.after(new_tr);
				}
				else
				{
					$current_tr.before(new_tr);
				}

				this.code.sync();
			},
			addColumn: function (type)
			{
				var $table = this.table.getTable();
				if (!$table) return;

				var index = 0;
				var current = $(this.selection.getCurrent());

				this.buffer.set();

				var $current_tr = current.closest('tr');
				var $current_td = current.closest('td, th');

				$current_tr.find('td, th').each($.proxy(function(i, elem)
				{
					if ($(elem)[0] === $current_td[0]) index = i;

				}, this));

				$table.find('tr').each($.proxy(function(i, elem)
				{
					var $current = $(elem).find('td, th').eq(index);

					var td = $current.clone();
					td.html(this.opts.invisibleSpace);

					if (type == 'after')
					{
						$current.after(td);
					}
					else
					{
						$current.before(td);
					}

				}, this));

				this.code.sync();
			}
		};
	};
})(jQuery);
//! moment.js
//! version : 2.10.6
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function(){"use strict";function a(){return Hc.apply(null,arguments)}function b(a){Hc=a}function c(a){return"[object Array]"===Object.prototype.toString.call(a)}function d(a){return a instanceof Date||"[object Date]"===Object.prototype.toString.call(a)}function e(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function f(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function g(a,b){for(var c in b)f(b,c)&&(a[c]=b[c]);return f(b,"toString")&&(a.toString=b.toString),f(b,"valueOf")&&(a.valueOf=b.valueOf),a}function h(a,b,c,d){return Ca(a,b,c,d,!0).utc()}function i(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function j(a){return null==a._pf&&(a._pf=i()),a._pf}function k(a){if(null==a._isValid){var b=j(a);a._isValid=!(isNaN(a._d.getTime())||!(b.overflow<0)||b.empty||b.invalidMonth||b.invalidWeekday||b.nullInput||b.invalidFormat||b.userInvalidated),a._strict&&(a._isValid=a._isValid&&0===b.charsLeftOver&&0===b.unusedTokens.length&&void 0===b.bigHour)}return a._isValid}function l(a){var b=h(NaN);return null!=a?g(j(b),a):j(b).userInvalidated=!0,b}function m(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=j(b)),"undefined"!=typeof b._locale&&(a._locale=b._locale),Jc.length>0)for(c in Jc)d=Jc[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function n(b){m(this,b),this._d=new Date(null!=b._d?b._d.getTime():NaN),Kc===!1&&(Kc=!0,a.updateOffset(this),Kc=!1)}function o(a){return a instanceof n||null!=a&&null!=a._isAMomentObject}function p(a){return 0>a?Math.ceil(a):Math.floor(a)}function q(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=p(b)),c}function r(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&q(a[d])!==q(b[d]))&&g++;return g+f}function s(){}function t(a){return a?a.toLowerCase().replace("_","-"):a}function u(a){for(var b,c,d,e,f=0;f<a.length;){for(e=t(a[f]).split("-"),b=e.length,c=t(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=v(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&r(e,c,!0)>=b-1)break;b--}f++}return null}function v(a){var b=null;if(!Lc[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Ic._abbr,require("./locale/"+a),w(b)}catch(c){}return Lc[a]}function w(a,b){var c;return a&&(c="undefined"==typeof b?y(a):x(a,b),c&&(Ic=c)),Ic._abbr}function x(a,b){return null!==b?(b.abbr=a,Lc[a]=Lc[a]||new s,Lc[a].set(b),w(a),Lc[a]):(delete Lc[a],null)}function y(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Ic;if(!c(a)){if(b=v(a))return b;a=[a]}return u(a)}function z(a,b){var c=a.toLowerCase();Mc[c]=Mc[c+"s"]=Mc[b]=a}function A(a){return"string"==typeof a?Mc[a]||Mc[a.toLowerCase()]:void 0}function B(a){var b,c,d={};for(c in a)f(a,c)&&(b=A(c),b&&(d[b]=a[c]));return d}function C(b,c){return function(d){return null!=d?(E(this,b,d),a.updateOffset(this,c),this):D(this,b)}}function D(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function E(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function F(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=A(a),"function"==typeof this[a])return this[a](b);return this}function G(a,b,c){var d=""+Math.abs(a),e=b-d.length,f=a>=0;return(f?c?"+":"":"-")+Math.pow(10,Math.max(0,e)).toString().substr(1)+d}function H(a,b,c,d){var e=d;"string"==typeof d&&(e=function(){return this[d]()}),a&&(Qc[a]=e),b&&(Qc[b[0]]=function(){return G(e.apply(this,arguments),b[1],b[2])}),c&&(Qc[c]=function(){return this.localeData().ordinal(e.apply(this,arguments),a)})}function I(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function J(a){var b,c,d=a.match(Nc);for(b=0,c=d.length;c>b;b++)Qc[d[b]]?d[b]=Qc[d[b]]:d[b]=I(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function K(a,b){return a.isValid()?(b=L(b,a.localeData()),Pc[b]=Pc[b]||J(b),Pc[b](a)):a.localeData().invalidDate()}function L(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Oc.lastIndex=0;d>=0&&Oc.test(a);)a=a.replace(Oc,c),Oc.lastIndex=0,d-=1;return a}function M(a){return"function"==typeof a&&"[object Function]"===Object.prototype.toString.call(a)}function N(a,b,c){dd[a]=M(b)?b:function(a){return a&&c?c:b}}function O(a,b){return f(dd,a)?dd[a](b._strict,b._locale):new RegExp(P(a))}function P(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function Q(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=q(a)}),c=0;c<a.length;c++)ed[a[c]]=d}function R(a,b){Q(a,function(a,c,d,e){d._w=d._w||{},b(a,d._w,d,e)})}function S(a,b,c){null!=b&&f(ed,a)&&ed[a](b,c._a,c,a)}function T(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function U(a){return this._months[a.month()]}function V(a){return this._monthsShort[a.month()]}function W(a,b,c){var d,e,f;for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=h([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function X(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),T(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function Y(b){return null!=b?(X(this,b),a.updateOffset(this,!0),this):D(this,"Month")}function Z(){return T(this.year(),this.month())}function $(a){var b,c=a._a;return c&&-2===j(a).overflow&&(b=c[gd]<0||c[gd]>11?gd:c[hd]<1||c[hd]>T(c[fd],c[gd])?hd:c[id]<0||c[id]>24||24===c[id]&&(0!==c[jd]||0!==c[kd]||0!==c[ld])?id:c[jd]<0||c[jd]>59?jd:c[kd]<0||c[kd]>59?kd:c[ld]<0||c[ld]>999?ld:-1,j(a)._overflowDayOfYear&&(fd>b||b>hd)&&(b=hd),j(a).overflow=b),a}function _(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function aa(a,b){var c=!0;return g(function(){return c&&(_(a+"\n"+(new Error).stack),c=!1),b.apply(this,arguments)},b)}function ba(a,b){od[a]||(_(b),od[a]=!0)}function ca(a){var b,c,d=a._i,e=pd.exec(d);if(e){for(j(a).iso=!0,b=0,c=qd.length;c>b;b++)if(qd[b][1].exec(d)){a._f=qd[b][0];break}for(b=0,c=rd.length;c>b;b++)if(rd[b][1].exec(d)){a._f+=(e[6]||" ")+rd[b][0];break}d.match(ad)&&(a._f+="Z"),va(a)}else a._isValid=!1}function da(b){var c=sd.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(ca(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ea(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function fa(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function ga(a){return ha(a)?366:365}function ha(a){return a%4===0&&a%100!==0||a%400===0}function ia(){return ha(this.year())}function ja(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=Da(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ka(a){return ja(a,this._week.dow,this._week.doy).week}function la(){return this._week.dow}function ma(){return this._week.doy}function na(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function oa(a){var b=ja(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function pa(a,b,c,d,e){var f,g=6+e-d,h=fa(a,0,1+g),i=h.getUTCDay();return e>i&&(i+=7),c=null!=c?1*c:e,f=1+g+7*(b-1)-i+c,{year:f>0?a:a-1,dayOfYear:f>0?f:ga(a-1)+f}}function qa(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function ra(a,b,c){return null!=a?a:null!=b?b:c}function sa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function ta(a){var b,c,d,e,f=[];if(!a._d){for(d=sa(a),a._w&&null==a._a[hd]&&null==a._a[gd]&&ua(a),a._dayOfYear&&(e=ra(a._a[fd],d[fd]),a._dayOfYear>ga(e)&&(j(a)._overflowDayOfYear=!0),c=fa(e,0,a._dayOfYear),a._a[gd]=c.getUTCMonth(),a._a[hd]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[id]&&0===a._a[jd]&&0===a._a[kd]&&0===a._a[ld]&&(a._nextDay=!0,a._a[id]=0),a._d=(a._useUTC?fa:ea).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[id]=24)}}function ua(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=ra(b.GG,a._a[fd],ja(Da(),1,4).year),d=ra(b.W,1),e=ra(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=ra(b.gg,a._a[fd],ja(Da(),f,g).year),d=ra(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=pa(c,d,e,g,f),a._a[fd]=h.year,a._dayOfYear=h.dayOfYear}function va(b){if(b._f===a.ISO_8601)return void ca(b);b._a=[],j(b).empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,k=0;for(e=L(b._f,b._locale).match(Nc)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(O(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&j(b).unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),k+=d.length),Qc[f]?(d?j(b).empty=!1:j(b).unusedTokens.push(f),S(f,d,b)):b._strict&&!d&&j(b).unusedTokens.push(f);j(b).charsLeftOver=i-k,h.length>0&&j(b).unusedInput.push(h),j(b).bigHour===!0&&b._a[id]<=12&&b._a[id]>0&&(j(b).bigHour=void 0),b._a[id]=wa(b._locale,b._a[id],b._meridiem),ta(b),$(b)}function wa(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function xa(a){var b,c,d,e,f;if(0===a._f.length)return j(a).invalidFormat=!0,void(a._d=new Date(NaN));for(e=0;e<a._f.length;e++)f=0,b=m({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._f=a._f[e],va(b),k(b)&&(f+=j(b).charsLeftOver,f+=10*j(b).unusedTokens.length,j(b).score=f,(null==d||d>f)&&(d=f,c=b));g(a,c||b)}function ya(a){if(!a._d){var b=B(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],ta(a)}}function za(a){var b=new n($(Aa(a)));return b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b}function Aa(a){var b=a._i,e=a._f;return a._locale=a._locale||y(a._l),null===b||void 0===e&&""===b?l({nullInput:!0}):("string"==typeof b&&(a._i=b=a._locale.preparse(b)),o(b)?new n($(b)):(c(e)?xa(a):e?va(a):d(b)?a._d=b:Ba(a),a))}function Ba(b){var f=b._i;void 0===f?b._d=new Date:d(f)?b._d=new Date(+f):"string"==typeof f?da(b):c(f)?(b._a=e(f.slice(0),function(a){return parseInt(a,10)}),ta(b)):"object"==typeof f?ya(b):"number"==typeof f?b._d=new Date(f):a.createFromInputFallback(b)}function Ca(a,b,c,d,e){var f={};return"boolean"==typeof c&&(d=c,c=void 0),f._isAMomentObject=!0,f._useUTC=f._isUTC=e,f._l=c,f._i=a,f._f=b,f._strict=d,za(f)}function Da(a,b,c,d){return Ca(a,b,c,d,!1)}function Ea(a,b){var d,e;if(1===b.length&&c(b[0])&&(b=b[0]),!b.length)return Da();for(d=b[0],e=1;e<b.length;++e)(!b[e].isValid()||b[e][a](d))&&(d=b[e]);return d}function Fa(){var a=[].slice.call(arguments,0);return Ea("isBefore",a)}function Ga(){var a=[].slice.call(arguments,0);return Ea("isAfter",a)}function Ha(a){var b=B(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=y(),this._bubble()}function Ia(a){return a instanceof Ha}function Ja(a,b){H(a,0,0,function(){var a=this.utcOffset(),c="+";return 0>a&&(a=-a,c="-"),c+G(~~(a/60),2)+b+G(~~a%60,2)})}function Ka(a){var b=(a||"").match(ad)||[],c=b[b.length-1]||[],d=(c+"").match(xd)||["-",0,0],e=+(60*d[1])+q(d[2]);return"+"===d[0]?e:-e}function La(b,c){var e,f;return c._isUTC?(e=c.clone(),f=(o(b)||d(b)?+b:+Da(b))-+e,e._d.setTime(+e._d+f),a.updateOffset(e,!1),e):Da(b).local()}function Ma(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Na(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ka(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ma(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?bb(this,Ya(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ma(this)}function Oa(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function Pa(a){return this.utcOffset(0,a)}function Qa(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ma(this),"m")),this}function Ra(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ka(this._i)),this}function Sa(a){return a=a?Da(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Ta(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Ua(){if("undefined"!=typeof this._isDSTShifted)return this._isDSTShifted;var a={};if(m(a,this),a=Aa(a),a._a){var b=a._isUTC?h(a._a):Da(a._a);this._isDSTShifted=this.isValid()&&r(a._a,b.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted}function Va(){return!this._isUTC}function Wa(){return this._isUTC}function Xa(){return this._isUTC&&0===this._offset}function Ya(a,b){var c,d,e,g=a,h=null;return Ia(a)?g={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(g={},b?g[b]=a:g.milliseconds=a):(h=yd.exec(a))?(c="-"===h[1]?-1:1,g={y:0,d:q(h[hd])*c,h:q(h[id])*c,m:q(h[jd])*c,s:q(h[kd])*c,ms:q(h[ld])*c}):(h=zd.exec(a))?(c="-"===h[1]?-1:1,g={y:Za(h[2],c),M:Za(h[3],c),d:Za(h[4],c),h:Za(h[5],c),m:Za(h[6],c),s:Za(h[7],c),w:Za(h[8],c)}):null==g?g={}:"object"==typeof g&&("from"in g||"to"in g)&&(e=_a(Da(g.from),Da(g.to)),g={},g.ms=e.milliseconds,g.M=e.months),d=new Ha(g),Ia(a)&&f(a,"_locale")&&(d._locale=a._locale),d}function Za(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function $a(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function _a(a,b){var c;return b=La(b,a),a.isBefore(b)?c=$a(a,b):(c=$a(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function ab(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(ba(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Ya(c,d),bb(this,e,a),this}}function bb(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&E(b,"Date",D(b,"Date")+g*d),h&&X(b,D(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function cb(a,b){var c=a||Da(),d=La(c,this).startOf("day"),e=this.diff(d,"days",!0),f=-6>e?"sameElse":-1>e?"lastWeek":0>e?"lastDay":1>e?"sameDay":2>e?"nextDay":7>e?"nextWeek":"sameElse";return this.format(b&&b[f]||this.localeData().calendar(f,this,Da(c)))}function db(){return new n(this)}function eb(a,b){var c;return b=A("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Da(a),+this>+a):(c=o(a)?+a:+Da(a),c<+this.clone().startOf(b))}function fb(a,b){var c;return b=A("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Da(a),+a>+this):(c=o(a)?+a:+Da(a),+this.clone().endOf(b)<c)}function gb(a,b,c){return this.isAfter(a,c)&&this.isBefore(b,c)}function hb(a,b){var c;return b=A(b||"millisecond"),"millisecond"===b?(a=o(a)?a:Da(a),+this===+a):(c=+Da(a),+this.clone().startOf(b)<=c&&c<=+this.clone().endOf(b))}function ib(a,b,c){var d,e,f=La(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=A(b),"year"===b||"month"===b||"quarter"===b?(e=jb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:p(e)}function jb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function kb(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function lb(){var a=this.clone().utc();return 0<a.year()&&a.year()<=9999?"function"==typeof Date.prototype.toISOString?this.toDate().toISOString():K(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):K(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function mb(b){var c=K(this,b||a.defaultFormat);return this.localeData().postformat(c)}function nb(a,b){return this.isValid()?Ya({to:this,from:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function ob(a){return this.from(Da(),a)}function pb(a,b){return this.isValid()?Ya({from:this,to:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function qb(a){return this.to(Da(),a)}function rb(a){var b;return void 0===a?this._locale._abbr:(b=y(a),null!=b&&(this._locale=b),this)}function sb(){return this._locale}function tb(a){switch(a=A(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a&&this.weekday(0),"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this}function ub(a){return a=A(a),void 0===a||"millisecond"===a?this:this.startOf(a).add(1,"isoWeek"===a?"week":a).subtract(1,"ms")}function vb(){return+this._d-6e4*(this._offset||0)}function wb(){return Math.floor(+this/1e3)}function xb(){return this._offset?new Date(+this):this._d}function yb(){var a=this;return[a.year(),a.month(),a.date(),a.hour(),a.minute(),a.second(),a.millisecond()]}function zb(){var a=this;return{years:a.year(),months:a.month(),date:a.date(),hours:a.hours(),minutes:a.minutes(),seconds:a.seconds(),milliseconds:a.milliseconds()}}function Ab(){return k(this)}function Bb(){return g({},j(this))}function Cb(){return j(this).overflow}function Db(a,b){H(0,[a,a.length],0,b)}function Eb(a,b,c){return ja(Da([a,11,31+b-c]),b,c).week}function Fb(a){var b=ja(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return null==a?b:this.add(a-b,"y")}function Gb(a){var b=ja(this,1,4).year;return null==a?b:this.add(a-b,"y")}function Hb(){return Eb(this.year(),1,4)}function Ib(){var a=this.localeData()._week;return Eb(this.year(),a.dow,a.doy)}function Jb(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)}function Kb(a,b){return"string"!=typeof a?a:isNaN(a)?(a=b.weekdaysParse(a),"number"==typeof a?a:null):parseInt(a,10)}function Lb(a){return this._weekdays[a.day()]}function Mb(a){return this._weekdaysShort[a.day()]}function Nb(a){return this._weekdaysMin[a.day()]}function Ob(a){var b,c,d;for(this._weekdaysParse=this._weekdaysParse||[],b=0;7>b;b++)if(this._weekdaysParse[b]||(c=Da([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Pb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Kb(a,this.localeData()),this.add(a-b,"d")):b}function Qb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Rb(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Sb(a,b){H(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Tb(a,b){return b._meridiemParse}function Ub(a){return"p"===(a+"").toLowerCase().charAt(0)}function Vb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Wb(a,b){b[ld]=q(1e3*("0."+a))}function Xb(){return this._isUTC?"UTC":""}function Yb(){return this._isUTC?"Coordinated Universal Time":""}function Zb(a){return Da(1e3*a)}function $b(){return Da.apply(null,arguments).parseZone()}function _b(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function ac(a){var b=this._longDateFormat[a],c=this._longDateFormat[a.toUpperCase()];return b||!c?b:(this._longDateFormat[a]=c.replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a])}function bc(){return this._invalidDate}function cc(a){return this._ordinal.replace("%d",a)}function dc(a){return a}function ec(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function fc(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function gc(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function hc(a,b,c,d){var e=y(),f=h().set(d,b);return e[c](f,a)}function ic(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return hc(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=hc(a,f,c,e);return g}function jc(a,b){return ic(a,b,"months",12,"month")}function kc(a,b){return ic(a,b,"monthsShort",12,"month")}function lc(a,b){return ic(a,b,"weekdays",7,"day")}function mc(a,b){return ic(a,b,"weekdaysShort",7,"day")}function nc(a,b){return ic(a,b,"weekdaysMin",7,"day")}function oc(){var a=this._data;return this._milliseconds=Wd(this._milliseconds),this._days=Wd(this._days),this._months=Wd(this._months),a.milliseconds=Wd(a.milliseconds),a.seconds=Wd(a.seconds),a.minutes=Wd(a.minutes),a.hours=Wd(a.hours),a.months=Wd(a.months),a.years=Wd(a.years),this}function pc(a,b,c,d){var e=Ya(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function qc(a,b){return pc(this,a,b,1)}function rc(a,b){return pc(this,a,b,-1)}function sc(a){return 0>a?Math.floor(a):Math.ceil(a)}function tc(){var a,b,c,d,e,f=this._milliseconds,g=this._days,h=this._months,i=this._data;return f>=0&&g>=0&&h>=0||0>=f&&0>=g&&0>=h||(f+=864e5*sc(vc(h)+g),g=0,h=0),i.milliseconds=f%1e3,a=p(f/1e3),i.seconds=a%60,b=p(a/60),i.minutes=b%60,c=p(b/60),i.hours=c%24,g+=p(c/24),e=p(uc(g)),h+=e,g-=sc(vc(e)),d=p(h/12),h%=12,i.days=g,i.months=h,i.years=d,this}function uc(a){return 4800*a/146097}function vc(a){return 146097*a/4800}function wc(a){var b,c,d=this._milliseconds;if(a=A(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+uc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(vc(this._months)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 1440*b+d/6e4;case"second":return 86400*b+d/1e3;case"millisecond":return Math.floor(864e5*b)+d;default:throw new Error("Unknown unit "+a)}}function xc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*q(this._months/12)}function yc(a){return function(){return this.as(a)}}function zc(a){return a=A(a),this[a+"s"]()}function Ac(a){return function(){return this._data[a]}}function Bc(){return p(this.days()/7)}function Cc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function Dc(a,b,c){var d=Ya(a).abs(),e=ke(d.as("s")),f=ke(d.as("m")),g=ke(d.as("h")),h=ke(d.as("d")),i=ke(d.as("M")),j=ke(d.as("y")),k=e<le.s&&["s",e]||1===f&&["m"]||f<le.m&&["mm",f]||1===g&&["h"]||g<le.h&&["hh",g]||1===h&&["d"]||h<le.d&&["dd",h]||1===i&&["M"]||i<le.M&&["MM",i]||1===j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,Cc.apply(null,k)}function Ec(a,b){return void 0===le[a]?!1:void 0===b?le[a]:(le[a]=b,!0)}function Fc(a){var b=this.localeData(),c=Dc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function Gc(){var a,b,c,d=me(this._milliseconds)/1e3,e=me(this._days),f=me(this._months);a=p(d/60),b=p(a/60),d%=60,a%=60,c=p(f/12),f%=12;var g=c,h=f,i=e,j=b,k=a,l=d,m=this.asSeconds();return m?(0>m?"-":"")+"P"+(g?g+"Y":"")+(h?h+"M":"")+(i?i+"D":"")+(j||k||l?"T":"")+(j?j+"H":"")+(k?k+"M":"")+(l?l+"S":""):"P0D"}var Hc,Ic,Jc=a.momentProperties=[],Kc=!1,Lc={},Mc={},Nc=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Oc=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Pc={},Qc={},Rc=/\d/,Sc=/\d\d/,Tc=/\d{3}/,Uc=/\d{4}/,Vc=/[+-]?\d{6}/,Wc=/\d\d?/,Xc=/\d{1,3}/,Yc=/\d{1,4}/,Zc=/[+-]?\d{1,6}/,$c=/\d+/,_c=/[+-]?\d+/,ad=/Z|[+-]\d\d:?\d\d/gi,bd=/[+-]?\d+(\.\d{1,3})?/,cd=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,dd={},ed={},fd=0,gd=1,hd=2,id=3,jd=4,kd=5,ld=6;H("M",["MM",2],"Mo",function(){return this.month()+1}),H("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),H("MMMM",0,0,function(a){return this.localeData().months(this,a)}),z("month","M"),N("M",Wc),N("MM",Wc,Sc),N("MMM",cd),N("MMMM",cd),Q(["M","MM"],function(a,b){b[gd]=q(a)-1}),Q(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[gd]=e:j(c).invalidMonth=a});var md="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),nd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),od={};a.suppressDeprecationWarnings=!1;var pd=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,qd=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],rd=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],sd=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=aa("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),H(0,["YY",2],0,function(){return this.year()%100}),H(0,["YYYY",4],0,"year"),H(0,["YYYYY",5],0,"year"),H(0,["YYYYYY",6,!0],0,"year"),z("year","y"),N("Y",_c),N("YY",Wc,Sc),N("YYYY",Yc,Uc),N("YYYYY",Zc,Vc),N("YYYYYY",Zc,Vc),Q(["YYYYY","YYYYYY"],fd),Q("YYYY",function(b,c){c[fd]=2===b.length?a.parseTwoDigitYear(b):q(b)}),Q("YY",function(b,c){c[fd]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return q(a)+(q(a)>68?1900:2e3)};var td=C("FullYear",!1);H("w",["ww",2],"wo","week"),H("W",["WW",2],"Wo","isoWeek"),z("week","w"),z("isoWeek","W"),N("w",Wc),N("ww",Wc,Sc),N("W",Wc),N("WW",Wc,Sc),R(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=q(a)});var ud={dow:0,doy:6};H("DDD",["DDDD",3],"DDDo","dayOfYear"),z("dayOfYear","DDD"),N("DDD",Xc),N("DDDD",Tc),Q(["DDD","DDDD"],function(a,b,c){c._dayOfYear=q(a)}),a.ISO_8601=function(){};var vd=aa("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=Da.apply(null,arguments);return this>a?this:a}),wd=aa("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=Da.apply(null,arguments);return a>this?this:a});Ja("Z",":"),Ja("ZZ",""),N("Z",ad),N("ZZ",ad),Q(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ka(a)});var xd=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var yd=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,zd=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Ya.fn=Ha.prototype;var Ad=ab(1,"add"),Bd=ab(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var Cd=aa("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});H(0,["gg",2],0,function(){return this.weekYear()%100}),H(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Db("gggg","weekYear"),Db("ggggg","weekYear"),Db("GGGG","isoWeekYear"),Db("GGGGG","isoWeekYear"),z("weekYear","gg"),z("isoWeekYear","GG"),N("G",_c),N("g",_c),N("GG",Wc,Sc),N("gg",Wc,Sc),N("GGGG",Yc,Uc),N("gggg",Yc,Uc),N("GGGGG",Zc,Vc),N("ggggg",Zc,Vc),R(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=q(a)}),R(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),H("Q",0,0,"quarter"),z("quarter","Q"),N("Q",Rc),Q("Q",function(a,b){b[gd]=3*(q(a)-1)}),H("D",["DD",2],"Do","date"),z("date","D"),N("D",Wc),N("DD",Wc,Sc),N("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),Q(["D","DD"],hd),Q("Do",function(a,b){b[hd]=q(a.match(Wc)[0],10)});var Dd=C("Date",!0);H("d",0,"do","day"),H("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),H("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),H("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),H("e",0,0,"weekday"),H("E",0,0,"isoWeekday"),z("day","d"),z("weekday","e"),z("isoWeekday","E"),N("d",Wc),N("e",Wc),N("E",Wc),N("dd",cd),N("ddd",cd),N("dddd",cd),R(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:j(c).invalidWeekday=a}),R(["d","e","E"],function(a,b,c,d){b[d]=q(a)});var Ed="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Fd="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Gd="Su_Mo_Tu_We_Th_Fr_Sa".split("_");H("H",["HH",2],0,"hour"),H("h",["hh",2],0,function(){return this.hours()%12||12}),Sb("a",!0),Sb("A",!1),z("hour","h"),N("a",Tb),N("A",Tb),N("H",Wc),N("h",Wc),N("HH",Wc,Sc),N("hh",Wc,Sc),Q(["H","HH"],id),Q(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),Q(["h","hh"],function(a,b,c){b[id]=q(a),j(c).bigHour=!0});var Hd=/[ap]\.?m?\.?/i,Id=C("Hours",!0);H("m",["mm",2],0,"minute"),z("minute","m"),N("m",Wc),N("mm",Wc,Sc),Q(["m","mm"],jd);var Jd=C("Minutes",!1);H("s",["ss",2],0,"second"),z("second","s"),N("s",Wc),N("ss",Wc,Sc),Q(["s","ss"],kd);var Kd=C("Seconds",!1);H("S",0,0,function(){return~~(this.millisecond()/100)}),H(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),H(0,["SSS",3],0,"millisecond"),H(0,["SSSS",4],0,function(){return 10*this.millisecond()}),H(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),H(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),H(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),H(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),H(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),z("millisecond","ms"),N("S",Xc,Rc),N("SS",Xc,Sc),N("SSS",Xc,Tc);var Ld;for(Ld="SSSS";Ld.length<=9;Ld+="S")N(Ld,$c);for(Ld="S";Ld.length<=9;Ld+="S")Q(Ld,Wb);var Md=C("Milliseconds",!1);H("z",0,0,"zoneAbbr"),H("zz",0,0,"zoneName");var Nd=n.prototype;Nd.add=Ad,Nd.calendar=cb,Nd.clone=db,Nd.diff=ib,Nd.endOf=ub,Nd.format=mb,Nd.from=nb,Nd.fromNow=ob,Nd.to=pb,Nd.toNow=qb,Nd.get=F,Nd.invalidAt=Cb,Nd.isAfter=eb,Nd.isBefore=fb,Nd.isBetween=gb,Nd.isSame=hb,Nd.isValid=Ab,Nd.lang=Cd,Nd.locale=rb,Nd.localeData=sb,Nd.max=wd,Nd.min=vd,Nd.parsingFlags=Bb,Nd.set=F,Nd.startOf=tb,Nd.subtract=Bd,Nd.toArray=yb,Nd.toObject=zb,Nd.toDate=xb,Nd.toISOString=lb,Nd.toJSON=lb,Nd.toString=kb,Nd.unix=wb,Nd.valueOf=vb,Nd.year=td,Nd.isLeapYear=ia,Nd.weekYear=Fb,Nd.isoWeekYear=Gb,Nd.quarter=Nd.quarters=Jb,Nd.month=Y,Nd.daysInMonth=Z,Nd.week=Nd.weeks=na,Nd.isoWeek=Nd.isoWeeks=oa,Nd.weeksInYear=Ib,Nd.isoWeeksInYear=Hb,Nd.date=Dd,Nd.day=Nd.days=Pb,Nd.weekday=Qb,Nd.isoWeekday=Rb,Nd.dayOfYear=qa,Nd.hour=Nd.hours=Id,Nd.minute=Nd.minutes=Jd,Nd.second=Nd.seconds=Kd,
Nd.millisecond=Nd.milliseconds=Md,Nd.utcOffset=Na,Nd.utc=Pa,Nd.local=Qa,Nd.parseZone=Ra,Nd.hasAlignedHourOffset=Sa,Nd.isDST=Ta,Nd.isDSTShifted=Ua,Nd.isLocal=Va,Nd.isUtcOffset=Wa,Nd.isUtc=Xa,Nd.isUTC=Xa,Nd.zoneAbbr=Xb,Nd.zoneName=Yb,Nd.dates=aa("dates accessor is deprecated. Use date instead.",Dd),Nd.months=aa("months accessor is deprecated. Use month instead",Y),Nd.years=aa("years accessor is deprecated. Use year instead",td),Nd.zone=aa("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Oa);var Od=Nd,Pd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Qd={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},Rd="Invalid date",Sd="%d",Td=/\d{1,2}/,Ud={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Vd=s.prototype;Vd._calendar=Pd,Vd.calendar=_b,Vd._longDateFormat=Qd,Vd.longDateFormat=ac,Vd._invalidDate=Rd,Vd.invalidDate=bc,Vd._ordinal=Sd,Vd.ordinal=cc,Vd._ordinalParse=Td,Vd.preparse=dc,Vd.postformat=dc,Vd._relativeTime=Ud,Vd.relativeTime=ec,Vd.pastFuture=fc,Vd.set=gc,Vd.months=U,Vd._months=md,Vd.monthsShort=V,Vd._monthsShort=nd,Vd.monthsParse=W,Vd.week=ka,Vd._week=ud,Vd.firstDayOfYear=ma,Vd.firstDayOfWeek=la,Vd.weekdays=Lb,Vd._weekdays=Ed,Vd.weekdaysMin=Nb,Vd._weekdaysMin=Gd,Vd.weekdaysShort=Mb,Vd._weekdaysShort=Fd,Vd.weekdaysParse=Ob,Vd.isPM=Ub,Vd._meridiemParse=Hd,Vd.meridiem=Vb,w("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===q(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=aa("moment.lang is deprecated. Use moment.locale instead.",w),a.langData=aa("moment.langData is deprecated. Use moment.localeData instead.",y);var Wd=Math.abs,Xd=yc("ms"),Yd=yc("s"),Zd=yc("m"),$d=yc("h"),_d=yc("d"),ae=yc("w"),be=yc("M"),ce=yc("y"),de=Ac("milliseconds"),ee=Ac("seconds"),fe=Ac("minutes"),ge=Ac("hours"),he=Ac("days"),ie=Ac("months"),je=Ac("years"),ke=Math.round,le={s:45,m:45,h:22,d:26,M:11},me=Math.abs,ne=Ha.prototype;ne.abs=oc,ne.add=qc,ne.subtract=rc,ne.as=wc,ne.asMilliseconds=Xd,ne.asSeconds=Yd,ne.asMinutes=Zd,ne.asHours=$d,ne.asDays=_d,ne.asWeeks=ae,ne.asMonths=be,ne.asYears=ce,ne.valueOf=xc,ne._bubble=tc,ne.get=zc,ne.milliseconds=de,ne.seconds=ee,ne.minutes=fe,ne.hours=ge,ne.days=he,ne.weeks=Bc,ne.months=ie,ne.years=je,ne.humanize=Fc,ne.toISOString=Gc,ne.toString=Gc,ne.toJSON=Gc,ne.locale=rb,ne.localeData=sb,ne.toIsoString=aa("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Gc),ne.lang=Cd,H("X",0,0,"unix"),H("x",0,0,"valueOf"),N("x",_c),N("X",bd),Q("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),Q("x",function(a,b,c){c._d=new Date(q(a))}),a.version="2.10.6",b(Da),a.fn=Od,a.min=Fa,a.max=Ga,a.utc=h,a.unix=Zb,a.months=jc,a.isDate=d,a.locale=w,a.invalid=l,a.duration=Ya,a.isMoment=o,a.weekdays=lc,a.parseZone=$b,a.localeData=y,a.isDuration=Ia,a.monthsShort=kc,a.weekdaysMin=nc,a.defineLocale=x,a.weekdaysShort=mc,a.normalizeUnits=A,a.relativeTimeThreshold=Ec;var oe=a;return oe});
class RemainingDaysCalculator {
    constructor(elementSelector) {
        this.element = $(elementSelector);
    }

    calculateRemainingDays() {
        // Getting the end date from data attributes
        let endDateStr = this.element.data('end-date');
        let endDate = moment(endDateStr);

        // Using Moment.js to get the current date in EST
        let currentDateEst = moment().utcOffset(-5 * 60);

        // Checking for valid Date objects to avoid errors
        if (!endDate.isValid() || !currentDateEst.isValid()) {
            console.error("Invalid date encountered. End Date:", endDate, "Current Date:", currentDateEst);
            return 0; // Return 0 days if dates are invalid
        }

        // Calculating the time difference in days using Moment.js, rounded up
        let timeDiff = endDate.diff(currentDateEst, 'days', true);
        let remainingDays = Math.ceil(timeDiff);

        // Adding 1 to include the end date in the count
        remainingDays += 1;

        // Ensure no negative days are returned
        return remainingDays > 0 ? remainingDays : 0;
    }
}
;
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
// https://github.com/igor-alexandrov/wiselinks













$(document).ready(function() {
  var calculator = new RemainingDaysCalculator('[data-describe="remaining-days-listing"]');

  var remainingDays = calculator.calculateRemainingDays();  // Call the method on the class instance to get remaining days
  var dayText = remainingDays === 1 ? 'Day Left' : 'Days Left';

  $('[data-describe="remaining-days-amount"]').text(remainingDays);
  $('[data-describe="remaining-days-caption"]').text(dayText);

  return window.wiselinks = new Wiselinks($('#main_container'), {
    html4_normalize_path: false
  });
});



