/* Minification failed. Returning unminified contents.
(27200,30-31): run-time error JS1195: Expected expression: .
(27200,36-37): run-time error JS1195: Expected expression: .
(27200,108-109): run-time error JS1003: Expected ':': )
(27202,21-24): run-time error JS1010: Expected identifier: for
(27202,26-29): run-time error JS1010: Expected identifier: var
(27202,30-35): run-time error JS1193: Expected ',' or ')': index
(27202,30-35): run-time error JS1006: Expected ')': index
(27202,30-35): run-time error JS1008: Expected '{': index
(27202,36-37): run-time error JS1195: Expected expression: =
(27202,113): run-time error JS1004: Expected ';'
(27202,113-114): run-time error JS1195: Expected expression: )
(27216,17-19): run-time error JS1009: Expected '}': if
(27216,17-19): run-time error JS1003: Expected ':': if
(27216,30-31): run-time error JS1195: Expected expression: .
(27216,36-37): run-time error JS1195: Expected expression: .
(27216,94-95): run-time error JS1003: Expected ':': )
(27218,21-24): run-time error JS1010: Expected identifier: for
(27218,26-29): run-time error JS1010: Expected identifier: var
(27218,30-35): run-time error JS1193: Expected ',' or ')': index
(27218,30-35): run-time error JS1006: Expected ')': index
(27218,30-35): run-time error JS1008: Expected '{': index
(27218,36-37): run-time error JS1195: Expected expression: =
(27218,93): run-time error JS1004: Expected ';'
(27218,93-94): run-time error JS1195: Expected expression: )
(27234,17-19): run-time error JS1009: Expected '}': if
(27234,17-19): run-time error JS1003: Expected ':': if
(27234,30-31): run-time error JS1195: Expected expression: .
(27234,36-37): run-time error JS1195: Expected expression: .
(27234,102-103): run-time error JS1003: Expected ':': )
(27236,21-24): run-time error JS1010: Expected identifier: for
(27236,26-29): run-time error JS1010: Expected identifier: var
(27236,30-35): run-time error JS1193: Expected ',' or ')': index
(27236,30-35): run-time error JS1006: Expected ')': index
(27236,30-35): run-time error JS1008: Expected '{': index
(27236,36-37): run-time error JS1195: Expected expression: =
(27236,97): run-time error JS1004: Expected ';'
(27236,97-98): run-time error JS1195: Expected expression: )
(27246,17-19): run-time error JS1009: Expected '}': if
(27246,17-19): run-time error JS1003: Expected ':': if
(27246,64-65): run-time error JS1006: Expected ')': {
(27246,64-65): run-time error JS1006: Expected ')': {
(27246,64-65): run-time error JS1006: Expected ')': {
(27331,30-31): run-time error JS1195: Expected expression: .
(27331,36-37): run-time error JS1195: Expected expression: .
(27331,108-109): run-time error JS1003: Expected ':': )
(27333,21-24): run-time error JS1010: Expected identifier: for
(27333,26-29): run-time error JS1010: Expected identifier: var
(27333,30-35): run-time error JS1193: Expected ',' or ')': index
(27333,30-35): run-time error JS1006: Expected ')': index
(27333,30-35): run-time error JS1008: Expected '{': index
(27333,36-37): run-time error JS1195: Expected expression: =
(27333,113): run-time error JS1004: Expected ';'
(27333,113-114): run-time error JS1195: Expected expression: )
(27346,17-19): run-time error JS1009: Expected '}': if
(27346,17-19): run-time error JS1003: Expected ':': if
(27346,30-31): run-time error JS1195: Expected expression: .
(27346,36-37): run-time error JS1195: Expected expression: .
(27346,94-95): run-time error JS1003: Expected ':': )
(27348,21-24): run-time error JS1010: Expected identifier: for
(27348,26-29): run-time error JS1010: Expected identifier: var
(27348,30-35): run-time error JS1193: Expected ',' or ')': index
(27348,30-35): run-time error JS1006: Expected ')': index
(27348,30-35): run-time error JS1008: Expected '{': index
(27348,36-37): run-time error JS1195: Expected expression: =
(27348,93): run-time error JS1004: Expected ';'
(27348,93-94): run-time error JS1195: Expected expression: )
(27365,17-19): run-time error JS1009: Expected '}': if
(27365,17-19): run-time error JS1003: Expected ':': if
(27365,59-60): run-time error JS1006: Expected ')': {
(27365,59-60): run-time error JS1006: Expected ')': {
(27517,30-31): run-time error JS1195: Expected expression: .
(27517,36-37): run-time error JS1195: Expected expression: .
(27517,102-103): run-time error JS1003: Expected ':': )
(27518,21-24): run-time error JS1010: Expected identifier: for
(27518,26-29): run-time error JS1010: Expected identifier: var
(27518,30-35): run-time error JS1193: Expected ',' or ')': index
(27518,30-35): run-time error JS1006: Expected ')': index
(27518,30-35): run-time error JS1008: Expected '{': index
(27518,36-37): run-time error JS1195: Expected expression: =
(27518,97): run-time error JS1004: Expected ';'
(27518,97-98): run-time error JS1195: Expected expression: )
(27525,17-19): run-time error JS1009: Expected '}': if
(27525,17-19): run-time error JS1003: Expected ':': if
(27525,59-60): run-time error JS1006: Expected ')': {
(27959,25-26): run-time error JS1009: Expected '}': [
(27959,41-42): run-time error JS1009: Expected '}': :
(27959,41-42): run-time error JS1006: Expected ')': :
(27957,24): run-time error JS1004: Expected ';'
(27960,14-15): run-time error JS1195: Expected expression: )
(27961,17-18): run-time error JS1195: Expected expression: .
(27991,10-11): run-time error JS1006: Expected ')': ;
(28109,5-6): run-time error JS1002: Syntax error: }
(29158,1-2): run-time error JS1002: Syntax error: }
(29158,2-3): run-time error JS1195: Expected expression: )
(29222,15-16): run-time error JS1010: Expected identifier: .
(29222,15-16): run-time error JS1195: Expected expression: .
(33908,68-76): run-time error JS1006: Expected ')': function
(33908,79): run-time error JS1004: Expected ';'
(33919,26): run-time error JS1004: Expected ';'
(33928,10-11): run-time error JS1195: Expected expression: )
(33929,68-76): run-time error JS1006: Expected ')': function
(33929,79): run-time error JS1004: Expected ';'
(33939,26): run-time error JS1004: Expected ';'
(33948,10-11): run-time error JS1195: Expected expression: )
(27202,21,27215,18): run-time error JS1314: Implicit property name must be identifier: for (var index = 0; index < response.data.docSearchSuggestsList.length && index < 3; index++) {
                        docSuggests.push(response.data.docSearchSuggestsList[index].docId);
                        docName = response.data.docSearchSuggestsList[index].h1Tag;
                        if (docName == null || docName == '') {
                            docName = response.data.docSearchSuggestsList[index].docName;
                        }
                        docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');


                        searchContent.append(`<div>
                                <a href="${response.data.docSearchSuggestsList[index].docUrl}" target="_blank" title="${docNameClear}">${docName}</a>
                            </div>`)
                    }
                }
(27218,21,27233,18): run-time error JS1314: Implicit property name must be identifier: for (var index = 0; index < response.data.docSearchsList.length; index++) {

                        if (!docSuggests.includes(response.data.docSearchsList[index].docId)) {
                            docName = response.data.docSearchsList[index].h1Tag;
                            if (docName == null || docName == '') {
                                docName = response.data.docSearchsList[index].docName;
                            }
                            docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');

                            searchContent.append(`<div>
                                <a href="${response.data.docSearchsList[index].docUrl}" target="_blank" title="${docNameClear}">${docName}</a>
                            </div>`)

                        }
                    }
                }
(27236,21,27244,18): run-time error JS1314: Implicit property name must be identifier: for (var index = 0; index < response.data.lawJudgSearchsList.length; index++) {

                        docSuggests.push(response.data.lawJudgSearchsList[index].docId)

                        searchContent.append(`<div class="suggest">
                                <a href="https://luatvietnam.vn${response.data.lawJudgSearchsList[index].docUrl}" target="_blank">${response.data.lawJudgSearchsList[index].title}</a>
                            </div>`)
                    }
                }
(27333,21,27345,18): run-time error JS1314: Implicit property name must be identifier: for (var index = 0; index < response.data.docSearchSuggestsList.length && index < 3; index++) {
                        docSuggests.push(response.data.docSearchSuggestsList[index].docId);
                        docName = response.data.docSearchSuggestsList[index].h1Tag;
                        if (docName == null || docName == '') {
                            docName = response.data.docSearchSuggestsList[index].docName;
                        }
                        docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');

                        searchContent.append(`<div>
                                <a href="${response.data.docSearchSuggestsList[index].docUrl}" target="_blank" title="${docNameClear}">${response.data.docSearchSuggestsList[index].docName}</a>
                            </div>`)
                    }
                }
(27348,21,27363,18): run-time error JS1314: Implicit property name must be identifier: for (var index = 0; index < response.data.docSearchsList.length; index++) {

                        if (!docSuggests.includes(response.data.docSearchsList[index].docId)) {
                            docName = response.data.docSearchsList[index].h1Tag;
                            if (docName == null || docName == '') {
                                docName = response.data.docSearchsList[index].docName;
                            }
                            docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');

                            searchContent.append(`<div>
                                <a href="${response.data.docSearchsList[index].docUrl}" target="_blank" title="${docNameClear}">${docName}</a>
                            </div>`)

                        }
                    }
                }
(27518,21,27523,18): run-time error JS1314: Implicit property name must be identifier: for (var index = 0; index < response.data.lawJudgSearchsList.length; index++) {
                        searchContent.append(`<div>
                                <a href="https://luatvietnam.vn${response.data.lawJudgSearchsList[index].docUrl}" target="_blank">${response.data.lawJudgSearchsList[index].title}</a>
                            </div>`)
                    }
                }
(29131,5,29157,6): run-time error JS1018: 'return' statement outside of function: return {
        fetchData: fetchData,
        ajaxEvents: ajaxEvents,
        showMessage: showMessage,
        storage: storage,
        showLoading: showLoading,
        hideLoading: hideLoading,
        pushState: pushState,
        validatorForm: validatorForm,
        getRecaptchaToken: getRecaptchaToken,
        addRecaptchaV3ToForm: addRecaptchaV3ToForm,
        loadScript: loadScript,
        loadGoogleRecaptcha: loadGoogleRecaptcha,
        loadGoogleTagManager: loadGoogleTagManager,
        loadFacebookPixel: loadFacebookPixel,
        loadFacebookJavascriptSDK: loadFacebookJavascriptSDK,
        loadZaloJavascriptSDK: loadZaloJavascriptSDK,
        loadvChat: loadvChat,
        removeAccents: removeAccents,
        requiredIf: requiredIf,
        formatNumber: formatNumber,
        initAdsSticky: initAdsSticky,
        debounce: debounce,
        setupFilterCheckboxSearchForm,
        setupFilterSearchForm,
        setupFilterAutocompleteSearchForm
    }
 */
/*!
 * jQuery JavaScript Library v1.7.1
 * http://jquery.com/
 *
 * Copyright 2011, John Resig
 * Released under the the MIT License.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2011, The Dojo Foundation
 * Released under the MIT and BSD Licenses.
 *
 * Date: Mon Nov 21 21:11:03 2011 -0500
 */
(function( window, undefined ) {

// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
	navigator = window.navigator,
	location = window.location;
var jQuery = (function() {

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	},

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$,

	// A central reference to the root jQuery(document)
	rootjQuery,

	// A simple way to check for HTML strings or ID strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,

	// Check if a string has a non-whitespace character in it
	rnotwhite = /\S/,

	// Used for trimming whitespace
	trimLeft = /^\s+/,
	trimRight = /\s+$/,

	// Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,

	// JSON RegExp
	rvalidchars = /^[\],:{}\s]*$/,
	rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
	rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,

	// Useragent RegExp
	rwebkit = /(webkit)[ \/]([\w.]+)/,
	ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
	rmsie = /(msie) ([\w.]+)/,
	rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,

	// Matches dashed string for camelizing
	rdashAlpha = /-([a-z]|[0-9])/ig,
	rmsPrefix = /^-ms-/,

	// Used by jQuery.camelCase as callback to replace()
	fcamelCase = function( all, letter ) {
		return ( letter + "" ).toUpperCase();
	},

	// Keep a UserAgent string for use with jQuery.browser
	userAgent = navigator.userAgent,

	// For matching the engine and version of the browser
	browserMatch,

	// The deferred used on DOM ready
	readyList,

	// The ready event handler
	DOMContentLoaded,

	// Save a reference to some core methods
	toString = Object.prototype.toString,
	hasOwn = Object.prototype.hasOwnProperty,
	push = Array.prototype.push,
	slice = Array.prototype.slice,
	trim = String.prototype.trim,
	indexOf = Array.prototype.indexOf,

	// [[Class]] -> type pairs
	class2type = {};

jQuery.fn = jQuery.prototype = {
	constructor: jQuery,
	init: function( selector, context, rootjQuery ) {
		var match, elem, ret, doc;

		// Handle $(""), $(null), or $(undefined)
		if ( !selector ) {
			return this;
		}

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this.context = this[0] = selector;
			this.length = 1;
			return this;
		}

		// The body element only exists once, optimize finding it
		if ( selector === "body" && !context && document.body ) {
			this.context = document;
			this[0] = document.body;
			this.selector = selector;
			this.length = 1;
			return this;
		}

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			// Are we dealing with HTML string or an ID?
			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = quickExpr.exec( selector );
			}

			// Verify a match, and that no context was specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] ) {
					context = context instanceof jQuery ? context[0] : context;
					doc = ( context ? context.ownerDocument || context : document );

					// If a single string is passed in and it's a single tag
					// just do a createElement and skip the rest
					ret = rsingleTag.exec( selector );

					if ( ret ) {
						if ( jQuery.isPlainObject( context ) ) {
							selector = [ document.createElement( ret[1] ) ];
							jQuery.fn.attr.call( selector, context, true );

						} else {
							selector = [ doc.createElement( ret[1] ) ];
						}

					} else {
						ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
						selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
					}

					return jQuery.merge( this, selector );

				// HANDLE: $("#id")
				} else {
					elem = document.getElementById( match[2] );

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[2] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[0] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || rootjQuery ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return rootjQuery.ready( selector );
		}

		if ( selector.selector !== undefined ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return jQuery.makeArray( selector, this );
	},

	// Start with an empty selector
	selector: "",

	// The current version of jQuery being used
	jquery: "1.7.1",

	// The default length of a jQuery object is 0
	length: 0,

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	toArray: function() {
		return slice.call( this, 0 );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num == null ?

			// Return a 'clean' array
			this.toArray() :

			// Return just the object
			( num < 0 ? this[ this.length + num ] : this[ num ] );
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems, name, selector ) {
		// Build a new jQuery matched element set
		var ret = this.constructor();

		if ( jQuery.isArray( elems ) ) {
			push.apply( ret, elems );

		} else {
			jQuery.merge( ret, elems );
		}

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		ret.context = this.context;

		if ( name === "find" ) {
			ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
		} else if ( name ) {
			ret.selector = this.selector + "." + name + "(" + selector + ")";
		}

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	ready: function( fn ) {
		// Attach the listeners
		jQuery.bindReady();

		// Add the callback
		readyList.add( fn );

		return this;
	},

	eq: function( i ) {
		i = +i;
		return i === -1 ?
			this.slice( i ) :
			this.slice( i, i + 1 );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ),
			"slice", slice.call(arguments).join(",") );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function( elem, i ) {
			return callback.call( elem, i, elem );
		}));
	},

	end: function() {
		return this.prevObject || this.constructor(null);
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: [].sort,
	splice: [].splice
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	if ( length === i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend({
	noConflict: function( deep ) {
		if ( window.$ === jQuery ) {
			window.$ = _$;
		}

		if ( deep && window.jQuery === jQuery ) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	},

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Hold (or release) the ready event
	holdReady: function( hold ) {
		if ( hold ) {
			jQuery.readyWait++;
		} else {
			jQuery.ready( true );
		}
	},

	// Handle when the DOM is ready
	ready: function( wait ) {
		// Either a released hold or an DOMready/load event and not yet ready
		if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
			// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
			if ( !document.body ) {
				return setTimeout( jQuery.ready, 1 );
			}

			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If a normal DOM Ready event fired, decrement, and wait if need be
			if ( wait !== true && --jQuery.readyWait > 0 ) {
				return;
			}

			// If there are functions bound, to execute
			readyList.fireWith( document, [ jQuery ] );

			// Trigger any bound ready events
			if ( jQuery.fn.trigger ) {
				jQuery( document ).trigger( "ready" ).off( "ready" );
			}
		}
	},

	bindReady: function() {
		if ( readyList ) {
			return;
		}

		readyList = jQuery.Callbacks( "once memory" );

		// Catch cases where $(document).ready() is called after the
		// browser event has already occurred.
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			return setTimeout( jQuery.ready, 1 );
		}

		// Mozilla, Opera and webkit nightlies currently support this event
		if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", jQuery.ready, false );

		// If IE event model is used
		} else if ( document.attachEvent ) {
			// ensure firing before onload,
			// maybe late but safe also for iframes
			document.attachEvent( "onreadystatechange", DOMContentLoaded );

			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", jQuery.ready );

			// If IE and not a frame
			// continually check to see if the document is ready
			var toplevel = false;

			try {
				toplevel = window.frameElement == null;
			} catch(e) {}

			if ( document.documentElement.doScroll && toplevel ) {
				doScrollCheck();
			}
		}
	},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type(obj) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type(obj) === "array";
	},

	// A crude way of determining if an object is a window
	isWindow: function( obj ) {
		return obj && typeof obj === "object" && "setInterval" in obj;
	},

	isNumeric: function( obj ) {
		return !isNaN( parseFloat(obj) ) && isFinite( obj );
	},

	type: function( obj ) {
		return obj == null ?
			String( obj ) :
			class2type[ toString.call(obj) ] || "object";
	},

	isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		try {
			// Not own constructor property must be Object
			if ( obj.constructor &&
				!hasOwn.call(obj, "constructor") &&
				!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
				return false;
			}
		} catch ( e ) {
			// IE8,9 Will throw exceptions on certain host objects #9897
			return false;
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.

		var key;
		for ( key in obj ) {}

		return key === undefined || hasOwn.call( obj, key );
	},

	isEmptyObject: function( obj ) {
		for ( var name in obj ) {
			return false;
		}
		return true;
	},

	error: function( msg ) {
		throw new Error( msg );
	},

	parseJSON: function( data ) {
		if ( typeof data !== "string" || !data ) {
			return null;
		}

		// Make sure leading/trailing whitespace is removed (IE can't handle it)
		data = jQuery.trim( data );

		// Attempt to parse using the native JSON parser first
		if ( window.JSON && window.JSON.parse ) {
			return window.JSON.parse( data );
		}

		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if ( rvalidchars.test( data.replace( rvalidescape, "@" )
			.replace( rvalidtokens, "]" )
			.replace( rvalidbraces, "")) ) {

			return ( new Function( "return " + data ) )();

		}
		jQuery.error( "Invalid JSON: " + data );
	},

	// Cross-browser xml parsing
	parseXML: function( data ) {
		var xml, tmp;
		try {
			if ( window.DOMParser ) { // Standard
				tmp = new DOMParser();
				xml = tmp.parseFromString( data , "text/xml" );
			} else { // IE
				xml = new ActiveXObject( "Microsoft.XMLDOM" );
				xml.async = "false";
				xml.loadXML( data );
			}
		} catch( e ) {
			xml = undefined;
		}
		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
			jQuery.error( "Invalid XML: " + data );
		}
		return xml;
	},

	noop: function() {},

	// Evaluates a script in a global context
	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && rnotwhite.test( data ) ) {
			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data );
			} )( data );
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// Microsoft forgot to hump their vendor prefix (#9572)
	camelCase: function( string ) {
		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
	},

	// args is for internal usage only
	each: function( object, callback, args ) {
		var name, i = 0,
			length = object.length,
			isObj = length === undefined || jQuery.isFunction( object );

		if ( args ) {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.apply( object[ name ], args ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.apply( object[ i++ ], args ) === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
						break;
					}
				}
			}
		}

		return object;
	},

	// Use native String.trim function wherever possible
	trim: trim ?
		function( text ) {
			return text == null ?
				"" :
				trim.call( text );
		} :

		// Otherwise use our own trimming functionality
		function( text ) {
			return text == null ?
				"" :
				text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
		},

	// results is for internal usage only
	makeArray: function( array, results ) {
		var ret = results || [];

		if ( array != null ) {
			// The window, strings (and functions) also have 'length'
			// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
			var type = jQuery.type( array );

			if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
				push.call( ret, array );
			} else {
				jQuery.merge( ret, array );
			}
		}

		return ret;
	},

	inArray: function( elem, array, i ) {
		var len;

		if ( array ) {
			if ( indexOf ) {
				return indexOf.call( array, elem, i );
			}

			len = array.length;
			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

			for ( ; i < len; i++ ) {
				// Skip accessing in sparse arrays
				if ( i in array && array[ i ] === elem ) {
					return i;
				}
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var i = first.length,
			j = 0;

		if ( typeof second.length === "number" ) {
			for ( var l = second.length; j < l; j++ ) {
				first[ i++ ] = second[ j ];
			}

		} else {
			while ( second[j] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, inv ) {
		var ret = [], retVal;
		inv = !!inv;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			retVal = !!callback( elems[ i ], i );
			if ( inv !== retVal ) {
				ret.push( elems[ i ] );
			}
		}

		return ret;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var value, key, ret = [],
			i = 0,
			length = elems.length,
			// jquery objects are treated as arrays
			isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;

		// Go through the array, translating each of the items to their
		if ( isArray ) {
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}

		// Go through every key on the object,
		} else {
			for ( key in elems ) {
				value = callback( elems[ key ], key, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}
		}

		// Flatten any nested arrays
		return ret.concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		if ( typeof context === "string" ) {
			var tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		var args = slice.call( arguments, 2 ),
			proxy = function() {
				return fn.apply( context, args.concat( slice.call( arguments ) ) );
			};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;

		return proxy;
	},

	// Mutifunctional method to get and set values to a collection
	// The value/s can optionally be executed if it's a function
	access: function( elems, key, value, exec, fn, pass ) {
		var length = elems.length;

		// Setting many attributes
		if ( typeof key === "object" ) {
			for ( var k in key ) {
				jQuery.access( elems, k, key[k], exec, fn, value );
			}
			return elems;
		}

		// Setting one attribute
		if ( value !== undefined ) {
			// Optionally, function values get executed if exec is true
			exec = !pass && exec && jQuery.isFunction(value);

			for ( var i = 0; i < length; i++ ) {
				fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
			}

			return elems;
		}

		// Getting an attribute
		return length ? fn( elems[0], key ) : undefined;
	},

	now: function() {
		return ( new Date() ).getTime();
	},

	// Use of jQuery.browser is frowned upon.
	// More details: http://docs.jquery.com/Utilities/jQuery.browser
	uaMatch: function( ua ) {
		ua = ua.toLowerCase();

		var match = rwebkit.exec( ua ) ||
			ropera.exec( ua ) ||
			rmsie.exec( ua ) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
			[];

		return { browser: match[1] || "", version: match[2] || "0" };
	},

	sub: function() {
		function jQuerySub( selector, context ) {
			return new jQuerySub.fn.init( selector, context );
		}
		jQuery.extend( true, jQuerySub, this );
		jQuerySub.superclass = this;
		jQuerySub.fn = jQuerySub.prototype = this();
		jQuerySub.fn.constructor = jQuerySub;
		jQuerySub.sub = this.sub;
		jQuerySub.fn.init = function init( selector, context ) {
			if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
				context = jQuerySub( context );
			}

			return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
		};
		jQuerySub.fn.init.prototype = jQuerySub.fn;
		var rootjQuerySub = jQuerySub(document);
		return jQuerySub;
	},

	browser: {}
});

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
	jQuery.browser[ browserMatch.browser ] = true;
	jQuery.browser.version = browserMatch.version;
}

// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
	jQuery.browser.safari = true;
}

// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
	trimLeft = /^[\s\xA0]+/;
	trimRight = /[\s\xA0]+$/;
}

// All jQuery objects should point back to these
rootjQuery = jQuery(document);

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		jQuery.ready();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			jQuery.ready();
		}
	};
}

// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( jQuery.isReady ) {
		return;
	}

	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch(e) {
		setTimeout( doScrollCheck, 1 );
		return;
	}

	// and execute any waiting functions
	jQuery.ready();
}

return jQuery;

})();


// String to Object flags format cache
var flagsCache = {};

// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
	var object = flagsCache[ flags ] = {},
		i, length;
	flags = flags.split( /\s+/ );
	for ( i = 0, length = flags.length; i < length; i++ ) {
		object[ flags[i] ] = true;
	}
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	flags:	an optional list of space-separated flags that will change how
 *			the callback list behaves
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible flags:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( flags ) {

	// Convert flags from String-formatted to Object-formatted
	// (we check in cache first)
	flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};

	var // Actual callback list
		list = [],
		// Stack of fire calls for repeatable lists
		stack = [],
		// Last fire value (for non-forgettable lists)
		memory,
		// Flag to know if list is currently firing
		firing,
		// First callback to fire (used internally by add and fireWith)
		firingStart,
		// End of the loop when firing
		firingLength,
		// Index of currently firing callback (modified by remove if needed)
		firingIndex,
		// Add one or several callbacks to the list
		add = function( args ) {
			var i,
				length,
				elem,
				type,
				actual;
			for ( i = 0, length = args.length; i < length; i++ ) {
				elem = args[ i ];
				type = jQuery.type( elem );
				if ( type === "array" ) {
					// Inspect recursively
					add( elem );
				} else if ( type === "function" ) {
					// Add if not in unique mode and callback is not in
					if ( !flags.unique || !self.has( elem ) ) {
						list.push( elem );
					}
				}
			}
		},
		// Fire callbacks
		fire = function( context, args ) {
			args = args || [];
			memory = !flags.memory || [ context, args ];
			firing = true;
			firingIndex = firingStart || 0;
			firingStart = 0;
			firingLength = list.length;
			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
				if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
					memory = true; // Mark as halted
					break;
				}
			}
			firing = false;
			if ( list ) {
				if ( !flags.once ) {
					if ( stack && stack.length ) {
						memory = stack.shift();
						self.fireWith( memory[ 0 ], memory[ 1 ] );
					}
				} else if ( memory === true ) {
					self.disable();
				} else {
					list = [];
				}
			}
		},
		// Actual Callbacks object
		self = {
			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {
					var length = list.length;
					add( arguments );
					// Do we need to add the callbacks to the
					// current firing batch?
					if ( firing ) {
						firingLength = list.length;
					// With memory, if we're not firing then
					// we should call right away, unless previous
					// firing was halted (stopOnFalse)
					} else if ( memory && memory !== true ) {
						firingStart = length;
						fire( memory[ 0 ], memory[ 1 ] );
					}
				}
				return this;
			},
			// Remove a callback from the list
			remove: function() {
				if ( list ) {
					var args = arguments,
						argIndex = 0,
						argLength = args.length;
					for ( ; argIndex < argLength ; argIndex++ ) {
						for ( var i = 0; i < list.length; i++ ) {
							if ( args[ argIndex ] === list[ i ] ) {
								// Handle firingIndex and firingLength
								if ( firing ) {
									if ( i <= firingLength ) {
										firingLength--;
										if ( i <= firingIndex ) {
											firingIndex--;
										}
									}
								}
								// Remove the element
								list.splice( i--, 1 );
								// If we have some unicity property then
								// we only need to do this once
								if ( flags.unique ) {
									break;
								}
							}
						}
					}
				}
				return this;
			},
			// Control if a given callback is in the list
			has: function( fn ) {
				if ( list ) {
					var i = 0,
						length = list.length;
					for ( ; i < length; i++ ) {
						if ( fn === list[ i ] ) {
							return true;
						}
					}
				}
				return false;
			},
			// Remove all callbacks from the list
			empty: function() {
				list = [];
				return this;
			},
			// Have the list do nothing anymore
			disable: function() {
				list = stack = memory = undefined;
				return this;
			},
			// Is it disabled?
			disabled: function() {
				return !list;
			},
			// Lock the list in its current state
			lock: function() {
				stack = undefined;
				if ( !memory || memory === true ) {
					self.disable();
				}
				return this;
			},
			// Is it locked?
			locked: function() {
				return !stack;
			},
			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( stack ) {
					if ( firing ) {
						if ( !flags.once ) {
							stack.push( [ context, args ] );
						}
					} else if ( !( flags.once && memory ) ) {
						fire( context, args );
					}
				}
				return this;
			},
			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},
			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!memory;
			}
		};

	return self;
};




var // Static reference to slice
	sliceDeferred = [].slice;

jQuery.extend({

	Deferred: function( func ) {
		var doneList = jQuery.Callbacks( "once memory" ),
			failList = jQuery.Callbacks( "once memory" ),
			progressList = jQuery.Callbacks( "memory" ),
			state = "pending",
			lists = {
				resolve: doneList,
				reject: failList,
				notify: progressList
			},
			promise = {
				done: doneList.add,
				fail: failList.add,
				progress: progressList.add,

				state: function() {
					return state;
				},

				// Deprecated
				isResolved: doneList.fired,
				isRejected: failList.fired,

				then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
					deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
					return this;
				},
				always: function() {
					deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
					return this;
				},
				pipe: function( fnDone, fnFail, fnProgress ) {
					return jQuery.Deferred(function( newDefer ) {
						jQuery.each( {
							done: [ fnDone, "resolve" ],
							fail: [ fnFail, "reject" ],
							progress: [ fnProgress, "notify" ]
						}, function( handler, data ) {
							var fn = data[ 0 ],
								action = data[ 1 ],
								returned;
							if ( jQuery.isFunction( fn ) ) {
								deferred[ handler ](function() {
									returned = fn.apply( this, arguments );
									if ( returned && jQuery.isFunction( returned.promise ) ) {
										returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
									} else {
										newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
									}
								});
							} else {
								deferred[ handler ]( newDefer[ action ] );
							}
						});
					}).promise();
				},
				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					if ( obj == null ) {
						obj = promise;
					} else {
						for ( var key in promise ) {
							obj[ key ] = promise[ key ];
						}
					}
					return obj;
				}
			},
			deferred = promise.promise({}),
			key;

		for ( key in lists ) {
			deferred[ key ] = lists[ key ].fire;
			deferred[ key + "With" ] = lists[ key ].fireWith;
		}

		// Handle state
		deferred.done( function() {
			state = "resolved";
		}, failList.disable, progressList.lock ).fail( function() {
			state = "rejected";
		}, doneList.disable, progressList.lock );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( firstParam ) {
		var args = sliceDeferred.call( arguments, 0 ),
			i = 0,
			length = args.length,
			pValues = new Array( length ),
			count = length,
			pCount = length,
			deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
				firstParam :
				jQuery.Deferred(),
			promise = deferred.promise();
		function resolveFunc( i ) {
			return function( value ) {
				args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
				if ( !( --count ) ) {
					deferred.resolveWith( deferred, args );
				}
			};
		}
		function progressFunc( i ) {
			return function( value ) {
				pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
				deferred.notifyWith( promise, pValues );
			};
		}
		if ( length > 1 ) {
			for ( ; i < length; i++ ) {
				if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
					args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
				} else {
					--count;
				}
			}
			if ( !count ) {
				deferred.resolveWith( deferred, args );
			}
		} else if ( deferred !== firstParam ) {
			deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
		}
		return promise;
	}
});




jQuery.support = (function() {

	var support,
		all,
		a,
		select,
		opt,
		input,
		marginDiv,
		fragment,
		tds,
		events,
		eventName,
		i,
		isSupported,
		div = document.createElement( "div" ),
		documentElement = document.documentElement;

	// Preliminary tests
	div.setAttribute("className", "t");
	div.innerHTML = "   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";

	all = div.getElementsByTagName( "*" );
	a = div.getElementsByTagName( "a" )[ 0 ];

	// Can't get basic test support
	if ( !all || !all.length || !a ) {
		return {};
	}

	// First batch of supports tests
	select = document.createElement( "select" );
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName( "input" )[ 0 ];

	support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: ( div.firstChild.nodeType === 3 ),

		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,

		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,

		// Get the style information from getAttribute
		// (IE uses .cssText instead)
		style: /top/.test( a.getAttribute("style") ),

		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: ( a.getAttribute("href") === "/a" ),

		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.55/.test( a.style.opacity ),

		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Make sure that if no value is specified for a checkbox
		// that it defaults to "on".
		// (WebKit defaults to "" instead)
		checkOn: ( input.value === "on" ),

		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: opt.selected,

		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
		getSetAttribute: div.className !== "t",

		// Tests for enctype support on a form(#6743)
		enctype: !!document.createElement("form").enctype,

		// Makes sure cloning an html5 element does not cause problems
		// Where outerHTML is undefined, this still works
		html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",

		// Will be defined later
		submitBubbles: true,
		changeBubbles: true,
		focusinBubbles: false,
		deleteExpando: true,
		noCloneEvent: true,
		inlineBlockNeedsLayout: false,
		shrinkWrapBlocks: false,
		reliableMarginRight: true
	};

	// Make sure checked status is properly cloned
	input.checked = true;
	support.noCloneChecked = input.cloneNode( true ).checked;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Test to see if it's possible to delete an expando from an element
	// Fails in Internet Explorer
	try {
		delete div.test;
	} catch( e ) {
		support.deleteExpando = false;
	}

	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
		div.attachEvent( "onclick", function() {
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			support.noCloneEvent = false;
		});
		div.cloneNode( true ).fireEvent( "onclick" );
	}

	// Check if a radio maintains its value
	// after being appended to the DOM
	input = document.createElement("input");
	input.value = "t";
	input.setAttribute("type", "radio");
	support.radioValue = input.value === "t";

	input.setAttribute("checked", "checked");
	div.appendChild( input );
	fragment = document.createDocumentFragment();
	fragment.appendChild( div.lastChild );

	// WebKit doesn't clone checked state correctly in fragments
	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	support.appendChecked = input.checked;

	fragment.removeChild( input );
	fragment.appendChild( div );

	div.innerHTML = "";

	// Check if div with explicit width and no margin-right incorrectly
	// gets computed margin-right based on width of container. For more
	// info see bug #3333
	// Fails in WebKit before Feb 2011 nightlies
	// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
	if ( window.getComputedStyle ) {
		marginDiv = document.createElement( "div" );
		marginDiv.style.width = "0";
		marginDiv.style.marginRight = "0";
		div.style.width = "2px";
		div.appendChild( marginDiv );
		support.reliableMarginRight =
			( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
	}

	// Technique from Juriy Zaytsev
	// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
	// We only care about the case where non-standard event systems
	// are used, namely in IE. Short-circuiting here helps us to
	// avoid an eval call (in setAttribute) which can cause CSP
	// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
	if ( div.attachEvent ) {
		for( i in {
			submit: 1,
			change: 1,
			focusin: 1
		}) {
			eventName = "on" + i;
			isSupported = ( eventName in div );
			if ( !isSupported ) {
				div.setAttribute( eventName, "return;" );
				isSupported = ( typeof div[ eventName ] === "function" );
			}
			support[ i + "Bubbles" ] = isSupported;
		}
	}

	fragment.removeChild( div );

	// Null elements to avoid leaks in IE
	fragment = select = opt = marginDiv = div = input = null;

	// Run tests that need a body at doc ready
	jQuery(function() {
		var container, outer, inner, table, td, offsetSupport,
			conMarginTop, ptlm, vb, style, html,
			body = document.getElementsByTagName("body")[0];

		if ( !body ) {
			// Return for frameset docs that don't have a body
			return;
		}

		conMarginTop = 1;
		ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";
		vb = "visibility:hidden;border:0;";
		style = "style='" + ptlm + "border:5px solid #000;padding:0;'";
		html = "<div " + style + "><div></div></div>" +
			"<table " + style + " cellpadding='0' cellspacing='0'>" +
			"<tr><td></td></tr></table>";

		container = document.createElement("div");
		container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
		body.insertBefore( container, body.firstChild );

		// Construct the test element
		div = document.createElement("div");
		container.appendChild( div );

		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		// (only IE 8 fails this test)
		div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
		tds = div.getElementsByTagName( "td" );
		isSupported = ( tds[ 0 ].offsetHeight === 0 );

		tds[ 0 ].style.display = "";
		tds[ 1 ].style.display = "none";

		// Check if empty table cells still have offsetWidth/Height
		// (IE <= 8 fail this test)
		support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );

		// Figure out if the W3C box model works as expected
		div.innerHTML = "";
		div.style.width = div.style.paddingLeft = "1px";
		jQuery.boxModel = support.boxModel = div.offsetWidth === 2;

		if ( typeof div.style.zoom !== "undefined" ) {
			// Check if natively block-level elements act like inline-block
			// elements when setting their display to 'inline' and giving
			// them layout
			// (IE < 8 does this)
			div.style.display = "inline";
			div.style.zoom = 1;
			support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );

			// Check if elements with layout shrink-wrap their children
			// (IE 6 does this)
			div.style.display = "";
			div.innerHTML = "<div style='width:4px;'></div>";
			support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
		}

		div.style.cssText = ptlm + vb;
		div.innerHTML = html;

		outer = div.firstChild;
		inner = outer.firstChild;
		td = outer.nextSibling.firstChild.firstChild;

		offsetSupport = {
			doesNotAddBorder: ( inner.offsetTop !== 5 ),
			doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
		};

		inner.style.position = "fixed";
		inner.style.top = "20px";

		// safari subtracts parent border width here which is 5px
		offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
		inner.style.position = inner.style.top = "";

		outer.style.overflow = "hidden";
		outer.style.position = "relative";

		offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
		offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );

		body.removeChild( container );
		div  = container = null;

		jQuery.extend( support, offsetSupport );
	});

	return support;
})();




var rbrace = /^(?:\{.*\}|\[.*\])$/,
	rmultiDash = /([A-Z])/g;

jQuery.extend({
	cache: {},

	// Please use with caution
	uuid: 0,

	// Unique for each copy of jQuery on the page
	// Non-digits removed to match rinlinejQuery
	expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),

	// The following elements throw uncatchable exceptions if you
	// attempt to add expando properties to them.
	noData: {
		"embed": true,
		// Ban all objects except for Flash (which handle expandos)
		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
		"applet": true
	},

	hasData: function( elem ) {
		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
		return !!elem && !isEmptyDataObject( elem );
	},

	data: function( elem, name, data, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}

		var privateCache, thisCache, ret,
			internalKey = jQuery.expando,
			getByName = typeof name === "string",

			// We have to handle DOM nodes and JS objects differently because IE6-7
			// can't GC object references properly across the DOM-JS boundary
			isNode = elem.nodeType,

			// Only DOM nodes need the global jQuery cache; JS object data is
			// attached directly to the object so GC can occur automatically
			cache = isNode ? jQuery.cache : elem,

			// Only defining an ID for JS objects if its cache already exists allows
			// the code to shortcut on the same path as a DOM node with no cache
			id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
			isEvents = name === "events";

		// Avoid doing any more work than we need to when trying to get data on an
		// object that has no data at all
		if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
			return;
		}

		if ( !id ) {
			// Only DOM nodes need a new unique ID for each element since their data
			// ends up in the global cache
			if ( isNode ) {
				elem[ internalKey ] = id = ++jQuery.uuid;
			} else {
				id = internalKey;
			}
		}

		if ( !cache[ id ] ) {
			cache[ id ] = {};

			// Avoids exposing jQuery metadata on plain JS objects when the object
			// is serialized using JSON.stringify
			if ( !isNode ) {
				cache[ id ].toJSON = jQuery.noop;
			}
		}

		// An object can be passed to jQuery.data instead of a key/value pair; this gets
		// shallow copied over onto the existing cache
		if ( typeof name === "object" || typeof name === "function" ) {
			if ( pvt ) {
				cache[ id ] = jQuery.extend( cache[ id ], name );
			} else {
				cache[ id ].data = jQuery.extend( cache[ id ].data, name );
			}
		}

		privateCache = thisCache = cache[ id ];

		// jQuery data() is stored in a separate object inside the object's internal data
		// cache in order to avoid key collisions between internal data and user-defined
		// data.
		if ( !pvt ) {
			if ( !thisCache.data ) {
				thisCache.data = {};
			}

			thisCache = thisCache.data;
		}

		if ( data !== undefined ) {
			thisCache[ jQuery.camelCase( name ) ] = data;
		}

		// Users should not attempt to inspect the internal events object using jQuery.data,
		// it is undocumented and subject to change. But does anyone listen? No.
		if ( isEvents && !thisCache[ name ] ) {
			return privateCache.events;
		}

		// Check for both converted-to-camel and non-converted data property names
		// If a data property was specified
		if ( getByName ) {

			// First Try to find as-is property data
			ret = thisCache[ name ];

			// Test for null|undefined property data
			if ( ret == null ) {

				// Try to find the camelCased property
				ret = thisCache[ jQuery.camelCase( name ) ];
			}
		} else {
			ret = thisCache;
		}

		return ret;
	},

	removeData: function( elem, name, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}

		var thisCache, i, l,

			// Reference to internal data cache key
			internalKey = jQuery.expando,

			isNode = elem.nodeType,

			// See jQuery.data for more information
			cache = isNode ? jQuery.cache : elem,

			// See jQuery.data for more information
			id = isNode ? elem[ internalKey ] : internalKey;

		// If there is already no cache entry for this object, there is no
		// purpose in continuing
		if ( !cache[ id ] ) {
			return;
		}

		if ( name ) {

			thisCache = pvt ? cache[ id ] : cache[ id ].data;

			if ( thisCache ) {

				// Support array or space separated string names for data keys
				if ( !jQuery.isArray( name ) ) {

					// try the string as a key before any manipulation
					if ( name in thisCache ) {
						name = [ name ];
					} else {

						// split the camel cased version by spaces unless a key with the spaces exists
						name = jQuery.camelCase( name );
						if ( name in thisCache ) {
							name = [ name ];
						} else {
							name = name.split( " " );
						}
					}
				}

				for ( i = 0, l = name.length; i < l; i++ ) {
					delete thisCache[ name[i] ];
				}

				// If there is no data left in the cache, we want to continue
				// and let the cache object itself get destroyed
				if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
					return;
				}
			}
		}

		// See jQuery.data for more information
		if ( !pvt ) {
			delete cache[ id ].data;

			// Don't destroy the parent cache unless the internal data object
			// had been the only thing left in it
			if ( !isEmptyDataObject(cache[ id ]) ) {
				return;
			}
		}

		// Browsers that fail expando deletion also refuse to delete expandos on
		// the window, but it will allow it on all other JS objects; other browsers
		// don't care
		// Ensure that `cache` is not a window object #10080
		if ( jQuery.support.deleteExpando || !cache.setInterval ) {
			delete cache[ id ];
		} else {
			cache[ id ] = null;
		}

		// We destroyed the cache and need to eliminate the expando on the node to avoid
		// false lookups in the cache for entries that no longer exist
		if ( isNode ) {
			// IE does not allow us to delete expando properties from nodes,
			// nor does it have a removeAttribute function on Document nodes;
			// we must handle all of these cases
			if ( jQuery.support.deleteExpando ) {
				delete elem[ internalKey ];
			} else if ( elem.removeAttribute ) {
				elem.removeAttribute( internalKey );
			} else {
				elem[ internalKey ] = null;
			}
		}
	},

	// For internal use only.
	_data: function( elem, name, data ) {
		return jQuery.data( elem, name, data, true );
	},

	// A method for determining if a DOM node can handle the data expando
	acceptData: function( elem ) {
		if ( elem.nodeName ) {
			var match = jQuery.noData[ elem.nodeName.toLowerCase() ];

			if ( match ) {
				return !(match === true || elem.getAttribute("classid") !== match);
			}
		}

		return true;
	}
});

jQuery.fn.extend({
	data: function( key, value ) {
		var parts, attr, name,
			data = null;

		if ( typeof key === "undefined" ) {
			if ( this.length ) {
				data = jQuery.data( this[0] );

				if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) {
					attr = this[0].attributes;
					for ( var i = 0, l = attr.length; i < l; i++ ) {
						name = attr[i].name;

						if ( name.indexOf( "data-" ) === 0 ) {
							name = jQuery.camelCase( name.substring(5) );

							dataAttr( this[0], name, data[ name ] );
						}
					}
					jQuery._data( this[0], "parsedAttrs", true );
				}
			}

			return data;

		} else if ( typeof key === "object" ) {
			return this.each(function() {
				jQuery.data( this, key );
			});
		}

		parts = key.split(".");
		parts[1] = parts[1] ? "." + parts[1] : "";

		if ( value === undefined ) {
			data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

			// Try to fetch any internally stored data first
			if ( data === undefined && this.length ) {
				data = jQuery.data( this[0], key );
				data = dataAttr( this[0], key, data );
			}

			return data === undefined && parts[1] ?
				this.data( parts[0] ) :
				data;

		} else {
			return this.each(function() {
				var self = jQuery( this ),
					args = [ parts[0], value ];

				self.triggerHandler( "setData" + parts[1] + "!", args );
				jQuery.data( this, key, value );
				self.triggerHandler( "changeData" + parts[1] + "!", args );
			});
		}
	},

	removeData: function( key ) {
		return this.each(function() {
			jQuery.removeData( this, key );
		});
	}
});

function dataAttr( elem, key, data ) {
	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {

		var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();

		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = data === "true" ? true :
				data === "false" ? false :
				data === "null" ? null :
				jQuery.isNumeric( data ) ? parseFloat( data ) :
					rbrace.test( data ) ? jQuery.parseJSON( data ) :
					data;
			} catch( e ) {}

			// Make sure we set the data so it isn't changed later
			jQuery.data( elem, key, data );

		} else {
			data = undefined;
		}
	}

	return data;
}

// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
	for ( var name in obj ) {

		// if the public data object is empty, the private is still empty
		if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
			continue;
		}
		if ( name !== "toJSON" ) {
			return false;
		}
	}

	return true;
}




function handleQueueMarkDefer( elem, type, src ) {
	var deferDataKey = type + "defer",
		queueDataKey = type + "queue",
		markDataKey = type + "mark",
		defer = jQuery._data( elem, deferDataKey );
	if ( defer &&
		( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
		( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
		// Give room for hard-coded callbacks to fire first
		// and eventually mark/queue something else on the element
		setTimeout( function() {
			if ( !jQuery._data( elem, queueDataKey ) &&
				!jQuery._data( elem, markDataKey ) ) {
				jQuery.removeData( elem, deferDataKey, true );
				defer.fire();
			}
		}, 0 );
	}
}

jQuery.extend({

	_mark: function( elem, type ) {
		if ( elem ) {
			type = ( type || "fx" ) + "mark";
			jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
		}
	},

	_unmark: function( force, elem, type ) {
		if ( force !== true ) {
			type = elem;
			elem = force;
			force = false;
		}
		if ( elem ) {
			type = type || "fx";
			var key = type + "mark",
				count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
			if ( count ) {
				jQuery._data( elem, key, count );
			} else {
				jQuery.removeData( elem, key, true );
				handleQueueMarkDefer( elem, type, "mark" );
			}
		}
	},

	queue: function( elem, type, data ) {
		var q;
		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			q = jQuery._data( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !q || jQuery.isArray(data) ) {
					q = jQuery._data( elem, type, jQuery.makeArray(data) );
				} else {
					q.push( data );
				}
			}
			return q || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			fn = queue.shift(),
			hooks = {};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
		}

		if ( fn ) {
			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			jQuery._data( elem, type + ".run", hooks );
			fn.call( elem, function() {
				jQuery.dequeue( elem, type );
			}, hooks );
		}

		if ( !queue.length ) {
			jQuery.removeData( elem, type + "queue " + type + ".run", true );
			handleQueueMarkDefer( elem, type, "queue" );
		}
	}
});

jQuery.fn.extend({
	queue: function( type, data ) {
		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
		}

		if ( data === undefined ) {
			return jQuery.queue( this[0], type );
		}
		return this.each(function() {
			var queue = jQuery.queue( this, type, data );

			if ( type === "fx" && queue[0] !== "inprogress" ) {
				jQuery.dequeue( this, type );
			}
		});
	},
	dequeue: function( type ) {
		return this.each(function() {
			jQuery.dequeue( this, type );
		});
	},
	// Based off of the plugin by Clint Helfers, with permission.
	// http://blindsignals.com/index.php/2009/07/jquery-delay/
	delay: function( time, type ) {
		time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
		type = type || "fx";

		return this.queue( type, function( next, hooks ) {
			var timeout = setTimeout( next, time );
			hooks.stop = function() {
				clearTimeout( timeout );
			};
		});
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},
	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, object ) {
		if ( typeof type !== "string" ) {
			object = type;
			type = undefined;
		}
		type = type || "fx";
		var defer = jQuery.Deferred(),
			elements = this,
			i = elements.length,
			count = 1,
			deferDataKey = type + "defer",
			queueDataKey = type + "queue",
			markDataKey = type + "mark",
			tmp;
		function resolve() {
			if ( !( --count ) ) {
				defer.resolveWith( elements, [ elements ] );
			}
		}
		while( i-- ) {
			if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
					( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
						jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
					jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
				count++;
				tmp.add( resolve );
			}
		}
		resolve();
		return defer.promise();
	}
});




var rclass = /[\n\t\r]/g,
	rspace = /\s+/,
	rreturn = /\r/g,
	rtype = /^(?:button|input)$/i,
	rfocusable = /^(?:button|input|object|select|textarea)$/i,
	rclickable = /^a(?:rea)?$/i,
	rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
	getSetAttribute = jQuery.support.getSetAttribute,
	nodeHook, boolHook, fixSpecified;

jQuery.fn.extend({
	attr: function( name, value ) {
		return jQuery.access( this, name, value, true, jQuery.attr );
	},

	removeAttr: function( name ) {
		return this.each(function() {
			jQuery.removeAttr( this, name );
		});
	},

	prop: function( name, value ) {
		return jQuery.access( this, name, value, true, jQuery.prop );
	},

	removeProp: function( name ) {
		name = jQuery.propFix[ name ] || name;
		return this.each(function() {
			// try/catch handles cases where IE balks (such as removing a property on window)
			try {
				this[ name ] = undefined;
				delete this[ name ];
			} catch( e ) {}
		});
	},

	addClass: function( value ) {
		var classNames, i, l, elem,
			setClass, c, cl;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).addClass( value.call(this, j, this.className) );
			});
		}

		if ( value && typeof value === "string" ) {
			classNames = value.split( rspace );

			for ( i = 0, l = this.length; i < l; i++ ) {
				elem = this[ i ];

				if ( elem.nodeType === 1 ) {
					if ( !elem.className && classNames.length === 1 ) {
						elem.className = value;

					} else {
						setClass = " " + elem.className + " ";

						for ( c = 0, cl = classNames.length; c < cl; c++ ) {
							if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
								setClass += classNames[ c ] + " ";
							}
						}
						elem.className = jQuery.trim( setClass );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classNames, i, l, elem, className, c, cl;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).removeClass( value.call(this, j, this.className) );
			});
		}

		if ( (value && typeof value === "string") || value === undefined ) {
			classNames = ( value || "" ).split( rspace );

			for ( i = 0, l = this.length; i < l; i++ ) {
				elem = this[ i ];

				if ( elem.nodeType === 1 && elem.className ) {
					if ( value ) {
						className = (" " + elem.className + " ").replace( rclass, " " );
						for ( c = 0, cl = classNames.length; c < cl; c++ ) {
							className = className.replace(" " + classNames[ c ] + " ", " ");
						}
						elem.className = jQuery.trim( className );

					} else {
						elem.className = "";
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value,
			isBool = typeof stateVal === "boolean";

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( i ) {
				jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className,
					i = 0,
					self = jQuery( this ),
					state = stateVal,
					classNames = value.split( rspace );

				while ( (className = classNames[ i++ ]) ) {
					// check each className given, space seperated list
					state = isBool ? state : !self.hasClass( className );
					self[ state ? "addClass" : "removeClass" ]( className );
				}

			} else if ( type === "undefined" || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery._data( this, "__className__", this.className );
				}

				// toggle whole className
				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ",
			i = 0,
			l = this.length;
		for ( ; i < l; i++ ) {
			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
				return true;
			}
		}

		return false;
	},

	val: function( value ) {
		var hooks, ret, isFunction,
			elem = this[0];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];

				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
					return ret;
				}

				ret = elem.value;

				return typeof ret === "string" ?
					// handle most common string cases
					ret.replace(rreturn, "") :
					// handle cases where value is null/undef or number
					ret == null ? "" : ret;
			}

			return;
		}

		isFunction = jQuery.isFunction( value );

		return this.each(function( i ) {
			var self = jQuery(this), val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call( this, i, self.val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";
			} else if ( typeof val === "number" ) {
				val += "";
			} else if ( jQuery.isArray( val ) ) {
				val = jQuery.map(val, function ( value ) {
					return value == null ? "" : value + "";
				});
			}

			hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		});
	}
});

jQuery.extend({
	valHooks: {
		option: {
			get: function( elem ) {
				// attributes.value is undefined in Blackberry 4.7 but
				// uses .value. See #6932
				var val = elem.attributes.value;
				return !val || val.specified ? elem.value : elem.text;
			}
		},
		select: {
			get: function( elem ) {
				var value, i, max, option,
					index = elem.selectedIndex,
					values = [],
					options = elem.options,
					one = elem.type === "select-one";

				// Nothing was selected
				if ( index < 0 ) {
					return null;
				}

				// Loop through all the selected options
				i = one ? index : 0;
				max = one ? index + 1 : options.length;
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// Don't return options that are disabled or in a disabled optgroup
					if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
							(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
				if ( one && !values.length && options.length ) {
					return jQuery( options[ index ] ).val();
				}

				return values;
			},

			set: function( elem, value ) {
				var values = jQuery.makeArray( value );

				jQuery(elem).find("option").each(function() {
					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
				});

				if ( !values.length ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	},

	attrFn: {
		val: true,
		css: true,
		html: true,
		text: true,
		data: true,
		width: true,
		height: true,
		offset: true
	},

	attr: function( elem, name, value, pass ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// don't get/set attributes on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( pass && name in jQuery.attrFn ) {
			return jQuery( elem )[ name ]( value );
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		// All attributes are lowercase
		// Grab necessary hook if one is defined
		if ( notxml ) {
			name = name.toLowerCase();
			hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
		}

		if ( value !== undefined ) {

			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;

			} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				elem.setAttribute( name, "" + value );
				return value;
			}

		} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
			return ret;

		} else {

			ret = elem.getAttribute( name );

			// Non-existent attributes return null, we normalize to undefined
			return ret === null ?
				undefined :
				ret;
		}
	},

	removeAttr: function( elem, value ) {
		var propName, attrNames, name, l,
			i = 0;

		if ( value && elem.nodeType === 1 ) {
			attrNames = value.toLowerCase().split( rspace );
			l = attrNames.length;

			for ( ; i < l; i++ ) {
				name = attrNames[ i ];

				if ( name ) {
					propName = jQuery.propFix[ name ] || name;

					// See #9699 for explanation of this approach (setting first, then removal)
					jQuery.attr( elem, name, "" );
					elem.removeAttribute( getSetAttribute ? name : propName );

					// Set corresponding property to false for boolean attributes
					if ( rboolean.test( name ) && propName in elem ) {
						elem[ propName ] = false;
					}
				}
			}
		}
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				// We can't allow the type property to be changed (since it causes problems in IE)
				if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
					jQuery.error( "type property can't be changed" );
				} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
					// Setting the type on a radio button after the value resets the value in IE6-9
					// Reset value to it's default in case type is set after value
					// This is for element creation
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		},
		// Use the value property for back compat
		// Use the nodeHook for button elements in IE6/7 (#1954)
		value: {
			get: function( elem, name ) {
				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
					return nodeHook.get( elem, name );
				}
				return name in elem ?
					elem.value :
					null;
			},
			set: function( elem, value, name ) {
				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
					return nodeHook.set( elem, value, name );
				}
				// Does not return so that setAttribute is also used
				elem.value = value;
			}
		}
	},

	propFix: {
		tabindex: "tabIndex",
		readonly: "readOnly",
		"for": "htmlFor",
		"class": "className",
		maxlength: "maxLength",
		cellspacing: "cellSpacing",
		cellpadding: "cellPadding",
		rowspan: "rowSpan",
		colspan: "colSpan",
		usemap: "useMap",
		frameborder: "frameBorder",
		contenteditable: "contentEditable"
	},

	prop: function( elem, name, value ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// don't get/set properties on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		if ( notxml ) {
			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				return ( elem[ name ] = value );
			}

		} else {
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
				return ret;

			} else {
				return elem[ name ];
			}
		}
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {
				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				var attributeNode = elem.getAttributeNode("tabindex");

				return attributeNode && attributeNode.specified ?
					parseInt( attributeNode.value, 10 ) :
					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
						0 :
						undefined;
			}
		}
	}
});

// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;

// Hook for boolean attributes
boolHook = {
	get: function( elem, name ) {
		// Align boolean attributes with corresponding properties
		// Fall back to attribute presence where some booleans are not supported
		var attrNode,
			property = jQuery.prop( elem, name );
		return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
			name.toLowerCase() :
			undefined;
	},
	set: function( elem, value, name ) {
		var propName;
		if ( value === false ) {
			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			// value is true since we know at this point it's type boolean and not false
			// Set boolean attributes to the same name and set the DOM property
			propName = jQuery.propFix[ name ] || name;
			if ( propName in elem ) {
				// Only set the IDL specifically if it already exists on the element
				elem[ propName ] = true;
			}

			elem.setAttribute( name, name.toLowerCase() );
		}
		return name;
	}
};

// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {

	fixSpecified = {
		name: true,
		id: true
	};

	// Use this for any attribute in IE6/7
	// This fixes almost every IE6/7 issue
	nodeHook = jQuery.valHooks.button = {
		get: function( elem, name ) {
			var ret;
			ret = elem.getAttributeNode( name );
			return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
				ret.nodeValue :
				undefined;
		},
		set: function( elem, value, name ) {
			// Set the existing or create a new attribute node
			var ret = elem.getAttributeNode( name );
			if ( !ret ) {
				ret = document.createAttribute( name );
				elem.setAttributeNode( ret );
			}
			return ( ret.nodeValue = value + "" );
		}
	};

	// Apply the nodeHook to tabindex
	jQuery.attrHooks.tabindex.set = nodeHook.set;

	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
	// This is for removals
	jQuery.each([ "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			set: function( elem, value ) {
				if ( value === "" ) {
					elem.setAttribute( name, "auto" );
					return value;
				}
			}
		});
	});

	// Set contenteditable to false on removals(#10429)
	// Setting to empty string throws an error as an invalid value
	jQuery.attrHooks.contenteditable = {
		get: nodeHook.get,
		set: function( elem, value, name ) {
			if ( value === "" ) {
				value = "false";
			}
			nodeHook.set( elem, value, name );
		}
	};
}


// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
	jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			get: function( elem ) {
				var ret = elem.getAttribute( name, 2 );
				return ret === null ? undefined : ret;
			}
		});
	});
}

if ( !jQuery.support.style ) {
	jQuery.attrHooks.style = {
		get: function( elem ) {
			// Return undefined in the case of empty string
			// Normalize to lowercase since IE uppercases css property names
			return elem.style.cssText.toLowerCase() || undefined;
		},
		set: function( elem, value ) {
			return ( elem.style.cssText = "" + value );
		}
	};
}

// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
	jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
		get: function( elem ) {
			var parent = elem.parentNode;

			if ( parent ) {
				parent.selectedIndex;

				// Make sure that it also works with optgroups, see #5701
				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
			return null;
		}
	});
}

// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
	jQuery.propFix.enctype = "encoding";
}

// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
	jQuery.each([ "radio", "checkbox" ], function() {
		jQuery.valHooks[ this ] = {
			get: function( elem ) {
				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
				return elem.getAttribute("value") === null ? "on" : elem.value;
			}
		};
	});
}
jQuery.each([ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
		set: function( elem, value ) {
			if ( jQuery.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
			}
		}
	});
});




var rformElems = /^(?:textarea|input|select)$/i,
	rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
	rhoverHack = /\bhover(\.\S+)?\b/,
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|contextmenu)|click/,
	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
	quickParse = function( selector ) {
		var quick = rquickIs.exec( selector );
		if ( quick ) {
			//   0  1    2   3
			// [ _, tag, id, class ]
			quick[1] = ( quick[1] || "" ).toLowerCase();
			quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
		}
		return quick;
	},
	quickIs = function( elem, m ) {
		var attrs = elem.attributes || {};
		return (
			(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
			(!m[2] || (attrs.id || {}).value === m[2]) &&
			(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
		);
	},
	hoverHack = function( events ) {
		return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
	};

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	add: function( elem, types, handler, data, selector ) {

		var elemData, eventHandle, events,
			t, tns, type, namespaces, handleObj,
			handleObjIn, quick, handlers, special;

		// Don't attach events to noData or text/comment nodes (allow plain objects tho)
		if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		events = elemData.events;
		if ( !events ) {
			elemData.events = events = {};
		}
		eventHandle = elemData.handle;
		if ( !eventHandle ) {
			elemData.handle = eventHandle = function( e ) {
				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
					undefined;
			};
			// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
			eventHandle.elem = elem;
		}

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		types = jQuery.trim( hoverHack(types) ).split( " " );
		for ( t = 0; t < types.length; t++ ) {

			tns = rtypenamespace.exec( types[t] ) || [];
			type = tns[1];
			namespaces = ( tns[2] || "" ).split( "." ).sort();

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend({
				type: type,
				origType: tns[1],
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				quick: quickParse( selector ),
				namespace: namespaces.join(".")
			}, handleObjIn );

			// Init the event handler queue if we're the first
			handlers = events[ type ];
			if ( !handlers ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener/attachEvent if the special events handler returns false
				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	global: {},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {

		var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
			t, tns, type, origType, namespaces, origCount,
			j, events, special, handle, eventType, handleObj;

		if ( !elemData || !(events = elemData.events) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
		for ( t = 0; t < types.length; t++ ) {
			tns = rtypenamespace.exec( types[t] ) || [];
			type = origType = tns[1];
			namespaces = tns[2];

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector? special.delegateType : special.bindType ) || type;
			eventType = events[ type ] || [];
			origCount = eventType.length;
			namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;

			// Remove matching events
			for ( j = 0; j < eventType.length; j++ ) {
				handleObj = eventType[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &&
					 ( !handler || handler.guid === handleObj.guid ) &&
					 ( !namespaces || namespaces.test( handleObj.namespace ) ) &&
					 ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
					eventType.splice( j--, 1 );

					if ( handleObj.selector ) {
						eventType.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( eventType.length === 0 && origCount !== eventType.length ) {
				if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			handle = elemData.handle;
			if ( handle ) {
				handle.elem = null;
			}

			// removeData also checks for emptiness and clears the expando if empty
			// so use it instead of delete
			jQuery.removeData( elem, [ "events", "handle" ], true );
		}
	},

	// Events that are safe to short-circuit if no handlers are attached.
	// Native DOM events should not be added, they may have inline handlers.
	customEvent: {
		"getData": true,
		"setData": true,
		"changeData": true
	},

	trigger: function( event, data, elem, onlyHandlers ) {
		// Don't do events on text and comment nodes
		if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
			return;
		}

		// Event object or event type
		var type = event.type || event,
			namespaces = [],
			cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "!" ) >= 0 ) {
			// Exclusive events trigger only for the exact event (no namespaces)
			type = type.slice(0, -1);
			exclusive = true;
		}

		if ( type.indexOf( "." ) >= 0 ) {
			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split(".");
			type = namespaces.shift();
			namespaces.sort();
		}

		if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
			// No jQuery handlers for this event type, and it can't have inline handlers
			return;
		}

		// Caller can pass in an Event, Object, or just an event type string
		event = typeof event === "object" ?
			// jQuery.Event object
			event[ jQuery.expando ] ? event :
			// Object literal
			new jQuery.Event( type, event ) :
			// Just the event type (string)
			new jQuery.Event( type );

		event.type = type;
		event.isTrigger = true;
		event.exclusive = exclusive;
		event.namespace = namespaces.join( "." );
		event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
		ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";

		// Handle a global trigger
		if ( !elem ) {

			// TODO: Stop taunting the data cache; remove global events and always attach to document
			cache = jQuery.cache;
			for ( i in cache ) {
				if ( cache[ i ].events && cache[ i ].events[ type ] ) {
					jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
				}
			}
			return;
		}

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data != null ? jQuery.makeArray( data ) : [];
		data.unshift( event );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		eventPath = [[ elem, special.bindType || type ]];
		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
			old = null;
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push([ cur, bubbleType ]);
				old = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( old && old === elem.ownerDocument ) {
				eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
			}
		}

		// Fire handlers on the event path
		for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {

			cur = eventPath[i][0];
			event.type = eventPath[i][1];

			handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}
			// Note that this is a bare JS function and not a jQuery handler
			handle = ontype && cur[ ontype ];
			if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
				event.preventDefault();
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
				!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name name as the event.
				// Can't use an .isFunction() check here because IE6/7 fails that test.
				// Don't do default actions on window, that's where global variables be (#6170)
				// IE<9 dies on focus/blur to hidden element (#1486)
				if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					old = elem[ ontype ];

					if ( old ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;
					elem[ type ]();
					jQuery.event.triggered = undefined;

					if ( old ) {
						elem[ ontype ] = old;
					}
				}
			}
		}

		return event.result;
	},

	dispatch: function( event ) {

		// Make a writable jQuery.Event from the native event object
		event = jQuery.event.fix( event || window.event );

		var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
			delegateCount = handlers.delegateCount,
			args = [].slice.call( arguments, 0 ),
			run_all = !event.exclusive && !event.namespace,
			handlerQueue = [],
			i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[0] = event;
		event.delegateTarget = this;

		// Determine handlers that should run if there are delegated events
		// Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
		if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) {

			// Pregenerate a single jQuery object for reuse with .is()
			jqcur = jQuery(this);
			jqcur.context = this.ownerDocument || this;

			for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
				selMatch = {};
				matches = [];
				jqcur[0] = cur;
				for ( i = 0; i < delegateCount; i++ ) {
					handleObj = handlers[ i ];
					sel = handleObj.selector;

					if ( selMatch[ sel ] === undefined ) {
						selMatch[ sel ] = (
							handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
						);
					}
					if ( selMatch[ sel ] ) {
						matches.push( handleObj );
					}
				}
				if ( matches.length ) {
					handlerQueue.push({ elem: cur, matches: matches });
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		if ( handlers.length > delegateCount ) {
			handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
		}

		// Run delegates first; they may want to stop propagation beneath us
		for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
			matched = handlerQueue[ i ];
			event.currentTarget = matched.elem;

			for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
				handleObj = matched.matches[ j ];

				// Triggered event must either 1) be non-exclusive and have no namespace, or
				// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
				if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {

					event.data = handleObj.data;
					event.handleObj = handleObj;

					ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
							.apply( matched.elem, args );

					if ( ret !== undefined ) {
						event.result = ret;
						if ( ret === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		return event.result;
	},

	// Includes some event props shared by KeyEvent and MouseEvent
	// *** attrChange attrName relatedNode srcElement  are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
	props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),

	fixHooks: {},

	keyHooks: {
		props: "char charCode key keyCode".split(" "),
		filter: function( event, original ) {

			// Add which for key events
			if ( event.which == null ) {
				event.which = original.charCode != null ? original.charCode : original.keyCode;
			}

			return event;
		}
	},

	mouseHooks: {
		props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
		filter: function( event, original ) {
			var eventDoc, doc, body,
				button = original.button,
				fromElement = original.fromElement;

			// Calculate pageX/Y if missing and clientX/Y available
			if ( event.pageX == null && original.clientX != null ) {
				eventDoc = event.target.ownerDocument || document;
				doc = eventDoc.documentElement;
				body = eventDoc.body;

				event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
				event.pageY = original.clientY + ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) - ( doc && doc.clientTop  || body && body.clientTop  || 0 );
			}

			// Add relatedTarget, if necessary
			if ( !event.relatedTarget && fromElement ) {
				event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
			}

			// Add which for click: 1 === left; 2 === middle; 3 === right
			// Note: button is not normalized, so don't use it
			if ( !event.which && button !== undefined ) {
				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
			}

			return event;
		}
	},

	fix: function( event ) {
		if ( event[ jQuery.expando ] ) {
			return event;
		}

		// Create a writable copy of the event object and normalize some properties
		var i, prop,
			originalEvent = event,
			fixHook = jQuery.event.fixHooks[ event.type ] || {},
			copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;

		event = jQuery.Event( originalEvent );

		for ( i = copy.length; i; ) {
			prop = copy[ --i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
		if ( !event.target ) {
			event.target = originalEvent.srcElement || document;
		}

		// Target should not be a text node (#504, Safari)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}

		// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
		if ( event.metaKey === undefined ) {
			event.metaKey = event.ctrlKey;
		}

		return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
	},

	special: {
		ready: {
			// Make sure the ready event is setup
			setup: jQuery.bindReady
		},

		load: {
			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},

		focus: {
			delegateType: "focusin"
		},
		blur: {
			delegateType: "focusout"
		},

		beforeunload: {
			setup: function( data, namespaces, eventHandle ) {
				// We only want to do this special case on windows
				if ( jQuery.isWindow( this ) ) {
					this.onbeforeunload = eventHandle;
				}
			},

			teardown: function( namespaces, eventHandle ) {
				if ( this.onbeforeunload === eventHandle ) {
					this.onbeforeunload = null;
				}
			}
		}
	},

	simulate: function( type, elem, event, bubble ) {
		// Piggyback on a donor event to simulate a different one.
		// Fake originalEvent to avoid donor's stopPropagation, but if the
		// simulated event prevents default then we do the same on the donor.
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{ type: type,
				isSimulated: true,
				originalEvent: {}
			}
		);
		if ( bubble ) {
			jQuery.event.trigger( e, null, elem );
		} else {
			jQuery.event.dispatch.call( elem, e );
		}
		if ( e.isDefaultPrevented() ) {
			event.preventDefault();
		}
	}
};

// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;

jQuery.removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle, false );
		}
	} :
	function( elem, type, handle ) {
		if ( elem.detachEvent ) {
			elem.detachEvent( "on" + type, handle );
		}
	};

jQuery.Event = function( src, props ) {
	// Allow instantiation without the 'new' keyword
	if ( !(this instanceof jQuery.Event) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
			src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || jQuery.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

function returnFalse() {
	return false;
}
function returnTrue() {
	return true;
}

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	preventDefault: function() {
		this.isDefaultPrevented = returnTrue;

		var e = this.originalEvent;
		if ( !e ) {
			return;
		}

		// if preventDefault exists run it on the original event
		if ( e.preventDefault ) {
			e.preventDefault();

		// otherwise set the returnValue property of the original event to false (IE)
		} else {
			e.returnValue = false;
		}
	},
	stopPropagation: function() {
		this.isPropagationStopped = returnTrue;

		var e = this.originalEvent;
		if ( !e ) {
			return;
		}
		// if stopPropagation exists run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}
		// otherwise set the cancelBubble property of the original event to true (IE)
		e.cancelBubble = true;
	},
	stopImmediatePropagation: function() {
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};

// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
	mouseenter: "mouseover",
	mouseleave: "mouseout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj,
				selector = handleObj.selector,
				ret;

			// For mousenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
});

// IE submit delegation
if ( !jQuery.support.submitBubbles ) {

	jQuery.event.special.submit = {
		setup: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Lazy-add a submit handler when a descendant form may potentially be submitted
			jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
				// Node name check avoids a VML-related crash in IE (#9807)
				var elem = e.target,
					form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
				if ( form && !form._submit_attached ) {
					jQuery.event.add( form, "submit._submit", function( event ) {
						// If form was submitted by the user, bubble the event up the tree
						if ( this.parentNode && !event.isTrigger ) {
							jQuery.event.simulate( "submit", this.parentNode, event, true );
						}
					});
					form._submit_attached = true;
				}
			});
			// return undefined since we don't need an event listener
		},

		teardown: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
			jQuery.event.remove( this, "._submit" );
		}
	};
}

// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {

	jQuery.event.special.change = {

		setup: function() {

			if ( rformElems.test( this.nodeName ) ) {
				// IE doesn't fire change on a check/radio until blur; trigger it on click
				// after a propertychange. Eat the blur-change in special.change.handle.
				// This still fires onchange a second time for check/radio after blur.
				if ( this.type === "checkbox" || this.type === "radio" ) {
					jQuery.event.add( this, "propertychange._change", function( event ) {
						if ( event.originalEvent.propertyName === "checked" ) {
							this._just_changed = true;
						}
					});
					jQuery.event.add( this, "click._change", function( event ) {
						if ( this._just_changed && !event.isTrigger ) {
							this._just_changed = false;
							jQuery.event.simulate( "change", this, event, true );
						}
					});
				}
				return false;
			}
			// Delegated event; lazy-add a change handler on descendant inputs
			jQuery.event.add( this, "beforeactivate._change", function( e ) {
				var elem = e.target;

				if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
					jQuery.event.add( elem, "change._change", function( event ) {
						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
							jQuery.event.simulate( "change", this.parentNode, event, true );
						}
					});
					elem._change_attached = true;
				}
			});
		},

		handle: function( event ) {
			var elem = event.target;

			// Swallow native change events from checkbox/radio, we already triggered them above
			if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
				return event.handleObj.handler.apply( this, arguments );
			}
		},

		teardown: function() {
			jQuery.event.remove( this, "._change" );

			return rformElems.test( this.nodeName );
		}
	};
}

// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler while someone wants focusin/focusout
		var attaches = 0,
			handler = function( event ) {
				jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
			};

		jQuery.event.special[ fix ] = {
			setup: function() {
				if ( attaches++ === 0 ) {
					document.addEventListener( orig, handler, true );
				}
			},
			teardown: function() {
				if ( --attaches === 0 ) {
					document.removeEventListener( orig, handler, true );
				}
			}
		};
	});
}

jQuery.fn.extend({

	on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
		var origFn, type;

		// Types can be a map of types/handlers
		if ( typeof types === "object" ) {
			// ( types-Object, selector, data )
			if ( typeof selector !== "string" ) {
				// ( types-Object, data )
				data = selector;
				selector = undefined;
			}
			for ( type in types ) {
				this.on( type, selector, data, types[ type ], one );
			}
			return this;
		}

		if ( data == null && fn == null ) {
			// ( types, fn )
			fn = selector;
			data = selector = undefined;
		} else if ( fn == null ) {
			if ( typeof selector === "string" ) {
				// ( types, selector, fn )
				fn = data;
				data = undefined;
			} else {
				// ( types, data, fn )
				fn = data;
				data = selector;
				selector = undefined;
			}
		}
		if ( fn === false ) {
			fn = returnFalse;
		} else if ( !fn ) {
			return this;
		}

		if ( one === 1 ) {
			origFn = fn;
			fn = function( event ) {
				// Can use an empty set, since event contains the info
				jQuery().off( event );
				return origFn.apply( this, arguments );
			};
			// Use same guid so caller can remove using origFn
			fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
		}
		return this.each( function() {
			jQuery.event.add( this, types, fn, data, selector );
		});
	},
	one: function( types, selector, data, fn ) {
		return this.on.call( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		if ( types && types.preventDefault && types.handleObj ) {
			// ( event )  dispatched jQuery.Event
			var handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {
			// ( types-object [, selector] )
			for ( var type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {
			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each(function() {
			jQuery.event.remove( this, types, fn, selector );
		});
	},

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	live: function( types, data, fn ) {
		jQuery( this.context ).on( types, this.selector, data, fn );
		return this;
	},
	die: function( types, fn ) {
		jQuery( this.context ).off( types, this.selector || "**", fn );
		return this;
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {
		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
	},

	trigger: function( type, data ) {
		return this.each(function() {
			jQuery.event.trigger( type, data, this );
		});
	},
	triggerHandler: function( type, data ) {
		if ( this[0] ) {
			return jQuery.event.trigger( type, data, this[0], true );
		}
	},

	toggle: function( fn ) {
		// Save reference to arguments for access in closure
		var args = arguments,
			guid = fn.guid || jQuery.guid++,
			i = 0,
			toggler = function( event ) {
				// Figure out which function to execute
				var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
				jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );

				// Make sure that clicks stop
				event.preventDefault();

				// and execute the function
				return args[ lastToggle ].apply( this, arguments ) || false;
			};

		// link all the functions, so any of them can unbind this click handler
		toggler.guid = guid;
		while ( i < args.length ) {
			args[ i++ ].guid = guid;
		}

		return this.click( toggler );
	},

	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
});

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		if ( fn == null ) {
			fn = data;
			data = null;
		}

		return arguments.length > 0 ?
			this.on( name, null, data, fn ) :
			this.trigger( name );
	};

	if ( jQuery.attrFn ) {
		jQuery.attrFn[ name ] = true;
	}

	if ( rkeyEvent.test( name ) ) {
		jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
	}

	if ( rmouseEvent.test( name ) ) {
		jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
	}
});



/*!
 * Sizzle CSS Selector Engine
 *  Copyright 2011, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){

var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
	expando = "sizcache" + (Math.random() + '').replace('.', ''),
	done = 0,
	toString = Object.prototype.toString,
	hasDuplicate = false,
	baseHasDuplicate = true,
	rBackslash = /\\/g,
	rReturn = /\r\n/g,
	rNonWord = /\W/;

// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
//   Thus far that includes Google Chrome.
[0, 0].sort(function() {
	baseHasDuplicate = false;
	return 0;
});

var Sizzle = function( selector, context, results, seed ) {
	results = results || [];
	context = context || document;

	var origContext = context;

	if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
		return [];
	}
	
	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	var m, set, checkSet, extra, ret, cur, pop, i,
		prune = true,
		contextXML = Sizzle.isXML( context ),
		parts = [],
		soFar = selector;
	
	// Reset the position of the chunker regexp (start from head)
	do {
		chunker.exec( "" );
		m = chunker.exec( soFar );

		if ( m ) {
			soFar = m[3];
		
			parts.push( m[1] );
		
			if ( m[2] ) {
				extra = m[3];
				break;
			}
		}
	} while ( m );

	if ( parts.length > 1 && origPOS.exec( selector ) ) {

		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
			set = posProcess( parts[0] + parts[1], context, seed );

		} else {
			set = Expr.relative[ parts[0] ] ?
				[ context ] :
				Sizzle( parts.shift(), context );

			while ( parts.length ) {
				selector = parts.shift();

				if ( Expr.relative[ selector ] ) {
					selector += parts.shift();
				}
				
				set = posProcess( selector, set, seed );
			}
		}

	} else {
		// Take a shortcut and set the context if the root selector is an ID
		// (but not if it'll be faster if the inner selector is an ID)
		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {

			ret = Sizzle.find( parts.shift(), context, contextXML );
			context = ret.expr ?
				Sizzle.filter( ret.expr, ret.set )[0] :
				ret.set[0];
		}

		if ( context ) {
			ret = seed ?
				{ expr: parts.pop(), set: makeArray(seed) } :
				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );

			set = ret.expr ?
				Sizzle.filter( ret.expr, ret.set ) :
				ret.set;

			if ( parts.length > 0 ) {
				checkSet = makeArray( set );

			} else {
				prune = false;
			}

			while ( parts.length ) {
				cur = parts.pop();
				pop = cur;

				if ( !Expr.relative[ cur ] ) {
					cur = "";
				} else {
					pop = parts.pop();
				}

				if ( pop == null ) {
					pop = context;
				}

				Expr.relative[ cur ]( checkSet, pop, contextXML );
			}

		} else {
			checkSet = parts = [];
		}
	}

	if ( !checkSet ) {
		checkSet = set;
	}

	if ( !checkSet ) {
		Sizzle.error( cur || selector );
	}

	if ( toString.call(checkSet) === "[object Array]" ) {
		if ( !prune ) {
			results.push.apply( results, checkSet );

		} else if ( context && context.nodeType === 1 ) {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
					results.push( set[i] );
				}
			}

		} else {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
					results.push( set[i] );
				}
			}
		}

	} else {
		makeArray( checkSet, results );
	}

	if ( extra ) {
		Sizzle( extra, origContext, results, seed );
		Sizzle.uniqueSort( results );
	}

	return results;
};

Sizzle.uniqueSort = function( results ) {
	if ( sortOrder ) {
		hasDuplicate = baseHasDuplicate;
		results.sort( sortOrder );

		if ( hasDuplicate ) {
			for ( var i = 1; i < results.length; i++ ) {
				if ( results[i] === results[ i - 1 ] ) {
					results.splice( i--, 1 );
				}
			}
		}
	}

	return results;
};

Sizzle.matches = function( expr, set ) {
	return Sizzle( expr, null, null, set );
};

Sizzle.matchesSelector = function( node, expr ) {
	return Sizzle( expr, null, null, [node] ).length > 0;
};

Sizzle.find = function( expr, context, isXML ) {
	var set, i, len, match, type, left;

	if ( !expr ) {
		return [];
	}

	for ( i = 0, len = Expr.order.length; i < len; i++ ) {
		type = Expr.order[i];
		
		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
			left = match[1];
			match.splice( 1, 1 );

			if ( left.substr( left.length - 1 ) !== "\\" ) {
				match[1] = (match[1] || "").replace( rBackslash, "" );
				set = Expr.find[ type ]( match, context, isXML );

				if ( set != null ) {
					expr = expr.replace( Expr.match[ type ], "" );
					break;
				}
			}
		}
	}

	if ( !set ) {
		set = typeof context.getElementsByTagName !== "undefined" ?
			context.getElementsByTagName( "*" ) :
			[];
	}

	return { set: set, expr: expr };
};

Sizzle.filter = function( expr, set, inplace, not ) {
	var match, anyFound,
		type, found, item, filter, left,
		i, pass,
		old = expr,
		result = [],
		curLoop = set,
		isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );

	while ( expr && set.length ) {
		for ( type in Expr.filter ) {
			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
				filter = Expr.filter[ type ];
				left = match[1];

				anyFound = false;

				match.splice(1,1);

				if ( left.substr( left.length - 1 ) === "\\" ) {
					continue;
				}

				if ( curLoop === result ) {
					result = [];
				}

				if ( Expr.preFilter[ type ] ) {
					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );

					if ( !match ) {
						anyFound = found = true;

					} else if ( match === true ) {
						continue;
					}
				}

				if ( match ) {
					for ( i = 0; (item = curLoop[i]) != null; i++ ) {
						if ( item ) {
							found = filter( item, match, i, curLoop );
							pass = not ^ found;

							if ( inplace && found != null ) {
								if ( pass ) {
									anyFound = true;

								} else {
									curLoop[i] = false;
								}

							} else if ( pass ) {
								result.push( item );
								anyFound = true;
							}
						}
					}
				}

				if ( found !== undefined ) {
					if ( !inplace ) {
						curLoop = result;
					}

					expr = expr.replace( Expr.match[ type ], "" );

					if ( !anyFound ) {
						return [];
					}

					break;
				}
			}
		}

		// Improper expression
		if ( expr === old ) {
			if ( anyFound == null ) {
				Sizzle.error( expr );

			} else {
				break;
			}
		}

		old = expr;
	}

	return curLoop;
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

/**
 * Utility function for retreiving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
var getText = Sizzle.getText = function( elem ) {
    var i, node,
		nodeType = elem.nodeType,
		ret = "";

	if ( nodeType ) {
		if ( nodeType === 1 || nodeType === 9 ) {
			// Use textContent || innerText for elements
			if ( typeof elem.textContent === 'string' ) {
				return elem.textContent;
			} else if ( typeof elem.innerText === 'string' ) {
				// Replace IE's carriage returns
				return elem.innerText.replace( rReturn, '' );
			} else {
				// Traverse it's children
				for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
					ret += getText( elem );
				}
			}
		} else if ( nodeType === 3 || nodeType === 4 ) {
			return elem.nodeValue;
		}
	} else {

		// If no nodeType, this is expected to be an array
		for ( i = 0; (node = elem[i]); i++ ) {
			// Do not traverse comment nodes
			if ( node.nodeType !== 8 ) {
				ret += getText( node );
			}
		}
	}
	return ret;
};

var Expr = Sizzle.selectors = {
	order: [ "ID", "NAME", "TAG" ],

	match: {
		ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
		TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
		CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
		PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
	},

	leftMatch: {},

	attrMap: {
		"class": "className",
		"for": "htmlFor"
	},

	attrHandle: {
		href: function( elem ) {
			return elem.getAttribute( "href" );
		},
		type: function( elem ) {
			return elem.getAttribute( "type" );
		}
	},

	relative: {
		"+": function(checkSet, part){
			var isPartStr = typeof part === "string",
				isTag = isPartStr && !rNonWord.test( part ),
				isPartStrNotTag = isPartStr && !isTag;

			if ( isTag ) {
				part = part.toLowerCase();
			}

			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
				if ( (elem = checkSet[i]) ) {
					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}

					checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
						elem || false :
						elem === part;
				}
			}

			if ( isPartStrNotTag ) {
				Sizzle.filter( part, checkSet, true );
			}
		},

		">": function( checkSet, part ) {
			var elem,
				isPartStr = typeof part === "string",
				i = 0,
				l = checkSet.length;

			if ( isPartStr && !rNonWord.test( part ) ) {
				part = part.toLowerCase();

				for ( ; i < l; i++ ) {
					elem = checkSet[i];

					if ( elem ) {
						var parent = elem.parentNode;
						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
					}
				}

			} else {
				for ( ; i < l; i++ ) {
					elem = checkSet[i];

					if ( elem ) {
						checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}

				if ( isPartStr ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},

		"": function(checkSet, part, isXML){
			var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;

			if ( typeof part === "string" && !rNonWord.test( part ) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}

			checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
		},

		"~": function( checkSet, part, isXML ) {
			var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;

			if ( typeof part === "string" && !rNonWord.test( part ) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}

			checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
		}
	},

	find: {
		ID: function( match, context, isXML ) {
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				return m && m.parentNode ? [m] : [];
			}
		},

		NAME: function( match, context ) {
			if ( typeof context.getElementsByName !== "undefined" ) {
				var ret = [],
					results = context.getElementsByName( match[1] );

				for ( var i = 0, l = results.length; i < l; i++ ) {
					if ( results[i].getAttribute("name") === match[1] ) {
						ret.push( results[i] );
					}
				}

				return ret.length === 0 ? null : ret;
			}
		},

		TAG: function( match, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( match[1] );
			}
		}
	},
	preFilter: {
		CLASS: function( match, curLoop, inplace, result, not, isXML ) {
			match = " " + match[1].replace( rBackslash, "" ) + " ";

			if ( isXML ) {
				return match;
			}

			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
				if ( elem ) {
					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
						if ( !inplace ) {
							result.push( elem );
						}

					} else if ( inplace ) {
						curLoop[i] = false;
					}
				}
			}

			return false;
		},

		ID: function( match ) {
			return match[1].replace( rBackslash, "" );
		},

		TAG: function( match, curLoop ) {
			return match[1].replace( rBackslash, "" ).toLowerCase();
		},

		CHILD: function( match ) {
			if ( match[1] === "nth" ) {
				if ( !match[2] ) {
					Sizzle.error( match[0] );
				}

				match[2] = match[2].replace(/^\+|\s*/g, '');

				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
				var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

				// calculate the numbers (first)n+(last) including if they are negative
				match[2] = (test[1] + (test[2] || 1)) - 0;
				match[3] = test[3] - 0;
			}
			else if ( match[2] ) {
				Sizzle.error( match[0] );
			}

			// TODO: Move to normal caching system
			match[0] = done++;

			return match;
		},

		ATTR: function( match, curLoop, inplace, result, not, isXML ) {
			var name = match[1] = match[1].replace( rBackslash, "" );
			
			if ( !isXML && Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}

			// Handle if an un-quoted value was used
			match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );

			if ( match[2] === "~=" ) {
				match[4] = " " + match[4] + " ";
			}

			return match;
		},

		PSEUDO: function( match, curLoop, inplace, result, not ) {
			if ( match[1] === "not" ) {
				// If we're dealing with a complex expression, or a simple one
				if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
					match[3] = Sizzle(match[3], null, null, curLoop);

				} else {
					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);

					if ( !inplace ) {
						result.push.apply( result, ret );
					}

					return false;
				}

			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
				return true;
			}
			
			return match;
		},

		POS: function( match ) {
			match.unshift( true );

			return match;
		}
	},
	
	filters: {
		enabled: function( elem ) {
			return elem.disabled === false && elem.type !== "hidden";
		},

		disabled: function( elem ) {
			return elem.disabled === true;
		},

		checked: function( elem ) {
			return elem.checked === true;
		},
		
		selected: function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}
			
			return elem.selected === true;
		},

		parent: function( elem ) {
			return !!elem.firstChild;
		},

		empty: function( elem ) {
			return !elem.firstChild;
		},

		has: function( elem, i, match ) {
			return !!Sizzle( match[3], elem ).length;
		},

		header: function( elem ) {
			return (/h\d/i).test( elem.nodeName );
		},

		text: function( elem ) {
			var attr = elem.getAttribute( "type" ), type = elem.type;
			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) 
			// use getAttribute instead to test this case
			return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
		},

		radio: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
		},

		checkbox: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
		},

		file: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
		},

		password: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
		},

		submit: function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return (name === "input" || name === "button") && "submit" === elem.type;
		},

		image: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
		},

		reset: function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return (name === "input" || name === "button") && "reset" === elem.type;
		},

		button: function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && "button" === elem.type || name === "button";
		},

		input: function( elem ) {
			return (/input|select|textarea|button/i).test( elem.nodeName );
		},

		focus: function( elem ) {
			return elem === elem.ownerDocument.activeElement;
		}
	},
	setFilters: {
		first: function( elem, i ) {
			return i === 0;
		},

		last: function( elem, i, match, array ) {
			return i === array.length - 1;
		},

		even: function( elem, i ) {
			return i % 2 === 0;
		},

		odd: function( elem, i ) {
			return i % 2 === 1;
		},

		lt: function( elem, i, match ) {
			return i < match[3] - 0;
		},

		gt: function( elem, i, match ) {
			return i > match[3] - 0;
		},

		nth: function( elem, i, match ) {
			return match[3] - 0 === i;
		},

		eq: function( elem, i, match ) {
			return match[3] - 0 === i;
		}
	},
	filter: {
		PSEUDO: function( elem, match, i, array ) {
			var name = match[1],
				filter = Expr.filters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );

			} else if ( name === "contains" ) {
				return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;

			} else if ( name === "not" ) {
				var not = match[3];

				for ( var j = 0, l = not.length; j < l; j++ ) {
					if ( not[j] === elem ) {
						return false;
					}
				}

				return true;

			} else {
				Sizzle.error( name );
			}
		},

		CHILD: function( elem, match ) {
			var first, last,
				doneName, parent, cache,
				count, diff,
				type = match[1],
				node = elem;

			switch ( type ) {
				case "only":
				case "first":
					while ( (node = node.previousSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}

					if ( type === "first" ) { 
						return true; 
					}

					node = elem;

				case "last":
					while ( (node = node.nextSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}

					return true;

				case "nth":
					first = match[2];
					last = match[3];

					if ( first === 1 && last === 0 ) {
						return true;
					}
					
					doneName = match[0];
					parent = elem.parentNode;
	
					if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
						count = 0;
						
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								node.nodeIndex = ++count;
							}
						} 

						parent[ expando ] = doneName;
					}
					
					diff = elem.nodeIndex - last;

					if ( first === 0 ) {
						return diff === 0;

					} else {
						return ( diff % first === 0 && diff / first >= 0 );
					}
			}
		},

		ID: function( elem, match ) {
			return elem.nodeType === 1 && elem.getAttribute("id") === match;
		},

		TAG: function( elem, match ) {
			return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
		},
		
		CLASS: function( elem, match ) {
			return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf( match ) > -1;
		},

		ATTR: function( elem, match ) {
			var name = match[1],
				result = Sizzle.attr ?
					Sizzle.attr( elem, name ) :
					Expr.attrHandle[ name ] ?
					Expr.attrHandle[ name ]( elem ) :
					elem[ name ] != null ?
						elem[ name ] :
						elem.getAttribute( name ),
				value = result + "",
				type = match[2],
				check = match[4];

			return result == null ?
				type === "!=" :
				!type && Sizzle.attr ?
				result != null :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value !== check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},

		POS: function( elem, match, i, array ) {
			var name = match[2],
				filter = Expr.setFilters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			}
		}
	}
};

var origPOS = Expr.match.POS,
	fescape = function(all, num){
		return "\\" + (num - 0 + 1);
	};

for ( var type in Expr.match ) {
	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}

var makeArray = function( array, results ) {
	array = Array.prototype.slice.call( array, 0 );

	if ( results ) {
		results.push.apply( results, array );
		return results;
	}
	
	return array;
};

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

// Provide a fallback method if it does not work
} catch( e ) {
	makeArray = function( array, results ) {
		var i = 0,
			ret = results || [];

		if ( toString.call(array) === "[object Array]" ) {
			Array.prototype.push.apply( ret, array );

		} else {
			if ( typeof array.length === "number" ) {
				for ( var l = array.length; i < l; i++ ) {
					ret.push( array[i] );
				}

			} else {
				for ( ; array[i]; i++ ) {
					ret.push( array[i] );
				}
			}
		}

		return ret;
	};
}

var sortOrder, siblingCheck;

if ( document.documentElement.compareDocumentPosition ) {
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
			return a.compareDocumentPosition ? -1 : 1;
		}

		return a.compareDocumentPosition(b) & 4 ? -1 : 1;
	};

} else {
	sortOrder = function( a, b ) {
		// The nodes are identical, we can exit early
		if ( a === b ) {
			hasDuplicate = true;
			return 0;

		// Fallback to using sourceIndex (in IE) if it's available on both nodes
		} else if ( a.sourceIndex && b.sourceIndex ) {
			return a.sourceIndex - b.sourceIndex;
		}

		var al, bl,
			ap = [],
			bp = [],
			aup = a.parentNode,
			bup = b.parentNode,
			cur = aup;

		// If the nodes are siblings (or identical) we can do a quick check
		if ( aup === bup ) {
			return siblingCheck( a, b );

		// If no parents were found then the nodes are disconnected
		} else if ( !aup ) {
			return -1;

		} else if ( !bup ) {
			return 1;
		}

		// Otherwise they're somewhere else in the tree so we need
		// to build up a full list of the parentNodes for comparison
		while ( cur ) {
			ap.unshift( cur );
			cur = cur.parentNode;
		}

		cur = bup;

		while ( cur ) {
			bp.unshift( cur );
			cur = cur.parentNode;
		}

		al = ap.length;
		bl = bp.length;

		// Start walking down the tree looking for a discrepancy
		for ( var i = 0; i < al && i < bl; i++ ) {
			if ( ap[i] !== bp[i] ) {
				return siblingCheck( ap[i], bp[i] );
			}
		}

		// We ended someplace up the tree so do a sibling check
		return i === al ?
			siblingCheck( a, bp[i], -1 ) :
			siblingCheck( ap[i], b, 1 );
	};

	siblingCheck = function( a, b, ret ) {
		if ( a === b ) {
			return ret;
		}

		var cur = a.nextSibling;

		while ( cur ) {
			if ( cur === b ) {
				return -1;
			}

			cur = cur.nextSibling;
		}

		return 1;
	};
}

// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
	// We're going to inject a fake input element with a specified name
	var form = document.createElement("div"),
		id = "script" + (new Date()).getTime(),
		root = document.documentElement;

	form.innerHTML = "<a name='" + id + "'/>";

	// Inject it into the root element, check its status, and remove it quickly
	root.insertBefore( form, root.firstChild );

	// The workaround has to do additional checks after a getElementById
	// Which slows things down for other browsers (hence the branching)
	if ( document.getElementById( id ) ) {
		Expr.find.ID = function( match, context, isXML ) {
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);

				return m ?
					m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
						[m] :
						undefined :
					[];
			}
		};

		Expr.filter.ID = function( elem, match ) {
			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");

			return elem.nodeType === 1 && node && node.nodeValue === match;
		};
	}

	root.removeChild( form );

	// release memory in IE
	root = form = null;
})();

(function(){
	// Check to see if the browser returns only elements
	// when doing getElementsByTagName("*")

	// Create a fake element
	var div = document.createElement("div");
	div.appendChild( document.createComment("") );

	// Make sure no comments are found
	if ( div.getElementsByTagName("*").length > 0 ) {
		Expr.find.TAG = function( match, context ) {
			var results = context.getElementsByTagName( match[1] );

			// Filter out possible comments
			if ( match[1] === "*" ) {
				var tmp = [];

				for ( var i = 0; results[i]; i++ ) {
					if ( results[i].nodeType === 1 ) {
						tmp.push( results[i] );
					}
				}

				results = tmp;
			}

			return results;
		};
	}

	// Check to see if an attribute returns normalized href attributes
	div.innerHTML = "<a href='#'></a>";

	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
			div.firstChild.getAttribute("href") !== "#" ) {

		Expr.attrHandle.href = function( elem ) {
			return elem.getAttribute( "href", 2 );
		};
	}

	// release memory in IE
	div = null;
})();

if ( document.querySelectorAll ) {
	(function(){
		var oldSizzle = Sizzle,
			div = document.createElement("div"),
			id = "__sizzle__";

		div.innerHTML = "<p class='TEST'></p>";

		// Safari can't handle uppercase or unicode characters when
		// in quirks mode.
		if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
			return;
		}
	
		Sizzle = function( query, context, extra, seed ) {
			context = context || document;

			// Only use querySelectorAll on non-XML documents
			// (ID selectors don't work in non-HTML documents)
			if ( !seed && !Sizzle.isXML(context) ) {
				// See if we find a selector to speed up
				var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
				
				if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
					// Speed-up: Sizzle("TAG")
					if ( match[1] ) {
						return makeArray( context.getElementsByTagName( query ), extra );
					
					// Speed-up: Sizzle(".CLASS")
					} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
						return makeArray( context.getElementsByClassName( match[2] ), extra );
					}
				}
				
				if ( context.nodeType === 9 ) {
					// Speed-up: Sizzle("body")
					// The body element only exists once, optimize finding it
					if ( query === "body" && context.body ) {
						return makeArray( [ context.body ], extra );
						
					// Speed-up: Sizzle("#ID")
					} else if ( match && match[3] ) {
						var elem = context.getElementById( match[3] );

						// Check parentNode to catch when Blackberry 4.6 returns
						// nodes that are no longer in the document #6963
						if ( elem && elem.parentNode ) {
							// Handle the case where IE and Opera return items
							// by name instead of ID
							if ( elem.id === match[3] ) {
								return makeArray( [ elem ], extra );
							}
							
						} else {
							return makeArray( [], extra );
						}
					}
					
					try {
						return makeArray( context.querySelectorAll(query), extra );
					} catch(qsaError) {}

				// qSA works strangely on Element-rooted queries
				// We can work around this by specifying an extra ID on the root
				// and working up from there (Thanks to Andrew Dupont for the technique)
				// IE 8 doesn't work on object elements
				} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
					var oldContext = context,
						old = context.getAttribute( "id" ),
						nid = old || id,
						hasParent = context.parentNode,
						relativeHierarchySelector = /^\s*[+~]/.test( query );

					if ( !old ) {
						context.setAttribute( "id", nid );
					} else {
						nid = nid.replace( /'/g, "\\$&" );
					}
					if ( relativeHierarchySelector && hasParent ) {
						context = context.parentNode;
					}

					try {
						if ( !relativeHierarchySelector || hasParent ) {
							return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
						}

					} catch(pseudoError) {
					} finally {
						if ( !old ) {
							oldContext.removeAttribute( "id" );
						}
					}
				}
			}
		
			return oldSizzle(query, context, extra, seed);
		};

		for ( var prop in oldSizzle ) {
			Sizzle[ prop ] = oldSizzle[ prop ];
		}

		// release memory in IE
		div = null;
	})();
}

(function(){
	var html = document.documentElement,
		matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;

	if ( matches ) {
		// Check to see if it's possible to do matchesSelector
		// on a disconnected node (IE 9 fails this)
		var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
			pseudoWorks = false;

		try {
			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( document.documentElement, "[test!='']:sizzle" );
	
		} catch( pseudoError ) {
			pseudoWorks = true;
		}

		Sizzle.matchesSelector = function( node, expr ) {
			// Make sure that attribute selectors are quoted
			expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");

			if ( !Sizzle.isXML( node ) ) {
				try { 
					if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
						var ret = matches.call( node, expr );

						// IE 9's matchesSelector returns false on disconnected nodes
						if ( ret || !disconnectedMatch ||
								// As well, disconnected nodes are said to be in a document
								// fragment in IE 9, so check for that
								node.document && node.document.nodeType !== 11 ) {
							return ret;
						}
					}
				} catch(e) {}
			}

			return Sizzle(expr, null, null, [node]).length > 0;
		};
	}
})();

(function(){
	var div = document.createElement("div");

	div.innerHTML = "<div class='test e'></div><div class='test'></div>";

	// Opera can't find a second classname (in 9.6)
	// Also, make sure that getElementsByClassName actually exists
	if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
		return;
	}

	// Safari caches class attributes, doesn't catch changes (in 3.2)
	div.lastChild.className = "e";

	if ( div.getElementsByClassName("e").length === 1 ) {
		return;
	}
	
	Expr.order.splice(1, 0, "CLASS");
	Expr.find.CLASS = function( match, context, isXML ) {
		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
			return context.getElementsByClassName(match[1]);
		}
	};

	// release memory in IE
	div = null;
})();

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];

		if ( elem ) {
			var match = false;

			elem = elem[dir];

			while ( elem ) {
				if ( elem[ expando ] === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 && !isXML ){
					elem[ expando ] = doneName;
					elem.sizset = i;
				}

				if ( elem.nodeName.toLowerCase() === cur ) {
					match = elem;
					break;
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];

		if ( elem ) {
			var match = false;
			
			elem = elem[dir];

			while ( elem ) {
				if ( elem[ expando ] === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 ) {
					if ( !isXML ) {
						elem[ expando ] = doneName;
						elem.sizset = i;
					}

					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}

					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
						match = elem;
						break;
					}
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

if ( document.documentElement.contains ) {
	Sizzle.contains = function( a, b ) {
		return a !== b && (a.contains ? a.contains(b) : true);
	};

} else if ( document.documentElement.compareDocumentPosition ) {
	Sizzle.contains = function( a, b ) {
		return !!(a.compareDocumentPosition(b) & 16);
	};

} else {
	Sizzle.contains = function() {
		return false;
	};
}

Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833) 
	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;

	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

var posProcess = function( selector, context, seed ) {
	var match,
		tmpSet = [],
		later = "",
		root = context.nodeType ? [context] : context;

	// Position selectors must be done after the filter
	// And so must :not(positional) so we move all PSEUDOs to the end
	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
		later += match[0];
		selector = selector.replace( Expr.match.PSEUDO, "" );
	}

	selector = Expr.relative[selector] ? selector + "*" : selector;

	for ( var i = 0, l = root.length; i < l; i++ ) {
		Sizzle( selector, root[i], tmpSet, seed );
	}

	return Sizzle.filter( later, tmpSet );
};

// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;


})();


var runtil = /Until$/,
	rparentsprev = /^(?:parents|prevUntil|prevAll)/,
	// Note: This RegExp should be improved, or likely pulled from Sizzle
	rmultiselector = /,/,
	isSimple = /^.[^:#\[\.,]*$/,
	slice = Array.prototype.slice,
	POS = jQuery.expr.match.POS,
	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend({
	find: function( selector ) {
		var self = this,
			i, l;

		if ( typeof selector !== "string" ) {
			return jQuery( selector ).filter(function() {
				for ( i = 0, l = self.length; i < l; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			});
		}

		var ret = this.pushStack( "", "find", selector ),
			length, n, r;

		for ( i = 0, l = this.length; i < l; i++ ) {
			length = ret.length;
			jQuery.find( selector, this[i], ret );

			if ( i > 0 ) {
				// Make sure that the results are unique
				for ( n = length; n < ret.length; n++ ) {
					for ( r = 0; r < length; r++ ) {
						if ( ret[r] === ret[n] ) {
							ret.splice(n--, 1);
							break;
						}
					}
				}
			}
		}

		return ret;
	},

	has: function( target ) {
		var targets = jQuery( target );
		return this.filter(function() {
			for ( var i = 0, l = targets.length; i < l; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},

	not: function( selector ) {
		return this.pushStack( winnow(this, selector, false), "not", selector);
	},

	filter: function( selector ) {
		return this.pushStack( winnow(this, selector, true), "filter", selector );
	},

	is: function( selector ) {
		return !!selector && ( 
			typeof selector === "string" ?
				// If this is a positional selector, check membership in the returned set
				// so $("p:first").is("p:last") won't return true for a doc with two "p".
				POS.test( selector ) ? 
					jQuery( selector, this.context ).index( this[0] ) >= 0 :
					jQuery.filter( selector, this ).length > 0 :
				this.filter( selector ).length > 0 );
	},

	closest: function( selectors, context ) {
		var ret = [], i, l, cur = this[0];
		
		// Array (deprecated as of jQuery 1.7)
		if ( jQuery.isArray( selectors ) ) {
			var level = 1;

			while ( cur && cur.ownerDocument && cur !== context ) {
				for ( i = 0; i < selectors.length; i++ ) {

					if ( jQuery( cur ).is( selectors[ i ] ) ) {
						ret.push({ selector: selectors[ i ], elem: cur, level: level });
					}
				}

				cur = cur.parentNode;
				level++;
			}

			return ret;
		}

		// String
		var pos = POS.test( selectors ) || typeof selectors !== "string" ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( i = 0, l = this.length; i < l; i++ ) {
			cur = this[i];

			while ( cur ) {
				if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
					ret.push( cur );
					break;

				} else {
					cur = cur.parentNode;
					if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
						break;
					}
				}
			}
		}

		ret = ret.length > 1 ? jQuery.unique( ret ) : ret;

		return this.pushStack( ret, "closest", selectors );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
		}

		// index in selector
		if ( typeof elem === "string" ) {
			return jQuery.inArray( this[0], jQuery( elem ) );
		}

		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this );
	},

	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context ) :
				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
			all = jQuery.merge( this.get(), set );

		return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
			all :
			jQuery.unique( all ) );
	},

	andSelf: function() {
		return this.add( this.prevObject );
	}
});

// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
	return !node || !node.parentNode || node.parentNode.nodeType === 11;
}

jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return jQuery.nth( elem, 2, "nextSibling" );
	},
	prev: function( elem ) {
		return jQuery.nth( elem, 2, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( elem.parentNode.firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( elem.firstChild );
	},
	contents: function( elem ) {
		return jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.makeArray( elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until );

		if ( !runtil.test( name ) ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;

		if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
			ret = ret.reverse();
		}

		return this.pushStack( ret, name, slice.call( arguments ).join(",") );
	};
});

jQuery.extend({
	filter: function( expr, elems, not ) {
		if ( not ) {
			expr = ":not(" + expr + ")";
		}

		return elems.length === 1 ?
			jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
			jQuery.find.matches(expr, elems);
	},

	dir: function( elem, dir, until ) {
		var matched = [],
			cur = elem[ dir ];

		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			if ( cur.nodeType === 1 ) {
				matched.push( cur );
			}
			cur = cur[dir];
		}
		return matched;
	},

	nth: function( cur, result, dir, elem ) {
		result = result || 1;
		var num = 0;

		for ( ; cur; cur = cur[dir] ) {
			if ( cur.nodeType === 1 && ++num === result ) {
				break;
			}
		}

		return cur;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				r.push( n );
			}
		}

		return r;
	}
});

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {

	// Can't pass null or undefined to indexOf in Firefox 4
	// Set to 0 to skip string check
	qualifier = qualifier || 0;

	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep(elements, function( elem, i ) {
			var retVal = !!qualifier.call( elem, i, elem );
			return retVal === keep;
		});

	} else if ( qualifier.nodeType ) {
		return jQuery.grep(elements, function( elem, i ) {
			return ( elem === qualifier ) === keep;
		});

	} else if ( typeof qualifier === "string" ) {
		var filtered = jQuery.grep(elements, function( elem ) {
			return elem.nodeType === 1;
		});

		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter(qualifier, filtered, !keep);
		} else {
			qualifier = jQuery.filter( qualifier, filtered );
		}
	}

	return jQuery.grep(elements, function( elem, i ) {
		return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
	});
}




function createSafeFragment( document ) {
	var list = nodeNames.split( "|" ),
	safeFrag = document.createDocumentFragment();

	if ( safeFrag.createElement ) {
		while ( list.length ) {
			safeFrag.createElement(
				list.pop()
			);
		}
	}
	return safeFrag;
}

var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" +
		"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
	rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnoInnerhtml = /<(?:script|style)/i,
	rnocache = /<(?:script|object|embed|option|style)/i,
	rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"),
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptType = /\/(java|ecma)script/i,
	rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
	wrapMap = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		thead: [ 1, "<table>", "</table>" ],
		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
		area: [ 1, "<map>", "</map>" ],
		_default: [ 0, "", "" ]
	},
	safeFragment = createSafeFragment( document );

wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
	wrapMap._default = [ 1, "div<div>", "</div>" ];
}

jQuery.fn.extend({
	text: function( text ) {
		if ( jQuery.isFunction(text) ) {
			return this.each(function(i) {
				var self = jQuery( this );

				self.text( text.call(this, i, self.text()) );
			});
		}

		if ( typeof text !== "object" && text !== undefined ) {
			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
		}

		return jQuery.text( this );
	},

	wrapAll: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapAll( html.call(this, i) );
			});
		}

		if ( this[0] ) {
			// The elements to wrap the target around
			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);

			if ( this[0].parentNode ) {
				wrap.insertBefore( this[0] );
			}

			wrap.map(function() {
				var elem = this;

				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}

				return elem;
			}).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapInner( html.call(this, i) );
			});
		}

		return this.each(function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		});
	},

	wrap: function( html ) {
		var isFunction = jQuery.isFunction( html );

		return this.each(function(i) {
			jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
		});
	},

	unwrap: function() {
		return this.parent().each(function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		}).end();
	},

	append: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 ) {
				this.appendChild( elem );
			}
		});
	},

	prepend: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 ) {
				this.insertBefore( elem, this.firstChild );
			}
		});
	},

	before: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this );
			});
		} else if ( arguments.length ) {
			var set = jQuery.clean( arguments );
			set.push.apply( set, this.toArray() );
			return this.pushStack( set, "before", arguments );
		}
	},

	after: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			});
		} else if ( arguments.length ) {
			var set = this.pushStack( this, "after", arguments );
			set.push.apply( set, jQuery.clean(arguments) );
			return set;
		}
	},

	// keepData is for internal use only--do not document
	remove: function( selector, keepData ) {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
				if ( !keepData && elem.nodeType === 1 ) {
					jQuery.cleanData( elem.getElementsByTagName("*") );
					jQuery.cleanData( [ elem ] );
				}

				if ( elem.parentNode ) {
					elem.parentNode.removeChild( elem );
				}
			}
		}

		return this;
	},

	empty: function() {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( elem.getElementsByTagName("*") );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function () {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		});
	},

	html: function( value ) {
		if ( value === undefined ) {
			return this[0] && this[0].nodeType === 1 ?
				this[0].innerHTML.replace(rinlinejQuery, "") :
				null;

		// See if we can take a shortcut and just use innerHTML
		} else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
			(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
			!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

			value = value.replace(rxhtmlTag, "<$1></$2>");

			try {
				for ( var i = 0, l = this.length; i < l; i++ ) {
					// Remove element nodes and prevent memory leaks
					if ( this[i].nodeType === 1 ) {
						jQuery.cleanData( this[i].getElementsByTagName("*") );
						this[i].innerHTML = value;
					}
				}

			// If using innerHTML throws an exception, use the fallback method
			} catch(e) {
				this.empty().append( value );
			}

		} else if ( jQuery.isFunction( value ) ) {
			this.each(function(i){
				var self = jQuery( this );

				self.html( value.call(this, i, self.html()) );
			});

		} else {
			this.empty().append( value );
		}

		return this;
	},

	replaceWith: function( value ) {
		if ( this[0] && this[0].parentNode ) {
			// Make sure that the elements are removed from the DOM before they are inserted
			// this can help fix replacing a parent with child elements
			if ( jQuery.isFunction( value ) ) {
				return this.each(function(i) {
					var self = jQuery(this), old = self.html();
					self.replaceWith( value.call( this, i, old ) );
				});
			}

			if ( typeof value !== "string" ) {
				value = jQuery( value ).detach();
			}

			return this.each(function() {
				var next = this.nextSibling,
					parent = this.parentNode;

				jQuery( this ).remove();

				if ( next ) {
					jQuery(next).before( value );
				} else {
					jQuery(parent).append( value );
				}
			});
		} else {
			return this.length ?
				this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
				this;
		}
	},

	detach: function( selector ) {
		return this.remove( selector, true );
	},

	domManip: function( args, table, callback ) {
		var results, first, fragment, parent,
			value = args[0],
			scripts = [];

		// We can't cloneNode fragments that contain checked, in WebKit
		if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
			return this.each(function() {
				jQuery(this).domManip( args, table, callback, true );
			});
		}

		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				args[0] = value.call(this, i, table ? self.html() : undefined);
				self.domManip( args, table, callback );
			});
		}

		if ( this[0] ) {
			parent = value && value.parentNode;

			// If we're in a fragment, just use that instead of building a new one
			if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
				results = { fragment: parent };

			} else {
				results = jQuery.buildFragment( args, this, scripts );
			}

			fragment = results.fragment;

			if ( fragment.childNodes.length === 1 ) {
				first = fragment = fragment.firstChild;
			} else {
				first = fragment.firstChild;
			}

			if ( first ) {
				table = table && jQuery.nodeName( first, "tr" );

				for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
					callback.call(
						table ?
							root(this[i], first) :
							this[i],
						// Make sure that we do not leak memory by inadvertently discarding
						// the original fragment (which might have attached data) instead of
						// using it; in addition, use the original fragment object for the last
						// item instead of first because it can end up being emptied incorrectly
						// in certain situations (Bug #8070).
						// Fragments from the fragment cache must always be cloned and never used
						// in place.
						results.cacheable || ( l > 1 && i < lastIndex ) ?
							jQuery.clone( fragment, true, true ) :
							fragment
					);
				}
			}

			if ( scripts.length ) {
				jQuery.each( scripts, evalScript );
			}
		}

		return this;
	}
});

function root( elem, cur ) {
	return jQuery.nodeName(elem, "table") ?
		(elem.getElementsByTagName("tbody")[0] ||
		elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
		elem;
}

function cloneCopyEvent( src, dest ) {

	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}

	var type, i, l,
		oldData = jQuery._data( src ),
		curData = jQuery._data( dest, oldData ),
		events = oldData.events;

	if ( events ) {
		delete curData.handle;
		curData.events = {};

		for ( type in events ) {
			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
				jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
			}
		}
	}

	// make the cloned public data object a copy from the original
	if ( curData.data ) {
		curData.data = jQuery.extend( {}, curData.data );
	}
}

function cloneFixAttributes( src, dest ) {
	var nodeName;

	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}

	// clearAttributes removes the attributes, which we don't want,
	// but also removes the attachEvent events, which we *do* want
	if ( dest.clearAttributes ) {
		dest.clearAttributes();
	}

	// mergeAttributes, in contrast, only merges back on the
	// original attributes, not the events
	if ( dest.mergeAttributes ) {
		dest.mergeAttributes( src );
	}

	nodeName = dest.nodeName.toLowerCase();

	// IE6-8 fail to clone children inside object elements that use
	// the proprietary classid attribute value (rather than the type
	// attribute) to identify the type of content to display
	if ( nodeName === "object" ) {
		dest.outerHTML = src.outerHTML;

	} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
		// IE6-8 fails to persist the checked state of a cloned checkbox
		// or radio button. Worse, IE6-7 fail to give the cloned element
		// a checked appearance if the defaultChecked value isn't also set
		if ( src.checked ) {
			dest.defaultChecked = dest.checked = src.checked;
		}

		// IE6-7 get confused and end up setting the value of a cloned
		// checkbox/radio button to an empty string instead of "on"
		if ( dest.value !== src.value ) {
			dest.value = src.value;
		}

	// IE6-8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.selected = src.defaultSelected;

	// IE6-8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}

	// Event data gets referenced instead of copied if the expando
	// gets copied too
	dest.removeAttribute( jQuery.expando );
}

jQuery.buildFragment = function( args, nodes, scripts ) {
	var fragment, cacheable, cacheresults, doc,
	first = args[ 0 ];

	// nodes may contain either an explicit document object,
	// a jQuery collection or context object.
	// If nodes[0] contains a valid object to assign to doc
	if ( nodes && nodes[0] ) {
		doc = nodes[0].ownerDocument || nodes[0];
	}

	// Ensure that an attr object doesn't incorrectly stand in as a document object
	// Chrome and Firefox seem to allow this to occur and will throw exception
	// Fixes #8950
	if ( !doc.createDocumentFragment ) {
		doc = document;
	}

	// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
	// Cloning options loses the selected state, so don't cache them
	// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
	// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
	// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
	if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
		first.charAt(0) === "<" && !rnocache.test( first ) &&
		(jQuery.support.checkClone || !rchecked.test( first )) &&
		(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {

		cacheable = true;

		cacheresults = jQuery.fragments[ first ];
		if ( cacheresults && cacheresults !== 1 ) {
			fragment = cacheresults;
		}
	}

	if ( !fragment ) {
		fragment = doc.createDocumentFragment();
		jQuery.clean( args, doc, fragment, scripts );
	}

	if ( cacheable ) {
		jQuery.fragments[ first ] = cacheresults ? fragment : 1;
	}

	return { fragment: fragment, cacheable: cacheable };
};

jQuery.fragments = {};

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var ret = [],
			insert = jQuery( selector ),
			parent = this.length === 1 && this[0].parentNode;

		if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
			insert[ original ]( this[0] );
			return this;

		} else {
			for ( var i = 0, l = insert.length; i < l; i++ ) {
				var elems = ( i > 0 ? this.clone(true) : this ).get();
				jQuery( insert[i] )[ original ]( elems );
				ret = ret.concat( elems );
			}

			return this.pushStack( ret, name, insert.selector );
		}
	};
});

function getAll( elem ) {
	if ( typeof elem.getElementsByTagName !== "undefined" ) {
		return elem.getElementsByTagName( "*" );

	} else if ( typeof elem.querySelectorAll !== "undefined" ) {
		return elem.querySelectorAll( "*" );

	} else {
		return [];
	}
}

// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
	if ( elem.type === "checkbox" || elem.type === "radio" ) {
		elem.defaultChecked = elem.checked;
	}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
	var nodeName = ( elem.nodeName || "" ).toLowerCase();
	if ( nodeName === "input" ) {
		fixDefaultChecked( elem );
	// Skip scripts, get other children
	} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
		jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
	}
}

// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
	var div = document.createElement( "div" );
	safeFragment.appendChild( div );

	div.innerHTML = elem.outerHTML;
	return div.firstChild;
}

jQuery.extend({
	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var srcElements,
			destElements,
			i,
			// IE<=8 does not properly clone detached, unknown element nodes
			clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ?
				elem.cloneNode( true ) :
				shimCloneNode( elem );

		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
			// IE copies events bound via attachEvent when using cloneNode.
			// Calling detachEvent on the clone will also remove the events
			// from the original. In order to get around this, we use some
			// proprietary methods to clear the events. Thanks to MooTools
			// guys for this hotness.

			cloneFixAttributes( elem, clone );

			// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
			srcElements = getAll( elem );
			destElements = getAll( clone );

			// Weird iteration because IE will replace the length property
			// with an element if you are cloning the body and one of the
			// elements on the page has a name or id of "length"
			for ( i = 0; srcElements[i]; ++i ) {
				// Ensure that the destination node is not null; Fixes #9587
				if ( destElements[i] ) {
					cloneFixAttributes( srcElements[i], destElements[i] );
				}
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			cloneCopyEvent( elem, clone );

			if ( deepDataAndEvents ) {
				srcElements = getAll( elem );
				destElements = getAll( clone );

				for ( i = 0; srcElements[i]; ++i ) {
					cloneCopyEvent( srcElements[i], destElements[i] );
				}
			}
		}

		srcElements = destElements = null;

		// Return the cloned set
		return clone;
	},

	clean: function( elems, context, fragment, scripts ) {
		var checkScriptType;

		context = context || document;

		// !context.createElement fails in IE with an error but returns typeof 'object'
		if ( typeof context.createElement === "undefined" ) {
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
		}

		var ret = [], j;

		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			if ( typeof elem === "number" ) {
				elem += "";
			}

			if ( !elem ) {
				continue;
			}

			// Convert html string into DOM nodes
			if ( typeof elem === "string" ) {
				if ( !rhtml.test( elem ) ) {
					elem = context.createTextNode( elem );
				} else {
					// Fix "XHTML"-style tags in all browsers
					elem = elem.replace(rxhtmlTag, "<$1></$2>");

					// Trim whitespace, otherwise indexOf won't work as expected
					var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
						wrap = wrapMap[ tag ] || wrapMap._default,
						depth = wrap[0],
						div = context.createElement("div");

					// Append wrapper element to unknown element safe doc fragment
					if ( context === document ) {
						// Use the fragment we've already created for this document
						safeFragment.appendChild( div );
					} else {
						// Use a fragment created with the owner document
						createSafeFragment( context ).appendChild( div );
					}

					// Go to html and back, then peel off extra wrappers
					div.innerHTML = wrap[1] + elem + wrap[2];

					// Move to the right depth
					while ( depth-- ) {
						div = div.lastChild;
					}

					// Remove IE's autoinserted <tbody> from table fragments
					if ( !jQuery.support.tbody ) {

						// String was a <table>, *may* have spurious <tbody>
						var hasBody = rtbody.test(elem),
							tbody = tag === "table" && !hasBody ?
								div.firstChild && div.firstChild.childNodes :

								// String was a bare <thead> or <tfoot>
								wrap[1] === "<table>" && !hasBody ?
									div.childNodes :
									[];

						for ( j = tbody.length - 1; j >= 0 ; --j ) {
							if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
								tbody[ j ].parentNode.removeChild( tbody[ j ] );
							}
						}
					}

					// IE completely kills leading whitespace when innerHTML is used
					if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
						div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
					}

					elem = div.childNodes;
				}
			}

			// Resets defaultChecked for any radios and checkboxes
			// about to be appended to the DOM in IE 6/7 (#8060)
			var len;
			if ( !jQuery.support.appendChecked ) {
				if ( elem[0] && typeof (len = elem.length) === "number" ) {
					for ( j = 0; j < len; j++ ) {
						findInputs( elem[j] );
					}
				} else {
					findInputs( elem );
				}
			}

			if ( elem.nodeType ) {
				ret.push( elem );
			} else {
				ret = jQuery.merge( ret, elem );
			}
		}

		if ( fragment ) {
			checkScriptType = function( elem ) {
				return !elem.type || rscriptType.test( elem.type );
			};
			for ( i = 0; ret[i]; i++ ) {
				if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );

				} else {
					if ( ret[i].nodeType === 1 ) {
						var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );

						ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
					}
					fragment.appendChild( ret[i] );
				}
			}
		}

		return ret;
	},

	cleanData: function( elems ) {
		var data, id,
			cache = jQuery.cache,
			special = jQuery.event.special,
			deleteExpando = jQuery.support.deleteExpando;

		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
				continue;
			}

			id = elem[ jQuery.expando ];

			if ( id ) {
				data = cache[ id ];

				if ( data && data.events ) {
					for ( var type in data.events ) {
						if ( special[ type ] ) {
							jQuery.event.remove( elem, type );

						// This is a shortcut to avoid jQuery.event.remove's overhead
						} else {
							jQuery.removeEvent( elem, type, data.handle );
						}
					}

					// Null the DOM reference to avoid IE6/7/8 leak (#7054)
					if ( data.handle ) {
						data.handle.elem = null;
					}
				}

				if ( deleteExpando ) {
					delete elem[ jQuery.expando ];

				} else if ( elem.removeAttribute ) {
					elem.removeAttribute( jQuery.expando );
				}

				delete cache[ id ];
			}
		}
	}
});

function evalScript( i, elem ) {
	if ( elem.src ) {
		jQuery.ajax({
			url: elem.src,
			async: false,
			dataType: "script"
		});
	} else {
		jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
	}

	if ( elem.parentNode ) {
		elem.parentNode.removeChild( elem );
	}
}




var ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity=([^)]*)/,
	// fixed for IE9, see #8346
	rupper = /([A-Z]|^ms)/g,
	rnumpx = /^-?\d+(?:px)?$/i,
	rnum = /^-?\d/,
	rrelNum = /^([\-+])=([\-+.\de]+)/,

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssWidth = [ "Left", "Right" ],
	cssHeight = [ "Top", "Bottom" ],
	curCSS,

	getComputedStyle,
	currentStyle;

jQuery.fn.css = function( name, value ) {
	// Setting 'undefined' is a no-op
	if ( arguments.length === 2 && value === undefined ) {
		return this;
	}

	return jQuery.access( this, name, value, true, function( elem, name, value ) {
		return value !== undefined ?
			jQuery.style( elem, name, value ) :
			jQuery.css( elem, name );
	});
};

jQuery.extend({
	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {
					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity", "opacity" );
					return ret === "" ? "1" : ret;

				} else {
					return elem.style.opacity;
				}
			}
		}
	},

	// Exclude the following css properties to add px
	cssNumber: {
		"fillOpacity": true,
		"fontWeight": true,
		"lineHeight": true,
		"opacity": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		// normalize float css property
		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {
		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, origName = jQuery.camelCase( name ),
			style = elem.style, hooks = jQuery.cssHooks[ origName ];

		name = jQuery.cssProps[ origName ] || origName;

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// convert relative number strings (+= or -=) to relative numbers. #7345
			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
				value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
				// Fixes bug #9237
				type = "number";
			}

			// Make sure that NaN and null values aren't set. See: #7116
			if ( value == null || type === "number" && isNaN( value ) ) {
				return;
			}

			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
				// Fixes bug #5509
				try {
					style[ name ] = value;
				} catch(e) {}
			}

		} else {
			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra ) {
		var ret, hooks;

		// Make sure that we're working with the right name
		name = jQuery.camelCase( name );
		hooks = jQuery.cssHooks[ name ];
		name = jQuery.cssProps[ name ] || name;

		// cssFloat needs a special treatment
		if ( name === "cssFloat" ) {
			name = "float";
		}

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
			return ret;

		// Otherwise, if a way to get the computed value exists, use that
		} else if ( curCSS ) {
			return curCSS( elem, name );
		}
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};

		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		// Revert the old values
		for ( name in options ) {
			elem.style[ name ] = old[ name ];
		}
	}
});

// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;

jQuery.each(["height", "width"], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			var val;

			if ( computed ) {
				if ( elem.offsetWidth !== 0 ) {
					return getWH( elem, name, extra );
				} else {
					jQuery.swap( elem, cssShow, function() {
						val = getWH( elem, name, extra );
					});
				}

				return val;
			}
		},

		set: function( elem, value ) {
			if ( rnumpx.test( value ) ) {
				// ignore negative width and height values #1599
				value = parseFloat( value );

				if ( value >= 0 ) {
					return value + "px";
				}

			} else {
				return value;
			}
		}
	};
});

if ( !jQuery.support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
				( parseFloat( RegExp.$1 ) / 100 ) + "" :
				computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style,
				currentStyle = elem.currentStyle,
				opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
				filter = currentStyle && currentStyle.filter || style.filter || "";

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
			if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {

				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
				// if "filter:" is present at all, clearType is disabled, we want to avoid this
				// style.removeAttribute is IE Only, but so apparently is this code path...
				style.removeAttribute( "filter" );

				// if there there is no filter style applied in a css rule, we are done
				if ( currentStyle && !currentStyle.filter ) {
					return;
				}
			}

			// otherwise, set new filter values
			style.filter = ralpha.test( filter ) ?
				filter.replace( ralpha, opacity ) :
				filter + " " + opacity;
		}
	};
}

jQuery(function() {
	// This hook cannot be added until DOM ready because the support test
	// for it is not run until after DOM ready
	if ( !jQuery.support.reliableMarginRight ) {
		jQuery.cssHooks.marginRight = {
			get: function( elem, computed ) {
				// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
				// Work around by temporarily setting element display to inline-block
				var ret;
				jQuery.swap( elem, { "display": "inline-block" }, function() {
					if ( computed ) {
						ret = curCSS( elem, "margin-right", "marginRight" );
					} else {
						ret = elem.style.marginRight;
					}
				});
				return ret;
			}
		};
	}
});

if ( document.defaultView && document.defaultView.getComputedStyle ) {
	getComputedStyle = function( elem, name ) {
		var ret, defaultView, computedStyle;

		name = name.replace( rupper, "-$1" ).toLowerCase();

		if ( (defaultView = elem.ownerDocument.defaultView) &&
				(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
			ret = computedStyle.getPropertyValue( name );
			if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
				ret = jQuery.style( elem, name );
			}
		}

		return ret;
	};
}

if ( document.documentElement.currentStyle ) {
	currentStyle = function( elem, name ) {
		var left, rsLeft, uncomputed,
			ret = elem.currentStyle && elem.currentStyle[ name ],
			style = elem.style;

		// Avoid setting ret to empty string here
		// so we don't default to auto
		if ( ret === null && style && (uncomputed = style[ name ]) ) {
			ret = uncomputed;
		}

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {

			// Remember the original values
			left = style.left;
			rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;

			// Put in the new values to get a computed value out
			if ( rsLeft ) {
				elem.runtimeStyle.left = elem.currentStyle.left;
			}
			style.left = name === "fontSize" ? "1em" : ( ret || 0 );
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			if ( rsLeft ) {
				elem.runtimeStyle.left = rsLeft;
			}
		}

		return ret === "" ? "auto" : ret;
	};
}

curCSS = getComputedStyle || currentStyle;

function getWH( elem, name, extra ) {

	// Start with offset property
	var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
		which = name === "width" ? cssWidth : cssHeight,
		i = 0,
		len = which.length;

	if ( val > 0 ) {
		if ( extra !== "border" ) {
			for ( ; i < len; i++ ) {
				if ( !extra ) {
					val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
				}
				if ( extra === "margin" ) {
					val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
				} else {
					val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
				}
			}
		}

		return val + "px";
	}

	// Fall back to computed then uncomputed css if necessary
	val = curCSS( elem, name, name );
	if ( val < 0 || val == null ) {
		val = elem.style[ name ] || 0;
	}
	// Normalize "", auto, and prepare for extra
	val = parseFloat( val ) || 0;

	// Add padding, border, margin
	if ( extra ) {
		for ( ; i < len; i++ ) {
			val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
			if ( extra !== "padding" ) {
				val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
			}
			if ( extra === "margin" ) {
				val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
			}
		}
	}

	return val + "px";
}

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		var width = elem.offsetWidth,
			height = elem.offsetHeight;

		return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
	};

	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}




var r20 = /%20/g,
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rhash = /#.*$/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
	rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,
	rquery = /\?/,
	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
	rselectTextarea = /^(?:select|textarea)/i,
	rspacesAjax = /\s+/,
	rts = /([?&])_=[^&]*/,
	rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,

	// Keep a copy of the old load method
	_load = jQuery.fn.load,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Document location
	ajaxLocation,

	// Document location segments
	ajaxLocParts,

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = ["*/"] + ["*"];

// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
	ajaxLocation = location.href;
} catch( e ) {
	// Use the href attribute of an A element
	// since IE will modify it given document.location
	ajaxLocation = document.createElement( "a" );
	ajaxLocation.href = "";
	ajaxLocation = ajaxLocation.href;
}

// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		if ( jQuery.isFunction( func ) ) {
			var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
				i = 0,
				length = dataTypes.length,
				dataType,
				list,
				placeBefore;

			// For each dataType in the dataTypeExpression
			for ( ; i < length; i++ ) {
				dataType = dataTypes[ i ];
				// We control if we're asked to add before
				// any existing element
				placeBefore = /^\+/.test( dataType );
				if ( placeBefore ) {
					dataType = dataType.substr( 1 ) || "*";
				}
				list = structure[ dataType ] = structure[ dataType ] || [];
				// then we add to the structure accordingly
				list[ placeBefore ? "unshift" : "push" ]( func );
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
		dataType /* internal */, inspected /* internal */ ) {

	dataType = dataType || options.dataTypes[ 0 ];
	inspected = inspected || {};

	inspected[ dataType ] = true;

	var list = structure[ dataType ],
		i = 0,
		length = list ? list.length : 0,
		executeOnly = ( structure === prefilters ),
		selection;

	for ( ; i < length && ( executeOnly || !selection ); i++ ) {
		selection = list[ i ]( options, originalOptions, jqXHR );
		// If we got redirected to another dataType
		// we try there if executing only and not done already
		if ( typeof selection === "string" ) {
			if ( !executeOnly || inspected[ selection ] ) {
				selection = undefined;
			} else {
				options.dataTypes.unshift( selection );
				selection = inspectPrefiltersOrTransports(
						structure, options, originalOptions, jqXHR, selection, inspected );
			}
		}
	}
	// If we're only executing or nothing was selected
	// we try the catchall dataType if not done already
	if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
		selection = inspectPrefiltersOrTransports(
				structure, options, originalOptions, jqXHR, "*", inspected );
	}
	// unnecessary when only executing (prefilters)
	// but it'll be ignored by the caller in that case
	return selection;
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};
	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}
}

jQuery.fn.extend({
	load: function( url, params, callback ) {
		if ( typeof url !== "string" && _load ) {
			return _load.apply( this, arguments );

		// Don't do a request if no elements are being requested
		} else if ( !this.length ) {
			return this;
		}

		var off = url.indexOf( " " );
		if ( off >= 0 ) {
			var selector = url.slice( off, url.length );
			url = url.slice( 0, off );
		}

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params ) {
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = undefined;

			// Otherwise, build a param string
			} else if ( typeof params === "object" ) {
				params = jQuery.param( params, jQuery.ajaxSettings.traditional );
				type = "POST";
			}
		}

		var self = this;

		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			// Complete callback (responseText is used internally)
			complete: function( jqXHR, status, responseText ) {
				// Store the response as specified by the jqXHR object
				responseText = jqXHR.responseText;
				// If successful, inject the HTML into all the matched elements
				if ( jqXHR.isResolved() ) {
					// #4825: Get the actual response in case
					// a dataFilter is present in ajaxSettings
					jqXHR.done(function( r ) {
						responseText = r;
					});
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(responseText.replace(rscript, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						responseText );
				}

				if ( callback ) {
					self.each( callback, [ responseText, status, jqXHR ] );
				}
			}
		});

		return this;
	},

	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},

	serializeArray: function() {
		return this.map(function(){
			return this.elements ? jQuery.makeArray( this.elements ) : this;
		})
		.filter(function(){
			return this.name && !this.disabled &&
				( this.checked || rselectTextarea.test( this.nodeName ) ||
					rinput.test( this.type ) );
		})
		.map(function( i, elem ){
			var val = jQuery( this ).val();

			return val == null ?
				null :
				jQuery.isArray( val ) ?
					jQuery.map( val, function( val, i ){
						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
					}) :
					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		}).get();
	}
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
	jQuery.fn[ o ] = function( f ){
		return this.on( o, f );
	};
});

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {
		// shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		return jQuery.ajax({
			type: method,
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	};
});

jQuery.extend({

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		if ( settings ) {
			// Building a settings object
			ajaxExtend( target, jQuery.ajaxSettings );
		} else {
			// Extending ajaxSettings
			settings = target;
			target = jQuery.ajaxSettings;
		}
		ajaxExtend( target, settings );
		return target;
	},

	ajaxSettings: {
		url: ajaxLocation,
		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		traditional: false,
		headers: {},
		*/

		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			text: "text/plain",
			json: "application/json, text/javascript",
			"*": allTypes
		},

		contents: {
			xml: /xml/,
			html: /html/,
			json: /json/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText"
		},

		// List of data converters
		// 1) key format is "source_type destination_type" (a single space in-between)
		// 2) the catchall symbol "*" can be used for source_type
		converters: {

			// Convert anything to text
			"* text": window.String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": jQuery.parseJSON,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			context: true,
			url: true
		}
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var // Create the final options object
			s = jQuery.ajaxSetup( {}, options ),
			// Callbacks context
			callbackContext = s.context || s,
			// Context for global events
			// It's the callbackContext if one was provided in the options
			// and if it's a DOM node or a jQuery collection
			globalEventContext = callbackContext !== s &&
				( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
						jQuery( callbackContext ) : jQuery.event,
			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),
			// Status-dependent callbacks
			statusCode = s.statusCode || {},
			// ifModified key
			ifModifiedKey,
			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},
			// Response headers
			responseHeadersString,
			responseHeaders,
			// transport
			transport,
			// timeout handle
			timeoutTimer,
			// Cross-domain detection vars
			parts,
			// The jqXHR state
			state = 0,
			// To know if global events are to be dispatched
			fireGlobals,
			// Loop variable
			i,
			// Fake xhr
			jqXHR = {

				readyState: 0,

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( !state ) {
						var lname = name.toLowerCase();
						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Raw string
				getAllResponseHeaders: function() {
					return state === 2 ? responseHeadersString : null;
				},

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( state === 2 ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match === undefined ? null : match;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( !state ) {
						s.mimeType = type;
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					statusText = statusText || "abort";
					if ( transport ) {
						transport.abort( statusText );
					}
					done( 0, statusText );
					return this;
				}
			};

		// Callback for when everything is done
		// It is defined here because jslint complains if it is declared
		// at the end of the function (which would be more logical and readable)
		function done( status, nativeStatusText, responses, headers ) {

			// Called once
			if ( state === 2 ) {
				return;
			}

			// State is "done" now
			state = 2;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			var isSuccess,
				success,
				error,
				statusText = nativeStatusText,
				response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
				lastModified,
				etag;

			// If successful, handle type chaining
			if ( status >= 200 && status < 300 || status === 304 ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {

					if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
						jQuery.lastModified[ ifModifiedKey ] = lastModified;
					}
					if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
						jQuery.etag[ ifModifiedKey ] = etag;
					}
				}

				// If not modified
				if ( status === 304 ) {

					statusText = "notmodified";
					isSuccess = true;

				// If we have data
				} else {

					try {
						success = ajaxConvert( s, response );
						statusText = "success";
						isSuccess = true;
					} catch(e) {
						// We have a parsererror
						statusText = "parsererror";
						error = e;
					}
				}
			} else {
				// We extract error from statusText
				// then normalize statusText and status for non-aborts
				error = statusText;
				if ( !statusText || status ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = "" + ( nativeStatusText || statusText );

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
						[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		// Attach deferreds
		deferred.promise( jqXHR );
		jqXHR.success = jqXHR.done;
		jqXHR.error = jqXHR.fail;
		jqXHR.complete = completeDeferred.add;

		// Status-dependent callbacks
		jqXHR.statusCode = function( map ) {
			if ( map ) {
				var tmp;
				if ( state < 2 ) {
					for ( tmp in map ) {
						statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
					}
				} else {
					tmp = map[ jqXHR.status ];
					jqXHR.then( tmp, tmp );
				}
			}
			return this;
		};

		// Remove hash character (#7531: and string promotion)
		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
		// We also use the url parameter if available
		s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );

		// Extract dataTypes list
		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );

		// Determine if a cross-domain request is in order
		if ( s.crossDomain == null ) {
			parts = rurl.exec( s.url.toLowerCase() );
			s.crossDomain = !!( parts &&
				( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
			);
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefiler, stop there
		if ( state === 2 ) {
			return false;
		}

		// We can fire global events as of now if asked to
		fireGlobals = s.global;

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// If data is available, append data to url
			if ( s.data ) {
				s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Get ifModifiedKey before adding the anti-cache parameter
			ifModifiedKey = s.url;

			// Add anti-cache in url if needed
			if ( s.cache === false ) {

				var ts = jQuery.now(),
					// try replacing _= if it is there
					ret = s.url.replace( rts, "$1_=" + ts );

				// if nothing was replaced, add timestamp to the end
				s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			ifModifiedKey = ifModifiedKey || s.url;
			if ( jQuery.lastModified[ ifModifiedKey ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
			}
			if ( jQuery.etag[ ifModifiedKey ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
			}
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
				// Abort if not done already
				jqXHR.abort();
				return false;

		}

		// Install callbacks on deferreds
		for ( i in { success: 1, error: 1, complete: 1 } ) {
			jqXHR[ i ]( s[ i ] );
		}

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;
			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}
			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = setTimeout( function(){
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				state = 1;
				transport.send( requestHeaders, done );
			} catch (e) {
				// Propagate exception as error if not done
				if ( state < 2 ) {
					done( -1, e );
				// Simply rethrow otherwise
				} else {
					throw e;
				}
			}
		}

		return jqXHR;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a, traditional ) {
		var s = [],
			add = function( key, value ) {
				// If value is a function, invoke it and return its value
				value = jQuery.isFunction( value ) ? value() : value;
				s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
			};

		// Set traditional to true for jQuery <= 1.3.2 behavior.
		if ( traditional === undefined ) {
			traditional = jQuery.ajaxSettings.traditional;
		}

		// If an array was passed in, assume that it is an array of form elements.
		if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
			// Serialize the form elements
			jQuery.each( a, function() {
				add( this.name, this.value );
			});

		} else {
			// If traditional, encode the "old" way (the way 1.3.2 or older
			// did it), otherwise encode params recursively.
			for ( var prefix in a ) {
				buildParams( prefix, a[ prefix ], traditional, add );
			}
		}

		// Return the resulting serialization
		return s.join( "&" ).replace( r20, "+" );
	}
});

function buildParams( prefix, obj, traditional, add ) {
	if ( jQuery.isArray( obj ) ) {
		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );

			} else {
				// If array item is non-scalar (array or object), encode its
				// numeric index to resolve deserialization ambiguity issues.
				// Note that rack (as of 1.0.0) can't currently deserialize
				// nested arrays properly, and attempting to do so may cause
				// a server error. Possible fixes are to modify rack's
				// deserialization algorithm or to provide an option or flag
				// to force array serialization to be shallow.
				buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
			}
		});

	} else if ( !traditional && obj != null && typeof obj === "object" ) {
		// Serialize object item.
		for ( var name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}

// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {}

});

/* Handles responses to an ajax request:
 * - sets all responseXXX fields accordingly
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var contents = s.contents,
		dataTypes = s.dataTypes,
		responseFields = s.responseFields,
		ct,
		type,
		finalDataType,
		firstDataType;

	// Fill responseXXX fields
	for ( type in responseFields ) {
		if ( type in responses ) {
			jqXHR[ responseFields[type] ] = responses[ type ];
		}
	}

	// Remove auto dataType and get content-type in the process
	while( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {
		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}
		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {

	// Apply the dataFilter if provided
	if ( s.dataFilter ) {
		response = s.dataFilter( response, s.dataType );
	}

	var dataTypes = s.dataTypes,
		converters = {},
		i,
		key,
		length = dataTypes.length,
		tmp,
		// Current and previous dataTypes
		current = dataTypes[ 0 ],
		prev,
		// Conversion expression
		conversion,
		// Conversion function
		conv,
		// Conversion functions (transitive conversion)
		conv1,
		conv2;

	// For each dataType in the chain
	for ( i = 1; i < length; i++ ) {

		// Create converters map
		// with lowercased keys
		if ( i === 1 ) {
			for ( key in s.converters ) {
				if ( typeof key === "string" ) {
					converters[ key.toLowerCase() ] = s.converters[ key ];
				}
			}
		}

		// Get the dataTypes
		prev = current;
		current = dataTypes[ i ];

		// If current is auto dataType, update it to prev
		if ( current === "*" ) {
			current = prev;
		// If no auto and dataTypes are actually different
		} else if ( prev !== "*" && prev !== current ) {

			// Get the converter
			conversion = prev + " " + current;
			conv = converters[ conversion ] || converters[ "* " + current ];

			// If there is no direct converter, search transitively
			if ( !conv ) {
				conv2 = undefined;
				for ( conv1 in converters ) {
					tmp = conv1.split( " " );
					if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
						conv2 = converters[ tmp[1] + " " + current ];
						if ( conv2 ) {
							conv1 = converters[ conv1 ];
							if ( conv1 === true ) {
								conv = conv2;
							} else if ( conv2 === true ) {
								conv = conv1;
							}
							break;
						}
					}
				}
			}
			// If we found no converter, dispatch an error
			if ( !( conv || conv2 ) ) {
				jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
			}
			// If found converter is not an equivalence
			if ( conv !== true ) {
				// Convert with 1 or 2 converters accordingly
				response = conv ? conv( response ) : conv2( conv1(response) );
			}
		}
	}
	return response;
}




var jsc = jQuery.now(),
	jsre = /(\=)\?(&|$)|\?\?/i;

// Default jsonp settings
jQuery.ajaxSetup({
	jsonp: "callback",
	jsonpCallback: function() {
		return jQuery.expando + "_" + ( jsc++ );
	}
});

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
		( typeof s.data === "string" );

	if ( s.dataTypes[ 0 ] === "jsonp" ||
		s.jsonp !== false && ( jsre.test( s.url ) ||
				inspectData && jsre.test( s.data ) ) ) {

		var responseContainer,
			jsonpCallback = s.jsonpCallback =
				jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
			previous = window[ jsonpCallback ],
			url = s.url,
			data = s.data,
			replace = "$1" + jsonpCallback + "$2";

		if ( s.jsonp !== false ) {
			url = url.replace( jsre, replace );
			if ( s.url === url ) {
				if ( inspectData ) {
					data = data.replace( jsre, replace );
				}
				if ( s.data === data ) {
					// Add callback manually
					url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
				}
			}
		}

		s.url = url;
		s.data = data;

		// Install callback
		window[ jsonpCallback ] = function( response ) {
			responseContainer = [ response ];
		};

		// Clean-up function
		jqXHR.always(function() {
			// Set callback back to previous value
			window[ jsonpCallback ] = previous;
			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( previous ) ) {
				window[ jsonpCallback ]( responseContainer[ 0 ] );
			}
		});

		// Use data converter to retrieve json after script execution
		s.converters["script json"] = function() {
			if ( !responseContainer ) {
				jQuery.error( jsonpCallback + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// force json dataType
		s.dataTypes[ 0 ] = "json";

		// Delegate to script
		return "script";
	}
});




// Install script dataType
jQuery.ajaxSetup({
	accepts: {
		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /javascript|ecmascript/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
});

// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
		s.global = false;
	}
});

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {

		var script,
			head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;

		return {

			send: function( _, callback ) {

				script = document.createElement( "script" );

				script.async = "async";

				if ( s.scriptCharset ) {
					script.charset = s.scriptCharset;
				}

				script.src = s.url;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function( _, isAbort ) {

					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;

						// Remove the script
						if ( head && script.parentNode ) {
							head.removeChild( script );
						}

						// Dereference the script
						script = undefined;

						// Callback if not abort
						if ( !isAbort ) {
							callback( 200, "success" );
						}
					}
				};
				// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
				// This arises when a base node is used (#2709 and #4378).
				head.insertBefore( script, head.firstChild );
			},

			abort: function() {
				if ( script ) {
					script.onload( 0, 1 );
				}
			}
		};
	}
});




var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
	xhrOnUnloadAbort = window.ActiveXObject ? function() {
		// Abort all pending requests
		for ( var key in xhrCallbacks ) {
			xhrCallbacks[ key ]( 0, 1 );
		}
	} : false,
	xhrId = 0,
	xhrCallbacks;

// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch( e ) {}
}

function createActiveXHR() {
	try {
		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
	} catch( e ) {}
}

// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
	/* Microsoft failed to properly
	 * implement the XMLHttpRequest in IE7 (can't request local files),
	 * so we use the ActiveXObject when it is available
	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
	 * we need a fallback.
	 */
	function() {
		return !this.isLocal && createStandardXHR() || createActiveXHR();
	} :
	// For all other browsers, use the standard XMLHttpRequest object
	createStandardXHR;

// Determine support properties
(function( xhr ) {
	jQuery.extend( jQuery.support, {
		ajax: !!xhr,
		cors: !!xhr && ( "withCredentials" in xhr )
	});
})( jQuery.ajaxSettings.xhr() );

// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {

	jQuery.ajaxTransport(function( s ) {
		// Cross domain only allowed if supported through XMLHttpRequest
		if ( !s.crossDomain || jQuery.support.cors ) {

			var callback;

			return {
				send: function( headers, complete ) {

					// Get a new xhr
					var xhr = s.xhr(),
						handle,
						i;

					// Open the socket
					// Passing null username, generates a login popup on Opera (#2865)
					if ( s.username ) {
						xhr.open( s.type, s.url, s.async, s.username, s.password );
					} else {
						xhr.open( s.type, s.url, s.async );
					}

					// Apply custom fields if provided
					if ( s.xhrFields ) {
						for ( i in s.xhrFields ) {
							xhr[ i ] = s.xhrFields[ i ];
						}
					}

					// Override mime type if needed
					if ( s.mimeType && xhr.overrideMimeType ) {
						xhr.overrideMimeType( s.mimeType );
					}

					// X-Requested-With header
					// For cross-domain requests, seeing as conditions for a preflight are
					// akin to a jigsaw puzzle, we simply never set it to be sure.
					// (it can always be set on a per-request basis or even using ajaxSetup)
					// For same-domain requests, won't change header if already provided.
					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
						headers[ "X-Requested-With" ] = "XMLHttpRequest";
					}

					// Need an extra try/catch for cross domain requests in Firefox 3
					try {
						for ( i in headers ) {
							xhr.setRequestHeader( i, headers[ i ] );
						}
					} catch( _ ) {}

					// Do send the request
					// This may raise an exception which is actually
					// handled in jQuery.ajax (so no try/catch here)
					xhr.send( ( s.hasContent && s.data ) || null );

					// Listener
					callback = function( _, isAbort ) {

						var status,
							statusText,
							responseHeaders,
							responses,
							xml;

						// Firefox throws exceptions when accessing properties
						// of an xhr when a network error occured
						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
						try {

							// Was never called and is aborted or complete
							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {

								// Only called once
								callback = undefined;

								// Do not keep as active anymore
								if ( handle ) {
									xhr.onreadystatechange = jQuery.noop;
									if ( xhrOnUnloadAbort ) {
										delete xhrCallbacks[ handle ];
									}
								}

								// If it's an abort
								if ( isAbort ) {
									// Abort it manually if needed
									if ( xhr.readyState !== 4 ) {
										xhr.abort();
									}
								} else {
									status = xhr.status;
									responseHeaders = xhr.getAllResponseHeaders();
									responses = {};
									xml = xhr.responseXML;

									// Construct response list
									if ( xml && xml.documentElement /* #4958 */ ) {
										responses.xml = xml;
									}
									responses.text = xhr.responseText;

									// Firefox throws an exception when accessing
									// statusText for faulty cross-domain requests
									try {
										statusText = xhr.statusText;
									} catch( e ) {
										// We normalize with Webkit giving an empty statusText
										statusText = "";
									}

									// Filter status for non standard behaviors

									// If the request is local and we have data: assume a success
									// (success with no data won't get notified, that's the best we
									// can do given current implementations)
									if ( !status && s.isLocal && !s.crossDomain ) {
										status = responses.text ? 200 : 404;
									// IE - #1450: sometimes returns 1223 when it should be 204
									} else if ( status === 1223 ) {
										status = 204;
									}
								}
							}
						} catch( firefoxAccessException ) {
							if ( !isAbort ) {
								complete( -1, firefoxAccessException );
							}
						}

						// Call complete if needed
						if ( responses ) {
							complete( status, statusText, responses, responseHeaders );
						}
					};

					// if we're in sync mode or it's in cache
					// and has been retrieved directly (IE6 & IE7)
					// we need to manually fire the callback
					if ( !s.async || xhr.readyState === 4 ) {
						callback();
					} else {
						handle = ++xhrId;
						if ( xhrOnUnloadAbort ) {
							// Create the active xhrs callbacks list if needed
							// and attach the unload handler
							if ( !xhrCallbacks ) {
								xhrCallbacks = {};
								jQuery( window ).unload( xhrOnUnloadAbort );
							}
							// Add to list of active xhrs callbacks
							xhrCallbacks[ handle ] = callback;
						}
						xhr.onreadystatechange = callback;
					}
				},

				abort: function() {
					if ( callback ) {
						callback(0,1);
					}
				}
			};
		}
	});
}




var elemdisplay = {},
	iframe, iframeDoc,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
	timerId,
	fxAttrs = [
		// height animations
		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
		// width animations
		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
		// opacity animations
		[ "opacity" ]
	],
	fxNow;

jQuery.fn.extend({
	show: function( speed, easing, callback ) {
		var elem, display;

		if ( speed || speed === 0 ) {
			return this.animate( genFx("show", 3), speed, easing, callback );

		} else {
			for ( var i = 0, j = this.length; i < j; i++ ) {
				elem = this[ i ];

				if ( elem.style ) {
					display = elem.style.display;

					// Reset the inline display of this element to learn if it is
					// being hidden by cascaded rules or not
					if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
						display = elem.style.display = "";
					}

					// Set elements which have been overridden with display: none
					// in a stylesheet to whatever the default browser style is
					// for such an element
					if ( display === "" && jQuery.css(elem, "display") === "none" ) {
						jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
					}
				}
			}

			// Set the display of most of the elements in a second loop
			// to avoid the constant reflow
			for ( i = 0; i < j; i++ ) {
				elem = this[ i ];

				if ( elem.style ) {
					display = elem.style.display;

					if ( display === "" || display === "none" ) {
						elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
					}
				}
			}

			return this;
		}
	},

	hide: function( speed, easing, callback ) {
		if ( speed || speed === 0 ) {
			return this.animate( genFx("hide", 3), speed, easing, callback);

		} else {
			var elem, display,
				i = 0,
				j = this.length;

			for ( ; i < j; i++ ) {
				elem = this[i];
				if ( elem.style ) {
					display = jQuery.css( elem, "display" );

					if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
						jQuery._data( elem, "olddisplay", display );
					}
				}
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( i = 0; i < j; i++ ) {
				if ( this[i].style ) {
					this[i].style.display = "none";
				}
			}

			return this;
		}
	},

	// Save the old toggle function
	_toggle: jQuery.fn.toggle,

	toggle: function( fn, fn2, callback ) {
		var bool = typeof fn === "boolean";

		if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
			this._toggle.apply( this, arguments );

		} else if ( fn == null || bool ) {
			this.each(function() {
				var state = bool ? fn : jQuery(this).is(":hidden");
				jQuery(this)[ state ? "show" : "hide" ]();
			});

		} else {
			this.animate(genFx("toggle", 3), fn, fn2, callback);
		}

		return this;
	},

	fadeTo: function( speed, to, easing, callback ) {
		return this.filter(":hidden").css("opacity", 0).show().end()
					.animate({opacity: to}, speed, easing, callback);
	},

	animate: function( prop, speed, easing, callback ) {
		var optall = jQuery.speed( speed, easing, callback );

		if ( jQuery.isEmptyObject( prop ) ) {
			return this.each( optall.complete, [ false ] );
		}

		// Do not change referenced properties as per-property easing will be lost
		prop = jQuery.extend( {}, prop );

		function doAnimation() {
			// XXX 'this' does not always have a nodeName when running the
			// test suite

			if ( optall.queue === false ) {
				jQuery._mark( this );
			}

			var opt = jQuery.extend( {}, optall ),
				isElement = this.nodeType === 1,
				hidden = isElement && jQuery(this).is(":hidden"),
				name, val, p, e,
				parts, start, end, unit,
				method;

			// will store per property easing and be used to determine when an animation is complete
			opt.animatedProperties = {};

			for ( p in prop ) {

				// property name normalization
				name = jQuery.camelCase( p );
				if ( p !== name ) {
					prop[ name ] = prop[ p ];
					delete prop[ p ];
				}

				val = prop[ name ];

				// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
				if ( jQuery.isArray( val ) ) {
					opt.animatedProperties[ name ] = val[ 1 ];
					val = prop[ name ] = val[ 0 ];
				} else {
					opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
				}

				if ( val === "hide" && hidden || val === "show" && !hidden ) {
					return opt.complete.call( this );
				}

				if ( isElement && ( name === "height" || name === "width" ) ) {
					// Make sure that nothing sneaks out
					// Record all 3 overflow attributes because IE does not
					// change the overflow attribute when overflowX and
					// overflowY are set to the same value
					opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];

					// Set display property to inline-block for height/width
					// animations on inline elements that are having width/height animated
					if ( jQuery.css( this, "display" ) === "inline" &&
							jQuery.css( this, "float" ) === "none" ) {

						// inline-level elements accept inline-block;
						// block-level elements need to be inline with layout
						if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
							this.style.display = "inline-block";

						} else {
							this.style.zoom = 1;
						}
					}
				}
			}

			if ( opt.overflow != null ) {
				this.style.overflow = "hidden";
			}

			for ( p in prop ) {
				e = new jQuery.fx( this, opt, p );
				val = prop[ p ];

				if ( rfxtypes.test( val ) ) {

					// Tracks whether to show or hide based on private
					// data attached to the element
					method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
					if ( method ) {
						jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
						e[ method ]();
					} else {
						e[ val ]();
					}

				} else {
					parts = rfxnum.exec( val );
					start = e.cur();

					if ( parts ) {
						end = parseFloat( parts[2] );
						unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );

						// We need to compute starting value
						if ( unit !== "px" ) {
							jQuery.style( this, p, (end || 1) + unit);
							start = ( (end || 1) / e.cur() ) * start;
							jQuery.style( this, p, start + unit);
						}

						// If a +=/-= token was provided, we're doing a relative animation
						if ( parts[1] ) {
							end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
						}

						e.custom( start, end, unit );

					} else {
						e.custom( start, val, "" );
					}
				}
			}

			// For JS strict compliance
			return true;
		}

		return optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},

	stop: function( type, clearQueue, gotoEnd ) {
		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue && type !== false ) {
			this.queue( type || "fx", [] );
		}

		return this.each(function() {
			var index,
				hadTimers = false,
				timers = jQuery.timers,
				data = jQuery._data( this );

			// clear marker counters if we know they won't be
			if ( !gotoEnd ) {
				jQuery._unmark( true, this );
			}

			function stopQueue( elem, data, index ) {
				var hooks = data[ index ];
				jQuery.removeData( elem, index, true );
				hooks.stop( gotoEnd );
			}

			if ( type == null ) {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
						stopQueue( this, data, index );
					}
				}
			} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
				stopQueue( this, data, index );
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
					if ( gotoEnd ) {

						// force the next step to be the last
						timers[ index ]( true );
					} else {
						timers[ index ].saveState();
					}
					hadTimers = true;
					timers.splice( index, 1 );
				}
			}

			// start the next in the queue if the last step wasn't forced
			// timers currently will call their complete callbacks, which will dequeue
			// but only if they were gotoEnd
			if ( !( gotoEnd && hadTimers ) ) {
				jQuery.dequeue( this, type );
			}
		});
	}

});

// Animations created synchronously will run synchronously
function createFxNow() {
	setTimeout( clearFxNow, 0 );
	return ( fxNow = jQuery.now() );
}

function clearFxNow() {
	fxNow = undefined;
}

// Generate parameters to create a standard animation
function genFx( type, num ) {
	var obj = {};

	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
		obj[ this ] = type;
	});

	return obj;
}

// Generate shortcuts for custom animations
jQuery.each({
	slideDown: genFx( "show", 1 ),
	slideUp: genFx( "hide", 1 ),
	slideToggle: genFx( "toggle", 1 ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
});

jQuery.extend({
	speed: function( speed, easing, fn ) {
		var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
			complete: fn || !fn && easing ||
				jQuery.isFunction( speed ) && speed,
			duration: speed,
			easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
		};

		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
			opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;

		// normalize opt.queue - true/undefined/null -> "fx"
		if ( opt.queue == null || opt.queue === true ) {
			opt.queue = "fx";
		}

		// Queueing
		opt.old = opt.complete;

		opt.complete = function( noUnmark ) {
			if ( jQuery.isFunction( opt.old ) ) {
				opt.old.call( this );
			}

			if ( opt.queue ) {
				jQuery.dequeue( this, opt.queue );
			} else if ( noUnmark !== false ) {
				jQuery._unmark( this );
			}
		};

		return opt;
	},

	easing: {
		linear: function( p, n, firstNum, diff ) {
			return firstNum + diff * p;
		},
		swing: function( p, n, firstNum, diff ) {
			return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum;
		}
	},

	timers: [],

	fx: function( elem, options, prop ) {
		this.options = options;
		this.elem = elem;
		this.prop = prop;

		options.orig = options.orig || {};
	}

});

jQuery.fx.prototype = {
	// Simple function for setting a style value
	update: function() {
		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
	},

	// Get the current size
	cur: function() {
		if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
			return this.elem[ this.prop ];
		}

		var parsed,
			r = jQuery.css( this.elem, this.prop );
		// Empty strings, null, undefined and "auto" are converted to 0,
		// complex values such as "rotate(1rad)" are returned as is,
		// simple values such as "10px" are parsed to Float.
		return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
	},

	// Start an animation from one number to another
	custom: function( from, to, unit ) {
		var self = this,
			fx = jQuery.fx;

		this.startTime = fxNow || createFxNow();
		this.end = to;
		this.now = this.start = from;
		this.pos = this.state = 0;
		this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );

		function t( gotoEnd ) {
			return self.step( gotoEnd );
		}

		t.queue = this.options.queue;
		t.elem = this.elem;
		t.saveState = function() {
			if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
				jQuery._data( self.elem, "fxshow" + self.prop, self.start );
			}
		};

		if ( t() && jQuery.timers.push(t) && !timerId ) {
			timerId = setInterval( fx.tick, fx.interval );
		}
	},

	// Simple 'show' function
	show: function() {
		var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );

		// Remember where we started, so that we can go back to it later
		this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
		this.options.show = true;

		// Begin the animation
		// Make sure that we start at a small width/height to avoid any flash of content
		if ( dataShow !== undefined ) {
			// This show is picking up where a previous hide or show left off
			this.custom( this.cur(), dataShow );
		} else {
			this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
		}

		// Start by showing the element
		jQuery( this.elem ).show();
	},

	// Simple 'hide' function
	hide: function() {
		// Remember where we started, so that we can go back to it later
		this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
		this.options.hide = true;

		// Begin the animation
		this.custom( this.cur(), 0 );
	},

	// Each step of an animation
	step: function( gotoEnd ) {
		var p, n, complete,
			t = fxNow || createFxNow(),
			done = true,
			elem = this.elem,
			options = this.options;

		if ( gotoEnd || t >= options.duration + this.startTime ) {
			this.now = this.end;
			this.pos = this.state = 1;
			this.update();

			options.animatedProperties[ this.prop ] = true;

			for ( p in options.animatedProperties ) {
				if ( options.animatedProperties[ p ] !== true ) {
					done = false;
				}
			}

			if ( done ) {
				// Reset the overflow
				if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {

					jQuery.each( [ "", "X", "Y" ], function( index, value ) {
						elem.style[ "overflow" + value ] = options.overflow[ index ];
					});
				}

				// Hide the element if the "hide" operation was done
				if ( options.hide ) {
					jQuery( elem ).hide();
				}

				// Reset the properties, if the item has been hidden or shown
				if ( options.hide || options.show ) {
					for ( p in options.animatedProperties ) {
						jQuery.style( elem, p, options.orig[ p ] );
						jQuery.removeData( elem, "fxshow" + p, true );
						// Toggle data is no longer needed
						jQuery.removeData( elem, "toggle" + p, true );
					}
				}

				// Execute the complete function
				// in the event that the complete function throws an exception
				// we must ensure it won't be called twice. #5684

				complete = options.complete;
				if ( complete ) {

					options.complete = false;
					complete.call( elem );
				}
			}

			return false;

		} else {
			// classical easing cannot be used with an Infinity duration
			if ( options.duration == Infinity ) {
				this.now = t;
			} else {
				n = t - this.startTime;
				this.state = n / options.duration;

				// Perform the easing function, defaults to swing
				this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
				this.now = this.start + ( (this.end - this.start) * this.pos );
			}
			// Perform the next step of the animation
			this.update();
		}

		return true;
	}
};

jQuery.extend( jQuery.fx, {
	tick: function() {
		var timer,
			timers = jQuery.timers,
			i = 0;

		for ( ; i < timers.length; i++ ) {
			timer = timers[ i ];
			// Checks the timer has not already been removed
			if ( !timer() && timers[ i ] === timer ) {
				timers.splice( i--, 1 );
			}
		}

		if ( !timers.length ) {
			jQuery.fx.stop();
		}
	},

	interval: 13,

	stop: function() {
		clearInterval( timerId );
		timerId = null;
	},

	speeds: {
		slow: 600,
		fast: 200,
		// Default speed
		_default: 400
	},

	step: {
		opacity: function( fx ) {
			jQuery.style( fx.elem, "opacity", fx.now );
		},

		_default: function( fx ) {
			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
				fx.elem.style[ fx.prop ] = fx.now + fx.unit;
			} else {
				fx.elem[ fx.prop ] = fx.now;
			}
		}
	}
});

// Adds width/height step functions
// Do not set anything below 0
jQuery.each([ "width", "height" ], function( i, prop ) {
	jQuery.fx.step[ prop ] = function( fx ) {
		jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
	};
});

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.animated = function( elem ) {
		return jQuery.grep(jQuery.timers, function( fn ) {
			return elem === fn.elem;
		}).length;
	};
}

// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {

	if ( !elemdisplay[ nodeName ] ) {

		var body = document.body,
			elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
			display = elem.css( "display" );
		elem.remove();

		// If the simple way fails,
		// get element's real default display by attaching it to a temp iframe
		if ( display === "none" || display === "" ) {
			// No iframe to use yet, so create it
			if ( !iframe ) {
				iframe = document.createElement( "iframe" );
				iframe.frameBorder = iframe.width = iframe.height = 0;
			}

			body.appendChild( iframe );

			// Create a cacheable copy of the iframe document on first call.
			// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
			// document to it; WebKit & Firefox won't allow reusing the iframe document.
			if ( !iframeDoc || !iframe.createElement ) {
				iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
				iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
				iframeDoc.close();
			}

			elem = iframeDoc.createElement( nodeName );

			iframeDoc.body.appendChild( elem );

			display = jQuery.css( elem, "display" );
			body.removeChild( iframe );
		}

		// Store the correct default display
		elemdisplay[ nodeName ] = display;
	}

	return elemdisplay[ nodeName ];
}




var rtable = /^t(?:able|d|h)$/i,
	rroot = /^(?:body|html)$/i;

if ( "getBoundingClientRect" in document.documentElement ) {
	jQuery.fn.offset = function( options ) {
		var elem = this[0], box;

		if ( options ) {
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}

		if ( !elem || !elem.ownerDocument ) {
			return null;
		}

		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}

		try {
			box = elem.getBoundingClientRect();
		} catch(e) {}

		var doc = elem.ownerDocument,
			docElem = doc.documentElement;

		// Make sure we're not dealing with a disconnected DOM node
		if ( !box || !jQuery.contains( docElem, elem ) ) {
			return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
		}

		var body = doc.body,
			win = getWindow(doc),
			clientTop  = docElem.clientTop  || body.clientTop  || 0,
			clientLeft = docElem.clientLeft || body.clientLeft || 0,
			scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
			scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
			top  = box.top  + scrollTop  - clientTop,
			left = box.left + scrollLeft - clientLeft;

		return { top: top, left: left };
	};

} else {
	jQuery.fn.offset = function( options ) {
		var elem = this[0];

		if ( options ) {
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}

		if ( !elem || !elem.ownerDocument ) {
			return null;
		}

		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}

		var computedStyle,
			offsetParent = elem.offsetParent,
			prevOffsetParent = elem,
			doc = elem.ownerDocument,
			docElem = doc.documentElement,
			body = doc.body,
			defaultView = doc.defaultView,
			prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
			top = elem.offsetTop,
			left = elem.offsetLeft;

		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
			if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
				break;
			}

			computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
			top  -= elem.scrollTop;
			left -= elem.scrollLeft;

			if ( elem === offsetParent ) {
				top  += elem.offsetTop;
				left += elem.offsetLeft;

				if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
					top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
					left += parseFloat( computedStyle.borderLeftWidth ) || 0;
				}

				prevOffsetParent = offsetParent;
				offsetParent = elem.offsetParent;
			}

			if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
				top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
				left += parseFloat( computedStyle.borderLeftWidth ) || 0;
			}

			prevComputedStyle = computedStyle;
		}

		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
			top  += body.offsetTop;
			left += body.offsetLeft;
		}

		if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
			top  += Math.max( docElem.scrollTop, body.scrollTop );
			left += Math.max( docElem.scrollLeft, body.scrollLeft );
		}

		return { top: top, left: left };
	};
}

jQuery.offset = {

	bodyOffset: function( body ) {
		var top = body.offsetTop,
			left = body.offsetLeft;

		if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
			top  += parseFloat( jQuery.css(body, "marginTop") ) || 0;
			left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
		}

		return { top: top, left: left };
	},

	setOffset: function( elem, options, i ) {
		var position = jQuery.css( elem, "position" );

		// set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		var curElem = jQuery( elem ),
			curOffset = curElem.offset(),
			curCSSTop = jQuery.css( elem, "top" ),
			curCSSLeft = jQuery.css( elem, "left" ),
			calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
			props = {}, curPosition = {}, curTop, curLeft;

		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;
		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( jQuery.isFunction( options ) ) {
			options = options.call( elem, i, curOffset );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	}
};


jQuery.fn.extend({

	position: function() {
		if ( !this[0] ) {
			return null;
		}

		var elem = this[0],

		// Get *real* offsetParent
		offsetParent = this.offsetParent(),

		// Get correct offsets
		offset       = this.offset(),
		parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();

		// Subtract element margins
		// note: when an element has margin: auto the offsetLeft and marginLeft
		// are the same in Safari causing offset.left to incorrectly be 0
		offset.top  -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
		offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;

		// Add offsetParent borders
		parentOffset.top  += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
		parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;

		// Subtract the two offsets
		return {
			top:  offset.top  - parentOffset.top,
			left: offset.left - parentOffset.left
		};
	},

	offsetParent: function() {
		return this.map(function() {
			var offsetParent = this.offsetParent || document.body;
			while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent;
		});
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
	var method = "scroll" + name;

	jQuery.fn[ method ] = function( val ) {
		var elem, win;

		if ( val === undefined ) {
			elem = this[ 0 ];

			if ( !elem ) {
				return null;
			}

			win = getWindow( elem );

			// Return the scroll offset
			return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
				jQuery.support.boxModel && win.document.documentElement[ method ] ||
					win.document.body[ method ] :
				elem[ method ];
		}

		// Set the scroll offset
		return this.each(function() {
			win = getWindow( this );

			if ( win ) {
				win.scrollTo(
					!i ? val : jQuery( win ).scrollLeft(),
					 i ? val : jQuery( win ).scrollTop()
				);

			} else {
				this[ method ] = val;
			}
		});
	};
});

function getWindow( elem ) {
	return jQuery.isWindow( elem ) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
}




// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {

	var type = name.toLowerCase();

	// innerHeight and innerWidth
	jQuery.fn[ "inner" + name ] = function() {
		var elem = this[0];
		return elem ?
			elem.style ?
			parseFloat( jQuery.css( elem, type, "padding" ) ) :
			this[ type ]() :
			null;
	};

	// outerHeight and outerWidth
	jQuery.fn[ "outer" + name ] = function( margin ) {
		var elem = this[0];
		return elem ?
			elem.style ?
			parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
			this[ type ]() :
			null;
	};

	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		var elem = this[0];
		if ( !elem ) {
			return size == null ? null : this;
		}

		if ( jQuery.isFunction( size ) ) {
			return this.each(function( i ) {
				var self = jQuery( this );
				self[ type ]( size.call( this, i, self[ type ]() ) );
			});
		}

		if ( jQuery.isWindow( elem ) ) {
			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
			var docElemProp = elem.document.documentElement[ "client" + name ],
				body = elem.document.body;
			return elem.document.compatMode === "CSS1Compat" && docElemProp ||
				body && body[ "client" + name ] || docElemProp;

		// Get document width or height
		} else if ( elem.nodeType === 9 ) {
			// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
			return Math.max(
				elem.documentElement["client" + name],
				elem.body["scroll" + name], elem.documentElement["scroll" + name],
				elem.body["offset" + name], elem.documentElement["offset" + name]
			);

		// Get or set width or height on the element
		} else if ( size === undefined ) {
			var orig = jQuery.css( elem, type ),
				ret = parseFloat( orig );

			return jQuery.isNumeric( ret ) ? ret : orig;

		// Set the width or height on the element (default to pixels if value is unitless)
		} else {
			return this.css( type, typeof size === "string" ? size : size + "px" );
		}
	};

});




// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
	define( "jquery", [], function () { return jQuery; } );
}



})( window );
;
/*! jQuery UI - v1.12.1 - 2020-11-05
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, focusable.js, form-reset-mixin.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/draggable.js, widgets/resizable.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/slider.js, widgets/tooltip.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.ui = $.ui || {};

var version = $.ui.version = "1.12.1";


/*!
 * jQuery UI Widget 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/



var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;

$.cleanData = ( function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
			try {

				// Only trigger remove when necessary to save time
				events = $._data( elem, "events" );
				if ( events && events.remove ) {
					$( elem ).triggerHandler( "remove" );
				}

			// Http://bugs.jquery.com/ticket/8235
			} catch ( e ) {}
		}
		orig( elems );
	};
} )( $.cleanData );

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

	var namespace = name.split( "." )[ 0 ];
	name = name.split( "." )[ 1 ];
	var fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	if ( $.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

	// Create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

	// We need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = ( function() {
			function _super() {
				return base.prototype[ prop ].apply( this, arguments );
			}

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	} );

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string";
		var args = widgetSlice.call( arguments, 1 );
		var returnValue = this;

		if ( isMethodCall ) {

			// If this is an empty collection, we need to have the instance method
			// return undefined instead of the jQuery instance
			if ( !this.length && options === "instance" ) {
				returnValue = undefined;
			} else {
				this.each( function() {
					var methodValue;
					var instance = $.data( this, fullName );

					if ( options === "instance" ) {
						returnValue = instance;
						return false;
					}

					if ( !instance ) {
						return $.error( "cannot call methods on " + name +
							" prior to initialization; " +
							"attempted to call method '" + options + "'" );
					}

					if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
						return $.error( "no such method '" + options + "' for " + name +
							" widget instance" );
					}

					methodValue = instance[ options ].apply( instance, args );

					if ( methodValue !== instance && methodValue !== undefined ) {
						returnValue = methodValue && methodValue.jquery ?
							returnValue.pushStack( methodValue.get() ) :
							methodValue;
						return false;
					}
				} );
			}
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat( args ) );
			}

			this.each( function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			} );
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;
		var parts;
		var curOption;
		var i;

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

			// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

		// If the widget is becoming disabled, then nothing is interactive
		if ( value ) {
			this._removeClass( this.hoverable, null, "ui-state-hover" );
			this._removeClass( this.focusable, null, "ui-state-focus" );
		}
	},

	enable: function() {
		return this._setOptions( { disabled: false } );
	},

	disable: function() {
		return this._setOptions( { disabled: true } );
	},

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i < classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					current = $( $.unique( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption && options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		this._on( options.element, {
			"remove": "_untrackClassesElement"
		} );

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_untrackClassesElement: function( event ) {
		var that = this;
		$.each( that.classesElementLookup, function( key, value ) {
			if ( $.inArray( event.target, value ) !== -1 ) {
				that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
			}
		} );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement;
		var instance = this;

		// No suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// No element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

				// Allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
						$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// Copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

	_off: function( element, eventName ) {
		eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.off( eventName ).off( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
			},
			mouseleave: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
			}
		} );
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
			},
			focusout: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
			}
		} );
	},

	_trigger: function( type, event, data ) {
		var prop, orig;
		var callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// Copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

var widget = $.widget;


/*!
 * jQuery UI Position 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */

//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/


( function() {
var cachedScrollbarWidth,
	max = Math.max,
	abs = Math.abs,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function getDimensions( elem ) {
	var raw = elem[ 0 ];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( $.isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div " +
				"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
				"<div style='height:100px;width:auto;'></div></div>" ),
			innerDiv = div.children()[ 0 ];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[ 0 ].clientWidth;
		}

		div.remove();

		return ( cachedScrollbarWidth = w1 - w2 );
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isWindow = $.isWindow( withinElement[ 0 ] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
			hasOffset = !isWindow && !isDocument;
		return {
			element: withinElement,
			isWindow: isWindow,
			isDocument: isDocument,
			offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),
			width: withinElement.outerWidth(),
			height: withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// Make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
		target = $( options.of ),
		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[ 0 ].preventDefault ) {

		// Force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;

	// Clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// Force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1 ) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// Calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// Reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	} );

	// Normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each( function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
				scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
				scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				} );
			}
		} );

		if ( options.using ) {

			// Adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	} );
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// Element is wider than within
			if ( data.collisionWidth > outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;

			// Too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;

			// Adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// Element is taller than within
			if ( data.collisionHeight > outerHeight ) {

				// Element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;

			// Too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;

			// Adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
					outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
					atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
					outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
					offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

} )();

var position = $.ui.position;


/*!
 * jQuery UI :data 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/


var data = $.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo( function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		} ) :

		// Support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		}
} );

/*!
 * jQuery UI Disable Selection 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/

// This file is deprecated


var disableSelection = $.fn.extend( {
	disableSelection: ( function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.on( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			} );
		};
	} )(),

	enableSelection: function() {
		return this.off( ".ui-disableSelection" );
	}
} );


/*!
 * jQuery UI Focusable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/



// Selectors
$.ui.focusable = function( element, hasTabindex ) {
	var map, mapName, img, focusableIfVisible, fieldset,
		nodeName = element.nodeName.toLowerCase();

	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap='#" + mapName + "']" );
		return img.length > 0 && img.is( ":visible" );
	}

	if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
		focusableIfVisible = !element.disabled;

		if ( focusableIfVisible ) {

			// Form controls within a disabled fieldset are disabled.
			// However, controls within the fieldset's legend do not get disabled.
			// Since controls generally aren't placed inside legends, we skip
			// this portion of the check.
			fieldset = $( element ).closest( "fieldset" )[ 0 ];
			if ( fieldset ) {
				focusableIfVisible = !fieldset.disabled;
			}
		}
	} else if ( "a" === nodeName ) {
		focusableIfVisible = element.href || hasTabindex;
	} else {
		focusableIfVisible = hasTabindex;
	}

	return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};

// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
	var visibility = element.css( "visibility" );
	while ( visibility === "inherit" ) {
		element = element.parent();
		visibility = element.css( "visibility" );
	}
	return visibility !== "hidden";
}

$.extend( $.expr[ ":" ], {
	focusable: function( element ) {
		return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
	}
} );

var focusable = $.ui.focusable;




// Support: IE8 Only
// IE8 does not support the form attribute and when it is supplied. It overwrites the form prop
// with a string, so we need to find the proper form.
var form = $.fn.form = function() {
	return typeof this[ 0 ].form === "string" ? this.closest( "form" ) : $( this[ 0 ].form );
};


/*!
 * jQuery UI Form Reset Mixin 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Form Reset Mixin
//>>group: Core
//>>description: Refresh input widgets when their form is reset
//>>docs: http://api.jqueryui.com/form-reset-mixin/



var formResetMixin = $.ui.formResetMixin = {
	_formResetHandler: function() {
		var form = $( this );

		// Wait for the form reset to actually happen before refreshing
		setTimeout( function() {
			var instances = form.data( "ui-form-reset-instances" );
			$.each( instances, function() {
				this.refresh();
			} );
		} );
	},

	_bindFormResetHandler: function() {
		this.form = this.element.form();
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" ) || [];
		if ( !instances.length ) {

			// We don't use _on() here because we use a single event handler per form
			this.form.on( "reset.ui-form-reset", this._formResetHandler );
		}
		instances.push( this );
		this.form.data( "ui-form-reset-instances", instances );
	},

	_unbindFormResetHandler: function() {
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" );
		instances.splice( $.inArray( this, instances ), 1 );
		if ( instances.length ) {
			this.form.data( "ui-form-reset-instances", instances );
		} else {
			this.form
				.removeData( "ui-form-reset-instances" )
				.off( "reset.ui-form-reset" );
		}
	}
};


/*!
 * jQuery UI Keycode 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/


var keycode = $.ui.keyCode = {
	BACKSPACE: 8,
	COMMA: 188,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	LEFT: 37,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SPACE: 32,
	TAB: 9,
	UP: 38
};




// Internal use only
var escapeSelector = $.ui.escapeSelector = ( function() {
	var selectorEscape = /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;
	return function( selector ) {
		return selector.replace( selectorEscape, "\\$1" );
	};
} )();


/*!
 * jQuery UI Labels 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: labels
//>>group: Core
//>>description: Find all the labels associated with a given input
//>>docs: http://api.jqueryui.com/labels/



var labels = $.fn.labels = function() {
	var ancestor, selector, id, labels, ancestors;

	// Check control.labels first
	if ( this[ 0 ].labels && this[ 0 ].labels.length ) {
		return this.pushStack( this[ 0 ].labels );
	}

	// Support: IE <= 11, FF <= 37, Android <= 2.3 only
	// Above browsers do not support control.labels. Everything below is to support them
	// as well as document fragments. control.labels does not work on document fragments
	labels = this.eq( 0 ).parents( "label" );

	// Look for the label based on the id
	id = this.attr( "id" );
	if ( id ) {

		// We don't search against the document in case the element
		// is disconnected from the DOM
		ancestor = this.eq( 0 ).parents().last();

		// Get a full set of top level ancestors
		ancestors = ancestor.add( ancestor.length ? ancestor.siblings() : this.siblings() );

		// Create a selector for the label based on the id
		selector = "label[for='" + $.ui.escapeSelector( id ) + "']";

		labels = labels.add( ancestors.find( selector ).addBack( selector ) );

	}

	// Return whatever we have found for labels
	return this.pushStack( labels );
};


/*!
 * jQuery UI Scroll Parent 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/



var scrollParent = $.fn.scrollParent = function( includeHidden ) {
	var position = this.css( "position" ),
		excludeStaticParent = position === "absolute",
		overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
		scrollParent = this.parents().filter( function() {
			var parent = $( this );
			if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
				return false;
			}
			return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
				parent.css( "overflow-x" ) );
		} ).eq( 0 );

	return position === "fixed" || !scrollParent.length ?
		$( this[ 0 ].ownerDocument || document ) :
		scrollParent;
};


/*!
 * jQuery UI Tabbable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :tabbable Selector
//>>group: Core
//>>description: Selects elements which can be tabbed to.
//>>docs: http://api.jqueryui.com/tabbable-selector/



var tabbable = $.extend( $.expr[ ":" ], {
	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			hasTabindex = tabIndex != null;
		return ( !hasTabindex || tabIndex >= 0 ) && $.ui.focusable( element, hasTabindex );
	}
} );


/*!
 * jQuery UI Unique ID 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/



var uniqueId = $.fn.extend( {
	uniqueId: ( function() {
		var uuid = 0;

		return function() {
			return this.each( function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			} );
		};
	} )(),

	removeUniqueId: function() {
		return this.each( function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		} );
	}
} );




// This file is deprecated
var ie = $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

/*!
 * jQuery UI Mouse 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/



var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
} );

var widgetsMouse = $.widget( "ui.mouse", {
	version: "1.12.1",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on( "mousedown." + this.widgetName, function( event ) {
				return that._mouseDown( event );
			} )
			.on( "click." + this.widgetName, function( event ) {
				if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
					$.removeData( event.target, that.widgetName + ".preventClickEvent" );
					event.stopImmediatePropagation();
					return false;
				}
			} );

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off( "." + this.widgetName );
		if ( this._mouseMoveDelegate ) {
			this.document
				.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
				.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
		}
	},

	_mouseDown: function( event ) {

		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		( this._mouseStarted && this._mouseUp( event ) );

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = ( event.which === 1 ),

			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
				$( event.target ).closest( this.options.cancel ).length : false );
		if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if ( !this.mouseDelayMet ) {
			this._mouseDelayTimer = setTimeout( function() {
				that.mouseDelayMet = true;
			}, this.options.delay );
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted = ( this._mouseStart( event ) !== false );
			if ( !this._mouseStarted ) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
			$.removeData( event.target, this.widgetName + ".preventClickEvent" );
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function( event ) {
			return that._mouseMove( event );
		};
		this._mouseUpDelegate = function( event ) {
			return that._mouseUp( event );
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {

			// IE mouseup check - mouseup happened when mouse was out of window
			if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
					!event.button ) {
				return this._mouseUp( event );

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {

				// Support: Safari <=8 - 9
				// Safari sets which to 0 if you press any of the following keys
				// during a drag (#14461)
				if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
						event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
					this.ignoreMissingWhich = true;
				} else if ( !this.ignoreMissingWhich ) {
					return this._mouseUp( event );
				}
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if ( this._mouseStarted ) {
			this._mouseDrag( event );
			return event.preventDefault();
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted =
				( this._mouseStart( this._mouseDownEvent, event ) !== false );
			( this._mouseStarted ? this._mouseDrag( event ) : this._mouseUp( event ) );
		}

		return !this._mouseStarted;
	},

	_mouseUp: function( event ) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if ( this._mouseStarted ) {
			this._mouseStarted = false;

			if ( event.target === this._mouseDownEvent.target ) {
				$.data( event.target, this.widgetName + ".preventClickEvent", true );
			}

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

	_mouseDistanceMet: function( event ) {
		return ( Math.max(
				Math.abs( this._mouseDownEvent.pageX - event.pageX ),
				Math.abs( this._mouseDownEvent.pageY - event.pageY )
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function( /* event */ ) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function( /* event */ ) {},
	_mouseDrag: function( /* event */ ) {},
	_mouseStop: function( /* event */ ) {},
	_mouseCapture: function( /* event */ ) { return true; }
} );




// $.ui.plugin is deprecated. Use $.widget() extensions instead.
var plugin = $.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode ||
				instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};



var safeActiveElement = $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
	try {
		activeElement = document.activeElement;
	} catch ( error ) {
		activeElement = document.body;
	}

	// Support: IE 9 - 11 only
	// IE may return null instead of an element
	// Interestingly, this only seems to occur when NOT in an iframe
	if ( !activeElement ) {
		activeElement = document.body;
	}

	// Support: IE 11 only
	// IE11 returns a seemingly empty object in some cases when accessing
	// document.activeElement from an <iframe>
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};



var safeBlur = $.ui.safeBlur = function( element ) {

	// Support: IE9 - 10 only
	// If the <body> is blurred, IE will switch windows, see #9420
	if ( element && element.nodeName.toLowerCase() !== "body" ) {
		$( element ).trigger( "blur" );
	}
};


/*!
 * jQuery UI Draggable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Draggable
//>>group: Interactions
//>>description: Enables dragging functionality for any element.
//>>docs: http://api.jqueryui.com/draggable/
//>>demos: http://jqueryui.com/draggable/
//>>css.structure: ../../themes/base/draggable.css



$.widget( "ui.draggable", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// Callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if ( this.options.addClasses ) {
			this._addClass( "ui-draggable" );
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var o = this.options;

		// Among others, prevent a drag on a resizable-handle
		if ( this.helper || o.disabled ||
				$( event.target ).closest( ".ui-resizable-handle" ).length > 0 ) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle( event );
		if ( !this.handle ) {
			return false;
		}

		this._blurActiveElement( event );

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
			target = $( event.target );

		// Don't blur if the event occurred on an element that is within
		// the currently focused element
		// See #10527, #12472
		if ( target.closest( activeElement ).length ) {
			return;
		}

		// Blur any element that currently has focus, see #4261
		$.ui.safeBlur( activeElement );
	},

	_mouseStart: function( event ) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		this._addClass( this.helper, "ui-draggable-dragging" );

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter( function() {
				return $( this ).css( "position" ) === "fixed";
			} ).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		( o.cursorAt && this._adjustOffsetFromHelper( o.cursorAt ) );

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if ( this._trigger( "start", event ) === false ) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		// Execute the drag once - this causes the helper not to be visible before getting its
		// correct position
		this._mouseDrag( event, true );

		// If the ddmanager is used for droppables, inform the manager that dragging has started
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart( this, event );
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function( event, noPropagation ) {

		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Call plugins and callbacks and use the resulting position if something is returned
		if ( !noPropagation ) {
			var ui = this._uiHash();
			if ( this._trigger( "drag", event, ui ) === false ) {
				this._mouseUp( new $.Event( "mouseup", event ) );
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		return false;
	},

	_mouseStop: function( event ) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			dropped = $.ui.ddmanager.drop( this, event );
		}

		//if a drop comes from outside (a sortable)
		if ( this.dropped ) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ( ( this.options.revert === "invalid" && !dropped ) ||
				( this.options.revert === "valid" && dropped ) ||
				this.options.revert === true || ( $.isFunction( this.options.revert ) &&
				this.options.revert.call( this.element, dropped ) )
		) {
			$( this.helper ).animate(
				this.originalPosition,
				parseInt( this.options.revertDuration, 10 ),
				function() {
					if ( that._trigger( "stop", event ) !== false ) {
						that._clear();
					}
				}
			);
		} else {
			if ( this._trigger( "stop", event ) !== false ) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		// If the ddmanager is used for droppables, inform the manager that dragging has stopped
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop( this, event );
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {

			// The interaction is over; whether or not the click resulted in a drag,
			// focus the element
			this.element.trigger( "focus" );
		}

		return $.ui.mouse.prototype._mouseUp.call( this, event );
	},

	cancel: function() {

		if ( this.helper.is( ".ui-draggable-dragging" ) ) {
			this._mouseUp( new $.Event( "mouseup", { target: this.element[ 0 ] } ) );
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function( event ) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this._addClass( this.handleElement, "ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this._removeClass( this.handleElement, "ui-draggable-handle" );
	},

	_createHelper: function( event ) {

		var o = this.options,
			helperIsFunction = $.isFunction( o.helper ),
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if ( !helper.parents( "body" ).length ) {
			helper.appendTo( ( o.appendTo === "parent" ?
				this.element[ 0 ].parentNode :
				o.appendTo ) );
		}

		// Http://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if ( helper[ 0 ] !== this.element[ 0 ] &&
				!( /(fixed|absolute)/ ).test( helper.css( "position" ) ) ) {
			helper.css( "position", "absolute" );
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( $.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== document &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
			left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: ( parseInt( this.element.css( "marginLeft" ), 10 ) || 0 ),
			top: ( parseInt( this.element.css( "marginTop" ), 10 ) || 0 ),
			right: ( parseInt( this.element.css( "marginRight" ), 10 ) || 0 ),
			bottom: ( parseInt( this.element.css( "marginBottom" ), 10 ) || 0 )
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() -
					this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() +
					( $( window ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document" ) {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod )
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ) {
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if ( event.pageX - this.offset.click.left < containment[ 0 ] ) {
					pageX = containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < containment[ 1 ] ) {
					pageY = containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > containment[ 2 ] ) {
					pageX = containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > containment[ 3 ] ) {
					pageY = containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {

				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
				// argument errors in IE (see ticket #6950)
				top = o.grid[ 1 ] ? this.originalPageY + Math.round( ( pageY -
					this.originalPageY ) / o.grid[ 1 ] ) * o.grid[ 1 ] : this.originalPageY;
				pageY = containment ? ( ( top - this.offset.click.top >= containment[ 1 ] ||
					top - this.offset.click.top > containment[ 3 ] ) ?
						top :
						( ( top - this.offset.click.top >= containment[ 1 ] ) ?
							top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) : top;

				left = o.grid[ 0 ] ? this.originalPageX +
					Math.round( ( pageX - this.originalPageX ) / o.grid[ 0 ] ) * o.grid[ 0 ] :
					this.originalPageX;
				pageX = containment ? ( ( left - this.offset.click.left >= containment[ 0 ] ||
					left - this.offset.click.left > containment[ 2 ] ) ?
						left :
						( ( left - this.offset.click.left >= containment[ 0 ] ) ?
							left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this._removeClass( this.helper, "ui-draggable-dragging" );
		if ( this.helper[ 0 ] !== this.element[ 0 ] && !this.cancelHelperRemoval ) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

} );

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each( function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// RefreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger( "activate", event, uiSortable );
			}
		} );
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop( event );

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {

				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		} );
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {

					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				} );
			}

			if ( innermostIntersecting ) {

				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					// Store draggable's parent in case we need to reappend to it later.
					draggable._parent = ui.helper.parent();

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );

					// Hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );

					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {

				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// Restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Restore and recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways. (#8809, #10669)
					ui.helper.appendTo( draggable._parent );
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );
				}
			}
		} );
	}
} );

$.ui.plugin.add( "draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if ( t.css( "cursor" ) ) {
			o._cursor = t.css( "cursor" );
		}
		t.css( "cursor", o.cursor );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._cursor ) {
			$( "body" ).css( "cursor", o._cursor );
		}
	}
} );

$.ui.plugin.add( "draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if ( t.css( "opacity" ) ) {
			o._opacity = t.css( "opacity" );
		}
		t.css( "opacity", o.opacity );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._opacity ) {
			$( ui.helper ).css( "opacity", o._opacity );
		}
	}
} );

$.ui.plugin.add( "draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] &&
				i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY <
						o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX <
						o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if ( !o.axis || o.axis !== "x" ) {
				if ( event.pageY - $( document ).scrollTop() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() - o.scrollSpeed );
				} else if ( $( window ).height() - ( event.pageY - $( document ).scrollTop() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() + o.scrollSpeed );
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( event.pageX - $( document ).scrollLeft() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() - o.scrollSpeed
					);
				} else if ( $( window ).width() - ( event.pageX - $( document ).scrollLeft() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() + o.scrollSpeed
					);
				}
			}

		}

		if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( i, event );
		}

	}
} );

$.ui.plugin.add( "draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$( o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap )
			.each( function() {
				var $t = $( this ),
					$o = $t.offset();
				if ( this !== i.element[ 0 ] ) {
					i.snapElements.push( {
						item: this,
						width: $t.outerWidth(), height: $t.outerHeight(),
						top: $o.top, left: $o.left
					} );
				}
			} );

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for ( i = inst.snapElements.length - 1; i >= 0; i-- ) {

			l = inst.snapElements[ i ].left - inst.margins.left;
			r = l + inst.snapElements[ i ].width;
			t = inst.snapElements[ i ].top - inst.margins.top;
			b = t + inst.snapElements[ i ].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
					!$.contains( inst.snapElements[ i ].item.ownerDocument,
					inst.snapElements[ i ].item ) ) {
				if ( inst.snapElements[ i ].snapping ) {
					( inst.options.snap.release &&
						inst.options.snap.release.call(
							inst.element,
							event,
							$.extend( inst._uiHash(), { snapItem: inst.snapElements[ i ].item } )
						) );
				}
				inst.snapElements[ i ].snapping = false;
				continue;
			}

			if ( o.snapMode !== "inner" ) {
				ts = Math.abs( t - y2 ) <= d;
				bs = Math.abs( b - y1 ) <= d;
				ls = Math.abs( l - x2 ) <= d;
				rs = Math.abs( r - x1 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l - inst.helperProportions.width
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r
					} ).left;
				}
			}

			first = ( ts || bs || ls || rs );

			if ( o.snapMode !== "outer" ) {
				ts = Math.abs( t - y1 ) <= d;
				bs = Math.abs( b - y2 ) <= d;
				ls = Math.abs( l - x1 ) <= d;
				rs = Math.abs( r - x2 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r - inst.helperProportions.width
					} ).left;
				}
			}

			if ( !inst.snapElements[ i ].snapping && ( ts || bs || ls || rs || first ) ) {
				( inst.options.snap.snap &&
					inst.options.snap.snap.call(
						inst.element,
						event,
						$.extend( inst._uiHash(), {
							snapItem: inst.snapElements[ i ].item
						} ) ) );
			}
			inst.snapElements[ i ].snapping = ( ts || bs || ls || rs || first );

		}

	}
} );

$.ui.plugin.add( "draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray( $( o.stack ) ).sort( function( a, b ) {
				return ( parseInt( $( a ).css( "zIndex" ), 10 ) || 0 ) -
					( parseInt( $( b ).css( "zIndex" ), 10 ) || 0 );
			} );

		if ( !group.length ) { return; }

		min = parseInt( $( group[ 0 ] ).css( "zIndex" ), 10 ) || 0;
		$( group ).each( function( i ) {
			$( this ).css( "zIndex", min + i );
		} );
		this.css( "zIndex", ( min + group.length ) );
	}
} );

$.ui.plugin.add( "draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if ( t.css( "zIndex" ) ) {
			o._zIndex = t.css( "zIndex" );
		}
		t.css( "zIndex", o.zIndex );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if ( o._zIndex ) {
			$( ui.helper ).css( "zIndex", o._zIndex );
		}
	}
} );

var widgetsDraggable = $.ui.draggable;


/*!
 * jQuery UI Resizable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Resizable
//>>group: Interactions
//>>description: Enables resize functionality for any element.
//>>docs: http://api.jqueryui.com/resizable/
//>>demos: http://jqueryui.com/resizable/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/resizable.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.resizable", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		classes: {
			"ui-resizable-se": "ui-icon ui-icon-gripsmall-diagonal-se"
		},
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,

		// See #7960
		zIndex: 90,

		// Callbacks
		resize: null,
		start: null,
		stop: null
	},

	_num: function( value ) {
		return parseFloat( value ) || 0;
	},

	_isNumber: function( value ) {
		return !isNaN( parseFloat( value ) );
	},

	_hasScroll: function( el, a ) {

		if ( $( el ).css( "overflow" ) === "hidden" ) {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	_create: function() {

		var margins,
			o = this.options,
			that = this;
		this._addClass( "ui-resizable" );

		$.extend( this, {
			_aspectRatio: !!( o.aspectRatio ),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
		} );

		// Wrap the element if it cannot hold child nodes
		if ( this.element[ 0 ].nodeName.match( /^(canvas|textarea|input|select|button|img)$/i ) ) {

			this.element.wrap(
				$( "<div class='ui-wrapper' style='overflow: hidden;'></div>" ).css( {
					position: this.element.css( "position" ),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css( "top" ),
					left: this.element.css( "left" )
				} )
			);

			this.element = this.element.parent().data(
				"ui-resizable", this.element.resizable( "instance" )
			);

			this.elementIsWrapper = true;

			margins = {
				marginTop: this.originalElement.css( "marginTop" ),
				marginRight: this.originalElement.css( "marginRight" ),
				marginBottom: this.originalElement.css( "marginBottom" ),
				marginLeft: this.originalElement.css( "marginLeft" )
			};

			this.element.css( margins );
			this.originalElement.css( "margin", 0 );

			// support: Safari
			// Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css( "resize" );
			this.originalElement.css( "resize", "none" );

			this._proportionallyResizeElements.push( this.originalElement.css( {
				position: "static",
				zoom: 1,
				display: "block"
			} ) );

			// Support: IE9
			// avoid IE jump (hard set the margin)
			this.originalElement.css( margins );

			this._proportionallyResize();
		}

		this._setupHandles();

		if ( o.autoHide ) {
			$( this.element )
				.on( "mouseenter", function() {
					if ( o.disabled ) {
						return;
					}
					that._removeClass( "ui-resizable-autohide" );
					that._handles.show();
				} )
				.on( "mouseleave", function() {
					if ( o.disabled ) {
						return;
					}
					if ( !that.resizing ) {
						that._addClass( "ui-resizable-autohide" );
						that._handles.hide();
					}
				} );
		}

		this._mouseInit();
	},

	_destroy: function() {

		this._mouseDestroy();

		var wrapper,
			_destroy = function( exp ) {
				$( exp )
					.removeData( "resizable" )
					.removeData( "ui-resizable" )
					.off( ".resizable" )
					.find( ".ui-resizable-handle" )
						.remove();
			};

		// TODO: Unwrap at same DOM position
		if ( this.elementIsWrapper ) {
			_destroy( this.element );
			wrapper = this.element;
			this.originalElement.css( {
				position: wrapper.css( "position" ),
				width: wrapper.outerWidth(),
				height: wrapper.outerHeight(),
				top: wrapper.css( "top" ),
				left: wrapper.css( "left" )
			} ).insertAfter( wrapper );
			wrapper.remove();
		}

		this.originalElement.css( "resize", this.originalResizeStyle );
		_destroy( this.originalElement );

		return this;
	},

	_setOption: function( key, value ) {
		this._super( key, value );

		switch ( key ) {
		case "handles":
			this._removeHandles();
			this._setupHandles();
			break;
		default:
			break;
		}
	},

	_setupHandles: function() {
		var o = this.options, handle, i, n, hname, axis, that = this;
		this.handles = o.handles ||
			( !$( ".ui-resizable-handle", this.element ).length ?
				"e,s,se" : {
					n: ".ui-resizable-n",
					e: ".ui-resizable-e",
					s: ".ui-resizable-s",
					w: ".ui-resizable-w",
					se: ".ui-resizable-se",
					sw: ".ui-resizable-sw",
					ne: ".ui-resizable-ne",
					nw: ".ui-resizable-nw"
				} );

		this._handles = $();
		if ( this.handles.constructor === String ) {

			if ( this.handles === "all" ) {
				this.handles = "n,e,s,w,se,sw,ne,nw";
			}

			n = this.handles.split( "," );
			this.handles = {};

			for ( i = 0; i < n.length; i++ ) {

				handle = $.trim( n[ i ] );
				hname = "ui-resizable-" + handle;
				axis = $( "<div>" );
				this._addClass( axis, "ui-resizable-handle " + hname );

				axis.css( { zIndex: o.zIndex } );

				this.handles[ handle ] = ".ui-resizable-" + handle;
				this.element.append( axis );
			}

		}

		this._renderAxis = function( target ) {

			var i, axis, padPos, padWrapper;

			target = target || this.element;

			for ( i in this.handles ) {

				if ( this.handles[ i ].constructor === String ) {
					this.handles[ i ] = this.element.children( this.handles[ i ] ).first().show();
				} else if ( this.handles[ i ].jquery || this.handles[ i ].nodeType ) {
					this.handles[ i ] = $( this.handles[ i ] );
					this._on( this.handles[ i ], { "mousedown": that._mouseDown } );
				}

				if ( this.elementIsWrapper &&
						this.originalElement[ 0 ]
							.nodeName
							.match( /^(textarea|input|select|button)$/i ) ) {
					axis = $( this.handles[ i ], this.element );

					padWrapper = /sw|ne|nw|se|n|s/.test( i ) ?
						axis.outerHeight() :
						axis.outerWidth();

					padPos = [ "padding",
						/ne|nw|n/.test( i ) ? "Top" :
						/se|sw|s/.test( i ) ? "Bottom" :
						/^e$/.test( i ) ? "Right" : "Left" ].join( "" );

					target.css( padPos, padWrapper );

					this._proportionallyResize();
				}

				this._handles = this._handles.add( this.handles[ i ] );
			}
		};

		// TODO: make renderAxis a prototype function
		this._renderAxis( this.element );

		this._handles = this._handles.add( this.element.find( ".ui-resizable-handle" ) );
		this._handles.disableSelection();

		this._handles.on( "mouseover", function() {
			if ( !that.resizing ) {
				if ( this.className ) {
					axis = this.className.match( /ui-resizable-(se|sw|ne|nw|n|e|s|w)/i );
				}
				that.axis = axis && axis[ 1 ] ? axis[ 1 ] : "se";
			}
		} );

		if ( o.autoHide ) {
			this._handles.hide();
			this._addClass( "ui-resizable-autohide" );
		}
	},

	_removeHandles: function() {
		this._handles.remove();
	},

	_mouseCapture: function( event ) {
		var i, handle,
			capture = false;

		for ( i in this.handles ) {
			handle = $( this.handles[ i ] )[ 0 ];
			if ( handle === event.target || $.contains( handle, event.target ) ) {
				capture = true;
			}
		}

		return !this.options.disabled && capture;
	},

	_mouseStart: function( event ) {

		var curleft, curtop, cursor,
			o = this.options,
			el = this.element;

		this.resizing = true;

		this._renderProxy();

		curleft = this._num( this.helper.css( "left" ) );
		curtop = this._num( this.helper.css( "top" ) );

		if ( o.containment ) {
			curleft += $( o.containment ).scrollLeft() || 0;
			curtop += $( o.containment ).scrollTop() || 0;
		}

		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };

		this.size = this._helper ? {
				width: this.helper.width(),
				height: this.helper.height()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.originalSize = this._helper ? {
				width: el.outerWidth(),
				height: el.outerHeight()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.sizeDiff = {
			width: el.outerWidth() - el.width(),
			height: el.outerHeight() - el.height()
		};

		this.originalPosition = { left: curleft, top: curtop };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		this.aspectRatio = ( typeof o.aspectRatio === "number" ) ?
			o.aspectRatio :
			( ( this.originalSize.width / this.originalSize.height ) || 1 );

		cursor = $( ".ui-resizable-" + this.axis ).css( "cursor" );
		$( "body" ).css( "cursor", cursor === "auto" ? this.axis + "-resize" : cursor );

		this._addClass( "ui-resizable-resizing" );
		this._propagate( "start", event );
		return true;
	},

	_mouseDrag: function( event ) {

		var data, props,
			smp = this.originalMousePosition,
			a = this.axis,
			dx = ( event.pageX - smp.left ) || 0,
			dy = ( event.pageY - smp.top ) || 0,
			trigger = this._change[ a ];

		this._updatePrevProperties();

		if ( !trigger ) {
			return false;
		}

		data = trigger.apply( this, [ event, dx, dy ] );

		this._updateVirtualBoundaries( event.shiftKey );
		if ( this._aspectRatio || event.shiftKey ) {
			data = this._updateRatio( data, event );
		}

		data = this._respectSize( data, event );

		this._updateCache( data );

		this._propagate( "resize", event );

		props = this._applyChanges();

		if ( !this._helper && this._proportionallyResizeElements.length ) {
			this._proportionallyResize();
		}

		if ( !$.isEmptyObject( props ) ) {
			this._updatePrevProperties();
			this._trigger( "resize", event, this.ui() );
			this._applyChanges();
		}

		return false;
	},

	_mouseStop: function( event ) {

		this.resizing = false;
		var pr, ista, soffseth, soffsetw, s, left, top,
			o = this.options, that = this;

		if ( this._helper ) {

			pr = this._proportionallyResizeElements;
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName );
			soffseth = ista && this._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = {
				width: ( that.helper.width()  - soffsetw ),
				height: ( that.helper.height() - soffseth )
			};
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null;
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

			if ( !o.animate ) {
				this.element.css( $.extend( s, { top: top, left: left } ) );
			}

			that.helper.height( that.size.height );
			that.helper.width( that.size.width );

			if ( this._helper && !o.animate ) {
				this._proportionallyResize();
			}
		}

		$( "body" ).css( "cursor", "auto" );

		this._removeClass( "ui-resizable-resizing" );

		this._propagate( "stop", event );

		if ( this._helper ) {
			this.helper.remove();
		}

		return false;

	},

	_updatePrevProperties: function() {
		this.prevPosition = {
			top: this.position.top,
			left: this.position.left
		};
		this.prevSize = {
			width: this.size.width,
			height: this.size.height
		};
	},

	_applyChanges: function() {
		var props = {};

		if ( this.position.top !== this.prevPosition.top ) {
			props.top = this.position.top + "px";
		}
		if ( this.position.left !== this.prevPosition.left ) {
			props.left = this.position.left + "px";
		}
		if ( this.size.width !== this.prevSize.width ) {
			props.width = this.size.width + "px";
		}
		if ( this.size.height !== this.prevSize.height ) {
			props.height = this.size.height + "px";
		}

		this.helper.css( props );

		return props;
	},

	_updateVirtualBoundaries: function( forceAspectRatio ) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: this._isNumber( o.minWidth ) ? o.minWidth : 0,
			maxWidth: this._isNumber( o.maxWidth ) ? o.maxWidth : Infinity,
			minHeight: this._isNumber( o.minHeight ) ? o.minHeight : 0,
			maxHeight: this._isNumber( o.maxHeight ) ? o.maxHeight : Infinity
		};

		if ( this._aspectRatio || forceAspectRatio ) {
			pMinWidth = b.minHeight * this.aspectRatio;
			pMinHeight = b.minWidth / this.aspectRatio;
			pMaxWidth = b.maxHeight * this.aspectRatio;
			pMaxHeight = b.maxWidth / this.aspectRatio;

			if ( pMinWidth > b.minWidth ) {
				b.minWidth = pMinWidth;
			}
			if ( pMinHeight > b.minHeight ) {
				b.minHeight = pMinHeight;
			}
			if ( pMaxWidth < b.maxWidth ) {
				b.maxWidth = pMaxWidth;
			}
			if ( pMaxHeight < b.maxHeight ) {
				b.maxHeight = pMaxHeight;
			}
		}
		this._vBoundaries = b;
	},

	_updateCache: function( data ) {
		this.offset = this.helper.offset();
		if ( this._isNumber( data.left ) ) {
			this.position.left = data.left;
		}
		if ( this._isNumber( data.top ) ) {
			this.position.top = data.top;
		}
		if ( this._isNumber( data.height ) ) {
			this.size.height = data.height;
		}
		if ( this._isNumber( data.width ) ) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if ( this._isNumber( data.height ) ) {
			data.width = ( data.height * this.aspectRatio );
		} else if ( this._isNumber( data.width ) ) {
			data.height = ( data.width / this.aspectRatio );
		}

		if ( a === "sw" ) {
			data.left = cpos.left + ( csize.width - data.width );
			data.top = null;
		}
		if ( a === "nw" ) {
			data.top = cpos.top + ( csize.height - data.height );
			data.left = cpos.left + ( csize.width - data.width );
		}

		return data;
	},

	_respectSize: function( data ) {

		var o = this._vBoundaries,
			a = this.axis,
			ismaxw = this._isNumber( data.width ) && o.maxWidth && ( o.maxWidth < data.width ),
			ismaxh = this._isNumber( data.height ) && o.maxHeight && ( o.maxHeight < data.height ),
			isminw = this._isNumber( data.width ) && o.minWidth && ( o.minWidth > data.width ),
			isminh = this._isNumber( data.height ) && o.minHeight && ( o.minHeight > data.height ),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.originalPosition.top + this.originalSize.height,
			cw = /sw|nw|w/.test( a ), ch = /nw|ne|n/.test( a );
		if ( isminw ) {
			data.width = o.minWidth;
		}
		if ( isminh ) {
			data.height = o.minHeight;
		}
		if ( ismaxw ) {
			data.width = o.maxWidth;
		}
		if ( ismaxh ) {
			data.height = o.maxHeight;
		}

		if ( isminw && cw ) {
			data.left = dw - o.minWidth;
		}
		if ( ismaxw && cw ) {
			data.left = dw - o.maxWidth;
		}
		if ( isminh && ch ) {
			data.top = dh - o.minHeight;
		}
		if ( ismaxh && ch ) {
			data.top = dh - o.maxHeight;
		}

		// Fixing jump error on top/left - bug #2330
		if ( !data.width && !data.height && !data.left && data.top ) {
			data.top = null;
		} else if ( !data.width && !data.height && !data.top && data.left ) {
			data.left = null;
		}

		return data;
	},

	_getPaddingPlusBorderDimensions: function( element ) {
		var i = 0,
			widths = [],
			borders = [
				element.css( "borderTopWidth" ),
				element.css( "borderRightWidth" ),
				element.css( "borderBottomWidth" ),
				element.css( "borderLeftWidth" )
			],
			paddings = [
				element.css( "paddingTop" ),
				element.css( "paddingRight" ),
				element.css( "paddingBottom" ),
				element.css( "paddingLeft" )
			];

		for ( ; i < 4; i++ ) {
			widths[ i ] = ( parseFloat( borders[ i ] ) || 0 );
			widths[ i ] += ( parseFloat( paddings[ i ] ) || 0 );
		}

		return {
			height: widths[ 0 ] + widths[ 2 ],
			width: widths[ 1 ] + widths[ 3 ]
		};
	},

	_proportionallyResize: function() {

		if ( !this._proportionallyResizeElements.length ) {
			return;
		}

		var prel,
			i = 0,
			element = this.helper || this.element;

		for ( ; i < this._proportionallyResizeElements.length; i++ ) {

			prel = this._proportionallyResizeElements[ i ];

			// TODO: Seems like a bug to cache this.outerDimensions
			// considering that we are in a loop.
			if ( !this.outerDimensions ) {
				this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
			}

			prel.css( {
				height: ( element.height() - this.outerDimensions.height ) || 0,
				width: ( element.width() - this.outerDimensions.width ) || 0
			} );

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if ( this._helper ) {

			this.helper = this.helper || $( "<div style='overflow:hidden;'></div>" );

			this._addClass( this.helper, this._helper );
			this.helper.css( {
				width: this.element.outerWidth(),
				height: this.element.outerHeight(),
				position: "absolute",
				left: this.elementOffset.left + "px",
				top: this.elementOffset.top + "px",
				zIndex: ++o.zIndex //TODO: Don't modify option
			} );

			this.helper
				.appendTo( "body" )
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function( event, dx ) {
			return { width: this.originalSize.width + dx };
		},
		w: function( event, dx ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function( event, dx, dy ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function( event, dx, dy ) {
			return { height: this.originalSize.height + dy };
		},
		se: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		sw: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		},
		ne: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		nw: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		}
	},

	_propagate: function( n, event ) {
		$.ui.plugin.call( this, n, [ event, this.ui() ] );
		( n !== "resize" && this._trigger( n, event, this.ui() ) );
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

} );

/*
 * Resizable Extensions
 */

$.ui.plugin.add( "resizable", "animate", {

	stop: function( event ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName ),
			soffseth = ista && that._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = {
				width: ( that.size.width - soffsetw ),
				height: ( that.size.height - soffseth )
			},
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null,
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

		that.element.animate(
			$.extend( style, top && left ? { top: top, left: left } : {} ), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseFloat( that.element.css( "width" ) ),
						height: parseFloat( that.element.css( "height" ) ),
						top: parseFloat( that.element.css( "top" ) ),
						left: parseFloat( that.element.css( "left" ) )
					};

					if ( pr && pr.length ) {
						$( pr[ 0 ] ).css( { width: data.width, height: data.height } );
					}

					// Propagating resize, and updating values for each animation step
					that._updateCache( data );
					that._propagate( "resize", event );

				}
			}
		);
	}

} );

$.ui.plugin.add( "resizable", "containment", {

	start: function() {
		var element, p, co, ch, cw, width, height,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			el = that.element,
			oc = o.containment,
			ce = ( oc instanceof $ ) ?
				oc.get( 0 ) :
				( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;

		if ( !ce ) {
			return;
		}

		that.containerElement = $( ce );

		if ( /document/.test( oc ) || oc === document ) {
			that.containerOffset = {
				left: 0,
				top: 0
			};
			that.containerPosition = {
				left: 0,
				top: 0
			};

			that.parentData = {
				element: $( document ),
				left: 0,
				top: 0,
				width: $( document ).width(),
				height: $( document ).height() || document.body.parentNode.scrollHeight
			};
		} else {
			element = $( ce );
			p = [];
			$( [ "Top", "Right", "Left", "Bottom" ] ).each( function( i, name ) {
				p[ i ] = that._num( element.css( "padding" + name ) );
			} );

			that.containerOffset = element.offset();
			that.containerPosition = element.position();
			that.containerSize = {
				height: ( element.innerHeight() - p[ 3 ] ),
				width: ( element.innerWidth() - p[ 1 ] )
			};

			co = that.containerOffset;
			ch = that.containerSize.height;
			cw = that.containerSize.width;
			width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw );
			height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ;

			that.parentData = {
				element: ce,
				left: co.left,
				top: co.top,
				width: width,
				height: height
			};
		}
	},

	resize: function( event ) {
		var woset, hoset, isParent, isOffsetRelative,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = {
				top: 0,
				left: 0
			},
			ce = that.containerElement,
			continueResize = true;

		if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
			cop = co;
		}

		if ( cp.left < ( that._helper ? co.left : 0 ) ) {
			that.size.width = that.size.width +
				( that._helper ?
					( that.position.left - co.left ) :
					( that.position.left - cop.left ) );

			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
			that.position.left = o.helper ? co.left : 0;
		}

		if ( cp.top < ( that._helper ? co.top : 0 ) ) {
			that.size.height = that.size.height +
				( that._helper ?
					( that.position.top - co.top ) :
					that.position.top );

			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
		isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );

		if ( isParent && isOffsetRelative ) {
			that.offset.left = that.parentData.left + that.position.left;
			that.offset.top = that.parentData.top + that.position.top;
		} else {
			that.offset.left = that.element.offset().left;
			that.offset.top = that.element.offset().top;
		}

		woset = Math.abs( that.sizeDiff.width +
			( that._helper ?
				that.offset.left - cop.left :
				( that.offset.left - co.left ) ) );

		hoset = Math.abs( that.sizeDiff.height +
			( that._helper ?
				that.offset.top - cop.top :
				( that.offset.top - co.top ) ) );

		if ( woset + that.size.width >= that.parentData.width ) {
			that.size.width = that.parentData.width - woset;
			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
		}

		if ( hoset + that.size.height >= that.parentData.height ) {
			that.size.height = that.parentData.height - hoset;
			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
		}

		if ( !continueResize ) {
			that.position.left = that.prevPosition.left;
			that.position.top = that.prevPosition.top;
			that.size.width = that.prevSize.width;
			that.size.height = that.prevSize.height;
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cop = that.containerPosition,
			ce = that.containerElement,
			helper = $( that.helper ),
			ho = helper.offset(),
			w = helper.outerWidth() - that.sizeDiff.width,
			h = helper.outerHeight() - that.sizeDiff.height;

		if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}

		if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}
	}
} );

$.ui.plugin.add( "resizable", "alsoResize", {

	start: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options;

		$( o.alsoResize ).each( function() {
			var el = $( this );
			el.data( "ui-resizable-alsoresize", {
				width: parseFloat( el.width() ), height: parseFloat( el.height() ),
				left: parseFloat( el.css( "left" ) ), top: parseFloat( el.css( "top" ) )
			} );
		} );
	},

	resize: function( event, ui ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			os = that.originalSize,
			op = that.originalPosition,
			delta = {
				height: ( that.size.height - os.height ) || 0,
				width: ( that.size.width - os.width ) || 0,
				top: ( that.position.top - op.top ) || 0,
				left: ( that.position.left - op.left ) || 0
			};

			$( o.alsoResize ).each( function() {
				var el = $( this ), start = $( this ).data( "ui-resizable-alsoresize" ), style = {},
					css = el.parents( ui.originalElement[ 0 ] ).length ?
							[ "width", "height" ] :
							[ "width", "height", "top", "left" ];

				$.each( css, function( i, prop ) {
					var sum = ( start[ prop ] || 0 ) + ( delta[ prop ] || 0 );
					if ( sum && sum >= 0 ) {
						style[ prop ] = sum || null;
					}
				} );

				el.css( style );
			} );
	},

	stop: function() {
		$( this ).removeData( "ui-resizable-alsoresize" );
	}
} );

$.ui.plugin.add( "resizable", "ghost", {

	start: function() {

		var that = $( this ).resizable( "instance" ), cs = that.size;

		that.ghost = that.originalElement.clone();
		that.ghost.css( {
			opacity: 0.25,
			display: "block",
			position: "relative",
			height: cs.height,
			width: cs.width,
			margin: 0,
			left: 0,
			top: 0
		} );

		that._addClass( that.ghost, "ui-resizable-ghost" );

		// DEPRECATED
		// TODO: remove after 1.12
		if ( $.uiBackCompat !== false && typeof that.options.ghost === "string" ) {

			// Ghost option
			that.ghost.addClass( this.options.ghost );
		}

		that.ghost.appendTo( that.helper );

	},

	resize: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost ) {
			that.ghost.css( {
				position: "relative",
				height: that.size.height,
				width: that.size.width
			} );
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost && that.helper ) {
			that.helper.get( 0 ).removeChild( that.ghost.get( 0 ) );
		}
	}

} );

$.ui.plugin.add( "resizable", "grid", {

	resize: function() {
		var outerDimensions,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			cs = that.size,
			os = that.originalSize,
			op = that.originalPosition,
			a = that.axis,
			grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
			gridX = ( grid[ 0 ] || 1 ),
			gridY = ( grid[ 1 ] || 1 ),
			ox = Math.round( ( cs.width - os.width ) / gridX ) * gridX,
			oy = Math.round( ( cs.height - os.height ) / gridY ) * gridY,
			newWidth = os.width + ox,
			newHeight = os.height + oy,
			isMaxWidth = o.maxWidth && ( o.maxWidth < newWidth ),
			isMaxHeight = o.maxHeight && ( o.maxHeight < newHeight ),
			isMinWidth = o.minWidth && ( o.minWidth > newWidth ),
			isMinHeight = o.minHeight && ( o.minHeight > newHeight );

		o.grid = grid;

		if ( isMinWidth ) {
			newWidth += gridX;
		}
		if ( isMinHeight ) {
			newHeight += gridY;
		}
		if ( isMaxWidth ) {
			newWidth -= gridX;
		}
		if ( isMaxHeight ) {
			newHeight -= gridY;
		}

		if ( /^(se|s|e)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
		} else if ( /^(ne)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
		} else if ( /^(sw)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.left = op.left - ox;
		} else {
			if ( newHeight - gridY <= 0 || newWidth - gridX <= 0 ) {
				outerDimensions = that._getPaddingPlusBorderDimensions( this );
			}

			if ( newHeight - gridY > 0 ) {
				that.size.height = newHeight;
				that.position.top = op.top - oy;
			} else {
				newHeight = gridY - outerDimensions.height;
				that.size.height = newHeight;
				that.position.top = op.top + os.height - newHeight;
			}
			if ( newWidth - gridX > 0 ) {
				that.size.width = newWidth;
				that.position.left = op.left - ox;
			} else {
				newWidth = gridX - outerDimensions.width;
				that.size.width = newWidth;
				that.position.left = op.left + os.width - newWidth;
			}
		}
	}

} );

var widgetsResizable = $.ui.resizable;


/*!
 * jQuery UI Menu 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Menu
//>>group: Widgets
//>>description: Creates nestable menus.
//>>docs: http://api.jqueryui.com/menu/
//>>demos: http://jqueryui.com/menu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/menu.css
//>>css.theme: ../../themes/base/theme.css



var widgetsMenu = $.widget( "ui.menu", {
	version: "1.12.1",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-caret-1-e"
		},
		items: "> *",
		menus: "ul",
		position: {
			my: "left top",
			at: "right top"
		},
		role: "menu",

		// Callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.attr( {
				role: this.options.role,
				tabIndex: 0
			} );

		this._addClass( "ui-menu", "ui-widget ui-widget-content" );
		this._on( {

			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .ui-menu-item": function( event ) {
				event.preventDefault();
			},
			"click .ui-menu-item": function( event ) {
				var target = $( event.target );
				var active = $( $.ui.safeActiveElement( this.document[ 0 ] ) );
				if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) &&
							active.closest( ".ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": function( event ) {

				// Ignore mouse events while typeahead is active, see #10458.
				// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
				// is over an item in the menu
				if ( this.previousFilter ) {
					return;
				}

				var actualTarget = $( event.target ).closest( ".ui-menu-item" ),
					target = $( event.currentTarget );

				// Ignore bubbled events on parent items, see #11641
				if ( actualTarget[ 0 ] !== target[ 0 ] ) {
					return;
				}

				// Remove ui-state-active class from siblings of the newly focused menu item
				// to avoid a jump caused by adjacent elements both having a class with a border
				this._removeClass( target.siblings().children( ".ui-state-active" ),
					null, "ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {

				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.find( this.options.items ).eq( 0 );

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay( function() {
					var notContained = !$.contains(
						this.element[ 0 ],
						$.ui.safeActiveElement( this.document[ 0 ] )
					);
					if ( notContained ) {
						this.collapseAll( event );
					}
				} );
			},
			keydown: "_keydown"
		} );

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		} );
	},

	_destroy: function() {
		var items = this.element.find( ".ui-menu-item" )
				.removeAttr( "role aria-disabled" ),
			submenus = items.children( ".ui-menu-item-wrapper" )
				.removeUniqueId()
				.removeAttr( "tabIndex role aria-haspopup" );

		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " +
					"tabIndex" )
				.removeUniqueId()
				.show();

		submenus.children().each( function() {
			var elem = $( this );
			if ( elem.data( "ui-menu-submenu-caret" ) ) {
				elem.remove();
			}
		} );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			skip = false;

			// Support number pad values
			character = event.keyCode >= 96 && event.keyCode <= 105 ?
				( event.keyCode - 96 ).toString() : String.fromCharCode( event.keyCode );

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip && match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay( function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.children( "[aria-haspopup='true']" ).length ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items, newSubmenus, newItems, newWrappers,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this._toggleClass( "ui-menu-icons", null, !!this.element.find( ".ui-icon" ).length );

		// Initialize nested menus
		newSubmenus = submenus.filter( ":not(.ui-menu)" )
			.hide()
			.attr( {
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			} )
			.each( function() {
				var menu = $( this ),
					item = menu.prev(),
					submenuCaret = $( "<span>" ).data( "ui-menu-submenu-caret", true );

				that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon );
				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCaret );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			} );

		this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" );

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".ui-menu-item" ).each( function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				that._addClass( item, "ui-menu-divider", "ui-widget-content" );
			}
		} );

		// Don't refresh list items that are already adapted
		newItems = items.not( ".ui-menu-item, .ui-menu-divider" );
		newWrappers = newItems.children()
			.not( ".ui-menu" )
				.uniqueId()
				.attr( {
					tabIndex: -1,
					role: this._itemRole()
				} );
		this._addClass( newItems, "ui-menu-item" )
			._addClass( newWrappers, "ui-menu-item-wrapper" );

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icons = this.element.find( ".ui-menu-icon" );
			this._removeClass( icons, null, this.options.icons.submenu )
				._addClass( icons, null, value.submenu );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", String( value ) );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	focus: function( event, item ) {
		var nested, focused, activeParent;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();

		focused = this.active.children( ".ui-menu-item-wrapper" );
		this._addClass( focused, null, "ui-state-active" );

		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		activeParent = this.active
			.parent()
				.closest( ".ui-menu-item" )
					.children( ".ui-menu-item-wrapper" );
		this._addClass( activeParent, null, "ui-state-active" );

		if ( event && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay( function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
			this._startOpening( nested );
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this._removeClass( this.active.children( ".ui-menu-item-wrapper" ),
			null, "ui-state-active" );

		this._trigger( "blur", event, { item: this.active } );
		this.active = null;
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the caret icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay( function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend( {
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay( function() {

			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event && event.target ).closest( this.element.find( ".ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all
			// sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );

			// Work around active item staying active after menu is blurred
			this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" );

			this.activeMenu = currentMenu;
		}, this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu.find( ".ui-menu" )
			.hide()
			.attr( "aria-hidden", "true" )
			.attr( "aria-expanded", "false" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &&
			this.active
				.children( ".ui-menu " )
					.find( this.options.items )
						.first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay( function() {
				this.focus( event, newItem );
			} );
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.eq( -1 );
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.eq( 0 );
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this.activeMenu.find( this.options.items )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.nextAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.prevAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
	},

	select: function( event ) {

		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function( character ) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

				// Only match on items, not dividers or other content (#10571)
				.filter( ".ui-menu-item" )
					.filter( function() {
						return regex.test(
							$.trim( $( this ).children( ".ui-menu-item-wrapper" ).text() ) );
					} );
	}
} );


/*!
 * jQuery UI Autocomplete 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Autocomplete
//>>group: Widgets
//>>description: Lists suggested words as the user is typing.
//>>docs: http://api.jqueryui.com/autocomplete/
//>>demos: http://jqueryui.com/autocomplete/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/autocomplete.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.autocomplete", {
	version: "1.12.1",
	defaultElement: "<input>",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,

	_create: function() {

		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		// Textareas are always multi-line
		// Inputs are always single-line, even if inside a contentEditable element
		// IE also treats inputs as contentEditable
		// All other element types are determined by whether or not they're contentEditable
		this.isMultiLine = isTextarea || !isInput && this._isContentEditable( this.element );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this._addClass( "ui-autocomplete-input" );
		this.element.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:

					// when menu is open and has focus
					if ( this.menu.active ) {

						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );

						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;

					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// Replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				if ( this.cancelBlur ) {
					delete this.cancelBlur;
					return;
				}

				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		} );

		this._initSource();
		this.menu = $( "<ul>" )
			.appendTo( this._appendTo() )
			.menu( {

				// disable ARIA support, the live region takes care of that
				role: null
			} )
			.hide()
			.menu( "instance" );

		this._addClass( this.menu.element, "ui-autocomplete", "ui-front" );
		this._on( this.menu.element, {
			mousedown: function( event ) {

				// prevent moving focus out of the text field
				event.preventDefault();

				// IE doesn't prevent moving focus even with event.preventDefault()
				// so we set a flag to know when we should ignore the blur event
				this.cancelBlur = true;
				this._delay( function() {
					delete this.cancelBlur;

					// Support: IE 8 only
					// Right clicking a menu item or selecting text from the menu items will
					// result in focus moving out of the input. However, we've already received
					// and ignored the blur event because of the cancelBlur flag set above. So
					// we restore focus to ensure that the menu closes properly based on the user's
					// next actions.
					if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
						this.element.trigger( "focus" );
					}
				} );
			},
			menufocus: function( event, ui ) {
				var label, item;

				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						} );

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {

					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label && $.trim( label ).length ) {
					this.liveRegion.children().hide();
					$( "<div>" ).text( label ).appendTo( this.liveRegion );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "ui-autocomplete-item" ),
					previous = this.previous;

				// Only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
					this.element.trigger( "focus" );
					this.previous = previous;

					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay( function() {
						this.previous = previous;
						this.selectedItem = item;
					} );
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}

				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		} );

		this.liveRegion = $( "<div>", {
			role: "status",
			"aria-live": "assertive",
			"aria-relevant": "additions"
		} )
			.appendTo( this.document[ 0 ].body );

		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		// Turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		} );
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_isEventTargetInWidget: function( event ) {
		var menuElement = this.menu.element[ 0 ];

		return event.target === this.element[ 0 ] ||
			event.target === menuElement ||
			$.contains( menuElement, event.target );
	},

	_closeOnClickOutside: function( event ) {
		if ( !this._isEventTargetInWidget( event ) ) {
			this.close();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front, dialog" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax( {
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response( [] );
					}
				} );
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay( function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// Always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this._addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return $.proxy( function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this._removeClass( "ui-autocomplete-loading" );
			}
		}, this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {

			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {

		// Remove the handler that closes the menu on outside clicks
		this._off( this.document, "mousedown" );

		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {

		// assume all items have the right format when the first item is complete
		if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			} );
		} );
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// Size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend( {
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}

		// Listen for interactions outside of the widget (#6642)
		this._on( this.document, {
			mousedown: "_closeOnClickOutside"
		} );
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(

			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "<li>" )
			.append( $( "<div>" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
				this.menu.isLastItem() && /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// Prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	},

	// Support: Chrome <=50
	// We should be able to just use this.element.prop( "isContentEditable" )
	// but hidden elements always report false in Chrome.
	// https://code.google.com/p/chromium/issues/detail?id=313082
	_isContentEditable: function( element ) {
		if ( !element.length ) {
			return false;
		}

		var editable = element.prop( "contentEditable" );

		if ( editable === "inherit" ) {
		  return this._isContentEditable( element.parent() );
		}

		return editable === "true";
	}
} );

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		} );
	}
} );

// Live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
	options: {
		messages: {
			noResults: "No search results.",
			results: function( amount ) {
				return amount + ( amount > 1 ? " results are" : " result is" ) +
					" available, use up and down arrow keys to navigate.";
			}
		}
	},

	__response: function( content ) {
		var message;
		this._superApply( arguments );
		if ( this.options.disabled || this.cancelSearch ) {
			return;
		}
		if ( content && content.length ) {
			message = this.options.messages.results( content.length );
		} else {
			message = this.options.messages.noResults;
		}
		this.liveRegion.children().hide();
		$( "<div>" ).text( message ).appendTo( this.liveRegion );
	}
} );

var widgetsAutocomplete = $.ui.autocomplete;


/*!
 * jQuery UI Controlgroup 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Controlgroup
//>>group: Widgets
//>>description: Visually groups form control widgets
//>>docs: http://api.jqueryui.com/controlgroup/
//>>demos: http://jqueryui.com/controlgroup/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/controlgroup.css
//>>css.theme: ../../themes/base/theme.css


var controlgroupCornerRegex = /ui-corner-([a-z]){2,6}/g;

var widgetsControlgroup = $.widget( "ui.controlgroup", {
	version: "1.12.1",
	defaultElement: "<div>",
	options: {
		direction: "horizontal",
		disabled: null,
		onlyVisible: true,
		items: {
			"button": "input[type=button], input[type=submit], input[type=reset], button, a",
			"controlgroupLabel": ".ui-controlgroup-label",
			"checkboxradio": "input[type='checkbox'], input[type='radio']",
			"selectmenu": "select",
			"spinner": ".ui-spinner-input"
		}
	},

	_create: function() {
		this._enhance();
	},

	// To support the enhanced option in jQuery Mobile, we isolate DOM manipulation
	_enhance: function() {
		this.element.attr( "role", "toolbar" );
		this.refresh();
	},

	_destroy: function() {
		this._callChildMethod( "destroy" );
		this.childWidgets.removeData( "ui-controlgroup-data" );
		this.element.removeAttr( "role" );
		if ( this.options.items.controlgroupLabel ) {
			this.element
				.find( this.options.items.controlgroupLabel )
				.find( ".ui-controlgroup-label-contents" )
				.contents().unwrap();
		}
	},

	_initWidgets: function() {
		var that = this,
			childWidgets = [];

		// First we iterate over each of the items options
		$.each( this.options.items, function( widget, selector ) {
			var labels;
			var options = {};

			// Make sure the widget has a selector set
			if ( !selector ) {
				return;
			}

			if ( widget === "controlgroupLabel" ) {
				labels = that.element.find( selector );
				labels.each( function() {
					var element = $( this );

					if ( element.children( ".ui-controlgroup-label-contents" ).length ) {
						return;
					}
					element.contents()
						.wrapAll( "<span class='ui-controlgroup-label-contents'></span>" );
				} );
				that._addClass( labels, null, "ui-widget ui-widget-content ui-state-default" );
				childWidgets = childWidgets.concat( labels.get() );
				return;
			}

			// Make sure the widget actually exists
			if ( !$.fn[ widget ] ) {
				return;
			}

			// We assume everything is in the middle to start because we can't determine
			// first / last elements until all enhancments are done.
			if ( that[ "_" + widget + "Options" ] ) {
				options = that[ "_" + widget + "Options" ]( "middle" );
			} else {
				options = { classes: {} };
			}

			// Find instances of this widget inside controlgroup and init them
			that.element
				.find( selector )
				.each( function() {
					var element = $( this );
					var instance = element[ widget ]( "instance" );

					// We need to clone the default options for this type of widget to avoid
					// polluting the variable options which has a wider scope than a single widget.
					var instanceOptions = $.widget.extend( {}, options );

					// If the button is the child of a spinner ignore it
					// TODO: Find a more generic solution
					if ( widget === "button" && element.parent( ".ui-spinner" ).length ) {
						return;
					}

					// Create the widget if it doesn't exist
					if ( !instance ) {
						instance = element[ widget ]()[ widget ]( "instance" );
					}
					if ( instance ) {
						instanceOptions.classes =
							that._resolveClassesValues( instanceOptions.classes, instance );
					}
					element[ widget ]( instanceOptions );

					// Store an instance of the controlgroup to be able to reference
					// from the outermost element for changing options and refresh
					var widgetElement = element[ widget ]( "widget" );
					$.data( widgetElement[ 0 ], "ui-controlgroup-data",
						instance ? instance : element[ widget ]( "instance" ) );

					childWidgets.push( widgetElement[ 0 ] );
				} );
		} );

		this.childWidgets = $( $.unique( childWidgets ) );
		this._addClass( this.childWidgets, "ui-controlgroup-item" );
	},

	_callChildMethod: function( method ) {
		this.childWidgets.each( function() {
			var element = $( this ),
				data = element.data( "ui-controlgroup-data" );
			if ( data && data[ method ] ) {
				data[ method ]();
			}
		} );
	},

	_updateCornerClass: function( element, position ) {
		var remove = "ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";
		var add = this._buildSimpleOptions( position, "label" ).classes.label;

		this._removeClass( element, null, remove );
		this._addClass( element, null, add );
	},

	_buildSimpleOptions: function( position, key ) {
		var direction = this.options.direction === "vertical";
		var result = {
			classes: {}
		};
		result.classes[ key ] = {
			"middle": "",
			"first": "ui-corner-" + ( direction ? "top" : "left" ),
			"last": "ui-corner-" + ( direction ? "bottom" : "right" ),
			"only": "ui-corner-all"
		}[ position ];

		return result;
	},

	_spinnerOptions: function( position ) {
		var options = this._buildSimpleOptions( position, "ui-spinner" );

		options.classes[ "ui-spinner-up" ] = "";
		options.classes[ "ui-spinner-down" ] = "";

		return options;
	},

	_buttonOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-button" );
	},

	_checkboxradioOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-checkboxradio-label" );
	},

	_selectmenuOptions: function( position ) {
		var direction = this.options.direction === "vertical";
		return {
			width: direction ? "auto" : false,
			classes: {
				middle: {
					"ui-selectmenu-button-open": "",
					"ui-selectmenu-button-closed": ""
				},
				first: {
					"ui-selectmenu-button-open": "ui-corner-" + ( direction ? "top" : "tl" ),
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "top" : "left" )
				},
				last: {
					"ui-selectmenu-button-open": direction ? "" : "ui-corner-tr",
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "bottom" : "right" )
				},
				only: {
					"ui-selectmenu-button-open": "ui-corner-top",
					"ui-selectmenu-button-closed": "ui-corner-all"
				}

			}[ position ]
		};
	},

	_resolveClassesValues: function( classes, instance ) {
		var result = {};
		$.each( classes, function( key ) {
			var current = instance.options.classes[ key ] || "";
			current = $.trim( current.replace( controlgroupCornerRegex, "" ) );
			result[ key ] = ( current + " " + classes[ key ] ).replace( /\s+/g, " " );
		} );
		return result;
	},

	_setOption: function( key, value ) {
		if ( key === "direction" ) {
			this._removeClass( "ui-controlgroup-" + this.options.direction );
		}

		this._super( key, value );
		if ( key === "disabled" ) {
			this._callChildMethod( value ? "disable" : "enable" );
			return;
		}

		this.refresh();
	},

	refresh: function() {
		var children,
			that = this;

		this._addClass( "ui-controlgroup ui-controlgroup-" + this.options.direction );

		if ( this.options.direction === "horizontal" ) {
			this._addClass( null, "ui-helper-clearfix" );
		}
		this._initWidgets();

		children = this.childWidgets;

		// We filter here because we need to track all childWidgets not just the visible ones
		if ( this.options.onlyVisible ) {
			children = children.filter( ":visible" );
		}

		if ( children.length ) {

			// We do this last because we need to make sure all enhancment is done
			// before determining first and last
			$.each( [ "first", "last" ], function( index, value ) {
				var instance = children[ value ]().data( "ui-controlgroup-data" );

				if ( instance && that[ "_" + instance.widgetName + "Options" ] ) {
					var options = that[ "_" + instance.widgetName + "Options" ](
						children.length === 1 ? "only" : value
					);
					options.classes = that._resolveClassesValues( options.classes, instance );
					instance.element[ instance.widgetName ]( options );
				} else {
					that._updateCornerClass( children[ value ](), value );
				}
			} );

			// Finally call the refresh method on each of the child widgets.
			this._callChildMethod( "refresh" );
		}
	}
} );

/*!
 * jQuery UI Checkboxradio 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Checkboxradio
//>>group: Widgets
//>>description: Enhances a form with multiple themeable checkboxes or radio buttons.
//>>docs: http://api.jqueryui.com/checkboxradio/
//>>demos: http://jqueryui.com/checkboxradio/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.structure: ../../themes/base/checkboxradio.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.checkboxradio", [ $.ui.formResetMixin, {
	version: "1.12.1",
	options: {
		disabled: null,
		label: null,
		icon: true,
		classes: {
			"ui-checkboxradio-label": "ui-corner-all",
			"ui-checkboxradio-icon": "ui-corner-all"
		}
	},

	_getCreateOptions: function() {
		var disabled, labels;
		var that = this;
		var options = this._super() || {};

		// We read the type here, because it makes more sense to throw a element type error first,
		// rather then the error for lack of a label. Often if its the wrong type, it
		// won't have a label (e.g. calling on a div, btn, etc)
		this._readType();

		labels = this.element.labels();

		// If there are multiple labels, use the last one
		this.label = $( labels[ labels.length - 1 ] );
		if ( !this.label.length ) {
			$.error( "No label found for checkboxradio widget" );
		}

		this.originalLabel = "";

		// We need to get the label text but this may also need to make sure it does not contain the
		// input itself.
		this.label.contents().not( this.element[ 0 ] ).each( function() {

			// The label contents could be text, html, or a mix. We concat each element to get a
			// string representation of the label, without the input as part of it.
			that.originalLabel += this.nodeType === 3 ? $( this ).text() : this.outerHTML;
		} );

		// Set the label option if we found label text
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}
		return options;
	},

	_create: function() {
		var checked = this.element[ 0 ].checked;

		this._bindFormResetHandler();

		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled;
		}

		this._setOption( "disabled", this.options.disabled );
		this._addClass( "ui-checkboxradio", "ui-helper-hidden-accessible" );
		this._addClass( this.label, "ui-checkboxradio-label", "ui-button ui-widget" );

		if ( this.type === "radio" ) {
			this._addClass( this.label, "ui-checkboxradio-radio-label" );
		}

		if ( this.options.label && this.options.label !== this.originalLabel ) {
			this._updateLabel();
		} else if ( this.originalLabel ) {
			this.options.label = this.originalLabel;
		}

		this._enhance();

		if ( checked ) {
			this._addClass( this.label, "ui-checkboxradio-checked", "ui-state-active" );
			if ( this.icon ) {
				this._addClass( this.icon, null, "ui-state-hover" );
			}
		}

		this._on( {
			change: "_toggleClasses",
			focus: function() {
				this._addClass( this.label, null, "ui-state-focus ui-visual-focus" );
			},
			blur: function() {
				this._removeClass( this.label, null, "ui-state-focus ui-visual-focus" );
			}
		} );
	},

	_readType: function() {
		var nodeName = this.element[ 0 ].nodeName.toLowerCase();
		this.type = this.element[ 0 ].type;
		if ( nodeName !== "input" || !/radio|checkbox/.test( this.type ) ) {
			$.error( "Can't create checkboxradio on element.nodeName=" + nodeName +
				" and element.type=" + this.type );
		}
	},

	// Support jQuery Mobile enhanced option
	_enhance: function() {
		this._updateIcon( this.element[ 0 ].checked );
	},

	widget: function() {
		return this.label;
	},

	_getRadioGroup: function() {
		var group;
		var name = this.element[ 0 ].name;
		var nameSelector = "input[name='" + $.ui.escapeSelector( name ) + "']";

		if ( !name ) {
			return $( [] );
		}

		if ( this.form.length ) {
			group = $( this.form[ 0 ].elements ).filter( nameSelector );
		} else {

			// Not inside a form, check all inputs that also are not inside a form
			group = $( nameSelector ).filter( function() {
				return $( this ).form().length === 0;
			} );
		}

		return group.not( this.element );
	},

	_toggleClasses: function() {
		var checked = this.element[ 0 ].checked;
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );

		if ( this.options.icon && this.type === "checkbox" ) {
			this._toggleClass( this.icon, null, "ui-icon-check ui-state-checked", checked )
				._toggleClass( this.icon, null, "ui-icon-blank", !checked );
		}

		if ( this.type === "radio" ) {
			this._getRadioGroup()
				.each( function() {
					var instance = $( this ).checkboxradio( "instance" );

					if ( instance ) {
						instance._removeClass( instance.label,
							"ui-checkboxradio-checked", "ui-state-active" );
					}
				} );
		}
	},

	_destroy: function() {
		this._unbindFormResetHandler();

		if ( this.icon ) {
			this.icon.remove();
			this.iconSpace.remove();
		}
	},

	_setOption: function( key, value ) {

		// We don't allow the value to be set to nothing
		if ( key === "label" && !value ) {
			return;
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( this.label, null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;

			// Don't refresh when setting disabled
			return;
		}
		this.refresh();
	},

	_updateIcon: function( checked ) {
		var toAdd = "ui-icon ui-icon-background ";

		if ( this.options.icon ) {
			if ( !this.icon ) {
				this.icon = $( "<span>" );
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-checkboxradio-icon-space" );
			}

			if ( this.type === "checkbox" ) {
				toAdd += checked ? "ui-icon-check ui-state-checked" : "ui-icon-blank";
				this._removeClass( this.icon, null, checked ? "ui-icon-blank" : "ui-icon-check" );
			} else {
				toAdd += "ui-icon-blank";
			}
			this._addClass( this.icon, "ui-checkboxradio-icon", toAdd );
			if ( !checked ) {
				this._removeClass( this.icon, null, "ui-icon-check ui-state-checked" );
			}
			this.icon.prependTo( this.label ).after( this.iconSpace );
		} else if ( this.icon !== undefined ) {
			this.icon.remove();
			this.iconSpace.remove();
			delete this.icon;
		}
	},

	_updateLabel: function() {

		// Remove the contents of the label ( minus the icon, icon space, and input )
		var contents = this.label.contents().not( this.element[ 0 ] );
		if ( this.icon ) {
			contents = contents.not( this.icon[ 0 ] );
		}
		if ( this.iconSpace ) {
			contents = contents.not( this.iconSpace[ 0 ] );
		}
		contents.remove();

		this.label.append( this.options.label );
	},

	refresh: function() {
		var checked = this.element[ 0 ].checked,
			isDisabled = this.element[ 0 ].disabled;

		this._updateIcon( checked );
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );
		if ( this.options.label !== null ) {
			this._updateLabel();
		}

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { "disabled": isDisabled } );
		}
	}

} ] );

var widgetsCheckboxradio = $.ui.checkboxradio;


/*!
 * jQuery UI Button 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Button
//>>group: Widgets
//>>description: Enhances a form with themeable buttons.
//>>docs: http://api.jqueryui.com/button/
//>>demos: http://jqueryui.com/button/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.button", {
	version: "1.12.1",
	defaultElement: "<button>",
	options: {
		classes: {
			"ui-button": "ui-corner-all"
		},
		disabled: null,
		icon: null,
		iconPosition: "beginning",
		label: null,
		showLabel: true
	},

	_getCreateOptions: function() {
		var disabled,

			// This is to support cases like in jQuery Mobile where the base widget does have
			// an implementation of _getCreateOptions
			options = this._super() || {};

		this.isInput = this.element.is( "input" );

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}

		this.originalLabel = this.isInput ? this.element.val() : this.element.html();
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		return options;
	},

	_create: function() {
		if ( !this.option.showLabel & !this.options.icon ) {
			this.options.showLabel = true;
		}

		// We have to check the option again here even though we did in _getCreateOptions,
		// because null may have been passed on init which would override what was set in
		// _getCreateOptions
		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled || false;
		}

		this.hasTitle = !!this.element.attr( "title" );

		// Check to see if the label needs to be set or if its already correct
		if ( this.options.label && this.options.label !== this.originalLabel ) {
			if ( this.isInput ) {
				this.element.val( this.options.label );
			} else {
				this.element.html( this.options.label );
			}
		}
		this._addClass( "ui-button", "ui-widget" );
		this._setOption( "disabled", this.options.disabled );
		this._enhance();

		if ( this.element.is( "a" ) ) {
			this._on( {
				"keyup": function( event ) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						event.preventDefault();

						// Support: PhantomJS <= 1.9, IE 8 Only
						// If a native click is available use it so we actually cause navigation
						// otherwise just trigger a click event
						if ( this.element[ 0 ].click ) {
							this.element[ 0 ].click();
						} else {
							this.element.trigger( "click" );
						}
					}
				}
			} );
		}
	},

	_enhance: function() {
		if ( !this.element.is( "button" ) ) {
			this.element.attr( "role", "button" );
		}

		if ( this.options.icon ) {
			this._updateIcon( "icon", this.options.icon );
			this._updateTooltip();
		}
	},

	_updateTooltip: function() {
		this.title = this.element.attr( "title" );

		if ( !this.options.showLabel && !this.title ) {
			this.element.attr( "title", this.options.label );
		}
	},

	_updateIcon: function( option, value ) {
		var icon = option !== "iconPosition",
			position = icon ? this.options.iconPosition : value,
			displayBlock = position === "top" || position === "bottom";

		// Create icon
		if ( !this.icon ) {
			this.icon = $( "<span>" );

			this._addClass( this.icon, "ui-button-icon", "ui-icon" );

			if ( !this.options.showLabel ) {
				this._addClass( "ui-button-icon-only" );
			}
		} else if ( icon ) {

			// If we are updating the icon remove the old icon class
			this._removeClass( this.icon, null, this.options.icon );
		}

		// If we are updating the icon add the new icon class
		if ( icon ) {
			this._addClass( this.icon, null, value );
		}

		this._attachIcon( position );

		// If the icon is on top or bottom we need to add the ui-widget-icon-block class and remove
		// the iconSpace if there is one.
		if ( displayBlock ) {
			this._addClass( this.icon, null, "ui-widget-icon-block" );
			if ( this.iconSpace ) {
				this.iconSpace.remove();
			}
		} else {

			// Position is beginning or end so remove the ui-widget-icon-block class and add the
			// space if it does not exist
			if ( !this.iconSpace ) {
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-button-icon-space" );
			}
			this._removeClass( this.icon, null, "ui-wiget-icon-block" );
			this._attachIconSpace( position );
		}
	},

	_destroy: function() {
		this.element.removeAttr( "role" );

		if ( this.icon ) {
			this.icon.remove();
		}
		if ( this.iconSpace ) {
			this.iconSpace.remove();
		}
		if ( !this.hasTitle ) {
			this.element.removeAttr( "title" );
		}
	},

	_attachIconSpace: function( iconPosition ) {
		this.icon[ /^(?:end|bottom)/.test( iconPosition ) ? "before" : "after" ]( this.iconSpace );
	},

	_attachIcon: function( iconPosition ) {
		this.element[ /^(?:end|bottom)/.test( iconPosition ) ? "append" : "prepend" ]( this.icon );
	},

	_setOptions: function( options ) {
		var newShowLabel = options.showLabel === undefined ?
				this.options.showLabel :
				options.showLabel,
			newIcon = options.icon === undefined ? this.options.icon : options.icon;

		if ( !newShowLabel && !newIcon ) {
			options.showLabel = true;
		}
		this._super( options );
	},

	_setOption: function( key, value ) {
		if ( key === "icon" ) {
			if ( value ) {
				this._updateIcon( key, value );
			} else if ( this.icon ) {
				this.icon.remove();
				if ( this.iconSpace ) {
					this.iconSpace.remove();
				}
			}
		}

		if ( key === "iconPosition" ) {
			this._updateIcon( key, value );
		}

		// Make sure we can't end up with a button that has neither text nor icon
		if ( key === "showLabel" ) {
				this._toggleClass( "ui-button-icon-only", null, !value );
				this._updateTooltip();
		}

		if ( key === "label" ) {
			if ( this.isInput ) {
				this.element.val( value );
			} else {

				// If there is an icon, append it, else nothing then append the value
				// this avoids removal of the icon when setting label text
				this.element.html( value );
				if ( this.icon ) {
					this._attachIcon( this.options.iconPosition );
					this._attachIconSpace( this.options.iconPosition );
				}
			}
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;
			if ( value ) {
				this.element.blur();
			}
		}
	},

	refresh: function() {

		// Make sure to only check disabled if its an element that supports this otherwise
		// check for the disabled class to determine state
		var isDisabled = this.element.is( "input, button" ) ?
			this.element[ 0 ].disabled : this.element.hasClass( "ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { disabled: isDisabled } );
		}

		this._updateTooltip();
	}
} );

// DEPRECATED
if ( $.uiBackCompat !== false ) {

	// Text and Icons options
	$.widget( "ui.button", $.ui.button, {
		options: {
			text: true,
			icons: {
				primary: null,
				secondary: null
			}
		},

		_create: function() {
			if ( this.options.showLabel && !this.options.text ) {
				this.options.showLabel = this.options.text;
			}
			if ( !this.options.showLabel && this.options.text ) {
				this.options.text = this.options.showLabel;
			}
			if ( !this.options.icon && ( this.options.icons.primary ||
					this.options.icons.secondary ) ) {
				if ( this.options.icons.primary ) {
					this.options.icon = this.options.icons.primary;
				} else {
					this.options.icon = this.options.icons.secondary;
					this.options.iconPosition = "end";
				}
			} else if ( this.options.icon ) {
				this.options.icons.primary = this.options.icon;
			}
			this._super();
		},

		_setOption: function( key, value ) {
			if ( key === "text" ) {
				this._super( "showLabel", value );
				return;
			}
			if ( key === "showLabel" ) {
				this.options.text = value;
			}
			if ( key === "icon" ) {
				this.options.icons.primary = value;
			}
			if ( key === "icons" ) {
				if ( value.primary ) {
					this._super( "icon", value.primary );
					this._super( "iconPosition", "beginning" );
				} else if ( value.secondary ) {
					this._super( "icon", value.secondary );
					this._super( "iconPosition", "end" );
				}
			}
			this._superApply( arguments );
		}
	} );

	$.fn.button = ( function( orig ) {
		return function() {
			if ( !this.length || ( this.length && this[ 0 ].tagName !== "INPUT" ) ||
					( this.length && this[ 0 ].tagName === "INPUT" && (
						this.attr( "type" ) !== "checkbox" && this.attr( "type" ) !== "radio"
					) ) ) {
				return orig.apply( this, arguments );
			}
			if ( !$.ui.checkboxradio ) {
				$.error( "Checkboxradio widget missing" );
			}
			if ( arguments.length === 0 ) {
				return this.checkboxradio( {
					"icon": false
				} );
			}
			return this.checkboxradio.apply( this, arguments );
		};
	} )( $.fn.button );

	$.fn.buttonset = function() {
		if ( !$.ui.controlgroup ) {
			$.error( "Controlgroup widget missing" );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" && arguments[ 2 ] ) {
			return this.controlgroup.apply( this,
				[ arguments[ 0 ], "items.button", arguments[ 2 ] ] );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" ) {
			return this.controlgroup.apply( this, [ arguments[ 0 ], "items.button" ] );
		}
		if ( typeof arguments[ 0 ] === "object" && arguments[ 0 ].items ) {
			arguments[ 0 ].items = {
				button: arguments[ 0 ].items
			};
		}
		return this.controlgroup.apply( this, arguments );
	};
}

var widgetsButton = $.ui.button;


// jscs:disable maximumLineLength
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
/*!
 * jQuery UI Datepicker 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Datepicker
//>>group: Widgets
//>>description: Displays a calendar from an input or inline for selecting dates.
//>>docs: http://api.jqueryui.com/datepicker/
//>>demos: http://jqueryui.com/datepicker/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/datepicker.css
//>>css.theme: ../../themes/base/theme.css



$.extend( $.ui, { datepicker: { version: "1.12.1" } } );

var datepicker_instActive;

function datepicker_getZindex( elem ) {
	var position, value;
	while ( elem.length && elem[ 0 ] !== document ) {

		// Ignore z-index if position is set to a value where z-index is ignored by the browser
		// This makes behavior of this function consistent across browsers
		// WebKit always returns auto if the element is positioned
		position = elem.css( "position" );
		if ( position === "absolute" || position === "relative" || position === "fixed" ) {

			// IE returns 0 when zIndex is not specified
			// other browsers return a string
			// we ignore the case of nested elements with an explicit value of 0
			// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
			value = parseInt( elem.css( "zIndex" ), 10 );
			if ( !isNaN( value ) && value !== 0 ) {
				return value;
			}
		}
		elem = elem.parent();
	}

	return 0;
}
/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
	this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
	this._appendClass = "ui-datepicker-append"; // The name of the append marker class
	this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
	this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
	this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
	this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
	this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
	this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[ "" ] = { // Default regional settings
		closeText: "Done", // Display text for close link
		prevText: "Prev", // Display text for previous month link
		nextText: "Next", // Display text for next month link
		currentText: "Today", // Display text for current month link
		monthNames: [ "January","February","March","April","May","June",
			"July","August","September","October","November","December" ], // Names of months for drop-down and formatting
		monthNamesShort: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // For formatting
		dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // For formatting
		dayNamesShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // For formatting
		dayNamesMin: [ "Su","Mo","Tu","We","Th","Fr","Sa" ], // Column headings for days starting at Sunday
		weekHeader: "Wk", // Column header for week of the year
		dateFormat: "mm/dd/yy", // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: "" // Additional text to append to the year in the month headers
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: "focus", // "focus" for popup on focus,
			// "button" for trigger button, or "both" for either
		showAnim: "fadeIn", // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: "", // Display text following the input box, e.g. showing the format
		buttonText: "...", // Text for trigger button
		buttonImage: "", // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: "c-10:c+10", // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: "+10", // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with "+" for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: "fast", // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: "", // Selector for an alternate field to store selected dates into
		altFormat: "", // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false, // True to size the input for the date format, false to leave as is
		disabled: false // The initial disabled state
	};
	$.extend( this._defaults, this.regional[ "" ] );
	this.regional.en = $.extend( true, {}, this.regional[ "" ] );
	this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
	this.dpDiv = datepicker_bindHover( $( "<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) );
}

$.extend( Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: "hasDatepicker",

	//Keep track of the maximum number of rows displayed (see #7043)
	maxRows: 4,

	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	 * @param  settings  object - the new settings to use as defaults (anonymous object)
	 * @return the manager object
	 */
	setDefaults: function( settings ) {
		datepicker_extendRemove( this._defaults, settings || {} );
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
	 */
	_attachDatepicker: function( target, settings ) {
		var nodeName, inline, inst;
		nodeName = target.nodeName.toLowerCase();
		inline = ( nodeName === "div" || nodeName === "span" );
		if ( !target.id ) {
			this.uuid += 1;
			target.id = "dp" + this.uuid;
		}
		inst = this._newInst( $( target ), inline );
		inst.settings = $.extend( {}, settings || {} );
		if ( nodeName === "input" ) {
			this._connectDatepicker( target, inst );
		} else if ( inline ) {
			this._inlineDatepicker( target, inst );
		}
	},

	/* Create a new instance object. */
	_newInst: function( target, inline ) {
		var id = target[ 0 ].id.replace( /([^A-Za-z0-9_\-])/g, "\\\\$1" ); // escape jQuery meta chars
		return { id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: ( !inline ? this.dpDiv : // presentation div
			datepicker_bindHover( $( "<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) ) ) };
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function( target, inst ) {
		var input = $( target );
		inst.append = $( [] );
		inst.trigger = $( [] );
		if ( input.hasClass( this.markerClassName ) ) {
			return;
		}
		this._attachments( input, inst );
		input.addClass( this.markerClassName ).on( "keydown", this._doKeyDown ).
			on( "keypress", this._doKeyPress ).on( "keyup", this._doKeyUp );
		this._autoSize( inst );
		$.data( target, "datepicker", inst );

		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
	},

	/* Make attachments based on settings. */
	_attachments: function( input, inst ) {
		var showOn, buttonText, buttonImage,
			appendText = this._get( inst, "appendText" ),
			isRTL = this._get( inst, "isRTL" );

		if ( inst.append ) {
			inst.append.remove();
		}
		if ( appendText ) {
			inst.append = $( "<span class='" + this._appendClass + "'>" + appendText + "</span>" );
			input[ isRTL ? "before" : "after" ]( inst.append );
		}

		input.off( "focus", this._showDatepicker );

		if ( inst.trigger ) {
			inst.trigger.remove();
		}

		showOn = this._get( inst, "showOn" );
		if ( showOn === "focus" || showOn === "both" ) { // pop-up date picker when in the marked field
			input.on( "focus", this._showDatepicker );
		}
		if ( showOn === "button" || showOn === "both" ) { // pop-up date picker when button clicked
			buttonText = this._get( inst, "buttonText" );
			buttonImage = this._get( inst, "buttonImage" );
			inst.trigger = $( this._get( inst, "buttonImageOnly" ) ?
				$( "<img/>" ).addClass( this._triggerClass ).
					attr( { src: buttonImage, alt: buttonText, title: buttonText } ) :
				$( "<button type='button'></button>" ).addClass( this._triggerClass ).
					html( !buttonImage ? buttonText : $( "<img/>" ).attr(
					{ src:buttonImage, alt:buttonText, title:buttonText } ) ) );
			input[ isRTL ? "before" : "after" ]( inst.trigger );
			inst.trigger.on( "click", function() {
				if ( $.datepicker._datepickerShowing && $.datepicker._lastInput === input[ 0 ] ) {
					$.datepicker._hideDatepicker();
				} else if ( $.datepicker._datepickerShowing && $.datepicker._lastInput !== input[ 0 ] ) {
					$.datepicker._hideDatepicker();
					$.datepicker._showDatepicker( input[ 0 ] );
				} else {
					$.datepicker._showDatepicker( input[ 0 ] );
				}
				return false;
			} );
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function( inst ) {
		if ( this._get( inst, "autoSize" ) && !inst.inline ) {
			var findMax, max, maxI, i,
				date = new Date( 2009, 12 - 1, 20 ), // Ensure double digits
				dateFormat = this._get( inst, "dateFormat" );

			if ( dateFormat.match( /[DM]/ ) ) {
				findMax = function( names ) {
					max = 0;
					maxI = 0;
					for ( i = 0; i < names.length; i++ ) {
						if ( names[ i ].length > max ) {
							max = names[ i ].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth( findMax( this._get( inst, ( dateFormat.match( /MM/ ) ?
					"monthNames" : "monthNamesShort" ) ) ) );
				date.setDate( findMax( this._get( inst, ( dateFormat.match( /DD/ ) ?
					"dayNames" : "dayNamesShort" ) ) ) + 20 - date.getDay() );
			}
			inst.input.attr( "size", this._formatDate( inst, date ).length );
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function( target, inst ) {
		var divSpan = $( target );
		if ( divSpan.hasClass( this.markerClassName ) ) {
			return;
		}
		divSpan.addClass( this.markerClassName ).append( inst.dpDiv );
		$.data( target, "datepicker", inst );
		this._setDate( inst, this._getDefaultDate( inst ), true );
		this._updateDatepicker( inst );
		this._updateAlternate( inst );

		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}

		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
		// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
		inst.dpDiv.css( "display", "block" );
	},

	/* Pop-up the date picker in a "dialog" box.
	 * @param  input element - ignored
	 * @param  date	string or Date - the initial date to display
	 * @param  onSelect  function - the function to call when a date is selected
	 * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	 * @param  pos int[2] - coordinates for the dialog's position within the screen or
	 *					event - with x/y coordinates or
	 *					leave empty for default (screen centre)
	 * @return the manager object
	 */
	_dialogDatepicker: function( input, date, onSelect, settings, pos ) {
		var id, browserWidth, browserHeight, scrollX, scrollY,
			inst = this._dialogInst; // internal instance

		if ( !inst ) {
			this.uuid += 1;
			id = "dp" + this.uuid;
			this._dialogInput = $( "<input type='text' id='" + id +
				"' style='position: absolute; top: -100px; width: 0px;'/>" );
			this._dialogInput.on( "keydown", this._doKeyDown );
			$( "body" ).append( this._dialogInput );
			inst = this._dialogInst = this._newInst( this._dialogInput, false );
			inst.settings = {};
			$.data( this._dialogInput[ 0 ], "datepicker", inst );
		}
		datepicker_extendRemove( inst.settings, settings || {} );
		date = ( date && date.constructor === Date ? this._formatDate( inst, date ) : date );
		this._dialogInput.val( date );

		this._pos = ( pos ? ( pos.length ? pos : [ pos.pageX, pos.pageY ] ) : null );
		if ( !this._pos ) {
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[ ( browserWidth / 2 ) - 100 + scrollX, ( browserHeight / 2 ) - 150 + scrollY ];
		}

		// Move input on screen for focus, but hidden behind dialog
		this._dialogInput.css( "left", ( this._pos[ 0 ] + 20 ) + "px" ).css( "top", this._pos[ 1 ] + "px" );
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass( this._dialogClass );
		this._showDatepicker( this._dialogInput[ 0 ] );
		if ( $.blockUI ) {
			$.blockUI( this.dpDiv );
		}
		$.data( this._dialogInput[ 0 ], "datepicker", inst );
		return this;
	},

	/* Detach a datepicker from its control.
	 * @param  target	element - the target input field or division or span
	 */
	_destroyDatepicker: function( target ) {
		var nodeName,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData( target, "datepicker" );
		if ( nodeName === "input" ) {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass( this.markerClassName ).
				off( "focus", this._showDatepicker ).
				off( "keydown", this._doKeyDown ).
				off( "keypress", this._doKeyPress ).
				off( "keyup", this._doKeyUp );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			$target.removeClass( this.markerClassName ).empty();
		}

		if ( datepicker_instActive === inst ) {
			datepicker_instActive = null;
		}
	},

	/* Enable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_enableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = false;
			inst.trigger.filter( "button" ).
				each( function() { this.disabled = false; } ).end().
				filter( "img" ).css( { opacity: "1.0", cursor: "" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().removeClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", false );
		}
		this._disabledInputs = $.map( this._disabledInputs,
			function( value ) { return ( value === target ? null : value ); } ); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_disableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = true;
			inst.trigger.filter( "button" ).
				each( function() { this.disabled = true; } ).end().
				filter( "img" ).css( { opacity: "0.5", cursor: "default" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().addClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", true );
		}
		this._disabledInputs = $.map( this._disabledInputs,
			function( value ) { return ( value === target ? null : value ); } ); // delete entry
		this._disabledInputs[ this._disabledInputs.length ] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	 * @param  target	element - the target input field or division or span
	 * @return boolean - true if disabled, false if enabled
	 */
	_isDisabledDatepicker: function( target ) {
		if ( !target ) {
			return false;
		}
		for ( var i = 0; i < this._disabledInputs.length; i++ ) {
			if ( this._disabledInputs[ i ] === target ) {
				return true;
			}
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	 * @param  target  element - the target input field or division or span
	 * @return  object - the associated instance data
	 * @throws  error if a jQuery problem getting data
	 */
	_getInst: function( target ) {
		try {
			return $.data( target, "datepicker" );
		}
		catch ( err ) {
			throw "Missing instance data for this datepicker";
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 * @param  name	object - the new settings to update or
	 *				string - the name of the setting to change or retrieve,
	 *				when retrieving also "all" for all instance settings or
	 *				"defaults" for all global defaults
	 * @param  value   any - the new value for the setting
	 *				(omit if above is an object or to retrieve a value)
	 */
	_optionDatepicker: function( target, name, value ) {
		var settings, date, minDate, maxDate,
			inst = this._getInst( target );

		if ( arguments.length === 2 && typeof name === "string" ) {
			return ( name === "defaults" ? $.extend( {}, $.datepicker._defaults ) :
				( inst ? ( name === "all" ? $.extend( {}, inst.settings ) :
				this._get( inst, name ) ) : null ) );
		}

		settings = name || {};
		if ( typeof name === "string" ) {
			settings = {};
			settings[ name ] = value;
		}

		if ( inst ) {
			if ( this._curInst === inst ) {
				this._hideDatepicker();
			}

			date = this._getDateDatepicker( target, true );
			minDate = this._getMinMaxDate( inst, "min" );
			maxDate = this._getMinMaxDate( inst, "max" );
			datepicker_extendRemove( inst.settings, settings );

			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if ( minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined ) {
				inst.settings.minDate = this._formatDate( inst, minDate );
			}
			if ( maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined ) {
				inst.settings.maxDate = this._formatDate( inst, maxDate );
			}
			if ( "disabled" in settings ) {
				if ( settings.disabled ) {
					this._disableDatepicker( target );
				} else {
					this._enableDatepicker( target );
				}
			}
			this._attachments( $( target ), inst );
			this._autoSize( inst );
			this._setDate( inst, date );
			this._updateAlternate( inst );
			this._updateDatepicker( inst );
		}
	},

	// Change method deprecated
	_changeDatepicker: function( target, name, value ) {
		this._optionDatepicker( target, name, value );
	},

	/* Redraw the date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 */
	_refreshDatepicker: function( target ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._updateDatepicker( inst );
		}
	},

	/* Set the dates for a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  date	Date - the new date
	 */
	_setDateDatepicker: function( target, date ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._setDate( inst, date );
			this._updateDatepicker( inst );
			this._updateAlternate( inst );
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  noDefault boolean - true if no default date is to be used
	 * @return Date - the current date
	 */
	_getDateDatepicker: function( target, noDefault ) {
		var inst = this._getInst( target );
		if ( inst && !inst.inline ) {
			this._setDateFromField( inst, noDefault );
		}
		return ( inst ? this._getDate( inst ) : null );
	},

	/* Handle keystrokes. */
	_doKeyDown: function( event ) {
		var onSelect, dateStr, sel,
			inst = $.datepicker._getInst( event.target ),
			handled = true,
			isRTL = inst.dpDiv.is( ".ui-datepicker-rtl" );

		inst._keyEvent = true;
		if ( $.datepicker._datepickerShowing ) {
			switch ( event.keyCode ) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: sel = $( "td." + $.datepicker._dayOverClass + ":not(." +
									$.datepicker._currentClass + ")", inst.dpDiv );
						if ( sel[ 0 ] ) {
							$.datepicker._selectDay( event.target, inst.selectedMonth, inst.selectedYear, sel[ 0 ] );
						}

						onSelect = $.datepicker._get( inst, "onSelect" );
						if ( onSelect ) {
							dateStr = $.datepicker._formatDate( inst );

							// Trigger custom callback
							onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );
						} else {
							$.datepicker._hideDatepicker();
						}

						return false; // don't submit the form
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							-$.datepicker._get( inst, "stepBigMonths" ) :
							-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							+$.datepicker._get( inst, "stepBigMonths" ) :
							+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // next month/year on page down/+ ctrl
				case 35: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._clearDate( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._gotoToday( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? +1 : -1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// -1 day on ctrl or command +left
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								-$.datepicker._get( inst, "stepBigMonths" ) :
								-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +left on Mac
						break;
				case 38: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, -7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? -1 : +1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// +1 day on ctrl or command +right
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								+$.datepicker._get( inst, "stepBigMonths" ) :
								+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +right
						break;
				case 40: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, +7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		} else if ( event.keyCode === 36 && event.ctrlKey ) { // display the date picker on ctrl+home
			$.datepicker._showDatepicker( this );
		} else {
			handled = false;
		}

		if ( handled ) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function( event ) {
		var chars, chr,
			inst = $.datepicker._getInst( event.target );

		if ( $.datepicker._get( inst, "constrainInput" ) ) {
			chars = $.datepicker._possibleChars( $.datepicker._get( inst, "dateFormat" ) );
			chr = String.fromCharCode( event.charCode == null ? event.keyCode : event.charCode );
			return event.ctrlKey || event.metaKey || ( chr < " " || !chars || chars.indexOf( chr ) > -1 );
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function( event ) {
		var date,
			inst = $.datepicker._getInst( event.target );

		if ( inst.input.val() !== inst.lastVal ) {
			try {
				date = $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
					( inst.input ? inst.input.val() : null ),
					$.datepicker._getFormatConfig( inst ) );

				if ( date ) { // only if valid
					$.datepicker._setDateFromField( inst );
					$.datepicker._updateAlternate( inst );
					$.datepicker._updateDatepicker( inst );
				}
			}
			catch ( err ) {
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	 * If false returned from beforeShow event handler do not show.
	 * @param  input  element - the input field attached to the date picker or
	 *					event - if triggered by focus
	 */
	_showDatepicker: function( input ) {
		input = input.target || input;
		if ( input.nodeName.toLowerCase() !== "input" ) { // find from button/image trigger
			input = $( "input", input.parentNode )[ 0 ];
		}

		if ( $.datepicker._isDisabledDatepicker( input ) || $.datepicker._lastInput === input ) { // already here
			return;
		}

		var inst, beforeShow, beforeShowSettings, isFixed,
			offset, showAnim, duration;

		inst = $.datepicker._getInst( input );
		if ( $.datepicker._curInst && $.datepicker._curInst !== inst ) {
			$.datepicker._curInst.dpDiv.stop( true, true );
			if ( inst && $.datepicker._datepickerShowing ) {
				$.datepicker._hideDatepicker( $.datepicker._curInst.input[ 0 ] );
			}
		}

		beforeShow = $.datepicker._get( inst, "beforeShow" );
		beforeShowSettings = beforeShow ? beforeShow.apply( input, [ input, inst ] ) : {};
		if ( beforeShowSettings === false ) {
			return;
		}
		datepicker_extendRemove( inst.settings, beforeShowSettings );

		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField( inst );

		if ( $.datepicker._inDialog ) { // hide cursor
			input.value = "";
		}
		if ( !$.datepicker._pos ) { // position below input
			$.datepicker._pos = $.datepicker._findPos( input );
			$.datepicker._pos[ 1 ] += input.offsetHeight; // add the height
		}

		isFixed = false;
		$( input ).parents().each( function() {
			isFixed |= $( this ).css( "position" ) === "fixed";
			return !isFixed;
		} );

		offset = { left: $.datepicker._pos[ 0 ], top: $.datepicker._pos[ 1 ] };
		$.datepicker._pos = null;

		//to avoid flashes on Firefox
		inst.dpDiv.empty();

		// determine sizing offscreen
		inst.dpDiv.css( { position: "absolute", display: "block", top: "-1000px" } );
		$.datepicker._updateDatepicker( inst );

		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset( inst, offset, isFixed );
		inst.dpDiv.css( { position: ( $.datepicker._inDialog && $.blockUI ?
			"static" : ( isFixed ? "fixed" : "absolute" ) ), display: "none",
			left: offset.left + "px", top: offset.top + "px" } );

		if ( !inst.inline ) {
			showAnim = $.datepicker._get( inst, "showAnim" );
			duration = $.datepicker._get( inst, "duration" );
			inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
			$.datepicker._datepickerShowing = true;

			if ( $.effects && $.effects.effect[ showAnim ] ) {
				inst.dpDiv.show( showAnim, $.datepicker._get( inst, "showOptions" ), duration );
			} else {
				inst.dpDiv[ showAnim || "show" ]( showAnim ? duration : null );
			}

			if ( $.datepicker._shouldFocusInput( inst ) ) {
				inst.input.trigger( "focus" );
			}

			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function( inst ) {
		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
		datepicker_instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append( this._generateHTML( inst ) );
		this._attachHandlers( inst );

		var origyearshtml,
			numMonths = this._getNumberOfMonths( inst ),
			cols = numMonths[ 1 ],
			width = 17,
			activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );

		if ( activeCell.length > 0 ) {
			datepicker_handleMouseover.apply( activeCell.get( 0 ) );
		}

		inst.dpDiv.removeClass( "ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4" ).width( "" );
		if ( cols > 1 ) {
			inst.dpDiv.addClass( "ui-datepicker-multi-" + cols ).css( "width", ( width * cols ) + "em" );
		}
		inst.dpDiv[ ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-multi" );
		inst.dpDiv[ ( this._get( inst, "isRTL" ) ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-rtl" );

		if ( inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
			inst.input.trigger( "focus" );
		}

		// Deffered render of the years select (to avoid flashes on Firefox)
		if ( inst.yearshtml ) {
			origyearshtml = inst.yearshtml;
			setTimeout( function() {

				//assure that inst.yearshtml didn't change.
				if ( origyearshtml === inst.yearshtml && inst.yearshtml ) {
					inst.dpDiv.find( "select.ui-datepicker-year:first" ).replaceWith( inst.yearshtml );
				}
				origyearshtml = inst.yearshtml = null;
			}, 0 );
		}
	},

	// #6694 - don't focus the input if it's already focused
	// this breaks the change event in IE
	// Support: IE and jQuery <1.9
	_shouldFocusInput: function( inst ) {
		return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function( inst, offset, isFixed ) {
		var dpWidth = inst.dpDiv.outerWidth(),
			dpHeight = inst.dpDiv.outerHeight(),
			inputWidth = inst.input ? inst.input.outerWidth() : 0,
			inputHeight = inst.input ? inst.input.outerHeight() : 0,
			viewWidth = document.documentElement.clientWidth + ( isFixed ? 0 : $( document ).scrollLeft() ),
			viewHeight = document.documentElement.clientHeight + ( isFixed ? 0 : $( document ).scrollTop() );

		offset.left -= ( this._get( inst, "isRTL" ) ? ( dpWidth - inputWidth ) : 0 );
		offset.left -= ( isFixed && offset.left === inst.input.offset().left ) ? $( document ).scrollLeft() : 0;
		offset.top -= ( isFixed && offset.top === ( inst.input.offset().top + inputHeight ) ) ? $( document ).scrollTop() : 0;

		// Now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= Math.min( offset.left, ( offset.left + dpWidth > viewWidth && viewWidth > dpWidth ) ?
			Math.abs( offset.left + dpWidth - viewWidth ) : 0 );
		offset.top -= Math.min( offset.top, ( offset.top + dpHeight > viewHeight && viewHeight > dpHeight ) ?
			Math.abs( dpHeight + inputHeight ) : 0 );

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function( obj ) {
		var position,
			inst = this._getInst( obj ),
			isRTL = this._get( inst, "isRTL" );

		while ( obj && ( obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden( obj ) ) ) {
			obj = obj[ isRTL ? "previousSibling" : "nextSibling" ];
		}

		position = $( obj ).offset();
		return [ position.left, position.top ];
	},

	/* Hide the date picker from view.
	 * @param  input  element - the input field attached to the date picker
	 */
	_hideDatepicker: function( input ) {
		var showAnim, duration, postProcess, onClose,
			inst = this._curInst;

		if ( !inst || ( input && inst !== $.data( input, "datepicker" ) ) ) {
			return;
		}

		if ( this._datepickerShowing ) {
			showAnim = this._get( inst, "showAnim" );
			duration = this._get( inst, "duration" );
			postProcess = function() {
				$.datepicker._tidyDialog( inst );
			};

			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
				inst.dpDiv.hide( showAnim, $.datepicker._get( inst, "showOptions" ), duration, postProcess );
			} else {
				inst.dpDiv[ ( showAnim === "slideDown" ? "slideUp" :
					( showAnim === "fadeIn" ? "fadeOut" : "hide" ) ) ]( ( showAnim ? duration : null ), postProcess );
			}

			if ( !showAnim ) {
				postProcess();
			}
			this._datepickerShowing = false;

			onClose = this._get( inst, "onClose" );
			if ( onClose ) {
				onClose.apply( ( inst.input ? inst.input[ 0 ] : null ), [ ( inst.input ? inst.input.val() : "" ), inst ] );
			}

			this._lastInput = null;
			if ( this._inDialog ) {
				this._dialogInput.css( { position: "absolute", left: "0", top: "-100px" } );
				if ( $.blockUI ) {
					$.unblockUI();
					$( "body" ).append( this.dpDiv );
				}
			}
			this._inDialog = false;
		}
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function( inst ) {
		inst.dpDiv.removeClass( this._dialogClass ).off( ".ui-datepicker-calendar" );
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function( event ) {
		if ( !$.datepicker._curInst ) {
			return;
		}

		var $target = $( event.target ),
			inst = $.datepicker._getInst( $target[ 0 ] );

		if ( ( ( $target[ 0 ].id !== $.datepicker._mainDivId &&
				$target.parents( "#" + $.datepicker._mainDivId ).length === 0 &&
				!$target.hasClass( $.datepicker.markerClassName ) &&
				!$target.closest( "." + $.datepicker._triggerClass ).length &&
				$.datepicker._datepickerShowing && !( $.datepicker._inDialog && $.blockUI ) ) ) ||
			( $target.hasClass( $.datepicker.markerClassName ) && $.datepicker._curInst !== inst ) ) {
				$.datepicker._hideDatepicker();
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function( id, offset, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}
		this._adjustInstDate( inst, offset +
			( period === "M" ? this._get( inst, "showCurrentAtPos" ) : 0 ), // undo positioning
			period );
		this._updateDatepicker( inst );
	},

	/* Action for current link. */
	_gotoToday: function( id ) {
		var date,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._get( inst, "gotoCurrent" ) && inst.currentDay ) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function( id, select, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		inst[ "selected" + ( period === "M" ? "Month" : "Year" ) ] =
		inst[ "draw" + ( period === "M" ? "Month" : "Year" ) ] =
			parseInt( select.options[ select.selectedIndex ].value, 10 );

		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a day. */
	_selectDay: function( id, month, year, td ) {
		var inst,
			target = $( id );

		if ( $( td ).hasClass( this._unselectableClass ) || this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}

		inst = this._getInst( target[ 0 ] );
		inst.selectedDay = inst.currentDay = $( "a", td ).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate( id, this._formatDate( inst,
			inst.currentDay, inst.currentMonth, inst.currentYear ) );
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function( id ) {
		var target = $( id );
		this._selectDate( target, "" );
	},

	/* Update the input field with the selected date. */
	_selectDate: function( id, dateStr ) {
		var onSelect,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		dateStr = ( dateStr != null ? dateStr : this._formatDate( inst ) );
		if ( inst.input ) {
			inst.input.val( dateStr );
		}
		this._updateAlternate( inst );

		onSelect = this._get( inst, "onSelect" );
		if ( onSelect ) {
			onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );  // trigger custom callback
		} else if ( inst.input ) {
			inst.input.trigger( "change" ); // fire the change event
		}

		if ( inst.inline ) {
			this._updateDatepicker( inst );
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[ 0 ];
			if ( typeof( inst.input[ 0 ] ) !== "object" ) {
				inst.input.trigger( "focus" ); // restore focus
			}
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function( inst ) {
		var altFormat, date, dateStr,
			altField = this._get( inst, "altField" );

		if ( altField ) { // update alternate field too
			altFormat = this._get( inst, "altFormat" ) || this._get( inst, "dateFormat" );
			date = this._getDate( inst );
			dateStr = this.formatDate( altFormat, date, this._getFormatConfig( inst ) );
			$( altField ).val( dateStr );
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	 * @param  date  Date - the date to customise
	 * @return [boolean, string] - is this date selectable?, what is its CSS class?
	 */
	noWeekends: function( date ) {
		var day = date.getDay();
		return [ ( day > 0 && day < 6 ), "" ];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	 * @param  date  Date - the date to get the week for
	 * @return  number - the number of the week within the year that contains this date
	 */
	iso8601Week: function( date ) {
		var time,
			checkDate = new Date( date.getTime() );

		// Find Thursday of this week starting on Monday
		checkDate.setDate( checkDate.getDate() + 4 - ( checkDate.getDay() || 7 ) );

		time = checkDate.getTime();
		checkDate.setMonth( 0 ); // Compare with Jan 1
		checkDate.setDate( 1 );
		return Math.floor( Math.round( ( time - checkDate ) / 86400000 ) / 7 ) + 1;
	},

	/* Parse a string value into a date object.
	 * See formatDate below for the possible formats.
	 *
	 * @param  format string - the expected format of the date
	 * @param  value string - the date in the above format
	 * @param  settings Object - attributes include:
	 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  Date - the extracted date value or null if value is blank
	 */
	parseDate: function( format, value, settings ) {
		if ( format == null || value == null ) {
			throw "Invalid arguments";
		}

		value = ( typeof value === "object" ? value.toString() : value + "" );
		if ( value === "" ) {
			return null;
		}

		var iFormat, dim, extra,
			iValue = 0,
			shortYearCutoffTemp = ( settings ? settings.shortYearCutoff : null ) || this._defaults.shortYearCutoff,
			shortYearCutoff = ( typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
				new Date().getFullYear() % 100 + parseInt( shortYearCutoffTemp, 10 ) ),
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,
			year = -1,
			month = -1,
			day = -1,
			doy = -1,
			literal = false,
			date,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Extract a number from the string value
			getNumber = function( match ) {
				var isDoubled = lookAhead( match ),
					size = ( match === "@" ? 14 : ( match === "!" ? 20 :
					( match === "y" && isDoubled ? 4 : ( match === "o" ? 3 : 2 ) ) ) ),
					minSize = ( match === "y" ? size : 1 ),
					digits = new RegExp( "^\\d{" + minSize + "," + size + "}" ),
					num = value.substring( iValue ).match( digits );
				if ( !num ) {
					throw "Missing number at position " + iValue;
				}
				iValue += num[ 0 ].length;
				return parseInt( num[ 0 ], 10 );
			},

			// Extract a name from the string value and convert to an index
			getName = function( match, shortNames, longNames ) {
				var index = -1,
					names = $.map( lookAhead( match ) ? longNames : shortNames, function( v, k ) {
						return [ [ k, v ] ];
					} ).sort( function( a, b ) {
						return -( a[ 1 ].length - b[ 1 ].length );
					} );

				$.each( names, function( i, pair ) {
					var name = pair[ 1 ];
					if ( value.substr( iValue, name.length ).toLowerCase() === name.toLowerCase() ) {
						index = pair[ 0 ];
						iValue += name.length;
						return false;
					}
				} );
				if ( index !== -1 ) {
					return index + 1;
				} else {
					throw "Unknown name at position " + iValue;
				}
			},

			// Confirm that a literal character matches the string value
			checkLiteral = function() {
				if ( value.charAt( iValue ) !== format.charAt( iFormat ) ) {
					throw "Unexpected literal at position " + iValue;
				}
				iValue++;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					checkLiteral();
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d":
						day = getNumber( "d" );
						break;
					case "D":
						getName( "D", dayNamesShort, dayNames );
						break;
					case "o":
						doy = getNumber( "o" );
						break;
					case "m":
						month = getNumber( "m" );
						break;
					case "M":
						month = getName( "M", monthNamesShort, monthNames );
						break;
					case "y":
						year = getNumber( "y" );
						break;
					case "@":
						date = new Date( getNumber( "@" ) );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "!":
						date = new Date( ( getNumber( "!" ) - this._ticksTo1970 ) / 10000 );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if ( lookAhead( "'" ) ) {
							checkLiteral();
						} else {
							literal = true;
						}
						break;
					default:
						checkLiteral();
				}
			}
		}

		if ( iValue < value.length ) {
			extra = value.substr( iValue );
			if ( !/^\s+/.test( extra ) ) {
				throw "Extra/unparsed characters found in date: " + extra;
			}
		}

		if ( year === -1 ) {
			year = new Date().getFullYear();
		} else if ( year < 100 ) {
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				( year <= shortYearCutoff ? 0 : -100 );
		}

		if ( doy > -1 ) {
			month = 1;
			day = doy;
			do {
				dim = this._getDaysInMonth( year, month - 1 );
				if ( day <= dim ) {
					break;
				}
				month++;
				day -= dim;
			} while ( true );
		}

		date = this._daylightSavingAdjust( new Date( year, month - 1, day ) );
		if ( date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day ) {
			throw "Invalid date"; // E.g. 31/02/00
		}
		return date;
	},

	/* Standard date formats. */
	ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
	COOKIE: "D, dd M yy",
	ISO_8601: "yy-mm-dd",
	RFC_822: "D, d M y",
	RFC_850: "DD, dd-M-y",
	RFC_1036: "D, d M y",
	RFC_1123: "D, d M yy",
	RFC_2822: "D, d M yy",
	RSS: "D, d M y", // RFC 822
	TICKS: "!",
	TIMESTAMP: "@",
	W3C: "yy-mm-dd", // ISO 8601

	_ticksTo1970: ( ( ( 1970 - 1 ) * 365 + Math.floor( 1970 / 4 ) - Math.floor( 1970 / 100 ) +
		Math.floor( 1970 / 400 ) ) * 24 * 60 * 60 * 10000000 ),

	/* Format a date object into a string value.
	 * The format can be combinations of the following:
	 * d  - day of month (no leading zero)
	 * dd - day of month (two digit)
	 * o  - day of year (no leading zeros)
	 * oo - day of year (three digit)
	 * D  - day name short
	 * DD - day name long
	 * m  - month of year (no leading zero)
	 * mm - month of year (two digit)
	 * M  - month name short
	 * MM - month name long
	 * y  - year (two digit)
	 * yy - year (four digit)
	 * @ - Unix timestamp (ms since 01/01/1970)
	 * ! - Windows ticks (100ns since 01/01/0001)
	 * "..." - literal text
	 * '' - single quote
	 *
	 * @param  format string - the desired format of the date
	 * @param  date Date - the date value to format
	 * @param  settings Object - attributes include:
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  string - the date in the above format
	 */
	formatDate: function( format, date, settings ) {
		if ( !date ) {
			return "";
		}

		var iFormat,
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Format a number, with leading zero if necessary
			formatNumber = function( match, value, len ) {
				var num = "" + value;
				if ( lookAhead( match ) ) {
					while ( num.length < len ) {
						num = "0" + num;
					}
				}
				return num;
			},

			// Format a name, short or long as requested
			formatName = function( match, value, shortNames, longNames ) {
				return ( lookAhead( match ) ? longNames[ value ] : shortNames[ value ] );
			},
			output = "",
			literal = false;

		if ( date ) {
			for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
				if ( literal ) {
					if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
						literal = false;
					} else {
						output += format.charAt( iFormat );
					}
				} else {
					switch ( format.charAt( iFormat ) ) {
						case "d":
							output += formatNumber( "d", date.getDate(), 2 );
							break;
						case "D":
							output += formatName( "D", date.getDay(), dayNamesShort, dayNames );
							break;
						case "o":
							output += formatNumber( "o",
								Math.round( ( new Date( date.getFullYear(), date.getMonth(), date.getDate() ).getTime() - new Date( date.getFullYear(), 0, 0 ).getTime() ) / 86400000 ), 3 );
							break;
						case "m":
							output += formatNumber( "m", date.getMonth() + 1, 2 );
							break;
						case "M":
							output += formatName( "M", date.getMonth(), monthNamesShort, monthNames );
							break;
						case "y":
							output += ( lookAhead( "y" ) ? date.getFullYear() :
								( date.getFullYear() % 100 < 10 ? "0" : "" ) + date.getFullYear() % 100 );
							break;
						case "@":
							output += date.getTime();
							break;
						case "!":
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if ( lookAhead( "'" ) ) {
								output += "'";
							} else {
								literal = true;
							}
							break;
						default:
							output += format.charAt( iFormat );
					}
				}
			}
		}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function( format ) {
		var iFormat,
			chars = "",
			literal = false,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					chars += format.charAt( iFormat );
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d": case "m": case "y": case "@":
						chars += "0123456789";
						break;
					case "D": case "M":
						return null; // Accept anything
					case "'":
						if ( lookAhead( "'" ) ) {
							chars += "'";
						} else {
							literal = true;
						}
						break;
					default:
						chars += format.charAt( iFormat );
				}
			}
		}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function( inst, name ) {
		return inst.settings[ name ] !== undefined ?
			inst.settings[ name ] : this._defaults[ name ];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function( inst, noDefault ) {
		if ( inst.input.val() === inst.lastVal ) {
			return;
		}

		var dateFormat = this._get( inst, "dateFormat" ),
			dates = inst.lastVal = inst.input ? inst.input.val() : null,
			defaultDate = this._getDefaultDate( inst ),
			date = defaultDate,
			settings = this._getFormatConfig( inst );

		try {
			date = this.parseDate( dateFormat, dates, settings ) || defaultDate;
		} catch ( event ) {
			dates = ( noDefault ? "" : dates );
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = ( dates ? date.getDate() : 0 );
		inst.currentMonth = ( dates ? date.getMonth() : 0 );
		inst.currentYear = ( dates ? date.getFullYear() : 0 );
		this._adjustInstDate( inst );
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function( inst ) {
		return this._restrictMinMax( inst,
			this._determineDate( inst, this._get( inst, "defaultDate" ), new Date() ) );
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function( inst, date, defaultDate ) {
		var offsetNumeric = function( offset ) {
				var date = new Date();
				date.setDate( date.getDate() + offset );
				return date;
			},
			offsetString = function( offset ) {
				try {
					return $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
						offset, $.datepicker._getFormatConfig( inst ) );
				}
				catch ( e ) {

					// Ignore
				}

				var date = ( offset.toLowerCase().match( /^c/ ) ?
					$.datepicker._getDate( inst ) : null ) || new Date(),
					year = date.getFullYear(),
					month = date.getMonth(),
					day = date.getDate(),
					pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
					matches = pattern.exec( offset );

				while ( matches ) {
					switch ( matches[ 2 ] || "d" ) {
						case "d" : case "D" :
							day += parseInt( matches[ 1 ], 10 ); break;
						case "w" : case "W" :
							day += parseInt( matches[ 1 ], 10 ) * 7; break;
						case "m" : case "M" :
							month += parseInt( matches[ 1 ], 10 );
							day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
							break;
						case "y": case "Y" :
							year += parseInt( matches[ 1 ], 10 );
							day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
							break;
					}
					matches = pattern.exec( offset );
				}
				return new Date( year, month, day );
			},
			newDate = ( date == null || date === "" ? defaultDate : ( typeof date === "string" ? offsetString( date ) :
				( typeof date === "number" ? ( isNaN( date ) ? defaultDate : offsetNumeric( date ) ) : new Date( date.getTime() ) ) ) );

		newDate = ( newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate );
		if ( newDate ) {
			newDate.setHours( 0 );
			newDate.setMinutes( 0 );
			newDate.setSeconds( 0 );
			newDate.setMilliseconds( 0 );
		}
		return this._daylightSavingAdjust( newDate );
	},

	/* Handle switch to/from daylight saving.
	 * Hours may be non-zero on daylight saving cut-over:
	 * > 12 when midnight changeover, but then cannot generate
	 * midnight datetime, so jump to 1AM, otherwise reset.
	 * @param  date  (Date) the date to check
	 * @return  (Date) the corrected date
	 */
	_daylightSavingAdjust: function( date ) {
		if ( !date ) {
			return null;
		}
		date.setHours( date.getHours() > 12 ? date.getHours() + 2 : 0 );
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function( inst, date, noChange ) {
		var clear = !date,
			origMonth = inst.selectedMonth,
			origYear = inst.selectedYear,
			newDate = this._restrictMinMax( inst, this._determineDate( inst, date, new Date() ) );

		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ( ( origMonth !== inst.selectedMonth || origYear !== inst.selectedYear ) && !noChange ) {
			this._notifyChange( inst );
		}
		this._adjustInstDate( inst );
		if ( inst.input ) {
			inst.input.val( clear ? "" : this._formatDate( inst ) );
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function( inst ) {
		var startDate = ( !inst.currentYear || ( inst.input && inst.input.val() === "" ) ? null :
			this._daylightSavingAdjust( new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
			return startDate;
	},

	/* Attach the onxxx handlers.  These are declared statically so
	 * they work with static code transformers like Caja.
	 */
	_attachHandlers: function( inst ) {
		var stepMonths = this._get( inst, "stepMonths" ),
			id = "#" + inst.id.replace( /\\\\/g, "\\" );
		inst.dpDiv.find( "[data-handler]" ).map( function() {
			var handler = {
				prev: function() {
					$.datepicker._adjustDate( id, -stepMonths, "M" );
				},
				next: function() {
					$.datepicker._adjustDate( id, +stepMonths, "M" );
				},
				hide: function() {
					$.datepicker._hideDatepicker();
				},
				today: function() {
					$.datepicker._gotoToday( id );
				},
				selectDay: function() {
					$.datepicker._selectDay( id, +this.getAttribute( "data-month" ), +this.getAttribute( "data-year" ), this );
					return false;
				},
				selectMonth: function() {
					$.datepicker._selectMonthYear( id, this, "M" );
					return false;
				},
				selectYear: function() {
					$.datepicker._selectMonthYear( id, this, "Y" );
					return false;
				}
			};
			$( this ).on( this.getAttribute( "data-event" ), handler[ this.getAttribute( "data-handler" ) ] );
		} );
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function( inst ) {
		var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
			controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
			monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
			selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
			cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
			printDate, dRow, tbody, daySettings, otherMonth, unselectable,
			tempDate = new Date(),
			today = this._daylightSavingAdjust(
				new Date( tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate() ) ), // clear time
			isRTL = this._get( inst, "isRTL" ),
			showButtonPanel = this._get( inst, "showButtonPanel" ),
			hideIfNoPrevNext = this._get( inst, "hideIfNoPrevNext" ),
			navigationAsDateFormat = this._get( inst, "navigationAsDateFormat" ),
			numMonths = this._getNumberOfMonths( inst ),
			showCurrentAtPos = this._get( inst, "showCurrentAtPos" ),
			stepMonths = this._get( inst, "stepMonths" ),
			isMultiMonth = ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ),
			currentDate = this._daylightSavingAdjust( ( !inst.currentDay ? new Date( 9999, 9, 9 ) :
				new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) ),
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			drawMonth = inst.drawMonth - showCurrentAtPos,
			drawYear = inst.drawYear;

		if ( drawMonth < 0 ) {
			drawMonth += 12;
			drawYear--;
		}
		if ( maxDate ) {
			maxDraw = this._daylightSavingAdjust( new Date( maxDate.getFullYear(),
				maxDate.getMonth() - ( numMonths[ 0 ] * numMonths[ 1 ] ) + 1, maxDate.getDate() ) );
			maxDraw = ( minDate && maxDraw < minDate ? minDate : maxDraw );
			while ( this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 ) ) > maxDraw ) {
				drawMonth--;
				if ( drawMonth < 0 ) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;

		prevText = this._get( inst, "prevText" );
		prevText = ( !navigationAsDateFormat ? prevText : this.formatDate( prevText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth - stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		prev = ( this._canAdjustMonth( inst, -1, drawYear, drawMonth ) ?
			"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
			" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w" ) + "'>" + prevText + "</span></a>" :
			( hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w" ) + "'>" + prevText + "</span></a>" ) );

		nextText = this._get( inst, "nextText" );
		nextText = ( !navigationAsDateFormat ? nextText : this.formatDate( nextText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth + stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		next = ( this._canAdjustMonth( inst, +1, drawYear, drawMonth ) ?
			"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
			" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e" ) + "'>" + nextText + "</span></a>" :
			( hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e" ) + "'>" + nextText + "</span></a>" ) );

		currentText = this._get( inst, "currentText" );
		gotoDate = ( this._get( inst, "gotoCurrent" ) && inst.currentDay ? currentDate : today );
		currentText = ( !navigationAsDateFormat ? currentText :
			this.formatDate( currentText, gotoDate, this._getFormatConfig( inst ) ) );

		controls = ( !inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
			this._get( inst, "closeText" ) + "</button>" : "" );

		buttonPanel = ( showButtonPanel ) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + ( isRTL ? controls : "" ) +
			( this._isInRange( inst, gotoDate ) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
			">" + currentText + "</button>" : "" ) + ( isRTL ? "" : controls ) + "</div>" : "";

		firstDay = parseInt( this._get( inst, "firstDay" ), 10 );
		firstDay = ( isNaN( firstDay ) ? 0 : firstDay );

		showWeek = this._get( inst, "showWeek" );
		dayNames = this._get( inst, "dayNames" );
		dayNamesMin = this._get( inst, "dayNamesMin" );
		monthNames = this._get( inst, "monthNames" );
		monthNamesShort = this._get( inst, "monthNamesShort" );
		beforeShowDay = this._get( inst, "beforeShowDay" );
		showOtherMonths = this._get( inst, "showOtherMonths" );
		selectOtherMonths = this._get( inst, "selectOtherMonths" );
		defaultDate = this._getDefaultDate( inst );
		html = "";

		for ( row = 0; row < numMonths[ 0 ]; row++ ) {
			group = "";
			this.maxRows = 4;
			for ( col = 0; col < numMonths[ 1 ]; col++ ) {
				selectedDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, inst.selectedDay ) );
				cornerClass = " ui-corner-all";
				calender = "";
				if ( isMultiMonth ) {
					calender += "<div class='ui-datepicker-group";
					if ( numMonths[ 1 ] > 1 ) {
						switch ( col ) {
							case 0: calender += " ui-datepicker-group-first";
								cornerClass = " ui-corner-" + ( isRTL ? "right" : "left" ); break;
							case numMonths[ 1 ] - 1: calender += " ui-datepicker-group-last";
								cornerClass = " ui-corner-" + ( isRTL ? "left" : "right" ); break;
							default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
						}
					}
					calender += "'>";
				}
				calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
					( /all|left/.test( cornerClass ) && row === 0 ? ( isRTL ? next : prev ) : "" ) +
					( /all|right/.test( cornerClass ) && row === 0 ? ( isRTL ? prev : next ) : "" ) +
					this._generateMonthYearHeader( inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort ) + // draw month headers
					"</div><table class='ui-datepicker-calendar'><thead>" +
					"<tr>";
				thead = ( showWeek ? "<th class='ui-datepicker-week-col'>" + this._get( inst, "weekHeader" ) + "</th>" : "" );
				for ( dow = 0; dow < 7; dow++ ) { // days of the week
					day = ( dow + firstDay ) % 7;
					thead += "<th scope='col'" + ( ( dow + firstDay + 6 ) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "" ) + ">" +
						"<span title='" + dayNames[ day ] + "'>" + dayNamesMin[ day ] + "</span></th>";
				}
				calender += thead + "</tr></thead><tbody>";
				daysInMonth = this._getDaysInMonth( drawYear, drawMonth );
				if ( drawYear === inst.selectedYear && drawMonth === inst.selectedMonth ) {
					inst.selectedDay = Math.min( inst.selectedDay, daysInMonth );
				}
				leadDays = ( this._getFirstDayOfMonth( drawYear, drawMonth ) - firstDay + 7 ) % 7;
				curRows = Math.ceil( ( leadDays + daysInMonth ) / 7 ); // calculate the number of rows to generate
				numRows = ( isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows ); //If multiple months, use the higher number of rows (see #7043)
				this.maxRows = numRows;
				printDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 - leadDays ) );
				for ( dRow = 0; dRow < numRows; dRow++ ) { // create date picker rows
					calender += "<tr>";
					tbody = ( !showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
						this._get( inst, "calculateWeek" )( printDate ) + "</td>" );
					for ( dow = 0; dow < 7; dow++ ) { // create date picker days
						daySettings = ( beforeShowDay ?
							beforeShowDay.apply( ( inst.input ? inst.input[ 0 ] : null ), [ printDate ] ) : [ true, "" ] );
						otherMonth = ( printDate.getMonth() !== drawMonth );
						unselectable = ( otherMonth && !selectOtherMonths ) || !daySettings[ 0 ] ||
							( minDate && printDate < minDate ) || ( maxDate && printDate > maxDate );
						tbody += "<td class='" +
							( ( dow + firstDay + 6 ) % 7 >= 5 ? " ui-datepicker-week-end" : "" ) + // highlight weekends
							( otherMonth ? " ui-datepicker-other-month" : "" ) + // highlight days from other months
							( ( printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent ) || // user pressed key
							( defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime() ) ?

							// or defaultDate is current printedDate and defaultDate is selectedDate
							" " + this._dayOverClass : "" ) + // highlight selected day
							( unselectable ? " " + this._unselectableClass + " ui-state-disabled" : "" ) +  // highlight unselectable days
							( otherMonth && !showOtherMonths ? "" : " " + daySettings[ 1 ] + // highlight custom dates
							( printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "" ) + // highlight selected day
							( printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "" ) ) + "'" + // highlight today (if different)
							( ( !otherMonth || showOtherMonths ) && daySettings[ 2 ] ? " title='" + daySettings[ 2 ].replace( /'/g, "&#39;" ) + "'" : "" ) + // cell title
							( unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'" ) + ">" + // actions
							( otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
							( unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
							( printDate.getTime() === today.getTime() ? " ui-state-highlight" : "" ) +
							( printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "" ) + // highlight selected day
							( otherMonth ? " ui-priority-secondary" : "" ) + // distinguish dates from other months
							"' href='#'>" + printDate.getDate() + "</a>" ) ) + "</td>"; // display selectable date
						printDate.setDate( printDate.getDate() + 1 );
						printDate = this._daylightSavingAdjust( printDate );
					}
					calender += tbody + "</tr>";
				}
				drawMonth++;
				if ( drawMonth > 11 ) {
					drawMonth = 0;
					drawYear++;
				}
				calender += "</tbody></table>" + ( isMultiMonth ? "</div>" +
							( ( numMonths[ 0 ] > 0 && col === numMonths[ 1 ] - 1 ) ? "<div class='ui-datepicker-row-break'></div>" : "" ) : "" );
				group += calender;
			}
			html += group;
		}
		html += buttonPanel;
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function( inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort ) {

		var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
			changeMonth = this._get( inst, "changeMonth" ),
			changeYear = this._get( inst, "changeYear" ),
			showMonthAfterYear = this._get( inst, "showMonthAfterYear" ),
			html = "<div class='ui-datepicker-title'>",
			monthHtml = "";

		// Month selection
		if ( secondary || !changeMonth ) {
			monthHtml += "<span class='ui-datepicker-month'>" + monthNames[ drawMonth ] + "</span>";
		} else {
			inMinYear = ( minDate && minDate.getFullYear() === drawYear );
			inMaxYear = ( maxDate && maxDate.getFullYear() === drawYear );
			monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
			for ( month = 0; month < 12; month++ ) {
				if ( ( !inMinYear || month >= minDate.getMonth() ) && ( !inMaxYear || month <= maxDate.getMonth() ) ) {
					monthHtml += "<option value='" + month + "'" +
						( month === drawMonth ? " selected='selected'" : "" ) +
						">" + monthNamesShort[ month ] + "</option>";
				}
			}
			monthHtml += "</select>";
		}

		if ( !showMonthAfterYear ) {
			html += monthHtml + ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" );
		}

		// Year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = "";
			if ( secondary || !changeYear ) {
				html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
			} else {

				// determine range of years to display
				years = this._get( inst, "yearRange" ).split( ":" );
				thisYear = new Date().getFullYear();
				determineYear = function( value ) {
					var year = ( value.match( /c[+\-].*/ ) ? drawYear + parseInt( value.substring( 1 ), 10 ) :
						( value.match( /[+\-].*/ ) ? thisYear + parseInt( value, 10 ) :
						parseInt( value, 10 ) ) );
					return ( isNaN( year ) ? thisYear : year );
				};
				year = determineYear( years[ 0 ] );
				endYear = Math.max( year, determineYear( years[ 1 ] || "" ) );
				year = ( minDate ? Math.max( year, minDate.getFullYear() ) : year );
				endYear = ( maxDate ? Math.min( endYear, maxDate.getFullYear() ) : endYear );
				inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
				for ( ; year <= endYear; year++ ) {
					inst.yearshtml += "<option value='" + year + "'" +
						( year === drawYear ? " selected='selected'" : "" ) +
						">" + year + "</option>";
				}
				inst.yearshtml += "</select>";

				html += inst.yearshtml;
				inst.yearshtml = null;
			}
		}

		html += this._get( inst, "yearSuffix" );
		if ( showMonthAfterYear ) {
			html += ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" ) + monthHtml;
		}
		html += "</div>"; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function( inst, offset, period ) {
		var year = inst.selectedYear + ( period === "Y" ? offset : 0 ),
			month = inst.selectedMonth + ( period === "M" ? offset : 0 ),
			day = Math.min( inst.selectedDay, this._getDaysInMonth( year, month ) ) + ( period === "D" ? offset : 0 ),
			date = this._restrictMinMax( inst, this._daylightSavingAdjust( new Date( year, month, day ) ) );

		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if ( period === "M" || period === "Y" ) {
			this._notifyChange( inst );
		}
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function( inst, date ) {
		var minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			newDate = ( minDate && date < minDate ? minDate : date );
		return ( maxDate && newDate > maxDate ? maxDate : newDate );
	},

	/* Notify change of month/year. */
	_notifyChange: function( inst ) {
		var onChange = this._get( inst, "onChangeMonthYear" );
		if ( onChange ) {
			onChange.apply( ( inst.input ? inst.input[ 0 ] : null ),
				[ inst.selectedYear, inst.selectedMonth + 1, inst ] );
		}
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function( inst ) {
		var numMonths = this._get( inst, "numberOfMonths" );
		return ( numMonths == null ? [ 1, 1 ] : ( typeof numMonths === "number" ? [ 1, numMonths ] : numMonths ) );
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function( inst, minMax ) {
		return this._determineDate( inst, this._get( inst, minMax + "Date" ), null );
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function( year, month ) {
		return 32 - this._daylightSavingAdjust( new Date( year, month, 32 ) ).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function( year, month ) {
		return new Date( year, month, 1 ).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function( inst, offset, curYear, curMonth ) {
		var numMonths = this._getNumberOfMonths( inst ),
			date = this._daylightSavingAdjust( new Date( curYear,
			curMonth + ( offset < 0 ? offset : numMonths[ 0 ] * numMonths[ 1 ] ), 1 ) );

		if ( offset < 0 ) {
			date.setDate( this._getDaysInMonth( date.getFullYear(), date.getMonth() ) );
		}
		return this._isInRange( inst, date );
	},

	/* Is the given date in the accepted range? */
	_isInRange: function( inst, date ) {
		var yearSplit, currentYear,
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			minYear = null,
			maxYear = null,
			years = this._get( inst, "yearRange" );
			if ( years ) {
				yearSplit = years.split( ":" );
				currentYear = new Date().getFullYear();
				minYear = parseInt( yearSplit[ 0 ], 10 );
				maxYear = parseInt( yearSplit[ 1 ], 10 );
				if ( yearSplit[ 0 ].match( /[+\-].*/ ) ) {
					minYear += currentYear;
				}
				if ( yearSplit[ 1 ].match( /[+\-].*/ ) ) {
					maxYear += currentYear;
				}
			}

		return ( ( !minDate || date.getTime() >= minDate.getTime() ) &&
			( !maxDate || date.getTime() <= maxDate.getTime() ) &&
			( !minYear || date.getFullYear() >= minYear ) &&
			( !maxYear || date.getFullYear() <= maxYear ) );
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function( inst ) {
		var shortYearCutoff = this._get( inst, "shortYearCutoff" );
		shortYearCutoff = ( typeof shortYearCutoff !== "string" ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt( shortYearCutoff, 10 ) );
		return { shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get( inst, "dayNamesShort" ), dayNames: this._get( inst, "dayNames" ),
			monthNamesShort: this._get( inst, "monthNamesShort" ), monthNames: this._get( inst, "monthNames" ) };
	},

	/* Format the given date for display. */
	_formatDate: function( inst, day, month, year ) {
		if ( !day ) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = ( day ? ( typeof day === "object" ? day :
			this._daylightSavingAdjust( new Date( year, month, day ) ) ) :
			this._daylightSavingAdjust( new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
		return this.formatDate( this._get( inst, "dateFormat" ), date, this._getFormatConfig( inst ) );
	}
} );

/*
 * Bind hover events for datepicker elements.
 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function datepicker_bindHover( dpDiv ) {
	var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
	return dpDiv.on( "mouseout", selector, function() {
			$( this ).removeClass( "ui-state-hover" );
			if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-prev-hover" );
			}
			if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-next-hover" );
			}
		} )
		.on( "mouseover", selector, datepicker_handleMouseover );
}

function datepicker_handleMouseover() {
	if ( !$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? datepicker_instActive.dpDiv.parent()[ 0 ] : datepicker_instActive.input[ 0 ] ) ) {
		$( this ).parents( ".ui-datepicker-calendar" ).find( "a" ).removeClass( "ui-state-hover" );
		$( this ).addClass( "ui-state-hover" );
		if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-prev-hover" );
		}
		if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-next-hover" );
		}
	}
}

/* jQuery extend now ignores nulls! */
function datepicker_extendRemove( target, props ) {
	$.extend( target, props );
	for ( var name in props ) {
		if ( props[ name ] == null ) {
			target[ name ] = props[ name ];
		}
	}
	return target;
}

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
					Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function( options ) {

	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}

	/* Initialise the date picker. */
	if ( !$.datepicker.initialized ) {
		$( document ).on( "mousedown", $.datepicker._checkExternalClick );
		$.datepicker.initialized = true;
	}

	/* Append datepicker main container to body if not exist. */
	if ( $( "#" + $.datepicker._mainDivId ).length === 0 ) {
		$( "body" ).append( $.datepicker.dpDiv );
	}

	var otherArgs = Array.prototype.slice.call( arguments, 1 );
	if ( typeof options === "string" && ( options === "isDisabled" || options === "getDate" || options === "widget" ) ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	if ( options === "option" && arguments.length === 2 && typeof arguments[ 1 ] === "string" ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	return this.each( function() {
		typeof options === "string" ?
			$.datepicker[ "_" + options + "Datepicker" ].
				apply( $.datepicker, [ this ].concat( otherArgs ) ) :
			$.datepicker._attachDatepicker( this, options );
	} );
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.12.1";

var widgetsDatepicker = $.datepicker;


/*!
 * jQuery UI Dialog 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Dialog
//>>group: Widgets
//>>description: Displays customizable dialog windows.
//>>docs: http://api.jqueryui.com/dialog/
//>>demos: http://jqueryui.com/dialog/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/dialog.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.dialog", {
	version: "1.12.1",
	options: {
		appendTo: "body",
		autoOpen: true,
		buttons: [],
		classes: {
			"ui-dialog": "ui-corner-all",
			"ui-dialog-titlebar": "ui-corner-all"
		},
		closeOnEscape: true,
		closeText: "Close",
		draggable: true,
		hide: null,
		height: "auto",
		maxHeight: null,
		maxWidth: null,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: {
			my: "center",
			at: "center",
			of: window,
			collision: "fit",

			// Ensure the titlebar is always visible
			using: function( pos ) {
				var topOffset = $( this ).css( pos ).offset().top;
				if ( topOffset < 0 ) {
					$( this ).css( "top", pos.top - topOffset );
				}
			}
		},
		resizable: true,
		show: null,
		title: null,
		width: 300,

		// Callbacks
		beforeClose: null,
		close: null,
		drag: null,
		dragStart: null,
		dragStop: null,
		focus: null,
		open: null,
		resize: null,
		resizeStart: null,
		resizeStop: null
	},

	sizeRelatedOptions: {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},

	resizableRelatedOptions: {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	},

	_create: function() {
		this.originalCss = {
			display: this.element[ 0 ].style.display,
			width: this.element[ 0 ].style.width,
			minHeight: this.element[ 0 ].style.minHeight,
			maxHeight: this.element[ 0 ].style.maxHeight,
			height: this.element[ 0 ].style.height
		};
		this.originalPosition = {
			parent: this.element.parent(),
			index: this.element.parent().children().index( this.element )
		};
		this.originalTitle = this.element.attr( "title" );
		if ( this.options.title == null && this.originalTitle != null ) {
			this.options.title = this.originalTitle;
		}

		// Dialogs can't be disabled
		if ( this.options.disabled ) {
			this.options.disabled = false;
		}

		this._createWrapper();

		this.element
			.show()
			.removeAttr( "title" )
			.appendTo( this.uiDialog );

		this._addClass( "ui-dialog-content", "ui-widget-content" );

		this._createTitlebar();
		this._createButtonPane();

		if ( this.options.draggable && $.fn.draggable ) {
			this._makeDraggable();
		}
		if ( this.options.resizable && $.fn.resizable ) {
			this._makeResizable();
		}

		this._isOpen = false;

		this._trackFocus();
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;
		if ( element && ( element.jquery || element.nodeType ) ) {
			return $( element );
		}
		return this.document.find( element || "body" ).eq( 0 );
	},

	_destroy: function() {
		var next,
			originalPosition = this.originalPosition;

		this._untrackInstance();
		this._destroyOverlay();

		this.element
			.removeUniqueId()
			.css( this.originalCss )

			// Without detaching first, the following becomes really slow
			.detach();

		this.uiDialog.remove();

		if ( this.originalTitle ) {
			this.element.attr( "title", this.originalTitle );
		}

		next = originalPosition.parent.children().eq( originalPosition.index );

		// Don't try to place the dialog next to itself (#8613)
		if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
			next.before( this.element );
		} else {
			originalPosition.parent.append( this.element );
		}
	},

	widget: function() {
		return this.uiDialog;
	},

	disable: $.noop,
	enable: $.noop,

	close: function( event ) {
		var that = this;

		if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
			return;
		}

		this._isOpen = false;
		this._focusedElement = null;
		this._destroyOverlay();
		this._untrackInstance();

		if ( !this.opener.filter( ":focusable" ).trigger( "focus" ).length ) {

			// Hiding a focused element doesn't trigger blur in WebKit
			// so in case we have nothing to focus on, explicitly blur the active element
			// https://bugs.webkit.org/show_bug.cgi?id=47182
			$.ui.safeBlur( $.ui.safeActiveElement( this.document[ 0 ] ) );
		}

		this._hide( this.uiDialog, this.options.hide, function() {
			that._trigger( "close", event );
		} );
	},

	isOpen: function() {
		return this._isOpen;
	},

	moveToTop: function() {
		this._moveToTop();
	},

	_moveToTop: function( event, silent ) {
		var moved = false,
			zIndices = this.uiDialog.siblings( ".ui-front:visible" ).map( function() {
				return +$( this ).css( "z-index" );
			} ).get(),
			zIndexMax = Math.max.apply( null, zIndices );

		if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) {
			this.uiDialog.css( "z-index", zIndexMax + 1 );
			moved = true;
		}

		if ( moved && !silent ) {
			this._trigger( "focus", event );
		}
		return moved;
	},

	open: function() {
		var that = this;
		if ( this._isOpen ) {
			if ( this._moveToTop() ) {
				this._focusTabbable();
			}
			return;
		}

		this._isOpen = true;
		this.opener = $( $.ui.safeActiveElement( this.document[ 0 ] ) );

		this._size();
		this._position();
		this._createOverlay();
		this._moveToTop( null, true );

		// Ensure the overlay is moved to the top with the dialog, but only when
		// opening. The overlay shouldn't move after the dialog is open so that
		// modeless dialogs opened after the modal dialog stack properly.
		if ( this.overlay ) {
			this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 );
		}

		this._show( this.uiDialog, this.options.show, function() {
			that._focusTabbable();
			that._trigger( "focus" );
		} );

		// Track the dialog immediately upon openening in case a focus event
		// somehow occurs outside of the dialog before an element inside the
		// dialog is focused (#10152)
		this._makeFocusTarget();

		this._trigger( "open" );
	},

	_focusTabbable: function() {

		// Set focus to the first match:
		// 1. An element that was focused previously
		// 2. First element inside the dialog matching [autofocus]
		// 3. Tabbable element inside the content element
		// 4. Tabbable element inside the buttonpane
		// 5. The close button
		// 6. The dialog itself
		var hasFocus = this._focusedElement;
		if ( !hasFocus ) {
			hasFocus = this.element.find( "[autofocus]" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.element.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialog;
		}
		hasFocus.eq( 0 ).trigger( "focus" );
	},

	_keepFocus: function( event ) {
		function checkFocus() {
			var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
				isActive = this.uiDialog[ 0 ] === activeElement ||
					$.contains( this.uiDialog[ 0 ], activeElement );
			if ( !isActive ) {
				this._focusTabbable();
			}
		}
		event.preventDefault();
		checkFocus.call( this );

		// support: IE
		// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
		// so we check again later
		this._delay( checkFocus );
	},

	_createWrapper: function() {
		this.uiDialog = $( "<div>" )
			.hide()
			.attr( {

				// Setting tabIndex makes the div focusable
				tabIndex: -1,
				role: "dialog"
			} )
			.appendTo( this._appendTo() );

		this._addClass( this.uiDialog, "ui-dialog", "ui-widget ui-widget-content ui-front" );
		this._on( this.uiDialog, {
			keydown: function( event ) {
				if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE ) {
					event.preventDefault();
					this.close( event );
					return;
				}

				// Prevent tabbing out of dialogs
				if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) {
					return;
				}
				var tabbables = this.uiDialog.find( ":tabbable" ),
					first = tabbables.filter( ":first" ),
					last = tabbables.filter( ":last" );

				if ( ( event.target === last[ 0 ] || event.target === this.uiDialog[ 0 ] ) &&
						!event.shiftKey ) {
					this._delay( function() {
						first.trigger( "focus" );
					} );
					event.preventDefault();
				} else if ( ( event.target === first[ 0 ] ||
						event.target === this.uiDialog[ 0 ] ) && event.shiftKey ) {
					this._delay( function() {
						last.trigger( "focus" );
					} );
					event.preventDefault();
				}
			},
			mousedown: function( event ) {
				if ( this._moveToTop( event ) ) {
					this._focusTabbable();
				}
			}
		} );

		// We assume that any existing aria-describedby attribute means
		// that the dialog content is marked up properly
		// otherwise we brute force the content as the description
		if ( !this.element.find( "[aria-describedby]" ).length ) {
			this.uiDialog.attr( {
				"aria-describedby": this.element.uniqueId().attr( "id" )
			} );
		}
	},

	_createTitlebar: function() {
		var uiDialogTitle;

		this.uiDialogTitlebar = $( "<div>" );
		this._addClass( this.uiDialogTitlebar,
			"ui-dialog-titlebar", "ui-widget-header ui-helper-clearfix" );
		this._on( this.uiDialogTitlebar, {
			mousedown: function( event ) {

				// Don't prevent click on close button (#8838)
				// Focusing a dialog that is partially scrolled out of view
				// causes the browser to scroll it into view, preventing the click event
				if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) {

					// Dialog isn't getting focus when dragging (#8063)
					this.uiDialog.trigger( "focus" );
				}
			}
		} );

		// Support: IE
		// Use type="button" to prevent enter keypresses in textboxes from closing the
		// dialog in IE (#9312)
		this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
			.button( {
				label: $( "<a>" ).text( this.options.closeText ).html(),
				icon: "ui-icon-closethick",
				showLabel: false
			} )
			.appendTo( this.uiDialogTitlebar );

		this._addClass( this.uiDialogTitlebarClose, "ui-dialog-titlebar-close" );
		this._on( this.uiDialogTitlebarClose, {
			click: function( event ) {
				event.preventDefault();
				this.close( event );
			}
		} );

		uiDialogTitle = $( "<span>" ).uniqueId().prependTo( this.uiDialogTitlebar );
		this._addClass( uiDialogTitle, "ui-dialog-title" );
		this._title( uiDialogTitle );

		this.uiDialogTitlebar.prependTo( this.uiDialog );

		this.uiDialog.attr( {
			"aria-labelledby": uiDialogTitle.attr( "id" )
		} );
	},

	_title: function( title ) {
		if ( this.options.title ) {
			title.text( this.options.title );
		} else {
			title.html( "&#160;" );
		}
	},

	_createButtonPane: function() {
		this.uiDialogButtonPane = $( "<div>" );
		this._addClass( this.uiDialogButtonPane, "ui-dialog-buttonpane",
			"ui-widget-content ui-helper-clearfix" );

		this.uiButtonSet = $( "<div>" )
			.appendTo( this.uiDialogButtonPane );
		this._addClass( this.uiButtonSet, "ui-dialog-buttonset" );

		this._createButtons();
	},

	_createButtons: function() {
		var that = this,
			buttons = this.options.buttons;

		// If we already have a button pane, remove it
		this.uiDialogButtonPane.remove();
		this.uiButtonSet.empty();

		if ( $.isEmptyObject( buttons ) || ( $.isArray( buttons ) && !buttons.length ) ) {
			this._removeClass( this.uiDialog, "ui-dialog-buttons" );
			return;
		}

		$.each( buttons, function( name, props ) {
			var click, buttonOptions;
			props = $.isFunction( props ) ?
				{ click: props, text: name } :
				props;

			// Default to a non-submitting button
			props = $.extend( { type: "button" }, props );

			// Change the context for the click callback to be the main element
			click = props.click;
			buttonOptions = {
				icon: props.icon,
				iconPosition: props.iconPosition,
				showLabel: props.showLabel,

				// Deprecated options
				icons: props.icons,
				text: props.text
			};

			delete props.click;
			delete props.icon;
			delete props.iconPosition;
			delete props.showLabel;

			// Deprecated options
			delete props.icons;
			if ( typeof props.text === "boolean" ) {
				delete props.text;
			}

			$( "<button></button>", props )
				.button( buttonOptions )
				.appendTo( that.uiButtonSet )
				.on( "click", function() {
					click.apply( that.element[ 0 ], arguments );
				} );
		} );
		this._addClass( this.uiDialog, "ui-dialog-buttons" );
		this.uiDialogButtonPane.appendTo( this.uiDialog );
	},

	_makeDraggable: function() {
		var that = this,
			options = this.options;

		function filteredUi( ui ) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		this.uiDialog.draggable( {
			cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
			handle: ".ui-dialog-titlebar",
			containment: "document",
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-dragging" );
				that._blockFrames();
				that._trigger( "dragStart", event, filteredUi( ui ) );
			},
			drag: function( event, ui ) {
				that._trigger( "drag", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var left = ui.offset.left - that.document.scrollLeft(),
					top = ui.offset.top - that.document.scrollTop();

				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-dragging" );
				that._unblockFrames();
				that._trigger( "dragStop", event, filteredUi( ui ) );
			}
		} );
	},

	_makeResizable: function() {
		var that = this,
			options = this.options,
			handles = options.resizable,

			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = this.uiDialog.css( "position" ),
			resizeHandles = typeof handles === "string" ?
				handles :
				"n,e,s,w,se,sw,ne,nw";

		function filteredUi( ui ) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		this.uiDialog.resizable( {
			cancel: ".ui-dialog-content",
			containment: "document",
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: this._minHeight(),
			handles: resizeHandles,
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-resizing" );
				that._blockFrames();
				that._trigger( "resizeStart", event, filteredUi( ui ) );
			},
			resize: function( event, ui ) {
				that._trigger( "resize", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var offset = that.uiDialog.offset(),
					left = offset.left - that.document.scrollLeft(),
					top = offset.top - that.document.scrollTop();

				options.height = that.uiDialog.height();
				options.width = that.uiDialog.width();
				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-resizing" );
				that._unblockFrames();
				that._trigger( "resizeStop", event, filteredUi( ui ) );
			}
		} )
			.css( "position", position );
	},

	_trackFocus: function() {
		this._on( this.widget(), {
			focusin: function( event ) {
				this._makeFocusTarget();
				this._focusedElement = $( event.target );
			}
		} );
	},

	_makeFocusTarget: function() {
		this._untrackInstance();
		this._trackingInstances().unshift( this );
	},

	_untrackInstance: function() {
		var instances = this._trackingInstances(),
			exists = $.inArray( this, instances );
		if ( exists !== -1 ) {
			instances.splice( exists, 1 );
		}
	},

	_trackingInstances: function() {
		var instances = this.document.data( "ui-dialog-instances" );
		if ( !instances ) {
			instances = [];
			this.document.data( "ui-dialog-instances", instances );
		}
		return instances;
	},

	_minHeight: function() {
		var options = this.options;

		return options.height === "auto" ?
			options.minHeight :
			Math.min( options.minHeight, options.height );
	},

	_position: function() {

		// Need to show the dialog to get the actual offset in the position plugin
		var isVisible = this.uiDialog.is( ":visible" );
		if ( !isVisible ) {
			this.uiDialog.show();
		}
		this.uiDialog.position( this.options.position );
		if ( !isVisible ) {
			this.uiDialog.hide();
		}
	},

	_setOptions: function( options ) {
		var that = this,
			resize = false,
			resizableOptions = {};

		$.each( options, function( key, value ) {
			that._setOption( key, value );

			if ( key in that.sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in that.resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		} );

		if ( resize ) {
			this._size();
			this._position();
		}
		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function( key, value ) {
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "disabled" ) {
			return;
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.uiDialog.appendTo( this._appendTo() );
		}

		if ( key === "buttons" ) {
			this._createButtons();
		}

		if ( key === "closeText" ) {
			this.uiDialogTitlebarClose.button( {

				// Ensure that we always pass a string
				label: $( "<a>" ).text( "" + this.options.closeText ).html()
			} );
		}

		if ( key === "draggable" ) {
			isDraggable = uiDialog.is( ":data(ui-draggable)" );
			if ( isDraggable && !value ) {
				uiDialog.draggable( "destroy" );
			}

			if ( !isDraggable && value ) {
				this._makeDraggable();
			}
		}

		if ( key === "position" ) {
			this._position();
		}

		if ( key === "resizable" ) {

			// currently resizable, becoming non-resizable
			isResizable = uiDialog.is( ":data(ui-resizable)" );
			if ( isResizable && !value ) {
				uiDialog.resizable( "destroy" );
			}

			// Currently resizable, changing handles
			if ( isResizable && typeof value === "string" ) {
				uiDialog.resizable( "option", "handles", value );
			}

			// Currently non-resizable, becoming resizable
			if ( !isResizable && value !== false ) {
				this._makeResizable();
			}
		}

		if ( key === "title" ) {
			this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
		}
	},

	_size: function() {

		// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		// divs will both have width and height set, so we need to reset them
		var nonContentHeight, minContentHeight, maxContentHeight,
			options = this.options;

		// Reset content sizing
		this.element.show().css( {
			width: "auto",
			minHeight: 0,
			maxHeight: "none",
			height: 0
		} );

		if ( options.minWidth > options.width ) {
			options.width = options.minWidth;
		}

		// Reset wrapper sizing
		// determine the height of all the non-content elements
		nonContentHeight = this.uiDialog.css( {
			height: "auto",
			width: options.width
		} )
			.outerHeight();
		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
		maxContentHeight = typeof options.maxHeight === "number" ?
			Math.max( 0, options.maxHeight - nonContentHeight ) :
			"none";

		if ( options.height === "auto" ) {
			this.element.css( {
				minHeight: minContentHeight,
				maxHeight: maxContentHeight,
				height: "auto"
			} );
		} else {
			this.element.height( Math.max( 0, options.height - nonContentHeight ) );
		}

		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
		}
	},

	_blockFrames: function() {
		this.iframeBlocks = this.document.find( "iframe" ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( {
					position: "absolute",
					width: iframe.outerWidth(),
					height: iframe.outerHeight()
				} )
				.appendTo( iframe.parent() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_allowInteraction: function( event ) {
		if ( $( event.target ).closest( ".ui-dialog" ).length ) {
			return true;
		}

		// TODO: Remove hack when datepicker implements
		// the .ui-front logic (#8989)
		return !!$( event.target ).closest( ".ui-datepicker" ).length;
	},

	_createOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		// We use a delay in case the overlay is created from an
		// event that we're going to be cancelling (#2804)
		var isOpening = true;
		this._delay( function() {
			isOpening = false;
		} );

		if ( !this.document.data( "ui-dialog-overlays" ) ) {

			// Prevent use of anchors and inputs
			// Using _on() for an event handler shared across many instances is
			// safe because the dialogs stack and must be closed in reverse order
			this._on( this.document, {
				focusin: function( event ) {
					if ( isOpening ) {
						return;
					}

					if ( !this._allowInteraction( event ) ) {
						event.preventDefault();
						this._trackingInstances()[ 0 ]._focusTabbable();
					}
				}
			} );
		}

		this.overlay = $( "<div>" )
			.appendTo( this._appendTo() );

		this._addClass( this.overlay, null, "ui-widget-overlay ui-front" );
		this._on( this.overlay, {
			mousedown: "_keepFocus"
		} );
		this.document.data( "ui-dialog-overlays",
			( this.document.data( "ui-dialog-overlays" ) || 0 ) + 1 );
	},

	_destroyOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		if ( this.overlay ) {
			var overlays = this.document.data( "ui-dialog-overlays" ) - 1;

			if ( !overlays ) {
				this._off( this.document, "focusin" );
				this.document.removeData( "ui-dialog-overlays" );
			} else {
				this.document.data( "ui-dialog-overlays", overlays );
			}

			this.overlay.remove();
			this.overlay = null;
		}
	}
} );

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for dialogClass option
	$.widget( "ui.dialog", $.ui.dialog, {
		options: {
			dialogClass: ""
		},
		_createWrapper: function() {
			this._super();
			this.uiDialog.addClass( this.options.dialogClass );
		},
		_setOption: function( key, value ) {
			if ( key === "dialogClass" ) {
				this.uiDialog
					.removeClass( this.options.dialogClass )
					.addClass( value );
			}
			this._superApply( arguments );
		}
	} );
}

var widgetsDialog = $.ui.dialog;


/*!
 * jQuery UI Progressbar 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Progressbar
//>>group: Widgets
// jscs:disable maximumLineLength
//>>description: Displays a status indicator for loading state, standard percentage, and other progress indicators.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/progressbar/
//>>demos: http://jqueryui.com/progressbar/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/progressbar.css
//>>css.theme: ../../themes/base/theme.css



var widgetsProgressbar = $.widget( "ui.progressbar", {
	version: "1.12.1",
	options: {
		classes: {
			"ui-progressbar": "ui-corner-all",
			"ui-progressbar-value": "ui-corner-left",
			"ui-progressbar-complete": "ui-corner-right"
		},
		max: 100,
		value: 0,

		change: null,
		complete: null
	},

	min: 0,

	_create: function() {

		// Constrain initial value
		this.oldValue = this.options.value = this._constrainedValue();

		this.element.attr( {

			// Only set static values; aria-valuenow and aria-valuemax are
			// set inside _refreshValue()
			role: "progressbar",
			"aria-valuemin": this.min
		} );
		this._addClass( "ui-progressbar", "ui-widget ui-widget-content" );

		this.valueDiv = $( "<div>" ).appendTo( this.element );
		this._addClass( this.valueDiv, "ui-progressbar-value", "ui-widget-header" );
		this._refreshValue();
	},

	_destroy: function() {
		this.element.removeAttr( "role aria-valuemin aria-valuemax aria-valuenow" );

		this.valueDiv.remove();
	},

	value: function( newValue ) {
		if ( newValue === undefined ) {
			return this.options.value;
		}

		this.options.value = this._constrainedValue( newValue );
		this._refreshValue();
	},

	_constrainedValue: function( newValue ) {
		if ( newValue === undefined ) {
			newValue = this.options.value;
		}

		this.indeterminate = newValue === false;

		// Sanitize value
		if ( typeof newValue !== "number" ) {
			newValue = 0;
		}

		return this.indeterminate ? false :
			Math.min( this.options.max, Math.max( this.min, newValue ) );
	},

	_setOptions: function( options ) {

		// Ensure "value" option is set after other values (like max)
		var value = options.value;
		delete options.value;

		this._super( options );

		this.options.value = this._constrainedValue( value );
		this._refreshValue();
	},

	_setOption: function( key, value ) {
		if ( key === "max" ) {

			// Don't allow a max less than min
			value = Math.max( this.min, value );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", value );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	_percentage: function() {
		return this.indeterminate ?
			100 :
			100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
	},

	_refreshValue: function() {
		var value = this.options.value,
			percentage = this._percentage();

		this.valueDiv
			.toggle( this.indeterminate || value > this.min )
			.width( percentage.toFixed( 0 ) + "%" );

		this
			._toggleClass( this.valueDiv, "ui-progressbar-complete", null,
				value === this.options.max )
			._toggleClass( "ui-progressbar-indeterminate", null, this.indeterminate );

		if ( this.indeterminate ) {
			this.element.removeAttr( "aria-valuenow" );
			if ( !this.overlayDiv ) {
				this.overlayDiv = $( "<div>" ).appendTo( this.valueDiv );
				this._addClass( this.overlayDiv, "ui-progressbar-overlay" );
			}
		} else {
			this.element.attr( {
				"aria-valuemax": this.options.max,
				"aria-valuenow": value
			} );
			if ( this.overlayDiv ) {
				this.overlayDiv.remove();
				this.overlayDiv = null;
			}
		}

		if ( this.oldValue !== value ) {
			this.oldValue = value;
			this._trigger( "change" );
		}
		if ( value === this.options.max ) {
			this._trigger( "complete" );
		}
	}
} );


/*!
 * jQuery UI Slider 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slider
//>>group: Widgets
//>>description: Displays a flexible slider with ranges and accessibility via keyboard.
//>>docs: http://api.jqueryui.com/slider/
//>>demos: http://jqueryui.com/slider/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/slider.css
//>>css.theme: ../../themes/base/theme.css



var widgetsSlider = $.widget( "ui.slider", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		classes: {
			"ui-slider": "ui-corner-all",
			"ui-slider-handle": "ui-corner-all",

			// Note: ui-widget-header isn't the most fittingly semantic framework class for this
			// element, but worked best visually with a variety of themes
			"ui-slider-range": "ui-corner-all ui-widget-header"
		},
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// Callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// Number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this._addClass( "ui-slider ui-slider-" + this.orientation,
			"ui-widget ui-widget-content" );

		this._refresh();

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ),
			handle = "<span tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this._addClass( this.handles, "ui-slider-handle", "ui-state-default" );

		this.handle = this.handles.eq( 0 );

		this.handles.each( function( i ) {
			$( this )
				.data( "ui-slider-handle-index", i )
				.attr( "tabIndex", 0 );
		} );
	},

	_createRange: function() {
		var options = this.options;

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[ 0 ], options.values[ 0 ] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice( 0 );
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div>" )
					.appendTo( this.element );

				this._addClass( this.range, "ui-slider-range" );
			} else {
				this._removeClass( this.range, "ui-slider-range-min ui-slider-range-max" );

				// Handle range switching from true to min/max
				this.range.css( {
					"left": "",
					"bottom": ""
				} );
			}
			if ( options.range === "min" || options.range === "max" ) {
				this._addClass( this.range, "ui-slider-range-" + options.range );
			}
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each( function( i ) {
			var thisDistance = Math.abs( normValue - that.values( i ) );
			if ( ( distance > thisDistance ) ||
				( distance === thisDistance &&
					( i === that._lastChangedValue || that.values( i ) === o.min ) ) ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		} );

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		this._addClass( closestHandle, null, "ui-state-active" );
		closestHandle.trigger( "focus" );

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css( "borderTopWidth" ), 10 ) || 0 ) -
				( parseInt( closestHandle.css( "borderBottomWidth" ), 10 ) || 0 ) +
				( parseInt( closestHandle.css( "marginTop" ), 10 ) || 0 )
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this._removeClass( this.handles, null, "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left -
				( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top -
				( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_uiHash: function( index, value, values ) {
		var uiHash = {
			handle: this.handles[ index ],
			handleIndex: index,
			value: value !== undefined ? value : this.value()
		};

		if ( this._hasMultipleValues() ) {
			uiHash.value = value !== undefined ? value : this.values( index );
			uiHash.values = values || this.values();
		}

		return uiHash;
	},

	_hasMultipleValues: function() {
		return this.options.values && this.options.values.length;
	},

	_start: function( event, index ) {
		return this._trigger( "start", event, this._uiHash( index ) );
	},

	_slide: function( event, index, newVal ) {
		var allowed, otherVal,
			currentValue = this.value(),
			newValues = this.values();

		if ( this._hasMultipleValues() ) {
			otherVal = this.values( index ? 0 : 1 );
			currentValue = this.values( index );

			if ( this.options.values.length === 2 && this.options.range === true ) {
				newVal =  index === 0 ? Math.min( otherVal, newVal ) : Math.max( otherVal, newVal );
			}

			newValues[ index ] = newVal;
		}

		if ( newVal === currentValue ) {
			return;
		}

		allowed = this._trigger( "slide", event, this._uiHash( index, newVal, newValues ) );

		// A slide can be canceled by returning false from the slide callback
		if ( allowed === false ) {
			return;
		}

		if ( this._hasMultipleValues() ) {
			this.values( index, newVal );
		} else {
			this.value( newVal );
		}
	},

	_stop: function( event, index ) {
		this._trigger( "stop", event, this._uiHash( index ) );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;
			this._trigger( "change", event, this._uiHash( index ) );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this._hasMultipleValues() ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this._removeClass( "ui-slider-horizontal ui-slider-vertical" )
					._addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				if ( this.options.range ) {
					this._refreshRange( value );
				}

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();

				// Start from the last handle to prevent unreachable handles (#9046)
				for ( i = valsLength - 1; i >= 0; i-- ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this._hasMultipleValues() ) {

			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1 ) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// Returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = ( val - this._valueMin() ) % step,
			alignValue = val - valModStep;

		if ( Math.abs( valModStep ) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed( 5 ) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.round( ( max - min ) / step ) * step;
		max = aboveMin + min;
		if ( max > this.options.max ) {

			//If max is not divisible by step, rounding off may increase its value
			max -= step;
		}
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshRange: function( orientation ) {
		if ( orientation === "vertical" ) {
			this.range.css( { "width": "", "left": "" } );
		}
		if ( orientation === "horizontal" ) {
			this.range.css( { "height": "", "bottom": "" } );
		}
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this._hasMultipleValues() ) {
			this.handles.each( function( i ) {
				valPercent = ( that.values( i ) - that._valueMin() ) / ( that._valueMax() -
					that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								left: valPercent + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								width: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								bottom: ( valPercent ) + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								height: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					}
				}
				lastValPercent = valPercent;
			} );
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						this._addClass( $( event.target ), null, "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this._hasMultipleValues() ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( ( this._valueMax() - this._valueMin() ) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				this._removeClass( $( event.target ), null, "ui-state-active" );
			}
		}
	}
} );


/*!
 * jQuery UI Tooltip 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Tooltip
//>>group: Widgets
//>>description: Shows additional information for any element on hover or focus.
//>>docs: http://api.jqueryui.com/tooltip/
//>>demos: http://jqueryui.com/tooltip/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/tooltip.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.tooltip", {
	version: "1.12.1",
	options: {
		classes: {
			"ui-tooltip": "ui-corner-all ui-widget-shadow"
		},
		content: function() {

			// support: IE<9, Opera in jQuery <1.7
			// .text() can't accept undefined, so coerce to a string
			var title = $( this ).attr( "title" ) || "";

			// Escape title, since we're going from an attribute to raw HTML
			return $( "<a>" ).text( title ).html();
		},
		hide: true,

		// Disabled elements have inconsistent behavior across browsers (#8661)
		items: "[title]:not([disabled])",
		position: {
			my: "left top+15",
			at: "left bottom",
			collision: "flipfit flip"
		},
		show: true,
		track: false,

		// Callbacks
		close: null,
		open: null
	},

	_addDescribedBy: function( elem, id ) {
		var describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ );
		describedby.push( id );
		elem
			.data( "ui-tooltip-id", id )
			.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
	},

	_removeDescribedBy: function( elem ) {
		var id = elem.data( "ui-tooltip-id" ),
			describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ ),
			index = $.inArray( id, describedby );

		if ( index !== -1 ) {
			describedby.splice( index, 1 );
		}

		elem.removeData( "ui-tooltip-id" );
		describedby = $.trim( describedby.join( " " ) );
		if ( describedby ) {
			elem.attr( "aria-describedby", describedby );
		} else {
			elem.removeAttr( "aria-describedby" );
		}
	},

	_create: function() {
		this._on( {
			mouseover: "open",
			focusin: "open"
		} );

		// IDs of generated tooltips, needed for destroy
		this.tooltips = {};

		// IDs of parent tooltips where we removed the title attribute
		this.parents = {};

		// Append the aria-live region so tooltips announce correctly
		this.liveRegion = $( "<div>" )
			.attr( {
				role: "log",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			} )
			.appendTo( this.document[ 0 ].body );
		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		this.disabledTitles = $( [] );
	},

	_setOption: function( key, value ) {
		var that = this;

		this._super( key, value );

		if ( key === "content" ) {
			$.each( this.tooltips, function( id, tooltipData ) {
				that._updateContent( tooltipData.element );
			} );
		}
	},

	_setOptionDisabled: function( value ) {
		this[ value ? "_disable" : "_enable" ]();
	},

	_disable: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			var event = $.Event( "blur" );
			event.target = event.currentTarget = tooltipData.element[ 0 ];
			that.close( event, true );
		} );

		// Remove title attributes to prevent native tooltips
		this.disabledTitles = this.disabledTitles.add(
			this.element.find( this.options.items ).addBack()
				.filter( function() {
					var element = $( this );
					if ( element.is( "[title]" ) ) {
						return element
							.data( "ui-tooltip-title", element.attr( "title" ) )
							.removeAttr( "title" );
					}
				} )
		);
	},

	_enable: function() {

		// restore title attributes
		this.disabledTitles.each( function() {
			var element = $( this );
			if ( element.data( "ui-tooltip-title" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
			}
		} );
		this.disabledTitles = $( [] );
	},

	open: function( event ) {
		var that = this,
			target = $( event ? event.target : this.element )

				// we need closest here due to mouseover bubbling,
				// but always pointing at the same event target
				.closest( this.options.items );

		// No element to show a tooltip for or the tooltip is already open
		if ( !target.length || target.data( "ui-tooltip-id" ) ) {
			return;
		}

		if ( target.attr( "title" ) ) {
			target.data( "ui-tooltip-title", target.attr( "title" ) );
		}

		target.data( "ui-tooltip-open", true );

		// Kill parent tooltips, custom or native, for hover
		if ( event && event.type === "mouseover" ) {
			target.parents().each( function() {
				var parent = $( this ),
					blurEvent;
				if ( parent.data( "ui-tooltip-open" ) ) {
					blurEvent = $.Event( "blur" );
					blurEvent.target = blurEvent.currentTarget = this;
					that.close( blurEvent, true );
				}
				if ( parent.attr( "title" ) ) {
					parent.uniqueId();
					that.parents[ this.id ] = {
						element: this,
						title: parent.attr( "title" )
					};
					parent.attr( "title", "" );
				}
			} );
		}

		this._registerCloseHandlers( event, target );
		this._updateContent( target, event );
	},

	_updateContent: function( target, event ) {
		var content,
			contentOption = this.options.content,
			that = this,
			eventType = event ? event.type : null;

		if ( typeof contentOption === "string" || contentOption.nodeType ||
				contentOption.jquery ) {
			return this._open( event, target, contentOption );
		}

		content = contentOption.call( target[ 0 ], function( response ) {

			// IE may instantly serve a cached response for ajax requests
			// delay this call to _open so the other call to _open runs first
			that._delay( function() {

				// Ignore async response if tooltip was closed already
				if ( !target.data( "ui-tooltip-open" ) ) {
					return;
				}

				// JQuery creates a special event for focusin when it doesn't
				// exist natively. To improve performance, the native event
				// object is reused and the type is changed. Therefore, we can't
				// rely on the type being correct after the event finished
				// bubbling, so we set it back to the previous value. (#8740)
				if ( event ) {
					event.type = eventType;
				}
				this._open( event, target, response );
			} );
		} );
		if ( content ) {
			this._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		var tooltipData, tooltip, delayedShow, a11yContent,
			positionOption = $.extend( {}, this.options.position );

		if ( !content ) {
			return;
		}

		// Content can be updated multiple times. If the tooltip already
		// exists, then just update the content and bail.
		tooltipData = this._find( target );
		if ( tooltipData ) {
			tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
			return;
		}

		// If we have a title, clear it to prevent the native tooltip
		// we have to check first to avoid defining a title if none exists
		// (we don't want to cause an element to start matching [title])
		//
		// We use removeAttr only for key events, to allow IE to export the correct
		// accessible attributes. For mouse events, set to empty string to avoid
		// native tooltip showing up (happens only when removing inside mouseover).
		if ( target.is( "[title]" ) ) {
			if ( event && event.type === "mouseover" ) {
				target.attr( "title", "" );
			} else {
				target.removeAttr( "title" );
			}
		}

		tooltipData = this._tooltip( target );
		tooltip = tooltipData.tooltip;
		this._addDescribedBy( target, tooltip.attr( "id" ) );
		tooltip.find( ".ui-tooltip-content" ).html( content );

		// Support: Voiceover on OS X, JAWS on IE <= 9
		// JAWS announces deletions even when aria-relevant="additions"
		// Voiceover will sometimes re-read the entire log region's contents from the beginning
		this.liveRegion.children().hide();
		a11yContent = $( "<div>" ).html( tooltip.find( ".ui-tooltip-content" ).html() );
		a11yContent.removeAttr( "name" ).find( "[name]" ).removeAttr( "name" );
		a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
		a11yContent.appendTo( this.liveRegion );

		function position( event ) {
			positionOption.of = event;
			if ( tooltip.is( ":hidden" ) ) {
				return;
			}
			tooltip.position( positionOption );
		}
		if ( this.options.track && event && /^mouse/.test( event.type ) ) {
			this._on( this.document, {
				mousemove: position
			} );

			// trigger once to override element-relative positioning
			position( event );
		} else {
			tooltip.position( $.extend( {
				of: target
			}, this.options.position ) );
		}

		tooltip.hide();

		this._show( tooltip, this.options.show );

		// Handle tracking tooltips that are shown with a delay (#8644). As soon
		// as the tooltip is visible, position the tooltip using the most recent
		// event.
		// Adds the check to add the timers only when both delay and track options are set (#14682)
		if ( this.options.track && this.options.show && this.options.show.delay ) {
			delayedShow = this.delayedShow = setInterval( function() {
				if ( tooltip.is( ":visible" ) ) {
					position( positionOption.of );
					clearInterval( delayedShow );
				}
			}, $.fx.interval );
		}

		this._trigger( "open", event, { tooltip: tooltip } );
	},

	_registerCloseHandlers: function( event, target ) {
		var events = {
			keyup: function( event ) {
				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
					var fakeEvent = $.Event( event );
					fakeEvent.currentTarget = target[ 0 ];
					this.close( fakeEvent, true );
				}
			}
		};

		// Only bind remove handler for delegated targets. Non-delegated
		// tooltips will handle this in destroy.
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			events.remove = function() {
				this._removeTooltip( this._find( target ).tooltip );
			};
		}

		if ( !event || event.type === "mouseover" ) {
			events.mouseleave = "close";
		}
		if ( !event || event.type === "focusin" ) {
			events.focusout = "close";
		}
		this._on( true, target, events );
	},

	close: function( event ) {
		var tooltip,
			that = this,
			target = $( event ? event.currentTarget : this.element ),
			tooltipData = this._find( target );

		// The tooltip may already be closed
		if ( !tooltipData ) {

			// We set ui-tooltip-open immediately upon open (in open()), but only set the
			// additional data once there's actually content to show (in _open()). So even if the
			// tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
			// the period between open() and _open().
			target.removeData( "ui-tooltip-open" );
			return;
		}

		tooltip = tooltipData.tooltip;

		// Disabling closes the tooltip, so we need to track when we're closing
		// to avoid an infinite loop in case the tooltip becomes disabled on close
		if ( tooltipData.closing ) {
			return;
		}

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		// Only set title if we had one before (see comment in _open())
		// If the title attribute has changed since open(), don't restore
		if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
			target.attr( "title", target.data( "ui-tooltip-title" ) );
		}

		this._removeDescribedBy( target );

		tooltipData.hiding = true;
		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			that._removeTooltip( $( this ) );
		} );

		target.removeData( "ui-tooltip-open" );
		this._off( target, "mouseleave focusout keyup" );

		// Remove 'remove' binding only on delegated targets
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			this._off( target, "remove" );
		}
		this._off( this.document, "mousemove" );

		if ( event && event.type === "mouseleave" ) {
			$.each( this.parents, function( id, parent ) {
				$( parent.element ).attr( "title", parent.title );
				delete that.parents[ id ];
			} );
		}

		tooltipData.closing = true;
		this._trigger( "close", event, { tooltip: tooltip } );
		if ( !tooltipData.hiding ) {
			tooltipData.closing = false;
		}
	},

	_tooltip: function( element ) {
		var tooltip = $( "<div>" ).attr( "role", "tooltip" ),
			content = $( "<div>" ).appendTo( tooltip ),
			id = tooltip.uniqueId().attr( "id" );

		this._addClass( content, "ui-tooltip-content" );
		this._addClass( tooltip, "ui-tooltip", "ui-widget ui-widget-content" );

		tooltip.appendTo( this._appendTo( element ) );

		return this.tooltips[ id ] = {
			element: element,
			tooltip: tooltip
		};
	},

	_find: function( target ) {
		var id = target.data( "ui-tooltip-id" );
		return id ? this.tooltips[ id ] : null;
	},

	_removeTooltip: function( tooltip ) {
		tooltip.remove();
		delete this.tooltips[ tooltip.attr( "id" ) ];
	},

	_appendTo: function( target ) {
		var element = target.closest( ".ui-front, dialog" );

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_destroy: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {

			// Delegate to close method to handle common cleanup
			var event = $.Event( "blur" ),
				element = tooltipData.element;
			event.target = event.currentTarget = element[ 0 ];
			that.close( event, true );

			// Remove immediately; destroying an open tooltip doesn't use the
			// hide animation
			$( "#" + id ).remove();

			// Restore the title
			if ( element.data( "ui-tooltip-title" ) ) {

				// If the title attribute has changed since open(), don't restore
				if ( !element.attr( "title" ) ) {
					element.attr( "title", element.data( "ui-tooltip-title" ) );
				}
				element.removeData( "ui-tooltip-title" );
			}
		} );
		this.liveRegion.remove();
	}
} );

// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for tooltipClass option
	$.widget( "ui.tooltip", $.ui.tooltip, {
		options: {
			tooltipClass: null
		},
		_tooltip: function() {
			var tooltipData = this._superApply( arguments );
			if ( this.options.tooltipClass ) {
				tooltipData.tooltip.addClass( this.options.tooltipClass );
			}
			return tooltipData;
		}
	} );
}

var widgetsTooltip = $.ui.tooltip;




}));;
/*!
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global window: false, jQuery: false */

(function ($) {
    var data_click = "unobtrusiveAjaxClick",
        data_validation = "unobtrusiveValidation";

    function getFunction(code, argNames) {
        var fn = window, parts = (code || "").split(".");
        while (fn && parts.length) {
            fn = fn[parts.shift()];
        }
        if (typeof (fn) === "function") {
            return fn;
        }
        argNames.push(code);
        return Function.constructor.apply(null, argNames);
    }

    function isMethodProxySafe(method) {
        return method === "GET" || method === "POST";
    }

    function asyncOnBeforeSend(xhr, method) {
        if (!isMethodProxySafe(method)) {
            xhr.setRequestHeader("X-HTTP-Method-Override", method);
        }
    }

    function asyncOnSuccess(element, data, contentType) {
        var mode;

        if (contentType.indexOf("application/x-javascript") !== -1) {  // jQuery already executes JavaScript for us
            return;
        }

        mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase();
        $(element.getAttribute("data-ajax-update")).each(function (i, update) {
            var top;

            switch (mode) {
            case "BEFORE":
                top = update.firstChild;
                $("<div />").html(data).contents().each(function () {
                    update.insertBefore(this, top);
                });
                break;
            case "AFTER":
                $("<div />").html(data).contents().each(function () {
                    update.appendChild(this);
                });
                break;
            default:
                $(update).html(data);
                break;
            }
        });
    }

    function asyncRequest(element, options) {
        var confirm, loading, method, duration;

        confirm = element.getAttribute("data-ajax-confirm");
        if (confirm && !window.confirm(confirm)) {
            return;
        }

        loading = $(element.getAttribute("data-ajax-loading"));
        duration = element.getAttribute("data-ajax-loading-duration") || 0;

        $.extend(options, {
            type: element.getAttribute("data-ajax-method") || undefined,
            url: element.getAttribute("data-ajax-url") || undefined,
            beforeSend: function (xhr) {
                var result;
                asyncOnBeforeSend(xhr, method);
                result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
                if (result !== false) {
                    loading.show(duration);
                }
                return result;
            },
            complete: function () {
                loading.hide(duration);
                getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(this, arguments);
            },
            success: function (data, status, xhr) {
                asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
                getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments);
            },
            error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
        });

        options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });

        method = options.type.toUpperCase();
        if (!isMethodProxySafe(method)) {
            options.type = "POST";
            options.data.push({ name: "X-HTTP-Method-Override", value: method });
        }

        $.ajax(options);
    }

    function validate(form) {
        var validationInfo = $(form).data(data_validation);
        return !validationInfo || !validationInfo.validate || validationInfo.validate();
    }

    $("a[data-ajax=true]").live("click", function (evt) {
        evt.preventDefault();
        asyncRequest(this, {
            url: this.href,
            type: "GET",
            data: []
        });
    });

    $("form[data-ajax=true] input[type=image]").live("click", function (evt) {
        var name = evt.target.name,
            $target = $(evt.target),
            form = $target.parents("form")[0],
            offset = $target.offset();

        $(form).data(data_click, [
            { name: name + ".x", value: Math.round(evt.pageX - offset.left) },
            { name: name + ".y", value: Math.round(evt.pageY - offset.top) }
        ]);

        setTimeout(function () {
            $(form).removeData(data_click);
        }, 0);
    });

    $("form[data-ajax=true] :submit").live("click", function (evt) {
        var name = evt.target.name,
            form = $(evt.target).parents("form")[0];

        $(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

        setTimeout(function () {
            $(form).removeData(data_click);
        }, 0);
    });

    $("form[data-ajax=true]").live("submit", function (evt) {
        var clickInfo = $(this).data(data_click) || [];
        evt.preventDefault();
        if (!validate(this)) {
            return;
        }
        asyncRequest(this, {
            url: this.action,
            type: this.method || "GET",
            data: clickInfo.concat($(this).serializeArray())
        });
    });
}(jQuery));;
/**
 * jQuery Validation Plugin 1.9.0
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2011 Jörn Zaefferer
 *
 * Licensed under MIT: http://www.opensource.org/licenses/mit-license.php
 */

(function($) {

$.extend($.fn, {
	// http://docs.jquery.com/Plugins/Validation/validate
	validate: function( options ) {

		// if nothing is selected, return nothing; can't chain anyway
		if (!this.length) {
			options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
			return;
		}

		// check if a validator for this form was already created
		var validator = $.data(this[0], 'validator');
		if ( validator ) {
			return validator;
		}

		// Add novalidate tag if HTML5.
		this.attr('novalidate', 'novalidate');

		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator);

		if ( validator.settings.onsubmit ) {

			var inputsAndButtons = this.find("input, button");

			// allow suppresing validation by adding a cancel class to the submit button
			inputsAndButtons.filter(".cancel").click(function () {
				validator.cancelSubmit = true;
			});

			// when a submitHandler is used, capture the submitting button
			if (validator.settings.submitHandler) {
				inputsAndButtons.filter(":submit").click(function () {
					validator.submitButton = this;
				});
			}

			// validate the form on submit
			this.submit( function( event ) {
				if ( validator.settings.debug )
					// prevent form submit to be able to see console output
					event.preventDefault();

				function handle() {
					if ( validator.settings.submitHandler ) {
						if (validator.submitButton) {
							// insert a hidden input as a replacement for the missing submit button
							var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
						}
						validator.settings.submitHandler.call( validator, validator.currentForm );
						if (validator.submitButton) {
							// and clean up afterwards; thanks to no-block-scope, hidden can be referenced
							hidden.remove();
						}
						return false;
					}
					return true;
				}

				// prevent submit for invalid forms or custom submit handlers
				if ( validator.cancelSubmit ) {
					validator.cancelSubmit = false;
					return handle();
				}
				if ( validator.form() ) {
					if ( validator.pendingRequest ) {
						validator.formSubmitted = true;
						return false;
					}
					return handle();
				} else {
					validator.focusInvalid();
					return false;
				}
			});
		}

		return validator;
	},
	// http://docs.jquery.com/Plugins/Validation/valid
	valid: function() {
        if ( $(this[0]).is('form')) {
            return this.validate().form();
        } else {
            var valid = true;
            var validator = $(this[0].form).validate();
            this.each(function() {
				valid &= validator.element(this);
            });
            return valid;
        }
    },
	// attributes: space seperated list of attributes to retrieve and remove
	removeAttrs: function(attributes) {
		var result = {},
			$element = this;
		$.each(attributes.split(/\s/), function(index, value) {
			result[value] = $element.attr(value);
			$element.removeAttr(value);
		});
		return result;
	},
	// http://docs.jquery.com/Plugins/Validation/rules
	rules: function(command, argument) {
		var element = this[0];

		if (command) {
			var settings = $.data(element.form, 'validator').settings;
			var staticRules = settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
				if (argument.messages)
					settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
				break;
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
					return existingRules;
				}
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
				});
				return filtered;
			}
		}

		var data = $.validator.normalizeRules(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), element);

		// make sure required is at front
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		}

		return data;
	}
});

// Custom selectors
$.extend($.expr[":"], {
	// http://docs.jquery.com/Plugins/Validation/blank
	blank: function(a) {return !$.trim("" + a.value);},
	// http://docs.jquery.com/Plugins/Validation/filled
	filled: function(a) {return !!$.trim("" + a.value);},
	// http://docs.jquery.com/Plugins/Validation/unchecked
	unchecked: function(a) {return !a.checked;}
});

// constructor for validator
$.validator = function( options, form ) {
	this.settings = $.extend( true, {}, $.validator.defaults, options );
	this.currentForm = form;
	this.init();
};

$.validator.format = function(source, params) {
	if ( arguments.length == 1 )
		return function() {
			var args = $.makeArray(arguments);
			args.unshift(source);
			return $.validator.format.apply( this, args );
		};
	if ( arguments.length > 2 && params.constructor != Array  ) {
		params = $.makeArray(arguments).slice(1);
	}
	if ( params.constructor != Array ) {
		params = [ params ];
	}
	$.each(params, function(i, n) {
		source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
	});
	return source;
};

$.extend($.validator, {

	defaults: {
		messages: {},
		groups: {},
		rules: {},
		errorClass: "error",
		validClass: "valid",
		errorElement: "label",
		focusInvalid: true,
		errorContainer: $( [] ),
		errorLabelContainer: $( [] ),
		onsubmit: true,
		ignore: ":hidden",
		ignoreTitle: false,
		onfocusin: function(element, event) {
			this.lastActive = element;

			// hide error label and remove error class on focus if enabled
			if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
				this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
				this.addWrapper(this.errorsFor(element)).hide();
			}
		},
		onfocusout: function(element, event) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element, event) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element, event) {
			// click on selects, radiobuttons and checkboxes
			if ( element.name in this.submitted )
				this.element(element);
			// or option elements, check parent select in that case
			else if (element.parentNode.name in this.submitted)
				this.element(element.parentNode);
		},
		highlight: function(element, errorClass, validClass) {
			if (element.type === 'radio') {
				this.findByName(element.name).addClass(errorClass).removeClass(validClass);
			} else {
				$(element).addClass(errorClass).removeClass(validClass);
			}
		},
		unhighlight: function(element, errorClass, validClass) {
			if (element.type === 'radio') {
				this.findByName(element.name).removeClass(errorClass).addClass(validClass);
			} else {
				$(element).removeClass(errorClass).addClass(validClass);
			}
		}
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
	setDefaults: function(settings) {
		$.extend( $.validator.defaults, settings );
	},

	messages: {
		required: "This field is required.",
		remote: "Please fix this field.",
		email: "Please enter a valid email address.",
		url: "Please enter a valid URL.",
		date: "Please enter a valid date.",
		dateISO: "Please enter a valid date (ISO).",
		number: "Please enter a valid number.",
		digits: "Please enter only digits.",
		creditcard: "Please enter a valid credit card number.",
		equalTo: "Please enter the same value again.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.validator.format("Please enter no more than {0} characters."),
		minlength: $.validator.format("Please enter at least {0} characters."),
		rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
		range: $.validator.format("Please enter a value between {0} and {1}."),
		max: $.validator.format("Please enter a value less than or equal to {0}."),
		min: $.validator.format("Please enter a value greater than or equal to {0}.")
	},

	autoCreateRanges: false,

	prototype: {

		init: function() {
			this.labelContainer = $(this.settings.errorLabelContainer);
			this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
			this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
			this.submitted = {};
			this.valueCache = {};
			this.pendingRequest = 0;
			this.pending = {};
			this.invalid = {};
			this.reset();

			var groups = (this.groups = {});
			$.each(this.settings.groups, function(key, value) {
				$.each(value.split(/\s/), function(index, name) {
					groups[name] = key;
				});
			});
			var rules = this.settings.rules;
			$.each(rules, function(key, value) {
				rules[key] = $.validator.normalizeRule(value);
			});

			function delegate(event) {
				var validator = $.data(this[0].form, "validator"),
					eventType = "on" + event.type.replace(/^validate/, "");
				validator.settings[eventType] && validator.settings[eventType].call(validator, this[0], event);
			}
			$(this.currentForm)
			       .validateDelegate("[type='text'], [type='password'], [type='file'], select, textarea, " +
						"[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
						"[type='email'], [type='datetime'], [type='date'], [type='month'], " +
						"[type='week'], [type='time'], [type='datetime-local'], " +
						"[type='range'], [type='color'] ",
						"focusin focusout keyup", delegate)
				.validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate);

			if (this.settings.invalidHandler)
				$(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/form
		form: function() {
			this.checkForm();
			$.extend(this.submitted, this.errorMap);
			this.invalid = $.extend({}, this.errorMap);
			if (!this.valid())
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			this.showErrors();
			return this.valid();
		},

		checkForm: function() {
			this.prepareForm();
			for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
				this.check( elements[i] );
			}
			return this.valid();
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/element
		element: function( element ) {
			element = this.validationTargetFor( this.clean( element ) );
			this.lastElement = element;
			this.prepareElement( element );
			this.currentElements = $(element);
			var result = this.check( element );
			if ( result ) {
				delete this.invalid[element.name];
			} else {
				this.invalid[element.name] = true;
			}
			if ( !this.numberOfInvalids() ) {
				// Hide error containers on last error
				this.toHide = this.toHide.add( this.containers );
			}
			this.showErrors();
			return result;
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/showErrors
		showErrors: function(errors) {
			if(errors) {
				// add items to error list and map
				$.extend( this.errorMap, errors );
				this.errorList = [];
				for ( var name in errors ) {
					this.errorList.push({
						message: errors[name],
						element: this.findByName(name)[0]
					});
				}
				// remove items from success list
				this.successList = $.grep( this.successList, function(element) {
					return !(element.name in errors);
				});
			}
			this.settings.showErrors
				? this.settings.showErrors.call( this, this.errorMap, this.errorList )
				: this.defaultShowErrors();
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/resetForm
		resetForm: function() {
			if ( $.fn.resetForm )
				$( this.currentForm ).resetForm();
			this.submitted = {};
			this.lastElement = null;
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass );
		},

		numberOfInvalids: function() {
			return this.objectLength(this.invalid);
		},

		objectLength: function( obj ) {
			var count = 0;
			for ( var i in obj )
				count++;
			return count;
		},

		hideErrors: function() {
			this.addWrapper( this.toHide ).hide();
		},

		valid: function() {
			return this.size() == 0;
		},

		size: function() {
			return this.errorList.length;
		},

		focusInvalid: function() {
			if( this.settings.focusInvalid ) {
				try {
					$(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
					.filter(":visible")
					.focus()
					// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
					.trigger("focusin");
				} catch(e) {
					// ignore IE throwing errors when focusing hidden elements
				}
			}
		},

		findLastActive: function() {
			var lastActive = this.lastActive;
			return lastActive && $.grep(this.errorList, function(n) {
				return n.element.name == lastActive.name;
			}).length == 1 && lastActive;
		},

		elements: function() {
			var validator = this,
				rulesCache = {};

			// select all valid inputs inside the form (no submit or reset buttons)
			return $(this.currentForm)
			.find("input, select, textarea")
			.not(":submit, :reset, :image, [disabled]")
			.not( this.settings.ignore )
			.filter(function() {
				!this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);

				// select only the first element for each name, and only those with rules specified
				if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
					return false;

				rulesCache[this.name] = true;
				return true;
			});
		},

		clean: function( selector ) {
			return $( selector )[0];
		},

		errors: function() {
			return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
		},

		reset: function() {
			this.successList = [];
			this.errorList = [];
			this.errorMap = {};
			this.toShow = $([]);
			this.toHide = $([]);
			this.currentElements = $([]);
		},

		prepareForm: function() {
			this.reset();
			this.toHide = this.errors().add( this.containers );
		},

		prepareElement: function( element ) {
			this.reset();
			this.toHide = this.errorsFor(element);
		},

		check: function( element ) {
			element = this.validationTargetFor( this.clean( element ) );

			var rules = $(element).rules();
			var dependencyMismatch = false;
			for (var method in rules ) {
				var rule = { method: method, parameters: rules[method] };
				try {
					var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );

					// if a method indicates that the field is optional and therefore valid,
					// don't mark it as valid when there are no other rules
					if ( result == "dependency-mismatch" ) {
						dependencyMismatch = true;
						continue;
					}
					dependencyMismatch = false;

					if ( result == "pending" ) {
						this.toHide = this.toHide.not( this.errorsFor(element) );
						return;
					}

					if( !result ) {
						this.formatAndAdd( element, rule );
						return false;
					}
				} catch(e) {
					this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
						 + ", check the '" + rule.method + "' method", e);
					throw e;
				}
			}
			if (dependencyMismatch)
				return;
			if ( this.objectLength(rules) )
				this.successList.push(element);
			return true;
		},

		// return the custom message for the given element and validation method
		// specified in the element's "messages" metadata
		customMetaMessage: function(element, method) {
			if (!$.metadata)
				return;

			var meta = this.settings.meta
				? $(element).metadata()[this.settings.meta]
				: $(element).metadata();

			return meta && meta.messages && meta.messages[method];
		},

		// return the custom message for the given element name and validation method
		customMessage: function( name, method ) {
			var m = this.settings.messages[name];
			return m && (m.constructor == String
				? m
				: m[method]);
		},

		// return the first defined argument, allowing empty strings
		findDefined: function() {
			for(var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined)
					return arguments[i];
			}
			return undefined;
		},

		defaultMessage: function( element, method) {
			return this.findDefined(
				this.customMessage( element.name, method ),
				this.customMetaMessage( element, method ),
				// title is never undefined, so handle empty string as undefined
				!this.settings.ignoreTitle && element.title || undefined,
				$.validator.messages[method],
				"<strong>Warning: No message defined for " + element.name + "</strong>"
			);
		},

		formatAndAdd: function( element, rule ) {
			var message = this.defaultMessage( element, rule.method ),
				theregex = /\$?\{(\d+)\}/g;
			if ( typeof message == "function" ) {
				message = message.call(this, rule.parameters, element);
			} else if (theregex.test(message)) {
				message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters);
			}
			this.errorList.push({
				message: message,
				element: element
			});

			this.errorMap[element.name] = message;
			this.submitted[element.name] = message;
		},

		addWrapper: function(toToggle) {
			if ( this.settings.wrapper )
				toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
			return toToggle;
		},

		defaultShowErrors: function() {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
		},

		validElements: function() {
			return this.currentElements.not(this.invalidElements());
		},

		invalidElements: function() {
			return $(this.errorList).map(function() {
				return this.element;
			});
		},

		showLabel: function(element, message) {
			var label = this.errorsFor( element );
			if ( label.length ) {
				// refresh error/success class
				label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );

				// check if we have a generated label, replace the message then
				label.attr("generated") && label.html(message);
			} else {
				// create label
				label = $("<" + this.settings.errorElement + "/>")
					.attr({"for":  this.idOrName(element), generated: true})
					.addClass(this.settings.errorClass)
					.html(message || "");
				if ( this.settings.wrapper ) {
					// make sure the element is visible, even in IE
					// actually showing the wrapped element is handled elsewhere
					label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
				}
				if ( !this.labelContainer.append(label).length )
					this.settings.errorPlacement
						? this.settings.errorPlacement(label, $(element) )
						: label.insertAfter(element);
			}
			if ( !message && this.settings.success ) {
				label.text("");
				typeof this.settings.success == "string"
					? label.addClass( this.settings.success )
					: this.settings.success( label );
			}
			this.toShow = this.toShow.add(label);
		},

		errorsFor: function(element) {
			var name = this.idOrName(element);
    		return this.errors().filter(function() {
				return $(this).attr('for') == name;
			});
		},

		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},

		validationTargetFor: function(element) {
			// if radio/checkbox, validate first element in group instead
			if (this.checkable(element)) {
				element = this.findByName( element.name ).not(this.settings.ignore)[0];
			}
			return element;
		},

		checkable: function( element ) {
			return /radio|checkbox/i.test(element.type);
		},

		findByName: function( name ) {
			// select by name and filter by form for performance over form.find("[name=...]")
			var form = this.currentForm;
			return $(document.getElementsByName(name)).map(function(index, element) {
				return element.form == form && element.name == name && element  || null;
			});
		},

		getLength: function(value, element) {
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				return $("option:selected", element).length;
			case 'input':
				if( this.checkable( element) )
					return this.findByName(element.name).filter(':checked').length;
			}
			return value.length;
		},

		depend: function(param, element) {
			return this.dependTypes[typeof param]
				? this.dependTypes[typeof param](param, element)
				: true;
		},

		dependTypes: {
			"boolean": function(param, element) {
				return param;
			},
			"string": function(param, element) {
				return !!$(param, element.form).length;
			},
			"function": function(param, element) {
				return param(element);
			}
		},

		optional: function(element) {
			return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
		},

		startRequest: function(element) {
			if (!this.pending[element.name]) {
				this.pendingRequest++;
				this.pending[element.name] = true;
			}
		},

		stopRequest: function(element, valid) {
			this.pendingRequest--;
			// sometimes synchronization fails, make sure pendingRequest is never < 0
			if (this.pendingRequest < 0)
				this.pendingRequest = 0;
			delete this.pending[element.name];
			if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
				$(this.currentForm).submit();
				this.formSubmitted = false;
			} else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
				$(this.currentForm).triggerHandler("invalid-form", [this]);
				this.formSubmitted = false;
			}
		},

		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", {
				old: null,
				valid: true,
				message: this.defaultMessage( element, "remote" )
			});
		}

	},

	classRuleSettings: {
		required: {required: true},
		email: {email: true},
		url: {url: true},
		date: {date: true},
		dateISO: {dateISO: true},
		dateDE: {dateDE: true},
		number: {number: true},
		numberDE: {numberDE: true},
		digits: {digits: true},
		creditcard: {creditcard: true}
	},

	addClassRules: function(className, rules) {
		className.constructor == String ?
			this.classRuleSettings[className] = rules :
			$.extend(this.classRuleSettings, className);
	},

	classRules: function(element) {
		var rules = {};
		var classes = $(element).attr('class');
		classes && $.each(classes.split(' '), function() {
			if (this in $.validator.classRuleSettings) {
				$.extend(rules, $.validator.classRuleSettings[this]);
			}
		});
		return rules;
	},

	attributeRules: function(element) {
		var rules = {};
		var $element = $(element);

		for (var method in $.validator.methods) {
			var value;
			// If .prop exists (jQuery >= 1.6), use it to get true/false for required
			if (method === 'required' && typeof $.fn.prop === 'function') {
				value = $element.prop(method);
			} else {
				value = $element.attr(method);
			}
			if (value) {
				rules[method] = value;
			} else if ($element[0].getAttribute("type") === method) {
				rules[method] = true;
			}
		}

		// maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
		if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
			delete rules.maxlength;
		}

		return rules;
	},

	metadataRules: function(element) {
		if (!$.metadata) return {};

		var meta = $.data(element.form, 'validator').settings.meta;
		return meta ?
			$(element).metadata()[meta] :
			$(element).metadata();
	},

	staticRules: function(element) {
		var rules = {};
		var validator = $.data(element.form, 'validator');
		if (validator.settings.rules) {
			rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
		}
		return rules;
	},

	normalizeRules: function(rules, element) {
		// handle dependency check
		$.each(rules, function(prop, val) {
			// ignore rule when param is explicitly false, eg. required:false
			if (val === false) {
				delete rules[prop];
				return;
			}
			if (val.param || val.depends) {
				var keepRule = true;
				switch (typeof val.depends) {
					case "string":
						keepRule = !!$(val.depends, element.form).length;
						break;
					case "function":
						keepRule = val.depends.call(element, element);
						break;
				}
				if (keepRule) {
					rules[prop] = val.param !== undefined ? val.param : true;
				} else {
					delete rules[prop];
				}
			}
		});

		// evaluate parameters
		$.each(rules, function(rule, parameter) {
			rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
		});

		// clean number parameters
		$.each(['minlength', 'maxlength', 'min', 'max'], function() {
			if (rules[this]) {
				rules[this] = Number(rules[this]);
			}
		});
		$.each(['rangelength', 'range'], function() {
			if (rules[this]) {
				rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
			}
		});

		if ($.validator.autoCreateRanges) {
			// auto-create ranges
			if (rules.min && rules.max) {
				rules.range = [rules.min, rules.max];
				delete rules.min;
				delete rules.max;
			}
			if (rules.minlength && rules.maxlength) {
				rules.rangelength = [rules.minlength, rules.maxlength];
				delete rules.minlength;
				delete rules.maxlength;
			}
		}

		// To support custom messages in metadata ignore rule methods titled "messages"
		if (rules.messages) {
			delete rules.messages;
		}

		return rules;
	},

	// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
	normalizeRule: function(data) {
		if( typeof data == "string" ) {
			var transformed = {};
			$.each(data.split(/\s/), function() {
				transformed[this] = true;
			});
			data = transformed;
		}
		return data;
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/addMethod
	addMethod: function(name, method, message) {
		$.validator.methods[name] = method;
		$.validator.messages[name] = message != undefined ? message : $.validator.messages[name];
		if (method.length < 3) {
			$.validator.addClassRules(name, $.validator.normalizeRule(name));
		}
	},

	methods: {

		// http://docs.jquery.com/Plugins/Validation/Methods/required
		required: function(value, element, param) {
			// check if dependency is met
			if ( !this.depend(param, element) )
				return "dependency-mismatch";
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				// could be an array for select-multiple or a string, both are fine this way
				var val = $(element).val();
				return val && val.length > 0;
			case 'input':
				if ( this.checkable(element) )
					return this.getLength(value, element) > 0;
			default:
				return $.trim(value).length > 0;
			}
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/remote
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";

			var previous = this.previousValue(element);
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			previous.originalMessage = this.settings.messages[element.name].remote;
			this.settings.messages[element.name].remote = previous.message;

			param = typeof param == "string" && {url:param} || param;

			if ( this.pending[element.name] ) {
				return "pending";
			}
			if ( previous.old === value ) {
				return previous.valid;
			}

			previous.old = value;
			var validator = this;
			this.startRequest(element);
			var data = {};
			data[element.name] = value;
			$.ajax($.extend(true, {
				url: param,
				mode: "abort",
				port: "validate" + element.name,
				dataType: "json",
				data: data,
				success: function(response) {
					validator.settings.messages[element.name].remote = previous.originalMessage;
					var valid = response === true;
					if ( valid ) {
						var submitted = validator.formSubmitted;
						validator.prepareElement(element);
						validator.formSubmitted = submitted;
						validator.successList.push(element);
						validator.showErrors();
					} else {
						var errors = {};
						var message = response || validator.defaultMessage( element, "remote" );
						errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
						validator.showErrors(errors);
					}
					previous.valid = valid;
					validator.stopRequest(element, valid);
				}
			}, param));
			return "pending";
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/minlength
		minlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) >= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/maxlength
		maxlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) <= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/rangelength
		rangelength: function(value, element, param) {
			var length = this.getLength($.trim(value), element);
			return this.optional(element) || ( length >= param[0] && length <= param[1] );
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/min
		min: function( value, element, param ) {
			return this.optional(element) || value >= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/max
		max: function( value, element, param ) {
			return this.optional(element) || value <= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/range
		range: function( value, element, param ) {
			return this.optional(element) || ( value >= param[0] && value <= param[1] );
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/email
		email: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/url
		url: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
			return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/date
		date: function(value, element) {
			return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/dateISO
		dateISO: function(value, element) {
			return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/number
		number: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/digits
		digits: function(value, element) {
			return this.optional(element) || /^\d+$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/creditcard
		// based on http://en.wikipedia.org/wiki/Luhn
		creditcard: function(value, element) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			// accept only spaces, digits and dashes
			if (/[^0-9 -]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

			value = value.replace(/\D/g, "");

			for (var n = value.length - 1; n >= 0; n--) {
				var cDigit = value.charAt(n);
				var nDigit = parseInt(cDigit, 10);
				if (bEven) {
					if ((nDigit *= 2) > 9)
						nDigit -= 9;
				}
				nCheck += nDigit;
				bEven = !bEven;
			}

			return (nCheck % 10) == 0;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/accept
		accept: function(value, element, param) {
			param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
			return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/equalTo
		equalTo: function(value, element, param) {
			// bind to the blur event of the target in order to revalidate whenever the target field is updated
			// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
			var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
				$(element).valid();
			});
			return value == target.val();
		}

	}

});

// deprecated, use $.validator.format instead
$.format = $.validator.format;

})(jQuery);

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
;(function($) {
	var pendingRequests = {};
	// Use a prefilter if available (1.5+)
	if ( $.ajaxPrefilter ) {
		$.ajaxPrefilter(function(settings, _, xhr) {
			var port = settings.port;
			if (settings.mode == "abort") {
				if ( pendingRequests[port] ) {
					pendingRequests[port].abort();
				}
				pendingRequests[port] = xhr;
			}
		});
	} else {
		// Proxy ajax
		var ajax = $.ajax;
		$.ajax = function(settings) {
			var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
				port = ( "port" in settings ? settings : $.ajaxSettings ).port;
			if (mode == "abort") {
				if ( pendingRequests[port] ) {
					pendingRequests[port].abort();
				}
				return (pendingRequests[port] = ajax.apply(this, arguments));
			}
			return ajax.apply(this, arguments);
		};
	}
})(jQuery);

// provides cross-browser focusin and focusout events
// IE has native support, in other browsers, use event caputuring (neither bubbles)

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
;(function($) {
	// only implement if not provided by jQuery core (since 1.4)
	// TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs
	if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) {
		$.each({
			focus: 'focusin',
			blur: 'focusout'
		}, function( original, fix ){
			$.event.special[fix] = {
				setup:function() {
					this.addEventListener( original, handler, true );
				},
				teardown:function() {
					this.removeEventListener( original, handler, true );
				},
				handler: function(e) {
					arguments[0] = $.event.fix(e);
					arguments[0].type = fix;
					return $.event.handle.apply(this, arguments);
				}
			};
			function handler(e) {
				e = $.event.fix(e);
				e.type = fix;
				return $.event.handle.call(this, e);
			}
		});
	};
	$.extend($.fn, {
		validateDelegate: function(delegate, type, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		}
	});
})(jQuery);
;
/*!
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */

(function ($) {
    var $jQval = $.validator,
        adapters,
        data_validation = "unobtrusiveValidation";

    function setValidationValues(options, ruleName, value) {
        options.rules[ruleName] = value;
        if (options.message) {
            options.messages[ruleName] = options.message;
        }
    }

    function splitAndTrim(value) {
        return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
    }

    function escapeAttributeValue(value) {
        // As mentioned on http://api.jquery.com/category/selectors/
        return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
    }

    function getModelPrefix(fieldName) {
        return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
    }

    function appendModelPrefix(value, prefix) {
        if (value.indexOf("*.") === 0) {
            value = value.replace("*.", prefix);
        }
        return value;
    }

    function onError(error, inputElement) {  // 'this' is the form element
        var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
            replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

        container.removeClass("field-validation-valid").addClass("field-validation-error");
        error.data("unobtrusiveContainer", container);

        if (replace) {
            container.empty();
            error.removeClass("input-validation-error").appendTo(container);
        }
        else {
            error.hide();
        }
    }

    function onErrors(event, validator) {  // 'this' is the form element
        var container = $(this).find("[data-valmsg-summary=true]"),
            list = container.find("ul");

        if (list && list.length && validator.errorList.length) {
            list.empty();
            container.addClass("validation-summary-errors").removeClass("validation-summary-valid");

            $.each(validator.errorList, function () {
                $("<li />").html(this.message).appendTo(list);
            });
        }
    }

    function onSuccess(error) {  // 'this' is the form element
        var container = error.data("unobtrusiveContainer"),
            replace = $.parseJSON(container.attr("data-valmsg-replace"));

        if (container) {
            container.addClass("field-validation-valid").removeClass("field-validation-error");
            error.removeData("unobtrusiveContainer");

            if (replace) {
                container.empty();
            }
        }
    }

    function onReset(event) {  // 'this' is the form element
        var $form = $(this);
        $form.data("validator").resetForm();
        $form.find(".validation-summary-errors")
            .addClass("validation-summary-valid")
            .removeClass("validation-summary-errors");
        $form.find(".field-validation-error")
            .addClass("field-validation-valid")
            .removeClass("field-validation-error")
            .removeData("unobtrusiveContainer")
            .find(">*")  // If we were using valmsg-replace, get the underlying error
                .removeData("unobtrusiveContainer");
    }

    function validationInfo(form) {
        var $form = $(form),
            result = $form.data(data_validation),
            onResetProxy = $.proxy(onReset, form);

        if (!result) {
            result = {
                options: {  // options structure passed to jQuery Validate's validate() method
                    errorClass: "input-validation-error",
                    errorElement: "span",
                    errorPlacement: $.proxy(onError, form),
                    invalidHandler: $.proxy(onErrors, form),
                    messages: {},
                    rules: {},
                    success: $.proxy(onSuccess, form)
                },
                attachValidation: function () {
                    $form
                        .unbind("reset." + data_validation, onResetProxy)
                        .bind("reset." + data_validation, onResetProxy)
                        .validate(this.options);
                },
                validate: function () {  // a validation function that is called by unobtrusive Ajax
                    $form.validate();
                    return $form.valid();
                }
            };
            $form.data(data_validation, result);
        }

        return result;
    }

    $jQval.unobtrusive = {
        adapters: [],

        parseElement: function (element, skipAttach) {
            /// <summary>
            /// Parses a single HTML element for unobtrusive validation attributes.
            /// </summary>
            /// <param name="element" domElement="true">The HTML element to be parsed.</param>
            /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
            /// validation to the form. If parsing just this single element, you should specify true.
            /// If parsing several elements, you should specify false, and manually attach the validation
            /// to the form when you are finished. The default is false.</param>
            var $element = $(element),
                form = $element.parents("form")[0],
                valInfo, rules, messages;

            if (!form) {  // Cannot do client-side validation without a form
                return;
            }

            valInfo = validationInfo(form);
            valInfo.options.rules[element.name] = rules = {};
            valInfo.options.messages[element.name] = messages = {};

            $.each(this.adapters, function () {
                var prefix = "data-val-" + this.name,
                    message = $element.attr(prefix),
                    paramValues = {};

                if (message !== undefined) {  // Compare against undefined, because an empty message is legal (and falsy)
                    prefix += "-";

                    $.each(this.params, function () {
                        paramValues[this] = $element.attr(prefix + this);
                    });

                    this.adapt({
                        element: element,
                        form: form,
                        message: message,
                        params: paramValues,
                        rules: rules,
                        messages: messages
                    });
                }
            });

            $.extend(rules, { "__dummy__": true });

            if (!skipAttach) {
                valInfo.attachValidation();
            }
        },

        parse: function (selector) {
            /// <summary>
            /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
            /// with the [data-val=true] attribute value and enables validation according to the data-val-*
            /// attribute values.
            /// </summary>
            /// <param name="selector" type="String">Any valid jQuery selector.</param>
            var $forms = $(selector)
                .parents("form")
                .andSelf()
                .add($(selector).find("form"))
                .filter("form");

            $(selector).find(":input[data-val=true]").each(function () {
                $jQval.unobtrusive.parseElement(this, true);
            });

            $forms.each(function () {
                var info = validationInfo(this);
                if (info) {
                    info.attachValidation();
                }
            });
        }
    };

    adapters = $jQval.unobtrusive.adapters;

    adapters.add = function (adapterName, params, fn) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
        /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
        /// mmmm is the parameter name).</param>
        /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
        /// attributes into jQuery Validate rules and/or messages.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        if (!fn) {  // Called with no params, just a function
            fn = params;
            params = [];
        }
        this.push({ name: adapterName, params: params, adapt: fn });
        return this;
    };

    adapters.addBool = function (adapterName, ruleName) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation rule has no parameter values.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
        /// of adapterName will be used instead.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, function (options) {
            setValidationValues(options, ruleName || adapterName, true);
        });
    };

    adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
        /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
        /// have a minimum value.</param>
        /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
        /// have a maximum value.</param>
        /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
        /// have both a minimum and maximum value.</param>
        /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
        /// contains the minimum value. The default is "min".</param>
        /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
        /// contains the maximum value. The default is "max".</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
            var min = options.params.min,
                max = options.params.max;

            if (min && max) {
                setValidationValues(options, minMaxRuleName, [min, max]);
            }
            else if (min) {
                setValidationValues(options, minRuleName, min);
            }
            else if (max) {
                setValidationValues(options, maxRuleName, max);
            }
        });
    };

    adapters.addSingleVal = function (adapterName, attribute, ruleName) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation rule has a single value.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
        /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
        /// The default is "val".</param>
        /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
        /// of adapterName will be used instead.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, [attribute || "val"], function (options) {
            setValidationValues(options, ruleName || adapterName, options.params[attribute]);
        });
    };

    $jQval.addMethod("__dummy__", function (value, element, params) {
        return true;
    });

    $jQval.addMethod("regex", function (value, element, params) {
        var match;
        if (this.optional(element)) {
            return true;
        }

        match = new RegExp(params).exec(value);
        return (match && (match.index === 0) && (match[0].length === value.length));
    });

    $jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
        var match;
        if (nonalphamin) {
            match = value.match(/\W/g);
            match = match && match.length >= nonalphamin;
        }
        return match;
    });

    adapters.addSingleVal("accept", "exts").addSingleVal("regex", "pattern");
    adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
    adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
    adapters.add("equalto", ["other"], function (options) {
        var prefix = getModelPrefix(options.element.name),
            other = options.params.other,
            fullOtherName = appendModelPrefix(other, prefix),
            element = $(options.form).find(":input[name='" + escapeAttributeValue(fullOtherName) + "']")[0];

        setValidationValues(options, "equalTo", element);
    });
    adapters.add("required", function (options) {
        // jQuery Validate equates "required" with "mandatory" for checkbox elements
        if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
            setValidationValues(options, "required", true);
        }
    });
    adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
        var value = {
            url: options.params.url,
            type: options.params.type || "GET",
            data: {}
        },
            prefix = getModelPrefix(options.element.name);

        $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
            var paramName = appendModelPrefix(fieldName, prefix);
            value.data[paramName] = function () {
                return $(options.form).find(":input[name='" + escapeAttributeValue(paramName) + "']").val();
            };
        });

        setValidationValues(options, "remote", value);
    });
    adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
        if (options.params.min) {
            setValidationValues(options, "minlength", options.params.min);
        }
        if (options.params.nonalphamin) {
            setValidationValues(options, "nonalphamin", options.params.nonalphamin);
        }
        if (options.params.regex) {
            setValidationValues(options, "regex", options.params.regex);
        }
    });

    $(function () {
        $jQval.unobtrusive.parse(document);
    });
} (jQuery));;
/*Bengin tooltip*/
$(document).ready(function () {
    $('a.menu').each(function () {
        $(this).qtip({
            content: $(this).next('.tooltiptext'),
            hide: {
                fixed: true,
                delay: 300
            }
        });
    });
    
});
/* Cache window, document, undefined */
(function( window, document, undefined ) {

// Uses AMD or browser globals to create a jQuery plugin.
(function( factory ) {
	"use strict";
	if(typeof define === 'function' && define.amd) {
		define(['jquery'], factory);
	}
	else if(jQuery && !jQuery.fn.qtip) {
		factory(jQuery);
	}
}
(function($) {
	"use strict"; // Enable ECMAScript "strict" operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
;// Munge the primitives - Paul Irish tip
var TRUE = true,
FALSE = false,
NULL = null,

// Common variables
X = 'x', Y = 'y',
WIDTH = 'width',
HEIGHT = 'height',

// Positioning sides
TOP = 'top',
LEFT = 'left',
BOTTOM = 'bottom',
RIGHT = 'right',
CENTER = 'center',

// Position adjustment types
FLIP = 'flip',
FLIPINVERT = 'flipinvert',
SHIFT = 'shift',

// Shortcut vars
QTIP, PROTOTYPE, CORNER, CHECKS,
PLUGINS = {},
NAMESPACE = 'qtip',
ATTR_HAS = 'data-hasqtip',
ATTR_ID = 'data-qtip-id',
WIDGET = ['ui-widget', 'ui-tooltip'],
SELECTOR = '.'+NAMESPACE,
INACTIVE_EVENTS = 'click dblclick mousedown mouseup mousemove mouseleave mouseenter'.split(' '),

CLASS_FIXED = NAMESPACE+'-fixed',
CLASS_DEFAULT = NAMESPACE + '-default',
CLASS_FOCUS = NAMESPACE + '-focus',
CLASS_HOVER = NAMESPACE + '-hover',
CLASS_DISABLED = NAMESPACE+'-disabled',

replaceSuffix = '_replacedByqTip',
oldtitle = 'oldtitle',
trackingBound,

// Browser detection
BROWSER = {
	/*
	 * IE version detection
	 *
	 * Adapted from: http://ajaxian.com/archives/attack-of-the-ie-conditional-comment
	 * Credit to James Padolsey for the original implemntation!
	 */
	ie: (function() {
		/* eslint-disable no-empty */
		var v, i;
		for (
			v = 4, i = document.createElement('div');
			(i.innerHTML = '<!--[if gt IE ' + v + ']><i></i><![endif]-->') && i.getElementsByTagName('i')[0];
			v+=1
		) {}
		return v > 4 ? v : NaN;
		/* eslint-enable no-empty */
	})(),

	/*
	 * iOS version detection
	 */
	iOS: parseFloat(
		('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0,''])[1])
		.replace('undefined', '3_2').replace('_', '.').replace('_', '')
	) || FALSE
};
;function QTip(target, options, id, attr) {
	// Elements and ID
	this.id = id;
	this.target = target;
	this.tooltip = NULL;
	this.elements = { target: target };

	// Internal constructs
	this._id = NAMESPACE + '-' + id;
	this.timers = { img: {} };
	this.options = options;
	this.plugins = {};

	// Cache object
	this.cache = {
		event: {},
		target: $(),
		disabled: FALSE,
		attr: attr,
		onTooltip: FALSE,
		lastClass: ''
	};

	// Set the initial flags
	this.rendered = this.destroyed = this.disabled = this.waiting =
		this.hiddenDuringWait = this.positioning = this.triggering = FALSE;
}
PROTOTYPE = QTip.prototype;

PROTOTYPE._when = function(deferreds) {
	return $.when.apply($, deferreds);
};

PROTOTYPE.render = function(show) {
	if(this.rendered || this.destroyed) { return this; } // If tooltip has already been rendered, exit

	var self = this,
		options = this.options,
		cache = this.cache,
		elements = this.elements,
		text = options.content.text,
		title = options.content.title,
		button = options.content.button,
		posOptions = options.position,
		deferreds = [];

	// Add ARIA attributes to target
	$.attr(this.target[0], 'aria-describedby', this._id);

	// Create public position object that tracks current position corners
	cache.posClass = this._createPosClass(
		(this.position = { my: posOptions.my, at: posOptions.at }).my
	);

	// Create tooltip element
	this.tooltip = elements.tooltip = $('<div/>', {
		'id': this._id,
		'class': [ NAMESPACE, CLASS_DEFAULT, options.style.classes, cache.posClass ].join(' '),
		'width': options.style.width || '',
		'height': options.style.height || '',
		'tracking': posOptions.target === 'mouse' && posOptions.adjust.mouse,

		/* ARIA specific attributes */
		'role': 'alert',
		'aria-live': 'polite',
		'aria-atomic': FALSE,
		'aria-describedby': this._id + '-content',
		'aria-hidden': TRUE
	})
	.toggleClass(CLASS_DISABLED, this.disabled)
	.attr(ATTR_ID, this.id)
	.data(NAMESPACE, this)
	.appendTo(posOptions.container)
	.append(
		// Create content element
		elements.content = $('<div />', {
			'class': NAMESPACE + '-content',
			'id': this._id + '-content',
			'aria-atomic': TRUE
		})
	);

	// Set rendered flag and prevent redundant reposition calls for now
	this.rendered = -1;
	this.positioning = TRUE;

	// Create title...
	if(title) {
		this._createTitle();

		// Update title only if its not a callback (called in toggle if so)
		if(!$.isFunction(title)) {
			deferreds.push( this._updateTitle(title, FALSE) );
		}
	}

	// Create button
	if(button) { this._createButton(); }

	// Set proper rendered flag and update content if not a callback function (called in toggle)
	if(!$.isFunction(text)) {
		deferreds.push( this._updateContent(text, FALSE) );
	}
	this.rendered = TRUE;

	// Setup widget classes
	this._setWidget();

	// Initialize 'render' plugins
	$.each(PLUGINS, function(name) {
		var instance;
		if(this.initialize === 'render' && (instance = this(self))) {
			self.plugins[name] = instance;
		}
	});

	// Unassign initial events and assign proper events
	this._unassignEvents();
	this._assignEvents();

	// When deferreds have completed
	this._when(deferreds).then(function() {
		// tooltiprender event
		self._trigger('render');

		// Reset flags
		self.positioning = FALSE;

		// Show tooltip if not hidden during wait period
		if(!self.hiddenDuringWait && (options.show.ready || show)) {
			self.toggle(TRUE, cache.event, FALSE);
		}
		self.hiddenDuringWait = FALSE;
	});

	// Expose API
	QTIP.api[this.id] = this;

	return this;
};

PROTOTYPE.destroy = function(immediate) {
	// Set flag the signify destroy is taking place to plugins
	// and ensure it only gets destroyed once!
	if(this.destroyed) { return this.target; }

	function process() {
		if(this.destroyed) { return; }
		this.destroyed = TRUE;

		var target = this.target,
			title = target.attr(oldtitle),
			timer;

		// Destroy tooltip if rendered
		if(this.rendered) {
			this.tooltip.stop(1,0).find('*').remove().end().remove();
		}

		// Destroy all plugins
		$.each(this.plugins, function() {
			this.destroy && this.destroy();
		});

		// Clear timers
		for (timer in this.timers) {
			if (this.timers.hasOwnProperty(timer)) {
				clearTimeout(this.timers[timer]);
			}
		}

		// Remove api object and ARIA attributes
		target.removeData(NAMESPACE)
			.removeAttr(ATTR_ID)
			.removeAttr(ATTR_HAS)
			.removeAttr('aria-describedby');

		// Reset old title attribute if removed
		if(this.options.suppress && title) {
			target.attr('title', title).removeAttr(oldtitle);
		}

		// Remove qTip events associated with this API
		this._unassignEvents();

		// Remove ID from used id objects, and delete object references
		// for better garbage collection and leak protection
		this.options = this.elements = this.cache = this.timers =
			this.plugins = this.mouse = NULL;

		// Delete epoxsed API object
		delete QTIP.api[this.id];
	}

	// If an immediate destroy is needed
	if((immediate !== TRUE || this.triggering === 'hide') && this.rendered) {
		this.tooltip.one('tooltiphidden', $.proxy(process, this));
		!this.triggering && this.hide();
	}

	// If we're not in the process of hiding... process
	else { process.call(this); }

	return this.target;
};
;function invalidOpt(a) {
	return a === NULL || $.type(a) !== 'object';
}

function invalidContent(c) {
	return !($.isFunction(c) || 
            c && c.attr || 
            c.length || 
            $.type(c) === 'object' && (c.jquery || c.then));
}

// Option object sanitizer
function sanitizeOptions(opts) {
	var content, text, ajax, once;

	if(invalidOpt(opts)) { return FALSE; }

	if(invalidOpt(opts.metadata)) {
		opts.metadata = { type: opts.metadata };
	}

	if('content' in opts) {
		content = opts.content;

		if(invalidOpt(content) || content.jquery || content.done) {
			text = invalidContent(content) ? FALSE : content;
			content = opts.content = {
				text: text
			};
		}
		else { text = content.text; }

		// DEPRECATED - Old content.ajax plugin functionality
		// Converts it into the proper Deferred syntax
		if('ajax' in content) {
			ajax = content.ajax;
			once = ajax && ajax.once !== FALSE;
			delete content.ajax;

			content.text = function(event, api) {
				var loading = text || $(this).attr(api.options.content.attr) || 'Loading...',

				deferred = $.ajax(
					$.extend({}, ajax, { context: api })
				)
				.then(ajax.success, NULL, ajax.error)
				.then(function(newContent) {
					if(newContent && once) { api.set('content.text', newContent); }
					return newContent;
				},
				function(xhr, status, error) {
					if(api.destroyed || xhr.status === 0) { return; }
					api.set('content.text', status + ': ' + error);
				});

				return !once ? (api.set('content.text', loading), deferred) : loading;
			};
		}

		if('title' in content) {
			if($.isPlainObject(content.title)) {
				content.button = content.title.button;
				content.title = content.title.text;
			}

			if(invalidContent(content.title || FALSE)) {
				content.title = FALSE;
			}
		}
	}

	if('position' in opts && invalidOpt(opts.position)) {
		opts.position = { my: opts.position, at: opts.position };
	}

	if('show' in opts && invalidOpt(opts.show)) {
		opts.show = opts.show.jquery ? { target: opts.show } :
			opts.show === TRUE ? { ready: TRUE } : { event: opts.show };
	}

	if('hide' in opts && invalidOpt(opts.hide)) {
		opts.hide = opts.hide.jquery ? { target: opts.hide } : { event: opts.hide };
	}

	if('style' in opts && invalidOpt(opts.style)) {
		opts.style = { classes: opts.style };
	}

	// Sanitize plugin options
	$.each(PLUGINS, function() {
		this.sanitize && this.sanitize(opts);
	});

	return opts;
}

// Setup builtin .set() option checks
CHECKS = PROTOTYPE.checks = {
	builtin: {
		// Core checks
		'^id$': function(obj, o, v, prev) {
			var id = v === TRUE ? QTIP.nextid : v,
				newId = NAMESPACE + '-' + id;

			if(id !== FALSE && id.length > 0 && !$('#'+newId).length) {
				this._id = newId;

				if(this.rendered) {
					this.tooltip[0].id = this._id;
					this.elements.content[0].id = this._id + '-content';
					this.elements.title[0].id = this._id + '-title';
				}
			}
			else { obj[o] = prev; }
		},
		'^prerender': function(obj, o, v) {
			v && !this.rendered && this.render(this.options.show.ready);
		},

		// Content checks
		'^content.text$': function(obj, o, v) {
			this._updateContent(v);
		},
		'^content.attr$': function(obj, o, v, prev) {
			if(this.options.content.text === this.target.attr(prev)) {
				this._updateContent( this.target.attr(v) );
			}
		},
		'^content.title$': function(obj, o, v) {
			// Remove title if content is null
			if(!v) { return this._removeTitle(); }

			// If title isn't already created, create it now and update
			v && !this.elements.title && this._createTitle();
			this._updateTitle(v);
		},
		'^content.button$': function(obj, o, v) {
			this._updateButton(v);
		},
		'^content.title.(text|button)$': function(obj, o, v) {
			this.set('content.'+o, v); // Backwards title.text/button compat
		},

		// Position checks
		'^position.(my|at)$': function(obj, o, v){
			if('string' === typeof v) {
				this.position[o] = obj[o] = new CORNER(v, o === 'at');
			}
		},
		'^position.container$': function(obj, o, v){
			this.rendered && this.tooltip.appendTo(v);
		},

		// Show checks
		'^show.ready$': function(obj, o, v) {
			v && (!this.rendered && this.render(TRUE) || this.toggle(TRUE));
		},

		// Style checks
		'^style.classes$': function(obj, o, v, p) {
			this.rendered && this.tooltip.removeClass(p).addClass(v);
		},
		'^style.(width|height)': function(obj, o, v) {
			this.rendered && this.tooltip.css(o, v);
		},
		'^style.widget|content.title': function() {
			this.rendered && this._setWidget();
		},
		'^style.def': function(obj, o, v) {
			this.rendered && this.tooltip.toggleClass(CLASS_DEFAULT, !!v);
		},

		// Events check
		'^events.(render|show|move|hide|focus|blur)$': function(obj, o, v) {
			this.rendered && this.tooltip[($.isFunction(v) ? '' : 'un') + 'bind']('tooltip'+o, v);
		},

		// Properties which require event reassignment
		'^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)': function() {
			if(!this.rendered) { return; }

			// Set tracking flag
			var posOptions = this.options.position;
			this.tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse);

			// Reassign events
			this._unassignEvents();
			this._assignEvents();
		}
	}
};

// Dot notation converter
function convertNotation(options, notation) {
	var i = 0, obj, option = options,

	// Split notation into array
	levels = notation.split('.');

	// Loop through
	while(option = option[ levels[i++] ]) {
		if(i < levels.length) { obj = option; }
	}

	return [obj || options, levels.pop()];
}

PROTOTYPE.get = function(notation) {
	if(this.destroyed) { return this; }

	var o = convertNotation(this.options, notation.toLowerCase()),
		result = o[0][ o[1] ];

	return result.precedance ? result.string() : result;
};

function setCallback(notation, args) {
	var category, rule, match;

	for(category in this.checks) {
		if (!this.checks.hasOwnProperty(category)) { continue; }

		for(rule in this.checks[category]) {
			if (!this.checks[category].hasOwnProperty(rule)) { continue; }

			if(match = (new RegExp(rule, 'i')).exec(notation)) {
				args.push(match);

				if(category === 'builtin' || this.plugins[category]) {
					this.checks[category][rule].apply(
						this.plugins[category] || this, args
					);
				}
			}
		}
	}
}

var rmove = /^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,
	rrender = /^prerender|show\.ready/i;

PROTOTYPE.set = function(option, value) {
	if(this.destroyed) { return this; }

	var rendered = this.rendered,
		reposition = FALSE,
		options = this.options,
		name;

	// Convert singular option/value pair into object form
	if('string' === typeof option) {
		name = option; option = {}; option[name] = value;
	}
	else { option = $.extend({}, option); }

	// Set all of the defined options to their new values
	$.each(option, function(notation, val) {
		if(rendered && rrender.test(notation)) {
			delete option[notation]; return;
		}

		// Set new obj value
		var obj = convertNotation(options, notation.toLowerCase()), previous;
		previous = obj[0][ obj[1] ];
		obj[0][ obj[1] ] = val && val.nodeType ? $(val) : val;

		// Also check if we need to reposition
		reposition = rmove.test(notation) || reposition;

		// Set the new params for the callback
		option[notation] = [obj[0], obj[1], val, previous];
	});

	// Re-sanitize options
	sanitizeOptions(options);

	/*
	 * Execute any valid callbacks for the set options
	 * Also set positioning flag so we don't get loads of redundant repositioning calls.
	 */
	this.positioning = TRUE;
	$.each(option, $.proxy(setCallback, this));
	this.positioning = FALSE;

	// Update position if needed
	if(this.rendered && this.tooltip[0].offsetWidth > 0 && reposition) {
		this.reposition( options.position.target === 'mouse' ? NULL : this.cache.event );
	}

	return this;
};
;PROTOTYPE._update = function(content, element) {
	var self = this,
		cache = this.cache;

	// Make sure tooltip is rendered and content is defined. If not return
	if(!this.rendered || !content) { return FALSE; }

	// Use function to parse content
	if($.isFunction(content)) {
		content = content.call(this.elements.target, cache.event, this) || '';
	}

	// Handle deferred content
	if($.isFunction(content.then)) {
		cache.waiting = TRUE;
		return content.then(function(c) {
			cache.waiting = FALSE;
			return self._update(c, element);
		}, NULL, function(e) {
			return self._update(e, element);
		});
	}

	// If content is null... return false
	if(content === FALSE || !content && content !== '') { return FALSE; }

	// Append new content if its a DOM array and show it if hidden
	if(content.jquery && content.length > 0) {
		element.empty().append(
			content.css({ display: 'block', visibility: 'visible' })
		);
	}

	// Content is a regular string, insert the new content
	else { element.html(content); }

	// Wait for content to be loaded, and reposition
	return this._waitForContent(element).then(function(images) {
		if(self.rendered && self.tooltip[0].offsetWidth > 0) {
			self.reposition(cache.event, !images.length);
		}
	});
};

PROTOTYPE._waitForContent = function(element) {
	var cache = this.cache;

	// Set flag
	cache.waiting = TRUE;

	// If imagesLoaded is included, ensure images have loaded and return promise
	return ( $.fn.imagesLoaded ? element.imagesLoaded() : new $.Deferred().resolve([]) )
		.done(function() { cache.waiting = FALSE; })
		.promise();
};

PROTOTYPE._updateContent = function(content, reposition) {
	this._update(content, this.elements.content, reposition);
};

PROTOTYPE._updateTitle = function(content, reposition) {
	if(this._update(content, this.elements.title, reposition) === FALSE) {
		this._removeTitle(FALSE);
	}
};

PROTOTYPE._createTitle = function()
{
	var elements = this.elements,
		id = this._id+'-title';

	// Destroy previous title element, if present
	if(elements.titlebar) { this._removeTitle(); }

	// Create title bar and title elements
	elements.titlebar = $('<div />', {
		'class': NAMESPACE + '-titlebar ' + (this.options.style.widget ? createWidgetClass('header') : '')
	})
	.append(
		elements.title = $('<div />', {
			'id': id,
			'class': NAMESPACE + '-title',
			'aria-atomic': TRUE
		})
	)
	.insertBefore(elements.content)

	// Button-specific events
	.delegate('.qtip-close', 'mousedown keydown mouseup keyup mouseout', function(event) {
		$(this).toggleClass('ui-state-active ui-state-focus', event.type.substr(-4) === 'down');
	})
	.delegate('.qtip-close', 'mouseover mouseout', function(event){
		$(this).toggleClass('ui-state-hover', event.type === 'mouseover');
	});

	// Create button if enabled
	if(this.options.content.button) { this._createButton(); }
};

PROTOTYPE._removeTitle = function(reposition)
{
	var elements = this.elements;

	if(elements.title) {
		elements.titlebar.remove();
		elements.titlebar = elements.title = elements.button = NULL;

		// Reposition if enabled
		if(reposition !== FALSE) { this.reposition(); }
	}
};
;PROTOTYPE._createPosClass = function(my) {
	return NAMESPACE + '-pos-' + (my || this.options.position.my).abbrev();
};

PROTOTYPE.reposition = function(event, effect) {
	if(!this.rendered || this.positioning || this.destroyed) { return this; }

	// Set positioning flag
	this.positioning = TRUE;

	var cache = this.cache,
		tooltip = this.tooltip,
		posOptions = this.options.position,
		target = posOptions.target,
		my = posOptions.my,
		at = posOptions.at,
		viewport = posOptions.viewport,
		container = posOptions.container,
		adjust = posOptions.adjust,
		method = adjust.method.split(' '),
		tooltipWidth = tooltip.outerWidth(FALSE),
		tooltipHeight = tooltip.outerHeight(FALSE),
		targetWidth = 0,
		targetHeight = 0,
		type = tooltip.css('position'),
		position = { left: 0, top: 0 },
		visible = tooltip[0].offsetWidth > 0,
		isScroll = event && event.type === 'scroll',
		win = $(window),
		doc = container[0].ownerDocument,
		mouse = this.mouse,
		pluginCalculations, offset, adjusted, newClass;

	// Check if absolute position was passed
	if($.isArray(target) && target.length === 2) {
		// Force left top and set position
		at = { x: LEFT, y: TOP };
		position = { left: target[0], top: target[1] };
	}

	// Check if mouse was the target
	else if(target === 'mouse') {
		// Force left top to allow flipping
		at = { x: LEFT, y: TOP };

		// Use the mouse origin that caused the show event, if distance hiding is enabled
		if((!adjust.mouse || this.options.hide.distance) && cache.origin && cache.origin.pageX) {
			event =  cache.origin;
		}

		// Use cached event for resize/scroll events
		else if(!event || event && (event.type === 'resize' || event.type === 'scroll')) {
			event = cache.event;
		}

		// Otherwise, use the cached mouse coordinates if available
		else if(mouse && mouse.pageX) {
			event = mouse;
		}

		// Calculate body and container offset and take them into account below
		if(type !== 'static') { position = container.offset(); }
		if(doc.body.offsetWidth !== (window.innerWidth || doc.documentElement.clientWidth)) {
			offset = $(document.body).offset();
		}

		// Use event coordinates for position
		position = {
			left: event.pageX - position.left + (offset && offset.left || 0),
			top: event.pageY - position.top + (offset && offset.top || 0)
		};

		// Scroll events are a pain, some browsers
		if(adjust.mouse && isScroll && mouse) {
			position.left -= (mouse.scrollX || 0) - win.scrollLeft();
			position.top -= (mouse.scrollY || 0) - win.scrollTop();
		}
	}

	// Target wasn't mouse or absolute...
	else {
		// Check if event targetting is being used
		if(target === 'event') {
			if(event && event.target && event.type !== 'scroll' && event.type !== 'resize') {
				cache.target = $(event.target);
			}
			else if(!event.target) {
				cache.target = this.elements.target;
			}
		}
		else if(target !== 'event'){
			cache.target = $(target.jquery ? target : this.elements.target);
		}
		target = cache.target;

		// Parse the target into a jQuery object and make sure there's an element present
		target = $(target).eq(0);
		if(target.length === 0) { return this; }

		// Check if window or document is the target
		else if(target[0] === document || target[0] === window) {
			targetWidth = BROWSER.iOS ? window.innerWidth : target.width();
			targetHeight = BROWSER.iOS ? window.innerHeight : target.height();

			if(target[0] === window) {
				position = {
					top: (viewport || target).scrollTop(),
					left: (viewport || target).scrollLeft()
				};
			}
		}

		// Check if the target is an <AREA> element
		else if(PLUGINS.imagemap && target.is('area')) {
			pluginCalculations = PLUGINS.imagemap(this, target, at, PLUGINS.viewport ? method : FALSE);
		}

		// Check if the target is an SVG element
		else if(PLUGINS.svg && target && target[0].ownerSVGElement) {
			pluginCalculations = PLUGINS.svg(this, target, at, PLUGINS.viewport ? method : FALSE);
		}

		// Otherwise use regular jQuery methods
		else {
			targetWidth = target.outerWidth(FALSE);
			targetHeight = target.outerHeight(FALSE);
			position = target.offset();
		}

		// Parse returned plugin values into proper variables
		if(pluginCalculations) {
			targetWidth = pluginCalculations.width;
			targetHeight = pluginCalculations.height;
			offset = pluginCalculations.offset;
			position = pluginCalculations.position;
		}

		// Adjust position to take into account offset parents
		position = this.reposition.offset(target, position, container);

		// Adjust for position.fixed tooltips (and also iOS scroll bug in v3.2-4.0 & v4.3-4.3.2)
		if(BROWSER.iOS > 3.1 && BROWSER.iOS < 4.1 ||
			BROWSER.iOS >= 4.3 && BROWSER.iOS < 4.33 ||
			!BROWSER.iOS && type === 'fixed'
		){
			position.left -= win.scrollLeft();
			position.top -= win.scrollTop();
		}

		// Adjust position relative to target
		if(!pluginCalculations || pluginCalculations && pluginCalculations.adjustable !== FALSE) {
			position.left += at.x === RIGHT ? targetWidth : at.x === CENTER ? targetWidth / 2 : 0;
			position.top += at.y === BOTTOM ? targetHeight : at.y === CENTER ? targetHeight / 2 : 0;
		}
	}

	// Adjust position relative to tooltip
	position.left += adjust.x + (my.x === RIGHT ? -tooltipWidth : my.x === CENTER ? -tooltipWidth / 2 : 0);
	position.top += adjust.y + (my.y === BOTTOM ? -tooltipHeight : my.y === CENTER ? -tooltipHeight / 2 : 0);

	// Use viewport adjustment plugin if enabled
	if(PLUGINS.viewport) {
		adjusted = position.adjusted = PLUGINS.viewport(
			this, position, posOptions, targetWidth, targetHeight, tooltipWidth, tooltipHeight
		);

		// Apply offsets supplied by positioning plugin (if used)
		if(offset && adjusted.left) { position.left += offset.left; }
		if(offset && adjusted.top) {  position.top += offset.top; }

		// Apply any new 'my' position
		if(adjusted.my) { this.position.my = adjusted.my; }
	}

	// Viewport adjustment is disabled, set values to zero
	else { position.adjusted = { left: 0, top: 0 }; }

	// Set tooltip position class if it's changed
	if(cache.posClass !== (newClass = this._createPosClass(this.position.my))) {
		cache.posClass = newClass;
		tooltip.removeClass(cache.posClass).addClass(newClass);
	}

	// tooltipmove event
	if(!this._trigger('move', [position, viewport.elem || viewport], event)) { return this; }
	delete position.adjusted;

	// If effect is disabled, target it mouse, no animation is defined or positioning gives NaN out, set CSS directly
	if(effect === FALSE || !visible || isNaN(position.left) || isNaN(position.top) || target === 'mouse' || !$.isFunction(posOptions.effect)) {
		tooltip.css(position);
	}

	// Use custom function if provided
	else if($.isFunction(posOptions.effect)) {
		posOptions.effect.call(tooltip, this, $.extend({}, position));
		tooltip.queue(function(next) {
			// Reset attributes to avoid cross-browser rendering bugs
			$(this).css({ opacity: '', height: '' });
			if(BROWSER.ie) { this.style.removeAttribute('filter'); }

			next();
		});
	}

	// Set positioning flag
	this.positioning = FALSE;

	return this;
};

// Custom (more correct for qTip!) offset calculator
PROTOTYPE.reposition.offset = function(elem, pos, container) {
	if(!container[0]) { return pos; }

	var ownerDocument = $(elem[0].ownerDocument),
		quirks = !!BROWSER.ie && document.compatMode !== 'CSS1Compat',
		parent = container[0],
		scrolled, position, parentOffset, overflow;

	function scroll(e, i) {
		pos.left += i * e.scrollLeft();
		pos.top += i * e.scrollTop();
	}

	// Compensate for non-static containers offset
	do {
		if((position = $.css(parent, 'position')) !== 'static') {
			if(position === 'fixed') {
				parentOffset = parent.getBoundingClientRect();
				scroll(ownerDocument, -1);
			}
			else {
				parentOffset = $(parent).position();
				parentOffset.left += parseFloat($.css(parent, 'borderLeftWidth')) || 0;
				parentOffset.top += parseFloat($.css(parent, 'borderTopWidth')) || 0;
			}

			pos.left -= parentOffset.left + (parseFloat($.css(parent, 'marginLeft')) || 0);
			pos.top -= parentOffset.top + (parseFloat($.css(parent, 'marginTop')) || 0);

			// If this is the first parent element with an overflow of "scroll" or "auto", store it
			if(!scrolled && (overflow = $.css(parent, 'overflow')) !== 'hidden' && overflow !== 'visible') { scrolled = $(parent); }
		}
	}
	while(parent = parent.offsetParent);

	// Compensate for containers scroll if it also has an offsetParent (or in IE quirks mode)
	if(scrolled && (scrolled[0] !== ownerDocument[0] || quirks)) {
		scroll(scrolled, 1);
	}

	return pos;
};

// Corner class
var C = (CORNER = PROTOTYPE.reposition.Corner = function(corner, forceY) {
	corner = ('' + corner).replace(/([A-Z])/, ' $1').replace(/middle/gi, CENTER).toLowerCase();
	this.x = (corner.match(/left|right/i) || corner.match(/center/) || ['inherit'])[0].toLowerCase();
	this.y = (corner.match(/top|bottom|center/i) || ['inherit'])[0].toLowerCase();
	this.forceY = !!forceY;

	var f = corner.charAt(0);
	this.precedance = f === 't' || f === 'b' ? Y : X;
}).prototype;

C.invert = function(z, center) {
	this[z] = this[z] === LEFT ? RIGHT : this[z] === RIGHT ? LEFT : center || this[z];
};

C.string = function(join) {
	var x = this.x, y = this.y;

	var result = x !== y ?
		x === 'center' || y !== 'center' && (this.precedance === Y || this.forceY) ? 
			[y,x] : 
			[x,y] :
		[x];

	return join !== false ? result.join(' ') : result;
};

C.abbrev = function() {
	var result = this.string(false);
	return result[0].charAt(0) + (result[1] && result[1].charAt(0) || '');
};

C.clone = function() {
	return new CORNER( this.string(), this.forceY );
};

;
PROTOTYPE.toggle = function(state, event) {
	var cache = this.cache,
		options = this.options,
		tooltip = this.tooltip;

	// Try to prevent flickering when tooltip overlaps show element
	if(event) {
		if((/over|enter/).test(event.type) && cache.event && (/out|leave/).test(cache.event.type) &&
			options.show.target.add(event.target).length === options.show.target.length &&
			tooltip.has(event.relatedTarget).length) {
			return this;
		}

		// Cache event
		cache.event = $.event.fix(event);
	}

	// If we're currently waiting and we've just hidden... stop it
	this.waiting && !state && (this.hiddenDuringWait = TRUE);

	// Render the tooltip if showing and it isn't already
	if(!this.rendered) { return state ? this.render(1) : this; }
	else if(this.destroyed || this.disabled) { return this; }

	var type = state ? 'show' : 'hide',
		opts = this.options[type],
		posOptions = this.options.position,
		contentOptions = this.options.content,
		width = this.tooltip.css('width'),
		visible = this.tooltip.is(':visible'),
		animate = state || opts.target.length === 1,
		sameTarget = !event || opts.target.length < 2 || cache.target[0] === event.target,
		identicalState, allow, after;

	// Detect state if valid one isn't provided
	if((typeof state).search('boolean|number')) { state = !visible; }

	// Check if the tooltip is in an identical state to the new would-be state
	identicalState = !tooltip.is(':animated') && visible === state && sameTarget;

	// Fire tooltip(show/hide) event and check if destroyed
	allow = !identicalState ? !!this._trigger(type, [90]) : NULL;

	// Check to make sure the tooltip wasn't destroyed in the callback
	if(this.destroyed) { return this; }

	// If the user didn't stop the method prematurely and we're showing the tooltip, focus it
	if(allow !== FALSE && state) { this.focus(event); }

	// If the state hasn't changed or the user stopped it, return early
	if(!allow || identicalState) { return this; }

	// Set ARIA hidden attribute
	$.attr(tooltip[0], 'aria-hidden', !!!state);

	// Execute state specific properties
	if(state) {
		// Store show origin coordinates
		this.mouse && (cache.origin = $.event.fix(this.mouse));

		// Update tooltip content & title if it's a dynamic function
		if($.isFunction(contentOptions.text)) { this._updateContent(contentOptions.text, FALSE); }
		if($.isFunction(contentOptions.title)) { this._updateTitle(contentOptions.title, FALSE); }

		// Cache mousemove events for positioning purposes (if not already tracking)
		if(!trackingBound && posOptions.target === 'mouse' && posOptions.adjust.mouse) {
			$(document).bind('mousemove.'+NAMESPACE, this._storeMouse);
			trackingBound = TRUE;
		}

		// Update the tooltip position (set width first to prevent viewport/max-width issues)
		if(!width) { tooltip.css('width', tooltip.outerWidth(FALSE)); }
		this.reposition(event, arguments[2]);
		if(!width) { tooltip.css('width', ''); }

		// Hide other tooltips if tooltip is solo
		if(!!opts.solo) {
			(typeof opts.solo === 'string' ? $(opts.solo) : $(SELECTOR, opts.solo))
				.not(tooltip).not(opts.target).qtip('hide', new $.Event('tooltipsolo'));
		}
	}
	else {
		// Clear show timer if we're hiding
		clearTimeout(this.timers.show);

		// Remove cached origin on hide
		delete cache.origin;

		// Remove mouse tracking event if not needed (all tracking qTips are hidden)
		if(trackingBound && !$(SELECTOR+'[tracking="true"]:visible', opts.solo).not(tooltip).length) {
			$(document).unbind('mousemove.'+NAMESPACE);
			trackingBound = FALSE;
		}

		// Blur the tooltip
		this.blur(event);
	}

	// Define post-animation, state specific properties
	after = $.proxy(function() {
		if(state) {
			// Prevent antialias from disappearing in IE by removing filter
			if(BROWSER.ie) { tooltip[0].style.removeAttribute('filter'); }

			// Remove overflow setting to prevent tip bugs
			tooltip.css('overflow', '');

			// Autofocus elements if enabled
			if('string' === typeof opts.autofocus) {
				$(this.options.show.autofocus, tooltip).focus();
			}

			// If set, hide tooltip when inactive for delay period
			this.options.show.target.trigger('qtip-'+this.id+'-inactive');
		}
		else {
			// Reset CSS states
			tooltip.css({
				display: '',
				visibility: '',
				opacity: '',
				left: '',
				top: ''
			});
		}

		// tooltipvisible/tooltiphidden events
		this._trigger(state ? 'visible' : 'hidden');
	}, this);

	// If no effect type is supplied, use a simple toggle
	if(opts.effect === FALSE || animate === FALSE) {
		tooltip[ type ]();
		after();
	}

	// Use custom function if provided
	else if($.isFunction(opts.effect)) {
		tooltip.stop(1, 1);
		opts.effect.call(tooltip, this);
		tooltip.queue('fx', function(n) {
			after(); n();
		});
	}

	// Use basic fade function by default
	else { tooltip.fadeTo(90, state ? 1 : 0, after); }

	// If inactive hide method is set, active it
	if(state) { opts.target.trigger('qtip-'+this.id+'-inactive'); }

	return this;
};

PROTOTYPE.show = function(event) { return this.toggle(TRUE, event); };

PROTOTYPE.hide = function(event) { return this.toggle(FALSE, event); };
;PROTOTYPE.focus = function(event) {
	if(!this.rendered || this.destroyed) { return this; }

	var qtips = $(SELECTOR),
		tooltip = this.tooltip,
		curIndex = parseInt(tooltip[0].style.zIndex, 10),
		newIndex = QTIP.zindex + qtips.length;

	// Only update the z-index if it has changed and tooltip is not already focused
	if(!tooltip.hasClass(CLASS_FOCUS)) {
		// tooltipfocus event
		if(this._trigger('focus', [newIndex], event)) {
			// Only update z-index's if they've changed
			if(curIndex !== newIndex) {
				// Reduce our z-index's and keep them properly ordered
				qtips.each(function() {
					if(this.style.zIndex > curIndex) {
						this.style.zIndex = this.style.zIndex - 1;
					}
				});

				// Fire blur event for focused tooltip
				qtips.filter('.' + CLASS_FOCUS).qtip('blur', event);
			}

			// Set the new z-index
			tooltip.addClass(CLASS_FOCUS)[0].style.zIndex = newIndex;
		}
	}

	return this;
};

PROTOTYPE.blur = function(event) {
	if(!this.rendered || this.destroyed) { return this; }

	// Set focused status to FALSE
	this.tooltip.removeClass(CLASS_FOCUS);

	// tooltipblur event
	this._trigger('blur', [ this.tooltip.css('zIndex') ], event);

	return this;
};
;PROTOTYPE.disable = function(state) {
	if(this.destroyed) { return this; }

	// If 'toggle' is passed, toggle the current state
	if(state === 'toggle') {
		state = !(this.rendered ? this.tooltip.hasClass(CLASS_DISABLED) : this.disabled);
	}

	// Disable if no state passed
	else if('boolean' !== typeof state) {
		state = TRUE;
	}

	if(this.rendered) {
		this.tooltip.toggleClass(CLASS_DISABLED, state)
			.attr('aria-disabled', state);
	}

	this.disabled = !!state;

	return this;
};

PROTOTYPE.enable = function() { return this.disable(FALSE); };
;PROTOTYPE._createButton = function()
{
	var self = this,
		elements = this.elements,
		tooltip = elements.tooltip,
		button = this.options.content.button,
		isString = typeof button === 'string',
		close = isString ? button : 'Close tooltip';

	if(elements.button) { elements.button.remove(); }

	// Use custom button if one was supplied by user, else use default
	if(button.jquery) {
		elements.button = button;
	}
	else {
		elements.button = $('<a />', {
			'class': 'qtip-close ' + (this.options.style.widget ? '' : NAMESPACE+'-icon'),
			'title': close,
			'aria-label': close
		})
		.prepend(
			$('<span />', {
				'class': 'ui-icon ui-icon-close',
				'html': '&times;'
			})
		);
	}

	// Create button and setup attributes
	elements.button.appendTo(elements.titlebar || tooltip)
		.attr('role', 'button')
		.click(function(event) {
			if(!tooltip.hasClass(CLASS_DISABLED)) { self.hide(event); }
			return FALSE;
		});
};

PROTOTYPE._updateButton = function(button)
{
	// Make sure tooltip is rendered and if not, return
	if(!this.rendered) { return FALSE; }

	var elem = this.elements.button;
	if(button) { this._createButton(); }
	else { elem.remove(); }
};
;// Widget class creator
function createWidgetClass(cls) {
	return WIDGET.concat('').join(cls ? '-'+cls+' ' : ' ');
}

// Widget class setter method
PROTOTYPE._setWidget = function()
{
	var on = this.options.style.widget,
		elements = this.elements,
		tooltip = elements.tooltip,
		disabled = tooltip.hasClass(CLASS_DISABLED);

	tooltip.removeClass(CLASS_DISABLED);
	CLASS_DISABLED = on ? 'ui-state-disabled' : 'qtip-disabled';
	tooltip.toggleClass(CLASS_DISABLED, disabled);

	tooltip.toggleClass('ui-helper-reset '+createWidgetClass(), on).toggleClass(CLASS_DEFAULT, this.options.style.def && !on);

	if(elements.content) {
		elements.content.toggleClass( createWidgetClass('content'), on);
	}
	if(elements.titlebar) {
		elements.titlebar.toggleClass( createWidgetClass('header'), on);
	}
	if(elements.button) {
		elements.button.toggleClass(NAMESPACE+'-icon', !on);
	}
};
;function delay(callback, duration) {
	// If tooltip has displayed, start hide timer
	if(duration > 0) {
		return setTimeout(
			$.proxy(callback, this), duration
		);
	}
	else{ callback.call(this); }
}

function showMethod(event) {
	if(this.tooltip.hasClass(CLASS_DISABLED)) { return; }

	// Clear hide timers
	clearTimeout(this.timers.show);
	clearTimeout(this.timers.hide);

	// Start show timer
	this.timers.show = delay.call(this,
		function() { this.toggle(TRUE, event); },
		this.options.show.delay
	);
}

function hideMethod(event) {
	if(this.tooltip.hasClass(CLASS_DISABLED) || this.destroyed) { return; }

	// Check if new target was actually the tooltip element
	var relatedTarget = $(event.relatedTarget),
		ontoTooltip = relatedTarget.closest(SELECTOR)[0] === this.tooltip[0],
		ontoTarget = relatedTarget[0] === this.options.show.target[0];

	// Clear timers and stop animation queue
	clearTimeout(this.timers.show);
	clearTimeout(this.timers.hide);

	// Prevent hiding if tooltip is fixed and event target is the tooltip.
	// Or if mouse positioning is enabled and cursor momentarily overlaps
	if(this !== relatedTarget[0] &&
		(this.options.position.target === 'mouse' && ontoTooltip) ||
		this.options.hide.fixed && (
			(/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget))
		)
	{
		/* eslint-disable no-empty */
		try {
			event.preventDefault();
			event.stopImmediatePropagation();
		} catch(e) {}
		/* eslint-enable no-empty */

		return;
	}

	// If tooltip has displayed, start hide timer
	this.timers.hide = delay.call(this,
		function() { this.toggle(FALSE, event); },
		this.options.hide.delay,
		this
	);
}

function inactiveMethod(event) {
	if(this.tooltip.hasClass(CLASS_DISABLED) || !this.options.hide.inactive) { return; }

	// Clear timer
	clearTimeout(this.timers.inactive);

	this.timers.inactive = delay.call(this,
		function(){ this.hide(event); },
		this.options.hide.inactive
	);
}

function repositionMethod(event) {
	if(this.rendered && this.tooltip[0].offsetWidth > 0) { this.reposition(event); }
}

// Store mouse coordinates
PROTOTYPE._storeMouse = function(event) {
	(this.mouse = $.event.fix(event)).type = 'mousemove';
	return this;
};

// Bind events
PROTOTYPE._bind = function(targets, events, method, suffix, context) {
	if(!targets || !method || !events.length) { return; }
	var ns = '.' + this._id + (suffix ? '-'+suffix : '');
	$(targets).bind(
		(events.split ? events : events.join(ns + ' ')) + ns,
		$.proxy(method, context || this)
	);
	return this;
};
PROTOTYPE._unbind = function(targets, suffix) {
	targets && $(targets).unbind('.' + this._id + (suffix ? '-'+suffix : ''));
	return this;
};

// Global delegation helper
function delegate(selector, events, method) {
	$(document.body).delegate(selector,
		(events.split ? events : events.join('.'+NAMESPACE + ' ')) + '.'+NAMESPACE,
		function() {
			var api = QTIP.api[ $.attr(this, ATTR_ID) ];
			api && !api.disabled && method.apply(api, arguments);
		}
	);
}
// Event trigger
PROTOTYPE._trigger = function(type, args, event) {
	var callback = new $.Event('tooltip'+type);
	callback.originalEvent = event && $.extend({}, event) || this.cache.event || NULL;

	this.triggering = type;
	this.tooltip.trigger(callback, [this].concat(args || []));
	this.triggering = FALSE;

	return !callback.isDefaultPrevented();
};

PROTOTYPE._bindEvents = function(showEvents, hideEvents, showTargets, hideTargets, showCallback, hideCallback) {
	// Get tasrgets that lye within both
	var similarTargets = showTargets.filter( hideTargets ).add( hideTargets.filter(showTargets) ),
		toggleEvents = [];

	// If hide and show targets are the same...
	if(similarTargets.length) {

		// Filter identical show/hide events
		$.each(hideEvents, function(i, type) {
			var showIndex = $.inArray(type, showEvents);

			// Both events are identical, remove from both hide and show events
			// and append to toggleEvents
			showIndex > -1 && toggleEvents.push( showEvents.splice( showIndex, 1 )[0] );
		});

		// Toggle events are special case of identical show/hide events, which happen in sequence
		if(toggleEvents.length) {
			// Bind toggle events to the similar targets
			this._bind(similarTargets, toggleEvents, function(event) {
				var state = this.rendered ? this.tooltip[0].offsetWidth > 0 : false;
				(state ? hideCallback : showCallback).call(this, event);
			});

			// Remove the similar targets from the regular show/hide bindings
			showTargets = showTargets.not(similarTargets);
			hideTargets = hideTargets.not(similarTargets);
		}
	}

	// Apply show/hide/toggle events
	this._bind(showTargets, showEvents, showCallback);
	this._bind(hideTargets, hideEvents, hideCallback);
};

PROTOTYPE._assignInitialEvents = function(event) {
	var options = this.options,
		showTarget = options.show.target,
		hideTarget = options.hide.target,
		showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [],
		hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : [];

	// Catch remove/removeqtip events on target element to destroy redundant tooltips
	this._bind(this.elements.target, ['remove', 'removeqtip'], function() {
		this.destroy(true);
	}, 'destroy');

	/*
	 * Make sure hoverIntent functions properly by using mouseleave as a hide event if
	 * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
	 */
	if(/mouse(over|enter)/i.test(options.show.event) && !/mouse(out|leave)/i.test(options.hide.event)) {
		hideEvents.push('mouseleave');
	}

	/*
	 * Also make sure initial mouse targetting works correctly by caching mousemove coords
	 * on show targets before the tooltip has rendered. Also set onTarget when triggered to
	 * keep mouse tracking working.
	 */
	this._bind(showTarget, 'mousemove', function(moveEvent) {
		this._storeMouse(moveEvent);
		this.cache.onTarget = TRUE;
	});

	// Define hoverIntent function
	function hoverIntent(hoverEvent) {
		// Only continue if tooltip isn't disabled
		if(this.disabled || this.destroyed) { return FALSE; }

		// Cache the event data
		this.cache.event = hoverEvent && $.event.fix(hoverEvent);
		this.cache.target = hoverEvent && $(hoverEvent.target);

		// Start the event sequence
		clearTimeout(this.timers.show);
		this.timers.show = delay.call(this,
			function() { this.render(typeof hoverEvent === 'object' || options.show.ready); },
			options.prerender ? 0 : options.show.delay
		);
	}

	// Filter and bind events
	this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, hoverIntent, function() {
		if(!this.timers) { return FALSE; }
		clearTimeout(this.timers.show);
	});

	// Prerendering is enabled, create tooltip now
	if(options.show.ready || options.prerender) { hoverIntent.call(this, event); }
};

// Event assignment method
PROTOTYPE._assignEvents = function() {
	var self = this,
		options = this.options,
		posOptions = options.position,

		tooltip = this.tooltip,
		showTarget = options.show.target,
		hideTarget = options.hide.target,
		containerTarget = posOptions.container,
		viewportTarget = posOptions.viewport,
		documentTarget = $(document),
		windowTarget = $(window),

		showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [],
		hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : [];


	// Assign passed event callbacks
	$.each(options.events, function(name, callback) {
		self._bind(tooltip, name === 'toggle' ? ['tooltipshow','tooltiphide'] : ['tooltip'+name], callback, null, tooltip);
	});

	// Hide tooltips when leaving current window/frame (but not select/option elements)
	if(/mouse(out|leave)/i.test(options.hide.event) && options.hide.leave === 'window') {
		this._bind(documentTarget, ['mouseout', 'blur'], function(event) {
			if(!/select|option/.test(event.target.nodeName) && !event.relatedTarget) {
				this.hide(event);
			}
		});
	}

	// Enable hide.fixed by adding appropriate class
	if(options.hide.fixed) {
		hideTarget = hideTarget.add( tooltip.addClass(CLASS_FIXED) );
	}

	/*
	 * Make sure hoverIntent functions properly by using mouseleave to clear show timer if
	 * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
	 */
	else if(/mouse(over|enter)/i.test(options.show.event)) {
		this._bind(hideTarget, 'mouseleave', function() {
			clearTimeout(this.timers.show);
		});
	}

	// Hide tooltip on document mousedown if unfocus events are enabled
	if(('' + options.hide.event).indexOf('unfocus') > -1) {
		this._bind(containerTarget.closest('html'), ['mousedown', 'touchstart'], function(event) {
			var elem = $(event.target),
				enabled = this.rendered && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0,
				isAncestor = elem.parents(SELECTOR).filter(this.tooltip[0]).length > 0;

			if(elem[0] !== this.target[0] && elem[0] !== this.tooltip[0] && !isAncestor &&
				!this.target.has(elem[0]).length && enabled
			) {
				this.hide(event);
			}
		});
	}

	// Check if the tooltip hides when inactive
	if('number' === typeof options.hide.inactive) {
		// Bind inactive method to show target(s) as a custom event
		this._bind(showTarget, 'qtip-'+this.id+'-inactive', inactiveMethod, 'inactive');

		// Define events which reset the 'inactive' event handler
		this._bind(hideTarget.add(tooltip), QTIP.inactiveEvents, inactiveMethod);
	}

	// Filter and bind events
	this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, showMethod, hideMethod);

	// Mouse movement bindings
	this._bind(showTarget.add(tooltip), 'mousemove', function(event) {
		// Check if the tooltip hides when mouse is moved a certain distance
		if('number' === typeof options.hide.distance) {
			var origin = this.cache.origin || {},
				limit = this.options.hide.distance,
				abs = Math.abs;

			// Check if the movement has gone beyond the limit, and hide it if so
			if(abs(event.pageX - origin.pageX) >= limit || abs(event.pageY - origin.pageY) >= limit) {
				this.hide(event);
			}
		}

		// Cache mousemove coords on show targets
		this._storeMouse(event);
	});

	// Mouse positioning events
	if(posOptions.target === 'mouse') {
		// If mouse adjustment is on...
		if(posOptions.adjust.mouse) {
			// Apply a mouseleave event so we don't get problems with overlapping
			if(options.hide.event) {
				// Track if we're on the target or not
				this._bind(showTarget, ['mouseenter', 'mouseleave'], function(event) {
					if(!this.cache) {return FALSE; }
					this.cache.onTarget = event.type === 'mouseenter';
				});
			}

			// Update tooltip position on mousemove
			this._bind(documentTarget, 'mousemove', function(event) {
				// Update the tooltip position only if the tooltip is visible and adjustment is enabled
				if(this.rendered && this.cache.onTarget && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0) {
					this.reposition(event);
				}
			});
		}
	}

	// Adjust positions of the tooltip on window resize if enabled
	if(posOptions.adjust.resize || viewportTarget.length) {
		this._bind( $.event.special.resize ? viewportTarget : windowTarget, 'resize', repositionMethod );
	}

	// Adjust tooltip position on scroll of the window or viewport element if present
	if(posOptions.adjust.scroll) {
		this._bind( windowTarget.add(posOptions.container), 'scroll', repositionMethod );
	}
};

// Un-assignment method
PROTOTYPE._unassignEvents = function() {
	var options = this.options,
		showTargets = options.show.target,
		hideTargets = options.hide.target,
		targets = $.grep([
			this.elements.target[0],
			this.rendered && this.tooltip[0],
			options.position.container[0],
			options.position.viewport[0],
			options.position.container.closest('html')[0], // unfocus
			window,
			document
		], function(i) {
			return typeof i === 'object';
		});

	// Add show and hide targets if they're valid
	if(showTargets && showTargets.toArray) {
		targets = targets.concat(showTargets.toArray());
	}
	if(hideTargets && hideTargets.toArray) {
		targets = targets.concat(hideTargets.toArray());
	}

	// Unbind the events
	this._unbind(targets)
		._unbind(targets, 'destroy')
		._unbind(targets, 'inactive');
};

// Apply common event handlers using delegate (avoids excessive .bind calls!)
$(function() {
	delegate(SELECTOR, ['mouseenter', 'mouseleave'], function(event) {
		var state = event.type === 'mouseenter',
			tooltip = $(event.currentTarget),
			target = $(event.relatedTarget || event.target),
			options = this.options;

		// On mouseenter...
		if(state) {
			// Focus the tooltip on mouseenter (z-index stacking)
			this.focus(event);

			// Clear hide timer on tooltip hover to prevent it from closing
			tooltip.hasClass(CLASS_FIXED) && !tooltip.hasClass(CLASS_DISABLED) && clearTimeout(this.timers.hide);
		}

		// On mouseleave...
		else {
			// When mouse tracking is enabled, hide when we leave the tooltip and not onto the show target (if a hide event is set)
			if(options.position.target === 'mouse' && options.position.adjust.mouse &&
				options.hide.event && options.show.target && !target.closest(options.show.target[0]).length) {
				this.hide(event);
			}
		}

		// Add hover class
		tooltip.toggleClass(CLASS_HOVER, state);
	});

	// Define events which reset the 'inactive' event handler
	delegate('['+ATTR_ID+']', INACTIVE_EVENTS, inactiveMethod);
});
;// Initialization method
function init(elem, id, opts) {
	var obj, posOptions, attr, config, title,

	// Setup element references
	docBody = $(document.body),

	// Use document body instead of document element if needed
	newTarget = elem[0] === document ? docBody : elem,

	// Grab metadata from element if plugin is present
	metadata = elem.metadata ? elem.metadata(opts.metadata) : NULL,

	// If metadata type if HTML5, grab 'name' from the object instead, or use the regular data object otherwise
	metadata5 = opts.metadata.type === 'html5' && metadata ? metadata[opts.metadata.name] : NULL,

	// Grab data from metadata.name (or data-qtipopts as fallback) using .data() method,
	html5 = elem.data(opts.metadata.name || 'qtipopts');

	// If we don't get an object returned attempt to parse it manualyl without parseJSON
	/* eslint-disable no-empty */
	try { html5 = typeof html5 === 'string' ? $.parseJSON(html5) : html5; }
	catch(e) {}
	/* eslint-enable no-empty */

	// Merge in and sanitize metadata
	config = $.extend(TRUE, {}, QTIP.defaults, opts,
		typeof html5 === 'object' ? sanitizeOptions(html5) : NULL,
		sanitizeOptions(metadata5 || metadata));

	// Re-grab our positioning options now we've merged our metadata and set id to passed value
	posOptions = config.position;
	config.id = id;

	// Setup missing content if none is detected
	if('boolean' === typeof config.content.text) {
		attr = elem.attr(config.content.attr);

		// Grab from supplied attribute if available
		if(config.content.attr !== FALSE && attr) { config.content.text = attr; }

		// No valid content was found, abort render
		else { return FALSE; }
	}

	// Setup target options
	if(!posOptions.container.length) { posOptions.container = docBody; }
	if(posOptions.target === FALSE) { posOptions.target = newTarget; }
	if(config.show.target === FALSE) { config.show.target = newTarget; }
	if(config.show.solo === TRUE) { config.show.solo = posOptions.container.closest('body'); }
	if(config.hide.target === FALSE) { config.hide.target = newTarget; }
	if(config.position.viewport === TRUE) { config.position.viewport = posOptions.container; }

	// Ensure we only use a single container
	posOptions.container = posOptions.container.eq(0);

	// Convert position corner values into x and y strings
	posOptions.at = new CORNER(posOptions.at, TRUE);
	posOptions.my = new CORNER(posOptions.my);

	// Destroy previous tooltip if overwrite is enabled, or skip element if not
	if(elem.data(NAMESPACE)) {
		if(config.overwrite) {
			elem.qtip('destroy', true);
		}
		else if(config.overwrite === FALSE) {
			return FALSE;
		}
	}

	// Add has-qtip attribute
	elem.attr(ATTR_HAS, id);

	// Remove title attribute and store it if present
	if(config.suppress && (title = elem.attr('title'))) {
		// Final attr call fixes event delegatiom and IE default tooltip showing problem
		elem.removeAttr('title').attr(oldtitle, title).attr('title', '');
	}

	// Initialize the tooltip and add API reference
	obj = new QTip(elem, config, id, !!attr);
	elem.data(NAMESPACE, obj);

	return obj;
}

// jQuery $.fn extension method
QTIP = $.fn.qtip = function(options, notation, newValue)
{
	var command = ('' + options).toLowerCase(), // Parse command
		returned = NULL,
		args = $.makeArray(arguments).slice(1),
		event = args[args.length - 1],
		opts = this[0] ? $.data(this[0], NAMESPACE) : NULL;

	// Check for API request
	if(!arguments.length && opts || command === 'api') {
		return opts;
	}

	// Execute API command if present
	else if('string' === typeof options) {
		this.each(function() {
			var api = $.data(this, NAMESPACE);
			if(!api) { return TRUE; }

			// Cache the event if possible
			if(event && event.timeStamp) { api.cache.event = event; }

			// Check for specific API commands
			if(notation && (command === 'option' || command === 'options')) {
				if(newValue !== undefined || $.isPlainObject(notation)) {
					api.set(notation, newValue);
				}
				else {
					returned = api.get(notation);
					return FALSE;
				}
			}

			// Execute API command
			else if(api[command]) {
				api[command].apply(api, args);
			}
		});

		return returned !== NULL ? returned : this;
	}

	// No API commands. validate provided options and setup qTips
	else if('object' === typeof options || !arguments.length) {
		// Sanitize options first
		opts = sanitizeOptions($.extend(TRUE, {}, options));

		return this.each(function(i) {
			var api, id;

			// Find next available ID, or use custom ID if provided
			id = $.isArray(opts.id) ? opts.id[i] : opts.id;
			id = !id || id === FALSE || id.length < 1 || QTIP.api[id] ? QTIP.nextid++ : id;

			// Initialize the qTip and re-grab newly sanitized options
			api = init($(this), id, opts);
			if(api === FALSE) { return TRUE; }
			else { QTIP.api[id] = api; }

			// Initialize plugins
			$.each(PLUGINS, function() {
				if(this.initialize === 'initialize') { this(api); }
			});

			// Assign initial pre-render events
			api._assignInitialEvents(event);
		});
	}
};

// Expose class
$.qtip = QTip;

// Populated in render method
QTIP.api = {};
;$.each({
	/* Allow other plugins to successfully retrieve the title of an element with a qTip applied */
	attr: function(attr, val) {
		if(this.length) {
			var self = this[0],
				title = 'title',
				api = $.data(self, 'qtip');

			if(attr === title && api && api.options && 'object' === typeof api && 'object' === typeof api.options && api.options.suppress) {
				if(arguments.length < 2) {
					return $.attr(self, oldtitle);
				}

				// If qTip is rendered and title was originally used as content, update it
				if(api && api.options.content.attr === title && api.cache.attr) {
					api.set('content.text', val);
				}

				// Use the regular attr method to set, then cache the result
				return this.attr(oldtitle, val);
			}
		}

		return $.fn['attr'+replaceSuffix].apply(this, arguments);
	},

	/* Allow clone to correctly retrieve cached title attributes */
	clone: function(keepData) {
		// Clone our element using the real clone method
		var elems = $.fn['clone'+replaceSuffix].apply(this, arguments);

		// Grab all elements with an oldtitle set, and change it to regular title attribute, if keepData is false
		if(!keepData) {
			elems.filter('['+oldtitle+']').attr('title', function() {
				return $.attr(this, oldtitle);
			})
			.removeAttr(oldtitle);
		}

		return elems;
	}
}, function(name, func) {
	if(!func || $.fn[name+replaceSuffix]) { return TRUE; }

	var old = $.fn[name+replaceSuffix] = $.fn[name];
	$.fn[name] = function() {
		return func.apply(this, arguments) || old.apply(this, arguments);
	};
});

/* Fire off 'removeqtip' handler in $.cleanData if jQuery UI not present (it already does similar).
 * This snippet is taken directly from jQuery UI source code found here:
 *     http://code.jquery.com/ui/jquery-ui-git.js
 */
if(!$.ui) {
	$['cleanData'+replaceSuffix] = $.cleanData;
	$.cleanData = function( elems ) {
		for(var i = 0, elem; (elem = $( elems[i] )).length; i++) {
			if(elem.attr(ATTR_HAS)) {
				/* eslint-disable no-empty */
				try { elem.triggerHandler('removeqtip'); }
				catch( e ) {}
				/* eslint-enable no-empty */
			}
		}
		$['cleanData'+replaceSuffix].apply(this, arguments);
	};
}
;// qTip version
QTIP.version = '3.0.3';

// Base ID for all qTips
QTIP.nextid = 0;

// Inactive events array
QTIP.inactiveEvents = INACTIVE_EVENTS;

// Base z-index for all qTips
QTIP.zindex = 15000;

// Define configuration defaults
QTIP.defaults = {
	prerender: FALSE,
	id: FALSE,
	overwrite: TRUE,
	suppress: TRUE,
	content: {
		text: TRUE,
		attr: 'title',
		title: FALSE,
		button: FALSE
	},
	position: {
		my: 'top left',
		at: 'bottom right',
		target: FALSE,
		container: FALSE,
		viewport: FALSE,
		adjust: {
			x: 0, y: 0,
			mouse: TRUE,
			scroll: TRUE,
			resize: TRUE,
			method: 'flipinvert flipinvert'
		},
		effect: function(api, pos) {
			$(this).animate(pos, {
				duration: 200,
				queue: FALSE
			});
		}
	},
	show: {
		target: FALSE,
		event: 'mouseenter',
		effect: TRUE,
		delay: 90,
		solo: FALSE,
		ready: FALSE,
		autofocus: FALSE
	},
	hide: {
		target: FALSE,
		event: 'mouseleave',
		effect: TRUE,
		delay: 0,
		fixed: FALSE,
		inactive: FALSE,
		leave: 'window',
		distance: FALSE
	},
	style: {
		classes: '',
		widget: FALSE,
		width: FALSE,
		height: FALSE,
		def: TRUE
	},
	events: {
		render: NULL,
		move: NULL,
		show: NULL,
		hide: NULL,
		toggle: NULL,
		visible: NULL,
		hidden: NULL,
		focus: NULL,
		blur: NULL
	}
};
;var TIP,
createVML,
SCALE,
PIXEL_RATIO,
BACKING_STORE_RATIO,

// Common CSS strings
MARGIN = 'margin',
BORDER = 'border',
COLOR = 'color',
BG_COLOR = 'background-color',
TRANSPARENT = 'transparent',
IMPORTANT = ' !important',

// Check if the browser supports <canvas/> elements
HASCANVAS = !!document.createElement('canvas').getContext,

// Invalid colour values used in parseColours()
INVALID = /rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i;

// Camel-case method, taken from jQuery source
// http://code.jquery.com/jquery-1.8.0.js
function camel(s) { return s.charAt(0).toUpperCase() + s.slice(1); }

/*
 * Modified from Modernizr's testPropsAll()
 * http://modernizr.com/downloads/modernizr-latest.js
 */
var cssProps = {}, cssPrefixes = ['Webkit', 'O', 'Moz', 'ms'];
function vendorCss(elem, prop) {
	var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
		props = (prop + ' ' + cssPrefixes.join(ucProp + ' ') + ucProp).split(' '),
		cur, val, i = 0;

	// If the property has already been mapped...
	if(cssProps[prop]) { return elem.css(cssProps[prop]); }

	while(cur = props[i++]) {
		if((val = elem.css(cur)) !== undefined) {
			cssProps[prop] = cur;
			return val;
		}
	}
}

// Parse a given elements CSS property into an int
function intCss(elem, prop) {
	return Math.ceil(parseFloat(vendorCss(elem, prop)));
}


// VML creation (for IE only)
if(!HASCANVAS) {
	createVML = function(tag, props, style) {
		return '<qtipvml:'+tag+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(props||'')+
			' style="behavior: url(#default#VML); '+(style||'')+ '" />';
	};
}

// Canvas only definitions
else {
	PIXEL_RATIO = window.devicePixelRatio || 1;
	BACKING_STORE_RATIO = (function() {
		var context = document.createElement('canvas').getContext('2d');
		return context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio ||
				context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || 1;
	})();
	SCALE = PIXEL_RATIO / BACKING_STORE_RATIO;
}


function Tip(qtip, options) {
	this._ns = 'tip';
	this.options = options;
	this.offset = options.offset;
	this.size = [ options.width, options.height ];

	// Initialize
	this.qtip = qtip;
	this.init(qtip);
}

$.extend(Tip.prototype, {
	init: function(qtip) {
		var context, tip;

		// Create tip element and prepend to the tooltip
		tip = this.element = qtip.elements.tip = $('<div />', { 'class': NAMESPACE+'-tip' }).prependTo(qtip.tooltip);

		// Create tip drawing element(s)
		if(HASCANVAS) {
			// save() as soon as we create the canvas element so FF2 doesn't bork on our first restore()!
			context = $('<canvas />').appendTo(this.element)[0].getContext('2d');

			// Setup constant parameters
			context.lineJoin = 'miter';
			context.miterLimit = 100000;
			context.save();
		}
		else {
			context = createVML('shape', 'coordorigin="0,0"', 'position:absolute;');
			this.element.html(context + context);

			// Prevent mousing down on the tip since it causes problems with .live() handling in IE due to VML
			qtip._bind( $('*', tip).add(tip), ['click', 'mousedown'], function(event) { event.stopPropagation(); }, this._ns);
		}

		// Bind update events
		qtip._bind(qtip.tooltip, 'tooltipmove', this.reposition, this._ns, this);

		// Create it
		this.create();
	},

	_swapDimensions: function() {
		this.size[0] = this.options.height;
		this.size[1] = this.options.width;
	},
	_resetDimensions: function() {
		this.size[0] = this.options.width;
		this.size[1] = this.options.height;
	},

	_useTitle: function(corner) {
		var titlebar = this.qtip.elements.titlebar;
		return titlebar && (
			corner.y === TOP || corner.y === CENTER && this.element.position().top + this.size[1] / 2 + this.options.offset < titlebar.outerHeight(TRUE)
		);
	},

	_parseCorner: function(corner) {
		var my = this.qtip.options.position.my;

		// Detect corner and mimic properties
		if(corner === FALSE || my === FALSE) {
			corner = FALSE;
		}
		else if(corner === TRUE) {
			corner = new CORNER( my.string() );
		}
		else if(!corner.string) {
			corner = new CORNER(corner);
			corner.fixed = TRUE;
		}

		return corner;
	},

	_parseWidth: function(corner, side, use) {
		var elements = this.qtip.elements,
			prop = BORDER + camel(side) + 'Width';

		return (use ? intCss(use, prop) : 
			intCss(elements.content, prop) ||
			intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) ||
			intCss(elements.tooltip, prop)
		) || 0;
	},

	_parseRadius: function(corner) {
		var elements = this.qtip.elements,
			prop = BORDER + camel(corner.y) + camel(corner.x) + 'Radius';

		return BROWSER.ie < 9 ? 0 :
			intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) ||
			intCss(elements.tooltip, prop) || 0;
	},

	_invalidColour: function(elem, prop, compare) {
		var val = elem.css(prop);
		return !val || compare && val === elem.css(compare) || INVALID.test(val) ? FALSE : val;
	},

	_parseColours: function(corner) {
		var elements = this.qtip.elements,
			tip = this.element.css('cssText', ''),
			borderSide = BORDER + camel(corner[ corner.precedance ]) + camel(COLOR),
			colorElem = this._useTitle(corner) && elements.titlebar || elements.content,
			css = this._invalidColour, color = [];

		// Attempt to detect the background colour from various elements, left-to-right precedance
		color[0] = css(tip, BG_COLOR) || css(colorElem, BG_COLOR) || css(elements.content, BG_COLOR) ||
			css(elements.tooltip, BG_COLOR) || tip.css(BG_COLOR);

		// Attempt to detect the correct border side colour from various elements, left-to-right precedance
		color[1] = css(tip, borderSide, COLOR) || css(colorElem, borderSide, COLOR) ||
			css(elements.content, borderSide, COLOR) || css(elements.tooltip, borderSide, COLOR) || elements.tooltip.css(borderSide);

		// Reset background and border colours
		$('*', tip).add(tip).css('cssText', BG_COLOR+':'+TRANSPARENT+IMPORTANT+';'+BORDER+':0'+IMPORTANT+';');

		return color;
	},

	_calculateSize: function(corner) {
		var y = corner.precedance === Y,
			width = this.options.width,
			height = this.options.height,
			isCenter = corner.abbrev() === 'c',
			base = (y ? width: height) * (isCenter ? 0.5 : 1),
			pow = Math.pow,
			round = Math.round,
			bigHyp, ratio, result,

		smallHyp = Math.sqrt( pow(base, 2) + pow(height, 2) ),
		hyp = [
			this.border / base * smallHyp,
			this.border / height * smallHyp
		];

		hyp[2] = Math.sqrt( pow(hyp[0], 2) - pow(this.border, 2) );
		hyp[3] = Math.sqrt( pow(hyp[1], 2) - pow(this.border, 2) );

		bigHyp = smallHyp + hyp[2] + hyp[3] + (isCenter ? 0 : hyp[0]);
		ratio = bigHyp / smallHyp;

		result = [ round(ratio * width), round(ratio * height) ];
		return y ? result : result.reverse();
	},

	// Tip coordinates calculator
	_calculateTip: function(corner, size, scale) {
		scale = scale || 1;
		size = size || this.size;

		var width = size[0] * scale,
			height = size[1] * scale,
			width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2),

		// Define tip coordinates in terms of height and width values
		tips = {
			br:	[0,0,		width,height,	width,0],
			bl:	[0,0,		width,0,		0,height],
			tr:	[0,height,	width,0,		width,height],
			tl:	[0,0,		0,height,		width,height],
			tc:	[0,height,	width2,0,		width,height],
			bc:	[0,0,		width,0,		width2,height],
			rc:	[0,0,		width,height2,	0,height],
			lc:	[width,0,	width,height,	0,height2]
		};

		// Set common side shapes
		tips.lt = tips.br; tips.rt = tips.bl;
		tips.lb = tips.tr; tips.rb = tips.tl;

		return tips[ corner.abbrev() ];
	},

	// Tip coordinates drawer (canvas)
	_drawCoords: function(context, coords) {
		context.beginPath();
		context.moveTo(coords[0], coords[1]);
		context.lineTo(coords[2], coords[3]);
		context.lineTo(coords[4], coords[5]);
		context.closePath();
	},

	create: function() {
		// Determine tip corner
		var c = this.corner = (HASCANVAS || BROWSER.ie) && this._parseCorner(this.options.corner);

		// If we have a tip corner...
		this.enabled = !!this.corner && this.corner.abbrev() !== 'c';
		if(this.enabled) {
			// Cache it
			this.qtip.cache.corner = c.clone();

			// Create it
			this.update();
		}

		// Toggle tip element
		this.element.toggle(this.enabled);

		return this.corner;
	},

	update: function(corner, position) {
		if(!this.enabled) { return this; }

		var elements = this.qtip.elements,
			tip = this.element,
			inner = tip.children(),
			options = this.options,
			curSize = this.size,
			mimic = options.mimic,
			round = Math.round,
			color, precedance, context,
			coords, bigCoords, translate, newSize, border;

		// Re-determine tip if not already set
		if(!corner) { corner = this.qtip.cache.corner || this.corner; }

		// Use corner property if we detect an invalid mimic value
		if(mimic === FALSE) { mimic = corner; }

		// Otherwise inherit mimic properties from the corner object as necessary
		else {
			mimic = new CORNER(mimic);
			mimic.precedance = corner.precedance;

			if(mimic.x === 'inherit') { mimic.x = corner.x; }
			else if(mimic.y === 'inherit') { mimic.y = corner.y; }
			else if(mimic.x === mimic.y) {
				mimic[ corner.precedance ] = corner[ corner.precedance ];
			}
		}
		precedance = mimic.precedance;

		// Ensure the tip width.height are relative to the tip position
		if(corner.precedance === X) { this._swapDimensions(); }
		else { this._resetDimensions(); }

		// Update our colours
		color = this.color = this._parseColours(corner);

		// Detect border width, taking into account colours
		if(color[1] !== TRANSPARENT) {
			// Grab border width
			border = this.border = this._parseWidth(corner, corner[corner.precedance]);

			// If border width isn't zero, use border color as fill if it's not invalid (1.0 style tips)
			if(options.border && border < 1 && !INVALID.test(color[1])) { color[0] = color[1]; }

			// Set border width (use detected border width if options.border is true)
			this.border = border = options.border !== TRUE ? options.border : border;
		}

		// Border colour was invalid, set border to zero
		else { this.border = border = 0; }

		// Determine tip size
		newSize = this.size = this._calculateSize(corner);
		tip.css({
			width: newSize[0],
			height: newSize[1],
			lineHeight: newSize[1]+'px'
		});

		// Calculate tip translation
		if(corner.precedance === Y) {
			translate = [
				round(mimic.x === LEFT ? border : mimic.x === RIGHT ? newSize[0] - curSize[0] - border : (newSize[0] - curSize[0]) / 2),
				round(mimic.y === TOP ? newSize[1] - curSize[1] : 0)
			];
		}
		else {
			translate = [
				round(mimic.x === LEFT ? newSize[0] - curSize[0] : 0),
				round(mimic.y === TOP ? border : mimic.y === BOTTOM ? newSize[1] - curSize[1] - border : (newSize[1] - curSize[1]) / 2)
			];
		}

		// Canvas drawing implementation
		if(HASCANVAS) {
			// Grab canvas context and clear/save it
			context = inner[0].getContext('2d');
			context.restore(); context.save();
			context.clearRect(0,0,6000,6000);

			// Calculate coordinates
			coords = this._calculateTip(mimic, curSize, SCALE);
			bigCoords = this._calculateTip(mimic, this.size, SCALE);

			// Set the canvas size using calculated size
			inner.attr(WIDTH, newSize[0] * SCALE).attr(HEIGHT, newSize[1] * SCALE);
			inner.css(WIDTH, newSize[0]).css(HEIGHT, newSize[1]);

			// Draw the outer-stroke tip
			this._drawCoords(context, bigCoords);
			context.fillStyle = color[1];
			context.fill();

			// Draw the actual tip
			context.translate(translate[0] * SCALE, translate[1] * SCALE);
			this._drawCoords(context, coords);
			context.fillStyle = color[0];
			context.fill();
		}

		// VML (IE Proprietary implementation)
		else {
			// Calculate coordinates
			coords = this._calculateTip(mimic);

			// Setup coordinates string
			coords = 'm' + coords[0] + ',' + coords[1] + ' l' + coords[2] +
				',' + coords[3] + ' ' + coords[4] + ',' + coords[5] + ' xe';

			// Setup VML-specific offset for pixel-perfection
			translate[2] = border && /^(r|b)/i.test(corner.string()) ?
				BROWSER.ie === 8 ? 2 : 1 : 0;

			// Set initial CSS
			inner.css({
				coordsize: newSize[0]+border + ' ' + newSize[1]+border,
				antialias: ''+(mimic.string().indexOf(CENTER) > -1),
				left: translate[0] - translate[2] * Number(precedance === X),
				top: translate[1] - translate[2] * Number(precedance === Y),
				width: newSize[0] + border,
				height: newSize[1] + border
			})
			.each(function(i) {
				var $this = $(this);

				// Set shape specific attributes
				$this[ $this.prop ? 'prop' : 'attr' ]({
					coordsize: newSize[0]+border + ' ' + newSize[1]+border,
					path: coords,
					fillcolor: color[0],
					filled: !!i,
					stroked: !i
				})
				.toggle(!!(border || i));

				// Check if border is enabled and add stroke element
				!i && $this.html( createVML(
					'stroke', 'weight="'+border*2+'px" color="'+color[1]+'" miterlimit="1000" joinstyle="miter"'
				) );
			});
		}

		// Opera bug #357 - Incorrect tip position
		// https://github.com/Craga89/qTip2/issues/367
		window.opera && setTimeout(function() {
			elements.tip.css({
				display: 'inline-block',
				visibility: 'visible'
			});
		}, 1);

		// Position if needed
		if(position !== FALSE) { this.calculate(corner, newSize); }
	},

	calculate: function(corner, size) {
		if(!this.enabled) { return FALSE; }

		var self = this,
			elements = this.qtip.elements,
			tip = this.element,
			userOffset = this.options.offset,
			position = {},
			precedance, corners;

		// Inherit corner if not provided
		corner = corner || this.corner;
		precedance = corner.precedance;

		// Determine which tip dimension to use for adjustment
		size = size || this._calculateSize(corner);

		// Setup corners and offset array
		corners = [ corner.x, corner.y ];
		if(precedance === X) { corners.reverse(); }

		// Calculate tip position
		$.each(corners, function(i, side) {
			var b, bc, br;

			if(side === CENTER) {
				b = precedance === Y ? LEFT : TOP;
				position[ b ] = '50%';
				position[MARGIN+'-' + b] = -Math.round(size[ precedance === Y ? 0 : 1 ] / 2) + userOffset;
			}
			else {
				b = self._parseWidth(corner, side, elements.tooltip);
				bc = self._parseWidth(corner, side, elements.content);
				br = self._parseRadius(corner);

				position[ side ] = Math.max(-self.border, i ? bc : userOffset + (br > b ? br : -b));
			}
		});

		// Adjust for tip size
		position[ corner[precedance] ] -= size[ precedance === X ? 0 : 1 ];

		// Set and return new position
		tip.css({ margin: '', top: '', bottom: '', left: '', right: '' }).css(position);
		return position;
	},

	reposition: function(event, api, pos) {
		if(!this.enabled) { return; }

		var cache = api.cache,
			newCorner = this.corner.clone(),
			adjust = pos.adjusted,
			method = api.options.position.adjust.method.split(' '),
			horizontal = method[0],
			vertical = method[1] || method[0],
			shift = { left: FALSE, top: FALSE, x: 0, y: 0 },
			offset, css = {}, props;

		function shiftflip(direction, precedance, popposite, side, opposite) {
			// Horizontal - Shift or flip method
			if(direction === SHIFT && newCorner.precedance === precedance && adjust[side] && newCorner[popposite] !== CENTER) {
				newCorner.precedance = newCorner.precedance === X ? Y : X;
			}
			else if(direction !== SHIFT && adjust[side]){
				newCorner[precedance] = newCorner[precedance] === CENTER ?
					adjust[side] > 0 ? side : opposite :
					newCorner[precedance] === side ? opposite : side;
			}
		}

		function shiftonly(xy, side, opposite) {
			if(newCorner[xy] === CENTER) {
				css[MARGIN+'-'+side] = shift[xy] = offset[MARGIN+'-'+side] - adjust[side];
			}
			else {
				props = offset[opposite] !== undefined ?
					[ adjust[side], -offset[side] ] : [ -adjust[side], offset[side] ];

				if( (shift[xy] = Math.max(props[0], props[1])) > props[0] ) {
					pos[side] -= adjust[side];
					shift[side] = FALSE;
				}

				css[ offset[opposite] !== undefined ? opposite : side ] = shift[xy];
			}
		}

		// If our tip position isn't fixed e.g. doesn't adjust with viewport...
		if(this.corner.fixed !== TRUE) {
			// Perform shift/flip adjustments
			shiftflip(horizontal, X, Y, LEFT, RIGHT);
			shiftflip(vertical, Y, X, TOP, BOTTOM);

			// Update and redraw the tip if needed (check cached details of last drawn tip)
			if(newCorner.string() !== cache.corner.string() || cache.cornerTop !== adjust.top || cache.cornerLeft !== adjust.left) {
				this.update(newCorner, FALSE);
			}
		}

		// Setup tip offset properties
		offset = this.calculate(newCorner);

		// Readjust offset object to make it left/top
		if(offset.right !== undefined) { offset.left = -offset.right; }
		if(offset.bottom !== undefined) { offset.top = -offset.bottom; }
		offset.user = this.offset;

		// Perform shift adjustments
		shift.left = horizontal === SHIFT && !!adjust.left;
		if(shift.left) {
			shiftonly(X, LEFT, RIGHT);
		}
		shift.top = vertical === SHIFT && !!adjust.top;
		if(shift.top) {
			shiftonly(Y, TOP, BOTTOM);
		}

		/*
		* If the tip is adjusted in both dimensions, or in a
		* direction that would cause it to be anywhere but the
		* outer border, hide it!
		*/
		this.element.css(css).toggle(
			!(shift.x && shift.y || newCorner.x === CENTER && shift.y || newCorner.y === CENTER && shift.x)
		);

		// Adjust position to accomodate tip dimensions
		pos.left -= offset.left.charAt ? offset.user :
			horizontal !== SHIFT || shift.top || !shift.left && !shift.top ? offset.left + this.border : 0;
		pos.top -= offset.top.charAt ? offset.user :
			vertical !== SHIFT || shift.left || !shift.left && !shift.top ? offset.top + this.border : 0;

		// Cache details
		cache.cornerLeft = adjust.left; cache.cornerTop = adjust.top;
		cache.corner = newCorner.clone();
	},

	destroy: function() {
		// Unbind events
		this.qtip._unbind(this.qtip.tooltip, this._ns);

		// Remove the tip element(s)
		if(this.qtip.elements.tip) {
			this.qtip.elements.tip.find('*')
				.remove().end().remove();
		}
	}
});

TIP = PLUGINS.tip = function(api) {
	return new Tip(api, api.options.style.tip);
};

// Initialize tip on render
TIP.initialize = 'render';

// Setup plugin sanitization options
TIP.sanitize = function(options) {
	if(options.style && 'tip' in options.style) {
		var opts = options.style.tip;
		if(typeof opts !== 'object') { opts = options.style.tip = { corner: opts }; }
		if(!(/string|boolean/i).test(typeof opts.corner)) { opts.corner = TRUE; }
	}
};

// Add new option checks for the plugin
CHECKS.tip = {
	'^position.my|style.tip.(corner|mimic|border)$': function() {
		// Make sure a tip can be drawn
		this.create();

		// Reposition the tooltip
		this.qtip.reposition();
	},
	'^style.tip.(height|width)$': function(obj) {
		// Re-set dimensions and redraw the tip
		this.size = [ obj.width, obj.height ];
		this.update();

		// Reposition the tooltip
		this.qtip.reposition();
	},
	'^content.title|style.(classes|widget)$': function() {
		this.update();
	}
};

// Extend original qTip defaults
$.extend(TRUE, QTIP.defaults, {
	style: {
		tip: {
			corner: TRUE,
			mimic: FALSE,
			width: 6,
			height: 6,
			border: TRUE,
			offset: 0
		}
	}
});
;var MODAL, OVERLAY,
	MODALCLASS = 'qtip-modal',
	MODALSELECTOR = '.'+MODALCLASS;

OVERLAY = function()
{
	var self = this,
		focusableElems = {},
		current,
		prevState,
		elem;

	// Modified code from jQuery UI 1.10.0 source
	// http://code.jquery.com/ui/1.10.0/jquery-ui.js
	function focusable(element) {
		// Use the defined focusable checker when possible
		if($.expr[':'].focusable) { return $.expr[':'].focusable; }

		var isTabIndexNotNaN = !isNaN($.attr(element, 'tabindex')),
			nodeName = element.nodeName && element.nodeName.toLowerCase(),
			map, mapName, img;

		if('area' === nodeName) {
			map = element.parentNode;
			mapName = map.name;
			if(!element.href || !mapName || map.nodeName.toLowerCase() !== 'map') {
				return false;
			}
			img = $('img[usemap=#' + mapName + ']')[0];
			return !!img && img.is(':visible');
		}

		return /input|select|textarea|button|object/.test( nodeName ) ?
			!element.disabled :
			'a' === nodeName ?
				element.href || isTabIndexNotNaN :
				isTabIndexNotNaN
		;
	}

	// Focus inputs using cached focusable elements (see update())
	function focusInputs(blurElems) {
		// Blurring body element in IE causes window.open windows to unfocus!
		if(focusableElems.length < 1 && blurElems.length) { blurElems.not('body').blur(); }

		// Focus the inputs
		else { focusableElems.first().focus(); }
	}

	// Steal focus from elements outside tooltip
	function stealFocus(event) {
		if(!elem.is(':visible')) { return; }

		var target = $(event.target),
			tooltip = current.tooltip,
			container = target.closest(SELECTOR),
			targetOnTop;

		// Determine if input container target is above this
		targetOnTop = container.length < 1 ? FALSE :
			parseInt(container[0].style.zIndex, 10) > parseInt(tooltip[0].style.zIndex, 10);

		// If we're showing a modal, but focus has landed on an input below
		// this modal, divert focus to the first visible input in this modal
		// or if we can't find one... the tooltip itself
		if(!targetOnTop && target.closest(SELECTOR)[0] !== tooltip[0]) {
			focusInputs(target);
		}
	}

	$.extend(self, {
		init: function() {
			// Create document overlay
			elem = self.elem = $('<div />', {
				id: 'qtip-overlay',
				html: '<div></div>',
				mousedown: function() { return FALSE; }
			})
			.hide();

			// Make sure we can't focus anything outside the tooltip
			$(document.body).bind('focusin'+MODALSELECTOR, stealFocus);

			// Apply keyboard "Escape key" close handler
			$(document).bind('keydown'+MODALSELECTOR, function(event) {
				if(current && current.options.show.modal.escape && event.keyCode === 27) {
					current.hide(event);
				}
			});

			// Apply click handler for blur option
			elem.bind('click'+MODALSELECTOR, function(event) {
				if(current && current.options.show.modal.blur) {
					current.hide(event);
				}
			});

			return self;
		},

		update: function(api) {
			// Update current API reference
			current = api;

			// Update focusable elements if enabled
			if(api.options.show.modal.stealfocus !== FALSE) {
				focusableElems = api.tooltip.find('*').filter(function() {
					return focusable(this);
				});
			}
			else { focusableElems = []; }
		},

		toggle: function(api, state, duration) {
			var tooltip = api.tooltip,
				options = api.options.show.modal,
				effect = options.effect,
				type = state ? 'show': 'hide',
				visible = elem.is(':visible'),
				visibleModals = $(MODALSELECTOR).filter(':visible:not(:animated)').not(tooltip);

			// Set active tooltip API reference
			self.update(api);

			// If the modal can steal the focus...
			// Blur the current item and focus anything in the modal we an
			if(state && options.stealfocus !== FALSE) {
				focusInputs( $(':focus') );
			}

			// Toggle backdrop cursor style on show
			elem.toggleClass('blurs', options.blur);

			// Append to body on show
			if(state) {
				elem.appendTo(document.body);
			}

			// Prevent modal from conflicting with show.solo, and don't hide backdrop is other modals are visible
			if(elem.is(':animated') && visible === state && prevState !== FALSE || !state && visibleModals.length) {
				return self;
			}

			// Stop all animations
			elem.stop(TRUE, FALSE);

			// Use custom function if provided
			if($.isFunction(effect)) {
				effect.call(elem, state);
			}

			// If no effect type is supplied, use a simple toggle
			else if(effect === FALSE) {
				elem[ type ]();
			}

			// Use basic fade function
			else {
				elem.fadeTo( parseInt(duration, 10) || 90, state ? 1 : 0, function() {
					if(!state) { elem.hide(); }
				});
			}

			// Reset position and detach from body on hide
			if(!state) {
				elem.queue(function(next) {
					elem.css({ left: '', top: '' });
					if(!$(MODALSELECTOR).length) { elem.detach(); }
					next();
				});
			}

			// Cache the state
			prevState = state;

			// If the tooltip is destroyed, set reference to null
			if(current.destroyed) { current = NULL; }

			return self;
		}
	});

	self.init();
};
OVERLAY = new OVERLAY();

function Modal(api, options) {
	this.options = options;
	this._ns = '-modal';

	this.qtip = api;
	this.init(api);
}

$.extend(Modal.prototype, {
	init: function(qtip) {
		var tooltip = qtip.tooltip;

		// If modal is disabled... return
		if(!this.options.on) { return this; }

		// Set overlay reference
		qtip.elements.overlay = OVERLAY.elem;

		// Add unique attribute so we can grab modal tooltips easily via a SELECTOR, and set z-index
		tooltip.addClass(MODALCLASS).css('z-index', QTIP.modal_zindex + $(MODALSELECTOR).length);

		// Apply our show/hide/focus modal events
		qtip._bind(tooltip, ['tooltipshow', 'tooltiphide'], function(event, api, duration) {
			var oEvent = event.originalEvent;

			// Make sure mouseout doesn't trigger a hide when showing the modal and mousing onto backdrop
			if(event.target === tooltip[0]) {
				if(oEvent && event.type === 'tooltiphide' && /mouse(leave|enter)/.test(oEvent.type) && $(oEvent.relatedTarget).closest(OVERLAY.elem[0]).length) {
					/* eslint-disable no-empty */
					try { event.preventDefault(); }
					catch(e) {}
					/* eslint-enable no-empty */
				}
				else if(!oEvent || oEvent && oEvent.type !== 'tooltipsolo') {
					this.toggle(event, event.type === 'tooltipshow', duration);
				}
			}
		}, this._ns, this);

		// Adjust modal z-index on tooltip focus
		qtip._bind(tooltip, 'tooltipfocus', function(event, api) {
			// If focus was cancelled before it reached us, don't do anything
			if(event.isDefaultPrevented() || event.target !== tooltip[0]) { return; }

			var qtips = $(MODALSELECTOR),

			// Keep the modal's lower than other, regular qtips
			newIndex = QTIP.modal_zindex + qtips.length,
			curIndex = parseInt(tooltip[0].style.zIndex, 10);

			// Set overlay z-index
			OVERLAY.elem[0].style.zIndex = newIndex - 1;

			// Reduce modal z-index's and keep them properly ordered
			qtips.each(function() {
				if(this.style.zIndex > curIndex) {
					this.style.zIndex -= 1;
				}
			});

			// Fire blur event for focused tooltip
			qtips.filter('.' + CLASS_FOCUS).qtip('blur', event.originalEvent);

			// Set the new z-index
			tooltip.addClass(CLASS_FOCUS)[0].style.zIndex = newIndex;

			// Set current
			OVERLAY.update(api);

			// Prevent default handling
			/* eslint-disable no-empty */
			try { event.preventDefault(); }
			catch(e) {}
			/* eslint-enable no-empty */
		}, this._ns, this);

		// Focus any other visible modals when this one hides
		qtip._bind(tooltip, 'tooltiphide', function(event) {
			if(event.target === tooltip[0]) {
				$(MODALSELECTOR).filter(':visible').not(tooltip).last().qtip('focus', event);
			}
		}, this._ns, this);
	},

	toggle: function(event, state, duration) {
		// Make sure default event hasn't been prevented
		if(event && event.isDefaultPrevented()) { return this; }

		// Toggle it
		OVERLAY.toggle(this.qtip, !!state, duration);
	},

	destroy: function() {
		// Remove modal class
		this.qtip.tooltip.removeClass(MODALCLASS);

		// Remove bound events
		this.qtip._unbind(this.qtip.tooltip, this._ns);

		// Delete element reference
		OVERLAY.toggle(this.qtip, FALSE);
		delete this.qtip.elements.overlay;
	}
});


MODAL = PLUGINS.modal = function(api) {
	return new Modal(api, api.options.show.modal);
};

// Setup sanitiztion rules
MODAL.sanitize = function(opts) {
	if(opts.show) {
		if(typeof opts.show.modal !== 'object') { opts.show.modal = { on: !!opts.show.modal }; }
		else if(typeof opts.show.modal.on === 'undefined') { opts.show.modal.on = TRUE; }
	}
};

// Base z-index for all modal tooltips (use qTip core z-index as a base)
/* eslint-disable camelcase */
QTIP.modal_zindex = QTIP.zindex - 200;
/* eslint-enable camelcase */

// Plugin needs to be initialized on render
MODAL.initialize = 'render';

// Setup option set checks
CHECKS.modal = {
	'^show.modal.(on|blur)$': function() {
		// Initialise
		this.destroy();
		this.init();

		// Show the modal if not visible already and tooltip is visible
		this.qtip.elems.overlay.toggle(
			this.qtip.tooltip[0].offsetWidth > 0
		);
	}
};

// Extend original api defaults
$.extend(TRUE, QTIP.defaults, {
	show: {
		modal: {
			on: FALSE,
			effect: TRUE,
			blur: TRUE,
			stealfocus: TRUE,
			escape: TRUE
		}
	}
});
;PLUGINS.viewport = function(api, position, posOptions, targetWidth, targetHeight, elemWidth, elemHeight)
{
	var target = posOptions.target,
		tooltip = api.elements.tooltip,
		my = posOptions.my,
		at = posOptions.at,
		adjust = posOptions.adjust,
		method = adjust.method.split(' '),
		methodX = method[0],
		methodY = method[1] || method[0],
		viewport = posOptions.viewport,
		container = posOptions.container,
		adjusted = { left: 0, top: 0 },
		fixed, newMy, containerOffset, containerStatic,
		viewportWidth, viewportHeight, viewportScroll, viewportOffset;

	// If viewport is not a jQuery element, or it's the window/document, or no adjustment method is used... return
	if(!viewport.jquery || target[0] === window || target[0] === document.body || adjust.method === 'none') {
		return adjusted;
	}

	// Cach container details
	containerOffset = container.offset() || adjusted;
	containerStatic = container.css('position') === 'static';

	// Cache our viewport details
	fixed = tooltip.css('position') === 'fixed';
	viewportWidth = viewport[0] === window ? viewport.width() : viewport.outerWidth(FALSE);
	viewportHeight = viewport[0] === window ? viewport.height() : viewport.outerHeight(FALSE);
	viewportScroll = { left: fixed ? 0 : viewport.scrollLeft(), top: fixed ? 0 : viewport.scrollTop() };
	viewportOffset = viewport.offset() || adjusted;

	// Generic calculation method
	function calculate(side, otherSide, type, adjustment, side1, side2, lengthName, targetLength, elemLength) {
		var initialPos = position[side1],
			mySide = my[side],
			atSide = at[side],
			isShift = type === SHIFT,
			myLength = mySide === side1 ? elemLength : mySide === side2 ? -elemLength : -elemLength / 2,
			atLength = atSide === side1 ? targetLength : atSide === side2 ? -targetLength : -targetLength / 2,
			sideOffset = viewportScroll[side1] + viewportOffset[side1] - (containerStatic ? 0 : containerOffset[side1]),
			overflow1 = sideOffset - initialPos,
			overflow2 = initialPos + elemLength - (lengthName === WIDTH ? viewportWidth : viewportHeight) - sideOffset,
			offset = myLength - (my.precedance === side || mySide === my[otherSide] ? atLength : 0) - (atSide === CENTER ? targetLength / 2 : 0);

		// shift
		if(isShift) {
			offset = (mySide === side1 ? 1 : -1) * myLength;

			// Adjust position but keep it within viewport dimensions
			position[side1] += overflow1 > 0 ? overflow1 : overflow2 > 0 ? -overflow2 : 0;
			position[side1] = Math.max(
				-containerOffset[side1] + viewportOffset[side1],
				initialPos - offset,
				Math.min(
					Math.max(
						-containerOffset[side1] + viewportOffset[side1] + (lengthName === WIDTH ? viewportWidth : viewportHeight),
						initialPos + offset
					),
					position[side1],

					// Make sure we don't adjust complete off the element when using 'center'
					mySide === 'center' ? initialPos - myLength : 1E9
				)
			);

		}

		// flip/flipinvert
		else {
			// Update adjustment amount depending on if using flipinvert or flip
			adjustment *= type === FLIPINVERT ? 2 : 0;

			// Check for overflow on the left/top
			if(overflow1 > 0 && (mySide !== side1 || overflow2 > 0)) {
				position[side1] -= offset + adjustment;
				newMy.invert(side, side1);
			}

			// Check for overflow on the bottom/right
			else if(overflow2 > 0 && (mySide !== side2 || overflow1 > 0)  ) {
				position[side1] -= (mySide === CENTER ? -offset : offset) + adjustment;
				newMy.invert(side, side2);
			}

			// Make sure we haven't made things worse with the adjustment and reset if so
			if(position[side1] < viewportScroll[side1] && -position[side1] > overflow2) {
				position[side1] = initialPos; newMy = my.clone();
			}
		}

		return position[side1] - initialPos;
	}

	// Set newMy if using flip or flipinvert methods
	if(methodX !== 'shift' || methodY !== 'shift') { newMy = my.clone(); }

	// Adjust position based onviewport and adjustment options
	adjusted = {
		left: methodX !== 'none' ? calculate( X, Y, methodX, adjust.x, LEFT, RIGHT, WIDTH, targetWidth, elemWidth ) : 0,
		top: methodY !== 'none' ? calculate( Y, X, methodY, adjust.y, TOP, BOTTOM, HEIGHT, targetHeight, elemHeight ) : 0,
		my: newMy
	};

	return adjusted;
};
;PLUGINS.polys = {
	// POLY area coordinate calculator
	//	Special thanks to Ed Cradock for helping out with this.
	//	Uses a binary search algorithm to find suitable coordinates.
	polygon: function(baseCoords, corner) {
		var result = {
			width: 0, height: 0,
			position: {
				top: 1e10, right: 0,
				bottom: 0, left: 1e10
			},
			adjustable: FALSE
		},
		i = 0, next,
		coords = [],
		compareX = 1, compareY = 1,
		realX = 0, realY = 0,
		newWidth, newHeight;

		// First pass, sanitize coords and determine outer edges
		i = baseCoords.length; 
		while(i--) {
			next = [ parseInt(baseCoords[--i], 10), parseInt(baseCoords[i+1], 10) ];

			if(next[0] > result.position.right){ result.position.right = next[0]; }
			if(next[0] < result.position.left){ result.position.left = next[0]; }
			if(next[1] > result.position.bottom){ result.position.bottom = next[1]; }
			if(next[1] < result.position.top){ result.position.top = next[1]; }

			coords.push(next);
		}

		// Calculate height and width from outer edges
		newWidth = result.width = Math.abs(result.position.right - result.position.left);
		newHeight = result.height = Math.abs(result.position.bottom - result.position.top);

		// If it's the center corner...
		if(corner.abbrev() === 'c') {
			result.position = {
				left: result.position.left + result.width / 2,
				top: result.position.top + result.height / 2
			};
		}
		else {
			// Second pass, use a binary search algorithm to locate most suitable coordinate
			while(newWidth > 0 && newHeight > 0 && compareX > 0 && compareY > 0)
			{
				newWidth = Math.floor(newWidth / 2);
				newHeight = Math.floor(newHeight / 2);

				if(corner.x === LEFT){ compareX = newWidth; }
				else if(corner.x === RIGHT){ compareX = result.width - newWidth; }
				else{ compareX += Math.floor(newWidth / 2); }

				if(corner.y === TOP){ compareY = newHeight; }
				else if(corner.y === BOTTOM){ compareY = result.height - newHeight; }
				else{ compareY += Math.floor(newHeight / 2); }

				i = coords.length;
				while(i--)
				{
					if(coords.length < 2){ break; }

					realX = coords[i][0] - result.position.left;
					realY = coords[i][1] - result.position.top;

					if(
						corner.x === LEFT && realX >= compareX ||
						corner.x === RIGHT && realX <= compareX ||
						corner.x === CENTER && (realX < compareX || realX > result.width - compareX) ||
						corner.y === TOP && realY >= compareY ||
						corner.y === BOTTOM && realY <= compareY ||
						corner.y === CENTER && (realY < compareY || realY > result.height - compareY)) {
						coords.splice(i, 1);
					}
				}
			}
			result.position = { left: coords[0][0], top: coords[0][1] };
		}

		return result;
	},

	rect: function(ax, ay, bx, by) {
		return {
			width: Math.abs(bx - ax),
			height: Math.abs(by - ay),
			position: {
				left: Math.min(ax, bx),
				top: Math.min(ay, by)
			}
		};
	},

	_angles: {
		tc: 3 / 2, tr: 7 / 4, tl: 5 / 4,
		bc: 1 / 2, br: 1 / 4, bl: 3 / 4,
		rc: 2, lc: 1, c: 0
	},
	ellipse: function(cx, cy, rx, ry, corner) {
		var c = PLUGINS.polys._angles[ corner.abbrev() ],
			rxc = c === 0 ? 0 : rx * Math.cos( c * Math.PI ),
			rys = ry * Math.sin( c * Math.PI );

		return {
			width: rx * 2 - Math.abs(rxc),
			height: ry * 2 - Math.abs(rys),
			position: {
				left: cx + rxc,
				top: cy + rys
			},
			adjustable: FALSE
		};
	},
	circle: function(cx, cy, r, corner) {
		return PLUGINS.polys.ellipse(cx, cy, r, r, corner);
	}
};
;PLUGINS.svg = function(api, svg, corner)
{
	var elem = svg[0],
		root = $(elem.ownerSVGElement),
		ownerDocument = elem.ownerDocument,
		strokeWidth2 = (parseInt(svg.css('stroke-width'), 10) || 0) / 2,
		frameOffset, mtx, transformed,
		len, next, i, points,
		result, position;

	// Ascend the parentNode chain until we find an element with getBBox()
	while(!elem.getBBox) { elem = elem.parentNode; }
	if(!elem.getBBox || !elem.parentNode) { return FALSE; }

	// Determine which shape calculation to use
	switch(elem.nodeName) {
		case 'ellipse':
		case 'circle':
			result = PLUGINS.polys.ellipse(
				elem.cx.baseVal.value,
				elem.cy.baseVal.value,
				(elem.rx || elem.r).baseVal.value + strokeWidth2,
				(elem.ry || elem.r).baseVal.value + strokeWidth2,
				corner
			);
		break;

		case 'line':
		case 'polygon':
		case 'polyline':
			// Determine points object (line has none, so mimic using array)
			points = elem.points || [
				{ x: elem.x1.baseVal.value, y: elem.y1.baseVal.value },
				{ x: elem.x2.baseVal.value, y: elem.y2.baseVal.value }
			];

			for(result = [], i = -1, len = points.numberOfItems || points.length; ++i < len;) {
				next = points.getItem ? points.getItem(i) : points[i];
				result.push.apply(result, [next.x, next.y]);
			}

			result = PLUGINS.polys.polygon(result, corner);
		break;

		// Unknown shape or rectangle? Use bounding box
		default:
			result = elem.getBBox();
			result = {
				width: result.width,
				height: result.height,
				position: {
					left: result.x,
					top: result.y
				}
			};
		break;
	}

	// Shortcut assignments
	position = result.position;
	root = root[0];

	// Convert position into a pixel value
	if(root.createSVGPoint) {
		mtx = elem.getScreenCTM();
		points = root.createSVGPoint();

		points.x = position.left;
		points.y = position.top;
		transformed = points.matrixTransform( mtx );
		position.left = transformed.x;
		position.top = transformed.y;
	}

	// Check the element is not in a child document, and if so, adjust for frame elements offset
	if(ownerDocument !== document && api.position.target !== 'mouse') {
		frameOffset = $((ownerDocument.defaultView || ownerDocument.parentWindow).frameElement).offset();
		if(frameOffset) {
			position.left += frameOffset.left;
			position.top += frameOffset.top;
		}
	}

	// Adjust by scroll offset of owner document
	ownerDocument = $(ownerDocument);
	position.left += ownerDocument.scrollLeft();
	position.top += ownerDocument.scrollTop();

	return result;
};
;PLUGINS.imagemap = function(api, area, corner)
{
	if(!area.jquery) { area = $(area); }

	var shape = (area.attr('shape') || 'rect').toLowerCase().replace('poly', 'polygon'),
		image = $('img[usemap="#'+area.parent('map').attr('name')+'"]'),
		coordsString = $.trim(area.attr('coords')),
		coordsArray = coordsString.replace(/,$/, '').split(','),
		imageOffset, coords, i, result, len;

	// If we can't find the image using the map...
	if(!image.length) { return FALSE; }

	// Pass coordinates string if polygon
	if(shape === 'polygon') {
		result = PLUGINS.polys.polygon(coordsArray, corner);
	}

	// Otherwise parse the coordinates and pass them as arguments
	else if(PLUGINS.polys[shape]) {
		for(i = -1, len = coordsArray.length, coords = []; ++i < len;) {
			coords.push( parseInt(coordsArray[i], 10) );
		}

		result = PLUGINS.polys[shape].apply(
			this, coords.concat(corner)
		);
	}

	// If no shapre calculation method was found, return false
	else { return FALSE; }

	// Make sure we account for padding and borders on the image
	imageOffset = image.offset();
	imageOffset.left += Math.ceil((image.outerWidth(FALSE) - image.width()) / 2);
	imageOffset.top += Math.ceil((image.outerHeight(FALSE) - image.height()) / 2);

	// Add image position to offset coordinates
	result.position.left += imageOffset.left;
	result.position.top += imageOffset.top;

	return result;
};
;var IE6,

/*
 * BGIFrame adaption (http://plugins.jquery.com/project/bgiframe)
 * Special thanks to Brandon Aaron
 */
BGIFRAME = '<iframe class="qtip-bgiframe" frameborder="0" tabindex="-1" src="javascript:\'\';" ' +
	' style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=0); ' +
		'-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";"></iframe>';

function Ie6(api) {
	this._ns = 'ie6';

	this.qtip = api;
	this.init(api);
}

$.extend(Ie6.prototype, {
	_scroll : function() {
		var overlay = this.qtip.elements.overlay;
		overlay && (overlay[0].style.top = $(window).scrollTop() + 'px');
	},

	init: function(qtip) {
		var tooltip = qtip.tooltip;

		// Create the BGIFrame element if needed
		if($('select, object').length < 1) {
			this.bgiframe = qtip.elements.bgiframe = $(BGIFRAME).appendTo(tooltip);

			// Update BGIFrame on tooltip move
			qtip._bind(tooltip, 'tooltipmove', this.adjustBGIFrame, this._ns, this);
		}

		// redraw() container for width/height calculations
		this.redrawContainer = $('<div/>', { id: NAMESPACE+'-rcontainer' })
			.appendTo(document.body);

		// Fixup modal plugin if present too
		if( qtip.elements.overlay && qtip.elements.overlay.addClass('qtipmodal-ie6fix') ) {
			qtip._bind(window, ['scroll', 'resize'], this._scroll, this._ns, this);
			qtip._bind(tooltip, ['tooltipshow'], this._scroll, this._ns, this);
		}

		// Set dimensions
		this.redraw();
	},

	adjustBGIFrame: function() {
		var tooltip = this.qtip.tooltip,
			dimensions = {
				height: tooltip.outerHeight(FALSE),
				width: tooltip.outerWidth(FALSE)
			},
			plugin = this.qtip.plugins.tip,
			tip = this.qtip.elements.tip,
			tipAdjust, offset;

		// Adjust border offset
		offset = parseInt(tooltip.css('borderLeftWidth'), 10) || 0;
		offset = { left: -offset, top: -offset };

		// Adjust for tips plugin
		if(plugin && tip) {
			tipAdjust = plugin.corner.precedance === 'x' ? [WIDTH, LEFT] : [HEIGHT, TOP];
			offset[ tipAdjust[1] ] -= tip[ tipAdjust[0] ]();
		}

		// Update bgiframe
		this.bgiframe.css(offset).css(dimensions);
	},

	// Max/min width simulator function
	redraw: function() {
		if(this.qtip.rendered < 1 || this.drawing) { return this; }

		var tooltip = this.qtip.tooltip,
			style = this.qtip.options.style,
			container = this.qtip.options.position.container,
			perc, width, max, min;

		// Set drawing flag
		this.qtip.drawing = 1;

		// If tooltip has a set height/width, just set it... like a boss!
		if(style.height) { tooltip.css(HEIGHT, style.height); }
		if(style.width) { tooltip.css(WIDTH, style.width); }

		// Simulate max/min width if not set width present...
		else {
			// Reset width and add fluid class
			tooltip.css(WIDTH, '').appendTo(this.redrawContainer);

			// Grab our tooltip width (add 1 if odd so we don't get wrapping problems.. huzzah!)
			width = tooltip.width();
			if(width % 2 < 1) { width += 1; }

			// Grab our max/min properties
			max = tooltip.css('maxWidth') || '';
			min = tooltip.css('minWidth') || '';

			// Parse into proper pixel values
			perc = (max + min).indexOf('%') > -1 ? container.width() / 100 : 0;
			max = (max.indexOf('%') > -1 ? perc : 1 * parseInt(max, 10)) || width;
			min = (min.indexOf('%') > -1 ? perc : 1 * parseInt(min, 10)) || 0;

			// Determine new dimension size based on max/min/current values
			width = max + min ? Math.min(Math.max(width, min), max) : width;

			// Set the newly calculated width and remvoe fluid class
			tooltip.css(WIDTH, Math.round(width)).appendTo(container);
		}

		// Set drawing flag
		this.drawing = 0;

		return this;
	},

	destroy: function() {
		// Remove iframe
		this.bgiframe && this.bgiframe.remove();

		// Remove bound events
		this.qtip._unbind([window, this.qtip.tooltip], this._ns);
	}
});

IE6 = PLUGINS.ie6 = function(api) {
	// Proceed only if the browser is IE6
	return BROWSER.ie === 6 ? new Ie6(api) : FALSE;
};

IE6.initialize = 'render';

CHECKS.ie6 = {
	'^content|style$': function() {
		this.redraw();
	}
};
;}));
}( window, document ));


Element.prototype.hasClass = function(className) {
    return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};
/* End tooltip */;
/*!***************************************************
* mark.js v8.11.1
* https://markjs.io/
* Copyright (c) 2014–2018, Julian Kühnel
* Released under the MIT license https://git.io/vwTVl
*****************************************************/

(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) :
	typeof define === 'function' && define.amd ? define(['jquery'], factory) :
	(global.Mark = factory(global.jQuery));
}(this, (function ($) { 'use strict';

$ = $ && $.hasOwnProperty('default') ? $['default'] : $;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};











var classCallCheck = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

var createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();







var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var DOMIterator = function () {
  function DOMIterator(ctx) {
    var iframes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    var exclude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
    var iframesTimeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 5000;
    classCallCheck(this, DOMIterator);

    this.ctx = ctx;
    this.iframes = iframes;
    this.exclude = exclude;
    this.iframesTimeout = iframesTimeout;
  }

  createClass(DOMIterator, [{
    key: 'getContexts',
    value: function getContexts() {
      var ctx = void 0,
          filteredCtx = [];
      if (typeof this.ctx === 'undefined' || !this.ctx) {
        ctx = [];
      } else if (NodeList.prototype.isPrototypeOf(this.ctx)) {
        ctx = Array.prototype.slice.call(this.ctx);
      } else if (Array.isArray(this.ctx)) {
        ctx = this.ctx;
      } else if (typeof this.ctx === 'string') {
        ctx = Array.prototype.slice.call(document.querySelectorAll(this.ctx));
      } else {
        ctx = [this.ctx];
      }
      ctx.forEach(function (ctx) {
        var isDescendant = filteredCtx.filter(function (contexts) {
          return contexts.contains(ctx);
        }).length > 0;
        if (filteredCtx.indexOf(ctx) === -1 && !isDescendant) {
          filteredCtx.push(ctx);
        }
      });
      return filteredCtx;
    }
  }, {
    key: 'getIframeContents',
    value: function getIframeContents(ifr, successFn) {
      var errorFn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};

      var doc = void 0;
      try {
        var ifrWin = ifr.contentWindow;
        doc = ifrWin.document;
        if (!ifrWin || !doc) {
          throw new Error('iframe inaccessible');
        }
      } catch (e) {
        errorFn();
      }
      if (doc) {
        successFn(doc);
      }
    }
  }, {
    key: 'isIframeBlank',
    value: function isIframeBlank(ifr) {
      var bl = 'about:blank',
          src = ifr.getAttribute('src').trim(),
          href = ifr.contentWindow.location.href;
      return href === bl && src !== bl && src;
    }
  }, {
    key: 'observeIframeLoad',
    value: function observeIframeLoad(ifr, successFn, errorFn) {
      var _this = this;

      var called = false,
          tout = null;
      var listener = function listener() {
        if (called) {
          return;
        }
        called = true;
        clearTimeout(tout);
        try {
          if (!_this.isIframeBlank(ifr)) {
            ifr.removeEventListener('load', listener);
            _this.getIframeContents(ifr, successFn, errorFn);
          }
        } catch (e) {
          errorFn();
        }
      };
      ifr.addEventListener('load', listener);
      tout = setTimeout(listener, this.iframesTimeout);
    }
  }, {
    key: 'onIframeReady',
    value: function onIframeReady(ifr, successFn, errorFn) {
      try {
        if (ifr.contentWindow.document.readyState === 'complete') {
          if (this.isIframeBlank(ifr)) {
            this.observeIframeLoad(ifr, successFn, errorFn);
          } else {
            this.getIframeContents(ifr, successFn, errorFn);
          }
        } else {
          this.observeIframeLoad(ifr, successFn, errorFn);
        }
      } catch (e) {
        errorFn();
      }
    }
  }, {
    key: 'waitForIframes',
    value: function waitForIframes(ctx, done) {
      var _this2 = this;

      var eachCalled = 0;
      this.forEachIframe(ctx, function () {
        return true;
      }, function (ifr) {
        eachCalled++;
        _this2.waitForIframes(ifr.querySelector('html'), function () {
          if (! --eachCalled) {
            done();
          }
        });
      }, function (handled) {
        if (!handled) {
          done();
        }
      });
    }
  }, {
    key: 'forEachIframe',
    value: function forEachIframe(ctx, filter, each) {
      var _this3 = this;

      var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {};

      var ifr = ctx.querySelectorAll('iframe'),
          open = ifr.length,
          handled = 0;
      ifr = Array.prototype.slice.call(ifr);
      var checkEnd = function checkEnd() {
        if (--open <= 0) {
          end(handled);
        }
      };
      if (!open) {
        checkEnd();
      }
      ifr.forEach(function (ifr) {
        if (DOMIterator.matches(ifr, _this3.exclude)) {
          checkEnd();
        } else {
          _this3.onIframeReady(ifr, function (con) {
            if (filter(ifr)) {
              handled++;
              each(con);
            }
            checkEnd();
          }, checkEnd);
        }
      });
    }
  }, {
    key: 'createIterator',
    value: function createIterator(ctx, whatToShow, filter) {
      return document.createNodeIterator(ctx, whatToShow, filter, false);
    }
  }, {
    key: 'createInstanceOnIframe',
    value: function createInstanceOnIframe(contents) {
      return new DOMIterator(contents.querySelector('html'), this.iframes);
    }
  }, {
    key: 'compareNodeIframe',
    value: function compareNodeIframe(node, prevNode, ifr) {
      var compCurr = node.compareDocumentPosition(ifr),
          prev = Node.DOCUMENT_POSITION_PRECEDING;
      if (compCurr & prev) {
        if (prevNode !== null) {
          var compPrev = prevNode.compareDocumentPosition(ifr),
              after = Node.DOCUMENT_POSITION_FOLLOWING;
          if (compPrev & after) {
            return true;
          }
        } else {
          return true;
        }
      }
      return false;
    }
  }, {
    key: 'getIteratorNode',
    value: function getIteratorNode(itr) {
      var prevNode = itr.previousNode();
      var node = void 0;
      if (prevNode === null) {
        node = itr.nextNode();
      } else {
        node = itr.nextNode() && itr.nextNode();
      }
      return {
        prevNode: prevNode,
        node: node
      };
    }
  }, {
    key: 'checkIframeFilter',
    value: function checkIframeFilter(node, prevNode, currIfr, ifr) {
      var key = false,
          handled = false;
      ifr.forEach(function (ifrDict, i) {
        if (ifrDict.val === currIfr) {
          key = i;
          handled = ifrDict.handled;
        }
      });
      if (this.compareNodeIframe(node, prevNode, currIfr)) {
        if (key === false && !handled) {
          ifr.push({
            val: currIfr,
            handled: true
          });
        } else if (key !== false && !handled) {
          ifr[key].handled = true;
        }
        return true;
      }
      if (key === false) {
        ifr.push({
          val: currIfr,
          handled: false
        });
      }
      return false;
    }
  }, {
    key: 'handleOpenIframes',
    value: function handleOpenIframes(ifr, whatToShow, eCb, fCb) {
      var _this4 = this;

      ifr.forEach(function (ifrDict) {
        if (!ifrDict.handled) {
          _this4.getIframeContents(ifrDict.val, function (con) {
            _this4.createInstanceOnIframe(con).forEachNode(whatToShow, eCb, fCb);
          });
        }
      });
    }
  }, {
    key: 'iterateThroughNodes',
    value: function iterateThroughNodes(whatToShow, ctx, eachCb, filterCb, doneCb) {
      var _this5 = this;

      var itr = this.createIterator(ctx, whatToShow, filterCb);
      var ifr = [],
          elements = [],
          node = void 0,
          prevNode = void 0,
          retrieveNodes = function retrieveNodes() {
        var _getIteratorNode = _this5.getIteratorNode(itr);

        prevNode = _getIteratorNode.prevNode;
        node = _getIteratorNode.node;

        return node;
      };
      while (retrieveNodes()) {
        if (this.iframes) {
          this.forEachIframe(ctx, function (currIfr) {
            return _this5.checkIframeFilter(node, prevNode, currIfr, ifr);
          }, function (con) {
            _this5.createInstanceOnIframe(con).forEachNode(whatToShow, function (ifrNode) {
              return elements.push(ifrNode);
            }, filterCb);
          });
        }
        elements.push(node);
      }
      elements.forEach(function (node) {
        eachCb(node);
      });
      if (this.iframes) {
        this.handleOpenIframes(ifr, whatToShow, eachCb, filterCb);
      }
      doneCb();
    }
  }, {
    key: 'forEachNode',
    value: function forEachNode(whatToShow, each, filter) {
      var _this6 = this;

      var done = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {};

      var contexts = this.getContexts();
      var open = contexts.length;
      if (!open) {
        done();
      }
      contexts.forEach(function (ctx) {
        var ready = function ready() {
          _this6.iterateThroughNodes(whatToShow, ctx, each, filter, function () {
            if (--open <= 0) {
              done();
            }
          });
        };
        if (_this6.iframes) {
          _this6.waitForIframes(ctx, ready);
        } else {
          ready();
        }
      });
    }
  }], [{
    key: 'matches',
    value: function matches(element, selector) {
      var selectors = typeof selector === 'string' ? [selector] : selector,
          fn = element.matches || element.matchesSelector || element.msMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.webkitMatchesSelector;
      if (fn) {
        var match = false;
        selectors.every(function (sel) {
          if (fn.call(element, sel)) {
            match = true;
            return false;
          }
          return true;
        });
        return match;
      } else {
        return false;
      }
    }
  }]);
  return DOMIterator;
}();

var Mark = function () {
  function Mark(ctx) {
    classCallCheck(this, Mark);

    this.ctx = ctx;
    this.ie = false;
    var ua = window.navigator.userAgent;
    if (ua.indexOf('MSIE') > -1 || ua.indexOf('Trident') > -1) {
      this.ie = true;
    }
  }

  createClass(Mark, [{
    key: 'log',
    value: function log(msg) {
      var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'debug';

      var log = this.opt.log;
      if (!this.opt.debug) {
        return;
      }
      if ((typeof log === 'undefined' ? 'undefined' : _typeof(log)) === 'object' && typeof log[level] === 'function') {
        log[level]('mark.js: ' + msg);
      }
    }
  }, {
    key: 'escapeStr',
    value: function escapeStr(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
    }
  }, {
    key: 'createRegExp',
    value: function createRegExp(str) {
      if (this.opt.wildcards !== 'disabled') {
        str = this.setupWildcardsRegExp(str);
      }
      str = this.escapeStr(str);
      if (Object.keys(this.opt.synonyms).length) {
        str = this.createSynonymsRegExp(str);
      }
      if (this.opt.ignoreJoiners || this.opt.ignorePunctuation.length) {
        str = this.setupIgnoreJoinersRegExp(str);
      }
      if (this.opt.diacritics) {
        str = this.createDiacriticsRegExp(str);
      }
      str = this.createMergedBlanksRegExp(str);
      if (this.opt.ignoreJoiners || this.opt.ignorePunctuation.length) {
        str = this.createJoinersRegExp(str);
      }
      if (this.opt.wildcards !== 'disabled') {
        str = this.createWildcardsRegExp(str);
      }
      str = this.createAccuracyRegExp(str);
      return str;
    }
  }, {
    key: 'createSynonymsRegExp',
    value: function createSynonymsRegExp(str) {
      var syn = this.opt.synonyms,
          sens = this.opt.caseSensitive ? '' : 'i',
          joinerPlaceholder = this.opt.ignoreJoiners || this.opt.ignorePunctuation.length ? '\0' : '';
      for (var index in syn) {
        if (syn.hasOwnProperty(index)) {
          var value = syn[index],
              k1 = this.opt.wildcards !== 'disabled' ? this.setupWildcardsRegExp(index) : this.escapeStr(index),
              k2 = this.opt.wildcards !== 'disabled' ? this.setupWildcardsRegExp(value) : this.escapeStr(value);
          if (k1 !== '' && k2 !== '') {
            str = str.replace(new RegExp('(' + this.escapeStr(k1) + '|' + this.escapeStr(k2) + ')', 'gm' + sens), joinerPlaceholder + ('(' + this.processSynomyms(k1) + '|') + (this.processSynomyms(k2) + ')') + joinerPlaceholder);
          }
        }
      }
      return str;
    }
  }, {
    key: 'processSynomyms',
    value: function processSynomyms(str) {
      if (this.opt.ignoreJoiners || this.opt.ignorePunctuation.length) {
        str = this.setupIgnoreJoinersRegExp(str);
      }
      return str;
    }
  }, {
    key: 'setupWildcardsRegExp',
    value: function setupWildcardsRegExp(str) {
      str = str.replace(/(?:\\)*\?/g, function (val) {
        return val.charAt(0) === '\\' ? '?' : '\x01';
      });
      return str.replace(/(?:\\)*\*/g, function (val) {
        return val.charAt(0) === '\\' ? '*' : '\x02';
      });
    }
  }, {
    key: 'createWildcardsRegExp',
    value: function createWildcardsRegExp(str) {
      var spaces = this.opt.wildcards === 'withSpaces';
      return str.replace(/\u0001/g, spaces ? '[\\S\\s]?' : '\\S?').replace(/\u0002/g, spaces ? '[\\S\\s]*?' : '\\S*');
    }
  }, {
    key: 'setupIgnoreJoinersRegExp',
    value: function setupIgnoreJoinersRegExp(str) {
      return str.replace(/[^(|)\\]/g, function (val, indx, original) {
        var nextChar = original.charAt(indx + 1);
        if (/[(|)\\]/.test(nextChar) || nextChar === '') {
          return val;
        } else {
          return val + '\0';
        }
      });
    }
  }, {
    key: 'createJoinersRegExp',
    value: function createJoinersRegExp(str) {
      var joiner = [];
      var ignorePunctuation = this.opt.ignorePunctuation;
      if (Array.isArray(ignorePunctuation) && ignorePunctuation.length) {
        joiner.push(this.escapeStr(ignorePunctuation.join('')));
      }
      if (this.opt.ignoreJoiners) {
        joiner.push('\\u00ad\\u200b\\u200c\\u200d');
      }
      return joiner.length ? str.split(/\u0000+/).join('[' + joiner.join('') + ']*') : str;
    }
  }, {
    key: 'createDiacriticsRegExp',
    value: function createDiacriticsRegExp(str) {
      var sens = this.opt.caseSensitive ? '' : 'i',
          dct = this.opt.caseSensitive ? ['aàáảãạăằắẳẵặâầấẩẫậäåāą', 'AÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ', 'cçćč', 'CÇĆČ', 'dđď', 'DĐĎ', 'eèéẻẽẹêềếểễệëěēę', 'EÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ', 'iìíỉĩịîïī', 'IÌÍỈĨỊÎÏĪ', 'lł', 'LŁ', 'nñňń', 'NÑŇŃ', 'oòóỏõọôồốổỗộơởỡớờợöøō', 'OÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ', 'rř', 'RŘ', 'sšśșş', 'SŠŚȘŞ', 'tťțţ', 'TŤȚŢ', 'uùúủũụưừứửữựûüůū', 'UÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ', 'yýỳỷỹỵÿ', 'YÝỲỶỸỴŸ', 'zžżź', 'ZŽŻŹ'] : ['aàáảãạăằắẳẵặâầấẩẫậäåāąAÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ', 'cçćčCÇĆČ', 'dđďDĐĎ', 'eèéẻẽẹêềếểễệëěēęEÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ', 'iìíỉĩịîïīIÌÍỈĨỊÎÏĪ', 'lłLŁ', 'nñňńNÑŇŃ', 'oòóỏõọôồốổỗộơởỡớờợöøōOÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ', 'rřRŘ', 'sšśșşSŠŚȘŞ', 'tťțţTŤȚŢ', 'uùúủũụưừứửữựûüůūUÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ', 'yýỳỷỹỵÿYÝỲỶỸỴŸ', 'zžżźZŽŻŹ'];
      var handled = [];
      str.split('').forEach(function (ch) {
        dct.every(function (dct) {
          if (dct.indexOf(ch) !== -1) {
            if (handled.indexOf(dct) > -1) {
              return false;
            }
            str = str.replace(new RegExp('[' + dct + ']', 'gm' + sens), '[' + dct + ']');
            handled.push(dct);
          }
          return true;
        });
      });
      return str;
    }
  }, {
    key: 'createMergedBlanksRegExp',
    value: function createMergedBlanksRegExp(str) {
      return str.replace(/[\s]+/gmi, '[\\s]+');
    }
  }, {
    key: 'createAccuracyRegExp',
    value: function createAccuracyRegExp(str) {
      var _this = this;

      var chars = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~¡¿';
      var acc = this.opt.accuracy,
          val = typeof acc === 'string' ? acc : acc.value,
          ls = typeof acc === 'string' ? [] : acc.limiters,
          lsJoin = '';
      ls.forEach(function (limiter) {
        lsJoin += '|' + _this.escapeStr(limiter);
      });
      switch (val) {
        case 'partially':
        default:
          return '()(' + str + ')';
        case 'complementary':
          lsJoin = '\\s' + (lsJoin ? lsJoin : this.escapeStr(chars));
          return '()([^' + lsJoin + ']*' + str + '[^' + lsJoin + ']*)';
        case 'exactly':
          return '(^|\\s' + lsJoin + ')(' + str + ')(?=$|\\s' + lsJoin + ')';
      }
    }
  }, {
    key: 'getSeparatedKeywords',
    value: function getSeparatedKeywords(sv) {
      var _this2 = this;

      var stack = [];
      sv.forEach(function (kw) {
        if (!_this2.opt.separateWordSearch) {
          if (kw.trim() && stack.indexOf(kw) === -1) {
            stack.push(kw);
          }
        } else {
          kw.split(' ').forEach(function (kwSplitted) {
            if (kwSplitted.trim() && stack.indexOf(kwSplitted) === -1) {
              stack.push(kwSplitted);
            }
          });
        }
      });
      return {
        'keywords': stack.sort(function (a, b) {
          return b.length - a.length;
        }),
        'length': stack.length
      };
    }
  }, {
    key: 'isNumeric',
    value: function isNumeric(value) {
      return Number(parseFloat(value)) == value;
    }
  }, {
    key: 'checkRanges',
    value: function checkRanges(array) {
      var _this3 = this;

      if (!Array.isArray(array) || Object.prototype.toString.call(array[0]) !== '[object Object]') {
        this.log('markRanges() will only accept an array of objects');
        this.opt.noMatch(array);
        return [];
      }
      var stack = [];
      var last = 0;
      array.sort(function (a, b) {
        return a.start - b.start;
      }).forEach(function (item) {
        var _callNoMatchOnInvalid = _this3.callNoMatchOnInvalidRanges(item, last),
            start = _callNoMatchOnInvalid.start,
            end = _callNoMatchOnInvalid.end,
            valid = _callNoMatchOnInvalid.valid;

        if (valid) {
          item.start = start;
          item.length = end - start;
          stack.push(item);
          last = end;
        }
      });
      return stack;
    }
  }, {
    key: 'callNoMatchOnInvalidRanges',
    value: function callNoMatchOnInvalidRanges(range, last) {
      var start = void 0,
          end = void 0,
          valid = false;
      if (range && typeof range.start !== 'undefined') {
        start = parseInt(range.start, 10);
        end = start + parseInt(range.length, 10);
        if (this.isNumeric(range.start) && this.isNumeric(range.length) && end - last > 0 && end - start > 0) {
          valid = true;
        } else {
          this.log('Ignoring invalid or overlapping range: ' + ('' + JSON.stringify(range)));
          this.opt.noMatch(range);
        }
      } else {
        this.log('Ignoring invalid range: ' + JSON.stringify(range));
        this.opt.noMatch(range);
      }
      return {
        start: start,
        end: end,
        valid: valid
      };
    }
  }, {
    key: 'checkWhitespaceRanges',
    value: function checkWhitespaceRanges(range, originalLength, string) {
      var end = void 0,
          valid = true,
          max = string.length,
          offset = originalLength - max,
          start = parseInt(range.start, 10) - offset;
      start = start > max ? max : start;
      end = start + parseInt(range.length, 10);
      if (end > max) {
        end = max;
        this.log('End range automatically set to the max value of ' + max);
      }
      if (start < 0 || end - start < 0 || start > max || end > max) {
        valid = false;
        this.log('Invalid range: ' + JSON.stringify(range));
        this.opt.noMatch(range);
      } else if (string.substring(start, end).replace(/\s+/g, '') === '') {
        valid = false;
        this.log('Skipping whitespace only range: ' + JSON.stringify(range));
        this.opt.noMatch(range);
      }
      return {
        start: start,
        end: end,
        valid: valid
      };
    }
  }, {
    key: 'getTextNodes',
    value: function getTextNodes(cb) {
      var _this4 = this;

      var val = '',
          nodes = [];
      this.iterator.forEachNode(NodeFilter.SHOW_TEXT, function (node) {
        nodes.push({
          start: val.length,
          end: (val += node.textContent).length,
          node: node
        });
      }, function (node) {
        if (_this4.matchesExclude(node.parentNode)) {
          return NodeFilter.FILTER_REJECT;
        } else {
          return NodeFilter.FILTER_ACCEPT;
        }
      }, function () {
        cb({
          value: val,
          nodes: nodes
        });
      });
    }
  }, {
    key: 'matchesExclude',
    value: function matchesExclude(el) {
      return DOMIterator.matches(el, this.opt.exclude.concat(['script', 'style', 'title', 'head', 'html']));
    }
  }, {
    key: 'wrapRangeInTextNode',
    value: function wrapRangeInTextNode(node, start, end) {
      var hEl = !this.opt.element ? 'mark' : this.opt.element,
          startNode = node.splitText(start),
          ret = startNode.splitText(end - start);
      var repl = document.createElement(hEl);
      repl.setAttribute('data-markjs', 'true');
      if (this.opt.className) {
        repl.setAttribute('class', this.opt.className);
      }
      repl.textContent = startNode.textContent;
      startNode.parentNode.replaceChild(repl, startNode);
      return ret;
    }
  }, {
    key: 'wrapRangeInMappedTextNode',
    value: function wrapRangeInMappedTextNode(dict, start, end, filterCb, eachCb) {
      var _this5 = this;

      dict.nodes.every(function (n, i) {
        var sibl = dict.nodes[i + 1];
        if (typeof sibl === 'undefined' || sibl.start > start) {
          if (!filterCb(n.node)) {
            return false;
          }
          var s = start - n.start,
              e = (end > n.end ? n.end : end) - n.start,
              startStr = dict.value.substr(0, n.start),
              endStr = dict.value.substr(e + n.start);
          n.node = _this5.wrapRangeInTextNode(n.node, s, e);
          dict.value = startStr + endStr;
          dict.nodes.forEach(function (k, j) {
            if (j >= i) {
              if (dict.nodes[j].start > 0 && j !== i) {
                dict.nodes[j].start -= e;
              }
              dict.nodes[j].end -= e;
            }
          });
          end -= e;
          eachCb(n.node.previousSibling, n.start);
          if (end > n.end) {
            start = n.end;
          } else {
            return false;
          }
        }
        return true;
      });
    }
  }, {
    key: 'wrapMatches',
    value: function wrapMatches(regex, ignoreGroups, filterCb, eachCb, endCb) {
      var _this6 = this;

      var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1;
      this.getTextNodes(function (dict) {
        dict.nodes.forEach(function (node) {
          node = node.node;
          var match = void 0;
          while ((match = regex.exec(node.textContent)) !== null && match[matchIdx] !== '') {
            if (!filterCb(match[matchIdx], node)) {
              continue;
            }
            var pos = match.index;
            if (matchIdx !== 0) {
              for (var i = 1; i < matchIdx; i++) {
                pos += match[i].length;
              }
            }
            node = _this6.wrapRangeInTextNode(node, pos, pos + match[matchIdx].length);
            eachCb(node.previousSibling);
            regex.lastIndex = 0;
          }
        });
        endCb();
      });
    }
  }, {
    key: 'wrapMatchesAcrossElements',
    value: function wrapMatchesAcrossElements(regex, ignoreGroups, filterCb, eachCb, endCb) {
      var _this7 = this;

      var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1;
      this.getTextNodes(function (dict) {
        var match = void 0;
        while ((match = regex.exec(dict.value)) !== null && match[matchIdx] !== '') {
          var start = match.index;
          if (matchIdx !== 0) {
            for (var i = 1; i < matchIdx; i++) {
              start += match[i].length;
            }
          }
          var end = start + match[matchIdx].length;
          _this7.wrapRangeInMappedTextNode(dict, start, end, function (node) {
            return filterCb(match[matchIdx], node);
          }, function (node, lastIndex) {
            regex.lastIndex = lastIndex;
            eachCb(node);
          });
        }
        endCb();
      });
    }
  }, {
    key: 'wrapRangeFromIndex',
    value: function wrapRangeFromIndex(ranges, filterCb, eachCb, endCb) {
      var _this8 = this;

      this.getTextNodes(function (dict) {
        var originalLength = dict.value.length;
        ranges.forEach(function (range, counter) {
          var _checkWhitespaceRange = _this8.checkWhitespaceRanges(range, originalLength, dict.value),
              start = _checkWhitespaceRange.start,
              end = _checkWhitespaceRange.end,
              valid = _checkWhitespaceRange.valid;

          if (valid) {
            _this8.wrapRangeInMappedTextNode(dict, start, end, function (node) {
              return filterCb(node, range, dict.value.substring(start, end), counter);
            }, function (node) {
              eachCb(node, range);
            });
          }
        });
        endCb();
      });
    }
  }, {
    key: 'unwrapMatches',
    value: function unwrapMatches(node) {
      var parent = node.parentNode;
      var docFrag = document.createDocumentFragment();
      while (node.firstChild) {
        docFrag.appendChild(node.removeChild(node.firstChild));
      }
      parent.replaceChild(docFrag, node);
      if (!this.ie) {
        parent.normalize();
      } else {
        this.normalizeTextNode(parent);
      }
    }
  }, {
    key: 'normalizeTextNode',
    value: function normalizeTextNode(node) {
      if (!node) {
        return;
      }
      if (node.nodeType === 3) {
        while (node.nextSibling && node.nextSibling.nodeType === 3) {
          node.nodeValue += node.nextSibling.nodeValue;
          node.parentNode.removeChild(node.nextSibling);
        }
      } else {
        this.normalizeTextNode(node.firstChild);
      }
      this.normalizeTextNode(node.nextSibling);
    }
  }, {
    key: 'markRegExp',
    value: function markRegExp(regexp, opt) {
      var _this9 = this;

      this.opt = opt;
      this.log('Searching with expression "' + regexp + '"');
      var totalMatches = 0,
          fn = 'wrapMatches';
      var eachCb = function eachCb(element) {
        totalMatches++;
        _this9.opt.each(element);
      };
      if (this.opt.acrossElements) {
        fn = 'wrapMatchesAcrossElements';
      }
      this[fn](regexp, this.opt.ignoreGroups, function (match, node) {
        return _this9.opt.filter(node, match, totalMatches);
      }, eachCb, function () {
        if (totalMatches === 0) {
          _this9.opt.noMatch(regexp);
        }
        _this9.opt.done(totalMatches);
      });
    }
  }, {
    key: 'mark',
    value: function mark(sv, opt) {
      var _this10 = this;

      this.opt = opt;
      var totalMatches = 0,
          fn = 'wrapMatches';

      var _getSeparatedKeywords = this.getSeparatedKeywords(typeof sv === 'string' ? [sv] : sv),
          kwArr = _getSeparatedKeywords.keywords,
          kwArrLen = _getSeparatedKeywords.length,
          sens = this.opt.caseSensitive ? '' : 'i',
          handler = function handler(kw) {
        var regex = new RegExp(_this10.createRegExp(kw), 'gm' + sens),
            matches = 0;
        _this10.log('Searching with expression "' + regex + '"');
        _this10[fn](regex, 1, function (term, node) {
          return _this10.opt.filter(node, kw, totalMatches, matches);
        }, function (element) {
          matches++;
          totalMatches++;
          _this10.opt.each(element);
        }, function () {
          if (matches === 0) {
            _this10.opt.noMatch(kw);
          }
          if (kwArr[kwArrLen - 1] === kw) {
            _this10.opt.done(totalMatches);
          } else {
            handler(kwArr[kwArr.indexOf(kw) + 1]);
          }
        });
      };

      if (this.opt.acrossElements) {
        fn = 'wrapMatchesAcrossElements';
      }
      if (kwArrLen === 0) {
        this.opt.done(totalMatches);
      } else {
        handler(kwArr[0]);
      }
    }
  }, {
    key: 'markRanges',
    value: function markRanges(rawRanges, opt) {
      var _this11 = this;

      this.opt = opt;
      var totalMatches = 0,
          ranges = this.checkRanges(rawRanges);
      if (ranges && ranges.length) {
        this.log('Starting to mark with the following ranges: ' + JSON.stringify(ranges));
        this.wrapRangeFromIndex(ranges, function (node, range, match, counter) {
          return _this11.opt.filter(node, range, match, counter);
        }, function (element, range) {
          totalMatches++;
          _this11.opt.each(element, range);
        }, function () {
          _this11.opt.done(totalMatches);
        });
      } else {
        this.opt.done(totalMatches);
      }
    }
  }, {
    key: 'unmark',
    value: function unmark(opt) {
      var _this12 = this;

      this.opt = opt;
      var sel = this.opt.element ? this.opt.element : '*';
      sel += '[data-markjs]';
      if (this.opt.className) {
        sel += '.' + this.opt.className;
      }
      this.log('Removal selector "' + sel + '"');
      this.iterator.forEachNode(NodeFilter.SHOW_ELEMENT, function (node) {
        _this12.unwrapMatches(node);
      }, function (node) {
        var matchesSel = DOMIterator.matches(node, sel),
            matchesExclude = _this12.matchesExclude(node);
        if (!matchesSel || matchesExclude) {
          return NodeFilter.FILTER_REJECT;
        } else {
          return NodeFilter.FILTER_ACCEPT;
        }
      }, this.opt.done);
    }
  }, {
    key: 'opt',
    set: function set$$1(val) {
      this._opt = _extends({}, {
        'element': '',
        'className': '',
        'exclude': [],
        'iframes': false,
        'iframesTimeout': 5000,
        'separateWordSearch': true,
        'diacritics': true,
        'synonyms': {},
        'accuracy': 'partially',
        'acrossElements': false,
        'caseSensitive': false,
        'ignoreJoiners': false,
        'ignoreGroups': 0,
        'ignorePunctuation': [],
        'wildcards': 'disabled',
        'each': function each() {},
        'noMatch': function noMatch() {},
        'filter': function filter() {
          return true;
        },
        'done': function done() {},
        'debug': false,
        'log': window.console
      }, val);
    },
    get: function get$$1() {
      return this._opt;
    }
  }, {
    key: 'iterator',
    get: function get$$1() {
      return new DOMIterator(this.ctx, this.opt.iframes, this.opt.exclude, this.opt.iframesTimeout);
    }
  }]);
  return Mark;
}();

$.fn.mark = function (sv, opt) {
  new Mark(this.get()).mark(sv, opt);
  return this;
};
$.fn.markRegExp = function (regexp, opt) {
  new Mark(this.get()).markRegExp(regexp, opt);
  return this;
};
$.fn.markRanges = function (ranges, opt) {
  new Mark(this.get()).markRanges(ranges, opt);
  return this;
};
$.fn.unmark = function (opt) {
  new Mark(this.get()).unmark(opt);
  return this;
};

return $;

})));
;
var appModule = (function () {
    var configs = {
        googleAuthUrl: 'https://accounts.google.com/o/oauth2/auth?',
        googleValidUrl: 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=',
        googleUserInfoUrl: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=',
        googleScope: 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email',
        facebookAppId: '117134849575084',
        googleClientId: '430060160652-v6547hpru6paae2boas196b4j7l1qcnr.apps.googleusercontent.com',
        redirectUrl: window.location.href.indexOf('https://luatvietnam.vn') > -1 ? 'https://luatvietnam.vn/' : 'https://luat.icsoft.vn/',
        changeTimer: false
    };
    ajaxEvents =
    {
        OnBegin: function () {
            showLoading();
        },
        OnComplete: function (element) {
            hideLoading();
        },
        LoginOnSuccess: function (response, status, xhr) {
            if (response != null) {
                if (response.Completed) {
                    $('#_login').removeClass('target-expanded').addClass('target-hidden');
                    if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                        //Kích hoạt tk thành công => chuyển hướng về homepage
                        if (response.ReturnUrl.indexOf('NewUserActive') !== -1) {
                            window.location.assign('/');
                        } else if (response.returnUrl == '/giao-dien-ca-nhan.html') {
                            setTimeout(function () {
                                window.location.href = response.ReturnUrl;
                            },
                                100);
                        } else if (response.returnUrl == '/user/dang-ky-linh-vuc-quan-tam.html') {
                            setTimeout(function () {
                                window.location.href = response.ReturnUrl;
                            },
                                100);
                        }
                        else if (response.ReturnUrl == '/user/dang-nhap-tai-khoan.html') {
                            setTimeout(function () {
                                window.location.href = '/';
                            },
                                100);
                        } else if (response.ReturnUrl == '/pldn/dang-nhap-tai-khoan.html') {
                            setTimeout(function () {
                                window.location.href = '/phap-ly-doanh-nghiep.html';
                            },
                                100);
                        }
                        else {
                            setTimeout(function () {
                                window.location.href = response.ReturnUrl;
                            },
                                100);
                        }
                    } else window.location.href = '/';
                } else {
                    if (response.Message != null && response.Message.length > 0) {
                        var username = '';
                        if (response.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                            response.Message = response.Message.replace(/"/g, "'");
                            var str = response.Message.match(/'(.*?)'/g);
                            if (str != null) username = str[1];
                        }
                        var msg = username.length > 0
                            ? 'Tài khoản: <b>' +
                            username +
                            '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                            : response.Message;
                        //msg += '<p>Để được hỗ trợ về đăng nhập tài khoản, Quý khách vui lòng liên hệ với LuatVietnam:</p>';
                        //msg += '<p>Hotline: <a href="tel:0938361919" title="Hotline: 0938361919" style="color: #ed1d35">0938361919</a></p>';
                        //msg += '<p>Email: <a href="mailto:cskh@luatvietnam.vn" title="Email: cskh@luatvietnam.vn">cskh@luatvietnam.vn</a></p>';
                        //msg += '<p><a href="javascript:void(0)" rel="nofollow" id="chat-online" title="Chat trực tuyến" style="color: #ed1d35">Chat trực tuyến</a></p>';

                        if (msg.indexOf('hiện đang đăng nhập') > -1) {
                            showMessageLogin({
                                buttons: [
                                    {
                                        Name: 'Tiếp tục',
                                        ClassName: 'btn-law-ok',
                                        ClickEvent: function () {
                                            $(`#_message`).remove();
                                            $('#login').find('form').submit();
                                        }
                                    }],
                                messages: [msg]
                            });
                        }
                        else {
                            showMessageLogin({
                                messages: [msg]
                            });
                        }
                    }
                }
            }
            hideLoading();
        },
        OnSuccess: function (response, status, xhr) {
            if (response != null) {
                if (response.Message != null) {
                    var username = '', msg = response.Message;
                    if (response.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                        response.Message = response.Message.replace(/"/g, "'");
                        var str = response.Message.match(/'(.*?)'/g);
                        if (str != null) username = str[1];

                        msg = username.length > 0
                            ? 'Tài khoản: <b>' +
                            username +
                            '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                            : response.Message;
                        msg += '<p>Để được hỗ trợ về đăng nhập tài khoản, Quý khách vui lòng liên hệ với LuatVietnam:</p>';
                        msg += '<p>Hotline: <a href="tel:0938361919" title="Hotline: 0938361919" style="color: #ed1d35">0938361919</a></p>';
                        msg += '<p>Email: <a href="mailto:cskh@luatvietnam.vn" title="Email: cskh@luatvietnam.vn">cskh@luatvietnam.vn</a></p>';
                    }

                    showMessage({
                        autoClose: true,
                        buttons: [{
                            Name: 'Đóng',
                            ClassName: 'btn-law',
                            ClickEvent: function () {

                                if ($(this).attr('data-clicked')) {
                                    return
                                }

                                if (!response.Completed) {
                                    return;
                                }

                                if (response.Callback != null && response.Callback.length > 0) {
                                    eval(b64DecodeUnicode(response.Callback));
                                }

                                $(this).attr('data-clicked', true)

                                if (response.Completed && response.ReturnUrl != null) {
                                    window.location.href = response.ReturnUrl;
                                    return;
                                }
                            }
                        }],
                        messages: [msg]
                    });
                } else if (response.Completed) {
                    if (response.ReturnUrl != null) {
                        window.location.href = response.ReturnUrl;
                        return;
                    }

                    if (response.Callback != null && response.Callback.length > 0) {
                        eval(b64DecodeUnicode(response.Callback));
                    }
                } else {
                    if (response.ReturnUrl != null) {
                        window.location.href = response.ReturnUrl;
                        return;
                    }
                }
            }
            hideLoading();
        },
        OnFailed: function () {
            hideLoading();
            showMessage({
                messages: ['Quý khách vui lòng thử lại sau.']
            });
        }
    };
    function ajaxError() {
        $(document).ajaxError(function (e, xhr) {
            if (xhr.status === 403) {
                var response = $.parseJSON(xhr.responseText);
                if (response.Message != null && (response.Message == 'ptvb' || response.Message == 'ChiDanThayDoi' || response.Message.match('^Rất tiếc. Quý khách không xem được nội dung này.'))) {
                    return;
                }
                $('#ReturnUrl').val(window.location.href.replace(window.location.origin, ''));
                $('.tabs-login-item, .tabs-login-content').removeClass('active');
                $('.tabs-login-item[data-tab="login"]').addClass('active');
                $('#login').addClass('active');
                $('#_login').addClass('target-expanded').css('display', '');
            } //else {
            //showMessage({ messages : ['Quý khách vui lòng thử lại sau.'] })
            //}
            hideLoading();
        });
    }
    function initLazyload() {
        if (jQuery().lazyload) { $('.lazyload').lazyload(); }
    }
    function init() {
        $('.opt-dropdown.dropdown-checkbox').each(function () {
            setupFilterCheckboxSearchForm(this);
        });
    }
    function initEvents() {
        $('.btn-menu-mega').on('click', function () {
            $('.menu-mega').toggleClass('open-menu')
            $('.btn-menu-mega').toggleClass('active')
        })
        $('.close-menu-mega').on('click', function () {
            $('.menu-mega').removeClass('open-menu')
            $('.btn-menu-mega').removeClass('active')
        })
        $(document).on('keyup change', '.input-menulvvb', function () {
            var self = $(this), searchTerm = self.val().trim();

            function normalizeString(str) {
                return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
            }

            function resetToInitialState() {
                const parent = self.closest('.col-mega'),
                    menuItems = parent.find('.ul-menu-list li');
                var isExpanded = parent.find('.btn-more-menu').text() === 'Thu gọn';
                menuItems.each(function () {
                    var li = $(this);
                    li.removeClass('highlight target-hidden');

                    if (!li.data('available') && !isExpanded) {
                        li.addClass('target-hidden');
                    }
                });
            }

            function highlightText(element, keyword) {
                var text = element.text();
                var normalizedText = normalizeString(text);
                var normalizedKeyword = normalizeString(keyword);

                if (normalizedKeyword.length > 0) {
                    var keywordIndex = normalizedText.indexOf(normalizedKeyword);
                    if (keywordIndex !== -1) {
                        var originalKeyword = text.substr(keywordIndex, keyword.length);
                        var highlightedText = text.replace(new RegExp(originalKeyword, 'gi'), function (match) {
                            return '<span class="highlight">' + match + '</span>';
                        });
                        element.html(highlightedText);
                    } else {
                        element.html(text);
                    }
                } else {
                    element.html(text);
                }
            }

            function highlightAndShowKeyword(keyword) {
                var keywordExists = keyword.length > 0;

                $('.ul-menu-list li').each(function () {
                    var li = $(this);
                    var link = li.find('a');

                    if (link.length) {
                        link.each(function () {
                            highlightText($(this), keyword);
                        });
                    } else {
                        highlightText(li, keyword);
                    }

                    if (keywordExists && li.find('.highlight').length === 0) {
                        li.addClass('target-hidden');
                    } else {
                        li.removeClass('target-hidden');
                    }
                });

                if (!keywordExists) {
                    resetToInitialState();
                }
            }

            highlightAndShowKeyword(searchTerm);
        });

        $(document).on('click', '.btn-more-menu', function (event) {
            event.preventDefault();
            const self = $(this), parent = self.closest('.col-mega'),
                menuItems = parent.find('.ul-mega'),
                hiddenItems = menuItems.find('li.target-hidden'),
                availableItems = menuItems.find('li[data-available="1"]'),
                initialItems = availableItems.length

            if (hiddenItems.length) {
                hiddenItems.removeClass('target-hidden')
                self.text('Thu gọn')
            } else {
                menuItems.find('li').addClass('target-hidden')

                availableItems.slice(0, initialItems).removeClass('target-hidden')

                if (availableItems.length < initialItems) {
                    menuItems.find('li:not([data-available])')
                        .slice(0, initialItems - availableItems.length)
                        .removeClass('target-hidden')
                }

                self.text('Xem thêm')
            }
        })
        $(document).on('keyup', 'input', function (event) {
            if (event.which === 13) {
                event.preventDefault();
                var form = $(this).closest('form');
                if (form && form.find('.btn-submit').first().length > 0) {
                    form.submit();
                }
            }
        })
        $(document).off('click', '.btn-submit').on('click', '.btn-submit', function () {
            $(this).closest('form').submit();
        })
        $(document).on('submit', 'form', function (e) {
            var self = $(this), action = self.data('action'), reCaptchaToken = self.find('input[type="hidden"][name$="ReCaptchaToken"]').first();
            if (reCaptchaToken.length > 0 && typeof action !== 'undefined') {
                getRecaptchaToken(self, action);
            }
        });
        $(document).on('click', '.btn-tips-thong-bao', function (event) {
            event.preventDefault();
            var self = $(this), url = self.data('url') || '', id = self.data('id') || 0
            if (url.trim().length > 0) {
                if (id > 0) {
                    fetchData(
                        {
                            type: 'POST',
                            url: '/ajax/CustomerNotifyUpdateComplete',
                            data: { id: id }
                        })
                        .then((response) => {
                            if (response.Completed) {
                                window.location.href = url;
                                return;
                            }

                            if (response.Message != null && response.Message.length > 0) {
                                appModule.showMessage({ messages: [response.Message] });
                            }
                        })
                        .catch((error) => {
                            console.error(error)
                        })
                }
            }
        })
        $('form#_register, form#RegisterFormTarget').on('submit', function (e) {
            e.preventDefault();
            return checkboxTermsOfUseRequired();
        });
        $(document).on('change', '.onchange-submit', function () {
            $(this).closest('form').submit();
        })
        $(document).on('change', '.onchange-redirect', function () {
            var url = $(this).find(':selected').attr('data-url');
            if (typeof url != 'undefined' && url.length > 0)
                window.location.href = url;
        })
        $(document).on('click', '.scroll-to', function () {
            var self = $(this), id = self.data('id');
            if (typeof id != 'undefined') {
                $('html, body').animate({
                    scrollTop: parseInt($(`#${id}`).offset().top)
                }, 500);
            }
        })
        $(document).on('click', '.lawsVnLogin', function () {
            $('.popup-bg').removeClass('target-expanded').addClass('target-hidden');
        })
        $(document).on('change keyup paste', 'input[name="CustomerName"]', function () {
            var self = $(this), customerName = self.val().trim();
            checkCustomerLoginByParent(self, customerName);
        })
        if ($('#category-scroll').length) {
            var self = $('#category-scroll'), tab = self.find('.tab-page').first(), scrollElement = self.find('.tab-page .tab-ban-tin.active').first();
            if (tab.length && scrollElement.length) {
                tab.animate({ scrollLeft: scrollElement.offset().left -= 100 });
            }
        }
        $('.category-more-icon').click(function () {
            $("#category-scroll").animate({ scrollLeft: "+=100px" });
        });
        $('.sidebar-toggle').off('click').on('click', function () {
            var overlay = $('.sidebar-overlay');
            var sidebar = $('#sidebardefault');
            sidebar.toggleClass('open');
            if ((sidebar.hasClass('sidebar-fixed-left') || sidebar.hasClass('sidebar-fixed-right')) && sidebar.hasClass('open')) {
                overlay.addClass('active');
            } else {
                overlay.removeClass('active');
            }
        })
        $('.sidebar-overlay').off('click').on('click', function () {
            $(this).removeClass('active');
            $('#sidebardefault').removeClass('open');
        })
        if ($('#customer-messages-container').length > 0 && $('#customer-messages-right').length > 0) {
            var customerMessages = $('#customer-messages-right').html();
            $('#customer-messages-right').remove();
            $('#customer-messages-container').html(customerMessages)
        }
        const isHover = e => e.parentElement.querySelector(':hover') === e;
        $('.btn-thongbao').click(function () {
            if ($('.w3-thongbao').hasClass('showme')) {
                $('.w3-thongbao').removeClass('showme');
            }
            else {
                $('.w3-thongbao').addClass('showme');
            }
        });

        $(document).on('click', '.w3-close-thongbao', function () {
            $('.w3-thongbao').removeClass('showme');
        })
        $(document).on('click', '.tabs-login-item', function () {
            $('.tabs-login-item, .tabs-login-content').removeClass('active');
            $(this).addClass('active');
            $(`#${$(this).data('tab')}`).addClass('active');
            $(`.tabs-login-content[data-content="${$(this).data('content')}"]`).addClass('active');
        })
        $(document).on('click', '.view-more2', function () {
            $('.menu-nav-sub2').addClass('show_hight');
        })
        $(document).on('click', '.close-more2', function () {
            $('.menu-nav-sub2').removeClass('show_hight');
        })
        $(document).on('click', '.tab-nav-doc-item', function () {
            $('.tab-nav-doc-item', $(this).parent('.tab-nav-doc')).removeClass('active');
            $(this).addClass('active');
        })
        $(document).on('click', '.tabvb-item', function () {
            $('.tabvb-item', $(this).parent('.tabvb-left')).removeClass('active');
            $(this).addClass('active');
        })
        $(document).on('change', '.orderby-filter', function () {
            var self = $(this), parent = self.closest('.tabvb'),
                currentLink = parent.find('.tabvb-item.active').first();

            if (currentLink.length > 0) {
                var urlRequest = currentLink.data('url');

                if (typeof urlRequest != 'undefined') {

                    urlRequest = updateQueryStringParameter(urlRequest, 'FilterBy', self.val());

                    currentLink.attr('data-url', urlRequest);

                    currentLink.trigger('click');
                }
            }
        })
        $(document).on('click', '[data-ajax="1"]', function () {
            var self = $(this), urlRequest = self.attr('data-url'), elementUpdate = self.data('id'),
                dataType = self.data('datatype') || 'html',
                type = self.data('type') || 'get', parent = self.closest('.tabvb');

            if (parent.length > 0) {

                var orderBySelect = parent.find('.orderby-filter').first();

                if (orderBySelect.length > 0) {

                    urlRequest = updateQueryStringParameter(urlRequest, 'FilterBy', orderBySelect.find('option:selected').val());

                    self.attr('data-url', urlRequest);
                }
            }


            if (typeof urlRequest != 'undefined' && typeof elementUpdate != 'undefined') {
                fetchData(
                    {
                        url: urlRequest,
                        dataType: dataType,
                        type: type
                    })
                    .then((response) => {
                        if (response != null && response.length > 0) {
                            $(`#${elementUpdate}`).html(response);
                        }
                        if (response.Callback != null && response.Callback.length > 0) {
                            eval(atob(response.Callback));
                        }
                    })
                    .catch((error) => {
                        console.error(error)
                    })
            }
        })
        $(document).on('click', '.btn-user-login', function () {
            $('.content-dropdown-login').addClass('show_dropdown');
        })
        $(document).on('click', '.close-fix', function () {
            $('.content-dropdown-login').removeClass('show_dropdown');
        })
        $(document).on('click', '.ic-show-pass', function (e) {
            var parent = $(this).closest('.form-group'), password = parent.find('input').first();
            $(this).remove();
            parent.append('<i class="iconlvn-eye-close ic-hidden-pass"></i>');
            password.prop("type", "text");
        });
        $(document).on('click', '.ic-hidden-pass', function (e) {
            var parent = $(this).closest('.form-group'), password = parent.find('input').first();
            $(this).remove();
            parent.append('<i class="iconlvn-eye-open ic-show-pass"></i>');
            password.prop("type", "password");
        });
        $(document).on('click', '.logout', function () {
            showMessage({
                buttons: [{
                    Name: 'Đóng',
                    ClassName: 'btn-law',
                    ClickEvent: function () { }
                },
                {
                    Name: 'Đồng ý',
                    ClassName: 'btn-law-ok',
                    ClickEvent: function () {
                        //lawsVn.logs.webpagelogs('pageview', '/user/dang-xuat-tai-khoan.html', pageTitle, source);
                        window.location.href = '/user/dang-xuat-tai-khoan.html';
                    }
                }],
                messages: ['Quý khách muốn đăng xuất khỏi hệ thống?']
            });
        })
        $(document).on('click', '.google-login', function (e) {
            e.preventDefault();
            var url = configs.googleAuthUrl + 'scope=' + configs.googleScope + '&client_id=' + configs.googleClientId + '&redirect_uri=' + configs.redirectUrl + '&response_type=token';
            var googlePopup = window.open(url, 'Đăng nhập tài khoản Google', 'width=800, height=600');

            var time = window.setInterval(function () {
                try {
                    if (googlePopup.document.URL.indexOf(configs.redirectUrl) !== -1) {
                        window.clearInterval(time);
                        var accessToken = getGoogleResponse(googlePopup.document.URL, 'access_token');
                        googlePopup.close();
                        requestGoogleAccountInfo(accessToken);
                    }
                }
                catch (e) {
                    console.log(e);
                }
            }, 500);
        });
        $(document).on('click', '.facebook-login', function (e) {
            e.preventDefault();
            facebookLogin();
        });
        $(document).on('click', '.save-doc', function () {
            var docId = $(this).data('id');
            if (typeof docId != 'undefined') {
                fetchData(
                    {
                        url: '/ajax/saveDocument',
                        dataType: 'json',
                        type: 'get',
                        data:
                        {
                            docId: docId
                        }
                    })
                    .then((resp) => {
                        if (resp.Message != null && resp.Message.length > 0) {
                            showMessage({
                                messages: [resp.Message]
                            });
                        }
                    })
                    .catch((error) => {
                        console.error(error)
                    })
            }
        });
        $(document).on('keyup change',
            '#text-search-field',
            function () {
                var searchTerm = $(this).val();
                $('#search-fields').removeHighlight();
                if (searchTerm) {
                    $('#search-fields').highlight(searchTerm);
                }
            });

        /*begin PartialHomeSearchBox*/
        $(document).on('click', '.search-clear', function (event) {
            const self = $(event.target), parent = self.closest('.search-suggest'),
                searchBox = parent.find('.search-box').first()
            searchContent = parent.find('.search-content').first();
            searchContent.empty();
            searchBox.removeClass('open-search');
            if ($('.search-field').length) {
                $('.search-field').val('');
            }
        })
        $(document).on('keyup', '.input-search-all-suggest', debounce((e) => {
            const self = $(e.target),
                inputValue = self.val().trim(), parent = self.closest('.search-suggest'),
                activeTab = $('.search-tab a.active', parent).text();
            iconContainer = self.next('.search-clear'),
                searchBox = parent.find('.search-box').first()
            searchContent = parent.find('.search-content').first()

            let urlRequest = '/van-ban/docs/search-suggest.html'
            if (activeTab == 'Tin tức') {
                urlRequest = '/tin-bai/search-suggest.html'
            } else if (activeTab == 'Hỏi đáp') {
                urlRequest = '/van-ban/faqs/search-suggest.html'
            } else if (activeTab == 'Bản án') {
                urlRequest = '/ban-an/search-suggest.html'
            }

            var code = (e.keyCode || e.which)

            if (inputValue.length == 0) {
                searchContent.empty()
                searchBox.removeClass('open-search')
                return
            }

            if (code == 37 || code == 38 || code == 39 || code == 40 || code == 13) {
                return
            }

            fetchData({
                url: urlRequest,
                type: 'GET',
                dataType: 'json',
                data:
                {
                    keywords: inputValue
                },
                beforeSend: () => {
                    iconContainer.html('<i class="loader"></i>')
                },
                always: () => {
                    iconContainer.html('<i class="iconlvn-remove"></i>')
                }
            }).then(response => {

                searchContent.empty()

                let docName = '', docNameClear = '', docSuggests = []


                if (response?.data?.docSearchSuggestsList && response.data.docSearchSuggestsList.length > 0) {

                    for (var index = 0; index < response.data.docSearchSuggestsList.length && index < 3; index++) {
                        docSuggests.push(response.data.docSearchSuggestsList[index].docId);
                        docName = response.data.docSearchSuggestsList[index].h1Tag;
                        if (docName == null || docName == '') {
                            docName = response.data.docSearchSuggestsList[index].docName;
                        }
                        docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');


                        searchContent.append(`<div>
                                <a href="${response.data.docSearchSuggestsList[index].docUrl}" target="_blank" title="${docNameClear}">${docName}</a>
                            </div>`)
                    }
                }
                if (response?.data?.docSearchsList && response.data.docSearchsList.length > 0) {

                    for (var index = 0; index < response.data.docSearchsList.length; index++) {

                        if (!docSuggests.includes(response.data.docSearchsList[index].docId)) {
                            docName = response.data.docSearchsList[index].h1Tag;
                            if (docName == null || docName == '') {
                                docName = response.data.docSearchsList[index].docName;
                            }
                            docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');

                            searchContent.append(`<div>
                                <a href="${response.data.docSearchsList[index].docUrl}" target="_blank" title="${docNameClear}">${docName}</a>
                            </div>`)

                        }
                    }
                }
                if (response?.data?.lawJudgSearchsList && response.data.lawJudgSearchsList.length > 0) {

                    for (var index = 0; index < response.data.lawJudgSearchsList.length; index++) {

                        docSuggests.push(response.data.lawJudgSearchsList[index].docId)

                        searchContent.append(`<div class="suggest">
                                <a href="https://luatvietnam.vn${response.data.lawJudgSearchsList[index].docUrl}" target="_blank">${response.data.lawJudgSearchsList[index].title}</a>
                            </div>`)
                    }
                }

                if (response.Data && response.Data.length > 0) {
                    let dataUrl = '', title = ''
                    for (var index = 0; index < response.Data.length; index++) {
                        if (response.Data[index].DocUrl) {
                            dataUrl = response.Data[index].DocUrl
                        } else {
                            dataUrl = response.Data[index].ArticleUrl
                        }
                        title = response.Data[index].Title
                        if (activeTab == 'Hỏi đáp') {
                            title = highlightKeywords(title, inputValue)
                        }
                        searchContent.append(`<div>
                                <a href="${dataUrl}" target="_blank">${title}</a>
                            </div>`)
                    }
                }
                if (response.data && response.data.length > 0) {
                    let dataUrl = '', title = ''
                    for (var index = 0; index < response.data.length; index++) {
                        if (response.data[index].docUrl) {
                            dataUrl = response.data[index].docUrl
                        } else {
                            dataUrl = response.data[index].articleUrl
                        }
                        title = response.data[index].title
                        if (activeTab == 'Hỏi đáp') {
                            title = highlightKeywords(title, inputValue)
                        }
                        searchContent.append(`<div>
                                <a href="${dataUrl}" target="_blank">${title}</a>
                            </div>`)
                    }
                }

                if (searchContent.children().length == 0) {
                    searchContent.html('<div>Không tìm thấy kết quả phù hợp.</div>')
                }

                searchBox.addClass('open-search')

            }).catch((error) => {
                console.log(error)
            })

        }, 350))

        $(document).on('keypress', '.input-search-all-suggest', function (e) {
            var code = (e.keyCode || e.which)
            if (code == 13) {
                $(this).closest('form').submit();
            }
        });

        $(document).on('click', '#suggested-doc-search', function (event) {
            const self = $(event.target), urlRequest = '/van-ban/docs/search-suggest.html',
                parent = self.closest('.search-suggest'),
                form = parent.find('form').first(),
                inputValue = parent.find('.input-search-all-suggest').first().val().trim(),
                searchBox = parent.find('.search-box').first()
            searchContent = parent.find('.search-content').first()

            if (self.hasClass('active')) {
                return
            }
            $('.search-tab a', parent).removeClass('active')
            self.addClass('active')
            form.attr('action', '/van-ban/tim-van-ban.html')
            fetchData({
                url: urlRequest,
                type: 'GET',
                dataType: 'json',
                data: { keywords: inputValue },
                beforeSend: () => {
                    self.html('<i class="loader"></i>')
                },
                always: () => {
                    self.text('Văn bản')
                }
            }).then(response => {

                searchContent.empty()

                let docName = '', docNameClear = '', docSuggests = []

                if (response?.data?.docSearchSuggestsList && response.data.docSearchSuggestsList.length > 0) {

                    for (var index = 0; index < response.data.docSearchSuggestsList.length && index < 3; index++) {
                        docSuggests.push(response.data.docSearchSuggestsList[index].docId);
                        docName = response.data.docSearchSuggestsList[index].h1Tag;
                        if (docName == null || docName == '') {
                            docName = response.data.docSearchSuggestsList[index].docName;
                        }
                        docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');

                        searchContent.append(`<div>
                                <a href="${response.data.docSearchSuggestsList[index].docUrl}" target="_blank" title="${docNameClear}">${response.data.docSearchSuggestsList[index].docName}</a>
                            </div>`)
                    }
                }
                if (response?.data?.docSearchsList && response.data.docSearchsList.length > 0) {

                    for (var index = 0; index < response.data.docSearchsList.length; index++) {

                        if (!docSuggests.includes(response.data.docSearchsList[index].docId)) {
                            docName = response.data.docSearchsList[index].h1Tag;
                            if (docName == null || docName == '') {
                                docName = response.data.docSearchsList[index].docName;
                            }
                            docNameClear = docName.replaceAll('<span class="bg_yelow">', '').replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '');

                            searchContent.append(`<div>
                                <a href="${response.data.docSearchsList[index].docUrl}" target="_blank" title="${docNameClear}">${docName}</a>
                            </div>`)

                        }
                    }
                }

                if (searchContent.children().length == 0) {
                    searchContent.html('<div>Không tìm thấy kết quả phù hợp.</div>')
                }

                searchBox.addClass('open-search')

            }).catch((error) => {
                console.log(error)
            })
        })
        $(document).on('click', '#suggested-article-search', function (event) {
            const self = $(event.target), urlRequest = '/tin-bai/search-suggest.html',
                parent = self.closest('.search-suggest'),
                form = parent.find('form').first(),
                inputValue = parent.find('.input-search-all-suggest').first().val().trim(),
                searchBox = parent.find('.search-box').first()
            searchContent = parent.find('.search-content').first()

            if (self.hasClass('active')) {
                return
            }
            $('.search-tab a', parent).removeClass('active')
            self.addClass('active')
            form.attr('action', '/tin-bai/tim-tin-bai.html')
            fetchData({
                url: urlRequest,
                type: 'GET',
                dataType: 'json',
                data: { keywords: inputValue },
                beforeSend: () => {
                    self.html('<i class="loader"></i>')
                },
                always: () => {
                    self.text('Tin tức')
                }
            }).then(response => {

                searchContent.empty()

                let title = ''

                if (response.data != null && response.data.length > 0) {

                    for (var index = 0; index < response.data.length; index++) {

                        searchContent.append(`<div>
                            <a href="${response.data[index].articleUrl}" target="_blank" title="${title}">${response.data[index].title}</a>
                        </div>`)
                    }
                }

                if (searchContent.children().length == 0) {
                    searchContent.html('<div>Không tìm thấy kết quả phù hợp.</div>')
                }

                searchBox.addClass('open-search')

            }).catch((error) => {
                console.log(error)
            })
        })
        $(document).on('click', '#suggested-faqs-search', function (event) {
            const self = $(event.target), urlRequest = '/van-ban/faqs/search-suggest.html',
                parent = self.closest('.search-suggest'),
                form = parent.find('form').first(),
                inputValue = parent.find('.input-search-all-suggest').first().val().trim(),
                searchBox = parent.find('.search-box').first()
            searchContent = parent.find('.search-content').first()

            if (self.hasClass('active')) {
                return
            }
            $('.search-tab a', parent).removeClass('active')
            self.addClass('active')
            form.attr('action', '/van-ban/tim-luat-su-tu-van.html')
            fetchData({
                url: urlRequest,
                type: 'GET',
                dataType: 'json',
                data: { keywords: inputValue },
                beforeSend: () => {
                    self.html('<i class="loader"></i>')
                },
                always: () => {
                    self.text('Hỏi đáp')
                }
            }).then(response => {

                searchContent.empty()

                if (response.data != null && response.data.length > 0) {
                    let title = ''
                    for (var index = 0; index < response.data.length; index++) {
                        title = highlightKeywords(response.data[index].title, inputValue)

                        searchContent.append(`<div>
                            <a href="${response.data[index].articleUrl}" target="_blank">${title}</a>
                        </div>`)
                    }
                }

                if (searchContent.children().length == 0) {
                    searchContent.html('<div>Không tìm thấy kết quả phù hợp.</div>')
                }

                searchBox.addClass('open-search')

            }).catch((error) => {
                console.log(error)
            })
        })
        $(document).on('click', '#suggested-lawjudg-search', function (event) {
            const self = $(event.target), urlRequest = '/ban-an/search-suggest.html',
                parent = self.closest('.search-suggest'),
                form = parent.find('form').first(),
                inputValue = parent.find('.input-search-all-suggest').first().val().trim(),
                searchBox = parent.find('.search-box').first()
            searchContent = parent.find('.search-content').first()

            if (self.hasClass('active')) {
                return
            }
            $('.search-tab a', parent).removeClass('active')
            self.addClass('active')
            form.attr('action', '/ban-an/tim-ban-an.html')
            fetchData({
                url: urlRequest,
                type: 'GET',
                dataType: 'json',
                data: { keywords: inputValue },
                beforeSend: () => {
                    self.html('<i class="loader"></i>')
                },
                always: () => {
                    self.text('Bản án')
                }
            }).then(response => {

                searchContent.empty()

                //if (response?.data?.lawJudgSearchSuggestsList && response.data.lawJudgSearchSuggestsList.length > 0) {

                //    for (var index = 0; index < 3 && index < response.data.lawJudgSearchSuggestsList.length; index++) {

                //        docSuggests.push(response.data.lawJudgSearchSuggestsList[index].docId)

                //        searchContent.append(`<div class="suggest">
                //                <a href="${response.data.lawJudgSearchSuggestsList[index].docUrl}" target="_blank">${response.data.lawJudgSearchSuggestsList[index].title}</a>
                //            </div>`)
                //    }
                //}

                if (response?.data?.lawJudgSearchsList && response.data.lawJudgSearchsList.length > 0) {
                    for (var index = 0; index < response.data.lawJudgSearchsList.length; index++) {
                        searchContent.append(`<div>
                                <a href="https://luatvietnam.vn${response.data.lawJudgSearchsList[index].docUrl}" target="_blank">${response.data.lawJudgSearchsList[index].title}</a>
                            </div>`)
                    }
                }

                if (searchContent.children().length == 0) {
                    searchContent.html('<div>Không tìm thấy kết quả phù hợp.</div>')
                }

                searchBox.addClass('open-search')

            }).catch((error) => {
                console.log(error)
            })
        })
        $('.search-field').keyup(function (e) {
            if ($(this).val().trim() == '') {
                $('.searchlawauto').addClass('empty-icon');
            } else {
                $('.searchlawauto').removeClass('empty-icon');
            }
        });
        /*end PartialHomeSearchBox*/
        /* Góp ý */
        $(document).on('click',
            '#gopyv2',
            function (event) {
                event.preventDefault();
                appModule.fetchData({
                    type: 'GET',
                    dataType: 'html',
                    url: '/Ajax/PartialGopY2'
                }).then(response => {
                    if (response.length > 0) {
                        $('#_gopy').find('.popup-content').first().html(response);

                        var form = $('#FormGopYv2');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                        $('#_gopy').removeClass('target-hidden').addClass('target-expanded');
                        appModule.getRecaptchaToken(form, 'FeedBacksV2')
                    }
                })
            });
        $(document).on('click',
            '#btn_attachmentGopY_10w2p3',
            function (e) {
                e.preventDefault();
                $('#input_attachmentGopY_6cnnq3').trigger('click');
            });
        $(document).on('change',
            '#input_attachmentGopY_6cnnq3',
            function (e) {
                e.preventDefault();
                if (this.files.length > 0) {
                    var formData = new FormData(),
                        fileUploads = this.files,
                        maxSize = 10,
                        limitNumberUploads = 1,
                        index = 0,
                        validExtensions = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'pdf', 'doc', 'docx'],
                        fileNameExt = '';
                    if ($(':input[type=hidden][name=FilePath]', $('#filePath_pw9l69')).length + fileUploads.length <= limitNumberUploads) {
                        if (fileUploads.length > limitNumberUploads) {
                            lawsVn.showMessage({ messages: ['Vui lòng chọn tối đa ' + limitNumberUploads + ' file đính kèm (PDF, word, ảnh).'] });
                            return;
                        }
                        for (; index < fileUploads.length; index++) {
                            fileNameExt = fileUploads[index].name.split('.').pop().toLowerCase();
                            if (validExtensions.indexOf(fileNameExt) == -1) {
                                lawsVn.showMessage({ messages: ['Vui lòng chọn file đính kèm (PDF, word, ảnh).'] });
                                return;
                            }
                            if (fileUploads[index].size / 1024 / 1024 > maxSize) {
                                lawsVn.showMessage({ messages: ['Dung lượng file đính kèm vượt quá ' + maxSize + 'MB cho phép.'] });
                                return;
                            }
                            formData.append('listFiles', fileUploads[index]);
                        }
                        $.ajax({
                            url: '/Ajax/UploadFileAttach',
                            type: 'POST',
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            xhr: function () {
                                var xhrUpload = $.ajaxSettings.xhr(),
                                    progress = $('#progress_container_ku8ufw'),
                                    progressBar = $('#progress_bar_835j9x');
                                progress.show();
                                if (xhrUpload.upload) {
                                    xhrUpload.upload.addEventListener('progress',
                                        function (evt) {
                                            if (evt.lengthComputable) {
                                                var percentComplete = Math.round((evt.loaded * 100) / evt.total);
                                                progressBar.css({
                                                    'width': percentComplete + '%',
                                                    'background-color': '#49c5c7'
                                                });
                                            }
                                        },
                                        false);
                                    xhrUpload.addEventListener("progress",
                                        function (evt) {
                                            if (evt.lengthComputable) {
                                                var percentComplete = Math.round((evt.loaded * 100) / evt.total);
                                                setTimeout(function () {
                                                    progress.hide();
                                                    progressBar.css({
                                                        'width': 100 - percentComplete + '%',
                                                        'background-color': 'none'
                                                    });
                                                },
                                                    1000);
                                            }
                                        },
                                        false);
                                }
                                return xhrUpload;
                            },
                            success: function (resp) {
                                if (resp.Completed) {
                                    if (resp.Data != null && resp.Data.length > 0) {
                                        var fileName = '';
                                        for (var i = 0; i < resp.Data.length; i++) {
                                            var fileId = Math.random().toString(36).substring(7);
                                            if (resp.Data[i].FilePath != null && resp.Data[i].FilePath.length > 0) {

                                                $('#filePath_pw9l69')
                                                    .append(
                                                        '<input type="hidden" name="FilePath" data-id="' +
                                                        fileId +
                                                        '" value="' +
                                                        resp.Data[i].FilePath +
                                                        '">');
                                            }
                                            if (resp.Data[i].FileName != null && resp.Data[i].FileName.length > 0) {
                                                fileName += '<p class="ptext2" style="color: #333;"><span class="img-text">' +
                                                    resp.Data[i].FileName +
                                                    '</span><span class="img-sce"></span><span class="del-img" title="Hủy file tải lên: ' +
                                                    resp.Data[i].FileName +
                                                    '" data-id="' +
                                                    fileId +
                                                    '">Hủy file tải lên</span></p>';
                                            }
                                        }
                                        if (fileName.length > 0)
                                            $('#attachment_name_fdk7tn').append(fileName).css('display', 'block');
                                    }
                                } else if (resp.Message != null && resp.Message.length > 0) {
                                    lawsVn.showMessage({ messages: [resp.Message] });
                                }
                            },
                            error: function () {
                                lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] });
                            }
                        });
                    } else {
                        lawsVn.showMessage({ messages: ['Quý khách vui lòng chọn tối đa ' + limitNumberUploads + ' file đính kèm.'] });
                    }
                }
            });




        /* End Góp ý */
        $(document).on('click',
            '.guigopy',
            function (e) {
                e.preventDefault();
                try {
                    let form = $('#FormGopYv2')
                    appModule.addRecaptchaV3ToForm(form, 'GopY').then(function () {
                        form.submit()
                    }).catch(function (error) {
                        console.error('reCAPTCHA error:', error)
                    })
                } catch (ex) {
                    console.log(ex);
                }
            });
        const backToTopButton = document.getElementById('backtotop');
        if (backToTopButton) {
            function toggleBackToTopButton() {
                if (window.scrollY > 20) {
                    backToTopButton.style.display = "block";
                } else {
                    backToTopButton.style.display = "none";
                }
            }

            window.addEventListener('scroll', toggleBackToTopButton);
        }
    }
    function highlightKeywords(title, keywordPhrase) {
        let keywords = keywordPhrase.split(/\s+/).filter(Boolean);

        let normalizedTitle = removeDiacritics(title)
        let highlightedTitle = title

        let matchRanges = []

        keywords.forEach(function (keyword) {
            let normalizedKeyword = removeDiacritics(keyword)

            let normalizedPattern = new RegExp("\\b" + escapeRegex(normalizedKeyword) + "\\b", "gi")

            let match
            while ((match = normalizedPattern.exec(normalizedTitle)) !== null) {
                matchRanges.push({ index: match.index, length: match[0].length })
            }
        })

        matchRanges.sort((a, b) => b.index - a.index)

        matchRanges.forEach(function ({ index, length }) {
            let originalText = highlightedTitle.substring(index, index + length)
            highlightedTitle = highlightedTitle.substring(0, index) +
                "<span class='bg_suggest'>" + originalText + "</span>" +
                highlightedTitle.substring(index + length)
        })

        return highlightedTitle
    }
    function removeDiacritics(str) {
        return str.normalize("NFD").replace(/[\u0300-\u036f]/g, '').replace(/[đĐ]/g, 'd')
    }

    function escapeRegex(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    }

    function checkCustomerLoginByParent(element, customerName) {
        try {
            if (configs.changeTimer) clearTimeout(configs.changeTimer);
            configs.changeTimer = setTimeout(function () {
                $('.ic-show-pass, .iconpass').hide();
                $.ajax({
                    url: '/ajax/checkloginbyparentcustomer',
                    dataType: 'json',
                    type: 'GET',
                    data: { customerName },
                    success: function (response) {
                        if (response != null && response.Id > 0) {
                            element.attr('readonly', true);
                            $('input[type=password]').addClass('password');
                        }
                        else {
                            $('.ic-show-pass, .iconpass').show();
                        };
                        configs.changeTimer = false;
                    }
                });
            }, 300);
        } catch (e) {
            console.log(e);
        }
    }
    function removeDiacritics(str) {
        return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
    }
    function setupFilterCheckboxSearchForm(optDropdownSelector) {
        var dataName = $(optDropdownSelector).data('name');

        var inputSelector = $(optDropdownSelector).find('.input.input-full.search-items');
        var checkboxSelector = $(optDropdownSelector).find('.row-opt .checkbox');
        var allCheckboxSelector = $(optDropdownSelector).find('.checkbox-all');
        var optDropdownSelectorContent = $(optDropdownSelector).find('.content-sc-y');

        var originalRows = $(optDropdownSelector).find('.row-opt').toArray();

        inputSelector.on('input', debounce(function () {
            var searchTerm = $(this).val().toLowerCase();
            var normalizedSearchTerm = removeDiacritics(searchTerm);
            var fragment = document.createDocumentFragment();

            if (searchTerm.trim().length == 0) {
                $(optDropdownSelectorContent).find('.row-opt').remove();
                $(optDropdownSelectorContent).append(originalRows);
            } else {
                $(optDropdownSelectorContent).find('.row-opt').remove();
                originalRows.forEach(function (row) {
                    var labelText = $(row).text().toLowerCase();
                    var normalizedLabelText = removeDiacritics(labelText);

                    if (normalizedLabelText.includes(normalizedSearchTerm)) {
                        fragment.appendChild(row);
                    }
                });

                $(optDropdownSelectorContent).append(fragment);
            }
        }, 250));

        allCheckboxSelector.on('change', function () {
            var isChecked = $(this).is(':checked');
            checkboxSelector.prop('checked', isChecked);
        });

        $('.btn-reset-search').one('click', function (event) {
            event.preventDefault();
            inputSelector.val('');
            $(optDropdownSelectorContent).find('.row-opt').remove();
            $(optDropdownSelectorContent).append(originalRows);
            checkboxSelector.prop('checked', false);
            allCheckboxSelector.prop('checked', false);
        });
        $('.btn-search-lvn').one('click', function (event) {
            event.preventDefault();
            const self = $(this), form = self.closest('form');
            var selectedValues = [];
            checkboxSelector.filter(':checked').each(function () {
                selectedValues.push($(this).val());
            });

            var selectedValueString = selectedValues.join(',');

            var hiddenInput = $(`input[name="${dataName}"]`, form);

            if (hiddenInput.length === 0) {

                hiddenInput = $('<input>', {
                    type: 'hidden',
                    name: dataName,
                    value: selectedValueString
                });

                form.append(hiddenInput);
            } else {
                hiddenInput.val(selectedValueString);
            }

            if (selectedValueString === '') {
                hiddenInput.remove();
            }

            if (form) {
                form.submit();
            }
        });
    }
    function setupFilterSearchForm(optDropdownSelector) {
        const dataName = $(optDropdownSelector).data('name');
        const inputSelector = $(optDropdownSelector).find('.input.input-full.search-items');
        const optDropdownSelectorContent = $(optDropdownSelector).find('.content-sc-y');
        const displayTextSelector = $(optDropdownSelector).find('.input-dropdown span').first();
        const wrapper = $(optDropdownSelector).find('.opt-wrapper');
        const originalRows = $(optDropdownSelectorContent).find('.item-search').toArray();
        const defaultText = displayTextSelector.text();

        const filterItems = (searchTerm) => {
            const normalizedSearchTerm = removeDiacritics(searchTerm.toLowerCase());
            const fragment = document.createDocumentFragment();

            originalRows.forEach(row => {
                const labelText = $(row).text().toLowerCase();
                const normalizedLabelText = removeDiacritics(labelText);
                if (normalizedLabelText.includes(normalizedSearchTerm)) {
                    fragment.appendChild(row);
                }
            });

            $(optDropdownSelectorContent).empty().append(fragment);
        };

        inputSelector.on('input', debounce(function () {
            const searchTerm = $(this).val().trim();
            if (searchTerm.length === 0) {
                $(optDropdownSelectorContent).empty().append(originalRows);
            } else {
                filterItems(searchTerm);
            }
        }, 250));

        $(optDropdownSelectorContent).on('click', '.item-search', function () {
            const selectedText = $(this).text();
            const itemValue = $(this).data('value');
            wrapper.hide();
            if (typeof itemValue !== 'undefined') {
                if (itemValue == 0) {
                    displayTextSelector.text(defaultText);
                } else {
                    displayTextSelector.text(selectedText);
                }

                const form = $(this).closest('form');
                let hiddenInput = $(`input[name="${dataName}"]`, form);

                if (hiddenInput.length === 0) {
                    hiddenInput = $('<input>', {
                        type: 'hidden',
                        name: dataName,
                        value: itemValue
                    }).appendTo(form);
                } else {
                    hiddenInput.val(itemValue);
                }

                if (itemValue === '' || itemValue === 0) {
                    hiddenInput.remove();
                }
            }
        });

        $('.btn-reset-search').one('click', function (event) {
            event.preventDefault();
            inputSelector.val('');
            $(optDropdownSelectorContent).empty().append(originalRows);
            displayTextSelector.text(defaultText);
        });
    }
    function setupFilterAutocompleteSearchForm(optDropdownSelector) {
        const dataNames = $(optDropdownSelector).data('name').split(',');
        const dataSearchName = $(optDropdownSelector).data('search-name') || 'name';
        const dataSearchKey = $(optDropdownSelector).data('search-key');
        const dataStoreName = $(optDropdownSelector).data('search-store') || '';
        const inputSelector = $(optDropdownSelector).find('.input.input-full.search-items');
        const optDropdownSelectorContent = $(optDropdownSelector).find('.content-sc-y');
        const displayTextSelector = $(optDropdownSelector).find('.input-dropdown span').first();
        const wrapper = $(optDropdownSelector).find('.opt-wrapper');
        const defaultText = displayTextSelector.text();
        let isLoading = false;
        let selectedText = '';

        if (dataStoreName) {
            deleteCookie(dataStoreName);
        }

        const searchItems = (searchTerm) => {
            if (isLoading) return;
            isLoading = true;

            displayTextSelector.text('Đang tải dữ liệu...');

            fetchData({
                url: $(optDropdownSelector).data('url'),
                data: { [dataSearchName]: searchTerm }
            })
                .then(response => {
                    let data;

                    if (dataSearchKey && response[dataSearchKey]) {
                        try {
                            data = JSON.parse(response[dataSearchKey]);
                        } catch (error) {
                            return;
                        }
                    } else {
                        if (Array.isArray(response)) {
                            data = response;
                        } else {
                            return;
                        }
                    }

                    if (Array.isArray(data)) {
                        updateItemList(data);
                    }
                })
                .catch(error => {
                    console.error(error);
                })
                .finally(() => {
                    isLoading = false;
                    setTimeout(() => {
                        displayTextSelector.text(selectedText.length > 0 ? selectedText : defaultText);
                    }, 200);
                });
        };

        const updateItemList = (items) => {
            const fragment = document.createDocumentFragment();

            if (items.length > 0 && items[0][dataNames[0]] != 0) {
                const allItem = $('<div>', {
                    class: 'item-search',
                    'data-value': 0,
                    text: 'Tất cả'
                });
                fragment.appendChild(allItem[0]);
            }

            items.forEach(item => {
                const listItem = $('<div>', {
                    class: 'item-search',
                    'data-value': item[dataNames[0]],
                    text: item[dataNames[1]].replace('...', 'Tất cả')
                });
                fragment.appendChild(listItem[0]);
            });

            $(optDropdownSelectorContent).empty().append(fragment);
        };

        inputSelector.on('input', debounce(function () {
            const searchTerm = $(this).val().trim();
            if (searchTerm.length == 0) {
                selectedText = '';
            }
            searchItems(searchTerm);
        }, 250));

        $(optDropdownSelector).on('click', function () {
            //if ($(optDropdownSelectorContent).children().length === 0) {
            searchItems(inputSelector.val().trim());
            //}
        });

        $(optDropdownSelectorContent).on('click', '.item-search', function () {
            selectedText = $(this).text();
            const itemValue = $(this).data('value');
            wrapper.hide();
            let cookieData = {};
            const form = $(this).closest('form');
            if (typeof itemValue !== 'undefined' && (itemValue !== 0 && itemValue !== '')) {
                displayTextSelector.text(selectedText);
                if (dataStoreName) {
                    dataNames.forEach((name) => {
                        cookieData[name] = name === dataNames[0] ? itemValue : selectedText;
                    });

                    setCookie(dataStoreName, JSON.stringify(cookieData), 1);
                }
            } else {
                selectedText = 'Tất cả';
                displayTextSelector.text(defaultText);
                if (dataStoreName) {
                    deleteCookie(dataStoreName);
                }
            }

            const existingInput = form.find(`input[name="${dataNames[0]}"]`);
            if (existingInput.length) {
                existingInput.val(itemValue);
            } else {
                $('<input>', {
                    type: 'hidden',
                    name: dataNames[0],
                    value: itemValue
                }).appendTo(form);
            }

            //dataNames.forEach((name, index) => {
            //    const existingInput = form.find(`input[name="${name}"]`);
            //    const valueToSet = index === 0 ? itemValue : selectedText;

            //    if (itemValue) {
            //        if (existingInput.length) {
            //            existingInput.val(valueToSet);
            //        } else {
            //            $('<input>', {
            //                type: 'hidden',
            //                name: name,
            //                value: valueToSet
            //            }).appendTo(form);
            //        }
            //    } else {
            //        existingInput.remove();
            //    }
            //});
        });

        $('.btn-reset-search').one('click', function (event) {
            event.preventDefault();
            inputSelector.val('');
            selectedText = '';
            $(optDropdownSelectorContent).empty();
            displayTextSelector.text(defaultText);
            if (dataStoreName) {
                deleteCookie(dataStoreName);
            }
        });

        function setCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + (value || "") + expires + "; path=/";
        }

        function deleteCookie(name) {
            document.cookie = name + '=; Max-Age=-99999999; path=/';
        }
    }
    function validatorForm(form) {
        form.removeData('validator');
        form.removeData('unobtrusiveValidation');
        $.validator.unobtrusive.parse(form);
    }
    function b64DecodeUnicode(str) {
        return decodeURIComponent(atob(str).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }
    function initWebPageLogs() {
        var logType = 'pageview',
            pageUrl = $(location).attr('href'),
            pageTitle = encodeURIComponent($(document).attr('title')),
            referSource = document.referrer || '';
        webPageLogs(logType, pageUrl, pageTitle, referSource);
    }
    function webPageLogs(logType, pageUrl, pageTitle, referSource, pageData) {
        try {
            var userLang = navigator.language || navigator.userLanguage;
            var colorDepth = screen.colorDepth;
            var screenS = screen.width + 'x' + screen.height;
            var viewport = screen.availWidth + 'x' + screen.availHeight;
            var preTop = localStorage.getItem("preTop");
            if (preTop == null) {
                preTop = 0;
            }
            var preLeft = localStorage.getItem("preLeft");
            if (preLeft == null) {
                preLeft = 0;
            }
            var preWidth = localStorage.getItem("preWidth");
            if (preWidth == null) {
                preWidth = 0;
            }
            var preHeight = localStorage.getItem("preHeight");
            if (preHeight == null) {
                preHeight = 0;
            }
            var preDom = localStorage.getItem("preDom");
            if (preDom == null) {
                preDom = "";
            }
            var preItem = localStorage.getItem("preItem");
            if (!preItem) {
                preItem = 0;
            }
            var ppTime = localStorage.getItem("ppTime");
            if (ppTime == null) {
                ppTime = Number(new Date());
            }
            var ppTimeEnd = localStorage.getItem("ppTimeEnd");
            if (ppTimeEnd == null) {
                ppTimeEnd = Number(new Date());
            }
            var objData = {
                t: logType,
                dl: pageUrl,
                dt: pageTitle,
                ul: userLang,
                sd: colorDepth,
                sr: screenS,
                vp: viewport,
                rs: referSource,
                pt: preTop,
                pl: preLeft,
                ppt: ppTime,
                ph: preHeight,
                pw: preWidth,
                pe: preDom,
                pi: preItem,
                pte: ppTimeEnd
            };
            var isEmpty = typeof pageData == 'string' && !pageData.trim() || typeof pageData == 'undefined' || pageData === null;
            if (!isEmpty) {
                objData.pgd = pageData;
            }
            window.setTimeout(function () {
                fetchData({
                    url: '/log',
                    dataType: 'json',
                    type: 'get',
                    data: objData,
                    beforeSend: function () { }
                }).then((resp) => {
                    localStorage.setItem("ppTime", Number(new Date()));
                })
                    .catch((error) => {
                        console.error(error);
                    })
            }, 5);
        } catch (e) {
            console.log(e)
        }
    }
    function updateQueryStringParameter(uri, key, value) {
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        }
        else {
            return uri + separator + key + "=" + value;
        }
    }
    function termsAndConditions() {
        var defaultRangeValidator = jQuery.validator.methods.range;
        jQuery.validator.methods.range = function (value, element, param) {
            if (element.type === 'checkbox') {
                // neu la checkbox: tra ve true neu checkbox checked
                return element.checked;
            } else {
                // neu ko thi goi ham range validator default
                return defaultRangeValidator.call(this, value, element, param);
            }
        }
    }
    function showMessageLogin(options) {
        var defaults = {
            id: '_message',
            buttons: [{
                Name: 'Thoát',
                ClassName: 'btn-law',
                ClickEvent: function () { }
            },
            {
                Name: 'Đồng ý',
                ClassName: 'btn-law-ok',
                ClickEvent: function () { }
            }],


            callback: {},
            success: true,
            title: 'Thông báo',
            messages: [],
            returnUrl: ''
        }
        options = $.extend(defaults, options);
        options.messages = $.isArray(options.messages) ? options.messages : [];
        var popup = `<div id="${options.id}" class="popup-bg target-hidden"> <div class="popup-wrapper popup-340"> <div class="popup-body"> <div class="popup-content"> <div class="form-pad16"> <div class="form-group text-center"> <div class="text-successful color-orange">${options.title}</div> </div> <div class="form-group text-center text-content">`;
        if (options.messages.length > 0) {
            popup += '<div class="form-group text-center text-content">';
            for (var i = 0; i < options.messages.length; i++) {
                popup += '<p>' + options.messages[i] + '</p>';
            }
            popup += `</div>
            <div class="form-group popup-button text-center">`;
            if (options.buttons.length > 0) {
                for (var i = 0; i < options.buttons.length; i++) {
                    if (options.buttons[i].Name == 'Thoát') {
                        popup += `<span class="btn-law" data-toggle-target="#${options.id}">Thoát</span>`;
                    } else if (options.buttons[i].Name == 'Đồng ý') {
                        popup += `<span class="btn-law-ok" data-toggle-target="#${options.id}">Đồng ý</span>`;
                    }
                    else {
                        popup += `<span class="${options.buttons[i].ClassName}">${options.buttons[i].Name}</span>`;
                    }
                }
            }
            popup += '</div>';
        }

        if (options.success) {
            $(`#${options.id}`).remove();
            $('body').append(popup);
            for (var i = 0; i < options.buttons.length; i++) {
                var el = options.buttons[i];
                var event = el.ClickEvent;
                $(`#${options.id}`).on('click',
                    `.${el.ClassName}`,
                    $.isFunction(event) ? event : $.noop
                );
            }
        }
        $('#' + options.id).addClass('target-expanded').css('display', '');
    }
    function showMessage(options) {
        var defaults = {
            id: '_message',
            buttons: [{
                Name: 'Đóng',
                ClassName: 'btn-law',
                ClickEvent: {}
            }],
            callback: {},
            success: true,
            title: 'Thông báo',
            messages: [],
            autoClose: false,
            timeClose: 2,
            returnUrl: ''
        }
        options = $.extend(defaults, options);
        options.messages = $.isArray(options.messages) ? options.messages : [];
        var popup = `<div id="${options.id}" class="popup-bg target-hidden"> <div class="popup-wrapper popup-340"> <div class="popup-body"> <div class="popup-content"> <div class="form-pad16"> <div class="form-group text-center"> <div class="text-successful color-orange">${options.title}</div> </div> <div class="form-group text-center text-content">`

        if (options.messages.length > 0) {
            popup += '<div class="form-group text-center text-content">';
            for (var i = 0; i < options.messages.length; i++) {
                popup += '<p>' + options.messages[i] + '</p>';
            }
            popup += `</div>
            <div class="form-group popup-button text-center">`;
            if (options.buttons.length > 0) {
                for (var i = 0; i < options.buttons.length; i++) {
                    if (options.buttons[i].Name == 'Đóng') {
                        popup += `<span class="btn-law" data-toggle-target="#${options.id}">Đóng</span>`;
                    } else {
                        popup += `<span class="${options.buttons[i].ClassName}">${options.buttons[i].Name}</span>`;
                    }
                }
            }
            popup += '</div>';
        }

        if (appModule.MessageTimer) {
            clearInterval(appModule.MessageTimer)
        }

        if (options.success) {
            $(`#${options.id}`).remove();
            $('body').append(popup);
            for (var i = 0; i < options.buttons.length; i++) {
                var el = options.buttons[i];
                var event = el.ClickEvent;

                $(`#${options.id}`).on('click',
                    `.${el.ClassName}`,
                    $.isFunction(event) ? event : $.noop
                );
            }
        }

        if (options.autoClose && options.buttons.length == 1) {
            var autoCloseAfter = options.timeClose,
                button = $(`.${options.buttons[0].ClassName}`, $(`#${options.id}`)),
                buttonText = button.text()

            appModule.MessageTimer = setInterval(function () {

                if (autoCloseAfter > 0) {
                    button.text(`${buttonText} (${autoCloseAfter})`)
                }
                else {
                    button.text(buttonText)
                }

                if (autoCloseAfter == 0) {

                    clearInterval(appModule.MessageTimer)

                    if (!button.attr('data-clicked')) {

                        button.trigger('click')

                        $(`#${options.id}`).remove()
                    }
                }
                autoCloseAfter--;
            }, 1000)

        }

        $('#' + options.id).addClass('target-expanded').css('display', '');
    }
    function pushState(object) {
        if (window.history && window.history.pushState) {
            var url = new URL(window.location.href);
            for (var key in object) {
                url.searchParams.set(key, object[key]);
            }
            window.history.pushState(null, '', url);
        }
    }
    function getGoogleResponse(url, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = '[\\#&]' + name + '=([^&#]*)';
        var regex = new RegExp(regexS);
        var results = regex.exec(url);
        if (results == null)
            return '';
        else
            return results[1];
    }
    function requestGoogleAccountInfo(accessToken) {
        $.ajax({
            type: 'Get',
            url: configs.googleUserInfoUrl + accessToken,
            success: function (response) {
                $.ajax({
                    type: 'post',
                    url: '/account/googlelogin',
                    data: { googleId: response.id, email: response.email, name: typeof (response.name) === 'undefined' ? '' : response.name, givenname: typeof (response.given_name) === 'undefined' ? '' : response.given_name, familyname: typeof (response.family_name) === 'undefined' ? '' : response.family_name, picture: typeof (response.picture) === 'undefined' ? '' : response.picture },
                    success: function (resp) {
                        if (resp.Completed) {
                            //logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                            if (resp.ReturnUrl != null && resp.ReturnUrl.length > 0) {
                                window.location.href = resp.ReturnUrl;
                            }
                        } else {
                            if (resp.Data != null) {
                                if (resp.Data.startsWith('NOK_REDIRECT')) {
                                    window.location.href = '/dang-nhap-tai-khoan-gmail.html?openId=' +
                                        response.id +
                                        '&email=' +
                                        (typeof (response.email) === 'undefined' ? '' : response.email) +
                                        '&name=' +
                                        (typeof (response.name) === 'undefined' ? '' : response.name) +
                                        '&givenname=' +
                                        (typeof (response.given_name) === 'undefined' ? '' : response.given_name) +
                                        '&familyname=' +
                                        (typeof (response.family_name) === 'undefined' ? '' : response.family_name);
                                } else if (resp.Data.startsWith('NOK')) {
                                    if (resp.Message != null && resp.Message.length > 0) {
                                        showMessage({ messages: [resp.Message] });
                                    }
                                }
                            }
                        }
                    }
                })
            }
        })
        //fetchData({ type: 'GET', url: configs.googleUserInfoUrl + accessToken })
        //    .then((response) => {
        //        return fetchData({ type: 'POST', url: '/account/googlelogin', data: { googleId: response.id, email: response.email, name: typeof (response.name) === 'undefined' ? '' : response.name, givenname: typeof (response.given_name) === 'undefined' ? '' : response.given_name, familyname: typeof (response.family_name) === 'undefined' ? '' : response.family_name, picture: typeof (response.picture) === 'undefined' ? '' : response.picture } });
        //    })
        //    .then((resp) => {
        //        if (resp.Completed) {
        //            //logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
        //            if (resp.ReturnUrl != null && resp.ReturnUrl.length > 0) {
        //                window.location.href = resp.ReturnUrl;
        //            }
        //        } else {
        //            if (resp.Data != null) {
        //                if (resp.Data.startsWith('NOK_REDIRECT')) {
        //                    window.location.href = '/dang-nhap-tai-khoan-gmail.html?openId=' +
        //                        response.id +
        //                        '&email=' +
        //                        (typeof (response.email) === 'undefined' ? '' : response.email) +
        //                        '&name=' +
        //                        (typeof (response.name) === 'undefined' ? '' : response.name) +
        //                        '&givenname=' +
        //                        (typeof (response.given_name) === 'undefined' ? '' : response.given_name) +
        //                        '&familyname=' +
        //                        (typeof (response.family_name) === 'undefined' ? '' : response.family_name);
        //                } else if (resp.Data.startsWith('NOK')) {
        //                    if (resp.Message != null && resp.Message.length > 0) {
        //                        showMessage({ messages: [resp.Message] });
        //                    }
        //                }
        //            }
        //        }
        //    })
        //    .catch((error) => {
        //        showMessage({ messages : ['Quý khách vui lòng thử lại sau.']});
        //    });
    }
    function fBOnSuccess(resp) {
        fetchData({
            type: 'POST', url: '/account/facebooklogin',
            data: { facebookId: resp.id, email: typeof (resp.email) === 'undefined' ? '' : resp.email, name: typeof (resp.name) === 'undefined' ? '' : resp.name, firstname: typeof (resp.first_name) === 'undefined' ? '' : resp.first_name, lastname: typeof (resp.last_name) === 'undefined' ? '' : resp.last_name, gender: typeof (resp.gender) === 'undefined' ? '' : resp.gender },
        }).then((response) => {
            if (response.completed || response.Completed) {
                //logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                    window.location.href = response.ReturnUrl;
                }
            } else {
                if (response.Data != null) {
                    if (response.Data.startsWith('NOK_REDIRECT')) {
                        window.location.href = '/dang-nhap-tai-khoan-facebook.html?openId=' +
                            resp.id +
                            '&email=' +
                            (typeof (resp.email) === 'undefined' ? '' : resp.email) +
                            '&name=' +
                            (typeof (resp.name) === 'undefined' ? '' : resp.name) +
                            '&firstname=' +
                            (typeof (resp.first_name) === 'undefined' ? '' : resp.first_name) +
                            '&lastname=' +
                            (typeof (resp.last_name) === 'undefined' ? '' : resp.last_name);
                    } else if (response.Data.startsWith('NOK')) {
                        if (response.Message != null && response.Message.length > 0) {
                            showMessage({ messages: [response.Message] });
                            //lawsVn.logs.webpagelogs('Login', pageUrl, response.Message, response.Data);
                        }
                    }
                }
            }
        })
            .catch((error) => {
                showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] });
            });
    }
    function fbOnError(error) {
        console.log(error);
    }
    function fbLog(message) {
        console.log('$.facebookLogin ' + message);
    }
    function fbOnConnected() {
        fbLog('fbOnConnected');
        FB.api('/me', 'GET', { fields: 'id,email,name,first_name,last_name,gender,birthday,location' }, $.proxy(function (response) {
            fbLog('successful login for: ' + response.name);
            fBOnSuccess(response);
        }, this));
    }
    function fbStatusChangeCallback(response) {
        fbLog('fbstatusChangeCallback');
        if (response.status === 'connected') {
            //connected = true;
            fbOnConnected();
        } else if (response.status === 'not_authorized') {
            fbLog('not authorized');
            //connected = false;
            fbOnError('not authorized');
        } else {
            fbLog('not connected');
            //connected = false;
            fbOnError('not connected');
        }
    }
    function fbCheckLoginState() {
        fbLog('fbcheckLoginState');
        FB.getLoginStatus($.proxy(function (response) {
            fbStatusChangeCallback(response);
        }, this));
    }
    function facebookLogin() {
        if (FB) {
            fbLog('login');
            FB.login($.proxy(fbCheckLoginState, this), {
                scope: 'email,user_photos',
                return_scopes: true
            });
        }
        else {
            fbLog('Đăng nhập tài khoản Facebook không thành công - thử lại sau 5 giây...');
            setTimeout($.proxy(facebookLogin, this), 5000);
        }
    }
    function initToggleTarget() {
        $(document).off('click', '[data-toggle-target]').on('click', '[data-toggle-target]', function (e) {
            e.preventDefault();
            var self = $(this), target = self.attr('data-toggle-target'), tab = self.attr('data-tab') || self.attr('data-content'),
                checkCustomerLoginByParentValue = $('footer').data('clpc') || 0;

            if (typeof tab != typeof undefined) {
                $('.tabs-login-item, .tabs-login-content').removeClass('active');
                $('.tabs-login-item[data-tab="' + tab + '"]').addClass('active');
                $('.tabs-login-item[data-content="' + tab + '"]').addClass('active');
                $(`#${tab}`).addClass('active');
                $(`.tabs-login-content[data-content="${tab}"]`).addClass('active');
                $(`.tabs-login-content[data-tab="${tab}"]`).addClass('active');
            }

            if ((tab == 'dangnhap' || tab == 'login') && checkCustomerLoginByParentValue > 0) {
                var inputCustomerName = $('input[name="CustomerName"]').first();
                checkCustomerLoginByParent(inputCustomerName, inputCustomerName.val().trim());
            }

            if (typeof target != typeof undefined) {
                $(target).toggleClass('target-expanded').css('display', '');
            }
        });
    }
    function initTab() {
        $('[data-tab]').off('click').on('click',
            function () {
                var self = $(this), tab = self.data('tab'), tabEl = $('#' + tab);
                self.parent().children().removeClass('active');
                self.addClass('active');
                tabEl.parent().children().removeClass('active');
                tabEl.addClass('active');
            });
    }
    function initAdsSticky() {
        if ($('.sticky-ads-content').length > 0) {
            $('.sticky-ads-content').each(function (i, item) {
                adsSticky($(item))
            });
        }
    }
    function adsSticky(ads) {
        try {
            var sticky_ads_content = ads, parent = ads.parent(),
                positionTop = sticky_ads_content.data('top'),
                end_sticky_ads = sticky_ads_content.data('id');
            positionTop = positionTop || 10;
            end_sticky_ads = end_sticky_ads || $('footer');
            setTimeout(function () {
                var sticky_ads_content_top = sticky_ads_content.offset().top;
                $(window).scroll(function () {
                    var scrollTop = $(window).scrollTop();
                    sticky_ads = sticky_ads_content.prev('.sticky-ads'),
                        end_sticky = $(end_sticky_ads).offset().top - sticky_ads.outerHeight();
                    if (sticky_ads_content_top < scrollTop)
                        sticky_ads.css({ position: 'fixed', top: positionTop, left: parent.offset().left, width: parent.width() });
                    else
                        sticky_ads.css('position', 'static');
                    if (end_sticky < scrollTop) {
                        var diff = end_sticky - scrollTop + -20;
                        sticky_ads.css({ top: diff });
                    }
                });
            }, 500);
        } catch (e) {
            console.error(e);
        }
    }
    function adjustBackToTopButton() {
        const chatDiv = document.getElementById('vnp_chat');
        const backToTopButton = document.getElementById('backtotop');

        if (backToTopButton) {

            backToTopButton.style.right = '40px';

            if (chatDiv) {
                backToTopButton.style.bottom = '115px';
            } else {
                backToTopButton.style.bottom = '40px';
            }
        }
    }

    function initBackToTopButton() {
        adjustBackToTopButton();

        // Tạo một MutationObserver để theo dõi sự thay đổi trong DOM
        const observer = new MutationObserver((mutationsList) => {
            for (const mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    adjustBackToTopButton();
                }
            }
        });

        // Bắt đầu theo dõi sự thay đổi trong body
        observer.observe(document.body, { childList: true, subtree: true });
    }

    function detectIframevChat() {
        var detector = setInterval(function () {
            try {
                var elem = document.activeElement;

                if (elem && elem.tagName == 'IFRAME' && elem.getAttribute('id') == 'vnp_code_chat') {
                    //clearInterval(detector);
                }
            } catch (e) {
                clearInterval(detector);
            }
        }, 500);
    }
    function fetchData(options) {
        return new Promise((resolve, reject) => {
            $.ajax({
                cache: false,
                url: options.url,
                type: options.type || 'GET',
                data: options.data || {},
                dataType: options.dataType || 'json',
                beforeSend: options.beforeSend || showLoading(),
                success: function (data) {
                    resolve(data);
                },
                error: function (error) {
                    reject(error);
                }
            }).always(options.always || hideLoading());
        });
    }
    function initGrecaptcha(reCaptchaSiteKey) {
        try {
            if (typeof reCaptchaSiteKey !== 'undefined') {
                $('form').each(function (i, form) {
                    var action = $(form).data('action');
                    if (typeof action !== 'undefined') {
                        grecaptcha.ready(function () {
                            grecaptcha.execute(reCaptchaSiteKey,
                                {
                                    action: action
                                })
                                .then(function (token) {
                                    if (token != null && token.length > 0) {
                                        $(form).find('.g-recaptcha-response').first().val(token);
                                    }
                                });
                        });
                    }
                })
            }
        } catch (e) {
            console.error(e);
        }
    }
    function getRecaptchaToken(form, action) {
        try {
            if (form.length > 0 && $('#hfCaptcha').length > 0) {
                var hfCaptcha = $('#hfCaptcha').first(), reCaptchaSiteKey = hfCaptcha.data('id');
                if (typeof reCaptchaSiteKey !== 'undefined') {
                    grecaptcha.ready(function () {
                        grecaptcha.execute(reCaptchaSiteKey,
                            {
                                action: action
                            })
                            .then(function (token) {
                                if (token != null && token.length > 0) {
                                    form.find('.g-recaptcha-response').first().val(token);
                                }
                            });
                    });
                }
            }
        } catch (e) {
            console.error(e);
        }
    }

    function addRecaptchaV3ToForm(formSelector, action) {
        return new Promise((resolve, reject) => {
            var hfCaptcha = $('#hfCaptcha').first(), reCAPTCHASiteKey = hfCaptcha.data('id');
            if (typeof reCAPTCHASiteKey !== 'undefined') {
                grecaptcha.ready(function () {

                    grecaptcha.execute(reCAPTCHASiteKey, { action: action }).then(function (token) {

                        var recaptchaResponse = $(formSelector).find('input.g-recaptcha-response')

                        if (recaptchaResponse.length === 0) {

                            recaptchaResponse = $('<input>').attr({
                                type: 'hidden',
                                name: 'RecaptchaResponse',
                                id: 'g-recaptcha-response'
                            })

                            $(formSelector).append(recaptchaResponse)
                        }

                        recaptchaResponse.val(token)

                        resolve()
                    }).catch(function (error) {
                        reject(error)
                    })
                })
            }
        })
    }
    function loadScript(src, async = true, type = "text/javascript") {
        return new Promise((resolve, reject) => {
            try {
                const el = document.createElement("script");
                const container = document.head || document.body;

                el.type = type;
                el.async = async;
                el.src = src;

                el.addEventListener("load", () => {
                    resolve({ status: true });
                });

                el.addEventListener("error", () => {
                    reject({
                        status: false,
                        message: `Failed to load the script ${src}`
                    });
                });

                container.appendChild(el);
            } catch (err) {
                reject(err);
            }
        });
    }
    function loadGoogleTagManager(w, d, l, i) {
        w[l] = w[l] || []; w[l].push({
            'gtm.start':
                new Date().getTime(), event: 'gtm.js'
        })
        var dl = l != 'dataLayer' ? '&l=' + l : '';
        loadScript('https://www.googletagmanager.com/gtm.js?id=' + i + dl)
            .then((data) => {
                console.log("Google Tag Manager script loaded successfully", data);
            })
            .catch((err) => {
                console.error(err);
            });
    }
    function loadFacebookPixel(f, b, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
                n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        };
        if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0';
        n.queue = [];
        loadScript('https://connect.facebook.net/en_US/fbevents.js')
            .then((data) => {
                console.log("Facebook Pixel script loaded successfully", data);
                fbq('init', '297190890797171');
                fbq('track', 'PageView');
            })
            .catch((err) => {
                console.error(err);
            });
    }
    function loadGoogleRecaptcha() {
        if ($('#hfCaptcha').length > 0) {
            var hfCaptcha = $('#hfCaptcha').first(), reCaptchaSiteKey = hfCaptcha.data('id');
            if (typeof reCaptchaSiteKey !== 'undefined') {
                loadScript(`https://www.google.com/recaptcha/api.js?render=${reCaptchaSiteKey}`)
                    .then((data) => {
                        console.log("Google recaptcha script loaded successfully", data);
                        initGrecaptcha(reCaptchaSiteKey);
                    })
                    .catch((err) => {
                        console.error(err);
                    });
            }
        }
    }
    function loadFacebookJavascriptSDK() {
        loadScript('https://connect.facebook.net/en_US/all.js')
            .then((data) => {
                console.log("Facebook script loaded successfully", data);
                window.fbAsyncInit = function () {
                    FB.init({
                        appId: configs.facebookAppId,
                        status: true,
                        xfbml: true,
                        cookie: true
                    });
                };
            })
            .catch((err) => {
                console.error(err);
            });
    }
    function loadZaloJavascriptSDK() {
        loadScript('https://sp.zalo.me/plugins/sdk.js')
            .then((data) => {
                console.log("Zalo script loaded successfully", data);
            })
            .catch((err) => {
                console.error(err);
            });
    }
    function loadvChat() {
        loadScript('https://core.vchat.vn/code/tracking.js')
            .then((data) => {
                console.log("vChat script loaded successfully", data);
            })
            .catch((err) => {
                console.error(err);
            });
    }
    function initNotify() {
        if ($('.tips-thong-bao').length > 0) {
            var tips = $('.tips-thong-bao').first(), objDate = new Date();
            if (localStorage.getItem('customer-notify') != objDate.getDate()) {
                localStorage.setItem('customer-notify-click', 'false');
                localStorage.setItem('customer-notify', objDate.getDate());
            }

            if (localStorage.getItem('customer-notify-click') == 'false') {
                tips.show();
            }
        }
    }
    function removeAccents(str) {
        str = str.toLowerCase();
        str = str
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[đĐ]/g, 'd')
            .replace(/[^\w]+/g, ' ');
        return str;
    }
    function checkboxTermsOfUseRequired() {
        var defaultRangeValidator = jQuery.validator.methods.range;
        jQuery.validator.methods.range = function (value, element, param) {
            if (element.type === 'checkbox') {
                // neu la checkbox: tra ve true neu checkbox checked
                return element.checked;
            } else {
                // neu ko thi goi ham range validator default
                return defaultRangeValidator.call(this, value, element, param);
            }
        }
    }
    function requiredIf() {
        $.validator.addMethod('requiredif',
            function (value, element, parameters) {
                var id = '#' + parameters['dependentproperty'];
                var targetvalue = parameters['targetvalue'];
                targetvalue = (targetvalue == null ? '' : targetvalue).toString();

                var control = $(id);
                var controltype = control.attr('type');
                var actualvalue =
                    (controltype === 'checkbox' || controltype === 'radio') ?
                        (control.is(':checked') ? true : false) : //control.attr('checked').toString() :
                        control.val();

                if ($.trim(targetvalue) === $.trim(actualvalue) || ($.trim(targetvalue) === '*' && $.trim(actualvalue) !== ''))
                    return $.validator.methods.required.call(
                        this, value, element, parameters);

                return true;
            });

        $.validator.unobtrusive.adapters.add(
            'requiredif',
            ['dependentproperty', 'targetvalue'],
            function (options) {
                options.rules['requiredif'] = {
                    dependentproperty: options.params['dependentproperty'],
                    targetvalue: options.params['targetvalue']
                };
                options.messages['requiredif'] = options.message;
            });
    }
    function formatNumber(nStr, decSeperate, groupSeperate) {
        nStr += '';
        var x = nStr.split(decSeperate);
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + groupSeperate + '$2');
        }
        return x1 + x2;
    }
    function showLoading() {
        $('#spinner-back').addClass('show');
        $('#spinner-front').addClass('show');
    }
    function hideLoading() {
        $('#spinner-back').removeClass('show');
        $('#spinner-front').removeClass('show');
    }
    function debounce(func, delay = 500) {
        let timeout

        return function executedFunc(...args) {
            if (timeout) {
                clearTimeout(timeout)
            }

            timeout = setTimeout(() => {
                //func(...args)
                func.apply(this, args);
                timeout = null
            }, delay)
        }
    }
    $(window).scroll(function () {
        if ($(window).scrollTop() >= 100) {
            $('.fixed-sticky-').addClass('navigation-sticky');
            $('.fixed-sticky- .nav-bar').addClass('visible-title');
        }
        else {
            $('.fixed-sticky-').removeClass('navigation-sticky');
            $('.fixed-sticky- .nav-bar').removeClass('visible-title');
        }
    });
    if ($('#doc-sticky').length == 0) {
        $(window).scroll(function () {
            if ($(window).scrollTop() >= 60) {
                $('#stickymenu').addClass('stickymenu')
            }
            else {
                $('#stickymenu').removeClass('stickymenu')
            }
        })
    }
    jQuery.fn.highlight = function (pat) {
        function innerHighlight(node, pat) {
            var skip = 0;
            if (node.nodeType == 3) {
                var pos = node.data.toUpperCase().indexOf(pat);
                if (pos >= 0) {
                    var spannode = document.createElement('span');
                    spannode.className = 'highlight';
                    var middlebit = node.splitText(pos);
                    var endbit = middlebit.splitText(pat.length);
                    var middleclone = middlebit.cloneNode(true);
                    spannode.appendChild(middleclone);
                    middlebit.parentNode.replaceChild(spannode, middlebit);
                    skip = 1;
                }
            }
            else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
                for (var i = 0; i < node.childNodes.length; ++i) {
                    i += innerHighlight(node.childNodes[i], pat);
                }
            }
            return skip;
        }
        return this.each(function () {
            innerHighlight(this, pat.toUpperCase());
        });
    };
    jQuery.fn.removeHighlight = function () {
        function newNormalize(node) {
            for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
                var child = children[i];
                if (child.nodeType == 1) {
                    newNormalize(child);
                    continue;
                }
                if (child.nodeType != 3) { continue; }
                var next = child.nextSibling;
                if (next == null || next.nodeType != 3) { continue; }
                var combined_text = child.nodeValue + next.nodeValue;
                new_node = node.ownerDocument.createTextNode(combined_text);
                node.insertBefore(new_node, child);
                node.removeChild(child);
                node.removeChild(next);
                i--;
                nodeCount--;
            }
        }

        return this.find("span.highlight").each(function () {
            var thisParent = this.parentNode;
            thisParent.replaceChild(this.firstChild, this);
            newNormalize(thisParent);
        }).end();
    };
    storage = {
        getItem: function (key, optionalCallback) {
            if (!this.supportsLocalStorage()) {
                return null;
            }

            var callback = function (data) {
                data = typeof data !== 'undefined' ? data : null;

                return typeof optionalCallback === 'function' ? optionalCallback(data) : data;
            };

            var value = localStorage.getItem(key);

            if (value !== null) {
                value = JSON.parse(value);

                if (value.hasOwnProperty('__expiry')) {
                    var expiry = value.__expiry;
                    var now = Date.now();

                    if (now >= expiry) {
                        this.removeItem(key);

                        return callback();
                    } else {
                        return callback(value.__data);
                    }
                } else {
                    return callback(value);
                }
            } else {
                return callback();
            }
        },
        setItem: function (key, value, expiry) {
            if (!this.supportsLocalStorage() || typeof value === 'undefined' || key === null || value === null) {
                return false;
            }

            if (typeof expiry === 'number') {
                value = {
                    __data: value,
                    __expiry: Date.now() + (parseInt(expiry) * 1000)
                };
            }

            try {
                localStorage.setItem(key, JSON.stringify(value));

                return true;
            } catch (e) {
                console.log('Không thể lưu dữ liệu ' + key + ' trong localStorage: ' + e.name);
                return false;
            }
        },
        removeItem: function (key) {
            if (this.supportsLocalStorage()) {
                localStorage.removeItem(key);
            }
        },
        clear: function () {
            if (this.supportsLocalStorage()) {
                localStorage.clear();
            }
        },
        supportsLocalStorage: function () {
            try {
                localStorage.setItem('_', '_');
                localStorage.removeItem('_');

                return true;
            } catch (e) {
                return false;
            }
        }
    }
    ajaxError();
    init();
    initEvents();
    initTab();
    initToggleTarget();
    initLazyload();
    initWebPageLogs();
    initNotify();
    initBackToTopButton();

    return {
        fetchData: fetchData,
        ajaxEvents: ajaxEvents,
        showMessage: showMessage,
        storage: storage,
        showLoading: showLoading,
        hideLoading: hideLoading,
        pushState: pushState,
        validatorForm: validatorForm,
        getRecaptchaToken: getRecaptchaToken,
        addRecaptchaV3ToForm: addRecaptchaV3ToForm,
        loadScript: loadScript,
        loadGoogleRecaptcha: loadGoogleRecaptcha,
        loadGoogleTagManager: loadGoogleTagManager,
        loadFacebookPixel: loadFacebookPixel,
        loadFacebookJavascriptSDK: loadFacebookJavascriptSDK,
        loadZaloJavascriptSDK: loadZaloJavascriptSDK,
        loadvChat: loadvChat,
        removeAccents: removeAccents,
        requiredIf: requiredIf,
        formatNumber: formatNumber,
        initAdsSticky: initAdsSticky,
        debounce: debounce,
        setupFilterCheckboxSearchForm,
        setupFilterSearchForm,
        setupFilterAutocompleteSearchForm
    };
})();
var lawsVn = {
    ajaxEvents: {
        OnBegin: function () {
            $('#loading').fadeIn('normal');
        },
        OnComplete: function (element) {
            $('#loading').fadeOut('normal');
        },
        OnFailure: function (jqXhr, errorMessage) {
            $('#loading').fadeOut('normal');
            $('.popup-bg').lawsExists(function () {
                $(this).hide();
            });
            appModule.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] });
        },
        FeedBackOnSuccess: function (data, status, xhr) {
            var form = $('#FormGopYv2'), msg = form.find('#FeedBacksMessages');
            if (data.Completed) {
                $('#Comment', form).val('');
                $('#CaptchaCode', form).val('');
            }
            if (data.Message !== null && data.Message.length > 0) {
                appModule.showMessage({ messages: [data.Message] });
            }
            form.remove()
            $('#_gopy').addClass('target-hidden').removeClass('target-expanded');
            $('.getcaptcha', form).trigger('click');
        },
        CustomerUpdateInfoOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                if ($('#_tipsthongbao_kq').length > 0) {
                    var tips = $('#_tipsthongbao_kq').first();
                    if (tips.find('.popup-content').children().length > 0) {
                        tips.removeClass('target-hidden').addClass('target-expanded');
                    }
                    tips.prev('.popup-bg').removeClass('target-expanded').addClass('target-hidden');
                    $('.tips-thong-bao').removeClass('target-expanded').addClass('target-hidden');
                    $('#attachment_name_fdk7tn').empty();
                    $('#filePath_pw9l69').find('input[type="hidden"][name="FilePath"]').remove();
                }
            } else {
                appModule.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] });
            }
        }
    }
};
/*!
 * Lazy Load - JavaScript plugin for lazy loading images
 *
 * Copyright (c) 2007-2019 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://appelsiini.net/projects/lazyload
 *
 * Version: 2.0.0-rc.2
 *
 */

(function (root, factory) {
    if (typeof exports === "object") {
        module.exports = factory(root);
    } else if (typeof define === "function" && define.amd) {
        define([], factory);
    } else {
        root.LazyLoad = factory(root);
    }
}) (typeof global !== "undefined" ? global : this.window || this.global, function (root) {

    "use strict";

    if (typeof define === "function" && define.amd){
        root = window;
    }

    const defaults = {
        src: "data-src",
        srcset: "data-srcset",
        selector: ".lazyload",
        root: null,
        rootMargin: "10px",
        threshold: 0
    };

    /**
    * Merge two or more objects. Returns a new object.
    * @private
    * @param {Boolean}  deep     If true, do a deep (or recursive) merge [optional]
    * @param {Object}   objects  The objects to merge together
    * @returns {Object}          Merged values of defaults and options
    */
    const extend = function ()  {

        let extended = {};
        let deep = false;
        let i = 0;
        let length = arguments.length;

        /* Check if a deep merge */
        if (Object.prototype.toString.call(arguments[0]) === "[object Boolean]") {
            deep = arguments[0];
            i++;
        }

        /* Merge the object into the extended object */
        let merge = function (obj) {
            for (let prop in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                    /* If deep merge and property is an object, merge properties */
                    if (deep && Object.prototype.toString.call(obj[prop]) === "[object Object]") {
                        extended[prop] = extend(true, extended[prop], obj[prop]);
                    } else {
                        extended[prop] = obj[prop];
                    }
                }
            }
        };

        /* Loop through each object and conduct a merge */
        for (; i < length; i++) {
            let obj = arguments[i];
            merge(obj);
        }

        return extended;
    };

    function LazyLoad(images, options) {
        this.settings = extend(defaults, options || {});
        this.images = images || document.querySelectorAll(this.settings.selector);
        this.observer = null;
        this.init();
    }

    LazyLoad.prototype = {
        init: function() {

            /* Without observers load everything and bail out early. */
            if (!root.IntersectionObserver) {
                this.loadImages();
                return;
            }

            let self = this;
            let observerConfig = {
                root: this.settings.root,
                rootMargin: this.settings.rootMargin,
                threshold: [this.settings.threshold]
            };

            this.observer = new IntersectionObserver(function(entries) {
                Array.prototype.forEach.call(entries, function (entry) {
                    if (entry.isIntersecting) {
                        self.observer.unobserve(entry.target);
                        let src = entry.target.getAttribute(self.settings.src);
                        let srcset = entry.target.getAttribute(self.settings.srcset);
                        if ("img" === entry.target.tagName.toLowerCase()) {
                            if (src) {
                                entry.target.src = src;
                            }
                            if (srcset) {
                                entry.target.srcset = srcset;
                            }
                        } else if ("source" === entry.target.tagName.toLowerCase()) {
                            entry.target.srcset = srcset;
                        }
                        else if ("picture" === entry.target.tagName.toLowerCase()) {
                            var childs = $(entry.target).children("source");
                            for (var index = 0; index < childs.length; index++) {
                                var child = childs[index];
                                child.srcset = child.getAttribute(self.settings.srcset);
                            }
                            entry.target.srcset = srcset;
                        }
                        else {
                            entry.target.style.backgroundImage = "url(" + src + ")";
                        }
                    }
                });
            }, observerConfig);

            Array.prototype.forEach.call(this.images, function (image) {
                var parentItem = $(image).parent()[0];
                if (parentItem.tagName.toLowerCase() === "picture" && image.tagName.toLowerCase() !== "img") {                    
                    self.observer.observe(parentItem);
                }
                else {
                    self.observer.observe(image);
                }
            });
        },

        loadAndDestroy: function () {
            if (!this.settings) { return; }
            this.loadImages();
            this.destroy();
        },

        loadImages: function () {
            if (!this.settings) { return; }

            let self = this;
            Array.prototype.forEach.call(this.images, function (image) {
                let src = image.getAttribute(self.settings.src);
                let srcset = image.getAttribute(self.settings.srcset);
                if ("img" === image.tagName.toLowerCase()) {
                    if (src) {
                        image.src = src;
                    }
                    if (srcset) {
                        image.srcset = srcset;
                    }
                } else {
                    image.style.backgroundImage = "url('" + src + "')";
                }
            });
        },

        destroy: function () {
            if (!this.settings) { return; }
            this.observer.disconnect();
            this.settings = null;
        }
    };

    root.lazyload = function (images, options) {
        return new LazyLoad(images, options);
    };

    if (root.jQuery) {
        const $ = root.jQuery;
        $.fn.lazyload = function (options) {
            options = options || {};
            options.attribute = options.attribute || "data-src";
            new LazyLoad($.makeArray(this), options);
            return this;
        };
    }

    return LazyLoad;
});
;
$(function () {
    lawsVn.init();
    $(document).ajaxError(function (e, xhr) {
        if (xhr.status === 403) {
            var response = $.parseJSON(xhr.responseText);
            if (response.Message != null && (response.Message == 'dichvu')) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: [lawsVn.Resource.getMessages('ServiceLoginMessages')],
                    buttons: [
                        {
                            text: lawsVn.Resource.getMessages('Login'),
                            'class': 'btn-thongbao1 lawsVnLogin'
                        },
                        {
                            text: lawsVn.Resource.getMessages('Close'),
                            click: function () {
                                $(this).dialog('close');
                            }
                        }
                    ]
                });
                return;
            }
            if (typeof pldn != 'undefined') {
                if (response.Message != null && response.Message.match('^Rất tiếc. Quý khách không xem được nội dung này.')) {
                    var messageError = '';
                    if (response.Message.EndTime != null && response.Message.EndTime != '') {
                        messageError = 'Tài khoản của Quý khách đã hết hạn dịch vụ vào ngày ' + response.Message.EndTime + '. Vui lòng gia hạn tài khoản <a href="/pldn/dich-vu.html#goipldn" title="Xem chi tiết" class="link-color underline font-bold">"Pháp lý doanh nghiệp"</a> để tiếp tục sử dụng.Cảm ơn Quý khách!';
                    } else {
                        messageError = 'Tài khoản của Quý khách bị giới hạn quyền truy cập nội dung này.<br/> Vui lòng <a href="/pldn/dich-vu.html#goipldn" title="Xem chi tiết" class="link-color underline font-bold">nâng cấp tài khoản</a> để xem chi tiết.'
                    }
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [messageError],
                        buttons: [
                            {
                                text: lawsVn.Resource.getMessages('Close'),
                                'class': 'btn-thongbao1',
                                click: function () {
                                    $(this).dialog('close');
                                }
                            }
                        ],
                        onOpen: function () {
                            if ($('.popupRelate').length) {
                                $('.popupRelate').removeAttr('requestRunning');
                            }
                        }
                    });
                    return;
                }
                else {
                    setTimeout(function () {
                        window.location.href = '/pldn/dang-nhap-tai-khoan.html';
                    }, 100);
                    return;
                }
            }
            if (response.Message != null && response.Message == 'ptvb') {
                if (response.ReturnUrl != null && response.ReturnUrl.match('/user/dang-nhap-tai-khoan.html')) {
                    $(".ui-dialog:visible").find('.ui-dialog-content').dialog('close');
                    var serviceId = response.ServiceId, buttonText = 'Nâng cấp',
                        endTime = '', messageOutOfDate = 'Để xem nội dung phân tích, vui lòng nâng cấp tài khoản <br/> gói <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="cl67942 bold" style="font-size:13px !important;text-decoration: none !important;"> Phân tích văn bản Vàng</a> hoặc gói <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="cl67942 bold" style="font-size:13px !important;text-decoration: none !important;"> Phân tích văn bản Bạch kim</a>.';
                    if (serviceId == null) {
                        serviceId = $(this).data('serviceid');
                    }
                    if (response.ServiceId > 0 && response.EndTime.length > 0) {
                        endTime = response.EndTime;
                        userName = response.userName;
                        if (typeof userName === "undefined") {
                            userName = $(".font-user").attr('title');
                        }
                        if (typeof userName === "undefined") {
                            userName = $('.user-acount-login').attr('title');
                        }
                        if (typeof userName === "undefined") {
                            userName = $('.name-user-text').attr('title');
                        }
                        if (endTime.length > 0) {
                            if (serviceId == 40 || serviceId == 41) {
                                messageOutOfDate = 'Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' +
                                    endTime +
                                    '.<br/> Vui lòng gia hạn gói  <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Phân tích văn bản Vàng</a> hoặc <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Phân tích văn bản Bạch kim</a>.';
                                buttonText = 'Gia hạn';
                            } else if (serviceId == 16) {
                                messageOutOfDate = 'Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' +
                                    endTime +
                                    '.<br/> Vui lòng đăng ký gói  <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> PTVB Vàng</a> hoặc <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Phân tích văn bản Bạch kim</a>.';
                                buttonText = 'Đăng ký';
                            } else {
                                messageOutOfDate = 'Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn vào ngày ' +
                                    endTime +
                                    '.<br/> Vui lòng nâng cấp gói  <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Phân tích văn bản Vàng</a> hoặc <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Phân tích văn bản Bạch kim</a>.';
                            }
                        }
                    }
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [messageOutOfDate],
                        buttons: [
                            {
                                text: lawsVn.Resource.getMessages('Close'),
                                'class': 'btn-thongbao1',
                                click: function () {
                                    $(this).dialog('close');
                                }
                            },
                            {
                                text: buttonText,
                                'class': 'btn-thongbao2',
                                click: function () {
                                    $(this).dialog('close');
                                    window.location.href = '/phan-tich-van-ban.html#thirdptvb'
                                }
                            }
                        ],
                        onOpen: function () {
                            if ($('.popupRelate').length) {
                                $('.popupRelate').removeAttr('requestRunning');
                            }
                        }
                    });
                    return;
                }
            }
            if (response.Message != null && response.Message.match('^Rất tiếc. Quý khách không xem được nội dung này.')) {
                if (response.ReturnUrl != null && response.ReturnUrl.match('/user/dang-nhap-tai-khoan.html')) {
                    $(".ui-dialog:visible").find('.ui-dialog-content').dialog('close');
                    var serviceId = response.ServiceId,
                        endTime = '', messageOutOfDate = '<em> Để xem chi tiết, vui lòng nâng cấp tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="cl67942 bold" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="cl67942 bold" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</em>';
                    if (serviceId == null) {
                        serviceId = $(this).data('serviceid');
                    }
                    if (response.ServiceId == 17 || response.ServiceId == 28 || response.ServiceId == 25) {
                        messageOutOfDate =
                            '<em>Để xem chi tiết, vui lòng nâng cấp tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="cl67942 bold" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</em>';
                    }
                    if (response.ServiceId > 0 && response.EndTime.length > 0) {
                        endTime = response.EndTime;
                        userName = response.userName;
                        if (typeof userName === "undefined") {
                            userName = $(".font-user").attr('title');
                        }
                        if (typeof userName === "undefined") {
                            userName = $('.user-acount-login').attr('title');
                        }
                        if (typeof userName === "undefined") {
                            userName = $('.name-user-text').attr('title');
                        }
                        if (endTime.length > 0) {
                            if (serviceId == 15 || serviceId == 27 || response.ServiceId == 26) {
                                messageOutOfDate = '<em>Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' +
                                    endTime +
                                    '.</em><br/><em> Vui lòng gia hạn gói  <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</em>';
                            } else if (serviceId == 17 || serviceId == 28 || response.ServiceId == 25) {
                                messageOutOfDate = '<em>Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' +
                                    endTime +
                                    '.</em><br/> <em>Vui lòng nâng cấp gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</em>';
                            } else if (serviceId == 23 || response.ServiceId == 24) {
                                messageOutOfDate = '<em>Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn vào ngày ' +
                                    endTime +
                                    '</em>.<br/> <em>Vui lòng gia hạn gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</em>';
                            } else {
                                messageOutOfDate = '<em>Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn vào ngày ' +
                                    endTime +
                                    '</em>.<br/> <em>Vui lòng đăng ký gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</em>';
                            }
                        }
                    }
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [messageOutOfDate],
                        buttons: [
                            {
                                text: lawsVn.Resource.getMessages('Close'),
                                'class': 'btn-thongbao1',
                                click: function () {
                                    $(this).dialog('close');
                                }
                            }
                        ],
                        onOpen: function () {
                            if ($('.popupRelate').length) {
                                $('.popupRelate').removeAttr('requestRunning');
                            }
                        }
                    });
                    return;
                }
            }
            if (response.Message !== null && (response.Message.indexOf('ChiDanThayDoi') != -1)) {
                $('#popup-chidan').lawsExists(function () {
                    $(this).addClass('target-hidden').removeClass('target-expanded');
                });
                if (response.Message == 'ChiDanThayDoiNotLoggedin') {
                    lawsVn.login();
                }
                return;
            }
            lawsVnConfig.returnUrl = response.ReturnUrl + '?ReturnUrl=' + lawsVnConfig.pathName;
            var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
            activeDialogs.dialog('close');
            lawsVnConfig.isAuthen = false;
            $('.btn-faqs-send').lawsExists(function () {
                $(this).attr('au', 0);
            });
            $('#_sosanhvb').lawsExists(function () {
                $(this).addClass('target-hidden').removeClass('target-expanded');
            });
            lawsVn.login();
        }
    });
});
var lawsVnConfig = {
    rootPath: '/',
    docContentViewLimit: 10,
    pathName: window.location.pathname,
    LanguageId: 1,
    DocGroupId: 0,
    FieldId: 0,
    EffectStatusId: 0,
    DocTypeId: 0,
    OrganId: 0,
    Year: 0,
    arrAdvs: [],
    currentStep: 0,
    currentFontSize: 15,
    resetParams: 0,
    pageCount: 0,
    fontSize: 14,
    isAuthen: false,
    show: false,
    indexTarget: null,
    parentCategoryId: 0,
    changeTimer: false
};
var lawsVn = {
    init: function () {
        this.events();
    },
    events: function () {
        window.onscroll = function () { lawsVn.scrollFunction() };
        if (typeof is_ie_lt9 != 'undefined' && is_ie_lt9) {
            $('<div id="MessageIEBrowser">' +
                '<div class="cat-box-content">' +
                '<div style="float:left;padding:15px;">' +
                '<div class="rows-thongbao-js" style="font-size: 16px; font-weight: bold; text-align: center; text-transform: uppercase; margin-bottom: 15px;">' +
                '<span style="float: left; line-height: 30px; width: 100%;"> THÔNG BÁO HỖ TRỢ SỬ DỤNG LUATVIETNAM.VN</span>' +
                '</div>' +
                '<div style="font-size:13px;margin-bottom:10px;">Để trải nghiệm giao diện mới cùng các tính năng nâng cao mới trên hệ thống LuatVietnam.vn. Luật Việt Nam khuyến nghị Quý khách hàng vui lòng nâng cấp lên phiên bản Internet Explorer 11 hoặc chuyển sang sử dụng trình duyệt Chrome, Firefox, Coccoc, Safari để có trải nghiệm tốt nhất trên LuatVietnam.vn <br/><br/> Cảm ơn sự ủng hộ, hợp tác của Quý khách hàng.<br/>Trân trọng, LuatVietnam.vn</div>' +
                '</div></div></div>').lawsDialog({
                    title: '',
                    width: 600,
                    buttons: {},
                    hideClose: false,
                    closeText: 'Đóng'
                });
        }
        var overlay = $('.sidebar-overlay');
        $('.sidebar-toggle').off('click').on('click', function () {
            var sidebar = $('#sidebardefault');
            sidebar.toggleClass('open');
            if ((sidebar.hasClass('sidebar-fixed-left') || sidebar.hasClass('sidebar-fixed-right')) && sidebar.hasClass('open')) {
                overlay.addClass('active');
            } else {
                overlay.removeClass('active');
            }
            $('.content-dropdown-login').removeClass('show_dropdown');
        });
        if ($('.the-document-body table').length > 0) {
            $('.the-document-body table').each(function (i, item) {
                if ($('.the-document-body').outerWidth() + 50 < $(this).outerWidth()) {
                    $(this).wrapAll('<div style="width:100%;overflow-x:auto;"></div>');
                }
            });
        }
        overlay.off('click').on('click', function () {
            $(this).removeClass('active');
            $('#sidebardefault').removeClass('open');
        });
        if ($('#customer-messages-container-').length > 0 && $('#customer-messages-right').length > 0) {
            var customerMessages = $('#customer-messages-right').html();
            $('#customer-messages-right').remove();
            $('#customer-messages-container').html(customerMessages)
        }
        //$('.btn-thongbao').hover(function () {
        //	$('.w3-thongbao').addClass('showme');
        //});
        $(document).on('click', '.goidvlvn2-price, .goidvlvn2-text, a.redirect-url', function (e) {
            var link = $(e.target).closest('a.redirect-url');
            if (link.length && typeof link.attr('href') !== 'undefined') {
                window.open(link.attr('href'), '_blank');
                return false;
            }
        });
        $(".btn-thongbao-").click(function () {
            if ($('.w3-thongbao').hasClass('showme')) {
                $('.w3-thongbao').removeClass('showme');
            }
            else {
                $('.w3-thongbao').addClass('showme');
            }
        });
        $(document).on('click', '.w3-close-thongbao-', function () {
            $('.w3-thongbao').removeClass('showme');
        })
        if ($('#doc-view-mode').length > 0) {
            var chidan = $('#chidanthaydoind'), options = {
                "0": "Tất cả chế độ xem",
                "2": "Hiện ghi chú cá nhân",
                "3": "Chỉ hiện điều khoản ghi chú cá nhân"
            };

            if (chidan.hasClass('noidungtracuu')) {
                options = {
                    "0": "Tất cả chế độ xem",
                    "1": "Hiện chú thích thay đổi nội dung",
                    "2": "Hiện ghi chú cá nhân",
                    "3": "Chỉ hiện điều khoản ghi chú cá nhân",
                    "4": "Chỉ hiện các điều khoản sửa đổi, bổ sung, đính chính",
                    "5": "Chỉ hiện các điều khoản hướng dẫn",
                    "6": "Chỉ hiện các điều khoản bị bãi bỏ",
                    "7": "Chỉ hiện các điều khoản thay thế",
                    "8": "Tắt chú thích"
                }
            }

            $.each(options, function (key, value) {
                $('#doc-view-mode')
                    .append($('<option></option>')
                        .attr('value', key)
                        .text(value))
            })
        }
        if (jQuery().lazyload) {
            $('.lazyload').lazyload();
        }
        if ($('.tips-thong-bao').length > 0) {
            var tips = $('.tips-thong-bao').first(), objDate = new Date();
            if (localStorage.getItem('customer-notify') != objDate.getDate()) {
                localStorage.setItem('customer-notify-click', 'false');
                localStorage.setItem('customer-notify', objDate.getDate());
            }

            if (localStorage.getItem('customer-notify-click') == 'false') {
                tips.show();
            }
        }
        $(document).on('click', '.btn-tips-thong-bao', function (event) {
            event.preventDefault();
            var self = $(this), url = self.data('url') || '', id = self.data('id') || 0
            if (url.trim().length > 0) {
                if (id > 0) {
                    $.lawsAjax({
                        type: 'Post',
                        url: 'ajax/CustomerNotifyUpdateComplete',
                        data: { id: id },
                        success: function (response) {
                            if (response.Completed) {
                                window.location.href = url;
                                return;
                            }
                            if (response.Message != null && response.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [response.Message],
                                    buttons: [
                                        {
                                            text: 'Đóng',
                                            'class': 'btn-thongbao1',
                                            click: function () {
                                                $(this).dialog('close');
                                            }
                                        }
                                    ]
                                });
                            }
                        }
                    });
                }
            }
        })
        $(document).on('click', '.btn-taibieumau', function (event) {
            var self = $(this), parent = self.closest('div[class^="docitem-"]'),
                docItemId = parent.data('id'),
                dataId = self.data('id'),
                domainDowload = 'https://static.luatvietnam.vn/'
            let isLogin = true;
            $('.text-thongbao', $('#hieuluc')).lawsExists(function () {
                if ($(this).hasClass('not-loggedin')) {
                    isLogin = false;
                }
            });

            if (!isLogin) {
                lawsVn.login();
                return;
            }

            if (docItemId && dataId) {
                const docItemIds = (typeof dataId === 'number')
                    ? [dataId]
                    : (typeof dataId === 'string'
                        ? dataId.split(',').map(id => id.trim())
                        : []);

                if (docItemIds.length == 1) {
                    const rowDownloadSub = $(`.row-download-sub.doc-item[data-id="${docItemId}"]`).first();
                    if (rowDownloadSub.length) {
                        const filePath = rowDownloadSub.find('a').attr('href');
                        if (filePath) {
                            window.location.href = filePath
                        }
                    }
                } else {
                    const pathFiles = docItemIds.toString().replaceAll(',', '-');
                    window.location.href = lawsVn.getLinkFile(pathFiles)
                }
            }
        })
        $(document).on('click', '.btn-taibm', function (event) {
            var self = $(this), parent = self.closest('div[class^="docitem-"]'),
                dataId = self.data('id'),
                domainDowload = 'https://static.luatvietnam.vn/'
            if (dataId) {
                const docItemIds = (typeof dataId === 'number')
                    ? [dataId]
                    : (typeof dataId === 'string'
                        ? dataId.split(',').map(id => id.trim())
                        : []);

                if (docItemIds.length == 1) {
                    const rowDownloadSub = $(`.row-download-sub.doc-item[data-id="${docItemId}"]`).first();
                    if (rowDownloadSub.length) {
                        const filePath = rowDownloadSub.find('a').attr('href');
                        if (filePath) {
                            window.location.href = filePath
                        }
                    }
                } else {
                    const pathFiles = docItemIds.toString().replaceAll(',', '-');
                    window.location.href = lawsVn.getLinkFile(pathFiles)
                }
            }
        })
        $(document).on('click', '.close-tips-thong-bao', function () {
            var self = $(this)
            localStorage.setItem('customer-notify-click', 'true');
        })
        if ($('.sticky-ads-content').length > 0) {
            $('.sticky-ads-content').each(function (i, item) {
                lawsVn.adsSticky($(item))
            });
        }
        $(document).on('click', (event) => {
            if (!$(event.target).closest('.search-suggest').length) {
                $('.searchlawauto-items').addClass('d-none')
            }
        })
        $('.input-search-lvn').on('focus', (e) => {
            const self = $(e.target), parent = self.closest('.search-suggest'),
                resultElement = parent.find('.searchlawauto-items').first()

            if (resultElement && resultElement.hasClass('d-none') && resultElement.children().length > 0) {
                resultElement.removeClass('d-none')
            }
        })
        $('.search-clear').click(function (e) {
            e.preventDefault();
            $('.search-field').val('');
            $('.searchlawauto').addClass('empty-icon');
            $('.searchlawauto-items').empty().addClass('d-none');
        });
        $('.search-field').keyup(function (e) {
            if ($(this).val() == '') {
                $('.searchlawauto').addClass('empty-icon');
            } else {
                $('.searchlawauto').removeClass('empty-icon');
            }
        });
        $(document).on('keyup', '.input-doc-search-all-suggest', lawsVn.debounce((e) => {
            const self = $(e.target), urlRequest = '/docs/search-all-suggest.html',
                inputValue = self.val().trim(), parent = self.closest('.search-suggest'),
                iconContainer = self.next('.search-clear'),
                resultElement = parent.find('.searchlawauto-items').first()

            var code = (e.keyCode || e.which)

            if (inputValue.length == 0) {
                resultElement.empty()
                resultElement.addClass('d-none')
                return
            }

            if (code == 37 || code == 38 || code == 39 || code == 40 || code == 13) {
                return
            }

            lawsVn.fetchData({
                url: urlRequest,
                type: 'GET',
                dataType: 'json',
                data:
                {
                    keywords: inputValue
                },
                beforeSend: () => {
                    iconContainer.html('<i class="loader"></i>')
                },
                always: () => {
                    iconContainer.html('<i class="iconlvn-remove"></i>')
                }
            }).then(response => {

                resultElement.empty()

                let docName = '', docSuggests = []

                if (response.Data.lDocSuggests != null && response.Data.lDocSuggests.length > 0) {

                    for (var index = 0; index < 3 && index < response.Data.lDocSuggests.length; index++) {

                        docSuggests.push(response.Data.lDocSuggests[index].DocId)

                        docName = response.Data.lDocSuggests[index].DocName.replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '')

                        resultElement.append(`<div class="suggest">
                                <a href="${response.Data.lDocSuggests[index].DocUrl}" target="_blank" title="${docName}">${response.Data.lDocSuggests[index].DocName}</a>
                            </div>`)
                    }

                    resultElement.removeClass('d-none')
                }

                if (response.Data.lDocs != null && response.Data.lDocs.length > 0) {

                    for (var index = 0; index < response.Data.lDocs.length; index++) {

                        if (!docSuggests.includes(response.Data.lDocs[index].DocId)) {

                            docName = response.Data.lDocs[index].DocName.replaceAll('<span class="bg_suggest">', '').replaceAll('</span>', '')

                            resultElement.append(`<div>
                                <a href="${response.Data.lDocs[index].DocUrl}" target="_blank" title="${docName}">${response.Data.lDocs[index].DocName}</a>
                            </div>`)

                        }
                    }

                    resultElement.removeClass('d-none')
                }
                else {
                    resultElement.addClass('d-none')
                }

            }).catch((error) => {
                console.log(error)
                resultElement.addClass('d-none')

            })

        }, 250))
        $(document).on('click', '.iconpass', function (e) {
            var content = $(this).html();
            if (content.indexOf("fa-eye.png") != -1) {
                $(this).html('<img src="/Assets/Images/fa-eye-slash.png" alt="eye" />');
                if ($('#DialogLoginPassword').length) {
                    $('#DialogLoginPassword').prop("type", "text");
                }
                if ($('#LoginCustomerPass').length) {
                    $('#LoginCustomerPass').prop("type", "text");
                }
            } else {
                $(this).html('<img src="/Assets/Images/fa-eye.png" alt="eye" />');
                if ($('#DialogLoginPassword').length) {
                    $('#DialogLoginPassword').prop("type", "password");
                }
                if ($('#LoginCustomerPass').length) {
                    $('#LoginCustomerPass').prop("type", "password");
                }
            }
        });
        $(document).on('change keyup paste', 'input[name="CustomerName"]', function () {
            var self = $(this), customerName = self.val().trim();
            checkCustomerLoginByParentValue = $('footer').data('clpc') || 0;
            if (checkCustomerLoginByParentValue > 0)
                lawsVn.checkCustomerLoginByParent(self, customerName);
        })
        $(document).on('click',
            '.insertLink',
            function (e) {
                e.preventDefault();
                try {
                    var self = $(this), redirectUrl = self.data('url');
                    if (typeof redirectUrl != 'undefined') {
                        window.open(redirectUrl, "_blank");
                    }
                } catch (e) {
                    console.log(e);
                }
            });
        $(document).on('click', '.btn-save-customer-document', function () {
            let form = $('#SaveCustomerDocumentForm').first()
            if (form) { 
                let checkboxes = form.find('input[name="CustomerFolderIds"]');
                 
                if (checkboxes.length === 0 || checkboxes.filter(':checked').length === 0) {
                    alert('Vui lòng tạo danh mục để lưu văn bản');
                    return false;  
                }
                form.submit();
            }
        })
        $(document).on('click', '.edit-customer-folder', function () {
            let self = $(this), parent = self.closest('.form-group'), nextElement = parent.next('.form-group').find('input[name="DocId"]').first(), folderId = parent.data('id') || 0,
                docId = nextElement.length > 0 ? nextElement.val() : 0, popup = $('#_addEditFolder')

            if (docId <= 0 || folderId <= 0) {
                lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] })
                return
            }

            lawsVn.fetchData(
                {
                    url: '/ajax/GetCustomerFolderByIdV2',
                    dataType: 'html',
                    type: 'GET',
                    data: { folderId: folderId },
                    beforeSend: () => {
                        $('#loading').fadeIn('normal');
                    },
                    always: () => {
                        $('#loading').fadeOut('normal');
                    }
                })
                .then((response) => {
                    if (response != null && response.length > 0) {
                        popup.find('.popup-content').first().html(response)
                        let form = $('#EditCustomerFolderForm')
                        form.find('input[name="DocId"]').val(docId)
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                        popup.removeClass('target-hidden')
                        popup.addClass('target-expanded').css('display', '')
                    }
                })
                .catch((error) => {
                    console.error(error)
                    //appModule.hideLoading()
                    lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] })
                })
        })
        $(document).on('click', '.remove-customer-folder', function () {
            let self = $(this), parent = self.closest('.form-group'), nextElement = parent.next('.form-group').find('input[name="DocId"]').first(), folderId = parent.data('id') || 0,
                docId = nextElement.length > 0 ? nextElement.val() : 0

            if (docId <= 0 || folderId <= 0) {
                lawsVn.showMessage({ autoClose: true, messages: ['Quý khách vui lòng thử lại sau.'] })
                return
            }

            lawsVn.showMessage({
                buttons: [{
                    Name: 'Đóng',
                    ClassName: 'btn-law',
                    ClickEvent: function () { }
                },
                {
                    Name: 'Đồng ý',
                    ClassName: 'btn-law-ok',
                    ClickEvent: function () {
                        lawsVn.fetchData(
                            {
                                url: '/ajax/DeleteCustomerFolderV2',
                                dataType: 'json',
                                type: 'POST',
                                data: { docId: docId, folderId: folderId },
                                beforeSend: () => {
                                    $('#loading').fadeIn('normal');
                                },
                                always: () => {
                                    $('#loading').fadeOut('normal');
                                }
                            })
                            .then((response) => {
                                if (response.Message != null && response.Message.length > 0) {
                                    lawsVn.showMessage({
                                        autoClose: true,
                                        buttons: [{
                                            Name: 'Đóng',
                                            ClassName: 'btn-law',
                                            ClickEvent: function () {

                                                if ($(this).attr('data-clicked')) {
                                                    return
                                                }

                                                if (!response.Completed) {
                                                    return
                                                }

                                                if (response.Callback != null && response.Callback.length > 0) {
                                                    eval(lawsVn.b64DecodeUnicode(response.Callback));
                                                    return;
                                                }

                                                $(this).attr('data-clicked', true)

                                                if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                                                    window.location.href = response.ReturnUrl
                                                }
                                            }
                                        }],
                                        messages: [response.Message]
                                    })
                                }
                            })
                            .catch((error) => {
                                console.error(error)
                                //appModule.hideLoading()
                                lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] })
                            })
                    }
                }],
                messages: ['Xác nhận xóa danh mục đã chọn?']
            })
        })
        $(document).on('click', '.phan-tich-vb', function (event) {
            event.preventDefault();
            var self = $(this), docId = self.data('id') || 0, popup = $('#_phantich'),
                popupContent = popup.find('.block-phantichvb').first();
            if (docId > 0) {
                if (self.attr('requestRunning')) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                    });
                    return false;
                }

                self.attr('requestRunning', true);
                popupContent.empty();

                lawsVn.fetchData(
                    {
                        url: '/docs/get-analyzes.html',
                        dataType: 'html',
                        type: 'post',
                        data: { docId: docId },
                        beforeSend: function () { $('#loading').fadeIn('normal'); },
                        always: function () {
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                        }
                    })
                    .then((response) => {
                        if (response != null) {
                            if (response.indexOf('"Completed":false') != -1) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Quý khách vui lòng thử lại sau !']
                                });
                                popup.removeClass('target-expanded').removeClass('target-hidden');
                                return false;
                            }
                            else {
                                popupContent.first().html(response);

                                $('.entry-phan-tich', $('.content-phantichvb')).each(function (i, selector) {
                                    if ($(selector).text().length > 1000) {
                                        var parent = $(selector).closest('.div-grid-column'), entry_phan_tich = parent.find('.entry-phan-tich').first();
                                        entry_phan_tich.addClass('max-hight');
                                        parent.append('<div class="div-more"><span class="btn-load-more doc-analyzes">Hiển thị hết <i class="ic icon-small-down-2lvn"></i></span></div>');
                                    }
                                })

                                $('#myBtn').hide();
                                $('body').css('overflow', 'hidden');
                                popup.removeClass('target-hidden');
                                popup.addClass('target-expanded').css('display', '');

                                $('.sticky_div').addClass('original_sticky').clone().insertAfter('.sticky_div').addClass('cloned_sticky').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '99').removeClass('original_sticky').hide();
                                scrollIntervalID = setInterval(stickIt, 10);
                                function stickIt() {
                                    if ($('.sticky_div').length) {
                                        var orgElementPos = $('.original_sticky').offset();
                                        orgElementTop = orgElementPos.top;
                                        if ($(window).scrollTop() >= (orgElementTop)) {
                                            orgElement = $('.original_sticky');
                                            coordsOrgElement = orgElement.offset();
                                            leftOrgElement = coordsOrgElement.left;
                                            widthOrgElement = orgElement.css('width');
                                            $('.cloned_sticky').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
                                            $('.original_sticky').css('visibility', 'hidden');
                                        } else {
                                            $('.cloned_sticky').hide();
                                            $('.original_sticky').css('visibility', 'visible');
                                        }
                                    }
                                }
                            }
                        }
                    })
                    .catch((error) => {
                        console.error(error);
                        $('body').css('overflow', 'hidden');
                        self.removeAttr('requestRunning');
                        $('#loading').fadeOut('normal');
                        if (error.status != '403') {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Quý khách vui lòng thử lại sau !']
                            });
                        }
                    })


                lawsVn.logs.docViewLogs(docId, 1, 'phantich');
            }
        })
        $(document).on('click', '.phan-tich-vbduthao', function (event) {
            event.preventDefault();
            var self = $(this), docId = self.data('id') || 0, popup = $('#_phantich'),
                popupContent = popup.find('.block-phantichvb').first();
            if (docId > 0) {
                if (self.attr('requestRunning')) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                    });
                    return false;
                }

                self.attr('requestRunning', true);
                popupContent.empty();

                lawsVn.fetchData(
                    {
                        url: '/docs/get-doc-analyzes.html',
                        dataType: 'html',
                        type: 'post',
                        data: { docId: docId },
                        beforeSend: function () { $('#loading').fadeIn('normal'); },
                        always: function () {
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                        }
                    })
                    .then((response) => {
                        if (response != null) {
                            if (response.indexOf('"Completed":false') != -1) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Quý khách vui lòng thử lại sau !']
                                });
                                popup.removeClass('target-expanded').removeClass('target-hidden');
                                return false;
                            }
                            else {
                                popupContent.first().html(response);

                                $('.entry-phan-tich', $('.content-phantichvb')).each(function (i, selector) {
                                    if ($(selector).text().length > 1000) {
                                        var parent = $(selector).closest('.div-grid-column'), entry_phan_tich = parent.find('.entry-phan-tich').first();
                                        entry_phan_tich.addClass('max-hight');
                                        parent.append('<div class="div-more"><span class="btn-load-more doc-analyzes">Hiển thị hết <i class="ic icon-small-down-2lvn"></i></span></div>');
                                    }
                                })

                                $('#myBtn').hide();
                                $('body').css('overflow', 'hidden');
                                popup.removeClass('target-hidden');
                                popup.addClass('target-expanded').css('display', '');

                                $('.sticky_div').addClass('original_sticky').clone().insertAfter('.sticky_div').addClass('cloned_sticky').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '99').removeClass('original_sticky').hide();
                                scrollIntervalID = setInterval(stickIt, 10);
                                function stickIt() {
                                    if ($('.sticky_div').length) {
                                        var orgElementPos = $('.original_sticky').offset();
                                        orgElementTop = orgElementPos.top;
                                        if ($(window).scrollTop() >= (orgElementTop)) {
                                            orgElement = $('.original_sticky');
                                            coordsOrgElement = orgElement.offset();
                                            leftOrgElement = coordsOrgElement.left;
                                            widthOrgElement = orgElement.css('width');
                                            $('.cloned_sticky').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
                                            $('.original_sticky').css('visibility', 'hidden');
                                        } else {
                                            $('.cloned_sticky').hide();
                                            $('.original_sticky').css('visibility', 'visible');
                                        }
                                    }
                                }
                            }
                        }
                    })
                    .catch((error) => {
                        console.error(error);
                        $('body').css('overflow', 'hidden');
                        self.removeAttr('requestRunning');
                        $('#loading').fadeOut('normal');
                        if (error.status != '403') {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Quý khách vui lòng thử lại sau !']
                            });
                        }
                    })


                lawsVn.logs.docViewLogs(docId, 1, 'phantich');
            }
        })
        $(document).on('click', '.bg_phantich', function (event) {
            event.preventDefault();
            try {

                var self = $(this), docId = self.data('id') || 0, popup = $('#_phantich'),
                    popupContent = popup.find('.block-phantichvb').first();
                var docItemId = $(this).attr('data-item');
                if (docId > 0 && docItemId != 0) {
                    if (self.attr('requestRunning')) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                        });
                        return false;
                    }

                    self.attr('requestRunning', true);
                    popupContent.empty();

                    lawsVn.fetchData(
                        {
                            url: '/docs/get-analyzes-by-doc-item.html',
                            dataType: 'html',
                            type: 'post',
                            data: { docId: docId, docItemId: docItemId },
                            beforeSend: function () { $('#loading').fadeIn('normal'); },
                            always: function () {
                                self.removeAttr('requestRunning');
                                $('#loading').fadeOut('normal');
                            }
                        })
                        .then((response) => {
                            if (response != null) {
                                if (response.indexOf('"Completed":false') != -1) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau !']
                                    });
                                    popup.removeClass('target-expanded').removeClass('target-hidden');
                                    return false;
                                } else {
                                    popupContent.first().html(response);

                                    $('.entry-phan-tich', $('.content-phantichvb')).each(function (i, selector) {
                                        if ($(selector).text().length > 1000) {
                                            var parent = $(selector).closest('.div-grid-column'), entry_phan_tich = parent.find('.entry-phan-tich').first();
                                            entry_phan_tich.addClass('max-hight');
                                            parent.append('<div class="div-more"><span class="btn-load-more doc-analyzes">Hiển thị hết <i class="ic icon-small-down-2lvn"></i></span></div>');
                                        }
                                    })
                                    $('#myBtn').hide();
                                    $('body').css('overflow', 'hidden');
                                    popup.removeClass('target-hidden');
                                    popup.addClass('target-expanded').css('display', '');
                                }
                            }
                        })
                        .catch((error) => {
                            console.error(error)
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                            if (!error.status == '403') {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Quý khách vui lòng thử lại sau !']
                                });
                            }
                        })
                } else {
                    self.closest('.toc-item').find('.muc-luc-phan-tich-vb').first().trigger('click');
                }
            } catch (e) {
                console.log(e);
                $('body').css('overflow', 'hidden');
                self.removeAttr('requestRunning');
                $('#loading').fadeOut('normal');
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách vui lòng thử lại sau !']
                });
            }
        })
        $(document).on('change', '#view-mode', function (event) {
            event.preventDefault();
            try {
                var self = $(this), parent = self.closest('.form-sosanh-vb'), docId = parent.data('id') || 0, docItemId = parent.data('item') || 0, popup = $('#_phantich'),
                    docAnalyzesValue = $('#DocAnalyzes option:selected').val() || '', docAnalyzeSplits = docAnalyzesValue.split('-') || 0,
                    popupContent = popup.find('.block-phantichvb').first();

                if (docId > 0) {
                    if (self.attr('requestRunning')) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                        });
                        return false;
                    }

                    self.attr('requestRunning', true);
                    popupContent.empty();

                    var urlRequest = '/docs/get-analyzes.html';
                    if (self.val() > 0)
                        urlRequest = '/docs/get-full-analyzes.html';
                    else if (docItemId > 0)
                        urlRequest = '/docs/get-analyzes-by-doc-item.html';

                    lawsVn.fetchData(
                        {
                            url: urlRequest,
                            dataType: 'html',
                            type: 'post',
                            data: { docId: docId, docItemId: docItemId, customerId: docAnalyzeSplits[0], infoChannelId: docAnalyzeSplits[1] },
                            beforeSend: function () { $('#loading').fadeIn('normal'); },
                            always: function () {
                                self.removeAttr('requestRunning');
                                $('#loading').fadeOut('normal');
                            }
                        })
                        .then((response) => {
                            if (response != null) {
                                if (response.indexOf('"Completed":false') != -1) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau !']
                                    });
                                    popup.removeClass('target-expanded').removeClass('target-hidden');
                                    return false;
                                } else {
                                    popupContent.first().html(response);

                                    if (self.val() > 0) {
                                        $('.text-ppc-content', $('.right-phantichvb')).each(function (i, selector) {
                                            if ($(selector).text().length > 1000) {
                                                var parent = $(selector).closest('.blockquote-ptvb'), blockquote_content = parent.find('.blockquote-ptvb-content').first();
                                                blockquote_content.addClass('show-more');
                                                parent.append('<div class="text-ppc-more"><span class="btn-ppc-more doc-analyzes">Hiển thị hết</span></div>');
                                            }
                                        })
                                    } else {
                                        $('.entry-phan-tich', $('.content-phantichvb')).each(function (i, selector) {
                                            if ($(selector).text().length > 1000) {
                                                var parent = $(selector).closest('.div-grid-column'), entry_phan_tich = parent.find('.entry-phan-tich').first();
                                                entry_phan_tich.addClass('max-hight');
                                                parent.append('<div class="div-more"><span class="btn-load-more doc-analyzes">Hiển thị hết <i class="ic icon-small-down-2lvn"></i></span></div>');
                                            }
                                        })
                                    }

                                    var sticky = $('.sticky-indexes');
                                    if (sticky.offset()) {
                                        var stickyTop = sticky.offset().top - $(window).scrollTop(), stickyWidth = 367.8, stickOffset = 5;
                                        $('.popup-phantich').scroll(function () {
                                            var windowTop = $('.popup-phantich').scrollTop();
                                            if (stickyTop < windowTop + stickOffset) {
                                                sticky.css({ position: 'fixed', top: stickOffset }); //, width: stickyWidth
                                            } else {
                                                sticky.css({ position: 'inherit', top: 'initial' });
                                            }
                                        });
                                    }

                                    if (self.val() <= 0) {
                                        $('.sticky_div').addClass('original_sticky').clone().insertAfter('.sticky_div').addClass('cloned_sticky').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '99').removeClass('original_sticky').hide();
                                        scrollIntervalID = setInterval(stickIt, 10);
                                        function stickIt() {
                                            if ($('.sticky_div').length) {
                                                var orgElementPos = $('.original_sticky').offset();
                                                orgElementTop = orgElementPos.top;
                                                if ($(window).scrollTop() >= (orgElementTop)) {
                                                    orgElement = $('.original_sticky');
                                                    coordsOrgElement = orgElement.offset();
                                                    leftOrgElement = coordsOrgElement.left;
                                                    widthOrgElement = orgElement.css('width');
                                                    $('.cloned_sticky').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
                                                    $('.original_sticky').css('visibility', 'hidden');
                                                } else {
                                                    $('.cloned_sticky').hide();
                                                    $('.original_sticky').css('visibility', 'visible');
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        })
                        .catch((error) => {
                            console.error(error)
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Quý khách vui lòng thử lại sau !']
                            });
                        })
                }
            } catch (e) {
                console.log(e);
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách vui lòng thử lại sau !']
                });
            }
        })
        $(document).on('click', '.btn-dropdown', function () {
            var t = $(this).parents(".dropdown").children(".dropdown-wrapper").is(":hidden");

            $(".dropdown .dropdown-wrapper").hide();
            $(".dropdown .btn-dropdown").removeClass("dropdown-active1");
            if (t) {
                $(this).parents(".dropdown").children(".dropdown-wrapper").toggle().parents(".dropdown")
                    .children(".btn-dropdown").addClass("dropdown-active1")
            }
        })
        $(document).on('click', '.btn-dropdownsongngu', function () {
            var t = $(this).parents(".dropdown").children(".dropdown-wrapper").is(":hidden");
            var e = $($(this).parents(".dropdown").find("#mucluc5").is(":hidden"))
            $(".dropdown .dropdown-wrapper").hide();
            $(".dropdown .btn-dropdown").removeClass("dropdown-active1");
            if (t) {
                $(this).parents(".dropdown").children(".dropdown-wrapper").toggle().parents(".dropdown")
                    .children(".btn-dropdown").addClass("dropdown-active1")
            }
            if (e) {
                $(this).parents(".dropdown").find("#mucluc5").show();
            }
        })
        $(document).on('click', '.mucluc_songngu_left', function (event) {
            event.preventDefault();
            const self = $(this), wrapper = self.closest('.dropdown-wrapper'),
                currentTargetLeft = null;
            currentTargetLeftOffset = 0;
            var id = $(this).attr('data-id') || $(this).attr('class').replace(/\s{2,}/g, ' ').split(' ')[2];
            if (typeof id != 'undefined') {
                var parent = $('.l08fyuscmy', $('#_vbsongngu')), target = $('#_vbsongngu').find('#' + id);
                if (target.length) {
                    $('.dropdown-wrapper').lawsExists(function () {
                        $(this).hide();
                    });
                    parent.animate({
                        scrollTop: target.position().top + parent.scrollTop()
                    }, 1000);
                }
            }
        })
        $(document).on('click', '.mucluc_songngu_right', function (event) {
            event.preventDefault();
            const self = $(this), parent = $('.bz2r9a68x5'), wrapper = self.closest('.dropdown-wrapper'), id = $(this).attr('data-id')
            if (id) {
                const target = parent.find(`#${id}`).first()
                if (target.length) {
                    wrapper.toggle().parents('.dropdown').children('.btn-dropdown').addClass('dropdown-active1')
                    parent.animate({ scrollTop: target.offset().top - parent.offset().top + parent.scrollTop() }, 1000)
                }
            }
            return false
        })
        $(document).on('click', '.ndvb-tab-item', function (event) {
            event.preventDefault();
            var parent = $(this).closest(".ndvb-tab");
            var blockContent = $(parent).closest(".block-ndvb");
            $(parent).find(".ndvb-tab-item").removeClass('active').addClass('nomix');
            $(this).removeClass('nomix').addClass('active');
            var value = $(this).attr('data-value');

            $(blockContent).find(".ndvb-content").addClass('target-hidden');

            var divContent = $(blockContent).find(".ndvb" + value).first();
            if (divContent) {
                $(divContent).removeClass('target-hidden');
                var content = $(divContent).html();
                if (content == null || content.length == 0) {
                    var docItemId = $(parent).attr('data-docItemId');
                    var docId = $(parent).attr('data-docId');
                    var docItemIds = $(parent).attr('data-docItemIds');

                    lawsVn.fetchData(
                        {
                            url: '/ajax/DocItemViewReferenceContentUnionAsync',
                            dataType: 'html',
                            type: 'GET',
                            data: { 'docItemId': docItemId, 'docId': docId, 'docItemIds': docItemIds },
                            beforeSend: () => {
                                $(divContent).html("Đang tải dữ liệu...");
                                $('#loading').fadeIn('normal');
                            },
                            always: () => {
                                $(divContent).html("");
                                $('#loading').fadeOut('normal');
                            }
                        })
                        .then((response) => {
                            if (response != null && response.length > 0) {
                                if (response.indexOf('data-title') != -1) {
                                    $(blockContent).find(".ndvb-status").removeClass('hidden');
                                } else {
                                    $(blockContent).find(".ndvb-status").addClass('hidden');
                                }
                                $(divContent).html(response);
                            }
                        });
                } else {
                    if (content.indexOf('data-title') != -1) {
                        $(blockContent).find(".ndvb-status").removeClass('hidden');
                    } else {
                        $(blockContent).find(".ndvb-status").addClass('hidden');
                    }
                }
            }
        })
        $(document).bind("click", function (t) {
            var n = $(t.target);
            if (!n.parents().hasClass("dropdown")) $(".dropdown .dropdown-wrapper").hide();
        });
        $(document).bind("click", function (t) {
            var n = $(t.target);
            if (!n.parents().hasClass("dropdown")) $(".dropdown .btn-dropdown").removeClass("dropdown-active1");
        })
        $(document).on('change', '#view-mode-duthao', function (event) {
            event.preventDefault();
            try {
                var self = $(this), parent = self.closest('.form-sosanh-vb'), docId = parent.data('id') || 0, docItemId = parent.data('item') || 0, popup = $('#_phantich'),
                    docAnalyzesValue = $('#DocAnalyzes option:selected').val() || '', docAnalyzeSplits = docAnalyzesValue.split('-') || 0,
                    popupContent = popup.find('.block-phantichvb').first();

                if (docId > 0) {
                    if (self.attr('requestRunning')) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                        });
                        return false;
                    }

                    self.attr('requestRunning', true);
                    popupContent.empty();

                    var urlRequest = '/docs/get-doc-analyzes.html';
                    if (self.val() > 0)
                        urlRequest = '/docs/get-full-duthao-analyzes.html';
                    else if (docItemId > 0)
                        urlRequest = '/docs/get-analyzes-by-doc-item.html';

                    lawsVn.fetchData(
                        {
                            url: urlRequest,
                            dataType: 'html',
                            type: 'post',
                            data: { docId: docId, docItemId: docItemId, customerId: docAnalyzeSplits[0], infoChannelId: docAnalyzeSplits[1] },
                            beforeSend: function () { $('#loading').fadeIn('normal'); },
                            always: function () {
                                self.removeAttr('requestRunning');
                                $('#loading').fadeOut('normal');
                            }
                        })
                        .then((response) => {
                            if (response != null) {
                                if (response.indexOf('"Completed":false') != -1) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau !']
                                    });
                                    popup.removeClass('target-expanded').removeClass('target-hidden');
                                    return false;
                                } else {
                                    popupContent.first().html(response);

                                    if (self.val() > 0) {
                                        $('.text-ppc-content', $('.right-phantichvb')).each(function (i, selector) {
                                            if ($(selector).text().length > 1000) {
                                                var parent = $(selector).closest('.blockquote-ptvb'), blockquote_content = parent.find('.blockquote-ptvb-content').first();
                                                blockquote_content.addClass('show-more');
                                                parent.append('<div class="text-ppc-more"><span class="btn-ppc-more doc-analyzes">Hiển thị hết</span></div>');
                                            }
                                        })
                                    } else {
                                        $('.entry-phan-tich', $('.content-phantichvb')).each(function (i, selector) {
                                            if ($(selector).text().length > 1000) {
                                                var parent = $(selector).closest('.div-grid-column'), entry_phan_tich = parent.find('.entry-phan-tich').first();
                                                entry_phan_tich.addClass('max-hight');
                                                parent.append('<div class="div-more"><span class="btn-load-more doc-analyzes">Hiển thị hết <i class="ic icon-small-down-2lvn"></i></span></div>');
                                            }
                                        })
                                    }

                                    var sticky = $('.sticky-indexes');
                                    if (sticky.offset()) {
                                        var stickyTop = sticky.offset().top - $(window).scrollTop(), stickyWidth = 367.8, stickOffset = 5;
                                        $('.popup-phantich').scroll(function () {
                                            var windowTop = $('.popup-phantich').scrollTop();
                                            if (stickyTop < windowTop + stickOffset) {
                                                sticky.css({ position: 'fixed', top: stickOffset }); //, width: stickyWidth
                                            } else {
                                                sticky.css({ position: 'inherit', top: 'initial' });
                                            }
                                        });
                                    }

                                    if (self.val() <= 0) {
                                        $('.sticky_div').addClass('original_sticky').clone().insertAfter('.sticky_div').addClass('cloned_sticky').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '99').removeClass('original_sticky').hide();
                                        scrollIntervalID = setInterval(stickIt, 10);
                                        function stickIt() {
                                            if ($('.sticky_div').length) {
                                                var orgElementPos = $('.original_sticky').offset();
                                                orgElementTop = orgElementPos.top;
                                                if ($(window).scrollTop() >= (orgElementTop)) {
                                                    orgElement = $('.original_sticky');
                                                    coordsOrgElement = orgElement.offset();
                                                    leftOrgElement = coordsOrgElement.left;
                                                    widthOrgElement = orgElement.css('width');
                                                    $('.cloned_sticky').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
                                                    $('.original_sticky').css('visibility', 'hidden');
                                                } else {
                                                    $('.cloned_sticky').hide();
                                                    $('.original_sticky').css('visibility', 'visible');
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        })
                        .catch((error) => {
                            console.error(error)
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Quý khách vui lòng thử lại sau !']
                            });
                        })
                }
            } catch (e) {
                console.log(e);
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách vui lòng thử lại sau !']
                });
            }
        })
        $(document).on('click', '.tai-file-ptvb', function (event) {
            event.preventDefault();
            try {
                var self = $(this), parent = self.closest('.form-sosanh-vb'), docId = parent.data('id') || 0, docItemId = parent.data('item') || 0,
                    docAnalyzesValue = $('#DocAnalyzes option:selected').val(), docAnalyzeSplit = docAnalyzesValue ? docAnalyzesValue.split('-') : '';

                var filename = self.data('filename');
                if (docId > 0) {
                    if (self.attr('requestRunning')) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                        });
                        return false;
                    }

                    self.attr('requestRunning', true);

                    var urlRequest = '/docs/export-analyzes.html';
                    if (docItemId > 0)
                        urlRequest = '/docs/export-analyzes-by-doc-item.html';

                    lawsVn.fetchData(
                        {
                            url: urlRequest,
                            dataType: 'html',
                            type: 'post',
                            data: { docId: docId, docItemId: docItemId, customerId: docAnalyzeSplit[0], infoChannelId: docAnalyzeSplit[1] },
                            beforeSend: function () { $('#loading').fadeIn('normal'); },
                            always: function () {
                                self.removeAttr('requestRunning');
                                $('#loading').fadeOut('normal');
                            }
                        })
                        .then((response) => {
                            if (response != null) {
                                if (response.indexOf('"Completed":false') != -1) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau !']
                                    });
                                    return false;
                                } else {
                                    var dataFileType = 'application/vnd.ms-excel';
                                    response = response.replace(/<br\s*\/?>/ig, "<br style='mso-data-placement:same-cell;' />");
                                    var d = new Date,
                                        dformat = [d.getMonth() + 1,
                                        d.getDate(),
                                        d.getFullYear()].join('') +
                                            [d.getHours(),
                                            d.getMinutes(),
                                            d.getSeconds()].join('');

                                    fileName = `Phân tích ${filename}.xls`;
                                    var base64 = function (s) {
                                        return window.btoa(unescape(encodeURIComponent(s)))
                                    };

                                    var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body style="font-size: 10pt; font-family: Times New Roman"><table>{table}</table></body></html>';
                                    var render = function (template, content) {
                                        return template.replace(/{(\w+)}/g, function (m, p) { return content[p]; });
                                    };

                                    var tableExcel = render(template, {
                                        worksheet: fileName,
                                        table: response
                                    });

                                    if (navigator.msSaveOrOpenBlob) {
                                        let blob = new Blob(
                                            ['\ufeff', tableExcel],
                                            { type: dataFileType }
                                        );

                                        navigator.msSaveOrOpenBlob(blob, fileName);
                                    } else {
                                        let downloadLink = document.createElement("a");

                                        document.body.appendChild(downloadLink);

                                        downloadLink.href = 'data:' + dataFileType + ';base64,' + base64(tableExcel);

                                        downloadLink.download = fileName;

                                        downloadLink.click();
                                    }
                                }
                            }
                        })
                        .catch((error) => {
                            console.error(error)
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Quý khách vui lòng thử lại sau !']
                            });
                        })
                }
            } catch (e) {
                console.log(e);
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách vui lòng thử lại sau !']
                });
            }
        })
        $(document).on('change', '#analysis-content', function (event) {
            event.preventDefault();
            var value = $(this).val();
            if (value == 1) {
                $('.div-grid-3.item.noi-dung-tuong-ung').show();
                $('.div-grid-3.item:not(.noi-dung-tuong-ung)').hide();
            } else if (value == 2) {
                $('.div-grid-3.item.noi-dung-moi').show();
                $('.div-grid-3.item:not(.noi-dung-moi)').hide();
            } else {
                $('.div-grid-3.item').show();
            }
        })
        $(document).on('change', '#DocAnalyzes', function (event) {
            event.preventDefault();
            try {
                var self = $(this), parent = self.closest('.form-sosanh-vb'), docId = parent.data('id') || 0,
                    docItemId = parent.data('item') || 0, popup = $('#_phantich'),
                    valueSplits = self.val().split('-'), customerId = valueSplits[0], infoChannelId = valueSplits[1],
                    viewMode = parent.data('view') || 0,
                    popupContent = popup.find('.block-phantichvb').first();
                if (docId > 0) {
                    if (self.attr('requestRunning')) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                        });
                        return false;
                    }

                    self.attr('requestRunning', true);
                    popupContent.empty();

                    var urlRequest = '/docs/get-analyzes.html';
                    if (docItemId > 0)
                        urlRequest = '/docs/get-analyzes-by-doc-item.html';
                    if (viewMode > 0) {
                        urlRequest = '/docs/get-full-analyzes.html';
                    }

                    lawsVn.fetchData(
                        {
                            url: urlRequest,
                            dataType: 'html',
                            type: 'post',
                            data: { docId: docId, docItemId: docItemId, customerId: customerId, infoChannelId: infoChannelId },
                            beforeSend: function () { $('#loading').fadeIn('normal'); },
                            always: function () {
                                self.removeAttr('requestRunning');
                                $('#loading').fadeOut('normal');
                            }
                        })
                        .then((response) => {
                            if (response != null) {
                                if (response.indexOf('"Completed":false') != -1) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau !']
                                    });
                                    popup.removeClass('target-expanded').removeClass('target-hidden');
                                    return false;
                                } else {
                                    popupContent.first().html(response);
                                    var sticky = $('.sticky-indexes');
                                    if (sticky.offset()) {
                                        var stickyTop = sticky.offset().top - $(window).scrollTop(), stickyWidth = 367.8, stickOffset = 5;
                                        $('.popup-phantich').scroll(function () {
                                            var windowTop = $('.popup-phantich').scrollTop();
                                            if (stickyTop < windowTop + stickOffset) {
                                                sticky.css({ position: 'fixed', top: stickOffset }); //, width: stickyWidth
                                            } else {
                                                sticky.css({ position: 'inherit', top: 'initial' });
                                            }
                                        });
                                    }

                                    if (viewMode <= 0) {
                                        $('.sticky_div').addClass('original_sticky').clone().insertAfter('.sticky_div').addClass('cloned_sticky').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '99').removeClass('original_sticky').hide();
                                        scrollIntervalID = setInterval(stickIt, 10);
                                        function stickIt() {
                                            if ($('.sticky_div').length) {
                                                var orgElementPos = $('.original_sticky').offset();
                                                orgElementTop = orgElementPos.top;
                                                if ($(window).scrollTop() >= (orgElementTop)) {
                                                    orgElement = $('.original_sticky');
                                                    coordsOrgElement = orgElement.offset();
                                                    leftOrgElement = coordsOrgElement.left;
                                                    widthOrgElement = orgElement.css('width');
                                                    $('.cloned_sticky').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
                                                    $('.original_sticky').css('visibility', 'hidden');
                                                } else {
                                                    $('.cloned_sticky').hide();
                                                    $('.original_sticky').css('visibility', 'visible');
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        })
                        .catch((error) => {
                            console.error(error)
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Quý khách vui lòng thử lại sau !']
                            });
                        })
                }
            } catch (e) {
                console.log(e);
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách vui lòng thử lại sau !']
                });
            }
        })
        $(document).on('click', '.btn-load-more.doc-analyzes', function (e) {
            e.preventDefault();
            var self = $(this), parent = self.closest('.div-grid-column'), entry_phan_tich = parent.find('.entry-phan-tich').first();
            entry_phan_tich.toggleClass('max-hight', 300, 'easeInQuad');
            self.text(function (i, text) {
                return text.trim() === 'Hiển thị hết' ? self.html('Thu gọn <i class="ic icon-small-up-2lvn"></i>') : self.html('Hiển thị hết <i class="ic icon-small-down-2lvn"></i>');
            })
            //if (text.trim() === 'Hiển thị hết') {
            //    self.html('Thu gọn <i class="ic icon-small-up-2lvn"></i>');
            //}
            //else {
            //    self.html('Hiển thị hết <i class="ic icon-small-down-2lvn"></i>');
            //}
        });
        $(document).on('mouseover', '.entry-phan-tich', function () {
            var self = $(this), parent = self.closest('.div-grid-2');
            if (self.hasClass('left')) {
                $('.entry-phan-tich.right', parent).addClass('hover');
            } else {
                $('.entry-phan-tich.left', parent).addClass('hover');
            }
        })
        $(document).on('mouseout', '.entry-phan-tich', function () {
            var self = $(this), parent = self.closest('.div-grid-2');
            $('.entry-phan-tich', parent).removeClass('hover');
        })
        $(document).on('click', '.submit-form-', function () {
            $(this).closest('form').submit();
        })
        $(document).on('click', '.btn-ppc-more.doc-analyzes', function (e) {
            e.preventDefault();
            var self = $(this), parent = self.closest('.blockquote-ptvb'), blockquote_content = parent.find('.blockquote-ptvb-content').first();
            blockquote_content.toggleClass('show-more', 300, 'easeInQuad');
            self.text(function (i, text) {
                return text === 'Hiển thị hết' ? 'Hiển thị rút gọn' : 'Hiển thị hết';
            })
        });
        $(document).on('click', '.ic-hidden-pass', function (e) {
            var password = $(this).closest('.form-group').find('input').first();
            $(this).remove();
            password.closest('.form-group').first().append('<i class="iconlvn-eye-open ic-show-pass"></i>');
            password.prop("type", "text");
        });
        $(document).on('click', '.ic-show-pass', function (e) {
            var password = $(this).closest('.form-group').find('input').first();
            $(this).remove();
            password.closest('.form-group').first().append('<i class="iconlvn-eye-close ic-hidden-pass"></i>');
            password.prop("type", "password");
        });
        $(document).on('click', '.link-tham-chieu', function (e) {
            e.preventDefault();
            var id = $(this).data('id');
            if (typeof id != 'undefined') {
                $('html, body').animate({
                    scrollTop: $('#' + id).offset().top - 150
                }, 500);
            }
        })
        $(document).on('click', '.muc-luc-phan-tich-vb', function (e) {
            e.preventDefault();
            var id = $(this).attr("data-id");
            if (typeof id != 'undefined') {
                $('.dropdown-wrapper').hide();
                var container = $('.popup-phantich');
                container.animate({
                    scrollTop: container.scrollTop = container.scrollTop() + $(`#${id}`).offset().top - container.offset().top
                }, 500);
            }
        })
        $(document).on('click', '.toc-show', function (e) {
            e.preventDefault();
            var parent = $(this).closest('.table-of-contents'), toc = parent.find('.toc-content');
            $(this).toggleClass('toc-active');
            if (toc.is(':visible')) {
                toc.hide();
            } else {
                toc.show();
            }
            if ($(this).hasClass('toc-active')) {
                $(this).html('[Hiện]')
            } else {
                $(this).html('[Ẩn]')
            }
        })

        $(document).on('click',
            '.login-item span[data-content="dangnhap"], .login-item span[data-content="dangky"]',
            function (event) {
                event.preventDefault();
                var me = $(this),
                    content = me.data('content'),
                    li = $('.tabs-login-content[data-content*="dang"], .tabs-login-content[data-content="dangky"]'),
                    liActive = $('.tabs-login-content[data-content="' + content + '"]'),
                    checkCustomerLoginByParentValue = $('footer').data('clpc') || 0;

                $('.tabs-login-item').removeClass('active');
                me.addClass('active');
                li.removeClass('active');
                liActive.addClass('active');
                $('.tabs-login-item[data-content="' + content + '"]').addClass('active');

                if ((content == 'dangnhap' || content == 'login') && checkCustomerLoginByParentValue > 0) {
                    var inputCustomerName = $('input[name="CustomerName"]').first();
                    lawsVn.checkCustomerLoginByParent(inputCustomerName, inputCustomerName.val().trim());
                }
            });
        $(document).on('click',
            '.tabs-login-item',
            function (e) {
                e.preventDefault();
                var self = $(this), tab = self.data('tab');
                if (typeof tab != 'undefined') {
                    $('.tabs-login-item').removeClass('active');
                    $('.tabs-login-content').removeClass('active');
                    self.addClass('active');
                    $('#tab' + tab).addClass('active');
                }
            });
        $(document).on('click',
            '.li-relatetypes',
            function () {
                $('.li-relatetypes').removeClass('active');
                $(this).addClass('active');
            });
        $(document).on('change',
            'form .select-onchange',
            function (event) {
                event.preventDefault();
                $('input[name="page"]').lawsExists(function () {
                    $(this).val(1);
                    lawsVn.ajaxEvents.pageIndex = 1; //reset page
                });
                var form = $(this).closest('form');
                if (form.find('input[name="pagesizeonchange"]').length == 0)
                    form.append('<input type="hidden" name="pagesizeonchange" value="1" />');
                lawsVn.ajaxEvents.showNumberOfResults = $(this).val();
                form.submit();
                $('.row-item.fix').lawsExists(function () {
                    $(this).css('color', '#222');
                });
            });
        $(document).on('click',
            '.t0u6y0q95s',
            function (e) {
                e.preventDefault();
                try {
                    var me = $(this);
                    grecaptcha.ready(function () {
                        grecaptcha.execute(clientId,
                            {
                                action: 'ForgotPassword'
                            })
                            .then(function (token) {
                                $('#ForgotPasswordReCaptchaToken').val(token);
                                me.closest('form').submit();
                            });
                    });
                } catch (e) {

                }
            });
        $(document).on('click',
            '.guigopy',
            function (e) {
                e.preventDefault();
                try {
                    let form = $('#FormGopYv2')
                    appModule.addRecaptchaV3ToForm(form, 'GopY').then(function () {
                        form.submit()
                    }).catch(function (error) {
                        console.error('reCAPTCHA error:', error)
                    })
                } catch (ex) {
                    console.log(ex);
                }
            });
        $(document).on('click',
            '#gopyv2',
            function (event) {
                event.preventDefault();
                appModule.fetchData({
                    type: 'GET',
                    dataType: 'html',
                    url: '/Ajax/PartialGopY2'
                }).then(response => {
                    if (response.length > 0) {
                        $('#_gopy').find('.popup-content').first().html(response);

                        var form = $('#FormGopYv2');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                        $('#_gopy').removeClass('target-hidden').addClass('target-expanded');
                        appModule.getRecaptchaToken(form, 'FeedBacksV2')
                    }
                })
            });
        $(document).on('click',
            '#btn_attachmentGopY_10w2p3',
            function (e) {
                e.preventDefault();
                $('#input_attachmentGopY_6cnnq3').trigger('click');
            });
        $(document).on('change',
            '#input_attachmentGopY_6cnnq3',
            function (e) {
                e.preventDefault();
                if (this.files.length > 0) {
                    var formData = new FormData(),
                        fileUploads = this.files,
                        maxSize = 10,
                        limitNumberUploads = 1,
                        index = 0,
                        validExtensions = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'pdf', 'doc', 'docx'],
                        fileNameExt = '';
                    if ($(':input[type=hidden][name=FilePath]', $('#filePath_pw9l69')).length + fileUploads.length <= limitNumberUploads) {
                        if (fileUploads.length > limitNumberUploads) {
                            lawsVn.showMessage({ messages: ['Vui lòng chọn tối đa ' + limitNumberUploads + ' file đính kèm (PDF, word, ảnh).'] });
                            return;
                        }
                        for (; index < fileUploads.length; index++) {
                            fileNameExt = fileUploads[index].name.split('.').pop().toLowerCase();
                            if (validExtensions.indexOf(fileNameExt) == -1) {
                                lawsVn.showMessage({ messages: ['Vui lòng chọn file đính kèm (PDF, word, ảnh).'] });
                                return;
                            }
                            if (fileUploads[index].size / 1024 / 1024 > maxSize) {
                                lawsVn.showMessage({ messages: ['Dung lượng file đính kèm vượt quá ' + maxSize + 'MB cho phép.'] });
                                return;
                            }
                            formData.append('listFiles', fileUploads[index]);
                        }
                        $.ajax({
                            url: '/Ajax/UploadFileAttach',
                            type: 'POST',
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            xhr: function () {
                                var xhrUpload = $.ajaxSettings.xhr(),
                                    progress = $('#progress_container_ku8ufw'),
                                    progressBar = $('#progress_bar_835j9x');
                                progress.show();
                                if (xhrUpload.upload) {
                                    xhrUpload.upload.addEventListener('progress',
                                        function (evt) {
                                            if (evt.lengthComputable) {
                                                var percentComplete = Math.round((evt.loaded * 100) / evt.total);
                                                progressBar.css({
                                                    'width': percentComplete + '%',
                                                    'background-color': '#49c5c7'
                                                });
                                            }
                                        },
                                        false);
                                    xhrUpload.addEventListener("progress",
                                        function (evt) {
                                            if (evt.lengthComputable) {
                                                var percentComplete = Math.round((evt.loaded * 100) / evt.total);
                                                setTimeout(function () {
                                                    progress.hide();
                                                    progressBar.css({
                                                        'width': 100 - percentComplete + '%',
                                                        'background-color': 'none'
                                                    });
                                                },
                                                    1000);
                                            }
                                        },
                                        false);
                                }
                                return xhrUpload;
                            },
                            success: function (resp) {
                                if (resp.Completed) {
                                    if (resp.Data != null && resp.Data.length > 0) {
                                        var fileName = '';
                                        for (var i = 0; i < resp.Data.length; i++) {
                                            var fileId = Math.random().toString(36).substring(7);
                                            if (resp.Data[i].FilePath != null && resp.Data[i].FilePath.length > 0) {

                                                $('#filePath_pw9l69')
                                                    .append(
                                                        '<input type="hidden" name="FilePath" data-id="' +
                                                        fileId +
                                                        '" value="' +
                                                        resp.Data[i].FilePath +
                                                        '">');
                                            }
                                            if (resp.Data[i].FileName != null && resp.Data[i].FileName.length > 0) {
                                                fileName += '<p class="ptext2" style="color: #333;"><span class="img-text">' +
                                                    resp.Data[i].FileName +
                                                    '</span><span class="img-sce"></span><span class="del-img" title="Hủy file tải lên: ' +
                                                    resp.Data[i].FileName +
                                                    '" data-id="' +
                                                    fileId +
                                                    '">Hủy file tải lên</span></p>';
                                            }
                                        }
                                        if (fileName.length > 0)
                                            $('#attachment_name_fdk7tn').append(fileName).css('display', 'block');
                                    }
                                } else if (resp.Message != null && resp.Message.length > 0) {
                                    lawsVn.showMessage({ messages: [resp.Message] });
                                }
                            },
                            error: function () {
                                lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] });
                            }
                        });
                    } else {
                        lawsVn.showMessage({ messages: ['Quý khách vui lòng chọn tối đa ' + limitNumberUploads + ' file đính kèm.'] });
                    }
                }
            });
        $(document).on('click',
            'span.del-img',
            function () {
                var id = $(this).data('id');
                if (typeof id != 'undefined') {
                    $('input[type=hidden][name=FilePath][data-id="' + id + '"]').remove();
                    $(this).closest('p.ptext2').remove();
                    if ($('#attachment_name_fdk7tn p.ptext2').length == 0)
                        $('#attachment_name_fdk7tn').css('display', 'none');
                }
            });
        $(document).on('click',
            '.btn-close',
            function () {
                const form = $(this).closest('form')
                form.remove()
                $('#_gopy').addClass('target-hidden').removeClass('target-expanded');
            });
        $(document).on('click',
            '.guigopy-',
            function (e) {
                e.preventDefault();
                try {
                    var me = $(this);
                    grecaptcha.ready(function () {
                        grecaptcha.execute(clientId,
                            {
                                action: 'FeedBacksV2'
                            })
                            .then(function (token) {
                                $('#ReCaptchaTokenGopY').val(token);
                                me.closest('form').submit();
                            });
                    });
                } catch (e) {

                }
            });
        $('#ReverseEffect').lawsExists(function () {
            var messages = $(this).text();
            $('.ReverseEffect_').html('<span style="color: #bb6b0a;font-style: italic;">' + messages + '</span>');
            $('.ReverseEffect').append('<div class="item-meta" style="color: #bb6b0a;font-style: italic;">' + messages.replace('Khoản 4 -', 'Khoản 4-') + '</div>');
        });
        $('.btn-user-login, .btn-login').on('click', function () {
            overlay.trigger('click');
            $('.content-dropdown-login').addClass('show_dropdown');
        });
        $('.close-fix').on('click', function () {
            $('.content-dropdown-login').removeClass('show_dropdown');
        });
        $('.view-more2').on('click', function () {
            $('.menu-nav-sub2').addClass('show_hight');
        });
        $('.close-more2').on('click', function () {
            $('.menu-nav-sub2').removeClass('show_hight');
        });
        //var stickyCustomerNote = $('.stickygc');
        //if (stickyCustomerNote.length) {
        //    var stickygc = stickyCustomerNote.position().top;
        //    if ($(window).width() > 960) {
        //        lawsVn.stickyCustomerNote(stickyCustomerNote, stickygc);
        //        $(window).on('scroll', function () {
        //            lawsVn.stickyCustomerNote(stickyCustomerNote, stickygc);
        //        });
        //    }
        //    if ($(window).width() < 960) {
        //        lawsVn.stickyCustomerNote(stickyCustomerNote, stickygc);
        //        $(window).on('scroll', function () {
        //            lawsVn.stickyCustomerNote(stickyCustomerNote, stickygc);
        //        });
        //    }
        //}
        $(document).on('click', 'a.tooltip-docdetail', function (event) {

            event.preventDefault(); // Ngăn không cho link điều hướng trang
            // Lấy href của link và URL hiện tại
            var href = $(this).attr('href');
            var currentUrl = window.location.pathname;

            var targetId = href.split('#')[1];

            // Nếu URL trong href trùng với URL hiện tại
            if (href.includes(currentUrl)) {
                if (targetId) {
                    // Trích xuất phần số từ targetId (ví dụ: demuc1496506 -> 1496506)
                    var numberPart = targetId.replace(/[^\d]/g, ''); // Lấy phần số

                    // Tìm phần tử đầu tiên có thuộc tính data-id bằng với numberPart
                    var targetElement = $('[data-id="' + numberPart + '"]').first();

                    // Nếu phần tử tồn tại, cuộn tới phần tử đó
                    if (targetElement.length) {
                        $(this).parents('.ui-dialog-content').dialog('close');
                        $('html, body').animate({
                            scrollTop: targetElement.offset().top - 100
                        }, 500); // Thời gian cuộn (800ms)
                    } else {
                        console.log("Không tìm thấy phần tử với data-id = " + numberPart);
                    }
                } else {
                    console.log("Không tìm thấy ID trong href.");
                }
            } else {
                window.location.href = href;
            }
        })

        $(document).on('click', '.customer-note-copy', function () {
            var self = $(this), parent = self.closest('ul'), docItemId = parent.data('item-id'), $temp = $('<textarea>'),
                element = lawsVn.customerDocItemsNotes.filter(x => $(x).data('id') == docItemId)
            note = $(element).find('.div-noidung-gccn').first(),
                elementClone = element
            $('body').append($temp);
            $temp.val($(elementClone).contents().not($('.document-tip, .document-tip-r, .tooltip-button, .docitem-gccn, .popupRelate2')).text().trim()).select();
            document.execCommand('copy');
            self.html('<i class="ic icon-single-copy-04lvn"></i> Đã sao chép')
            setTimeout(() => {
                self.html('<i class="ic icon-single-copy-04lvn"></i> Sao chép')
            }, 1000)
            $temp.remove();
        })
        $(document).on('click', '#finish viewing user manual customer note', function () {
            luatVietnamStore.setItem('user_manual_note', {
                'finish': true
            })
            $('.div-hdsd').remove()
        })
        $(document).on('click', '#user-manual-customer-note-step-1', function () {
            $('.div-hdsd').addClass('target-hidden')
            $($('.div-hdsd')[1]).removeClass('target-hidden')
        })
        $(document).on('click', '#user-manual-customer-note-step-2', function () {
            $('.div-hdsd').addClass('target-hidden')
            const element = $($('.div-hdsd')[$('.div-hdsd').length - 1])
            element.removeClass('target-hidden')
            $(window).scrollTop(element.offset().top - 180)
        })
        $(document).on('click', '#finish-viewing-user-manual-customer-note', function () {
            luatVietnamStore.setItem('user_manual_note_customer_note', {
                'finish': true
            })
            $('.div-hdsd').remove()
        })
        $(document).on('click', 'a.effect-tracking', function () {
            const self = $(this), parent = self.closest('ul'),
                docId = $('#chidanthaydoi').data('id'), docItemId = parent.data('item-id')
            lawsVn.fetchData(
                {
                    url: '/ajax/adddocitemcustomer',
                    dataType: 'json',
                    type: 'post',
                    data: { docId: docId, docItemId: docItemId },
                    beforeSend: function () { },
                    always: function () { }
                }).then((response) => {
                    if (response.Message != null && response.Message.length > 0) {
                        lawsVn.showMessage({ messages: [response.Message] });
                    }
                    if (response != null && response.Data != null) {
                        lawsVn.processDocItemCustomerButton(response.Data.Id)
                        self.removeClass('effect-tracking').addClass('cancel-tracking-effect active').html('<i class="iconlvn-bookmark-outline"></i> Hủy theo dõi')
                    }

                    setTimeout(lawsVn.logs.docViewLogs(docId, 1, 'theodoidieukhoan'), 300);
                })
                .catch((error) => {
                    console.error(error)
                })
        })
        $(document).on('click', 'a.effect-trackings-all', function () {
            const docId = $('#chidanthaydoi').data('id')
            lawsVn.fetchData(
                {
                    url: '/ajax/AddDocItemCustomerBy',
                    dataType: 'json',
                    type: 'post',
                    data: { docId: docId },
                    beforeSend: function () { },
                    always: function () { }
                }).then((response) => {
                    if (response.Message != null && response.Message.length > 0) {
                        lawsVn.showMessage({ messages: [response.Message] });

                        const docItemCustomer = $('#chidanthaydoind').find('div.docitem-13').first()
                        if (docItemCustomer) {
                            $('.tooltip-button.effect-tracking').remove()
                            const docAnalyzyButton = $(docItemCustomer).find('.bg_phantich').first(),
                                customerNoteButton = $(docItemCustomer).find('.tooltip-button.note').first(),
                                htmlButton = `<div class="tooltip-button effect-tracking-all">
				                                <span class="bg-theo-doi-hieu-luc">Đang theo dõi</span>
				                                <div class="tooltip-chidan">
					                                <div class="tooltip-boxs">
						                                <div class="text-theo-doi">Bạn đang theo dõi tất cả điều khoản văn bản này.  Các thay đổi về nội dung như sửa đổi, bổ sung, thay thế, bãi bỏ, đính chính... của điều khoản sẽ được thông báo cho bạn. </div>
	                                                    <div class="text-theo-doi">Để huỷ theo dõi tất cả điều khoản, bạn vui lòng <a href="javascript:void(0)" data-id="0" class="cancel-tracking-effect" title="Hủy theo dõi">click Huỷ theo dõi</a>. </div>
					                                </div>
				                                </div>
			                                </div>`

                            $(docItemCustomer).find('.tooltip-button.effect-tracking').remove()
                            if (docAnalyzyButton.length > 0) {
                                docAnalyzyButton.after(htmlButton);
                            } else if (customerNoteButton.length > 0) {
                                $(customerNoteButton).before(htmlButton);
                            } else {
                                $(docItemCustomer).append(htmlButton)
                            }

                            $('.effect-tracking, .cancel-tracking-effect', $('.tooltip-content-1'))
                                .removeAttr('class')
                                .addClass('tracked-doc-effect active')
                                .html('<i class="iconlvn-bookmark-outline"></i> Đang theo dõi')
                        }
                        //$('#chidanthaydoind div[class^="docitem"]').each(function (index, item) {
                        //    lawsVn.processDocItemCustomerButton($(item).data('id'))
                        //    $(item).find('a.effect-tracking').addClass('cancel-tracking-effect active').html('<i class="iconlvn-bookmark-outline"></i> Hủy theo dõi')
                        //})
                    }
                })
                .catch((error) => {
                    console.error(error)
                })
        })
        $(document).on('change', '#customerDocs_5um68a24ji', function () {
            const docId = $('#chidanthaydoi').data('id'), self = $(this), isSave = self.is(':checked'),
                btnDoc = self.closest('.document-item').find('.btn-doc').first(),
                urlRequest = isSave ? '/ajax/AddDocItemCustomerBy' : '/ajax/docitemcustomerremove'

            lawsVn.fetchData(
                {
                    url: urlRequest,
                    dataType: 'json',
                    type: 'post',
                    data: { id: 0, docId: docId },
                    beforeSend: function () { },
                    always: function () { }
                }).then((response) => {
                    if (response.Message != null && response.Message.length > 0) {
                        lawsVn.showMessage({ messages: [response.Message] });

                        if (!isSave) {
                            $('.tooltip-button.effect-tracking-all').remove()
                            $('.tracked-doc-effect')
                                .addClass('effect-tracking')
                                .removeClass('tracked-doc-effect')
                                .removeClass('active')
                                .html('<i class="iconlvn-bookmark-outline"></i> Theo dõi điều khoản')
                        }
                        else {
                            const docItemCustomer = $('#chidanthaydoind').find('div.docitem-13').first()
                            if (docItemCustomer) {
                                $('.tooltip-button.effect-tracking').remove()
                                const docAnalyzyButton = $(docItemCustomer).find('.bg_phantich').first(),
                                    customerNoteButton = $(docItemCustomer).find('.tooltip-button.note').first(),
                                    htmlButton = `<div class="tooltip-button effect-tracking-all">
				                                <span class="bg-theo-doi-hieu-luc">Đang theo dõi</span>
				                                <div class="tooltip-chidan">
					                                <div class="tooltip-boxs">
						                                <div class="text-theo-doi">Bạn đang theo dõi tất cả điều khoản văn bản này.  Các thay đổi về nội dung như sửa đổi, bổ sung, thay thế, bãi bỏ, đính chính... của điều khoản sẽ được thông báo cho bạn. </div>
	                                                    <div class="text-theo-doi">Để huỷ theo dõi tất cả điều khoản, bạn vui lòng <a href="javascript:void(0)" data-id="0" class="cancel-tracking-effect" title="Hủy theo dõi">click Huỷ theo dõi</a>. </div>
					                                </div>
				                                </div>
			                                </div>`

                                $(docItemCustomer).find('.tooltip-button.effect-tracking').remove()
                                if (docAnalyzyButton.length > 0) {
                                    docAnalyzyButton.after(htmlButton);
                                } else if (customerNoteButton.length > 0) {
                                    $(customerNoteButton).before(htmlButton);
                                } else {
                                    $(docItemCustomer).append(htmlButton)
                                }

                                $('.effect-tracking, .cancel-tracking-effect', $('.tooltip-content-1'))
                                    .removeAttr('class')
                                    .addClass('tracked-doc-effect active')
                                    .html('<i class="iconlvn-bookmark-outline"></i> Đang theo dõi')
                            }
                        }
                        //$('#chidanthaydoind div[class^="docitem"]').each(function (index, item) {
                        //    lawsVn.processDocItemCustomerButton($(item).data('id'))
                        //    $(item).find('a.effect-tracking').addClass('cancel-tracking-effect active').html('<i class="iconlvn-bookmark-outline"></i> Hủy theo dõi')
                        //})
                        let respDocItemsCustomer
                        if (response.Data != null) {
                            luatVietnamStore.getItem('luatvietnam_customerdocs_' + response.Data.DocId + '_' + response.Data.CustomerId + '_' + response.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respDocItemsCustomer = response;
                                }
                            })

                            if (respDocItemsCustomer === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    response.Data.DocId +
                                    '_' +
                                    response.Data.CustomerId +
                                    '_' +
                                    response.Data.LanguageId,
                                    { 'documentSaved': 0, 'hasTrackedDocumentEffect': 0, 'hasEffectTrackingsAll': isSave ? 1 : 0 },
                                    15 * 60);
                            } else {
                                if (respDocItemsCustomer.hasEffectTrackingsAll === undefined) {
                                    respDocItemsCustomer.hasEffectTrackingsAll = 0
                                }

                                if (isSave && respDocItemsCustomer.hasEffectTrackingsAll < 1) {
                                    respDocItemsCustomer.hasEffectTrackingsAll++;
                                } else {
                                    if (respDocItemsCustomer.hasEffectTrackingsAll > 0)
                                        respDocItemsCustomer.hasEffectTrackingsAll--;
                                }

                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    response.Data.DocId +
                                    '_' +
                                    response.Data.CustomerId +
                                    '_' +
                                    response.Data.LanguageId,
                                    { 'documentSaved': respDocItemsCustomer.documentSaved, 'hasTrackedDocumentEffect': respDocItemsCustomer.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': respDocItemsCustomer.hasEffectTrackingsAll },
                                    15 * 60);
                            }

                            if (!isSave) {
                                if ($('.customer-docs:checked').length == 0) {
                                    btnDoc.removeClass('active unsave').addClass('save')
                                }
                            } else {
                                btnDoc.removeClass('save').addClass('active unsave')
                            }
                        }

                    }
                })
                .catch((error) => {
                    console.error(error)
                })
        })
        $(document).on('click', 'a.cancel-tracking-effect', function () {
            const self = $(this), parent = self.closest('ul'),
                docItemId = parent.data('item-id') || self.data('id'),
                docId = $('#chidanthaydoi').data('id')

            lawsVn.fetchData(
                {
                    url: '/ajax/docitemcustomerremove',
                    dataType: 'json',
                    type: 'post',
                    data: { id: docItemId, docId: docId },
                    beforeSend: function () { },
                    always: function () { }
                }).then((response) => {
                    if (response.Message != null && response.Message.length > 0) {
                        lawsVn.showMessage({ messages: [response.Message] });
                    }

                    if (docItemId > 0) {
                        const element = lawsVn.customerDocItemsNotes.filter(x => $(x).data('id') == docItemId),
                            effectTrackingTooltip = $(element).find('.cancel-tracking-effect.active')
                        $(element).find('.tooltip-button.effect-tracking').remove()
                        effectTrackingTooltip.removeClass('cancel-tracking-effect active').addClass('effect-tracking').html('<i class="iconlvn-bookmark-outline"></i> Theo dõi điều khoản')
                    } else {
                        $('.tooltip-button.effect-tracking-all').remove()
                        $('.tracked-doc-effect')
                            .addClass('effect-tracking')
                            .removeClass('tracked-doc-effect')
                            .removeClass('active')
                            .html('<i class="iconlvn-bookmark-outline"></i> Theo dõi điều khoản')

                        let respDocItemsCustomer
                        if (response.Data != null) {
                            luatVietnamStore.getItem('luatvietnam_customerdocs_' + response.Data.DocId + '_' + response.Data.CustomerId + '_' + response.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respDocItemsCustomer = response;
                                }
                            })

                            if (respDocItemsCustomer === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    response.Data.DocId +
                                    '_' +
                                    response.Data.CustomerId +
                                    '_' +
                                    response.Data.LanguageId,
                                    { 'documentSaved': 0, 'hasTrackedDocumentEffect': 0, 'hasEffectTrackingsAll': 0 },
                                    15 * 60);
                            } else {
                                if (respDocItemsCustomer.hasEffectTrackingsAll === undefined) {
                                    respDocItemsCustomer.hasEffectTrackingsAll = 0
                                }

                                if (respDocItemsCustomer.hasEffectTrackingsAll < 1) {
                                    respDocItemsCustomer.hasEffectTrackingsAll++;
                                } else {
                                    if (respDocItemsCustomer.hasEffectTrackingsAll > 0)
                                        respDocItemsCustomer.hasEffectTrackingsAll--;
                                }

                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    response.Data.DocId +
                                    '_' +
                                    response.Data.CustomerId +
                                    '_' +
                                    response.Data.LanguageId,
                                    { 'documentSaved': respDocItemsCustomer.documentSaved, 'hasTrackedDocumentEffect': respDocItemsCustomer.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': respDocItemsCustomer.hasEffectTrackingsAll },
                                    15 * 60);
                            }

                            $('#customerDocs_5um68a24ji').lawsExists(function () {
                                var btnDoc = $(this).closest('.document-item').find('.btn-doc').first();
                                $(this).prop('checked', false);
                                if (!$('#customerDocs_5um68a24jj').is(':checked')) {
                                    btnDoc.removeClass('active unsave').addClass('save');
                                }
                            });
                        }
                    }
                })
                .catch((error) => {
                    console.error(error)
                })
        })
        $(document).on('click', '.btn-download-ghi-chu', function (e) {
            var self = $(this), docId = self.data('id') || 0, docName = $('h1.the-document-title').first().text(),
                customerName = $('.name-user-text').attr('title') || ''

            if (docId > 0 && customerName.trim().length > 0) {
                window.location.href = `https://static.luatvietnam.vn/tai-ghi-chu-van-ban-${lawsVn.removeAccents(docName)}/${customerName}-d${docId}.aspx`
            }
        })
        $(document).on('click', '.link-popupghichu.create', function () {
            const self = $(this),
                parent = self.closest('ul'),
                docId = $('#chidanthaydoi').data('id'),
                docItemId = parent.attr('data-item-id'),
                element = lawsVn.customerDocItemsNotes.filter(x => $(x).attr('data-id') == docItemId),
                popup = $('#_popupghichu'),
                popupContent = popup.find('.popup-content').first();

            if (self.attr('requestRunning')) {
                lawsVn.showMessage({ messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...'] });
                return false;
            }

            self.attr('requestRunning', true);

            if (typeof docId != 'undefined' && typeof docItemId != 'undefined') {
                lawsVn.fetchData({
                    url: '/ajax/customernote',
                    type: 'get',
                    data: { docId: docId, docItemId: docItemId },
                    dataType: 'html',
                    beforeSend: function () { },
                    always: function () {
                        self.removeAttr('requestRunning');
                    }
                }).then((response) => {
                    if (response !== null && response.length > 0) {
                        popupContent.html(response);
                        const form = $('#CustomerNoteForm');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                        if ($(element).length > 0) {
                            const clone = $(element).clone();
                            clone.find('.document-tip, .document-tip-r, .tooltip-button, .docitem-gccn, .popupRelate2').remove();
                            $('.scrol-po', form).html(clone.html());
                        }
                        $('body').css('overflow', 'initial');
                        $(popup).removeClass('target-hidden');
                        $(popup).addClass('target-expanded').css('display', '');

                        setTimeout(lawsVn.logs.docViewLogs(docId, 1, 'ghichuvanban'), 300);
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        popupContent.html(
                            '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                    })
            }
        })
        $(document).on('click', '.link-popupghichu.edit, .btn-edit-ghi-chu', function () {
            const self = $(this), id = self.attr('data-id'),
                element = lawsVn.customerDocItemsNotes.filter(x => $(x).attr('data-id') == id),
                popup = $('#_popupeditghichu'),
                popupContent = popup.find('.popup-content').first();

            if (self.attr('requestRunning')) {
                lawsVn.showMessage({ messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...'] });
                return false;
            }

            self.attr('requestRunning', true);

            if (typeof id != 'undefined') {
                lawsVn.fetchData({
                    url: '/ajax/customereditnote',
                    type: 'get',
                    data: { docItemId: id },
                    dataType: 'html',
                    beforeSend: function () { },
                    always: function () {
                        self.removeAttr('requestRunning');
                    }
                }).then((response) => {
                    if (response !== null && response.length > 0) {
                        popupContent.html(response);
                        const form = $('#CustomerEditNoteForm');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                        if ($(element).length > 0) {
                            const clone = $(element).clone();
                            clone.find('.document-tip, .document-tip-r, .tooltip-button, .docitem-gccn, .popupRelate2').remove();
                            $('.scrol-po', form).html(clone.html());
                        }
                        $('body').css('overflow', 'initial');
                        $(popup).removeClass('target-hidden');
                        $(popup).addClass('target-expanded').css('display', '');

                        setTimeout(lawsVn.logs.docViewLogs(id, 1, 'ghichuvanban'), 300);
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        popupContent.html(
                            '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                    })
            }
        })
        $(document).on('click', '#sticky-customer-note, .btn-edit-ghi-chu.all, .btn-popupghichu', function () {
            const self = $(this), parent = self.closest('.tab-content'), id = parent.data('id'),
                docName = parent.data('title'),
                popup = $('#_popupghichu_vanban'),
                popupContent = popup.find('.popup-content').first()

            //if (!self.hasClass('btn-edit-ghi-chu') && !self.hasClass('stickyghichu') && parent.find('.tooltip-chidan.posi-right').length > 0) {
            //    return false;
            //}

            //if (self.attr('requestRunning')) {
            //    lawsVn.showMessage({ messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...'] });
            //    return false;
            //}

            self.attr('requestRunning', true);

            if (typeof id != 'undefined') {
                lawsVn.fetchData({
                    url: '/ajax/customerdocnote',
                    type: 'get',
                    data: { docId: id, docName: docName },
                    dataType: 'html',
                    beforeSend: function () { },
                    always: function () {
                        self.removeAttr('requestRunning');
                    }
                }).then((response) => {
                    if (response !== null && response.length > 0) {
                        popupContent.html(response);
                        const form = $('#CustomerDocNoteForm');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);

                        $('body').css('overflow', 'initial');
                        $(popup).removeClass('target-hidden');
                        $(popup).addClass('target-expanded').css('display', '');

                        setTimeout(lawsVn.logs.docViewLogs(id, 1, 'ghichuvanban'), 300);
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        popupContent.html(
                            '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                    })
            }
        })
        $(document).on('click', '.customer-remove-note', function () {
            const self = $(this), docItemId = self.attr('data-id')

            if (typeof docItemId != 'undefined') {
                lawsVn.showMessage({
                    buttons: [{
                        Name: 'Đóng',
                        ClassName: 'btn-law',
                        ClickEvent: function () { }
                    },
                    {
                        Name: 'Đồng ý',
                        ClassName: 'btn-law-ok',
                        ClickEvent: function () {
                            lawsVn.fetchData(
                                {
                                    url: '/ajax/customerremovenote',
                                    data: { id: docItemId },
                                    dataType: 'json',
                                    type: 'POST',
                                    beforeSend: function () { },
                                    always: function () {
                                        self.removeAttr('requestRunning');
                                    }
                                })
                                .then(response => {
                                    if (response.Message != null && response.Message.length > 0) {
                                        lawsVn.showMessage({ messages: [response.Message] });
                                    }
                                    if (response.Completed) {
                                        const element = lawsVn.customerDocItemsNotes.filter(x => $(x).data('id') == docItemId)
                                        $(element).find('.tooltip-button.note').remove()
                                        $(element).find('.docitem-gccn').remove()
                                        lawsVn.processCustomerNoteTooltip(element)
                                        lawsVn.closePopup('#_popupeditghichu')
                                    }
                                })
                                .catch((error) => {
                                    console.error(error);
                                    lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] });
                                });
                        }
                    }],
                    messages: ['Xác nhận xóa ghi chú đã chọn ?']
                })
            }
        })
        $(document).on('click', '.tools-chidanvb', function () {
            document.getElementById("myctmcd").classList.toggle("show");
        })
        $(document).on('click', '.btn-remove-customer-doc', function () {
            const self = $(this), docId = self.data('id')

            if (typeof docId != 'undefined') {
                lawsVn.showMessage({
                    buttons: [{
                        Name: 'Đóng',
                        ClassName: 'btn-law',
                        ClickEvent: function () { }
                    },
                    {
                        Name: 'Đồng ý',
                        ClassName: 'btn-law-ok',
                        ClickEvent: function () {
                            lawsVn.fetchData(
                                {
                                    url: '/ajax/customerremovenotebydocId',
                                    data: { docId: docId },
                                    dataType: 'json',
                                    type: 'POST',
                                    beforeSend: function () { },
                                    always: function () {
                                        self.removeAttr('requestRunning');
                                    }
                                })
                                .then(response => {
                                    if (response.Message != null && response.Message.length > 0) {
                                        lawsVn.showMessage({ messages: [response.Message] });
                                    }
                                    if (response.Completed) {
                                        const stickyNote = $('#sticky-customer-note'), stickyNoteParent = stickyNote.closest('.tooltip-button');
                                        //stickyNoteParent.find('.tooltip-chidan.posi-right').remove();
                                        $('.tooltip-chidan.posi-right').remove();
                                        lawsVn.closePopup('#_popupghichu_vanban')
                                    }
                                })
                                .catch((error) => {
                                    console.error(error);
                                    lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] });
                                });
                        }
                    }],
                    messages: ['Xác nhận xóa ghi chú của văn bản đã chọn ?']
                })
            }
        })
        $(document).off('click', '[data-toggle-target-]').on('click', '[data-toggle-target-]', function (e) {
            e.preventDefault();
            var target = $(this).attr('data-toggle-target');
            if (typeof target != typeof undefined) {
                $('#myBtn').show();
                $('body').css('overflow', 'initial');
                $(target).addClass('target-hidden');
                $(target).toggleClass('target-expanded').css('display', '');
            }
        });
        $(window).scroll(function () {
            var tabContent = $('.tab-content');
            if (tabContent.length > 0) {
                var panneltop = tabContent.offset().top,
                    stickyCustomerNote = $('.stickygc');

                if ($(window).scrollTop() >= panneltop) {
                    $('#doc-sticky').addClass('doc-sticky');
                    $('#doc-sticky .the-tab-panel').addClass('visible-title');
                }
                else {
                    $('#doc-sticky').removeClass('doc-sticky');
                    $('#stickpannel').height('');
                    $('#doc-sticky .the-tab-panel').removeClass('visible-title');
                }

                if (stickyCustomerNote.length) {
                    if ($('#doc-sticky').hasClass('doc-sticky')) {
                        stickyCustomerNote.addClass('stickyghichu')
                    } else {
                        stickyCustomerNote.removeClass('stickyghichu')
                    }
                }
            }
        });
        $('.google-login').googleLogin({ accountInfoType: 2 });
        $('.facebook-login').facebookLogin({ accountInfoType: 2 });
        $('form#RegisterFormTarget').on('submit', function (e) {
            lawsValidate.termsAndConditions();
            return lawsVn.CheckboxTermsAndConditionsRequired();
        });
        $('[id*=TermsAndConditions]').click(function () {
            lawsVn.CheckboxTermsAndConditionsRequired();
        });
        $(document).click(function (event) {
            var widget = $('#vanbantacdong'), container = $('.box_wg_vb2', widget), popup = $('.tooltip-boxs', widget);
            if (!$(event.target).closest(container).length) {
                popup.slideUp("fast");
            }
        });
        $(document).on('click', '.tabs-login-item', function () {
            $('.tabs-login-item, .tabs-login-content').removeClass('active');
            $(this).addClass('active');
            $(`#${$(this).data('tab')}`).addClass('active');
            $(`.tabs-login-content[data-content="${$(this).data('content')}"]`).addClass('active');
        })
        $(document).on('click',
            '.dk-dich',
            function (e) {
                e.preventDefault();
                var me = $(this), parent = me.closest('.col-info2');
                parent.find('.lea-dk').lawsExists(function () {
                    $(this).toggleClass('hidden');
                });
            });
        $(document).on('click', '.register-account',
            function (e) {
                e.preventDefault();
                $('.tab-nav a[data-content="dangky"]').lawsExists(function () {
                    $(this).addClass('tab-active');
                });
                $('li[data-content="dangky"]').lawsExists(function () {
                    $(this).addClass('tab-active');
                });
                $('.tab-nav a[data-content="dangnhap"]').lawsExists(function () {
                    $(this).removeClass('tab-active');
                });
                $('li[data-content="dangnhap"]').lawsExists(function () {
                    $(this).removeClass('tab-active');
                });
            });
        $(document).on('click',
            '.yeucaudichmay',
            function (e) {
                e.preventDefault();
                var me = $(this),
                    parent = me.closest('.col-info2'),
                    docId = $('input:hidden[name="DocId"]', parent),
                    docFileId = $('input:hidden[name="DocFileId"]', parent),
                    filePath = $('input:hidden[name="FilePath"]', parent), countMyTranslations = $('#countMyTranslations'),
                    count = parseInt(countMyTranslations.text().replace(/[^\d]/g, ''), 10);
                if (!$.isNumeric(count))
                    count = 0;
                if (typeof docId !== 'undefined' &&
                    typeof docFileId !== 'undefined' &&
                    typeof filePath !== 'undefined') {
                    if (me.attr('requestRunning')) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                        });
                        return false;
                    }
                    me.attr('requestRunning', true);
                    $.lawsAjax({
                        type: 'Post',
                        url: lawsVn.virtualPath('/ajax/DocumentsMachineTranslation'),
                        data: { docId: docId.val(), docFileId: docFileId.val(), filePath: filePath.val() },
                        success: function (response) {
                            if (response.Completed) {
                                parent.find('.lea3').lawsExists(function () {
                                    $(this).remove();
                                });
                                parent.find('#dichmaytudong').lawsExists(function () {
                                    $(this).remove();
                                });
                                parent.append('<div class="lea4">' +
                                    '<img class="circle-03 fa-spin" src="/assets/images/circle-03.svg">Văn bản đang được dịch máy tự động, Quý khách có thể truy cập <span class="a-crum"> <a href="/giao-dien-ca-nhan.html" title="Quản lý tài khoản" target="_blank">"Quản lý tài khoản</a> <span class="ic icon-small-rightlvn iccrum"></span> <a href="/user/ban-dich-may-cua-toi.html" title="Bản dịch máy của tôi" target="_blank">Bản dịch máy của tôi"</a></span> để kiểm tra tiến trình dịch hoặc nhấp vào liên kết dưới đây:</div>' +
                                    '<div class="link-site"><a href="/user/ban-dich-may-cua-toi.html" target="_blank"><span class="ic icon-attachlvn ic5"></span>https://luatvietnam.vn/user/ban-dich-may-cua-toi.html</a></div>');
                                count++;
                                countMyTranslations.data('count', count);
                                countMyTranslations.text('(' + count + ')');
                            } else if (response.Message != null && response.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [response.Message]
                                });
                            }
                        },
                        always: function () {
                            me.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                        }
                    });
                }
            });
        $(document).on('click',
            '.english-translation-required',
            function (e) {
                var me = $(this), root = me.closest('.box-content'), name = me.data('name'), url = me.data('url');
                e.preventDefault();
                if (typeof name !== 'undefined' && typeof url !== 'undefined') {
                    $.lawsAjax({
                        type: 'post',
                        url: lawsVnConfig.rootPath + 'Ajax/EnglishTranslationRequired',
                        data: { docName: name, docUrl: url },
                        success: function (resp) {
                            if (resp.Completed) {
                                root.find('.btn_vb').remove();
                                root.append('<div class="btn_vb_text">' +
                                    '<p style="font-size: 14px;"><strong>Yêu cầu của Quý khách đã được gửi đi!</strong></p>' +
                                    '<p><em>Cảm ơn Quý khách đã quan tâm và sử dụng phần mềm!</em></p>' +
                                    '</div>');
                            }
                            else if (resp.Message != null && resp.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [resp.Message]
                                });
                            }
                        }
                    });
                } else {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Quý khách vui lòng thử lại sau.']
                    });
                }
            });
        $(document).on('click',
            '.xoa-bandichmay',
            function (e) {
                var me = $(this), id = me.data('id');
                e.preventDefault();
                if (confirm('Xác nhận xóa bản dịch máy đã chọn ?')) {
                    if (typeof id !== 'undefined') {
                        $.lawsAjax({
                            type: 'post',
                            url: lawsVn.virtualPath('/Ajax/ConviLawRequestRemove'),
                            data: { conviLawRequestId: id },
                            success: function (resp) {
                                if (resp.Completed) {
                                    location.reload(true);
                                }
                                else if (data.Message != null && data.Message.length > 0) {
                                    var username = '';
                                    if (data.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                                        data.Message = data.Message.replace(/"/g, "'");
                                        var str = data.Message.match(/'(.*?)'/g);
                                        if (str != null) username = str[1];
                                    }
                                    $().lawsDialog({
                                        messages: [
                                            username.length > 0
                                                ? 'Tài khoản: <b>' +
                                                username +
                                                '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                                                : data.Message
                                        ],
                                        dialogClass: 'lawsVnDialogTitle',
                                        showIcon: false
                                    });
                                }
                            }
                        });
                    } else {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách vui lòng thử lại sau.']
                        });
                    }
                }
            });
        $('.btn-readmore').click(function () {
            $('.sumary-tacgia').toggleClass('show-more', 300, 'easeInQuad');
        }).toggle(function () {
            $(this).text('Rút gọn');
        }, function () {
            $(this).text('Xem thêm');
        });
        $(document).on('click', '.down-vb', function () {
            var addressValue = $(this).attr("href");
            lawsVn.logs.webpagelogs("downloadfile", pageUrl, pageTitle, source, addressValue);
        });
        $(document).on({
            mouseenter: function (e) {
                var me = $(this),
                    dd = me.children('.dropdown-tips-content-2.downloadfile'),
                    left = 0,
                    contentEntry = me.closest('.content-left'),
                    maincontentOffset = $('.main-content').offset(),
                    contentEntryRight = maincontentOffset.left + contentEntry.outerWidth(),
                    isLogin = false;
                $('.hearder-right').find('.btn-user-login').lawsExists(function () {
                    isLogin = true;
                });
                if (isLogin) {
                    left = (e.pageX - maincontentOffset.left) / 2;
                    if (e.pageX + 100 > contentEntryRight) {
                        left = e.pageX - 420;
                    }
                    $('.dropdown-tips-content-2.downloadfile').css('visibility', 'hidden');
                    if (dd.length === 0) {
                        me.append('<div class="dropdown-tips-content-2 downloadfile" style="visibility:visible;left:' +
                            left +
                            'px;top:' +
                            (e.pageY - 90) +
                            'px"><div class="tooltip-boxs">' +
                            '<div class="form-login-hd fix-font">Quý khách vui lòng <a href="#" data-toggle-target="#login-form-target" class="login-action" style="font-size:13px !important;text-decoration: none !important;font-weight:bold;"> Đăng nhập</a> tài khoản LuatVietnam để tải file.</div>' +
                            '</div></div>');
                    }
                    dd.css({ left: left, top: e.pageY - 90, visibility: 'visible' });
                }
            }, mouseleave: function () {
                var isLogin = false;
                isLogin = false;
                $('.hearder-right').find('.btn-user-login').lawsExists(function () {
                    isLogin = true;
                });
                if (isLogin) {
                    $('.dropdown-tips-content-2.downloadfile', $(this)).css('visibility', 'hidden');
                }
            }
        }, '.btnDownloadFileLogin');
        $(document).on({
            mouseenter: function (e) {
                var me = $(this),
                    dd = me.children('.dropdown-tips-content-2.downloadfile'),
                    left = 0,
                    contentEntry = me.closest('.content-left'),
                    maincontentOffset = $('.main-content').offset(),
                    contentEntryRight = maincontentOffset.left + contentEntry.outerWidth(),
                    isLogin = false, isRole = false;
                $('.hearder-right').find('.btn-user-login').lawsExists(function () {
                    isLogin = true;
                });
                $('.user_myluat_acount').lawsExists(function () {
                    if (typeof $(this).data('r') === 'undefined') {
                        isRole = true;
                    }
                });
                if (isLogin || isRole) {
                    left = (e.pageX - maincontentOffset.left) / 2;
                    if (e.pageX + 100 > contentEntryRight) {
                        left = e.pageX - 420;
                    }
                    $('.dropdown-tips-content-2.downloadfile').css('visibility', 'hidden');
                    if (dd.length === 0) {
                        me.append('<div class="dropdown-tips-content-2 downloadfile" style="visibility:visible;left:' +
                            left +
                            'px;top:' +
                            (e.pageY - 90) +
                            'px"><div class="tooltip-boxs">' +
                            '<div class="form-login-hd fix-font">Quý khách vui lòng <a href="javascript:void(0)" rel="nofollow" data-toggle-target="#login-form-target" class="login-action" style="font-size:13px !important;text-decoration: none !important;font-weight:bold;"> Đăng nhập</a> tài khoản LuatVietnam để tải file.</div>' +
                            '</div></div>');
                    }
                    dd.css({ left: left, top: e.pageY - 90, visibility: 'visible' });
                }
            }, mouseleave: function () {
                var isRole = false;
                $('.user_myluat_acount').lawsExists(function () {
                    if (typeof $(this).data('r') !== 'undefined') {
                        isRole = true;
                    }
                });
                if (isRole) {
                    $('.dropdown-tips-content-2.downloadfile', $(this)).css('visibility', 'hidden');
                }
            }
        }, '.btnDownloadFileRole');
        lawsVn.docComment($('#doc-comment'));
        $(document).on('click',
            '.doc-comment-more',
            function () {
                var me = $(this), docComment = me.closest('.box-text'), content = docComment.find('.box-text-content');
                if (me.text().trim() == 'Hiển thị thêm') {
                    me.html('Thu gọn <i class="ic icon-small-up-2lvn"></i>').attr('title', 'Thu gọn');
                    docComment.addClass('textfull'), content.addClass('textfull');
                } else {
                    me.html('Hiển thị thêm <i class="ic icon-small-down-2lvn"></i>').attr('title', 'Hiển thị thêm');
                    docComment.removeClass('textfull'), content.removeClass('textfull');
                }
            });
        $(document).on('mouseenter', '.tooltip-relate', function (event) {
            var div_relate = $(this).find('.div-relate');
            if (div_relate) {
                div_relate.show();
            }
        });

        $(document).on('mouseleave', '.tooltip-relate', function (event) {
            $(this).find('.div-relate').hide();
        });
        var isTooltipHovered = false;
        $(document).on('mouseenter', '.tooltip-data', function (e) {
            var tooltipType = $(this).data("tooltip-type");
            var dataTooltip = $(this).data("title");
            var tooltipWindow = $('.tooltip-main');

            $('.tooltip-main').fadeIn(100).css({
                left: e.clientX + 'px',
                top: e.clientY + 'px',
            }).html(dataTooltip);
        });

        $(document).on('mouseleave', '.tooltip-data', function (e) {
            setTimeout(function () {
                if (!isTooltipHovered) {
                    $('.tooltip-main').fadeOut(100);
                }
            }, 100);
        });
        $(document).on('mouseenter', '.tooltip-main', function () {
            isTooltipHovered = true;
            $('.tooltip-main').fadeIn(100); // Giữ tooltip hiển thị
        });

        $(document).on('mouseleave', '.tooltip-main', function () {
            isTooltipHovered = false;
            $('.tooltip-main').fadeOut(100);
        });
        $('#ConsultingQuestionsWithFeeForm').lawsExists(function () {
            var cookieValue = lawsVn.getValueFromCookie('ConsultingQuestionsWithFee');
            if (cookieValue.length > 0) {
                var fullname = cookieValue['FullName'],
                    email = cookieValue['CustomerEmail'],
                    mobile = cookieValue['PhoneNumber'],
                    address = cookieValue['Address'];
                if (typeof fullname !== 'undefined') {
                    $(this).find(':input[name=FullName]').val(fullname);
                }
                if (typeof email !== 'undefined') {
                    $(this).find(':input[name=CustomerEmail]').val(email);
                }
                if (typeof mobile !== 'undefined') {
                    $(this).find(':input[name=PhoneNumber]').val(mobile);
                }
                if (typeof address !== 'undefined') {
                    $(this).find(':input[name=Address]').val(address);
                }
            }
        });
        $("#taive").find("a").click(function () {
            var addressValue = $(this).attr("href");
            lawsVn.logs.webpagelogs("downloadfile", pageUrl, pageTitle, source, addressValue);
        });
        $('#gotoConsultingQuestionsWithFee').click(function () {
            $('html, body').animate({
                scrollTop: $('.btn-gui').offset().top
            }, 300);
        });
        $(document).on('click',
            '.indulieu',
            function (event) {
                event.preventDefault();
                $('#indulieu').lawsExists(function () {
                    try {
                        var printContent = $(this),
                            cssLink = $('link'),
                            printWindow = window.open('',
                                '',
                                'height=' + window.outerHeight * 0.6 + ', width=' + window.outerWidth * 0.6);
                        printWindow.document.write('<html><head><title>luatvietnam.vn</title>');
                        for (var i = 0; i < cssLink.length; i++) {
                            printWindow.document.write(cssLink[i].outerHTML);
                        }
                        printWindow.document.write('<link rel="stylesheet" type="text/css" href="/assets/print.css">');
                        printWindow.document.write('</head><body >');
                        printWindow.document.write(
                            '<div class="hearder-logo-print1"><div class="logo-print"><img alt="luat viet nam" src="' +
                            lawsVn.virtualPath('/assets/images/logo.png') +
                            '"></div></div>');
                        printWindow.document.write(printContent.html());
                        printWindow.document.write('</body></html>');
                        printWindow.document.close();
                        printWindow.onload = function () {
                            printWindow.focus();
                            setTimeout(function () {
                                printWindow.print();
                                printWindow.close();
                            },
                                100);
                        }
                    } catch (e) {
                        console.log(e);
                    }
                });
            });
        $(document).bind('click', function (t) {
            var n = $(t.target);
            if (!n.parents().hasClass('btn-dropdown1'))
                $('.btn-dropdown1 .content-drop').hide();
            //log position and time
            localStorage.setItem("preTop", t.clientY + window.scrollY);
            localStorage.setItem("preLeft", t.clientX);
            localStorage.setItem("ppTimeEnd", Number(new Date()));
            localStorage.setItem("preWidth", $(window).width());
            localStorage.setItem("preHeight", Math.max($(document).height(), $(window).height()));
            var domtext = "";
            var tagName = t.target.tagName.toLowerCase();
            if (tagName == "a" || tagName == "button" || tagName == "span" || tagName == "label")
                domtext = "[" + t.target.tagName + "] " + t.target.textContent.trim();
            localStorage.setItem("preDom", domtext);
            var index = 0;
            if (typeof t.target.getAttribute("data-index") != 'undefined')
                index = t.target.getAttribute("data-index");
            localStorage.setItem("preItem", index);
        });
        $(document).bind('click',
            function (t) {
                var n = $(t.target);
                if (!n.parents().hasClass('btn-dropdown1')) $('.btn-dropdown1 .btn-toggle1').removeClass('active');
            });
        $(document).on('click', '.show-sapolvn',
            function (e) {
                e.preventDefault();
                $('input[type="hidden"][name="ShowSapo"]').lawsExists(function () {
                    $(this).val(0);
                });
                $('.search-filter').find('form').trigger('submit');
            });
        $(document).on('click', '.login-action',
            function (e) {
                e.preventDefault();
                var target = $(this).attr('data-toggle-target');
                if (typeof target !== 'undefined') {
                    $(target).addClass('target-hidden');
                    $(target).toggleClass('target-expanded').css('display', '');
                }
            });
        $(document).on('click', '.hide-sapolvn',
            function (e) {
                e.preventDefault();
                $('input[type="hidden"][name="ShowSapo"]').lawsExists(function () {
                    $(this).val(1);
                });
                $('.search-filter').find('form').trigger('submit');
            });
        $(document).on('click', '.show-sapolvn2',
            function (e) {
                e.preventDefault();
                $('input[type="hidden"][name="showSapo"]').lawsExists(function () {
                    $(this).val(1);
                });
                $(this).closest('form').trigger('submit');
            });
        $(document).on('click', '.hide-sapolvn2',
            function (e) {
                e.preventDefault();
                $('input[type="hidden"][name="showSapo"]').lawsExists(function () {
                    $(this).val(0);
                });
                $(this).closest('form').trigger('submit');
            });
        $('input.paramKeywords').on('keypress keyup blur',
            function () {
                $('.searchByParam').trigger('click');
            });
        $('input#ol2xfnhovh').on('keypress keyup blur',
            function () {
                var me = $(this), keywords = lawsVn.KhongDau(me.val().toLowerCase());
                $('#searchFieldContent').lawsExists(function () {
                    $(this).find('.scrollbar-content').css({ 'top': '0' });
                });
                var listFields = $('input[id^="FieldIdVb_"]');
                if (listFields.length > 0) {
                    for (var index = 0; index < listFields.length; index++) {
                        var field = $(listFields[index]),
                            fieldName = field.data('name');
                        if (typeof $(fieldName) !== 'undefined') {
                            fieldName = lawsVn.KhongDau(fieldName).toLowerCase();
                            if (fieldName.indexOf(keywords) == -1) {
                                field.closest('.statistic-field-rows').hide();
                            } else {
                                field.closest('.statistic-field-rows').show();
                            }
                        }
                    }
                }
            });
        $('input#nhaz5ksz9i').on('keypress keyup blur',
            function () {
                var me = $(this), keywords = lawsVn.KhongDau(me.val().toLowerCase());
                $('#searchFieldContent').lawsExists(function () {
                    $(this).find('.scrollbar-content').css({ 'top': '0' });
                });
                var listOrgans = $('input[id^="OrganItem_"]');
                if (listOrgans.length > 0) {
                    for (var index = 0; index < listOrgans.length; index++) {
                        var organ = $(listOrgans[index]),
                            organName = organ.data('name');
                        if (typeof $(organName) !== 'undefined') {
                            organName = lawsVn.KhongDau(organName).toLowerCase();
                            if (organName.indexOf(keywords) == -1) {
                                organ.closest('.statistic-field-rows').hide();
                            } else {
                                organ.closest('.statistic-field-rows').show();
                            }
                        }
                    }
                }
            });
        $(document).on('click', '.block-list-title',
            function (e) {
                //e.preventDefault();
                var self = $(this),
                    next = self.next();
                if (!self.hasClass("div-tooltip")) {
                    next.slideToggle();
                    self.parent().toggleClass('block-list-open');
                }
            });
        $('.btn-redirect').on("click", function (e) {
            e.preventDefault();
            var url = $(this).data('target');
            location.replace(url);
        });
        $(document).on('click',
            '.popup-bg',
            function (e) {
                if (e.target == this) {
                    if ($('.popup-bg').is(':visible')) {
                        if (event.target.id != 'login-form-target') {
                            $('.popup-bg').hide();
                            if ($('body').hasClass('modal-open')) {
                                $('body').removeClass('modal-open');
                            }
                            $('.tab-nav a[data-content="dangky"]').lawsExists(function () {
                                $(this).removeClass('tab-active');
                            });
                            $('li[data-content="dangky"]').lawsExists(function () {
                                $(this).removeClass('tab-active');
                            });
                            $('.tab-nav a[data-content="dangnhap"]').lawsExists(function () {
                                $(this).addClass('tab-active');
                            });
                            $('li[data-content="dangnhap"]').lawsExists(function () {
                                $(this).addClass('tab-active');
                            });
                            $('#LoginFormTarget').lawsExists(function () {
                                var form = $(this);
                                form.clearForm();
                                form.find('input').removeClass('boder_red').removeClass('boder_green');
                                form.find('.icon-validator').remove();
                                form.find(':input').each(function () {
                                    switch (this.type) {
                                        case 'password':
                                        case 'select-multiple':
                                        case 'select-one':
                                        case 'text':
                                        case 'textarea':
                                            $(this).val('');
                                            break;
                                        case 'checkbox':
                                        case 'radio':
                                            this.checked = false;
                                    }
                                });
                            });
                            $('#RegisterFormTarget').lawsExists(function () {
                                var form = $(this);
                                form.clearForm();
                                form.find('input').removeClass('boder_red').removeClass('boder_green');
                                form.find('.icon-validator').remove();
                                form.find(':input').each(function () {
                                    switch (this.type) {
                                        case 'password':
                                        case 'select-multiple':
                                        case 'select-one':
                                        case 'text':
                                        case 'textarea':
                                            $(this).val('');
                                            break;
                                        case 'checkbox':
                                        case 'radio':
                                            this.checked = false;
                                    }
                                });
                            });
                        }
                        $('button.btn_tk').removeClass('active');
                        $('#leftboxContent').lawsExists(function () {
                            $(this).css({ 'zIndex': 998 });
                        });
                        $('#tabPannel').lawsExists(function () {
                            $(this).css({ 'zIndex': 998 });
                        });
                        $('.btn.next33').lawsExists(function () {
                            $(this).css({ 'zIndex': 998 });
                        });
                        $('.btn.prev33').lawsExists(function () {
                            $(this).css({ 'zIndex': 998 });
                        });
                        $('#closePopup').lawsExists(function () {
                            $(this).find('a').text('Mục Lục');
                            $('#mucluc').lawsExists(function () {
                                $(this).hide();
                            });
                        });
                        $('#closePopup2').lawsExists(function () {
                            $(this).find('a').text('Mục Lục');
                            $('#mucluc2').lawsExists(function () {
                                $(this).hide();
                            });
                        });
                        $('#closePopup3').lawsExists(function () {
                            $(this).find('a').text('Mục Lục');
                            $('#mucluc3').lawsExists(function () {
                                $(this).hide();
                            });
                        });
                        $('.wrapper-yeucaubosungvb').lawsExists(function () {
                            $(this).show();
                        });
                        $('.thongbao-send').lawsExists(function () {
                            $(this).closest('.popup-wrapper').css('width', '600px');
                            $(this).empty();
                        });
                    }
                }
            });
        $('.close-popup, .close-chuthich').click(function (e) {
            $('#leftboxContent').lawsExists(function () {
                $(this).css({ 'zIndex': 998 });
            });
            $('#tabPannel').lawsExists(function () {
                $(this).css({ 'zIndex': 998 });
            });
            $('.btn.next33').lawsExists(function () {
                $(this).css({ 'zIndex': 998 });
            });
            $('.btn.prev33').lawsExists(function () {
                $(this).css({ 'zIndex': 998 });
            });

            $('html').css({ overflow: '' });
            $('body').css({ overflow: '' });
        });
        $('.btn.close-popup2').click(function () {
            $('.tab-nav a[data-content="dangky"]').lawsExists(function () {
                $(this).removeClass('tab-active');
            });
            $('li[data-content="dangky"]').lawsExists(function () {
                $(this).removeClass('tab-active');
            });
            $('.tab-nav a[data-content="dangnhap"]').lawsExists(function () {
                $(this).addClass('tab-active');
            });
            $('li[data-content="dangnhap"]').lawsExists(function () {
                $(this).addClass('tab-active');
            });
            $('#LoginFormTarget').lawsExists(function () {
                var form = $(this);
                form.clearForm();
                form.find('input').removeClass('boder_red').removeClass('boder_green');
                form.find('.icon-validator').remove();
                form.find(':input').each(function () {
                    switch (this.type) {
                        case 'password':
                        case 'select-multiple':
                        case 'select-one':
                        case 'text':
                        case 'textarea':
                            $(this).val('');
                            break;
                        case 'checkbox':
                            break;
                        case 'radio':
                            this.checked = false;
                    }
                });
            });
            $('#RegisterFormTarget').lawsExists(function () {
                var form = $(this);
                form.clearForm();
                form.find('input').removeClass('boder_red').removeClass('boder_green');
                form.find('.icon-validator').remove();
                form.find(':input').each(function () {
                    switch (this.type) {
                        case 'password':
                        case 'select-multiple':
                        case 'select-one':
                        case 'text':
                        case 'textarea':
                            $(this).val('');
                            break;
                        case 'checkbox':
                        case 'radio':
                            this.checked = false;
                    }
                });
            });
        });
        this.widgetUser();
        $(document).on('click',
            '#closePopup2',
            function (e) {
                e.preventDefault();
                var seft = $(this), link = seft.find('a');
                seft.closest('.fix_ghichu2').css({ 'zIndex': 9999999 });
                if (link.find('img').length) {
                    link.text('Mục Lục');
                    $('#mucluc2').lawsExists(function () {
                        $(this).hide();
                    });
                } else {
                    link.html('<img src="/assets/images/x.png" alt="close">');
                    $('#mucluc2').lawsExists(function () {
                        $(this).show();
                    });
                }
            });
        $(document).on('click',
            '.vb-khong-co-nd',
            function (event) {
                event.preventDefault();
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Văn bản không có nội dung download']
                });
            });
        $('.overlayLink').click(function (event) {
            event.preventDefault();
            var p = $('.main-content');
            if (p.length) {
                var position = p.position();
                $('div.overlay > div.login-wrapper').css('margin-left', position.left + 'px');
            }
            $('.login-wrapper, .overlay').show(300);
            //$('.overlay').fadeToggle('fast');
        });

        $(".close").click(function () {
            $('.login-wrapper, .overlay').hide(300);
        });
        $("#showmucluc").click(function () {
            var x = document.getElementById("xemthem_mucluc");
            if (x.style.display === "none") {
                $('#xemthem_mucluc').show(300);
                $('#showmucluc').html('Thu gọn');
            } else {
                $('#xemthem_mucluc').hide(300);
                $('#showmucluc').html('Hiển thị thêm');
            }

        });
        $(document).keyup(function (e) {
            if (e.keyCode == 27 && $(".overlay").css("display") != "none") {
                event.preventDefault();
                $('.login-wrapper, .overlay').hide(300);
                //$(".overlay").fadeToggle("fast");
            }
        });
        $(document).on('click', '.btn-yeucau-bandich', function (e) {
            e.preventDefault();
            var me = $(this),
                parent = me.closest('.btn_vb'),
                form = $('#DocumentsTranslationRequiredForm'),
                el = form.closest('.lea-dk2'),
                docId = me.data('id'),
                customerId = me.data('customer'),
                customerRequestedDocTranslation;
            if (typeof docId !== 'undefined' && typeof customerId !== 'undefined') {
                luatVietnamStore.getItem('luatvietnam_documents_translation_required_' + docId + '_' + customerId,
                    function (response) {
                        if (response !== null) {
                            customerRequestedDocTranslation = response;
                        }
                    });
                if (typeof customerRequestedDocTranslation == 'undefined') {
                    el.lawsExists(function () {
                        parent.lawsExists(function () {
                            $(this).remove();
                        });
                        $(this).removeClass('hidden');
                    });
                } else {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Quý khách đã yêu cầu dịch văn bản này trước đó.']
                    });
                    return false;
                }
            }
        })
        $(document).on('click',
            '.btn-dichuan',
            function (e) {
                e.preventDefault();
                var me = $(this),
                    parent = me.closest('.col-info2'),
                    el = parent.find('.lea-dk2').first(),
                    docId = me.data('id'),
                    customerId = me.data('customer'),
                    customerRequestedDocTranslation;
                if (typeof docId !== 'undefined' && typeof customerId !== 'undefined') {
                    luatVietnamStore.getItem('luatvietnam_documents_translation_required_' + docId + '_' + customerId, function (response) {
                        if (response !== null) {
                            customerRequestedDocTranslation = response;
                        }
                    });
                    if (typeof customerRequestedDocTranslation == 'undefined') {
                        el.lawsExists(function () {
                            $(this).toggleClass('hidden');
                        });
                        parent.find('.lea-dk3').lawsExists(function () {
                            $(this).remove();
                        });
                    } else {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách đã yêu cầu dịch chuẩn cho văn bản này trước đó.']
                        });
                        return false;
                    }
                }
            });
        $(document).on('click',
            '.socialShare, .socialShare2',
            function (e) {
                e.preventDefault();
                var social = $(this).data('social');
                var shareUrl;
                var quote = "";
                var url = $(this).data('url');
                //var picture = "";
                if (typeof ($(this).data('quote')) != 'undefined') {
                    quote = $(this).data('quote');
                }
                //if (typeof ($(this).data('picture')) != 'undefined') {
                //    picture = $(this).data('picture'); 
                //}
                switch (social) {
                    case 'facebook':
                        {
                            shareUrl = 'https://www.facebook.com/sharer/sharer.php?u=';
                            quote = '&quote=' + quote;
                            //picture = '&picture=' + picture;
                            break;
                        }
                    case 'gplus':
                        {
                            shareUrl = 'https://plus.google.com/share?url=';
                            quote = '';
                            //picture = '';
                            break;
                        }
                    case 'twitter':
                        {
                            shareUrl = 'https://twitter.com/share?url=';
                            //quote = '&text=' + quote;
                            //picture = '&picture=' + picture;
                            break;
                        }
                    default:
                        {
                            shareUrl = '';
                            break;
                        }
                }
                if (shareUrl !== '') {
                    if (typeof url !== 'undefined')
                        shareUrl = shareUrl + url + quote;
                    else shareUrl = shareUrl + document.URL.replace('/private/', '/') + quote; // + picture
                    var winTop = (screen.height / 2) - (350 / 2);
                    var winLeft = (screen.width / 2) - (600 / 2);
                    var socialWindow = window.open(shareUrl,
                        'social-popup',
                        'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,top=' +
                        winTop +
                        ',left=' +
                        winLeft +
                        ',height=350,width=600');
                    if (socialWindow.focus) {
                        socialWindow.focus();
                    }
                }
                return false;
            });
        $(document).on('click',
            '.lawsVnLogin',
            function (event) {
                event.preventDefault();
                lawsVn.login();
            });
        $(document).on('click',
            '.btn-back',
            function (event) {
                event.preventDefault();
                var me = $(this);
                $(this).closest('.popup-bg').lawsExists(function () {
                    $(this).hide();
                });
            });
        $(document).on('click',
            '.forgot-password',
            function (event) {
                event.preventDefault();
                lawsVn.forgotPassword();
            });
        $('.doc-properties').tooltip({
            //content: 'Vui lòng đợi...',
            track: true,
            content: function (response) {
                var id = this.id;
                var splitId = id.split('-');
                var languageId = splitId[1];
                var docId = splitId[2];
                $.ajax({
                    url: lawsVn.virtualPath('/Ajax/GetDocProperties'),
                    data: { docId: docId, languageId: languageId },
                    type: 'Post'
                })
                    .then(function (data) {
                        response(data);
                    });
            },
            items: "*"
        });
        $('.no-permission-download').tooltip();
        $('.no-permission').tooltip({
            content: function () {
                return $(this).prop('title');
            },
            position: {
                at: 'center bottom',
                my: 'left top'
            },
            show: {
                effect: "slideDown",
                delay: 250
            },
            close: function (event, ui) {
                ui.tooltip.hover(
                    function () {
                        $(this).stop(true).fadeTo(400, 1);
                    },
                    function () {
                        $(this).fadeOut("400",
                            function () {
                                $(this).remove();
                            });
                    });
            }
        });
        $('.no-permission-s').tooltip({
            content: function () {
                return $(this).prop('title');
            },
            position: {
                at: 'center bottom',
                my: 'left top'
            },
            show: {
                effect: "slideDown",
                delay: 250
            },
            close: function (event, ui) {
                ui.tooltip.hover(
                    function () {
                        $(this).stop(true).fadeTo(400, 1);
                    },
                    function () {
                        $(this).fadeOut("400",
                            function () {
                                $(this).remove();
                            });
                    });
            }
        });
        $('.chuthich-tooltip').tooltip({
            content: function () {
                return $(this).prop('title');
            },
            tooltipClass: 'chu-thich',
            track: true,
            show: {
                effect: "slideDown",
                delay: 100
            },
            open: function (event, ui) {
                ui.tooltip.css({
                    'max-width': '150px',
                    'line-height': '20px'
                });
            },
            close: function (event, ui) {
                ui.tooltip.hover(
                    function () {
                        $(this).stop(true).fadeTo(200, 1);
                    },
                    function () {
                        $(this).fadeOut("200",
                            function () {
                                $(this).remove();
                            });
                    });
            }
        });
        $('.chuthich-vbthaydoi').tooltip({
            content: function () {
                return $(this).prop('title');
            },
            position: {
                at: 'center bottom',
                my: 'left top+10'
            },
            show: {
                effect: "slideDown",
                delay: 250
            },
            open: function (event, ui) {
                ui.tooltip.css({
                    'max-width': '200px',
                    'line-height': '20px'
                });
            },
            close: function (event, ui) {
                ui.tooltip.hover(
                    function () {
                        $(this).stop(true).fadeTo(400, 1);
                    },
                    function () {
                        $(this).fadeOut("400",
                            function () {
                                $(this).remove();
                            });
                    });
            }
        });
        $('.chuthich-vbthaydoi2').tooltip({
            content: function () {
                return $(this).prop('title');
            },
            position: {
                my: "center top",
                at: "right top+10"
            },
            show: {
                effect: "slideDown",
                delay: 250
            },
            open: function (event, ui) {
                ui.tooltip.css({
                    'max-width': '200px',
                    'line-height': '20px'
                });
            },
            close: function (event, ui) {
                ui.tooltip.hover(
                    function () {
                        $(this).stop(true).fadeTo(400, 1);
                    },
                    function () {
                        $(this).fadeOut("400",
                            function () {
                                $(this).remove();
                            });
                    });
            }
        });
        $('.no-permission-view').tooltip({
            content: function () {
                return $(this).prop('title');
            },
            position: {
                at: 'center bottom',
                my: 'left top'
            },
            show: {
                effect: "slideDown",
                delay: 250
            },
            close: function (event, ui) {
                ui.tooltip.hover(
                    function () {
                        $(this).stop(true).fadeTo(400, 1);
                    },
                    function () {
                        $(this).fadeOut("400",
                            function () {
                                $(this).remove();
                            });
                    });
            }
        });
        $(document).on('click',
            '.sendMailBT',
            function (event) {
                event.preventDefault();
                //var docUrl = $(this).data('url');
                lawsVn.docRegistMail();
            });
        $(document).on('click',
            '.sendMailVanbanCNHT',
            function (event) {
                event.preventDefault();
                $.lawsAjax({
                    type: 'Post',
                    url: lawsVn.virtualPath('/Ajax/CustomerRegisterNewsLetterEmail'),
                    success: function (resp) {
                        if (resp.Completed) {
                            if (resp.Message != null && resp.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [resp.Message]
                                });
                            }
                        } else if (resp.Message != null && resp.Message.length > 0) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [resp.Message]
                            });
                        }
                    }
                });
            });
        $(document).on('click',
            '.gop-y',
            function (event) {
                event.preventDefault();
                var docName = $(this).data('name');
                lawsVn.gopy(docName);
            });
        $(document).on('click',
            '.baoloi, .report-error',
            function (event) {
                event.preventDefault();
                var docId = $(this).data('id') || 0, docName = $(this).data('name'), docUrl = window.location.href.split('?')[0];

                $.lawsAjax({
                    type: 'Get',
                    async: true,
                    dataType: 'html',
                    url: lawsVn.virtualPath('/Ajax/PartialReportError'),
                    success: function (resp) {
                        if (resp.length > 0) {
                            $('#_reporterror').find('.popup-content').first().html(resp);
                            $('#ReportErrorForm #DocId').lawsExists(function () {
                                $(this).val(docId);
                            });
                            $('#ReportErrorForm .doc-name').lawsExists(function () {
                                $(this).attr("href", docUrl).text(docName);
                            });
                            $('#ReportErrorForm input[type="hidden"][name="Title"]').lawsExists(function () {
                                $(this).val(docName);
                            });
                            var form = $('#ReportErrorForm');
                            form.removeData('validator');
                            form.removeData('unobtrusiveValidation');
                            $.validator.unobtrusive.parse(form);
                            $('#_reporterror').removeClass('target-hidden').addClass('target-expanded');
                        }
                    }
                });
            });
        $(document).on('click',
            '.docPrint',
            function (event) {
                event.preventDefault();
                $('#docPrint').lawsExists(function () {
                    $(this).printThis({
                        pageTitle: 'Luật Việt Nam',
                        header:
                            '<div class="hearder-logo-print"><div class="logo-print"><img alt="luat viet nam" src="' +
                            lawsVn.virtualPath('/assets/images/logo.png') +
                            '"></div></div>',
                        loadCSS: lawsVn.virtualPath('/assets/print.css')
                    });
                });
            });
        //$(document).on('click',
        //    '#tangfont_sr09u89nys, .iconlvn-fontsize-a2',
        //    function () {
        //        var target = $('#article-content');
        //        lawsVn.setFontSize(target, 1 / 0.8);
        //    });
        //$(document).on('click',
        //    '#giamfont_5u5ytn9fre, .iconlvn-fontsize-a1',
        //    function () {
        //        var target = $('#article-content');
        //        lawsVn.setFontSize(target, 0.8);
        //    });
        $(document).on('click',
            '.doc-send-mail',
            function (event) {
                event.preventDefault();
                var docId = $(this).data('id'), docUrl = $(this).data('url'), docName = $(this).data('title');
                $.lawsAjax({
                    type: 'Get',
                    async: true,
                    dataType: 'html',
                    url: lawsVn.virtualPath('/Ajax/PartialDocSendMailResponsive'),
                    success: function (resp) {
                        if (resp.length > 0) {
                            $('#_sendemail').find('.entry-popup').first().html(resp);
                            $('#DocSendMailForm #DocId').lawsExists(function () {
                                $(this).val(docId);
                            });
                            $('#DocSendMailForm #DocUrl').lawsExists(function () {
                                $(this).attr("href", docUrl).text(docName);
                            });
                            $('#DocSendMailForm #DocName').lawsExists(function () {
                                $(this).val(docName);
                            });
                            var form = $('#DocSendMailForm');
                            form.removeData('validator');
                            form.removeData('unobtrusiveValidation');
                            $.validator.unobtrusive.parse(form);
                            $('#_sendemail').removeClass('target-hidden').addClass('target-expanded');
                        }
                    }
                });
            });
        $('.lawsVnChangePassword').off('click').on('click',
            function (event) {
                event.preventDefault();
                lawsVn.changePassword();
            });
        $('.lawsVnLogOut').off('click').on('click',
            function (event) {
                event.preventDefault();
                lawsVn.logOut();
            });
        $(document).off('click', '.btn-submit').on('click',
            '.btn-submit',
            function (event) {
                event.preventDefault();
                $(this).closest('form').submit();
            });
        $(document).on('click',
            '.view-ismq',
            function (e) {
                e.preventDefault();
                $('.the-document-download.ismq').toggleClass('target-hidden');
            });
        $(document).on('click',
            '.click-envent-btn',
            function (e) {
                e.preventDefault();
                var parent = $(this).closest('.box1-popup-content');
                $(this).toggleClass('fix_mo_rong');
                var title = $(this).attr('title') == 'Thu gọn danh mục chỉ dẫn' ? 'Mở rộng danh mục chỉ dẫn' : 'Thu gọn danh mục chỉ dẫn';
                $(this).attr('title', title);
                parent.lawsExists(function () {
                    var col1 = $(this).find('.popupclum_1'), col2 = $(this).find('.popupclum_2');
                    col1.lawsExists(function () {
                        $(this).toggleClass('hidden fix_mo_rong');
                    });
                    col2.lawsExists(function () {
                        $(this).toggleClass('fix_mo_rong');
                    });
                });
            });
        $(document).on('click',
            '.dong-nd-bi-suadoi, .nd-duoc-hd-thugon',
            function (e) {
                e.preventDefault();
                $('.nd-duoc-hd-thugon').toggleClass('hidden');
                $('.click-envent-btn').toggleClass('hidden');
                $('.nd-bi-suadoi').toggleClass('hidden');
                $('.nd-suadoi').toggleClass('popup_col2_full');
                $('.scrollbar-content').lawsExists(function () {
                    $(this).css('top', 0);
                });
                $('.scrollbar-handle').lawsExists(function () {
                    $(this).css('top', 0);
                });
            });
        $(document).on('click',
            '.dong-nd-bi-suadoi-m',
            function (e) {
                e.preventDefault();
                var content = '', el = $('.noidung1col').find('.noidungthaydoi');
                if (el.children().length === 0) {
                    $('.nd-suadoi').find('.noidung_100.fix-top0').lawsExists(function () {
                        content = $(this).html();
                        el.html(content);
                    });
                }

                $('.noidung1col').lawsExists(function () {
                    $(this).removeClass('hidden');
                });
                $('.noidung2cols').lawsExists(function () {
                    $(this).addClass('hidden');
                });
            });
        $(document).on('click',
            '.dong-nd-duoc-huongdan-m',
            function (e) {
                e.preventDefault();
                $('.noidung2cols').lawsExists(function () {
                    $(this).addClass('hidden');
                });
                $('.tonghop-content').lawsExists(function () {
                    $(this).addClass('hidden');
                });
                $('.noidung1col').find('.col-1').lawsExists(function () {
                    $(this).removeClass('hidden');
                });
                $('.noidung1col').lawsExists(function () {
                    $(this).removeClass('hidden');
                });
            });
        $(document).on('click',
            '.docitemrelate-parent',
            function (e) {
                e.preventDefault();
                var me = $(this);
                var title = me.attr('title') == 'Thu gọn danh mục chỉ dẫn' ? 'Mở rộng danh mục chỉ dẫn' : 'Thu gọn danh mục chỉ dẫn';
                me.attr('title', title);
                if (me.hasClass('opendownlvn')) {
                    me.removeClass('opendownlvn').addClass('openuplvn');
                } else if (me.hasClass('openuplvn')) {
                    me.removeClass('openuplvn').addClass('opendownlvn');
                }
                $('.docitemrelate-child').lawsExists(function () {
                    $(this).toggleClass('hidden');
                });
            });
        $(document).on('click',
            '#vanbantacdong :checkbox[name=DocIds]',
            function () {
                var box = $('.theo-doi-vbmix');
                if ($('#vanbantacdong :checkbox[name=DocIds]:checked').length > 0) {
                    box.removeClass('hidden');
                } else {
                    box.addClass('hidden');
                }
            });
        $(document).on('click',
            '.parent-docItemId',
            function (event) {
                event.preventDefault();
                var me = $(this), id = me.data('id'),
                    icon = me.find('.docitem-parent-icon'),
                    chuong = me.children('.li-chuong'),
                    title = icon.attr('title') == 'Thu gọn' ? 'Mở rộng' : 'Thu gọn';
                icon.lawsExists(function () {
                    $(this).attr('title', title);
                    if ($(this).hasClass('opendownlvn')) {
                        $(this).removeClass('opendownlvn').addClass('openuplvn');
                    } else if ($(this).hasClass('openuplvn')) {
                        $(this).removeClass('openuplvn').addClass('opendownlvn');
                    }
                });
                if (chuong.length > 0) {
                    $('.parent-docItemId .li-chuong').removeClass('dropdown_active5');
                    chuong.addClass('dropdown_active5');
                }

                if (typeof id !== 'undefined') {
                    var el = $($('.' + id)[0]);
                    if (el.hasClass('hidden')) {
                        $('.' + id).removeClass('hidden');
                    } else {
                        $('.' + id).addClass('hidden');
                    }
                }
            });
        $(document).on('click',
            '.dang-ky-dv',
            function (event) {
                event.preventDefault();
                var serviceId = $(this).data('id'), urlRedirect = '/dich-vu.html';
                if (serviceId == 36 || serviceId == 37) {
                    urlRedirect = '/pldn/dich-vu.html';
                }
                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/KiemTraDvDangKy'),
                    data: { serviceId: serviceId },
                    success: function (resp) {
                        if (resp.Completed) {
                            if (resp.Data != null) {
                                if (resp.Data.IsRegistService < 1) { //chưa đăng ký dịch vụ
                                    if (resp.Data.ActionButton === 'Register') {
                                        if (resp.Data.FeeType === 'Free') {
                                            //window.location.href =
                                            //    lawsVn.virtualPath('/user/dang-ky-goi-dich-vu-mien-phi.html');
                                            lawsVn.account.registerFreeService(serviceId);
                                        } else if (resp.Data.FeeType === 'Trial') {
                                            //lawsVn.account.registerTrialService(serviceId);
                                        } else if (resp.Data.FeeType === 'Sub') {
                                            window.location.href = lawsVn.virtualPath(
                                                '/dich-vu.html');
                                        }
                                    } else if (resp.Data.ActionButton === 'ExpiredTrial') {
                                        if (resp.Data.FeeType === 'Trial') {
                                            window.location.href = lawsVn.virtualPath(urlRedirect);
                                        }
                                    }
                                } else { //đã đăng ký dịch vụ: hiện thông báo tương ứng
                                    if (resp.Data.FeeType === 'Free' ||
                                        resp.Data.FeeType === 'Trial' ||
                                        resp.Data.ActionButton === '') {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [
                                                resp.Data.Messages +
                                                '<br/><a href="' +
                                                lawsVn.virtualPath('/dich-vu.html') +
                                                '" title="Đăng ký phần mềm" style="color:#a67942">Đăng ký phần mềm</a>'
                                            ]
                                        });
                                        // 
                                    } else if (resp.Data.ActionButton === 'NoAction') {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [resp.Data.Messages]
                                        });
                                    } else if (resp.Data.ActionButton === 'ReNew' ||
                                        resp.Data.ActionButton === 'ReNewAndConvert') {
                                        var buttons = [
                                            {
                                                text: 'Gia hạn',
                                                'class': 'btn-nhap-lai dv',
                                                click: function () {
                                                    window.location.href =
                                                        lawsVn.virtualPath(urlRedirect);
                                                }
                                            },
                                            {
                                                text: 'Chuyển đổi',
                                                'class': 'btn-nhap-lai dv',
                                                click: function () {
                                                    window.location.href =
                                                        lawsVn.virtualPath(urlRedirect);
                                                }
                                            },
                                            {
                                                text: 'Đóng',
                                                'class': 'btn-nhap-lai dv2',
                                                click: function () {
                                                    $(this).dialog('close');
                                                }
                                            }
                                        ];
                                        //Không hỗ trợ nâng cấp dịch vụ - hiển thị button Gia hạn
                                        if (resp.Data.ActionButton === 'ReNew') {
                                            buttons.splice(1, 1);
                                        }
                                        var msg = '<div class="from-thong-bao-4">' +
                                            '<div class="content-thongbao">' +
                                            '<div class="rows-thongbao">' +
                                            resp.Data.Messages +
                                            '</div>' +
                                            '</div>' +
                                            '</div>';
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            width: 520,
                                            messages: [msg],
                                            onCreate: function () {
                                                var elem = $('.content-thongbao');
                                                elem.removeAttr('width');
                                                elem.css('width', '93.7%');
                                            },
                                            buttons: buttons
                                        });
                                    }
                                }
                            }
                        }
                    }
                });
            });
        $(document).on('click',
            '.dang-ky-dv-v2',
            function (event) {
                event.preventDefault();
                var serviceId = $(this).attr('data-serviceId'),
                    servicePackageId = $(this).attr('data-servicePackageId');
                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/KiemTraDvDangKyV3'),
                    data: { serviceId: serviceId },
                    success: function (resp) {
                        if (resp.Completed) {
                            if (resp.Data != null) {
                                var isAuthenticated = resp.Data.IsAuthenticated;
                                if (resp.Data.IsRegistService < 1) { //chưa đăng ký dịch vụ
                                    if (resp.Data.ActionButton === 'Register') {
                                        if (resp.Data.FeeType === 'Free') {
                                            //window.location.href =
                                            //    lawsVn.virtualPath('/user/dang-ky-goi-dich-vu-mien-phi.html');
                                            lawsVn.account.registerFreeService(serviceId);
                                        }
                                        else if (resp.Data.FeeType === 'Trial') {
                                            //lawsVn.account.registerTrialService(serviceId);
                                        }
                                        else if (resp.Data.FeeType === 'Sub') {
                                            window.location.href = lawsVn.virtualPath(
                                                '/user/dang-ky-goi-dich-vu.html?serviceId=' +
                                                serviceId +
                                                '&servicePackageId=' +
                                                servicePackageId + (isAuthenticated == 1 ? '&step=3' : '&step=2'));
                                        }
                                    } else if (resp.Data.ActionButton === 'ExpiredTrial') {
                                        if (resp.Data.FeeType === 'Trial') {
                                            window.location.href = lawsVn.virtualPath(
                                                '/user/dang-ky-goi-dich-vu.html?serviceId=' +
                                                serviceId +
                                                '&servicePackageId=' +
                                                servicePackageId + (isAuthenticated == 1 ? '&step=3' : '&step=2'));
                                        }
                                    }
                                } else { //đã đăng ký dịch vụ: hiện thông báo tương ứng
                                    if (resp.Data.FeeType === 'Free' ||
                                        resp.Data.FeeType === 'Trial' ||
                                        resp.Data.ActionButton === '') {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [
                                                resp.Data.Messages +
                                                '<br/><a href="' +
                                                lawsVn.virtualPath('/user/dang-ky-goi-dich-vu.html?serviceId=' +
                                                    serviceId +
                                                    '&servicePackageId=' +
                                                    servicePackageId + (isAuthenticated == 1 ? '&step=3' : '&step=2')) +
                                                '" title="' +
                                                lawsVn.Resource.getMessages('RegisterService') +
                                                '" style="color:#a67942">' +
                                                lawsVn.Resource.getMessages('RegisterService') +
                                                '</a>'
                                            ]
                                        });
                                        // 
                                    } else if (resp.Data.ActionButton === 'NoAction') {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [resp.Data.Messages]
                                        });
                                    } else if (resp.Data.ActionButton === 'ReNew' ||
                                        resp.Data.ActionButton === 'Convert') {
                                        var buttons = [
                                            {
                                                text: lawsVn.Resource.getMessages('Renewal'),
                                                'class': 'btn-nhap-lai dv',
                                                click: function () {
                                                    window.location.href =
                                                        lawsVn.virtualPath('/user/gia-han-dich-vu.html?serviceId=' +
                                                            serviceId +
                                                            '&servicePackageId=' +
                                                            servicePackageId + (isAuthenticated == 1 ? '&step=3' : '&step=2'));
                                                }
                                            },
                                            {
                                                text: lawsVn.Resource.getMessages('Convert'),
                                                'class': 'btn-nhap-lai dv',
                                                click: function () {
                                                    window.location.href =
                                                        lawsVn.virtualPath('/user/chuyen-doi-dich-vu.html?serviceId=' +
                                                            serviceId +
                                                            '&servicePackageId=' +
                                                            servicePackageId + (isAuthenticated == 1 ? '&step=3' : '&step=2'));
                                                }
                                            },
                                            {
                                                text: lawsVn.Resource.getMessages('Close'),
                                                'class': 'btn-nhap-lai dv2',
                                                click: function () {
                                                    $(this).dialog('close');
                                                }
                                            }
                                        ];
                                        //Gia hạn dịch vụ
                                        if (resp.Data.ActionButton === 'ReNew') {
                                            buttons.splice(1, 1);
                                        }
                                        //Chuyển đổi dịch vụ
                                        if (resp.Data.ActionButton === 'Convert') {
                                            buttons.splice(0, 1);
                                        }
                                        var msg = '<div class="from-thong-bao-4">' +
                                            '<div class="content-thongbao">' +
                                            '<div class="rows-thongbao">' +
                                            resp.Data.Messages +
                                            '</div>' +
                                            '</div>' +
                                            '</div>';
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            width: 520,
                                            messages: [msg],
                                            onCreate: function () {
                                                var elem = $('.content-thongbao');
                                                elem.removeAttr('width');
                                                elem.css('width', '93.7%');
                                            },
                                            buttons: buttons
                                        });
                                    }
                                }
                            }
                        }
                    }
                });
            });
        $(document).on('click',
            '.dang-ky-dv-v3',
            function (event) {
                event.preventDefault();
                var serviceId = $(this).attr('data-serviceid'),
                    servicePackageId = $(this).attr('data-servicepackageid');
                if (serviceId > 0 && servicePackageId > 0) {
                    window.location.href = lawsVn.virtualPath(
                        '/user/dang-ky-goi-dich-vu.html?serviceId=' +
                        serviceId +
                        '&servicePackageId=' +
                        servicePackageId);
                }
            });
        $(document).on('click',
            '.btn-xacnhan',
            function (event) {
                event.preventDefault();
                $(this).closest('form').submit();
            });

        $(document).on('click',
            '.fieldIdTCVN',
            function (e) {
                e.preventDefault();
                var fieldId = $(this).data('id');
                $('.fieldIdTCVN').removeClass('active');
                $(this).addClass('active');
                lawsVn.CustomerInterFaceTCVNC(fieldId);
                $("#ddlFieldTCVN")
                    .removeAttr('selected')
                    .find(':first') //find('[value=0]')
                    .attr('selected', 'selected');
            });
        $(document).on('click',
            '.page-minus',
            function (e) {
                e.preventDefault();
                var number = $('input[name="NumberOfPapers"]'), thanh_tien = $('.thanh-tien'), currentVal = parseInt(number.val()), pageNumbers = parseInt($('.so-trang').text());
                if (!isNaN(pageNumbers) && !isNaN(currentVal) && currentVal > 1) {
                    var total = currentVal - 1
                    number.val(total);
                    if (pageNumbers >= 1 && pageNumbers <= 10) {
                        thanh_tien.html(lawsVn.formatNumber(total * 50000, '.', '.') + '<sup>đ</sup>');
                    } else if (pageNumbers >= 11 && pageNumbers <= 20) {
                        thanh_tien.html(lawsVn.formatNumber(total * 100000, '.', '.') + '<sup>đ</sup>');
                    } else if (pageNumbers >= 21 && pageNumbers <= 30) {
                        thanh_tien.html(lawsVn.formatNumber(total * 150000, '.', '.') + '<sup>đ</sup>');
                    } else if (pageNumbers >= 31 && pageNumbers <= 40) {
                        thanh_tien.html(lawsVn.formatNumber(total * 200000, '.', '.') + '<sup>đ</sup>');
                    } else if (pageNumbers > 40) {
                        thanh_tien.html(lawsVn.formatNumber(total * pageNumbers * 4000, '.', '.') + '<sup>đ</sup>');
                    }
                } else {
                    number.val(1);
                }
            });
        $(document).on('click',
            '.page-plus',
            function (e) {
                e.preventDefault();
                var number = $('input[name="NumberOfPapers"]'), thanh_tien = $('.thanh-tien'), maxValue = number.attr('max'), currentVal = parseInt(number.val()), pageNumbers = parseInt($('.so-trang').text());
                if (!isNaN(pageNumbers) && !isNaN(currentVal)) {
                    if (currentVal < maxValue) {
                        var total = currentVal + 1;
                        number.val(total);
                        if (pageNumbers >= 1 && pageNumbers <= 10) {
                            thanh_tien.html(lawsVn.formatNumber(total * 50000, '.', '.') + '<sup>đ</sup>');
                        } else if (pageNumbers >= 11 && pageNumbers <= 20) {
                            thanh_tien.html(lawsVn.formatNumber(total * 100000, '.', '.') + '<sup>đ</sup>');
                        } else if (pageNumbers >= 21 && pageNumbers <= 30) {
                            thanh_tien.html(lawsVn.formatNumber(total * 150000, '.', '.') + '<sup>đ</sup>');
                        } else if (pageNumbers >= 31 && pageNumbers <= 40) {
                            thanh_tien.html(lawsVn.formatNumber(total * 200000, '.', '.') + '<sup>đ</sup>');
                        } else if (pageNumbers > 40) {
                            thanh_tien.html(lawsVn.formatNumber(total * pageNumbers * 4000, '.', '.') + '<sup>đ</sup>');
                        }
                    }
                } else {
                    number.val(1);
                }
            });
        $(document).on('click',
            '.close-popup-datmua',
            function (e) {
                e.preventDefault();
                $('html').css({ overflow: 'inherit' });
                $('body').css({ overflow: 'inherit' });
                $(this).closest('.ui-dialog-content').dialog('destroy').remove();
            });
        $(document).on('keyup change', 'input[name=NumberOfPapers]', function () {
            var _this = $(this);
            var min = parseInt(_this.attr('min')) || 1;
            var max = parseInt(_this.attr('max')) || 100000;
            var val = parseInt(_this.val()) || (min - 1);
            if (val > max || val < min)
                _this.val(min);
            var currentVal = parseInt(_this.val()), thanh_tien = '', pageNumbers = parseInt($('.so-trang').text()),
                don_gia = '';
            if (!isNaN(pageNumbers) && !isNaN(currentVal)) {
                if (pageNumbers >= 1 && pageNumbers <= 10) {
                    don_gia = '50.000<sup>đ</sup>/cuốn';
                    thanh_tien = lawsVn.formatNumber(currentVal * 50000, '.', '.');
                } else if (pageNumbers >= 11 && pageNumbers <= 20) {
                    don_gia = '100.000<sup>đ</sup>/cuốn';
                    thanh_tien = lawsVn.formatNumber(currentVal * 100000, '.', '.');
                } else if (pageNumbers >= 21 && pageNumbers <= 30) {
                    don_gia = '150.000<sup>đ</sup>/cuốn';
                    thanh_tien = lawsVn.formatNumber(currentVal * 150000, '.', '.');
                } else if (pageNumbers >= 31 && pageNumbers <= 40) {
                    don_gia = '200.000<sup>đ</sup>/cuốn';
                    thanh_tien = lawsVn.formatNumber(currentVal * 200000, '.', '.');
                } else if (pageNumbers > 40) {
                    don_gia = '4.000<sup>đ</sup>/trang';
                    thanh_tien = lawsVn.formatNumber(currentVal * pageNumbers * 4000, '.', '.');
                }
            }
            $('.don-gia').html(`
                    <p><strong>Đơn giá:</strong> ${don_gia}</p>
                    <p class="font-16"><strong>Tổng cộng: <span class="color-red thanh-tien">${thanh_tien}<sup>đ</sup></span></strong></p>
                `);
        });
        $(document).on('change',
            '#ckOrderFileRar',
            function () {
                var pageNumbers = $('.so-trang').text();
                $('#numberFile').hide();
                $('.don-gia').html(`
                    <p><strong>Đơn giá:</strong> 12.000<sup>đ</sup>/trang</p>
                    <p class="font-16"><strong>Tổng cộng: <span class="color-red">${lawsVn.formatNumber(pageNumbers * 12000, '.', '.')}<sup>đ</sup></span></strong></p>
                `);
            });

        $(document).on('change',
            '#ckOrderFileDoc',
            function () {
                $('#numberFile').show();
                var number = $('input[name="NumberOfPapers"]'), currentVal = parseInt(number.val()), thanh_tien = '', pageNumbers = parseInt($('.so-trang').text()),
                    don_gia = '';
                if (!isNaN(pageNumbers) && !isNaN(currentVal)) {
                    if (pageNumbers >= 1 && pageNumbers <= 10) {
                        don_gia = '50.000<sup>đ</sup>/cuốn';
                        thanh_tien = lawsVn.formatNumber(currentVal * 50000, '.', '.');
                    } else if (pageNumbers >= 11 && pageNumbers <= 20) {
                        don_gia = '100.000<sup>đ</sup>/cuốn';
                        thanh_tien = lawsVn.formatNumber(currentVal * 100000, '.', '.');
                    } else if (pageNumbers >= 21 && pageNumbers <= 30) {
                        don_gia = '150.000<sup>đ</sup>/cuốn';
                        thanh_tien = lawsVn.formatNumber(currentVal * 150000, '.', '.');
                    } else if (pageNumbers >= 31 && pageNumbers <= 40) {
                        don_gia = '200.000<sup>đ</sup>/cuốn';
                        thanh_tien = lawsVn.formatNumber(currentVal * 200000, '.', '.');
                    } else if (pageNumbers > 40) {
                        don_gia = '4.000<sup>đ</sup>/trang';
                        thanh_tien = lawsVn.formatNumber(currentVal * pageNumbers * 4000, '.', '.');
                    }
                }
                $('.don-gia').html(`
                    <p><strong>Đơn giá:</strong> ${don_gia}</p>
                    <p class="font-16"><strong>Tổng cộng: <span class="color-red thanh-tien">${thanh_tien}<sup>đ</sup></span></strong></p>
                `);
            });
        $(document).on('change',
            '#VATInvoiceTCVN',
            function () {
                if ($('input[type=checkbox][id="VATInvoiceTCVN"]').is(':checked')) {
                    $("#OrderTCVN_InfoVATInvoice").removeClass('invoice');
                }
                else {
                    $("#OrderTCVN_InfoVATInvoice").addClass('invoice');
                }
            });
        $(document).on('change', '#check-ndvb2',
            function () {
                const self = $(this), parent = self.closest('.block-ndvb')
                var allowedClasses = ["docitem-45", "docitem-46", "docitem-47", "docitem-49",
                    "docitem-51", "docitem-52", "docitem-53", "docitem-55", "docitem-57", "text-baibocumtu"];

                $('.div-relatevb-show').addClass('target-hidden')

                if ($('input[type=checkbox][id="check-ndvb2"]').is(':checked')) {

                    $('.popupRelateCutom, .popupRelate', parent).each(function (i, element) {
                        var hasAllowedClass = allowedClasses.some(function (allowedClass) {
                            return $(element).hasClass(allowedClass);
                        });
                        if (hasAllowedClass) {
                            if ($(element).find(".div-relatevb-show").length == 0) {
                                var content = $(element).attr('data-title');
                                if (content.length) {
                                    var div = $("<div>", { "class": "div-relatevb-show" });
                                    div.html(content);
                                    $(element).append(div);
                                }
                            } else {
                                $(element).find(".div-relatevb-show").removeClass('target-hidden');
                            }
                        }
                    });
                }
            });
        $(document).on('click',
            '.tab-dat-mua, .dat-mua',
            function (event) {
                event.preventDefault();
                var self = $(this), docId = self.data('id'), customerId = self.data('cid'), resultResponse;
                if (self.attr('requestRunning')) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                    });
                    return false;
                }
                if (typeof customerId == 'undefined') {
                    customerId = 0;
                }
                if (customerId > 0) {
                    luatVietnamStore.getItem('luatvietnam_order_tcvn_' + docId + '_' + customerId, function (response) {
                        if (response !== null) {
                            resultResponse = response;
                        }
                    });
                    if (typeof resultResponse != 'undefined') {
                        $().Alert({
                            success: true,
                            buttons: [{
                                Name: 'Có',
                                ClassName: 'btn-xoa',
                                ClickEvent: function () {
                                    $('.lvn-alert').lawsExists(function () {
                                        $(this).remove();
                                    });
                                    luatVietnamStore.removeItem('luatvietnam_order_tcvn_' + docId + '_' + customerId);
                                    self.trigger('click');
                                }
                            },
                            {
                                Name: 'Không',
                                ClassName: 'btn-noxoa',
                                ClickEvent: function () {
                                    $('.lvn-alert').lawsExists(function () {
                                        $(this).remove();
                                    });
                                    return;
                                }
                            }],
                            messages: ['<p class="pf14"><strong>Quý khách đã đặt mua Tiêu chuẩn quốc gia này trước đó. Xác nhận mua tiếp ?</strong></p>']
                        });
                        return;
                    }
                }
                if (typeof docId != 'undefined') {
                    var popup = $('#_dat_mua_tcvn');
                    self.attr('requestRunning', true);
                    $.lawsAjax({
                        type: 'Get',
                        async: true,
                        dataType: 'html',
                        url: lawsVn.virtualPath('/Ajax/PartialOrderTCVN'),
                        data: { docId: docId },
                        success: function (resp) {
                            if (resp.length > 0) {
                                popup.find('.content-po').first().html(resp);
                                var form = $('#OrderTCVNForm');
                                form.removeData('validator');
                                form.removeData('unobtrusiveValidation');
                                lawsValidate.RequiredIf();
                                $.validator.unobtrusive.parse(form);
                                popup.removeClass('target-hidden').addClass('target-expanded');
                            }
                        },
                        always: function () {
                            self.removeAttr('requestRunning');
                            $('#loading').fadeOut('normal');
                        }
                    });
                }
            });
        $(document).on('click', '.closessvb', function (event) {
            event.preventDefault();
            $('#_sosanhvb').toggleClass('target-expanded').css('display', '');
            $('html').css({ overflow: 'inherit' });
            $('body').css({ overflow: 'inherit' });
        });
        $(document).on('click',
            '.doc-so-sanhvb',
            function (event) {
                event.preventDefault();
                if (!lawsVn.isMobile()) {
                    sosanhvanban();
                }
            });
        
        $(document).on('click', '.songngu_increaseFontSize', async function () {
            //tangfont($("#_vbsongngu .l08fyuscmy"))
            const self = $(this), parent = self.closest('.vbsongngu-col2'), container = parent.find('.body-vbsongngu').first()
            try {
                if (!self.hasClass('disabled')) {
                    let timeOut
                    self.addClass('disabled')

                    if (fontSize < 25) {
                        fontSize++
                    }
                    await handleFontSize(container)
                    timeOut = setTimeout(function () {
                        self.removeClass('disabled')
                        clearTimeout(timeOut)
                    }, 200)
                }
            } catch (e) {
                console.log(e)
            }
        })
        $(document).on('click', '.songngu_decreaseFontSize', async function () {
            const self = $(this), parent = self.closest('.vbsongngu-col2'), container = parent.find('.body-vbsongngu').first()
            try {
                if (!self.hasClass('disabled')) {
                    let timeOut
                    self.addClass('disabled')

                    if (fontSize > 14) {
                        fontSize--
                    }
                    await handleFontSize(container)
                    timeOut = setTimeout(function () {
                        self.removeClass('disabled')
                        clearTimeout(timeOut)
                    }, 200)
                }
            } catch (e) {
                console.log(e)
            }
        })
        $(document).on('click', '#tang-font-vn', function () {
            tangfont($("#_vbsongngu .vbsongngu-vn"))
        })
        $(document).on('click', '#giam-font-vn', function () {
            giamfont($("#_vbsongngu .vbsongngu-vn"))
        })
        $(document).on('click', '#tang-font-en', function () {
            tangfont($("#_vbsongngu .vbsongngu-en"))
        })
        $(document).on('click', '#giam-font-en', function () {
            giamfont($("#_vbsongngu .vbsongngu-en"))
        })
        $(document).on('click', '.doc-items.left',
            function (e) {
                tatssLeft = tatssRight = currentTargetLeft == e.target ? true : false;
                currentTargetRight = null;
                currentTargetRightOffset = 0;
                if (!tatssLeft) {
                    loadItemLeft($(this));
                    currentTargetLeft = e.target;
                    currentTargetLeftOffset = e.target.offsetTop;
                }
                else {
                    currentTargetLeft = null;
                    currentTargetLeftOffset = 0;
                }
                checkScrollLeft();
            });
        $(document).on('mouseover', '.doc-items.left', function () {
            if (tatssLeft) {
                timerLeft = setTimeout(loadItemLeft($(this)), 10);
            }
        });
        $(document).on('mouseout', '.doc-items.left', function () {
            if (tatssLeft) {
                clearTimeout(timerLeft);
                //$(this).removeClass('bg-soanh1')
                //.removeClass('bg-soanh2').removeClass('bg-soanh3');
                clearBackground();
            }
        });
        $(document).on('click', '.tpy3l03894',
            function (e) {
                if (currentTargetLeftOffset > 0) {
                    $('.l08fyuscmy').animate({ scrollTop: currentTargetLeftOffset - 100 - $('.block-popup-sosanh').offset().top }, 1000);
                }
                checkScrollLeft();
            });
        $(document).on('click', '.7unpjmf3xr',
            function (e) {
                if (currentTargetLeftOffset > $(window).height()) {
                    $('.l08fyuscmy').animate({ scrollTop: currentTargetLeftOffset - 100 - $('.block-popup-sosanh').offset().top }, 1000);
                }
                checkScrollLeft();
            });
        $('.l08fyuscmy').scroll(function () {
            clearTimeout($.data(this, 'scrollLeftTimer'));
            $.data(this, 'scrollLeftTimer', setTimeout(function () {
                checkScrollLeft();
            }, 500));
        });
        $(document).on('click', '.doc-items.right',
            function (e) {
                tatssLeft = tatssRight = currentTargetRight == e.target ? true : false;
                currentTargetLeft = null;
                currentTargetLeftOffset = 0;
                if (!tatssRight) {
                    loadItemRight($(this));
                    currentTargetRight = e.target;
                    currentTargetRightOffset = e.target.offsetTop;
                }
                else {
                    currentTargetRight = null;
                    currentTargetRightOffset = 0;
                }
                checkScrollRight();
            });
        $(document).on('mouseover', '.doc-items.right', function () {
            if (tatssRight) {
                timerRight = setTimeout(loadItemRight($(this)), 10);
            }
        });
        $(document).on('mouseout', '.doc-items.right', function () {
            if (tatssRight) {
                clearTimeout(timerRight);
                //$(this).removeClass('bg-soanh1')
                //.removeClass('bg-soanh2');
                clearBackground();
            }
        });
        $(document).on('click', '.raam6rajky',
            function (e) {
                if (currentTargetRightOffset > 0) {
                    $('.bz2r9a68x5').animate({ scrollTop: currentTargetRightOffset - 100 - $('.block-popup-sosanh').offset().top }, 1000);
                }
                checkScrollRight();
            });
        $(document).on('click', '.h4r7z6cwrp',
            function (e) {
                if (currentTargetRightOffset > $(window).height()) {
                    $('.bz2r9a68x5').animate({ scrollTop: currentTargetRightOffset - 100 - $('.block-popup-sosanh').offset().top }, 1000);
                }
                checkScrollRight();
            });
        $('.bz2r9a68x5').scroll(function () {
            clearTimeout($.data(this, 'scrollRightTimer'));
            $.data(this, 'scrollRightTimer', setTimeout(function () {
                checkScrollRight();
            }, 500));
        });
        $(document).click(function (e) {
            var container = $('#_sosanhvb').find('.main-content').first(), muclucleft = $('.popup-wrapper', $('#rc6tpytoov')), contentSosanhVb = $('.content-ssvb'), boxGhichu = $('.box-ghichu');
            if ($('#_sosanhvb').hasClass('target-expanded') && (!container.is(e.target) && container.has(e.target).length === 0 || (!contentSosanhVb.is(e.target) && contentSosanhVb.has(e.target).length === 0 && !boxGhichu.is(e.target) && boxGhichu.has(e.target).length === 0)) && !muclucleft.is(e.target) && muclucleft.has(e.target).length === 0 && (!$('.rowic').is(e.target) && $('.rowic').has(e.target).length === 0 && !$('.noidung_soanh').is(e.target) && $('.noidung_soanh').has(e.target).length === 0) && !contentSosanhVb.is(e.target) && contentSosanhVb.has(e.target).length === 0 && !boxGhichu.is(e.target) && boxGhichu.has(e.target).length === 0) {
                tatssLeft = true;
                tatssRight = true;
                currentTargetRight = null;
                currentTargetRightOffset = 0;
                currentTargetLeft = null;
                currentTargetLeftOffset = 0;
                $('.rowic').hide();
                clearBackground();
            }
        });
        $('.no-permission-ss').lawsExists(function () {
            $('.no-permission-ss').tooltip({
                content: function () {
                    return $(this).prop('title');
                },
                position: {
                    my: 'center bottom+78',
                    at: 'center top',
                },
                show: {
                    effect: "slideDown",
                    delay: 250
                },
                close: function (event, ui) {
                    ui.tooltip.hover(
                        function () {
                            $(this).stop(true).fadeTo(400, 1);
                        },
                        function () {
                            $(this).fadeOut("400",
                                function () {
                                    $(this).remove();
                                });
                        });
                }
            });
        });
        var timerLeft, timerRight, currentTargetLeft = null, currentTargetLeftOffset = 0, currentTargetRight = null, currentTargetRightOffset = 0, tatssLeft = true, tatssRight = true, parentNode = null, parentArr = [],
            sosanhvanban = function () {
                var self = $(this), docCompareId = $('.nuanntrb9l option:selected').val(),
                    isLoading = $('.noidung_soanh', $('#_sosanhvb')).find('p').first().filter(function () {
                        return $(this).text() == 'Đang tải dữ liệu...';
                    });
                if (isLoading.length > 0 && typeof docCompareId != 'undefined') {
                    $.lawsAjax({
                        type: 'POST',
                        url: lawsVn.virtualPath('/ajax/doccompares'),
                        data: { docCompareId: docCompareId },
                        dataType: 'html',
                        async: true,
                        cache: true,
                        timeout: 90000,
                        beforeSend: {},
                        success: function (resp) {
                            if (resp.length > 0) {

                                $('.nuanntrb9l').removeAttr('disabled');
                                $('.szo67pmo5r').removeAttr('disabled');
                                $('.l08fyuscmy', $('#_sosanhvb')).html($(resp).filter('#8vh58r6d0v').html());
                                $('.bz2r9a68x5', $('#_sosanhvb')).html($(resp).filter('#clpa89ctcj').html());
                                $('#rc6tpytoov').find('.fcafig71ut').first().html($(resp).filter('#my6z8nszfw').html());
                                $('#el24tiie3c').find('.9hknfjqc8k').first().html($(resp).filter('#2hcrflk50n').html());
                                $('.rowssa-1').show();
                                $('#_sosanhvb').lawsExists(function () {
                                    $(this).removeClass('target-hidden').addClass('target-expanded');
                                });
                                $('html').css({ overflow: 'hidden' });
                                $('body').css({ overflow: 'hidden' });
                            }
                        }
                    });
                }

            },
            vanbansongngu_ = function (docId) {
                $('#noteloading').html("Đang tải dữ liệu ...");
                if (typeof docId != 'undefined') {
                    $.lawsAjax({
                        type: 'GET',
                        url: lawsVn.virtualPath('/Ajax/BilingualDocument'),
                        data: { docId: docId },
                        dataType: 'html',
                        async: true,
                        cache: true,
                        timeout: 90000,
                        beforeSend: {},
                        success: function (resp) {
                            if (resp.length > 0) {
                                $('#_vbsongngu').html(resp)

                                //$('.popupRelate, .popupRelate2', $('#ndsongngu')).each(function (i, element) {
                                    //console.log(e)
                                    //popupChiDan(element, e);
                                //});

                                $(document).on({
                                    mouseenter: function (e) {
                                       popupChiDan($(this), e);
                                    }, mouseleave: function () {
                                        $('.dropdown-tips-content-2', $(this)).css('visibility', 'hidden');
                                    }
                                }, '.popupRelate, .popupRelate2, .noi-dung-tham-chieu');

                                //$('.vbsongngu-vn', $("#_vbsongngu")).html($(resp).filter('#docsongngu-vn').html());
                                //$('.vbsongngu-en', $("#_vbsongngu")).html($(resp).filter('#docsongngu-en').html());
                                //s$('.toc-document', $("#_vbsongngu")).html($(resp).filter('#mucluc').html());
                            }
                        }
                    });
                }

            },
            tangfont = function (element) {
                setFontSize(element, 1 / 0.8);
                displayCurrentFontSize(element);
            },
            giamfont = function (element) {
                setFontSize(element, 0.8);
                displayCurrentFontSize(element);
            }, displayCurrentFontSize = function (element) {
                try {
                    var currentFontSize = window.getComputedStyle(
                        document.querySelector(element), ':first-line'
                    ).getPropertyValue('font-size');
                    var fs = $(element).not('.hidden').attr('data-fs');
                    if (typeof fs != 'undefined') {
                        currentFontSize = fs + '';
                    }
                    $(opts.textSize).lawsExists(function () {
                        $(this).text(currentFontSize.replace('px', ''));
                    });
                } catch (e) {

                }
            },
            getFontSize = function (el) {
                var fs = $(el).css('font-size');
                if (!el.originalFontSize) el.originalFontSize = fs;
                return parseFloat(fs);
            },
            setFontSize = function (el, fact, min, max) {
                var newsize, fs;
                min = min || 16, max = max || 35;
                section = el.find('*')
                    .filter(
                        function () {
                            return $(this).clone()
                                .children()
                                .remove()
                                .end()
                                .text().trim().length >
                                0;
                        });

                section.each(function () {
                    if ($(this).is(':visible')) {
                        newsize = fact ? getFontSize(this) * fact : this.originalFontSize;
                        if (newsize >= min && newsize <= max) {
                            if (newsize) {
                                fs = newsize;
                                $(this).css('cssText', 'font-size: ' + newsize + 'px !important;line-height:1.6 !important;');
                                //$(this).attr('style', function (i, s) { return (s || '') + `font-size:${newsize}px!important;line-height:1.6 !important;` });
                            }
                        }
                    }
                });
                if (fs)
                    $(el).attr('data-fs', parseInt(fs))
            }
            , loadItemLeft = function (element) {
                try {
                    clearBackground();
                    var id = element.attr('data-id'), levelId = element.attr('data-lv'), foundIt = null;
                    if (typeof id != 'undefined') {
                        scrollToItemLeft(id);
                        foundIt = $('.doc-items.right').filter(function () {
                            return typeof $(this).attr('data-c') != 'undefined' && $(this).attr('data-c').indexOf(id) >= 0;
                        });
                    }
                    if (foundIt != null && foundIt.length > 0) {
                        addClassByTypeName(element, 'conoidungthaythe');
                        addClassByTypeName(foundIt, 'conoidungthaythe');
                        if (levelIsDisplayed(levelId)) {
                            setChildrenBackground($('.doc-items.left[data-p="' + id + '"]'), 'conoidungthaythe');
                            if (foundIt.length < 2)
                                setChildrenBackground($('.doc-items.right[data-p="' + $(foundIt[0]).attr('data-id') + '"]'), 'conoidungthaythe');
                        }

                        return false;
                    } else {
                        parentNode = null;
                        parentArr = getParents(element);
                        if (parentArr.length > 0) {
                            id = $(parentArr[0]).attr('data-id');
                            scrollToItemLeft(id);
                            foundIt = $('.doc-items.right').filter(function () {
                                return typeof $(this).attr('data-c') != 'undefined' && $(this).attr('data-c').indexOf(id) >= 0;
                            });
                            if (displayRulesByArticlesTermsPoints(parentArr, element)) {
                                if (foundIt != null && foundIt.length > 0) {
                                    addClassByTypeName(parentArr[0], 'conoidungthaythe');
                                    addClassByTypeName(foundIt, 'conoidungthaythe');
                                    setChildrenBackground($('.doc-items.left[data-p="' + id + '"]'),
                                        'conoidungthaythe');
                                    if (foundIt.length < 2)
                                        setChildrenBackground(
                                            $('.doc-items.right[data-p="' + $(foundIt[0]).attr('data-id') + '"]'),
                                            'conoidungthaythe');
                                    return false;
                                }
                            } else {
                                if (levelIsDisplayed(levelId)) {
                                    addClassByTypeName(element, 'khongconoidungthaythe');
                                }
                                currentTargetRight = null;
                                currentTargetRightOffset = 0;
                            }
                        } else {
                            if (levelIsDisplayed(levelId))
                                addClassByTypeName(element, 'khongconoidungthaythe');
                            currentTargetRight = null;
                            currentTargetRightOffset = 0;
                        }
                    }
                } catch (e) {
                    console.log(e)
                }
                return false;
            }, scrollToItemLeft = function (id) {
                var offset = 0,
                    offsetTop = $('.noidung_soanh').offset().top,
                    right = $('.bz2r9a68x5'),
                    foundIt = $('.doc-items.right').filter(function () {
                        return $(this).is(':visible') && typeof $(this).attr('data-c') != 'undefined' && $(this).attr('data-c').indexOf(id) >= 0;
                    });
                if (foundIt.length > 0) {
                    offset = right.scrollTop() + $($(foundIt)[0]).offset().top - 100 - offsetTop;
                    right.animate({ scrollTop: offset }, 0);
                }
            }, loadItemRight = function (element) {
                try {
                    clearBackground();
                    var id = element.attr('data-c'), foundIt = null;
                    if (typeof id != 'undefined') {
                        scrollToItemRight(id);
                        foundIt = $('.doc-items.left').filter(function () {
                            return typeof $(this).attr('data-id') != 'undefined' && $(this).attr('data-id').indexOf(id) >= 0;
                        });
                    }
                    if (foundIt != null && foundIt.length > 0) {
                        addClassByTypeName(element, 'conoidungthaythe');
                        addClassByTypeName(foundIt, 'conoidungthaythe');
                        if (levelIsDisplayed(element.attr('data-lv'))) {
                            setChildrenBackground($('.doc-items.right[data-p="' + element.attr('data-id') + '"]'), 'conoidungthaythe');
                            if (foundIt.length < 2)
                                setChildrenBackground($('.doc-items.left[data-p="' + $(foundIt[0]).attr('data-id') + '"]'), 'conoidungthaythe');
                        }
                        return false;
                    } else {
                        parentNode = null;
                        parentArr = getParents(element);
                        console.log(parentArr);
                        if (parentArr.length > 0) {
                            id = $(parentArr[0]).attr('data-c');
                            scrollToItemRight(id);
                            foundIt = $('.doc-items.left').filter(function () {
                                return typeof $(this).attr('data-id') != 'undefined' &&
                                    $(this).attr('data-id').indexOf(id) >= 0;
                            });
                            if (displayRulesByArticlesTermsPoints(parentArr, element)) {
                                if (foundIt != null && foundIt.length > 0) {
                                    addClassByTypeName(parentArr[0], 'conoidungthaythe');
                                    addClassByTypeName(foundIt, 'conoidungthaythe');
                                    setChildrenBackground($('.doc-items.right[data-p="' + $(parentArr[0]).attr('data-id') + '"]'), 'conoidungthaythe');
                                    if (foundIt.length < 2)
                                        setChildrenBackground($('.doc-items.left[data-p="' + $(foundIt[0]).attr('data-id') + '"]'), 'conoidungthaythe');
                                    return false;
                                }
                            } else {
                                if (levelIsDisplayed(element.attr('data-lv')))
                                    addClassByTypeName(element, 'noidungmoi');
                                currentTargetLeft = null;
                                currentTargetLeftOffset = 0;
                            }
                        } else {
                            if (levelIsDisplayed(element.attr('data-lv')))
                                addClassByTypeName(element, 'noidungmoi');
                            currentTargetLeft = null;
                            currentTargetLeftOffset = 0;
                        }
                    }
                } catch (e) {
                    console.log(e)
                }
                return false;
            }, scrollToItemRight = function (id) {
                var offset = 0,
                    offsetTop = $('.noidung_soanh').offset().top,
                    left = $('.l08fyuscmy'),
                    foundIt = $('.doc-items.left').filter(function () {
                        return $(this).is(':visible') && typeof $(this).attr('data-id') != 'undefined' && id.indexOf($(this).attr('data-id')) >= 0;
                    });
                if (foundIt.length > 0) {
                    offset = left.scrollTop() + $($(foundIt)[0]).offset().top - 100 - offsetTop;
                    left.animate({ scrollTop: offset }, 0);
                }
            }, clearBackground = function () {
                $('.doc-items.left.bg-soanh1').each(function (i, item) {
                    $(item).removeClass('bg-soanh1');
                })
                $('.doc-items.left.bg-soanh2').each(function (i, item) {
                    $(item).removeClass('bg-soanh2');
                })
                $('.doc-items.left.bg-soanh3').each(function (i, item) {
                    $(item).removeClass('bg-soanh3');
                })
                $('.doc-items.right.bg-soanh1').each(function (i, item) {
                    $(item).removeClass('bg-soanh1');
                })
                $('.doc-items.right.bg-soanh2').each(function (i, item) {
                    $(item).removeClass('bg-soanh2');
                })
                $('.doc-items.right.bg-soanh3').each(function (i, item) {
                    $(item).removeClass('bg-soanh3');
                })
            }, checkScrollLeft = function () {
                $('.rowic').hide();
                if (currentTargetLeft != null) {
                    if ($(currentTargetLeft).offset().top < 35) {
                        $('.tpy3l03894').show();
                        return false;
                    }
                    if ($(currentTargetLeft).offset().top > $(window).height()) {
                        $('.7unpjmf3xr').show();
                        return false;
                    }
                }
                return false;
            }, checkScrollRight = function () {
                $('.rowic').hide();
                if (currentTargetRight != null) {
                    if ($(currentTargetRight).offset().top < 35) {
                        $('.raam6rajky').show();
                        return false;
                    }
                    if ($(currentTargetRight).offset().top > $(window).height()) {
                        $('.h4r7z6cwrp').show();
                        return false;
                    }
                }
                return false;
            }, setChildrenBackground = function (node, typeName) {
                for (var i = 0; i < node.length; i++) {
                    if (!levelIsDisplayed($(node[i]).attr('data-lv'))) {
                        return false;
                    }
                    if ($(node[i]).hasClass('bg-soanh89-') || $(node[i]).hasClass('bg-soanh9')) {
                        continue;
                    }
                    addClassByTypeName($(node[i]), typeName);
                    var child = $('.doc-items.' + ($(node[i]).hasClass('left') ? 'left' : 'right') + '[data-p="' + $(node[i]).attr('data-id') + '"]');
                    if (child.length)
                        setChildrenBackground(child, typeName);
                }
            }, setParentBackground = function (parentArr, typeName) {
                addClassByTypeName(parentArr, typeName);
            }, getParents = function (element) {
                var parentArr = [],
                    parentId = element.attr('data-p'),
                    parent = null,
                    pos = element.hasClass('left') ? 'left' : 'right';
                while (parentId > 0) {
                    parent = $('.doc-items.' + pos + '[data-id="' + parentId + '"]');
                    if (parent.length > 0) {
                        if (!levelIsDisplayed(parent.attr('data-lv'))) {
                            break;
                        }
                        if (parent.hasClass('linked')) {
                            parentArr.push(parent);
                        }
                        //if (parent.attr('data-c')) {
                        //parentArr.push(parent);
                        //}
                        parentId = parent.attr('data-p');
                    }
                }
                return parentArr;
            },
            displayRulesByArticlesTermsPoints = function (parentArr, element) {
                if (element.attr('data-lv') != termDocItemLevelId()) {
                    element = $('.doc-items.' + (element.hasClass('left') ? 'left' : 'right') + '[data-id="' + element.attr('data-p') + '"][data-lv="' + termDocItemLevelId() + '"]');
                }
                if (element.hasClass('linked')) {
                    return true;
                }
                for (var j = 0; j < parentArr.length; j++) {
                    if ($(parentArr[j]).attr('data-lv') == articleDocItemLevelId()) {
                        var child = $('.doc-items.' + ($(parentArr[j]).hasClass('left') ? 'left' : 'right') + '[data-p="' + $(parentArr[j]).attr('data-id') + '"][data-id!="' + element.attr('data-id') + '"][data-lv="' + termDocItemLevelId() + '"]');

                        for (var i = 0; i < child.length; i++) {
                            if ($(child[i]).hasClass('linked')) {
                                return false;
                            }
                        }
                        break;
                    }
                }
                return true;
            }, addClassByTypeName = function (element, typeName) {
                const typeId = $('.szo67pmo5r option:selected').val();

                if (typeName == 'conoidungthaythe' && typeId != 2 && typeId != 3) {
                    element.removeClass('bg-soanh1').removeClass('bg-soanh3').addClass('bg-soanh2');
                    element.attr('title', 'Có nội dung thay thế tương ứng');
                } else if (typeName == 'khongconoidungthaythe') {
                    element.removeClass('bg-soanh2').removeClass('bg-soanh3').addClass('bg-soanh1');
                    element.attr('title', 'Không có nội dung thay thế tương ứng');
                } else if (typeName == 'noidungmoi') {
                    element.removeClass('bg-soanh1').removeClass('bg-soanh2').addClass('bg-soanh3');
                    element.attr('title', 'Nội dung mới - Không có nội dung bị thay thế tương ứng');
                }
            }, levelIsDisplayed = function (level) {
                return ',1,2,3,4,8,9,13,14,15,17,'.indexOf(',' + level + ',') < 0;
            }, articleDocItemLevelId = function () {
                return 5;
            }, termDocItemLevelId = function () {
                return 11;
            }, pointDocItemLevelId = function () {
                return 12;
            }
        $(document).on('change', '.nuanntrb9l', function (event) {
            event.preventDefault();
            $('.nuanntrb9l').prop('disabled', true);
            $('.szo67pmo5r option:first').prop('selected', true);
            $('.szo67pmo5r').prop('disabled', true);
            currentTargetRight = null;
            currentTargetRightOffset = 0;
            currentTargetLeft = null;
            currentTargetLeftOffset = 0;
            const divSosanhRight = $('.noidung_soanh.bz2r9a68x5'),
                parentDivSosanhRight = divSosanhRight.closest('popup_col2'),
                divDocIndexRight = parentDivSosanhRight.find('.rowssa-1').first(),
                divSosanhLeft = $('.noidung_soanh.l08fyuscmy'),
                parentDivSosanhLeft = divSosanhLeft.closest('popup_col2'),
                divDocIndexLeft = parentDivSosanhLeft.find('.rowssa-1').first();

            divSosanhLeft.show();
            divDocIndexLeft.show();
            divSosanhRight.show();
            divDocIndexRight.show();
            var self = $('.nuanntrb9l option:selected'), docName = self.data('name'), compareName = self.data('comparename'), docCompareId = self.val();
            if (typeof docName != 'undefined' && typeof compareName != 'undefined') {
                $('#n6yhamxww1').attr('title', docName).text(docName);
                $('#9eosiucrrc').attr('title', compareName).text(compareName);
                $('.rowssa-1').hide();
                $('.l08fyuscmy', $('#_sosanhvb')).html('<p style="text-align: center;">Đang tải dữ liệu...</p>');
                $('.bz2r9a68x5', $('#_sosanhvb')).html('<p style="text-align: center;">Đang tải dữ liệu...</p>');
                sosanhvanban();
            }
        });
        $(document).on('change', '.szo67pmo5r', function (event) {
            event.preventDefault();
            currentTargetRight = null;
            currentTargetRightOffset = 0;
            currentTargetLeft = null;
            currentTargetLeftOffset = 0;
            var self = $('.szo67pmo5r option:selected'), viewTypeId = self.val();
            const divSosanhRight = $('.noidung_soanh.bz2r9a68x5'),
                parentDivSosanhRight = divSosanhRight.closest('.popup_col2'),
                divDocIndexRight = parentDivSosanhRight.find('.rowssa-1').first(),
                divSosanhLeft = $('.noidung_soanh.l08fyuscmy'),
                parentDivSosanhLeft = divSosanhLeft.closest('.popup_col2'),
                divDocIndexLeft = parentDivSosanhLeft.find('.rowssa-1').first();

            if (viewTypeId == 1) {
                divSosanhLeft.show();
                divDocIndexLeft.show();
                divSosanhRight.show();
                divDocIndexRight.show();
                $('.doc-items.left').not('.bg-soanh8').hide();
                $('.doc-items.left').not('.anchor').hide();
                $('.doc-items.left.bg-soanh8').show();
                $('.doc-items.right').not('.bg-soanh8').hide();
                $('.doc-items.right').not('.bg-soanh89').hide();
                $('.doc-items.right.bg-soanh8').show();
                //$('.doc-items.right.bg-soanh89').show();
            } else if (viewTypeId == 2) {
                divSosanhLeft.hide();
                divDocIndexLeft.hide();
                divSosanhRight.show();
                divDocIndexRight.show();

                $('.doc-items.right').not('.bg-soanh10, .bg-soanh89').hide();
                $('.doc-items.right.bg-soanh10').show();
                $('.doc-items.right.bg-soanh89').show();
                $('.doc-items.right.bg-soanh89').each(function () {
                    // Lấy giá trị data-id của mỗi item đang hiển thị
                    var currentId = $(this).data('p');
                    // Hiển thị các item cấp cha có data-p bằng với data-id đang hiển thị
                    $('.doc-items.right').filter(function () {
                        return $(this).data('id') == currentId && $(this).data('lv') == 5;
                    }).each(function () {
                        // Hiển thị cấp cha đầu tiên
                        $(this).show();
                        // Lấy giá trị data-p của cấp cha đầu tiên
                        var parentId = $(this).data('p');
                        // Hiển thị cấp cha thứ hai
                        $('.doc-items.right').filter(function () {
                            return $(this).data('id') == parentId && $(this).data('lv') == 5;
                        }).show();
                    });
                });
                $('.doc-items.right.bg-soanh10').each(function () {
                    // Lấy giá trị data-id của mỗi item đang hiển thị
                    var currentId = $(this).data('p');
                    // Hiển thị các item cấp cha có data-p bằng với data-id đang hiển thị
                    $('.doc-items.right').filter(function () {
                        return $(this).data('id') == currentId;
                    }).each(function () {
                        // Hiển thị cấp cha đầu tiên
                        $(this).show();
                        // Lấy giá trị data-p của cấp cha đầu tiên
                        var parentId = $(this).data('p');

                        // Hiển thị cấp cha thứ hai
                        $('.doc-items.right').filter(function () {
                            return $(this).data('id') == parentId;
                        }).show();
                    });
                });

            } else if (viewTypeId == 3) {
                divSosanhLeft.show();
                divDocIndexLeft.show();
                divSosanhRight.hide();
                divDocIndexRight.hide();

                $('.doc-items.left').not('.bg-soanh9').hide();
                $('.doc-items.left.bg-soanh9').each(function () {
                    $(this).show();
                    var parent = getParentss($(this));
                    if (parent.length > 0) {
                        $(parent[parent.length - 1]).addClass('anchor').show();
                    }
                });

                function getParentss(element) {
                    var parentArr = [];
                    // Lấy giá trị data-p dưới dạng số
                    var parentId = parseInt(element.attr('data-p'), 10);
                    var pos = element.hasClass('left') ? 'left' : 'right';

                    while (parentId > 0) {
                        // Sử dụng document.querySelector để tìm nhanh phần tử cha
                        var parentElem = document.querySelector('.doc-items.' + pos + '[data-id="' + parentId + '"]');
                        if (!parentElem) break;
                        // Chỉ wrap đối tượng khi cần dùng jQuery
                        var $parent = $(parentElem);
                        // Nếu hàm kiểm tra level tốn kém, hãy đảm bảo nó được tối ưu hoặc có thể cache kết quả nếu giá trị không thay đổi
                        if (!levelIsDisplayed($parent.attr('data-lv'))) {
                            break;
                        }
                        if ($parent.hasClass('linked')) {
                            parentArr.push($parent);
                        }
                        // Lấy data-p của phần tử cha (chuyển về số nếu cần)
                        parentId = parseInt($parent.attr('data-p'), 10);
                    }
                    return parentArr;
                }
            } else {
                divSosanhLeft.show();
                divDocIndexLeft.show();
                divSosanhRight.show();
                divDocIndexRight.show();
                $('.doc-items.left').show();
                $('.doc-items.right').show();
            }
        });
        $(document).on('click', '.rxentanfyh', function (event) {
            event.preventDefault();
            $(this).hide();
            $('.1m5ha80pu6').show();
            $('.sosanh-col2', $('#_sosanhvb')).css('width', '80%');
        });
        $(document).on('click', '.1xz64mp3lh', function (event) {
            event.preventDefault();
            $('.rxentanfyh').show();
            $('.1m5ha80pu6').hide();
            $('.sosanh-col2', $('#_sosanhvb')).css('width', '100%');
        });
        $(document).on('click',
            '#3g0w117nr7',
            function (e) {
                e.preventDefault();
                $('#rc6tpytoov').lawsExists(function () {
                    tatssLeft = false;
                    tatssRight = false;
                    currentTargetLeft = null;
                    currentTargetLeftOffset = 0;
                    currentTargetRight = null;
                    currentTargetRightOffset = 0;
                    $(this).show();
                });
            });
        $(document).on('click',
            '#vhxynoouaz',
            function (e) {
                e.preventDefault();
                $('#el24tiie3c').lawsExists(function () {
                    tatssLeft = false;
                    tatssRight = false;
                    currentTargetLeft = null;
                    currentTargetLeftOffset = 0;
                    currentTargetRight = null;
                    currentTargetRightOffset = 0;
                    $(this).show();
                });
            });
        $(document).on('click',
            '.mucluc_left',
            function (e) {
                tatssLeft = false;
                currentTargetLeft = null;
                currentTargetLeftOffset = 0;
                var id = $(this).attr('data-id');
                if (typeof id != 'undefined') {
                    var parent = $('.l08fyuscmy'), target = $('.doc-items.left[data-id="' + id + '"]');
                    if (target.length) {
                        $('#rc6tpytoov').lawsExists(function () {
                            $(this).hide();
                        });
                        parent.animate({ scrollTop: target.position().top + parent.scrollTop() }, 2000, function () {
                            tatssLeft = true;
                        });
                    }
                }
            });
        $(document).on('click',
            '.muclucsongngu_left',
            function (e) {
                tatssLeft = false;
                currentTargetLeft = null;
                currentTargetLeftOffset = 0;
                var id = $(this).attr('data-id') || $(this).attr('class').replace(/\s{2,}/g, ' ').split(' ')[2];
                if (typeof id != 'undefined') {
                    var parent = $('.vbsongngu-vn', $('#_vbsongngu')), target = $('#_vbsongngu').find('#' + id);
                    if (target.length) {
                        $('.dropdown-wrapper').lawsExists(function () {
                            $(this).hide();
                        });
                        parent.animate({
                            scrollTop: target.position().top + parent.scrollTop()
                        }, 1000, function () {
                            tatssRight = true;
                        });
                    }
                }
            });
        $(document).on('click',
            '.mucluc_right',
            function (e) {
                tatssRight = false;
                currentTargetRight = null;
                currentTargetRightOffset = 0;
                var id = $(this).attr('data-id');
                if (typeof id != 'undefined') {
                    var parent = $('.bz2r9a68x5'), target = $('.doc-items.right[data-id="' + id + '"]');
                    if (target.length) {
                        $('#el24tiie3c').lawsExists(function () {
                            $(this).hide();
                        });
                        parent.animate({ scrollTop: target.position().top + parent.scrollTop() }, 2000, function () {
                            tatssRight = true;
                        });
                    }
                }
                return false;
            });
        $(document).on('click',
            '.btn-reset',
            function (event) {
                event.preventDefault();
                lawsVn.ResetForm($(this).closest('form'));
            });
        $('#ToggleDocIndexes').off('click').on('click',
            function (event) {
                event.preventDefault();
                $('#DocIndexes').slideToggle();
            }).toggle(function () {
                $(this).html(
                    '<img class="icon-hidden-article" alt="icon-hidden-article" src="' +
                    lawsVn.virtualPath('/assets/images/an-dmuc.png') +
                    '">Hiện mục lục')
                    .attr('title', 'Hiện mục lục');
            },
                function () {
                    $(this).html(
                        '<img class="icon-hidden-article" alt="icon-hidden-article" src="' +
                        lawsVn.virtualPath('/assets/images/an-dmuc.png') +
                        '">Ẩn mục lục')
                        .attr('title', 'Ẩn mục lục');
                });;

        $('#advancedSearch').off('click').on('click',
            function (event) {
                event.preventDefault();
                $("#advancedSearchPannel").toggle();
            });

        $('.doc-thong-bao').off('click').on('click',
            function (event) {
                event.preventDefault();
                var self = $(this);
                var messageId = $(this).data('id');
                var targetUrl = $(this).data('url');
                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/ReadNotifyMessages'),
                    type: 'Post',
                    data: { messageId: messageId, targetUrl: targetUrl },
                    success: function (resp) {
                        $(self).parent().remove();
                        if (resp.ReturnUrl != null && resp.ReturnUrl.length > 0) {
                            window.location.href = resp.ReturnUrl;
                        }
                    }
                });
            });

        $('.danh-dau-tat-ca-da-doc-thong-bao').off('click').on('click',
            function (event) {
                event.preventDefault();
                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/ReadAllNotifyMessages'),
                    type: 'Post',
                    success: function (resp) {
                        if (resp.Message != null && resp.Message > 0) {
                            $().lawsDialog({
                                messages: [resp.Message],
                                showIcon: false,
                                onClose: function () {
                                    if (resp.ReturnUrl != null && resp.ReturnUrl > 0) {
                                        window.location.href = resp.ReturnUrl;
                                    }
                                }
                            });
                        }
                    }
                });
            });
        $(document).on('click',
            '.closeDialog',
            function (event) {
                event.preventDefault();
                $(this).parents('.ui-dialog-content').dialog('close'); //or closest
            });

        $(".icon").click(function (event) {
            event.preventDefault();
            var icon = $(this),
                input = icon.parent().find("#search"),
                submit = icon.parent().find(".submit"),
                isSubmitClicked = false;

            input.animate({
                "width": "180px",
                "padding": "10px",
                "opacity": 1
            },
                300,
                function () {
                    input.focus();
                });

            submit.mousedown(function () {
                isSubmitClicked = true;
            });
            icon.fadeOut(300);
            input.blur(function () {
                if (!input.val() && !isSubmitClicked) {
                    input.animate({
                        "width": "0",
                        "padding": "0",
                        "opacity": 0
                    },
                        200);
                    icon.fadeIn(200);
                };
            });
        });
        $(document).on('click',
            'form .submit-link',
            function (event) {
                event.preventDefault();
                $(this).closest('form').submit();
            });
        $(document).on('click',
            '.a-time-mixvb-left2',
            function (event) {
                event.preventDefault();
                var me = $(this),
                    parent = me.closest('#vanbantacdong'),
                    role = me.data('role'),
                    login = me.data('login'),
                    popup, pos = me.position();
                $('.tooltip-boxs').lawsExists(function () {
                    $('.tooltip-boxs').addClass('hidden').removeAttr('style');
                });
                if (typeof role !== 'undefined' || typeof login !== 'undefined') {
                    if (typeof login !== 'undefined')
                        popup = $('.login-required');
                    else if (typeof role !== 'undefined')
                        popup = $('.role-required');
                    parent.lawsExists(function () {
                        popup.lawsExists(function () {
                            $(this).removeClass('hidden').css({
                                position: 'absolute',
                                top: event.clientY
                            }).fadeIn();
                            popup.LawScrollTo();
                        });
                    });
                }
            });

        $(document).on('click',
            '.theo-doi-hlvb',
            function (event) {
                event.preventDefault();
                var me = $(this), form = me.closest('form');
                if ($('input:checked', form).length > 0) {
                    form.trigger('submit');
                } else {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Quý khách vui lòng chọn văn bản cần theo dõi hiệu lực.'],
                        buttons: [
                            {
                                text: lawsVn.Resource.getMessages('Close'),
                                click: function () {
                                    $(this).dialog('close');
                                }
                            }
                        ]
                    });
                }
            });
        $('select').each(function () {
            var item = $(this).find('option:selected').val();
            if (item > 0) {
                if (!$(this).hasClass('bgdefault'))
                    $(this).addClass('select-background-selected');
            } else $(this).removeClass('select-background-selected');
        });
        $(document).on('change',
            'select',
            function () {
                var item = $(this).find('option:selected').val();
                if (item > 0) {
                    if (!$(this).hasClass('bgdefault'))
                        $(this).addClass('select-background-selected');
                } else $(this).removeClass('select-background-selected');
            });
        $(document).on('click',
            '.save-doc-of-interest',
            function (event) {
                event.preventDefault();
                var me = $(this), docId = me.data('id'), respCustomerDoc;
                var countMyDocuments = $('#countMyDocuments');
                var count = parseInt(countMyDocuments.text().replace(/[^\d]/g, ''), 10);
                if (!$.isNumeric(count))
                    count = 0;
                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/SaveDocument'),
                    data: { docId: docId },
                    beforeSend: {},
                    success: function (resp) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [resp.Message]
                            });
                        }
                        if (resp.Data.RegistTypeId !== 3) { //Đã thêm rồi -> ko tăng count
                            count++;
                            countMyDocuments.data('count', count);
                            countMyDocuments.text('(' + count + ')');
                        }
                        if (resp.Data != null) {
                            luatVietnamStore.getItem('luatvietnam_customerdoc_' + resp.Data.DocId + '_' + resp.Data.CustomerId + '_' + resp.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respCustomerDoc = response;
                                }
                            });
                            if (respCustomerDoc === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': 1, 'hasTrackedDocumentEffect': 0, 'hasEffectTrackingsAll': 0 },
                                    15 * 60);
                            } else {
                                respCustomerDoc.documentSaved++;
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': respCustomerDoc.documentSaved, 'hasTrackedDocumentEffect': respCustomerDoc.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': respCustomerDoc.hasEffectTrackingsAll },
                                    15 * 60);
                            }
                            //me.removeClass('save-doc-of-interest').addClass('active unsave-doc-of-interest')
                            //    .find('span').text('Hủy lưu');
                        }
                    }
                });
            });
        $(document).on('click',
            '.unsave-doc-of-interest',
            function (event) {
                event.preventDefault();
                var me = $(this), docId = me.data('id');
                var countMyDocuments = $('#countMyDocuments');
                var count = parseInt(countMyDocuments.text().replace(/[^\d]/g, ''), 10);
                if (!$.isNumeric(count))
                    count = 0;
                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/UnSaveDocument'),
                    data: { docId: docId },
                    beforeSend: {},
                    success: function (resp) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [resp.Message]
                            });
                        }
                        if (count > 0)
                            count--;
                        countMyDocuments.data('count', count);
                        countMyDocuments.text('(' + count + ')');
                        if (resp.Data != null) {
                            var respCustomerDoc;
                            luatVietnamStore.getItem('luatvietnam_customerdoc_' + resp.Data.DocId + '_' + resp.Data.CustomerId + '_' + resp.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respCustomerDoc = response;
                                }
                            });
                            if (respCustomerDoc === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdoc_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': 1, 'hasTrackedDocumentEffect': 0, 'hasEffectTrackingsAll': 0 },
                                    15 * 60);
                            } else {
                                if (respCustomerDoc.documentSaved > 0)
                                    respCustomerDoc.documentSaved--;
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdoc_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': respCustomerDoc.documentSaved, 'hasTrackedDocumentEffect': respCustomerDoc.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': respCustomerDoc.hasEffectTrackingsAll },
                                    15 * 60);
                            }
                            //me.removeClass('active unsave-doc-of-interest').addClass('save-doc-of-interest')
                            //    .find('span').text('Lưu');
                        }
                    }
                });
            });
        $(document).on('click',
            '#customerDocs_ccnmjq6o6h',
            function (event) {
                event.preventDefault();
                var me = $(this),
                    docId = me.data('id'),
                    respCustomerDocs,
                    countMyDocuments = $('#countMyDocuments'),
                    count = parseInt(countMyDocuments.text().replace(/[^\d]/g, ''), 10),
                    isSave = me.hasClass('save'),
                    urlRequest = lawsVn.virtualPath('/Ajax/' + (isSave ? '' : 'Un') + 'SaveDocument');
                if (!$.isNumeric(count))
                    count = 0;
                $.lawsAjax({
                    url: urlRequest,
                    data: { docId: docId },
                    beforeSend: {},
                    success: function (resp) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            //$().lawsDialog({
                            //    dialogClass: 'lawsVnDialogTitle',
                            //    messages: [resp.Message]
                            //});
                            lawsVn.showMessage({ messages: [resp.Message] });
                        }
                        if (isSave) {
                            count++;
                        } else {
                            if (count > 0)
                                count--;
                        }
                        countMyDocuments.data('count', count);
                        countMyDocuments.text('(' + count + ')');
                        if (resp.Data != null) {
                            luatVietnamStore.getItem('luatvietnam_customerdocs_' + resp.Data.DocId + '_' + resp.Data.CustomerId + '_' + resp.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respCustomerDocs = response;
                                }
                            });
                            if (respCustomerDocs === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': isSave ? 1 : 0, 'hasTrackedDocumentEffect': 0, 'hasEffectTrackingsAll': 0 },
                                    15 * 60);
                            } else {
                                if (isSave && respCustomerDocs.documentSaved < 1) {
                                    respCustomerDocs.documentSaved++;
                                } else {
                                    if (respCustomerDocs.documentSaved > 0)
                                        respCustomerDocs.documentSaved--;
                                }
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': respCustomerDocs.documentSaved, 'hasTrackedDocumentEffect': respCustomerDocs.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': respCustomerDocs.hasEffectTrackingsAll },
                                    15 * 60);
                            }
                            if (!isSave) {
                                me.removeClass('active unsave').addClass('save')
                                    .find('span').text('Lưu');
                                me.next().find('.content_bgfff').text('Lưu văn bản');
                            } else {
                                me.removeClass('save').addClass('active unsave')
                                    .find('span').text('Bỏ lưu');
                                me.next().find('.content_bgfff').text('Bỏ lưu văn bản');
                            }
                        }
                    }
                });
            });
        $(document).on('click', '.customer-doc.save', function () {
            let self = $(this), docId = self.data('id') || 0, popup = $('#_luuvanban')

            if (docId <= 0) {
                lawsVn.showMessage({ autoClose: true, messages: ['Quý khách vui lòng thử lại sau.'] })
                return
            }

            lawsVn.getCustomerFolders(docId);
        })
        $(document).on('click', '.customer-doc.unsave', function () {
            let self = $(this), docId = self.data('id') || 0

            if (docId <= 0) {
                lawsVn.showMessage({ autoClose: true, messages: ['Quý khách vui lòng thử lại sau.'] })
                return
            }

            lawsVn.fetchData(
                {
                    url: '/ajax/UnSavePrivateDocument',
                    dataType: 'json',
                    type: 'POST',
                    data: { docId: docId },
                    beforeSend: () => {
                        $('#loading').fadeIn('normal');
                    },
                    always: () => {
                        $('#loading').fadeOut('normal');
                    }
                })
                .then((response) => {
                    if (response.Message != null && response.Message.length > 0) {
                        lawsVn.showMessage({
                            messages: [response.Message]
                        });
                    }

                    if (response.Data != null) {
                        lawsVn.bindCustomerDocument(response.Data.DocId, response.Data.CustomerId, response.Data.LanguageId, 0)
                    }
                })
                .catch((error) => {
                    console.error(error)
                    //appModule.hideLoading()
                    //lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] })
                })
        })
        $(document).on('click',
            '#customerDocs_mrvekdu7ze',
            function (event) {
                event.preventDefault();
                var self = $(this),
                    articleId = self.data('id'),
                    registTypeId = self.data('registtypeid'),
                    respCustomerDocs,
                    isSave = self.hasClass('save');
                if (typeof registTypeId == 'undefined') {
                    registTypeId = 4;
                }
                var urlRequest = lawsVn.virtualPath('/Ajax/' + (isSave ? '' : 'Un') + 'SaveArticle' + '?registTypeId=' + registTypeId);
                $.lawsAjax({
                    url: urlRequest,
                    data: { articleId: articleId },
                    beforeSend: {},
                    success: function (resp) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [resp.Message]
                            });
                        }
                        if (resp.Data != null) {
                            luatVietnamStore.getItem('luatvietnam_customerarticles_' + resp.Data.DocId + '_' + resp.Data.CustomerId + '_' + resp.Data.RegistTypeId + '_' + resp.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respCustomerDocs = response;
                                }
                            });
                            if (respCustomerDocs === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerarticles_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.RegistTypeId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'articleSaved': isSave ? 1 : 0 },
                                    3600 * 24 * 365);
                            } else {
                                if (isSave && respCustomerDocs.articleSaved < 1) {
                                    respCustomerDocs.articleSaved++;
                                } else {
                                    if (respCustomerDocs.articleSaved > 0)
                                        respCustomerDocs.articleSaved--;
                                }
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerarticles_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.RegistTypeId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'articleSaved': respCustomerDocs.articleSaved },
                                    3600 * 24 * 365);
                            }
                            if (!isSave) {
                                self.removeClass('active unsave').addClass('save').attr('title', 'Lưu bài viết');
                            } else {
                                self.removeClass('save').addClass('active unsave').attr('title', 'Bỏ lưu bài viết');
                            }
                        }
                    }
                });
            });
        $(document).on('click',
            '#customerDocs_5um68a24jk',
            function (event) {
                event.preventDefault();
                var me = $(this),
                    docId = me.data('id'),
                    respCustomerDocs,
                    isSave = me.hasClass('save'),
                    urlRequest = lawsVn.virtualPath('/Ajax/' + (isSave ? '' : 'Un') + 'SubscriptionNoticeOfValidity');
                $.lawsAjax({
                    url: urlRequest,
                    type: isSave ? 'GET' : 'POST',
                    data: { docId: docId },
                    beforeSend: {},
                    success: function (resp) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [resp.Message]
                            });
                        }
                        if (resp.Data != null) {
                            luatVietnamStore.getItem('luatvietnam_customerdocs_' + resp.Data.DocId + '_' + resp.Data.CustomerId + '_' + resp.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respCustomerDocs = response;
                                }
                            });
                            if (respCustomerDocs === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': 0, 'hasTrackedDocumentEffect': isSave ? 1 : 0, 'hasEffectTrackingsAll': 0 },
                                    15 * 60);
                            } else {
                                if (isSave && respCustomerDocs.hasTrackedDocumentEffect < 1) {
                                    respCustomerDocs.hasTrackedDocumentEffect++;
                                } else {
                                    if (respCustomerDocs.hasTrackedDocumentEffect > 0)
                                        respCustomerDocs.hasTrackedDocumentEffect--;
                                }
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': respCustomerDocs.documentSaved, 'hasTrackedDocumentEffect': respCustomerDocs.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': respCustomerDocs.hasEffectTrackingsAll },
                                    15 * 60);
                            }
                            if (!isSave) {
                                me.removeClass('active unsave').addClass('save')
                                    .find('span').text('Theo dõi hiệu lực VB');
                                me.next().find('.content_bgfff').text('Theo dõi hiệu lực VB');
                            } else {
                                me.removeClass('save').addClass('active unsave')
                                    .find('span').text('Bỏ theo dõi hiệu lực VB');
                                me.next().find('.content_bgfff').text('Bỏ theo dõi hiệu lực VB');
                            }
                        }
                    }
                });
            });
        $(document).on('change',
            '#customerDocs_5um68a24jj',
            function (event) {
                event.preventDefault();
                var me = $(this),
                    parent = me.closest('.ul-navtip'),
                    btnDoc = me.closest('.document-item').find('.btn-doc').first(),
                    isSave = me.is(':checked'),
                    docId = parent.data('id'),
                    respCustomerDocs,
                    urlRequest = lawsVn.virtualPath('/Ajax/' + (isSave ? '' : 'Un') + 'SubscriptionNoticeOfValidity');
                $.lawsAjax({
                    url: urlRequest,
                    type: isSave ? 'GET' : 'POST',
                    data: { docId: docId },
                    beforeSend: {},
                    success: function (resp) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            //$().lawsDialog({
                            //    dialogClass: 'lawsVnDialogTitle',
                            //    messages: [resp.Message]
                            //});
                            lawsVn.showMessage({ messages: [resp.Message] });
                        }
                        if (resp.Data != null) {
                            luatVietnamStore.getItem('luatvietnam_customerdocs_' + resp.Data.DocId + '_' + resp.Data.CustomerId + '_' + resp.Data.LanguageId, function (response) {
                                if (response !== null) {
                                    respCustomerDocs = response;
                                }
                            });
                            if (respCustomerDocs === undefined) {
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': 0, 'hasTrackedDocumentEffect': isSave ? 1 : 0, 'hasEffectTrackingsAll': 0 },
                                    15 * 60);
                            } else {
                                if (isSave && respCustomerDocs.hasTrackedDocumentEffect < 1) {
                                    respCustomerDocs.hasTrackedDocumentEffect++;
                                } else {
                                    if (respCustomerDocs.hasTrackedDocumentEffect > 0)
                                        respCustomerDocs.hasTrackedDocumentEffect--;
                                }
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': respCustomerDocs.documentSaved, 'hasTrackedDocumentEffect': respCustomerDocs.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': respCustomerDocs.hasEffectTrackingsAll },
                                    15 * 60);
                            }
                            if (!isSave) {
                                if ($('.docitems-customer:checked').length == 0) {
                                    btnDoc.removeClass('active unsave').addClass('save');
                                }
                            } else {
                                btnDoc.removeClass('save').addClass('active unsave');
                            }
                        }
                    }
                });
            });
    },
    checkCustomerLoginByParent: function (element, customerName) {
        try {
            if (lawsVnConfig.changeTimer) clearTimeout(lawsVnConfig.changeTimer);
            changeTimer = setTimeout(function () {
                $('.ic-show-pass, .iconpass').hide();
                $.ajax({
                    url: '/ajax/checkloginbyparentcustomer',
                    dataType: 'json',
                    type: 'GET',
                    data: { customerName },
                    success: function (response) {
                        if (response != null && response.Id > 0) {
                            element.attr('readonly', true);
                            $('input[type=password]').addClass('password');
                        }
                        else {
                            $('.ic-show-pass, .iconpass').show();
                        };
                        lawsVnConfig.changeTimer = false;
                    }
                });
            }, 300);
        } catch (e) {
            console.log(e)
        }
    },
    isMobile: function () {
        return ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent));
    },
    removeAccents: function (str) {
        str = str.toLowerCase();
        str = str
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[đĐ]/g, 'd')
            .replace(/[^\w]+/g, '-');
        return str;
    },
    debounce: function (func, delay = 500) {
        let timeout

        return function executedFunc(...args) {
            if (timeout) {
                clearTimeout(timeout)
            }

            timeout = setTimeout(() => {
                func(...args)
                timeout = null
            }, delay)
        }
    },
    b64DecodeUnicode: function (str) {
        return decodeURIComponent(atob(str).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    },
    getLinkFile: function (params) {
        const mediadomain = 'https://static.luatvietnam.vn/';
        const docUrl = window.location.pathname;
        const array = docUrl.split('/');
        let slug = '';

        for (let i = 0; i < array.length; i++) {
            if (array[i].includes('.html')) {
                slug = array[i].replace('.html', '');
                break;
            }
        }

        if (slug.length > 0) {
            return `${mediadomain}tai-noi-dung-nen-zip-${slug}/${params}.aspx`;
        }
    },
    getCustomerFolders: function (docId = 0, folderId = 0) {
        let popup = $('#_luuvanban')

        if (docId <= 0) {
            lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] })
            return
        }

        lawsVn.fetchData(
            {
                url: '/ajax/GetCustomerDocFolders',
                dataType: 'html',
                type: 'GET',
                data: { docId: docId },
                beforeSend: () => {
                    $('#loading').fadeIn('normal');
                },
                always: () => {
                    $('#loading').fadeOut('normal');
                }
            })
            .then((response) => {
                if (response != null && response.length > 0) {
                    popup.find('.popup-title').first().text('Chọn danh mục văn bản cần lưu')
                    popup.find('#_luuvanban_result').first().html(response)
                    popup.find('#AddCustomerFolder_DocId').first().val(docId)
                    if (folderId > 0) {
                        $(`input.checkbox_[value="${folderId}"]`, $('#_luuvanban_result')).prop('checked', true)
                    }
                    var form = $('#AddCustomerFolderForm');
                    form.removeData('validator');
                    form.removeData('unobtrusiveValidation');
                    $.validator.unobtrusive.parse(form);
                    popup.removeClass('target-hidden')
                    popup.addClass('target-expanded').css('display', '')
                }
            })
            .catch((error) => {
                console.error(error)
                //appModule.hideLoading()
                //lawsVn.showMessage({ messages: ['Quý khách vui lòng thử lại sau.'] })
            })
    },
    bindCustomerDocument: function (docId, customerId, languageId, isSave) {
        let element = $('.customer-doc'), keyStorage = `luatvietnam_customerdocs_${docId}_${customerId}_${languageId}`, dataCustomerDocs

        luatVietnamStore.getItem(keyStorage, function (data) {
            if (data !== null) {
                dataCustomerDocs = data;
            }
        });
        if (dataCustomerDocs === undefined) {
            luatVietnamStore.setItem(keyStorage,
                { 'documentSaved': isSave, 'hasTrackedDocumentEffect': 0, 'hasEffectTrackingsAll': 0 },
                15 * 60);
        } else {

            if (isSave > 0 && dataCustomerDocs.documentSaved < 1) {
                dataCustomerDocs.documentSaved++;
            } else {
                if (dataCustomerDocs.documentSaved > 0)
                    dataCustomerDocs.documentSaved--;
            }

            luatVietnamStore.setItem(keyStorage,
                {
                    'documentSaved': dataCustomerDocs.documentSaved, 'hasTrackedDocumentEffect': dataCustomerDocs.hasTrackedDocumentEffect, 'hasEffectTrackingsAll': dataCustomerDocs
                        .hasEffectTrackingsAll
                },
                15 * 60);
        }

        if (isSave <= 0) {
            element.removeClass('active unsave').addClass('save').attr('title', 'Lưu văn bản').find('span').text('Lưu');
        } else {
            element.removeClass('save').addClass('active unsave').attr('title', 'Bỏ lưu văn bản').find('span').text('Bỏ lưu');
        }
    },
    adsSticky: function (ads) {
        try {
            var sticky_ads_content = ads, parent = ads.parent(),
                positionTop = sticky_ads_content.data('top'),
                end_sticky_ads = sticky_ads_content.data('id');
            positionTop = positionTop || 50;
            end_sticky_ads = end_sticky_ads || $('footer');
            setTimeout(function () {
                var sticky_ads_content_top = sticky_ads_content.offset().top;
                $(window).scroll(function () {
                    var scrollTop = $(window).scrollTop();
                    sticky_ads = sticky_ads_content.prev('.sticky-ads'),
                        end_sticky = $(end_sticky_ads).offset().top - sticky_ads.outerHeight();
                    if (sticky_ads_content_top < scrollTop) {
                        sticky_ads.css({ position: 'fixed', top: positionTop, left: parent.offset().left, width: parent.width() });
                        sticky_ads.addClass('sidebar-scrollbar');
                    }
                    else {
                        sticky_ads.css('position', 'static');
                        sticky_ads.removeClass('sidebar-scrollbar');
                    }
                    if (end_sticky < scrollTop) {
                        var diff = end_sticky - scrollTop + -20;
                        sticky_ads.css({ top: diff });
                        sticky_ads.addClass('sidebar-scrollbar')
                    }
                });
            }, 500);
        } catch (e) {
            console.error(e);
        }
    },

    getWindowDims: function () {
        var doc = document, w = window;
        var docEl = (doc.compatMode && doc.compatMode === 'CSS1Compat') ? doc.documentElement : doc.body;
        var width = docEl.clientWidth;
        var height = docEl.clientHeight;
        // mobile zoomed in?
        if (w.innerWidth && width > w.innerWidth) {
            width = w.innerWidth;
            height = w.innerHeight;
        }
        return { width: width, height: height };
    },
    topFunction: function () {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    },
    fetchData: function (options) {
        return new Promise((resolve, reject) => {
            $.ajax({
                cache: false,
                url: options.url,
                type: options.type || 'GET',
                data: options.data || {},
                dataType: options.dataType || 'json',
                timeout: options.timeOut || 35000,
                beforeSend: options.beforeSend || showLoading(),
                success: function (data) {
                    resolve(data);
                },
                error: function (error) {
                    reject(error);
                }
            }).always(options.always || hideLoading());
        });
    },
    reloadIFrame: function () {
        var iframe = document.getElementById('luatvietnam-iframe');
        if (iframe.contentDocument != null && iframe.contentDocument.URL != null && iframe.contentDocument.URL == 'about:blank') {
            iframe.src = iframe.src;
        }
    },
    loadScript: function (src, async = true, type = 'text/javascript') {
        return new Promise((resolve, reject) => {
            try {
                const el = document.createElement("script");
                const container = document.head || document.body;

                el.type = type;
                el.async = async;
                el.src = src;

                el.addEventListener("load", () => {
                    resolve({ status: true });
                });

                el.addEventListener("error", () => {
                    reject({
                        status: false,
                        message: `Failed to load the script ${src}`
                    });
                });

                container.appendChild(el);
            } catch (err) {
                reject(err);
            }
        });
    },
    docDuThaoAnalyzes: function (docId) {
        if (typeof docId != 'undefined') {
            lawsVn.fetchData(
                {
                    url: '/docs/duthaoanalyzes.html',
                    /* url: '/docs/analyzes.html',*/
                    dataType: 'json',
                    type: 'post',
                    data: { docId: docId },
                    beforeSend: function () { },
                    always: function () { }
                })
                .then((response) => {
                    if (response != null && response.Data != null) {
                        var docAnalyes, boldTag, hasIconPTVB;
                        $.each(response.Data, function (i, docItemId) {
                            var docitem = docItemId.toString().replace('-', '');
                            docAnalyes = $('.noidungtracuu').find(`[data-id="${docitem}"]`).first();
                            if (docAnalyes.length == 0) {
                                docAnalyes = $('.noidungtracuu').find(`[data-id="${-docItemId}"]`).first();
                            }
                            if (docAnalyes) {
                                boldTag = docAnalyes.find('b').last();
                                hasIconPTVB = docAnalyes.find('.bg_phantich');
                                if (hasIconPTVB.length) {

                                }
                                else {
                                    if (boldTag.length) {
                                        $(`<a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích văn bản">Phân tích</span>`).insertAfter(boldTag);
                                    } else {
                                        docAnalyes.append(`<a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích văn bản">Phân tích</span>`);
                                    }
                                }
                            }
                        });


                    }
                })
                .catch((error) => {
                    console.error(error)
                })
        }
    }, docAnalyzes: function (docId) {
        if (typeof docId != 'undefined') {
            lawsVn.fetchData(
                {
                    url: '/docs/analyzes.html',
                    dataType: 'json',
                    type: 'post',
                    data: { docId: docId },
                    beforeSend: function () { },
                    always: function () { }
                })
                .then((response) => {
                    if (response != null && response.Data != null) {
                        var docAnalyes, boldTag, hasIconPTVB;
                        let isLogin = true, permission = true;
                        $('.text-thongbao', $('#hieuluc')).lawsExists(function () {
                            if ($(this).hasClass('not-loggedin')) {
                                isLogin = false;
                                permission = false;
                            }
                            else if ($(this).hasClass('not-have-access'))
                                permission = false;
                        });
                        $.each(response.Data, function (i, docItemId) {
                            docAnalyes = $('.noidungtracuu').find(`[data-id="${docItemId}"]`).first();
                            if (docAnalyes) {
                                boldTag = docAnalyes.find('b').last();
                                hasIconPTVB = docAnalyes.find('.bg_phantich');
                                if (hasIconPTVB.length) {

                                }
                                else {
                                    if (boldTag.length) {
                                        if (!isLogin) {
                                            $(`<div class="tooltip-button"> <a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích">Phân tích</a>
                                                <div class="tooltip-chidan2">
                                                  <div class="tooltip-boxs">
                                                    <div class="text-theo-doi2">
                                                      <div>Đây là tiện ích dành cho thành viên đăng ký phần mềm.<br>
                                                        Quý khách vui lòng <span data-toggle-target="#_login" data-tab="login" class="btn-login2 link-color underline">đăng nhập</span> tài khoản gói <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="link-color underline">Phân tích văn bản Vàng</a> hoặc <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="link-color underline">Phân tích văn bản Bạch kim</a> để xem chi tiết. <br/>
                                                        Nếu chưa có tài khoản, Quý khách đăng ký <span data-toggle-target="#_login" data-tab="register" class="btn-login2 link-color underline">tại đây!</span>
                                                        </div>
                                                    </div>
                                                  </div>
                                                </div>
                                              </div>`).insertAfter(boldTag);
                                        } else if (!permission) {
                                            $(`<div class="tooltip-button"> <a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích">Phân tích</a>
                                                <div class="tooltip-chidan2">
                                                  <div class="tooltip-boxs">
                                                    <div class="text-theo-doi2">
                                                      <div>Đây là tiện ích dành cho thành viên đăng ký phần mềm.<br>
                                                        Quý khách vui lòng đăng nhập tài khoản gói <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="link-color underline">Phân tích văn bản Vàng</a> hoặc <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="link-color underline">Phân tích văn bản Bạch kim</a> để xem chi tiết. </div>
                                                    </div>
                                                  </div>
                                                </div>
                                              </div>`).insertAfter(boldTag);
                                        }
                                        else {
                                            $(`<a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích văn bản">Phân tích</span>`).insertAfter(boldTag);
                                        }
                                    } else {
                                        if (!isLogin) {
                                            docAnalyes.append(`<div class="tooltip-button"> <a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích">Phân tích</a>
                                                <div class="tooltip-chidan2">
                                                  <div class="tooltip-boxs">
                                                    <div class="text-theo-doi2">
                                                      <div>Đây là tiện ích dành cho thành viên đăng ký phần mềm.<br>
                                                        Quý khách vui lòng <span data-toggle-target="#_login" data-tab="login" class="btn-login2 link-color underline">đăng nhập</span> tài khoản gói <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="link-color underline">Phân tích văn bản Vàng</a> hoặc <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="link-color underline">Phân tích văn bản Bạch kim</a> để xem chi tiết. <br/>
                                                        Nếu chưa có tài khoản, Quý khách đăng ký <span data-toggle-target="#_login" data-tab="register" class="btn-login2 link-color underline">tại đây!</span>
                                                        </div>
                                                    </div>
                                                  </div>
                                                </div>
                                              </div>`)
                                        } else if (!permission) {
                                            docAnalyes.append(`<div class="tooltip-button"> <a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích">Phân tích</a>
                                                <div class="tooltip-chidan2">
                                                  <div class="tooltip-boxs">
                                                    <div class="text-theo-doi2">
                                                      <div>Đây là tiện ích dành cho thành viên đăng ký phần mềm.<br>
                                                        Quý khách vui lòng đăng nhập tài khoản gói <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Vàng" target="_blank" class="link-color underline">Phân tích văn bản Vàng</a> hoặc <a href="/phan-tich-van-ban.html" title="Phân tích văn bản Bạch kim" target="_blank" class="link-color underline">Phân tích văn bản Bạch kim</a> để xem chi tiết. </div>
                                                    </div>
                                                  </div>
                                                </div>
                                              </div>`)
                                        } else {
                                            docAnalyes.append(`<a href="javascript:void(0)" rel="nofollow" data-id="${docId}" data-item="${docItemId}" class="bg_phantich" title="Phân tích văn bản">Phân tích</span>`);
                                        }
                                    }
                                }
                            }
                        });


                    }
                })
                .catch((error) => {
                    console.error(error)
                })
        }
    }, docRelatedKeywords: (docId) => {
        if (typeof docId != 'undefined') {
            lawsVn.fetchData(
                {
                    url: '/docs/related-keywords.html',
                    dataType: 'html',
                    type: 'post',
                    data: { docId: docId },
                    beforeSend: function () { },
                    always: function () { }
                })
                .then((response) => {
                    if (response != null && response.length > 0) {
                        $('#document-related-keywords').html(response)
                    }
                })
                .catch((error) => {
                    console.error(error)
                })
        }
    },
    customerDocItemsNotes: [],
    processCustomerNoteTooltip: function (element, docItemId, docItemFiles) {
        var followTerms = true;
        docItemId = docItemId || $(element).attr('data-id')
        const docItemHasNote = $(element).find('.tooltip-button.note').first(),
            docItemClassAttr = $(element).attr('class'),
            docItemHasTrackingAll = $('#chidanthaydoi').find('.tooltip-button.effect-tracking-all').first(),
            docItemHasTracking = $(element).find('.tooltip-button.effect-tracking').first()
        var userManualNote = null, hasUserManual = false

        if (docItemClassAttr &&
            (docItemClassAttr.indexOf('docitem-8') != -1 ||
                docItemClassAttr.indexOf('docitem-9') != -1 ||
                docItemClassAttr.indexOf('docitem-13') != -1 ||
                docItemClassAttr.indexOf('docitem-14') != -1 ||
                docItemClassAttr.indexOf('docitem-15') != -1)) {
            return
        }
        var parent = $(element).parents('#chidanthaydoi');
        if (parent.length) {
            var attrHasfollowterms = $(parent).attr('hasfollowterms');
            if (typeof attrHasfollowterms !== 'undefined') {
                followTerms = JSON.parse(attrHasfollowterms.toLowerCase());
            }
        }

        luatVietnamStore.getItem('user_manual_note_customer_note',
            response => {
                if (response !== null) {
                    userManualNote = response;
                }
            })

        if (userManualNote == null) {
            $($('.div-hdsd').first()).removeClass('target-hidden')
        }

        hasUserManual = $(element).find('.div-hdsd').length > 0;

        const docItemFileId = docItemFiles.filter(x => x.DocItemId == docItemId)
            .map(x => x.DocFileId)
            .join(',');

        const textThongbao = $('.text-thongbao', $('#hieuluc')).first();

        let isLogin = false, btnTaiBieumau = ''

        if (textThongbao.length) {
            if (textThongbao.hasClass('not-loggedin')) {
                isLogin = false;

                btnTaiBieumau = `<div class="div-taibieumau tip-bmhover">
						<span class="btn-taibieumau">Tải biểu mẫu <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3 14v6a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-6M12 3v14m0 0-5-5.444M12 17l5-5.444" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg></span>
						<div class="tip-bmcontent">
							 <p>Đây là tiện ích dành cho thành viên đăng ký phần mềm.</p><p>Quý khách vui lòng <a href="javascript:void(0)" rel="nofollow" title="Đăng nhập" class="link-color underline lawsVnLogin">Đăng nhập</a> tài khoản LuatVietnam và <a href="/dich-vu.html" target="_blank" title="Đăng ký phần mềm" class="link-color underline">đăng ký sử dụng Phần mềm tra cứu văn bản.</a></p>
						</div>
					</div>`
            }
        }
        else {
            isLogin = true;

            btnTaiBieumau = `<div class="div-taibieumau">
						<span class="btn-taibieumau" data-id="${docItemFileId + ''}">Tải biểu mẫu <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3 14v6a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-6M12 3v14m0 0-5-5.444M12 17l5-5.444" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg></span>
					</div>`
        }

        $(element).find('.document-tip').remove()
        var tooltip = `<div class="document-tip">
                            ${docItemFileId.length ? btnTaiBieumau : ''}
                            <div class="document-tip-r">
								<div class="btn-tip-r-more tooltip-1">
									<span class="btn-tip-r"><i class="iconlvn-more"></i></span>
									<div class="tooltip-content-1 w-tip-r">
										<ul data-item-id="${docItemId}" class="ul-tip-r">`
        if (followTerms) {
            if (docItemHasTrackingAll.length > 0) {
                tooltip += `<li><a href="javascript:void(0)" rel="nofollow" class="tracked-doc-effect active"><i class="iconlvn-bookmark-outline"></i> Đang theo dõi</a></li>`
            }
            else if (docItemHasTracking.length > 0) {
                tooltip += `<li><a href="javascript:void(0)" rel="nofollow" class="cancel-tracking-effect active"><i class="iconlvn-bookmark-outline"></i> Hủy theo dõi</a></li>`
            } else {
                tooltip += `<li><a href="javascript:void(0)" rel="nofollow" class="effect-tracking"><i class="iconlvn-bookmark-outline"></i> Theo dõi điều khoản</a></li>`
            }
        }
        tooltip += `<li><a href="javascript:void(0)" rel="nofollow" title="Sao chép điều, khoản văn bản" class="customer-note-copy"><i class="ic icon-single-copy-04lvn"></i> Sao chép</a></li>`
        if (docItemHasNote.length > 0) {
            tooltip += `<li><span class="link-popupghichu edit" title="Sửa ghi chú" data-id="${docItemId}"><i class="iconlvn-pencil"></i> Sửa ghi chú</span></li>
                                                            <li><a href="javascript:void(0)" rel="nofollow" title="Xóa ghi chú" class="customer-remove-note" data-id="${docItemId}"><i class="iconlvn-bin"></i> Xóa ghi chú</a></li>`
        } else {
            tooltip += `<li><span class="link-popupghichu create" title="Ghi chú"><i class="iconlvn-pencil"></i> Ghi chú</span></li>`
        }
        tooltip += `</ul>
									</div>
								</div>`
        if (userManualNote == null && $('.document-tip', '#chidanthaydoind').length == 0 || hasUserManual) {
            tooltip += `<div class="div-hdsd target-hidden">
								                        <span class="iconlvn-triangle-sm-up ics-hdsd" style="right: 3%;"></span>
								                        <div class="div-text-hdsd">
									                        <strong>Tính năng cho từng điều khoản: </strong><br>
									                        - Theo dõi điều khoản: Các thay đổi về nội dung như sửa đổi, bổ sung, thay thế, bãi bỏ, đính chính... của điều khoản sẽ được thông báo cho bạn.<br>
									                        - Sao chép: Sao chép điều khoản và dán vào bất cứ đâu.<br>
									                        - Ghi chú: Thêm ghi chú cá nhân cho điều khoản.
								                        </div>
							                        <div class="div-next"><a href="javascript:void(0)" id="finish-viewing-user-manual-customer-note" title="Hoàn tất">Hoàn tất</a></div>
						                        </div>`
        }
        `</div>
                        </div>`
        $(element).prepend($(tooltip))
    },
    processCustomerNoteButton: function (docItemId, note, docId) {
        const parent = $('#chidanthaydoind'),
            stickyNote = $('.stickygc'), stickyNoteParent = stickyNote.closest('.tooltip-button'),
            customerNote = parent.find(`[data-id="${docItemId}"]`).first(),
            docAnalyzyButton = $(customerNote).find('.bg_phantich').first(),
            showPersonalNote = $('#doc-view-mode option:selected').val() == 2 ? '' : ' target-hidden',
            docItemCustomerButton = $(customerNote).find('.tooltip-button.effect-tracking').first(),
            htmlButton = `<div data-id="${docItemId}" class="tooltip-button note">
                                    <span class="bg-ghi-chu">Ghi chú cá nhân</span>
                                    <div class="tooltip-chidan">
                                    <div class="tooltip-boxs">
                                        <div class="text-theo-doi">${note}</div>
                                        <div class="row-btn">
										    <a href="javascript:void(0)" class="btn-edit-ghi-chu" title="Sửa ghi chú" data-id="${docItemId}"><i class="iconlvn-pencil"></i> Sửa ghi chú</a>
										</div>
                                    </div>
                                    </div>
                                </div>
                                <div class="docitem-gccn${showPersonalNote}">
									<div class="div-gccn-1">Ghi chú cá nhân:</div>
									<div class="div-noidung-gccn">
										${note}
									</div>
								</div>`

        if (docItemId == 0) {
            let headDoc = parent.find('div.docitem-13').first()
            stickyNoteParent.find('.tooltip-chidan.posi-right').remove();
            if (!docId) {
                docId = $('#chidanthaydoi').attr('data-id') || 0;
            }
            stickyNoteParent.append(`
            <div class="tooltip-chidan posi-right">
				<div class="tooltip-boxs">
                    <div class="head-ghichu">Ghi chú cá nhân</div>
					<div class="text-theo-doi">${note}</div>
					<div class="row-btn">
                    <span class="btn-download-ghi-chu" data-id="${docId}"><i class="iconlvn-download-file icdwn"></i> Tải ghi chú</span>
					<span class="btn-edit-ghi-chu all"><i class="iconlvn-pencil"></i> Sửa ghi chú</span>
					</div>
				</div>
			</div>
            `);

            if (headDoc.length > 0) {
                $('.docitem-gccn-head').remove();
                headDoc.after(`<div class="docitem-gccn-head${showPersonalNote}">
									<div class="div-gccn-1">Ghi chú cá nhân:</div>
									<div class="div-noidung-gccn">
										${note}
									</div>
								</div>`);
            }
        }

        else if (customerNote) {
            customerNote.find('.tooltip-button.note, .docitem-gccn').remove()

            if (docAnalyzyButton.length > 0 && docItemCustomerButton.length == 0) {
                docAnalyzyButton.after(htmlButton)
            } else if (docItemCustomerButton.length > 0) {
                $(docItemCustomerButton).after(htmlButton)
            } else if (docAnalyzyButton.length > 0) {
                docAnalyzyButton.after(htmlButton)
            } else {
                if (parent.hasClass('duthaond'))//du thao
                {
                    customerNote.children().not('.document-tip').first().append(htmlButton);
                }
                else {
                    customerNote.append(htmlButton);
                }
            }
        }
    },
    processDocItemCustomerButton: function (docItemId) {
        var parent = $('#chidanthaydoind'),
            docItemCustomer = parent.find(`[data-id="${docItemId}"]`).first(),
            docAnalyzyButton = $(docItemCustomer).find('.bg_phantich').first(),
            customerNoteButton = $(docItemCustomer).find('.tooltip-button.note').first(),
            htmlButton = docItemId == -1 ?
                `<div class="tooltip-button effect-tracking-all">
				<span class="bg-theo-doi-hieu-luc">Đang theo dõi</span>
				<div class="tooltip-chidan">
					<div class="tooltip-boxs">
						<div class="text-theo-doi">Bạn đang theo dõi tất cả điều khoản văn bản này.  Các thay đổi về nội dung như sửa đổi, bổ sung, thay thế, bãi bỏ, đính chính... của điều khoản sẽ được thông báo cho bạn. </div>
	                    <div class="text-theo-doi">Để huỷ theo dõi tất cả điều khoản, bạn vui lòng <a href="javascript:void(0)" data-id="0" class="cancel-tracking-effect" title="Hủy theo dõi">click Huỷ theo dõi</a>. </div>
					</div>
				</div>
			</div>`
                : `<div class="tooltip-button effect-tracking">
					<span class="bg-theo-doi-hieu-luc">Đang theo dõi</span>
					<div class="tooltip-chidan">
						<div class="tooltip-boxs">
							<div class="text-theo-doi">Bạn đang theo dõi điều khoản này. Các thay đổi về nội dung như sửa đổi, bổ sung, thay thế, bãi bỏ, đính chính... của điều khoản sẽ được thông báo cho bạn. </div>
							<div class="text-theo-doi">Để huỷ theo dõi, bạn vui lòng <a href="javascript:void(0)" data-id="${docItemId}" class="cancel-tracking-effect" title="Hủy theo dõi">click Huỷ theo dõi</a>. </div>
						</div>
					</div>
				</div>`
        if (docItemId == -1) {
            docItemCustomer = parent.find('div.docitem-13').first()
            if (docItemCustomer) {
                docAnalyzyButton = $(docItemCustomer).find('.bg_phantich').first(),
                    customerNoteButton = $(docItemCustomer).find('.tooltip-button.note').first()

                $(docItemCustomer).find('.tooltip-button.effect-tracking').remove()
                if (docAnalyzyButton.length > 0) {
                    docAnalyzyButton.after(htmlButton);
                } else if (customerNoteButton.length > 0) {
                    $(customerNoteButton).before(htmlButton);
                } else {
                    $(docItemCustomer).append(htmlButton)
                }
            }
        }
        else if (docItemCustomer) {
            $(docItemCustomer).find('.tooltip-button.effect-tracking').remove()
            if (docAnalyzyButton.length > 0) {
                docAnalyzyButton.after(htmlButton);
            } else if (customerNoteButton.length > 0) {
                $(customerNoteButton).before(htmlButton);
            } else {
                $(docItemCustomer).append(htmlButton)
            }
        }
    },
    stickyCustomerNote: function (menugc, sticky) {
        //if (typeof stickygc === 'undefined' || !jQuery.isNumeric(stickygc)) stickygc = 0;
        //if ($(window).scrollTop() >= stickygc) {
        //    menugc.addClass("stickyghichu");
        //} else {
        //    menugc.removeClass("stickyghichu");
        //}
        //const height = $('#sticky-note-height')
        if (typeof sticky === 'undefined' || !jQuery.isNumeric(sticky)) sticky = 0;
        if ($(window).scrollTop() >= sticky) {
            //if (height.length === 0) {
            //menugc.after(`<div id="sticky-note-height" style="height:${ menugc.height() }px"></div>`)
            //}
            menugc.addClass("stickyghichu");
        } else {
            menugc.removeClass("stickyghichu");
            //height.remove();
        }
    },
    customerNotes: function (docId, customerId, docItemFiles) {
        if (typeof docId != 'undefined') {
            const parent = $('#chidanthaydoind'),
                docItemsElement = parent.find('div[data-id]')
            docItemsElement.each(function (index, item) {
                lawsVn.customerDocItemsNotes.push(item);
            })
            //docItemFiles = []; //tạm off
            if (typeof customerId != 'undefined' && customerId > 0) {
                Promise.all([lawsVn.fetchData(
                    {
                        url: '/docs/customer-notes.html',
                        dataType: 'json',
                        type: 'post',
                        data: { docId: docId },
                        beforeSend: function () { },
                        always: function () { }
                    }), lawsVn.fetchData(
                        {
                            url: '/docs/docitem-customers.html',
                            dataType: 'json',
                            type: 'post',
                            data: { docId: docId },
                            beforeSend: function () { },
                            always: function () { }
                        })]).then(response => {

                            if (response != null) {
                                $.each(response[1].Data, function (i, item) {
                                    lawsVn.processDocItemCustomerButton(item.Id)
                                });

                                $.each(response[0].Data, function (i, item) {
                                    lawsVn.processCustomerNoteButton(item.Id, item.Name, docId)
                                });

                                $.each(lawsVn.customerDocItemsNotes, function (index, element) {
                                    let docItemId = $(element).attr('data-id');

                                    lawsVn.processCustomerNoteTooltip(element, docItemId, docItemFiles)
                                })
                            }

                        }).catch(error => {
                            console.error(error)
                        })
            }
            else {
                $.each(lawsVn.customerDocItemsNotes, function (index, element) {
                    var docItemId = $(element).attr('data-id');
                    lawsVn.processCustomerNoteTooltip(element, docItemId, docItemFiles)
                })
            }
        }
    },
    showMessage: function (options) {
        var defaults = {
            id: '_message',
            buttons: [{
                Name: 'Đóng',
                ClassName: 'btn-law',
                ClickEvent: {}
            }],
            callback: {},
            success: true,
            title: 'Thông báo',
            messages: [],
            returnUrl: ''
        }
        options = $.extend(defaults, options);
        options.messages = $.isArray(options.messages) ? options.messages : [];
        var popup = `<div id="${options.id}" class="popup-bg target-hidden"> <div class="popup-wrapper popup-340"> <div class="popup-body"> <div class="popup-content"> <div class="form-pad16"> <div class="form-group text-center"> <div class="text-successful color-orange">${options.title}</div> </div> <div class="form-group text-center text-content">`;
        if (options.messages.length > 0) {
            popup += '<div class="form-group text-center text-content">';
            for (var i = 0; i < options.messages.length; i++) {
                popup += '<p>' + options.messages[i] + '</p>';
            }
            popup += `</div>
            <div class="form-group popup-button text-center">`;
            if (options.buttons.length > 0) {
                for (var i = 0; i < options.buttons.length; i++) {
                    if (options.buttons[i].Name == 'Đóng') {
                        popup += `<span class="btn-law" data-toggle-target="#${options.id}">Đóng</span>`;
                    } else {
                        popup += `<span class="${options.buttons[i].ClassName}">${options.buttons[i].Name}</span>`;
                    }
                }
            }
            popup += '</div>';
        }

        if (options.success) {
            $(`#${options.id}`).remove();
            $('body').append(popup);
            for (var i = 0; i < options.buttons.length; i++) {
                var el = options.buttons[i];
                var event = el.ClickEvent;
                $(`#${options.id}`).on('click',
                    `.${el.ClassName}`,
                    $.isFunction(event) ? event : $.noop
                );
            }
        }
        $('#' + options.id).addClass('target-expanded').css('display', '');
    },
    closePopup: function (popup) {
        popup = popup || '.popup-bg'
        $(popup).removeClass('target-expanded').css('display', '');
        $('html').css({ overflow: 'inherit' });
        $('body').css({ overflow: 'inherit' });
    },
    docComment: function (el) {
        el.lawsExists(function () {
            el.find('.box-text-content').lawsExists(function () {
                var selector = $(this);
                if (selector.text().trim().length >= 70) {
                    el.find('.more-full').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                }
            });
        });
        $('#ReverseEffect').lawsExists(function () {
            var messages = $(this).text();
            $('.ReverseEffect_').text(messages);
            if ($('#wmptnyfgm0') && $('#cep3ie7532').length == 0)
                $('<p id="cep3ie7532" style="margin-top: 10px; color: #bb6b0a;">' + messages + '</p>').insertAfter('#wmptnyfgm0');
            if ($('.ReverseEffect') && $('#eu8pjcyuwi').length == 0)
                $('.ReverseEffect').append('<div id="eu8pjcyuwi" class="item-meta" style="color: #bb6b0a;font-style: italic;">' + messages.replace('Khoản 4 -', 'Khoản 4-') + '</div>');
        });
    },
    CheckboxTermsAndConditionsRequired: function () {
        var errorElement = $('span[data-valmsg-for="TermsAndConditions"]');
        var errorMessage = lawsVn.Resource.getMessages('TermsAndConditions');
        if ($('[id*=TermsAndConditions]:checked').length == 0) {
            errorElement.addClass('field-validation-error').removeClass('field-validation-valid').text(errorMessage);
            return false;
        } else
            errorElement.addClass('field-validation-valid').removeClass('field-validation-error').text('');
        return true;
    },
    createCookie: function (name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
            var expires = "; expires=" + date.toGMTString();
        } else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },
    readCookie: function (name) {
        var nameEq = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1, c.length);
            } if (c.indexOf(nameEq) == 0) return c.substring(nameEq.length, c.length);
        }
        return null;
    },
    getValueFromCookie: function (name) {
        var value = [], hash;
        var cookieValue = lawsVn.readCookie(name);
        if (typeof cookieValue !== "undefined" && cookieValue != null) {
            var hashes = cookieValue.split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                value.push(hash[0]);
                value[hash[0]] = hash[1];
            }
        }
        return value;
    },
    getParameterByName: function (name, url) {
        if (!url) {
            url = window.location.href.toLowerCase();
        }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name.toLowerCase() + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    },
    virtualPath: function (patch) {
        var host = window.location.protocol + '//' + window.location.host;
        return host + patch;
    },
    Cookies: {
        getItem: function (key) {
            var name = key + "=";
            var decodedCookie = decodeURIComponent(document.cookie);
            var ca = decodedCookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return 'vi';
        }
    },
    Resource: {
        getCulture: function () {
            return lawsVn.Cookies.getItem('LuatVietNamCulture');
        },
        designer: Array(
            { name: 'Message', culture: { en: 'Message', vi: 'Thông báo' } },
            { name: 'Close', culture: { en: 'Close', vi: 'Đóng' } },
            { name: 'Agree', culture: { en: 'Agree', vi: 'Đồng ý' } },
            { name: 'Cancel', culture: { en: 'Cancel', vi: 'Hủy' } },
            { name: 'Login', culture: { en: 'Login', vi: 'Đăng nhập' } },
            { name: 'RegisterService', culture: { en: 'Register Service', vi: 'Đăng ký phần mềm' } },
            { name: 'Renewal', culture: { en: 'Renewal', vi: 'Gia hạn' } },
            { name: 'Convert', culture: { en: 'Convert', vi: 'Chuyển đổi' } },
            { name: 'UserNameInvalid', culture: { en: 'Username does not include spaces, only includes letters and numbers.', vi: 'Tên truy cập không bao gồm khoảng trắng, chỉ bao gồm chữ cái và số.' } },
            { name: 'ServiceLoginMessages', culture: { en: 'To sign up for the text search service on LuatVietnam.vn, please <br/> log in to Vietnam Law Account and make registration under the guide. <br/> <span style = "font-weight : normal; color: # a67942; "> If you do not have an account? Click on <a href="/user/dang-ky-tai-khoan.html" title="Sign up for an account" style="color:#a67942;"> <b> Account Registration </b> </a>. </span>', vi: 'Để đăng ký phần mềm Tra cứu văn bản trên LuatVietnam.vn, Quý khách vui lòng <br/> đăng nhập tài khoản Luật Việt Nam và thực hiện đăng ký theo hướng dẫn.<br/><span style="font-weight:normal;color:#a67942;">Nếu Quý khách chưa có tài khoản? Bấm vào <a href="/user/dang-ky-tai-khoan.html" title="Đăng ký tài khoản" style="color:#a67942;"><b>Đăng ký tài khoản</b></a>.</span>' } },
            { name: 'CommentInformation', culture: { en: 'Payment information', vi: 'Thông tin chú thích' } },
            { name: 'TransferInformation', culture: { en: 'Payment information', vi: 'Thông tin chuyển khoản' } },
            { name: 'PleaseEnterAPhoneNumber', culture: { en: 'Please enter a phone number.', vi: 'Quý khách vui lòng nhập số điện thoại.' } },
            { name: 'InvalidPhoneNumber', culture: { en: 'Invalid phone number! Please enter valid number of 84xxxxxx or 0xxxxxx.', vi: 'Số điện thoại không đúng ! Số điện thoại hợp lệ dạng 84xxxxxxxxx hoặc 0xxxxxxxxx.' } },
            { name: 'PleaseEnterTheDiscountCode', culture: { en: 'Please enter discount code.', vi: 'Quý khách vui lòng nhập mã giảm giá.' } },
            { name: 'Discount', culture: { en: 'Discount', vi: 'Giảm giá' } },
            { name: 'User', culture: { en: 'user', vi: 'người' } },
            { name: 'Users', culture: { en: 'users', vi: 'người' } },
            { name: 'Month', culture: { en: 'month', vi: 'tháng' } },
            { name: 'Months', culture: { en: 'months', vi: 'tháng' } },
            { name: 'NumMonthFree', culture: { en: 'Num month free', vi: 'Tháng miễn phí' } },
            { name: 'NumDayFree', culture: { en: 'Num day free', vi: 'Ngày miễn phí' } },
            { name: 'LoginAccountAndPay', culture: { en: 'Login account and pay', vi: 'Đăng nhập và thanh toán' } },
            { name: 'CreateAccountAndPay', culture: { en: 'Create account and pay', vi: 'Tạo tài khoản và thanh toán' } },
            { name: 'SelectTheNumberOfUsersAtATime', culture: { en: 'Select the number of users at a time', vi: 'Quý khách vui lòng chọn số người dùng tại một thời điểm' } },
            { name: 'TermsAndConditions', culture: { en: 'Please agree to the LuatVietnam.vn Terms of Use', vi: 'Vui lòng chọn đồng ý với Quy ước sử dụng của Luật Việt Nam' } },
            { name: 'AreYouSureYouWantToLogout', culture: { en: 'Are you sure you want to log out?', vi: 'Quý khách muốn đăng xuất khỏi hệ thống?' } },
            { name: 'Available', culture: { en: 'Available', vi: 'Có thể sử dụng' } },
            { name: 'SelectSubscriptionDuration', culture: { en: 'Select subscription duration', vi: 'Quý khách vui lòng chọn thời hạn thuê bao' } }
        ),
        getMessages: function (name) {
            var culture = this.getCulture();
            var retval = $.map(this.designer, function (value, key) {
                if (value.name == name) {
                    return value.culture[culture];
                }
            });
            return retval.length > 0 ? retval[0] : '';
        }
    },
    ajaxEvents: {
        pageIndex: $('#txtChangePage').val(),
        showNumberOfResults: $('#dllNumberOfResults').length ? $('#dllNumberOfResults option:selected').val() : 20,
        pageTitle: $('title').text(),
        OnBegin: function () {
            $('#loading').fadeIn('normal');
            $('.btn-login').lawsExists(function () {
                $(this).attr('disabled', 'disabled');
            });
        },
        OnComplete: function (element) {
            $('#loading').fadeOut('normal');
            if (element && typeof element == 'string' && lawsVn.isDomElement($('#' + element))) {
                $('#' + element).lawsExists(function () {
                    $(this).LawScrollTo();
                });
            }
            //$('#lawsVnLogin').lawsExists(function () {
            //    $(this).dialog('close');
            //}); 
            var form = $('#abc');
            form.removeData('validator');
            form.removeData('unobtrusiveValidation');
            $.validator.unobtrusive.parse(form);

            $('.no-permission').lawsExists(function () {
                //if (!$('.no-permission').is(':ui-tooltip')) {
                $('.no-permission').tooltip({
                    content: function () {
                        return $(this).prop('title');
                    },
                    position: {
                        at: 'center bottom',
                        my: 'left top'
                    },
                    show: {
                        effect: "slideDown",
                        delay: 250
                    },
                    close: function (event, ui) {
                        ui.tooltip.hover(
                            function () {
                                $(this).stop(true).fadeTo(400, 1);
                            },
                            function () {
                                $(this).fadeOut("400",
                                    function () {
                                        $(this).remove();
                                    });
                            });
                    }
                });
                //}
            });
        },
        OnCompleteV2: function (element) {
            $('#loading').fadeOut('normal');
            if (element && typeof element == 'string' && lawsVn.isDomElement($('#' + element))) {
                $('#' + element).lawsExists(function () {
                    $(this).LawScrollTo();
                });
            }
            $('.no-permission').lawsExists(function () {
                //if (!$('.no-permission').is(':ui-tooltip')) {
                $('.no-permission').tooltip({
                    content: function () {
                        return $(this).prop('title');
                    },
                    position: {
                        at: 'center bottom',
                        my: 'left top'
                    },
                    show: {
                        effect: "slideDown",
                        delay: 250
                    },
                    close: function (event, ui) {
                        ui.tooltip.hover(
                            function () {
                                $(this).stop(true).fadeTo(400, 1);
                            },
                            function () {
                                $(this).fadeOut("400",
                                    function () {
                                        $(this).remove();
                                    });
                            });
                    }
                });
                //}
            });
            var pageIndex = 1;
            $('.pagination-item.active').lawsExists(function () {
                pageIndex = $(this).text();
            });
            var idx = lawsVn.ajaxEvents.pageTitle.indexOf('- trang');
            if (idx > 0)
                lawsVn.ajaxEvents.pageTitle = lawsVn.ajaxEvents.pageTitle.substring(0, idx);
            var pageTitle = lawsVn.ajaxEvents.pageIndex > 1
                ? lawsVn.ajaxEvents.pageTitle + ' - trang ' + lawsVn.ajaxEvents.pageIndex
                : lawsVn.ajaxEvents.pageTitle;
            var listfield = $("input[name='lFieldId']:checked").map(function () {
                return this.value;
            }).get();
            var lOrganId = $('[name=lOrganId]').val();
            var field = listfield.join(",");
            var f = $('input[name=FieldId]').val();
            var organid = lOrganId;
            var effectstatusid = $('[name=lEffectStatusId]').val();
            var year = $('[name=lYear]').val();
            var Provinces = $('[name=ddlProvinces]').val();
            var OrderBy = $('select[name=OrderBy]').val();
            var keywords = $('input[name=keywords]').val();
            var DocTypeId = $('[name=lDocTypeId]').val();
            var ShowSapo = $('[name=ShowSapo]').val();
            var url = lawsVn.replaceUrlParam({
                'page': pageIndex > 1 ? pageIndex : '',
                'pSize': lawsVn.ajaxEvents.showNumberOfResults,
                'year': typeof (year) != "undefined" ? year : '',
                'organId': typeof (organid) != "undefined" ? organid : '',
                'fieldId': typeof (field) != "undefined" && field.length > 0 ? field : (typeof (f) != "undefined" && f > 0 ? f : ''),
                'effectStatusId': typeof (effectstatusid) != "undefined" ? effectstatusid : '',
                'OrderBy': typeof (OrderBy) != "undefined" ? OrderBy : '',
                'keywords': typeof (keywords) != "undefined" ? keywords : '',
                'provinceId': typeof (provinceId) != "undefined" ? provinceId : '',
                'docTypeId': typeof (DocTypeId) != "undefined" ? DocTypeId : '',
                'showsapo': typeof (ShowSapo) != "undefined" ? ShowSapo : ''
            });
            lawsVn.setTitleAndHistory(pageTitle, url);
            $('#DocElasticSearch_Total').lawsExists(function () {
                var el = $(this);
                $('input[type="hidden"][name="DocElasticSearch_Total"]').lawsExists(function () {
                    var total = $(this).val();
                    if ($.isNumeric(total) && total != 0) {
                        $('#DocElasticSearch_Total_Text').lawsExists(function () {
                            $('#DocElasticSearch_Total').lawsExists(function () {
                                $(this).text(total);
                            });
                            $(this).show();
                        });
                    } else {
                        $('#DocElasticSearch_Total_Text').lawsExists(function () {
                            $(this).hide();
                        });
                    }
                });
            });
            $('.search-params-ajax').lawsExists(function () {
                var el = $(this);
                $('.search-params').lawsExists(function () {
                    $(this).html(el.html());
                });
            });
            $('.text-help').lawsExists(function () {
                var t = $(this);
                $('.field-keywords').lawsExists(function () {
                    if ($(this).val().trim() != '') {
                        t.removeClass('hidden');
                    }
                });
            });
            $('.div-orderby').lawsExists(function () {
                var t = $(this);
                $('.field-keywords').lawsExists(function () {
                    if ($(this).val().trim() != '') {
                        t.addClass('hidden');
                    } else t.removeClass('hidden');
                });
            });
        },
        OnCompleteV3: function (element) {
            $('#loading').fadeOut('normal');
            if (element && typeof element == 'string' && lawsVn.isDomElement($('#' + element))) {
                $('#' + element).lawsExists(function () {
                    $(this).LawScrollTo();
                });
            }
            $('.no-permission').lawsExists(function () {
                //if (!$('.no-permission').is(':ui-tooltip')) {
                $('.no-permission').tooltip({
                    content: function () {
                        return $(this).prop('title');
                    },
                    position: {
                        at: 'center bottom',
                        my: 'left top'
                    },
                    show: {
                        effect: "slideDown",
                        delay: 250
                    },
                    close: function (event, ui) {
                        ui.tooltip.hover(
                            function () {
                                $(this).stop(true).fadeTo(400, 1);
                            },
                            function () {
                                $(this).fadeOut("400",
                                    function () {
                                        $(this).remove();
                                    });
                            });
                    }
                });
                //}
            });
            $('#FaqsSearchTotal').lawsExists(function () {
                var el = $(this);
                $('input[type="hidden"][name="FaqsSearch_Total"]').lawsExists(function () {
                    var total = $(this).val();
                    if ($.isNumeric(total)) {
                        $('#FaqsSearchTotal').lawsExists(function () {
                            $(this).text(total);
                        });
                    }
                });
            });
            $('#SearchResultHidden').lawsExists(function () {
                var el = $(this);
                var value;
                var docCount;
                $('input[type="hidden"][name="SearchResult_DocGroups"]').lawsExists(function () {
                    var ListDocGroup = $('input[type="hidden"][name="SearchResult_DocGroups"]');
                    //$('span[id^="SearchFormDocGroup_"]').html(' (0)');
                    if (ListDocGroup.length > 0) {
                        for (var index = 0; index < ListDocGroup.length; index++) {
                            var DocGroupItem = ListDocGroup[index];
                            value = DocGroupItem.getAttribute("value");
                            docCount = DocGroupItem.getAttribute('data-DocCount');
                            if ($.isNumeric(value)) {
                                $('#SearchFormDocGroup_' + value).lawsExists(function () {
                                    $(this).text(' (' + docCount + ')');
                                });
                            }
                        }
                    }
                });
                $('input[type="hidden"][name="SearchResult_Fields"]').lawsExists(function () {
                    var ListField = $('input[type="hidden"][name="SearchResult_Fields"]');
                    //$('span[id^="SearchFormField_"]').html(' (0)');
                    if (ListField.length > 0) {
                        for (var index = 0; index < ListField.length; index++) {
                            var item = ListField[index];
                            value = item.getAttribute("value");
                            docCount = item.getAttribute('data-DocCount');
                            if ($.isNumeric(value)) {
                                $('#SearchFormField_' + value).lawsExists(function () {
                                    $(this).text(' (' + docCount + ')');
                                });
                            }
                        }
                    }
                });
                $('input[type="hidden"][name="SearchResult_DocTypes"]').lawsExists(function () {
                    var ListDocType = $('input[type="hidden"][name="SearchResult_DocTypes"]');
                    //$('span[id^="SearchFormDocType_"]').html(' (0)');
                    if (ListDocType.length > 0) {
                        for (var index = 0; index < ListDocType.length; index++) {
                            var item = ListDocType[index];
                            value = item.getAttribute("value");
                            docCount = item.getAttribute('data-DocCount');
                            if ($.isNumeric(value)) {
                                $('#SearchFormDocType_' + value).lawsExists(function () {
                                    $(this).text(' (' + docCount + ')');
                                });
                            }
                        }
                    }
                });
                $('input[type="hidden"][name="SearchResult_EffectStatus"]').lawsExists(function () {
                    var ListEffectStatus = $('input[type="hidden"][name="SearchResult_EffectStatus"]');
                    //$('span[id^="SearchFormEffectStatus_"]').html(' (0)');
                    if (ListEffectStatus.length > 0) {
                        for (var index = 0; index < ListEffectStatus.length; index++) {
                            var item = ListEffectStatus[index];
                            value = item.getAttribute("value");
                            docCount = item.getAttribute('data-DocCount');
                            if ($.isNumeric(value)) {
                                $('#SearchFormEffectStatus_' + value).lawsExists(function () {
                                    $(this).text(' (' + docCount + ')');
                                });
                            }
                        }
                    }
                });
                $('input[type="hidden"][name="SearchResult_Organs"]').lawsExists(function () {
                    var ListOrgans = $('input[type="hidden"][name="SearchResult_Organs"]');
                    //$('span[id^="SearchFormOrgan_"]').html(' (0)');
                    if (ListOrgans.length > 0) {
                        for (var index = 0; index < ListOrgans.length; index++) {
                            var item = ListOrgans[index];
                            value = item.getAttribute("value");
                            docCount = item.getAttribute('data-DocCount');
                            if ($.isNumeric(value)) {
                                $('#SearchFormOrgan_' + value).lawsExists(function () {
                                    $(this).text(' (' + docCount + ')');
                                });
                            }
                        }
                    }
                });
                $('input[type="hidden"][name="SearchResult_Years"]').lawsExists(function () {
                    var ListYear = $('input[type="hidden"][name="SearchResult_Years"]');
                    //$('span[id^="SearchFormYear_"]').html(' (0)');
                    if (ListYear.length > 0) {
                        for (var index = 0; index < ListYear.length; index++) {
                            var item = ListYear[index];
                            value = item.getAttribute("value");
                            docCount = item.getAttribute('data-DocCount');
                            if ($.isNumeric(value)) {
                                $('#SearchFormYear_' + value).lawsExists(function () {
                                    $(this).text(' (' + docCount + ')');
                                });
                            }
                        }
                    }
                });
            });
            $('#AbsoluteUri').lawsExists(function () {
                lawsVn.setTitleAndHistory(lawsVn.ajaxEvents.pageTitle, $('#AbsoluteUri').val());
            });
            //var pageIndex = $('#ArticlesByCateBox').find('.post-listing:last').data('page');
            //$('#pagination-loadmore').lawsExists(function () {
            //    if (lawsVnConfig.pageCount > 2) {
            //        $(this).remove();
            //    }else
            //    $(this).attr('data-page', pageIndex+1);
            //});
            //var idx = lawsVn.ajaxEvents.pageTitle.indexOf('- trang');
            //if (idx > 0)
            //    lawsVn.ajaxEvents.pageTitle = lawsVn.ajaxEvents.pageTitle.substring(0, idx);
            //var pageTitle = pageIndex > 1
            //    ? lawsVn.ajaxEvents.pageTitle + ' - trang ' + pageIndex
            //    : lawsVn.ajaxEvents.pageTitle;
            //var url = lawsVn.replaceUrlParam({ 'page': pageIndex > 1 ? pageIndex : '' });
            //lawsVn.setTitleAndHistory(pageTitle, url);
        },
        OnSuccess: function (data, status, xhr) {
            if (data.Message != null && data.Message.length > 0) {
                if (data.Message === 'ModelStateInValid') {
                    $().lawsDialog({
                        messages: ['Quý khách vui lòng kiểm tra lại các thông tin có cảnh báo màu đỏ.'],
                        dialogClass: 'lawsVnDialogTitle'
                    });
                } else
                    $().lawsDialog({
                        messages: [data.Message],
                        dialogClass: 'lawsVnDialogTitle',
                        onClose: function () {
                            var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
                            activeDialogs.dialog('close');
                        }
                    });
            }
        },
        ResponsiveOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $('#_message').lawsExists(function () {
                    $(this).find('.text-content').first().html('<p>' + data.Message + '</p>');
                    $(this).removeClass('target-hidden').addClass('target-expanded');
                    $('.popup-bg.target-expanded').not(this).removeClass('target-expanded').addClass('target-hidden');
                });
            } else if (data.Message != null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                    data.Message = data.Message.replace(/"/g, "'");
                    var str = data.Message.match(/'(.*?)'/g);
                    if (str != null) username = str[1];
                }
                $('#_message').lawsExists(function () {
                    $(this).find('.text-content').first().html('<p>' + (username.length > 0
                        ? 'Tài khoản: <b>' +
                        username +
                        '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                        : data.Message) + '</p>');
                    $(this).removeClass('target-hidden').addClass('target-expanded');
                });
            }
        },
        OnSuccessV6: function (response, status, xhr) {
            if (response != null) {
                if (response.Message != null) {
                    var username = '', msg = response.Message;
                    if (response.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                        response.Message = response.Message.replace(/"/g, "'");
                        var str = response.Message.match(/'(.*?)'/g);
                        if (str != null) username = str[1];

                        msg = username.length > 0
                            ? 'Tài khoản: <b>' +
                            username +
                            '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                            : response.Message;
                        msg += '<p>Để được hỗ trợ về đăng nhập tài khoản, Quý khách vui lòng liên hệ với LuatVietnam:</p>';
                        msg += '<p>Hotline: <a href="tel:0938361919" title="Hotline: 0938361919" style="color: #ed1d35">0938361919</a></p>';
                        msg += '<p>Email: <a href="mailto:cskh@luatvietnam.vn" title="Email: cskh@luatvietnam.vn">cskh@luatvietnam.vn</a></p>';
                    }

                    lawsVn.showMessage({
                        autoClose: true,
                        buttons: [{
                            Name: 'Đóng',
                            ClassName: 'btn-law',
                            ClickEvent: function () {

                                if ($(this).attr('data-clicked')) {
                                    return
                                }

                                if (!response.Completed) {
                                    return;
                                }

                                if (response.Callback != null && response.Callback.length > 0) {
                                    eval(lawsVn.b64DecodeUnicode(response.Callback));
                                    return;
                                }

                                $(this).attr('data-clicked', true)

                                if (response.Completed && response.ReturnUrl != null) {
                                    window.location.href = response.ReturnUrl;
                                    return;
                                }
                            }
                        }],
                        messages: [msg]
                    });
                } else if (response.Completed) {
                    if (response.ReturnUrl != null) {
                        window.location.href = response.ReturnUrl;
                        return;
                    }

                    if (response.Callback != null && response.Callback.length > 0) {
                        eval(b64DecodeUnicode(response.Callback));
                    }
                } else {
                    if (response.ReturnUrl != null) {
                        window.location.href = response.ReturnUrl;
                        return;
                    }
                }
            }
            //hideLoading();
        },
        OnCustomerNoteSuccess: function (response, status, xhr) {
            lawsVn.closePopup('#_popupghichu, #_popupeditghichu')
            if (response.Completed) {
                const docItemId = response.Data.Id || 0,
                    note = response.Data.Name || '',
                    element = lawsVn.customerDocItemsNotes.filter(x => $(x).attr('data-id') == docItemId)

                if (docItemId > 0 && note.trim().length > 0) {
                    lawsVn.processCustomerNoteButton(docItemId, note)
                    lawsVn.processCustomerNoteTooltip(element)
                }

                lawsVn.showMessage({ messages: [response.Message] });
            } else if (response.Message != null && response.Message.length > 0) {
                var username = '';
                if (response.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                    response.Message = response.Message.replace(/"/g, "'");
                    var str = response.Message.match(/'(.*?)'/g);
                    if (str != null) username = str[1];
                }

                lawsVn.showMessage({
                    messages: [(username.length > 0
                        ? 'Tài khoản: <b>' +
                        username +
                        '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                        : response.Message)]
                });
            }
        },
        OnCustomerDocNoteSuccess: function (response, status, xhr) {
            lawsVn.closePopup('#_popupghichu_vanban')
            lawsVn.closePopup('#_popupeditghichu')
            if (response.Completed) {
                const docNote = $('#CustomerDocNoteForm #Note').val();
                $('#CustomerDocNoteForm #Note').val('');
                lawsVn.processCustomerNoteButton(0, docNote);
                lawsVn.showMessage({ messages: [response.Message] });
            } else if (response.Message != null && response.Message.length > 0) {
                var username = '';
                if (response.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                    response.Message = response.Message.replace(/"/g, "'");
                    var str = response.Message.match(/'(.*?)'/g);
                    if (str != null) username = str[1];
                }

                lawsVn.showMessage({
                    messages: [(username.length > 0
                        ? 'Tài khoản: <b>' +
                        username +
                        '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                        : response.Message)]
                });
            }
        },
        FeedBackOnSuccess: function (data, status, xhr) {
            var form = $('#FormGopYv2'), msg = form.find('#FeedBacksMessages');
            if (data.Completed) {
                $('#Comment', form).val('');
                $('#CaptchaCode', form).val('');
            }
            if (data.Message !== null && data.Message.length > 0) {
                appModule.showMessage({ messages: [data.Message] });
            }
            form.remove()
            $('#_gopy').addClass('target-hidden').removeClass('target-expanded');
            $('.getcaptcha', form).trigger('click');
        },
        OnFailure: function (jqXhr, errorMessage) {
            $('#loading').fadeOut('normal');
            $('.popup-bg').lawsExists(function () {
                $(this).hide();
            });
            if (jqXhr.status === 0) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.']
                    , showIcon: false
                });
            } else if (jqXhr.status === 404) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Không tìm thấy trang yêu cầu. [404]']
                    , showIcon: false
                });
            } else if (jqXhr.status === 500) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Lỗi máy chủ nội bộ. [500].']
                    , showIcon: false
                });
            } else if (errorMessage === 'parsererror') {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Yêu cầu phân tích cú pháp JSON lỗi.']
                    , showIcon: false
                });
            } else if (errorMessage === 'timeout') {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Hết thời gian yêu cầu.']
                    , showIcon: false
                });
            } else if (errorMessage === 'abort') {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Yêu cầu xử lý bị hủy.']
                    , showIcon: false
                });
            } else if (jqXhr.status !== 403) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Lỗi :.n' + jqXhr.responseText]
                    , showIcon: false
                });
            }
        },
        AccountLoginLogs: function (data, status, xhr) {
            if (data.Completed) {
                if (data.Data != null && data.Data != 'TheAccountIsLoggedin') {
                    lawsVn.logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                }
            }
            else if (data.Message != null && data.Message.length > 0) {
                if (data.Data != null && data.Data.length > 0) {
                    source = data.Data
                }
                lawsVn.logs.webpagelogs("Login", pageUrl, data.Message.indexOf('Vui lòng đăng xuất khỏi các thiết bị khác để có thể đăng nhập từ thiết bị này của bạn') != -1 ? 'Vượt quá số thiết bị truy cập' : data.Message, source);
            }
        },
        AccountLoginOnSuccess: function (data, status, xhr) {
            $('#tabPannel').lawsExists(function () {
                lawsVn.preventAnchorScroll();
            });
            if (data.Completed) {
                $('#login-form-target').lawsExists(function () {
                    $(this).removeClass('target-expanded').addClass('target-hidden');
                });
                //$('#lawsVnLoginForm').bind('submit', function (e) { e.preventDefault(); });
                //window.location.replace(data.ReturnUrl);
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                    //Kích hoạt tk thành công => chuyển hướng về homepage
                    if (data.ReturnUrl.indexOf('NewUserActive') !== -1) {
                        window.location.assign(lawsVnConfig.rootPath);
                    } else if (data.ReturnUrl == '/giao-dien-ca-nhan.html') {
                        setTimeout(function () {
                            window.location.href = data.ReturnUrl;
                        },
                            100);
                    } else if (data.ReturnUrl == '/user/dang-ky-linh-vuc-quan-tam.html') {
                        setTimeout(function () {
                            window.location.href = data.ReturnUrl;
                        },
                            100);
                    }
                    else if (data.ReturnUrl == '/user/dang-nhap-tai-khoan.html') {
                        setTimeout(function () {
                            window.location.href = lawsVnConfig.rootPath;
                        },
                            100);
                    } else if (data.ReturnUrl == '/pldn/dang-nhap-tai-khoan.html') {
                        setTimeout(function () {
                            window.location.href = '/phap-ly-doanh-nghiep.html';
                        },
                            100);
                    }
                    else {
                        setTimeout(function () {
                            window.location.href = data.ReturnUrl;
                            //location.reload();
                        },
                            100);
                    }
                } else window.location.href = lawsVnConfig.rootPath;
            } else if (data.Message != null && data.Message.length > 0) {
                $('.btn-login').removeAttr('disabled', 'disabled');
                //$('#lawsVnLoginForm').unbind('submit');
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                    data.Message = data.Message.replace(/"/g, "'");
                    var str = data.Message.match(/'(.*?)'/g);
                    if (str != null) username = str[1];
                }
                var msg = username.length > 0
                    ? 'Tài khoản: <b>' +
                    username +
                    '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                    : data.Message;
                msg += '<p style="font-size:12px;">Để được hỗ trợ về đăng nhập tài khoản, Quý khách vui lòng liên hệ với LuatVietnam:</p>';
                msg += '<p style="font-size:12px;">Hotline: <a href="tel:0938361919" title="Hotline: 0938361919" style="color: #ed1d35">0938361919</a></p>';
                msg += '<p style="font-size:12px;">Email: <a href="mailto:cskh@luatvietnam.vn" title="Email: cskh@luatvietnam.vn">cskh@luatvietnam.vn</a></p>';
                msg += '<p style="font-size:12px;"><a href="javascript:void(0)" rel="nofollow" id="chat-online" title="Chat trực tuyến" style="color: #ed1d35">Chat trực tuyến</a></p>';
                $().lawsDialog({
                    messages: [msg],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false,
                    onOpen: function () {
                        $('#chat-online').on('click',
                            function (e) {
                                e.preventDefault();
                                $('.widget-layout.widget-layout--right').lawsExists(function () {
                                    if (!$(this).hasClass('widget-layout--hidden'))
                                        $(this).addClass('widget-layout--hidden');
                                });
                                $('.widget-container.widget-container--right').lawsExists(function () {
                                    if ($(this).hasClass('widget-container--hide'))
                                        $(this).removeClass('widget-container--hide');
                                });
                                var subizKey = 'sbz2020#items#isopen', isOpen = localStorage.getItem(subizKey);
                                if (typeof isOpen !== 'undefined') {
                                    var obj = JSON.parse(isOpen);
                                    obj.value = true;
                                    localStorage.setItem(subizKey, JSON.stringify(obj));
                                }
                                var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
                                activeDialogs.dialog('close');
                                $('.message-input--input').lawsExists(function () {
                                    $(this).focus();
                                });
                            });
                        $('.widget-header--button-close').on('click',
                            function (e) {
                                e.preventDefault();
                                $('.widget-layout.widget-layout--right').lawsExists(function () {
                                    $(this).removeClass('widget-layout--hidden');
                                });
                                $('.widget-container.widget-container--right').lawsExists(function () {
                                    if (!$(this).hasClass('widget-container--hide'))
                                        $(this).addClass('widget-container--hide');
                                });
                                var subizKey = 'sbz2020#items#isopen', isOpen = localStorage.getItem(subizKey);
                                if (typeof isOpen !== 'undefined') {
                                    var obj = JSON.parse(isOpen);
                                    obj.value = false;
                                    localStorage.setItem(subizKey, JSON.stringify(obj));
                                }
                            });
                    }
                });
            }
        },
        RedirectOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                    setTimeout(function () {
                        window.location.href = data.ReturnUrl;
                    },
                        100);
                    return false;
                }
            } else if (data.Message !== null && data.Message.length > 0) {
                $().lawsDialog({
                    messages: [data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                }); return false;
            }
        },
        RedirectOnSuccessV2: function (data, status, xhr) {
            if (data.Completed) {
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                    setTimeout(function () {
                        window.location.href = data.ReturnUrl;
                    }, 100);
                }
            } else if (data.Message !== null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant') > -1) {
                    var str = data.Message.match(/\"(.*?)\"/);
                    if (str != null) username = str[1];
                }

                $().lawsDialog({
                    messages: [username.length > 0 ? 'Tài khoản: <b>' + username + '</b> hiện đã hết thời gian đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.' : data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
                $('.btn-thanhtoan').lawsExists(function () {
                    $(this).removeAttr('requestRunning');
                });
            }
        },
        RedirectOnSuccessV3: function (data, status, xhr) {
            if (data.Completed) {
                if (data.Message !== null && data.Message.length > 0) {
                    $().lawsDialog({
                        messages: [data.Message],
                        dialogClass: 'lawsVnDialogTitle',
                        showIcon: false
                    });
                }
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                    setTimeout(function () {
                        window.location.href = data.ReturnUrl;
                    }, 100);
                }
            } else if (data.Message !== null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant') > -1) {
                    var str = data.Message.match(/\"(.*?)\"/);
                    if (str != null) username = str[1];
                }

                $().lawsDialog({
                    messages: [username.length > 0 ? 'Tài khoản: <b>' + username + '</b> hiện đã hết thời gian đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.' : data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
        },
        LoginOnSuccessful: function (data, status, xhr) {
            if (data.Completed) {
                $().lawsDialog({
                    messages: [data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false,
                    onOpen: function () {
                        $("#lawsVnLogin").dialog("close");
                    },
                    onClose: function () {
                        if (data.ReturnUrl != null && data.ReturnUrl.length > 0)
                            setTimeout(function () {
                                window.location.href = data.ReturnUrl;
                                location.reload();
                            },
                                100);
                        else window.location.href = lawsVnConfig.rootPath;
                    }
                });
            } else if (data.Message !== null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant') > -1) {
                    var str = data.Message.match(/\"(.*?)\"/);
                    if (str != null) username = str[1];
                }

                $().lawsDialog({
                    messages: [username.length > 0 ? 'Tài khoản: <b>' + username + '</b> hiện đã hết thời gian đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.' : data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
        },
        LoginOnSuccessfulRedirect: function (data, status, xhr) {
            if (data.Completed) {
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0)
                    setTimeout(function () {
                        window.location.href = data.ReturnUrl;
                        location.reload();
                    },
                        100);
                else window.location.href = lawsVnConfig.rootPath;
            } else if (data.Message !== null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant') > -1) {
                    var str = data.Message.match(/\"(.*?)\"/);
                    if (str != null) username = str[1];
                }

                $().lawsDialog({
                    messages: [username.length > 0 ? 'Tài khoản: <b>' + username + '</b> hiện đã hết thời gian đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.' : data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
        },
        OrderTCVNOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $('#_dat_mua_tcvn').find('.content-po').first().empty();
                $('#_dat_mua_tcvn').removeClass('target-expanded').addClass('target-hidden');
                $().Alert({
                    success: true,
                    buttons: [],
                    messages: ['<p class="pf14 color_green"><span class="ic icon-c-checklvn"></span> <strong>Quý khách đã đặt mua thành công!</strong></p> <p><em style="font-size:13px;">Chúng tôi sẽ liên hệ sớm với Quý khách.</em></p>']
                });
                luatVietnamStore.setItem(
                    'luatvietnam_order_tcvn_' +
                    data.Data.DocId +
                    '_' +
                    data.Data.CustomerId,
                    1,
                    3600 * 24 * 30);

            } else if (data.Message != null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                    data.Message = data.Message.replace(/"/g, "'");
                    var str = data.Message.match(/'(.*?)'/g);
                    if (str != null) username = str[1];
                }
                $().Alert({
                    success: true,
                    buttons: [],
                    callback: function () {
                        window.location.href = window.location.href;
                    },
                    messages: [
                        username.length > 0
                            ? '<p class="pf14 color-red">Tài khoản: <b>' +
                            username +
                            '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.</p>'
                            : '<p class="pf14 color-red"><strong>Yêu cầu của Quý khách chưa được gửi đi!</strong></p> <p><em class="pf14">Có thể do lỗi kết nối mạng hoặc sever phản hồi chậm. </em></p> <p><em>Xin Quý khách thông cảm và thực hiện lại!</em></p>'
                    ]
                });
            }
        },
        OnSuccessValid: function (element) {
            $('#loading').fadeOut('normal');
            $('#' + element).lawsExists(function () {
                var form = $('#' + element);
                form.removeData('validator');
                form.removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse(form);
            });
        },
        DocumentsTranslationRequiredOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $('#DocumentsTranslationRequiredForm').lawsExists(function () {
                    var cookieValue = 'FullName=' +
                        $(this).find(':input[name=FullName]').val() +
                        '&Email=' +
                        $(this).find(':input[name=Email]').val() +
                        '&Mobile=' +
                        $(this).find(':input[name=Mobile]').val(), customerRequestedDocTranslation;
                    lawsVn.createCookie('DocumentsTranslationRequired', cookieValue, 90);
                    $(this).closest('.lea-dk2').remove();
                    luatVietnamStore.getItem('luatvietnam_documents_translation_required_' + data.Data.DocId + '_' + data.Data.CustomerId, function (response) {
                        if (response !== null) {
                            customerRequestedDocTranslation = response;
                        }
                    });
                    if (customerRequestedDocTranslation === undefined) {
                        luatVietnamStore.setItem(
                            'luatvietnam_documents_translation_required_' +
                            data.Data.DocId +
                            '_' +
                            data.Data.CustomerId,
                            1,
                            3600 * 24 * 30);
                    }
                });
                //$().Alert({
                //    success: true,
                //    buttons: [],
                //    messages: ['<p class="pf14 "><strong>Yêu cầu của Quý khách đã được gửi đến LuatVietnam!</strong></p> <p><em>Cảm ơn quý khách đã sử dụng dịch vụ của LuatVietnam</em></p>']
                //});
                $('<div class="row-group-item"><div class="text-send">' +
                    '<p class="p-font18"><strong>Yêu cầu dịch văn bản của Quý khách đã được gửi đi!</strong> </p><p><em>Cảm ơn Quý khách đã quan tâm và sử dụng dịch vụ!</em></p>' +
                    '</div></div>').insertAfter($('#tienganh .block-dich-vb').find('.row-group-item').eq(2));
            } else if (data.Message != null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                    data.Message = data.Message.replace(/"/g, "'");
                    var str = data.Message.match(/'(.*?)'/g);
                    if (str != null) username = str[1];
                }
                $().lawsDialog({
                    messages: [
                        username.length > 0
                            ? 'Tài khoản: <b>' +
                            username +
                            '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                            : data.Message
                    ],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
        },
        DocumentsTranslationRequiredV2OnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $('#DocumentsTranslationRequiredForm').lawsExists(function () {
                    var cookieValue = 'FullName=' +
                        $(this).find(':input[name=FullName]').val() +
                        '&Email=' +
                        $(this).find(':input[name=Email]').val() +
                        '&Mobile=' +
                        $(this).find(':input[name=Mobile]').val(),
                        customerRequestedDocTranslation,
                        cold = $(this).closest('.col-info2');
                    lawsVn.createCookie('DocumentsTranslationRequired', cookieValue, 90);
                    //$(this).clearForm();
                    cold.find('.lea3').lawsExists(function () {
                        $(this).remove();
                    });
                    cold.find('.lea-dk2').lawsExists(function () {
                        $(this).remove();
                    });
                    cold.lawsExists(function () {
                        $(this).append('<div class="lea-dk33">' +
                            '<p style="font-size: 14px"><strong>Yêu cầu dịch văn bản của Quý khách đã được gửi đến LuatVietnam.</strong></p>' +
                            '<p style="font-size: 12px; padding-top: 3px;"><em>Cảm ơn Quý khách!</em></p></div>');
                    });
                    luatVietnamStore.getItem('luatvietnam_documents_translation_required_' + data.Data.DocId + '_' + data.Data.CustomerId, function (response) {
                        if (response !== null) {
                            customerRequestedDocTranslation = response;
                        }
                    });
                    if (customerRequestedDocTranslation === undefined) {
                        luatVietnamStore.setItem(
                            'luatvietnam_documents_translation_required_' +
                            data.Data.DocId +
                            '_' +
                            data.Data.CustomerId,
                            1,
                            3600 * 24 * 30);
                    }
                });
            } else if (data.Message != null && data.Message.length > 0) {
                var username = '';
                if (data.Message.indexOf('The provided anti-forgery token was meant for user') > -1) {
                    data.Message = data.Message.replace(/"/g, "'");
                    var str = data.Message.match(/'(.*?)'/g);
                    if (str != null) username = str[1];
                }
                $().lawsDialog({
                    messages: [
                        username.length > 0
                            ? 'Tài khoản: <b>' +
                            username +
                            '</b> hiện đã đăng nhập. Quý khách vui lòng refresh lại trang web để tiếp tục sử dụng.'
                            : data.Message
                    ],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
        },
        VbSapCoHieuLucOnComplete: function (data, status, xhr) {
            if (data != null && data.length > 0) {
                var total = $(data).filter('.content-document').data('tp');
                var page = $(data).filter('input[type=hidden][name=page_]').val(),
                    pageSize = $(data).filter('input[type=hidden][name=pageSize_]').val(),
                    folderId = $(data).filter('input[type=hidden][name=folderId_]').val(),
                    docTypeId = $(data).filter('input[type=hidden][name=docTypeId_]').val(),
                    organId = $(data).filter('input[type=hidden][name=organId_]').val(),
                    dateFrom = $(data).filter('input[type=hidden][name=dateFrom_]').val(),
                    dateTo = $(data).filter('input[type=hidden][name=dateTo_]').val(),
                    searchByTime = $(data).filter('input[type=hidden][name=searchByTime_]').val();
                if (typeof total != 'undefined') {
                    $('.3rqwct1oro').text('(' + total + ')');
                    $('.fbvcpq3kkq').text(total);
                    $('#wdpzcvun5e').text(total).closest('.fix-left').show();
                    $('#olhci8abx3').closest('.btn-item').show();
                }
                else {
                    $('.3rqwct1oro').text('');
                    $('#wdpzcvun5e').text('').closest('.fix-left').hide();
                    $('.fbvcpq3kkq').closest('div.row').text('');
                    $('#olhci8abx3').closest('.btn-item').hide();
                }
                if (typeof page != 'undefined') {
                    $('input[name="Page"]', $('#lz5kkbx51b')).val(page);
                }
                if (typeof pageSize != 'undefined') {
                    $('input[name="PageSize"]', $('#lz5kkbx51b')).val(pageSize);
                }
                if (typeof folderId != 'undefined') {
                    $('input[name="FolderId"]', $('#lz5kkbx51b')).val(folderId);
                }
                if (typeof docTypeId != 'undefined') {
                    $('input[name="DocTypeId"]', $('#lz5kkbx51b')).val(docTypeId);
                }
                if (typeof organId != 'undefined') {
                    $('input[name="OrganId"]', $('#lz5kkbx51b')).val(organId);
                }
                if (typeof dateFrom != 'undefined') {
                    $('input[name="DateFrom"]', $('#lz5kkbx51b')).val(dateFrom);
                }
                if (typeof dateTo != 'undefined') {
                    $('input[name="DateTo"]', $('#lz5kkbx51b')).val(dateTo);
                }
                if (typeof searchByTime != 'undefined') {
                    $('input[name="SearchByTime"]', $('#lz5kkbx51b')).val(searchByTime);
                }
            }
        },
        CustomerUpdateInfoOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                if ($('#_tipsthongbao_kq').length > 0) {
                    var tips = $('#_tipsthongbao_kq').first();
                    if (tips.find('.popup-content').children().length > 0) {
                        tips.removeClass('target-hidden').addClass('target-expanded');
                    }
                    tips.prev('.popup-bg').removeClass('target-expanded').addClass('target-hidden');
                    $('.tips-thong-bao').removeClass('target-expanded').addClass('target-hidden');
                }
            } else {
                $().lawsDialog({
                    messages: ['Quý khách vui lòng thử lại sau.'],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
        }
    },
    isDomElement: function (el) {
        return el instanceof HTMLElement ||
            el[0] instanceof HTMLElement
            ? true
            : false;
    },
    closeDialog: function () {
        var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
        activeDialogs.dialog('close');
    },
    closeDialogById: function (id) {
        $('#' + id).dialog('close');
    },
    formatNumber: function (nStr, decSeperate, groupSeperate) {
        nStr += '';
        var x = nStr.split(decSeperate);
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + groupSeperate + '$2');
        }
        return x1 + x2;
    },
    ResetForm: function (form) {
        form.find('input:text, input:password, input:file, select, textarea').val('');
        form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
        form.find('select').val('').trigger('change');
    },
    widgetUser: function () {
        $('#customerNameSub').lawsExists(function () {
            $('.customerNameSub').lawsExists(function () {
                $(this).text($('#customerNameSub').text());
            });
        });
        $('#user-vip').lawsExists(function () {
            $('.user-vip').lawsExists(function () {
                $(this).show();
            });
        });
        $('#countMyMessages').lawsExists(function () {
            $('.countMyMessages').lawsExists(function () {
                $(this).text($('#countMyMessages').text());
            });
        });
        $('#countMyDocuments').lawsExists(function () {
            $('.countMyDocuments').lawsExists(function () {
                $(this).text($('#countMyDocuments').text());
            });
        });
        $('#countNoticeOfValidity').lawsExists(function () {
            $('.countNoticeOfValidity').lawsExists(function () {
                $(this).text($('#countNoticeOfValidity').text());
            });
        });
        $('#countPaymentTransactionSuccess').lawsExists(function () {
            $('.countPaymentTransactionSuccess').lawsExists(function () {
                $(this).text($('#countPaymentTransactionSuccess').text());
            });
        });
        $('#countMyTranslations').lawsExists(function () {
            $('.countMyTranslations').lawsExists(function () {
                $(this).text($('#countMyTranslations').text());
            });
        });
        $('#gia-han-dv-header').lawsExists(function () {
            $('#gia-han-dv').lawsExists(function () {
                $(this).html($('#gia-han-dv-header').html());
            });
        });
    },
    FontZoom: function (zoomValue) {
        var curSize = parseInt($('div.content-entry').css('font-size')) + zoomValue; console.log(parseInt($('div.content-entry').css('font-size')))
        var curLineHeight = parseInt($('div.content-entry span').css('line-height'));
        if (!$.isNumeric(curLineHeight)) {
            curLineHeight = 20;
        }
        curLineHeight += zoomValue;
        if (curSize > 32)
            curSize = 32;
        if (curSize < 10)
            curSize = 10;
        if (curLineHeight > 32)
            curLineHeight = 32;
        if (curLineHeight < 10)
            curLineHeight = 10;
        $('div.content-entry,div.content-entry *').attr('style',
            function () { return 'font-size: ' + curSize.toString() + 'px' + ' !important;' + '; line-height: ' + curLineHeight.toString() + 'px' + ' !important;' });
    },
    SaveDoc: function (docId) {
        $.lawsAjax({
            url: lawsVn.virtualPath('/Ajax/SaveDocument'),
            data: { docId: docId },
            beforeSend: {},
            success: function (resp) {
                if (resp.Message != null && resp.Message.length > 0) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [resp.Message],
                        showIcon: false
                    });
                }
            }
        });
    },
    preventAnchorScroll: function () {
        var scrollToTop = function () {
            $(window).scrollTop(0);
        };
        if (window.location.hash) {
            $(window).one('scroll', scrollToTop);
        }
        $(function () {
            setTimeout(
                function () {
                    $(window).off('scroll', scrollToTop);
                },
                1000
            );
        });
    },
    scrollFunction: function () {
        if (document.getElementById("myBtn") != null) {
            if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
                document.getElementById("myBtn").style.display = "block";
            } else {
                document.getElementById("myBtn").style.display = "none";
            }
        }
    },
    login: function () {
        $('#login-form-target').lawsExists(function () {
            $(this).removeClass('target-hidden').addClass('target-expanded');
            $('.tabs-login-item[data-content="dangnhap"]').trigger('click');
        });
        $('#_login').lawsExists(function () {
            $(this).removeClass('target-hidden').addClass('target-expanded');
            $('.tabs-login-item[data-content="dangnhap"]').trigger('click');
        });
    },
    changePassword: function () {
        $('<div id="changePassword"></div>').lawsDialog({
            title: '',
            width: 300,
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#changePassword').load(lawsVn.virtualPath('/Ajax/PartialChangePassword'),
                    function () {
                        var form = $('#lawsVnChangePasswordForm');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    forgotPassword: function () {
        $('<div id="lawForgotPassword"></div>').lawsDialog({
            title: '',
            width: 400,
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#lawForgotPassword').load(lawsVn.virtualPath('/Ajax/PartialForgotPassword'),
                    function () {
                        var form = $('#ForgotPasswordForm');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    gopy: function (docName) {
        $('<div id="gopy"></div>').lawsDialog({
            title: '',
            width: 600,
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#gopy').load(lawsVn.virtualPath('/Ajax/PartialGopY'),
                    function () {
                        $('#FormGopY #Title').lawsExists(function () {
                            $(this).val(docName);
                        });
                        $('#FormGopY #TitleText').lawsExists(function () {
                            $(this).text(docName);
                        });
                        var form = $('#FormGopY');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    docSendMail: function (docUrl, docName) {
        $('<div id="docSendMail"></div>').lawsDialog({
            title: '',
            width: 400,
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
                var elem = $('.content-thongbao');
                elem.removeAttr('width');
                elem.css('width', '100%');
            },
            onOpen: function () {
                $('#docSendMail').load(lawsVn.virtualPath('/Ajax/PartialDocSendMail'),
                    function () {
                        $('#DocSendMailForm #DocUrl').val(docUrl);
                        $('#DocSendMailForm #DocName').val(docName);
                        var form = $('#DocSendMailForm');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    logOut: function () {
        $().lawsDialog({
            dialogClass: 'lawsVnDialogTitle',
            messages: [lawsVn.Resource.getMessages('AreYouSureYouWantToLogout')],
            buttons: [
                {
                    text: lawsVn.Resource.getMessages('Cancel'),
                    'class': 'btn-thongbao1',
                    click: function () {
                        $(this).dialog('close');
                    }
                },
                {
                    text: lawsVn.Resource.getMessages('Agree'),
                    click: function () {
                        $(this).dialog('close');
                        lawsVn.logs.webpagelogs('pageview', '/user/dang-xuat-tai-khoan.html', pageTitle, source);
                        window.location.href = lawsVn.virtualPath('/user/dang-xuat-tai-khoan.html');
                    }
                }
            ]
        });
    },
    account: {
        registerFreeService: function (serviceId) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận đăng ký gói phần mềm miễn phí ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/RegisterFreeService'),
                                type: 'Post',
                                data: { serviceId: serviceId },
                                success: function (resp) {
                                    if (resp.Completed) {
                                        if (resp.Completed && resp.ReturnUrl !== void 0 && resp.ReturnUrl.length > 0) {
                                            window.location.href = resp.ReturnUrl;
                                        }
                                    } else if (resp.Message !== void 0 && resp.Message.length > 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [resp.Message],
                                            showIcon: false
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        registerTrialService: function (serviceId) {
            return;
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận đăng ký gói phần mềm dùng thử ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/RegisterTrialService'),
                                type: 'Post',
                                data: { serviceId: serviceId },
                                success: function (resp) {
                                    if (resp.Message != null && resp.Message.length > 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [resp.Message],
                                            showIcon: false,
                                            onClose: function () {
                                                if (resp.Completed && resp.ReturnUrl != null && resp.ReturnUrl.length > 0) {
                                                    window.location.href = resp.ReturnUrl;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        deleteNewsletterMembers: function () {
            var newsletterMemberIds = $('.newsletterMembers input[type=checkbox]:checked').map(function (_, el) {
                return $(el).val();
            }).get();
            if (!newsletterMemberIds.length) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách chưa chọn tài khoản liên kết cần xóa.'],
                    showIcon: false
                });
                return;
            }
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận xóa tài khoản liên kết ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/NewsletterMembersDelete'),
                                type: 'Post',
                                traditional: true,
                                data: { newsletterMemberIds: newsletterMemberIds },
                                success: function (resp) {
                                    if (resp.Message != null && resp.Message.length > 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [resp.Message],
                                            showIcon: false,
                                            onClose: function () {
                                                if (resp.Completed && resp.ReturnUrl != null && resp.ReturnUrl.length > 0) {
                                                    window.location.href = resp.ReturnUrl;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
    },
    logs: {
        articleLogs: function (articleId, categoryId) {
            $.lawsAjax({
                url: lawsVn.virtualPath('/Ajax/ArticleLogs'),
                async: true,
                data: { articleId: articleId, categoryId: categoryId },
                beforeSend: {},
                success: function (resp) {
                    if (!resp.Completed) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            console.log('ArticleLogs Error: ' + resp.Message);
                        }
                    }
                },
                error: function (resp) {
                    console.log('articleLogs Error: ' + resp.Message);
                }
            });
        },
        docViewLogs: function (docId, docGroupId, actionTypeId) {
            $.lawsAjax({
                url: lawsVn.virtualPath('/Ajax/DocViewLogs'),
                async: true,
                data: { docId: docId, docGroupId: docGroupId, actionTypeId: actionTypeId },
                beforeSend: {},
                success: function (resp) {
                    if (!resp.Completed) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            console.log('DocViewLogs Error: ' + resp.Message);
                        }
                    }
                },
                error: function (resp) {
                    console.log('DocViewLogs Error: ' + resp.Message);
                }
            });
        },
        webpagelogs: function (logtype, pageUrl, pageTitle, referSource, pageData) {
            var userLang = navigator.language || navigator.userLanguage;
            var colorDepth = screen.colorDepth;
            var screenS = screen.width + 'x' + screen.height;
            var viewport = screen.availWidth + 'x' + screen.availHeight;
            var preTop = localStorage.getItem("preTop");
            if (preTop == null) {
                preTop = 0;
            }
            var preLeft = localStorage.getItem("preLeft");
            if (preLeft == null) {
                preLeft = 0;
            }
            var preWidth = localStorage.getItem("preWidth");
            if (preWidth == null) {
                preWidth = 0;
            }
            var preHeight = localStorage.getItem("preHeight");
            if (preHeight == null) {
                preHeight = 0;
            }
            var preDom = localStorage.getItem("preDom");
            if (preDom == null) {
                preDom = "";
            }
            var preItem = localStorage.getItem("preItem");
            if (!preItem) {
                preItem = 0;
            }
            var ppTime = localStorage.getItem("ppTime");
            if (ppTime == null) {
                ppTime = Number(new Date());
            }
            var ppTimeEnd = localStorage.getItem("ppTimeEnd");
            if (ppTimeEnd == null) {
                ppTimeEnd = Number(new Date());
            }
            var objData = {
                t: logtype,
                dl: pageUrl,
                dt: pageTitle,
                ul: userLang,
                sd: colorDepth,
                sr: screenS,
                vp: viewport,
                rs: referSource,
                pt: preTop,
                pl: preLeft,
                ppt: ppTime,
                ph: preHeight,
                pw: preWidth,
                pe: preDom,
                pi: preItem,
                pte: ppTimeEnd
            };
            var isEmpty = typeof pageData == 'string' && !pageData.trim() || typeof pageData == 'undefined' || pageData === null;
            if (!isEmpty) {
                objData.pgd = pageData;
            }
            window.setTimeout(function () {

                $.lawsAjax({
                    url: lawsVn.virtualPath('/log'),
                    data: objData,
                    async: true,
                    beforeSend: {},
                    success: function (resp) {

                    },
                    error: function (resp) {
                        console.log('webpagelogs Error: ' + resp.Message);
                    }
                });
                localStorage.setItem("ppTime", Number(new Date()));

            }, 5);
        }
    }
}
//obj chua cac phuong thuc validate phia client
var lawsValidate = {
    isValidDate: function (controlName, format) {
        var isValid = true;
        try {
            jQuery.datepicker.parseDate(format, jQuery('#' + controlName).val(), null);
        }
        catch (error) {
            isValid = false;
        }
        return isValid;
    },
    fileType: function () {
        jQuery.validator.unobtrusive.adapters.add('filetype', ['validtypes'], function (options) {
            options.rules['filetype'] = { validtypes: options.params.validtypes.split(',') };
            options.messages['filetype'] = options.message;
        });

        jQuery.validator.addMethod("filetype", function (value, element, param) {
            for (var i = 0; i < element.files.length; i++) {
                var extension = validateFn.getFileExtension(element.files[0].name);
                if ($.inArray(extension, param.validtypes) === -1) {
                    return false;
                }
            }
            return true;
        });
    },
    maxFileSize: function () {
        jQuery.validator.unobtrusive.adapters.add(
            'filesize', ['maxsize'], function (options) {
                options.rules['filesize'] = options.params;
                if (options.message) {
                    options.messages['filesize'] = options.message;
                }
            }
        );

        jQuery.validator.addMethod('filesize', function (value, element, params) {
            if (element.files.length < 1) {
                // ko co file nao duoc chon
                return true;
            }

            if (!element.files || !element.files[0].size) {
                // trinh duyet ko ho tro HTML5 API
                return true;
            }

            return element.files[0].size < params.maxsize;
        }, '');
    },
    age: function () {
        jQuery.validator.addMethod(
            'validateage',
            function (value, element, params) {
                return Date.parse(value) >= Date.parse(params.minumumdate) && Date.parse(value) <= Date.parse(params.maximumdate);
            });

        jQuery.validator.unobtrusive.adapters.add(
            'validateage', ['minumumdate', 'maximumdate'], function (options) {
                var params = {
                    minumumdate: options.params.minumumdate,
                    maximumdate: options.params.maximumdate
                };
                options.rules['validateage'] = params;
                options.messages['validateage'] = options.message;
            });
    },
    termsAndConditions: function () {
        var defaultRangeValidator = jQuery.validator.methods.range;
        jQuery.validator.methods.range = function (value, element, param) {
            if (element.type === 'checkbox') {
                // neu la checkbox: tra ve true neu checkbox checked
                return element.checked;
            } else {
                // neu ko thi goi ham range validator default
                return defaultRangeValidator.call(this, value, element, param);
            }
        }
    },
    multiCheckboxRequired: function () {
        jQuery.validator.unobtrusive.adapters.add("multicheckboxrequired", function (options) {
            if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "HIDDEN") {
                options.rules["required"] = true;
                if (options.message) {
                    options.messages["required"] = options.message;
                }
            }
        });
    },
    validateFn: {
        getFileExtension: function (fileName) {
            if (/[.]/.exec(fileName)) {
                return /[^.]+$/.exec(fileName)[0].toLowerCase();
            }
            return null;
        }
    },
    formatDate: function () {
        jQuery.validator.methods.date = function (value, element) {
            if (value) {
                try {
                    $.datepicker.parseDate('dd/mm/yy', value);
                } catch (ex) {
                    return false;
                }
            }
            return true;
        };
    },
    formatEmail: function (email) {
        var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return regex.test(email);
    },
    SelectListRequired: function () {
        jQuery.validator.unobtrusive.adapters.add("dropdown", function (options) {
            if (options.element.tagName.toUpperCase() == "SELECT" && options.element.type.toUpperCase() == "SELECT-ONE") {
                options.rules["required"] = true;
                if (options.message) {
                    options.messages["required"] = options.message;
                }
            }
        });
    },
    RequiredIf: function () {
        $.validator.addMethod('requiredif',
            function (value, element, parameters) {
                var id = '#' + parameters['dependentproperty'];
                var targetvalue = parameters['targetvalue'];
                targetvalue = (targetvalue == null ? '' : targetvalue).toString();

                var control = $(id);
                var controltype = control.attr('type');
                var actualvalue =
                    (controltype === 'checkbox' || controltype === 'radio') ?
                        (control.is(':checked') ? true : false) : //control.attr('checked').toString() :
                        control.val();

                if ($.trim(targetvalue) === $.trim(actualvalue) || ($.trim(targetvalue) === '*' && $.trim(actualvalue) !== ''))
                    return $.validator.methods.required.call(
                        this, value, element, parameters);

                return true;
            });

        $.validator.unobtrusive.adapters.add(
            'requiredif',
            ['dependentproperty', 'targetvalue'],
            function (options) {
                options.rules['requiredif'] = {
                    dependentproperty: options.params['dependentproperty'],
                    targetvalue: options.params['targetvalue']
                };
                options.messages['requiredif'] = options.message;
            });
    }
}

$.fn.lawsExists = function (callback) {
    var args = [].slice.call(arguments, 1);
    if (this.length) {
        callback.call(this, args);
    }
    return this;
}

$.extend({
    lawsVnAjax: function (url, type, dataGetter, onsuccess) {
        var execOnSuccess = $.isFunction(onsuccess) ? onsuccess : $.noop;
        var getData = $.isFunction(dataGetter) ? dataGetter : function () { return dataGetter; };
        $.ajax({
            url: url,
            type: type,
            traditional: true,
            data: getData(),
            beforeSend: function () {
                $('#loading').fadeIn('normal');
                $('#loadmore').prop('disabled', true).css('cursor', 'wait').text('Đang tải dữ liệu...');
            },
            error: function (jqXhr, errorMessage) {
                $('#loading').fadeOut('normal');
                if (jqXhr.status === 0) {
                    lawsVn.dialog({
                        messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.']
                        , showIcon: false
                    });
                } else if (jqXhr.status == 404) {
                    lawsVn.dialog({
                        messages: ['Không tìm thấy trang yêu cầu. [404]']
                        , showIcon: false
                    });
                } else if (jqXhr.status == 500) {
                    lawsVn.dialog({
                        messages: ['Lỗi máy chủ nội bộ. [500].']
                        , showIcon: false
                    });
                } else if (errorMessage === 'parsererror') {
                    lawsVn.dialog({
                        messages: ['Yêu cầu phân tích cú pháp JSON lỗi.']
                        , showIcon: false
                    });
                } else if (errorMessage === 'timeout') {
                    lawsVn.dialog({
                        messages: ['Hết thời gian yêu cầu.']
                        , showIcon: false
                    });
                } else if (errorMessage === 'abort') {
                    lawsVn.dialog({
                        messages: ['Yêu cầu xử lý bị hủy.']
                        , showIcon: false
                    });
                } else if (jqXhr.status != 403) {
                    lawsVn.dialog({
                        messages: ['Lỗi :.n' + jqXhr.responseText]
                        , showIcon: false
                    });
                }
                $('#loadmore').prop('disabled', true).css('cursor', 'default').text('Xem thêm');
            },
            success: function (data, status, xhr) {
                window.setTimeout(function () {
                    execOnSuccess(data);
                }, 10);
                $('#loadmore').prop('disabled', true).css('cursor', 'default').text('Xem thêm');
                $('#loading').fadeOut('normal');
            }, always: function () {
                $('#loading').fadeOut('normal');
                $('.no-permission').lawsExists(function () {
                    if (!$('.no-permission').is(':ui-tooltip')) {
                        $('.no-permission').tooltip({
                            content: function () {
                                return $(this).prop('title');
                            },
                            position: {
                                at: 'center bottom',
                                my: 'left top'
                            },
                            show: {
                                effect: "slideDown",
                                delay: 250
                            },
                            close: function (event, ui) {
                                ui.tooltip.hover(
                                    function () {
                                        $(this).stop(true).fadeTo(400, 1);
                                    },
                                    function () {
                                        $(this).fadeOut("400",
                                            function () {
                                                $(this).remove();
                                            });
                                    });
                            }
                        });
                    }
                });
            }
        });
    }
});

(function ($) {
    $.fn.lawsDialog = function (options) {
        var defaultOptions = {
            title: lawsVn.Resource.getMessages('Message'),
            isHtmlTitle: false,
            width: 'auto',
            height: 'auto',
            minWidth: 'auto',
            minHeight: 'auto',
            resizable: false,
            autoOpen: true,
            modal: true,
            show: { effect: 'fade', duration: 250 },
            hide: { effect: 'fade', duration: 250 },
            closeText: "Đóng",
            position: { my: "center", at: "top+150", of: window.top },
            dialogClass: 'lawsVnDialog',
            buttons: null,
            onCreate: {},
            onOpen: {},
            onClose: {},
            hideClose: true,
            showIcon: false, //hiện icon chuông hay ko
            isDestroy: true,
            messages: []
        };
        if (typeof options == 'object') {
            options = $.extend(defaultOptions, options);
        } else {
            options = defaultOptions;
        }
        var self = this;
        var execOnClose = $.isFunction(options.onClose) ? options.onClose : $.noop;
        var execOnOpen = $.isFunction(options.onOpen) ? options.onOpen : $.noop;
        var execOnCreate = $.isFunction(options.onCreate) ? options.onCreate : $.noop;
        options.messages = $.isArray(options.messages) ? options.messages : [];

        var html = '<div class="content-thongbao"><div class="rows-thongbao" style=" font-size: 12px;font-weight: bold; line-height: 24px; text-align: center;">';

        if (options.showIcon) {
            html += '<img alt="img-tb" class="img-tb" src="' + lawsVn.virtualPath('/assets/images/icon-tb.png') + '">';
        }
        html += options.messages[0] +
            '</div>';
        if (options.messages.length > 1) {
            html +=
                '<div class="rows-thongbao center" style="font-size: 13px; font-style: italic; line-height: 24px;">' +
                '<span>' + options.messages[1] + '</span> <br>';
        }
        if (options.messages.length > 2) {
            html += '<span style="color: #d81c22">' + options.messages[2] + '</span>';
        }
        html += '</div>';

        if (!self.length) {
            self = $(html);
        }

        self.dialog({
            title: options.title,
            width: options.width,
            height: options.height,
            minWidth: options.minWidth,
            minHeight: options.minHeight,
            resizable: options.resizable,
            autoOpen: options.autoOpen,
            modal: options.modal,
            closeText: options.closeText,
            position: options.position,
            dialogClass: options.dialogClass,
            show: options.show,
            hide: options.hide,
            buttons: options.buttons || [
                {
                    text: lawsVn.Resource.getMessages('Close'),
                    'class': 'btn-thongbao1',
                    click: function () {
                        $(self).dialog('close');
                        window.setTimeout(function () {
                            execOnClose();
                        }, 10);
                    }
                }
            ],
            create: function () {
                window.setTimeout(function () {
                    execOnCreate();
                }, 10);
                $('html').css({ overflow: 'hidden' });
                $('body').css({ overflow: 'hidden' });
            },
            open: function (event, ui) {
                $(this).closest('.ui-dialog').focus();
                $('.btn-thongbao1:eq(1)').focus();
                //ẩn nút đóng x
                if (options.hideClose) {
                    $(self).parent().children().children('.ui-dialog-titlebar-close').hide();
                }
                if (options.title === '') {
                    //$(this).siblings('.ui-dialog-titlebar').remove();
                    $(this).dialog("widget").find(".ui-dialog-title").remove();
                } else if (options.isHtmlTitle) {
                    $(this).dialog("widget").find(".ui-dialog-titlebar").addClass('lawsDialogTitle');
                    $(this).dialog("widget").find(".ui-dialog-title").html(options.title);
                }
                $('.ui-widget-overlay').bind('click',
                    function () {
                        $(self).dialog('close');
                    });
                window.setTimeout(function () {
                    execOnOpen(event, ui);
                }, 10);
            },
            beforeClose: function (event, ui) {
                $('html').css({ overflow: 'inherit' });
                $('body').css({ overflow: 'inherit' });
            },
            close: function (event, ui) {
                $(self).dialog('close');
                if (options.isDestroy) {
                    $(self).dialog('destroy').remove();
                }
                window.setTimeout(function () {
                    execOnClose(event, ui);
                }, 10);
            }
        });
        if (self.dialog('isOpen') === false) {
            self.dialog('open');
        }
    }
})(jQuery);

$.extend({
    lawsAjax: function (options) {
        var defaults =
        {
            url: '',
            type: 'Get',
            data: {},
            dataType: 'json',
            async: false,
            cache: false,
            traditional: false,
            timeout: 5000,
            beforeSend: function () {
                $('#loading').fadeIn('normal');
            },
            success: function (data, status, xhr) {
                if (data.Message != null && data.Message.length > 0) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [data.Message],
                        showIcon: false,
                        onClose: function () {
                            if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                                window.location.href = data.ReturnUrl;
                            }
                        }
                    });
                }
            },
            error: function (jqXhr, errorMessage) {
                $('#loading').fadeOut('normal');
                if (jqXhr.status === 0) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.']
                        , showIcon: false
                    });
                } else if (jqXhr.status === 404) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Không tìm thấy trang yêu cầu. [404]']
                        , showIcon: false
                    });
                } else if (jqXhr.status === 500) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Lỗi máy chủ nội bộ. [500].']
                        , showIcon: false
                    });
                } else if (errorMessage === 'parsererror') {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Yêu cầu phân tích cú pháp JSON lỗi.']
                        , showIcon: false
                    });
                } else if (errorMessage === 'timeout') {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Hết thời gian yêu cầu.']
                        , showIcon: false
                    });
                } else if (errorMessage === 'abort') {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Yêu cầu xử lý bị hủy.']
                        , showIcon: false
                    });
                } else if (jqXhr.status !== 403) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Lỗi :.n' + jqXhr.responseText]
                        , showIcon: false
                    });
                }
            },
            always: function () {
                $('#loading').fadeOut('normal');
                $('.no-permission').lawsExists(function () {
                    //if (!$('.no-permission').is(':ui-tooltip')) {
                    $('.no-permission').tooltip({
                        content: function () {
                            return $(this).prop('title');
                        },
                        position: {
                            at: 'center bottom',
                            my: 'left top'
                        },
                        show: {
                            effect: "slideDown",
                            delay: 250
                        },
                        close: function (event, ui) {
                            ui.tooltip.hover(
                                function () {
                                    $(this).stop(true).fadeTo(400, 1);
                                },
                                function () {
                                    $(this).fadeOut("400",
                                        function () {
                                            $(this).remove();
                                        });
                                });
                        }
                    });
                    //}
                });
            }
        }
        options = $.extend(defaults, options);
        if (options.url.length) {
            $.ajax({
                url: options.url,
                type: options.type,
                data: options.data,
                dataType: options.dataType,
                async: options.async,
                cache: options.cache,
                traditional: options.traditional,
                timeout: options.timeout,
                beforeSend: function () {
                    if ($.isFunction(options.beforeSend)) {
                        window.setTimeout(function () {
                            options.beforeSend();
                        }, 10);
                    }
                },
                success: function (data, status, xhr) {
                    if ($.isFunction(options.success)) {
                        window.setTimeout(function () {
                            options.success(data, status, xhr);
                        }, 10);
                    }
                },
                error: function (jqXhr, errorMessage) {
                    window.setTimeout(function () {
                        options.error(jqXhr, errorMessage);
                    }, 10);
                }
            }).always(function () {
                window.setTimeout(function () {
                    options.always();
                }, 10);
            });
        }
    }
});

$.fn.extend({
    LawScrollTo: function () {
        $(this).lawsExists(function () {
            var x = $(this).offset().top - 100;
            jQuery('html,body').animate({ scrollTop: x }, 100);
        });
    }
});

$.fn.clearErrors = function () {
    $(this).each(function () {
        $(this).trigger('reset.unobtrusiveValidation');
    });
};

(function ($) {
    $.fn.clearForm = function (options) {
        var settings = $.extend({
            formId: this.closest('form')

        }, options);

        var $form = $(settings.formId);
        $form.validate().resetForm();

        $form.find("[data-valmsg-summary=true]")
            .removeClass("validation-summary-errors")
            .addClass("validation-summary-valid")
            .find("ul").empty();

        $form.find("[data-valmsg-replace]")
            .removeClass("field-validation-error")
            .addClass("field-validation-valid")
            .empty();

        return $form;
    };
}(jQuery));

$.fn.googleLogin = function (options) {
    var defaults = {
        oAuthUrl: 'https://accounts.google.com/o/oauth2/auth?',
        validUrl: 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=',
        userInfoUrl: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=',
        scope: 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email',
        redirectUrl: 'https://luatvietnam.vn/',
        clientId: '430060160652-v6547hpru6paae2boas196b4j7l1qcnr.apps.googleusercontent.com',
        type: 'token',
        accessToken: '',
        accountInfoType: 1
    }
    options = $.extend(defaults, options);
    $(this).on('click',
        function (e) {
            e.preventDefault();
            var url = options.oAuthUrl + 'scope=' + options.scope + '&client_id=' + options.clientId + '&redirect_uri=' + options.redirectUrl + '&response_type=' + options.type;
            var gPopup = window.open(url, 'Văn bản luật đăng nhập tài khoản Google', 'width=800, height=600');
            var time = window.setInterval(function () {
                try {
                    if (gPopup.document.URL.indexOf(options.redirectUrl) !== -1) {
                        window.clearInterval(time);
                        options.accessToken = getResponse(gPopup.document.URL, 'access_token');
                        gPopup.close();
                        options.accountInfoType === 1 ? requestAccountInfo(options.accessToken) : (options.accountInfoType == 2 ? requestAccountInfo2(options.accessToken) : requestAccountInfo3(options.accessToken));
                    }
                }
                catch (e) {
                    console.log(e);
                }
            }, 500);
        });
    function getResponse(url, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = '[\\#&]' + name + '=([^&#]*)';
        var regex = new RegExp(regexS);
        var results = regex.exec(url);
        if (results == null)
            return '';
        else
            return results[1];
    }
    function requestAccountInfo(accessToken) {
        $.lawsAjax({
            type: 'Get',
            url: options.userInfoUrl + accessToken,
            success: function (resp) {
                $.lawsAjax({
                    type: 'Post',
                    url: lawsVn.virtualPath('/account/googlelogin'),
                    data: { googleId: resp.id, email: resp.email, name: typeof (resp.name) === 'undefined' ? '' : resp.name, givenname: typeof (resp.given_name) === 'undefined' ? '' : resp.given_name, familyname: typeof (resp.family_name) === 'undefined' ? '' : resp.family_name, picture: typeof (resp.picture) === 'undefined' ? '' : resp.picture },
                    success: function (response) {
                        if (response.Completed) {
                            lawsVn.logs.webpagelogs('Login', pageUrl, "Đăng nhập thành công", source);
                            if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                                window.location.href = response.ReturnUrl;
                            }
                        } else {
                            if (response.Data != null) {
                                if (response.Data.startsWith('NOK_REDIRECT')) {
                                    $('input[name="FullName"]', $('#RegisterAcountSocialPaymentForm')).lawsExists(function () {
                                        $(this).val('');
                                        if (resp.name != null && resp.name.length > 0) {
                                            $(this).val(resp.name);
                                        }
                                        else if (resp.given_name != null && resp.given_name.length > 0 && resp.family_name != null && resp.family_name.length > 0) {
                                            $(this).val(resp.family_name + ' ' + resp.given_name);
                                        }
                                    });
                                    $('input[name="Email"]', $('#RegisterAcountSocialPaymentForm')).lawsExists(function () {
                                        $(this).val('');
                                        if (resp.email != null && resp.email.length > 0) {
                                            $(this).val(resp.email);
                                        }
                                    });
                                    $('input[name="Phone"]', $('#RegisterAcountSocialPaymentForm')).lawsExists(function () {
                                        $(this).val('');
                                    });
                                    $('#RegisterAccountSocialForm').lawsExists(function () {
                                        if ($(this).hasClass('hidden'))
                                            $(this).removeClass('hidden');
                                    });
                                    $('form#RegisterAcountPaymentForm').lawsExists(function () {
                                        $(this).addClass('hidden');
                                    });
                                    $('input[type="checkbox"][name="CreateAccounWithAnotherEmail"]').lawsExists(function () {
                                        $(this).prop('checked', false);
                                    });
                                    $('input[type="hidden"][name="OpenId"]').lawsExists(function () {
                                        $(this).val(resp.id);
                                    });
                                    $('input[type="hidden"][name="OpenAuthTypeId"]').lawsExists(function () {
                                        $(this).val(2);
                                    });
                                    $('input[type="hidden"][name="Avatar"]').lawsExists(function () {
                                        if (typeof (resp.picture) !== 'undefined') {
                                            $(this).val(resp.picture);
                                        }
                                    });
                                } else if (response.Data.startsWith('NOK')) {
                                    if (response.Message != null && response.Message.length > 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [response.Message],
                                            buttons: [
                                                {
                                                    text: lawsVn.Resource.getMessages('Close'),
                                                    click: function () {
                                                        $(this).dialog('close');
                                                    }
                                                }
                                            ]
                                        });
                                        lawsVn.logs.webpagelogs('Login', pageUrl, response.Message, response.Data);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });
    }
    function requestAccountInfo2(accessToken) {
        $.lawsAjax({
            type: 'Get',
            url: options.userInfoUrl + accessToken,
            success: function (resp) {
                $.lawsAjax({
                    type: 'Post',
                    url: lawsVn.virtualPath('/account/googlelogin'),
                    data: { googleId: resp.id, email: resp.email, name: typeof (resp.name) === 'undefined' ? '' : resp.name, givenname: typeof (resp.given_name) === 'undefined' ? '' : resp.given_name, familyname: typeof (resp.family_name) === 'undefined' ? '' : resp.family_name, picture: typeof (resp.picture) === 'undefined' ? '' : resp.picture },
                    success: function (response) {
                        if (response.Completed) {
                            lawsVn.logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                            if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                                window.location.href = response.ReturnUrl;
                            }
                        } else {
                            if (response.Data != null) {
                                if (response.Data.startsWith('NOK_REDIRECT')) {
                                    window.location.href = lawsVn.virtualPath('/dang-nhap-tai-khoan-gmail.html?openId=' +
                                        resp.id +
                                        '&email=' +
                                        (typeof (resp.email) === 'undefined' ? '' : resp.email) +
                                        '&name=' +
                                        (typeof (resp.name) === 'undefined' ? '' : resp.name) +
                                        '&givenname=' +
                                        (typeof (resp.given_name) === 'undefined' ? '' : resp.given_name) +
                                        '&familyname=' +
                                        (typeof (resp.family_name) === 'undefined' ? '' : resp.family_name));
                                } else if (response.Data.startsWith('NOK')) {
                                    if (response.Message != null && response.Message.length > 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [response.Message],
                                            buttons: [
                                                {
                                                    text: lawsVn.Resource.getMessages('Close'),
                                                    click: function () {
                                                        $(this).dialog('close');
                                                    }
                                                }
                                            ]
                                        });
                                        lawsVn.logs.webpagelogs('Login', pageUrl, response.Message, response.Data);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });
    }
    function requestAccountInfo3(accessToken) {
        $.lawsAjax({
            type: 'Get',
            url: options.userInfoUrl + accessToken,
            success: function (resp) {
                $.lawsAjax({
                    type: 'Post',
                    url: lawsVn.virtualPath('/account/googleloginpldn'),
                    data: { googleId: resp.id, email: resp.email, name: typeof (resp.name) === 'undefined' ? '' : resp.name, givenname: typeof (resp.given_name) === 'undefined' ? '' : resp.given_name, familyname: typeof (resp.family_name) === 'undefined' ? '' : resp.family_name, picture: typeof (resp.picture) === 'undefined' ? '' : resp.picture },
                    success: function (response) {
                        if (response.Completed) {
                            lawsVn.logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                            if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                                window.location.href = response.ReturnUrl;
                            }
                        } else {
                            if (response.Message != null && response.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [response.Message]
                                });
                            }
                        }
                    }
                });
            }
        });
    }
}

$.fn.facebookLogin = function (options) {
    var defaults = {
        AppId: '117134849575084',
        showLogs: false,
        permissions: 'email,user_photos',
        connected: false,
        accountInfoType: 1
    }
    options = $.extend(defaults, options);
    $(this).on('click',
        function (e) {
            e.preventDefault();
            fbLogin();
        });
    function fBOnSuccess(resp) {
        $.lawsAjax({
            type: 'Post',
            url: lawsVn.virtualPath('/account/facebooklogin'),
            data: { facebookId: resp.id, email: typeof (resp.email) === 'undefined' ? '' : resp.email, name: typeof (resp.name) === 'undefined' ? '' : resp.name, firstname: typeof (resp.first_name) === 'undefined' ? '' : resp.first_name, lastname: typeof (resp.last_name) === 'undefined' ? '' : resp.last_name, gender: typeof (resp.gender) === 'undefined' ? '' : resp.gender },
            success: function (response) {
                if (response.Completed) {
                    lawsVn.logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                    if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                        window.location.href = response.ReturnUrl;
                    }
                } else {
                    if (response.Data != null) {
                        if (response.Data.startsWith('NOK_REDIRECT')) {
                            $('#FullName', $('#RegisterAcountSocialPaymentForm')).lawsExists(function () {
                                $(this).val('');
                                if (resp.name != null && resp.name.length > 0) {
                                    $(this).val(resp.name);
                                }
                                else if (resp.last_name != null && resp.last_name.length > 0 && resp.first_name != null && resp.first_name.length > 0) {
                                    $(this).val(resp.last_name + ' ' + resp.first_name);
                                }
                            });
                            $('#Email', $('#RegisterAcountSocialPaymentForm')).lawsExists(function () {
                                $(this).val('');
                                if (resp.email != null && resp.email.length > 0) {
                                    $(this).val(resp.email);
                                }
                            });
                            $('#Phone', $('#RegisterAcountSocialPaymentForm')).lawsExists(function () {
                                $(this).val('');
                            });
                            $('#RegisterAccountSocialForm').lawsExists(function () {
                                if ($(this).hasClass('hidden'))
                                    $(this).removeClass('hidden');
                            });
                            $('form#RegisterAcountPaymentForm').lawsExists(function () {
                                $(this).addClass('hidden');
                            });
                            $('input[type="hidden"][name="OpenId"]').lawsExists(function () {
                                $(this).val(resp.id);
                            });
                            $('input[type="hidden"][name="OpenAuthTypeId"]').lawsExists(function () {
                                $(this).val(1);
                            });
                            $('input[type="hidden"][name="Avatar"]').lawsExists(function () {
                                $(this).val('https://graph.facebook.com/' + resp.id + '/picture?type=large');
                            });
                        } else if (response.Data.startsWith('NOK')) {
                            if (response.Message != null && response.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [response.Message],
                                    buttons: [
                                        {
                                            text: lawsVn.Resource.getMessages('Close'),
                                            click: function () {
                                                $(this).dialog('close');
                                            }
                                        }
                                    ]
                                });
                                lawsVn.logs.webpagelogs('Login', pageUrl, response.Message, response.Data);
                            }
                        }
                    }
                }
            }
        });
    }
    function fBOnSuccess2(resp) {
        $.lawsAjax({
            type: 'Post',
            url: lawsVn.virtualPath('/account/facebooklogin'),
            data: { facebookId: resp.id, email: typeof (resp.email) === 'undefined' ? '' : resp.email, name: typeof (resp.name) === 'undefined' ? '' : resp.name, firstname: typeof (resp.first_name) === 'undefined' ? '' : resp.first_name, lastname: typeof (resp.last_name) === 'undefined' ? '' : resp.last_name, gender: typeof (resp.gender) === 'undefined' ? '' : resp.gender },
            success: function (response) {
                if (response.Completed) {
                    lawsVn.logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                    if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                        window.location.href = response.ReturnUrl;
                    }
                } else {
                    if (response.Data != null) {
                        if (response.Data.startsWith('NOK_REDIRECT')) {
                            window.location.href = lawsVn.virtualPath('/dang-nhap-tai-khoan-facebook.html?openId=' +
                                resp.id +
                                '&email=' +
                                (typeof (resp.email) === 'undefined' ? '' : resp.email) +
                                '&name=' +
                                (typeof (resp.name) === 'undefined' ? '' : resp.name) +
                                '&firstname=' +
                                (typeof (resp.first_name) === 'undefined' ? '' : resp.first_name) +
                                '&lastname=' +
                                (typeof (resp.last_name) === 'undefined' ? '' : resp.last_name));
                        } else if (response.Data.startsWith('NOK')) {
                            if (response.Message != null && response.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [response.Message],
                                    buttons: [
                                        {
                                            text: lawsVn.Resource.getMessages('Close'),
                                            click: function () {
                                                $(this).dialog('close');
                                            }
                                        }
                                    ]
                                });
                                lawsVn.logs.webpagelogs('Login', pageUrl, response.Message, response.Data);
                            }
                        }
                    }
                }
            }
        });
    }
    function fBOnSuccess3(resp) {
        $.lawsAjax({
            type: 'Post',
            url: lawsVn.virtualPath('/account/facebookloginpldn'),
            data: { facebookId: resp.id, email: typeof (resp.email) === 'undefined' ? '' : resp.email, name: typeof (resp.name) === 'undefined' ? '' : resp.name, firstname: typeof (resp.first_name) === 'undefined' ? '' : resp.first_name, lastname: typeof (resp.last_name) === 'undefined' ? '' : resp.last_name, gender: typeof (resp.gender) === 'undefined' ? '' : resp.gender },
            success: function (response) {
                if (response.Completed) {
                    lawsVn.logs.webpagelogs("Login", pageUrl, "Đăng nhập thành công", source);
                    if (response.ReturnUrl != null && response.ReturnUrl.length > 0) {
                        window.location.href = response.ReturnUrl;
                    }
                } else {
                    if (response.Data != null) {
                        if (response.Data.startsWith('NOK_REDIRECT')) {
                            window.location.href = lawsVn.virtualPath('/dang-nhap-tai-khoan-facebook.html?openId=' +
                                resp.id +
                                '&email=' +
                                (typeof (resp.email) === 'undefined' ? '' : resp.email) +
                                '&name=' +
                                (typeof (resp.name) === 'undefined' ? '' : resp.name) +
                                '&firstname=' +
                                (typeof (resp.first_name) === 'undefined' ? '' : resp.first_name) +
                                '&lastname=' +
                                (typeof (resp.last_name) === 'undefined' ? '' : resp.last_name));
                        } else if (response.Data.startsWith('NOK')) {
                            if (response.Message != null && response.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [response.Message],
                                    buttons: [
                                        {
                                            text: lawsVn.Resource.getMessages('Close'),
                                            click: function () {
                                                $(this).dialog('close');
                                            }
                                        }
                                    ]
                                });
                                lawsVn.logs.webpagelogs('Login', pageUrl, response.Message, response.Data);
                            }
                        }
                    }
                }
            }
        });
    }
    function fbOnError(error) {
        console.log(error);
    }
    function fbLogin() {
        if (FB) {
            fbLog('login');
            FB.login($.proxy(fbcheckLoginState, this), {
                scope: options.permissions,
                return_scopes: true
            });
        }
        else {
            fbLog('Đăng nhập tài khoản Facebook không thành công - thử lại sau 5 giây...');
            setTimeout($.proxy(fbLogin, this), 5000);
        }
    }
    function fbLogout() {
        if (FB && options.connected) {
            fbLog('Đăng xuất tài khoản Facebook');
            FB.logout();
        }
    }
    function fbcheckLoginState() {
        fbLog('fbcheckLoginState');
        FB.getLoginStatus($.proxy(function (response) {
            fbstatusChangeCallback(response);
        }, this));
    }
    function fbLog(message) {
        if (options.showLogs) console.log('$.facebookLogin ' + message);
    }
    function fbstatusChangeCallback(response) {
        fbLog('fbstatusChangeCallback');
        if (response.status === 'connected') {
            options.connected = true;
            fbOnConnected();
        } else if (response.status === 'not_authorized') {
            fbLog('not authorized');
            options.connected = false;
            fbOnError('not authorized');
        } else {
            fbLog('not connected');
            options.connected = false;
            fbOnError('not connected');
        }
    }
    function fbOnConnected() {
        fbLog('fbOnConnected');
        FB.api('/me', 'GET', { fields: 'id,email,name,first_name,last_name,gender,birthday,location' }, $.proxy(function (response) {
            fbLog('successful login for: ' + response.name);
            options.accountInfoType === 1 ? fBOnSuccess(response) : (options.accountInfoType === 2 ? fBOnSuccess2(response) : fBOnSuccess3(response));
        }, this));
    }
}

$.fn.loadmoreContent = function (options) {
    var defaults = {
        rowClass: '.statistic-rows',
        container: '.content-scroll-1',
        pageSize: 10,
        userCustomScrollbar: true,
        callBack: {}
    }
    options = $.extend(defaults, options);
    if ($(options.rowClass).length <= options.pageSize) $(this).hide();
    $(options.rowClass).slice(0, options.pageSize).show();
    var execCallback = $.isFunction(options.callBack) ? options.callBack : $.noop;
    $(this).on('click',
        function (e) {
            e.preventDefault();
            var rows = $(options.rowClass).length;
            $(options.rowClass + ':hidden').slice(0, rows).slideDown();
            var elPos = $(options.rowClass + ':eq(' + options.pageSize + ')');
            if ($(options.rowClass + ':hidden').length == 0) {
                $(this).fadeOut('slow');
                execCallback();
                var position = elPos.position().top - 10;
                setTimeout(function () {
                    if (options.userCustomScrollbar) {
                        $(options.container).mCustomScrollbar('scrollTo',
                            position,
                            {
                                timeout: 300
                            });
                    } else {
                        $(options.container).addClass('filter-box');
                    }
                }, 300);
            }
        });
}

jQuery.fn.highlight = function (pat) {
    function innerHighlight(node, pat) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                spannode.className = 'highlight';
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.each(function () {
        innerHighlight(this, pat.toUpperCase());
    });
};
$.fn.extend({
    lawsPopup: function (options) {
        var defaults = {
            callback: null,
            autoClose: true,
            clearError: false
        }
        options = $.extend(defaults, options);
        return this.each(function () {
            var me = $(this), wrap = me.find('.popup-wrapper'), btnClose = me.find('.bnt_x');
            if (wrap.length === 0) {
                me.wrapInner("<div class='popup-wrapper'></div>");
            }
            if (options.clearError) {
                var form = me.find('form');
                if (form.length) {
                    form.clearForm();
                }
            }
            me.show();
            me.bind('click',
                function (e) {
                    if (e.target === this && options.autoClose) {
                        if (me.is(':visible')) {
                            me.hide();
                            if ($.isFunction(options.callback()))
                                options.callback();
                        }
                    }
                });
            btnClose.bind('click',
                function () {
                    me.hide();
                    options.callback();
                });
        });
    }
});
jQuery.fn.removeHighlight = function () {
    function newNormalize(node) {
        for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
            var child = children[i];
            if (child.nodeType == 1) {
                newNormalize(child);
                continue;
            }
            if (child.nodeType != 3) { continue; }
            var next = child.nextSibling;
            if (next == null || next.nodeType != 3) { continue; }
            var combined_text = child.nodeValue + next.nodeValue;
            new_node = node.ownerDocument.createTextNode(combined_text);
            node.insertBefore(new_node, child);
            node.removeChild(child);
            node.removeChild(next);
            i--;
            nodeCount--;
        }
    }

    return this.find("span.highlight").each(function () {
        var thisParent = this.parentNode;
        thisParent.replaceChild(this.firstChild, this);
        newNormalize(thisParent);
    }).end();
};
$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
    if (results == null) {
        return null;
    }
    else {
        return results[1] || 0;
    }
}

$(document).ready(function () {
    var url_cur = location.href;
    if (url_cur.indexOf("#") > -1 && url_cur.indexOf('huong-dan.html') > -1) {
        idx = url_cur.indexOf("#");
        var str_id_guid = idx != -1 ? url_cur.substring(idx + 1) : "";
        if (str_id_guid.length) {
            var btn_guid = $('#' + str_id_guid);
            if (btn_guid.length) {
                var li_parent = btn_guid.parent();
                if (!li_parent.hasClass('active')) {
                    btn_guid.trigger('click');
                }
            }
        }
    }
});
var luatVietnamStore = {
    getItem: function (key, optionalCallback) {
        if (!this.supportsLocalStorage()) {
            return null;
        }

        var callback = function (data) {
            data = typeof data !== 'undefined' ? data : null;

            return typeof optionalCallback === 'function' ? optionalCallback(data) : data;
        };

        var value = localStorage.getItem(key);

        if (value !== null) {
            value = JSON.parse(value);

            if (value.hasOwnProperty('__expiry')) {
                var expiry = value.__expiry;
                var now = Date.now();

                if (now >= expiry) {
                    this.removeItem(key);

                    return callback();
                } else {
                    return callback(value.__data);
                }
            } else {
                return callback(value);
            }
        } else {
            return callback();
        }
    },
    setItem: function (key, value, expiry) {
        if (!this.supportsLocalStorage() || typeof value === 'undefined' || key === null || value === null) {
            return false;
        }

        if (typeof expiry === 'number') {
            value = {
                __data: value,
                __expiry: Date.now() + (parseInt(expiry) * 1000)
            };
        }

        try {
            localStorage.setItem(key, JSON.stringify(value));

            return true;
        } catch (e) {
            console.log('Không thể lưu dữ liệu ' + key + ' trong localStorage: ' + e.name);

            return false;
        }
    },
    removeItem: function (key) {
        if (this.supportsLocalStorage()) {
            localStorage.removeItem(key);
        }
    },
    clear: function () {
        if (this.supportsLocalStorage()) {
            localStorage.clear();
        }
    },
    supportsLocalStorage: function () {
        try {
            localStorage.setItem('_', '_');
            localStorage.removeItem('_');

            return true;
        } catch (e) {
            return false;
        }
    }
};
//gây lỗi bundle
//if (typeof module !== 'undefined') {
//    module.exports = luatVietnamStore;
//}
(function () {
    $.validator.addMethod('requiredif',
        function (value, element, parameters) {
            var id = '#' + parameters['dependentproperty'];
            var targetvalue = parameters['targetvalue'];
            targetvalue = (targetvalue == null ? '' : targetvalue).toString();

            var control = $(id);
            var controltype = control.attr('type');
            var actualvalue =
                (controltype === 'checkbox' || controltype === 'radio') ?
                    (control.is(':checked') ? true : false) : //control.attr('checked').toString() :
                    control.val();

            if ($.trim(targetvalue) === $.trim(actualvalue) || ($.trim(targetvalue) === '*' && $.trim(actualvalue) !== ''))
                return $.validator.methods.required.call(
                    this, value, element, parameters);

            return true;
        });

    $.validator.unobtrusive.adapters.add(
        'requiredif',
        ['dependentproperty', 'targetvalue'],
        function (options) {
            options.rules['requiredif'] = {
                dependentproperty: options.params['dependentproperty'],
                targetvalue: options.params['targetvalue']
            };
            options.messages['requiredif'] = options.message;
        });
})();

(function ($) {
    $.fn.Alert = function (options) {
        var defaults = {
            mainClass: 'lvn-alert',
            buttons: [{
                Name: 'Có',
                ClassName: 'btn-xoa',
                ClickEvent: {}
            },
            {
                Name: 'Không',
                ClassName: 'btn-noxoa',
                ClickEvent: {}
            }],
            callback: {},
            success: true,
            messages: [],
            returnUrl: ''
        }
        options = $.extend(defaults, options);
        options.messages = $.isArray(options.messages) ? options.messages : [];
        var htmlPopup = '<div class="popup-bg ' + options.mainClass + '"><div class="popup-wrapper" style="max-width: 425px;"><div class="popup-body"><div class="popup-conten padd24"><button name="close" class="close-popup close-nav"><i class="ic icon-e-remove-2lvn icon-remove order-tcvn"></i></button><div class="content-confirm">';
        if (options.messages.length > 0) {
            for (var i = 0; i < options.messages.length; i++) {
                htmlPopup += '<div class="item-xoa">' + options.messages[i] + '</div>';
            }
            if (options.buttons.length > 0) {
                htmlPopup += '<div class="item-xoa-btn">';
                for (var i = 0; i < options.buttons.length; i++) {
                    htmlPopup += '<a href="javascript:void(0)" rel="nofollow" class="' + options.buttons[i].ClassName + '">' + options.buttons[i].Name + '</a>';
                }
                htmlPopup += '</div>';
            }
        }
        htmlPopup += '</div></div></div></div></div>';
        function showPopup() {
            if (options.success) {
                $('.' + options.mainClass).remove();
                $('body').append(htmlPopup);
                for (var i = 0; i < options.buttons.length; i++) {
                    var el = options.buttons[i];
                    var event = el.ClickEvent;
                    $('.' + options.mainClass).on('click',
                        '.' + el.ClassName,
                        $.isFunction(event) ? event : $.noop
                    );
                }
            }
            $('.' + options.mainClass).show();
        }
        showPopup();
        $('.' + options.mainClass).click(function (e) {
            if (e.target === this) {
                if ($(this).is(':visible')) {
                    $(this).remove();
                    if ($.isFunction(options.callback)) {
                        window.setTimeout(function () {
                            options.callback();
                        },
                            10);
                    }
                }
            }
        });
        $('.' + options.mainClass).find('button[name=close]').on('click', function () {
            $('.' + options.mainClass).remove();
            if ($.isFunction(options.callback)) {
                window.setTimeout(function () {
                    options.callback();
                },
                    10);
            }
            return false;
        });
    }
})(jQuery);

var $content1 = $('.noidungtracuu'),
    $input1 = $(".input-indoc"),
    $clearBtn1 = $("span[data-search='clear']"),
    $prevBtn1 = $("span[data-search='prev']"),
    $nextBtn1 = $("span[data-search='next']"),
    $parent1 = $input1.closest('.form-indoc'),
    $textTracuu1 = $('.text-tracuu', $parent1),
    $results1,
    currentClass = 'current',
    offsetTop = 120,
    currentIndex = 0;
$input1.on("input", function () {
    var searchVal = this.value;
    $content1.unmark({
        done: function () {
            $content1.mark(searchVal, {
                separateWordSearch: false,
                caseSensitive: false,
                ignoreJoiners: true,
                done: function () {
                    $results1 = $content1.find("mark");
                    currentIndex = 0;
                    if ($results1.length > 0) {
                        $prevBtn1.removeClass('disabled');
                        $nextBtn1.removeClass('disabled');
                        $textTracuu1.text((currentIndex + 1) + '/' + $results1.length);
                    } else {
                        $prevBtn1.addClass('disabled');
                        $nextBtn1.addClass('disabled');
                        $textTracuu1.text('');
                    }
                    jumpTo();
                }
            });
        }
    });
});

$clearBtn1.on("click", function () {
    $content1.unmark();
    $input1.val("").focus();
    $prevBtn1.addClass('disabled');
    $nextBtn1.addClass('disabled');
    $textTracuu1.text('');
    //$parent1.hide();
    //$('#_timkiemvb').addClass('target-hidden').removeClass('target-expanded');
});

$nextBtn1.add($prevBtn1).on("click", function () {
    if ($(this).hasClass('disabled')) return false;
    if ($results1.length) {
        currentIndex += $(this).is($prevBtn1) ? -1 : 1;
        if (currentIndex < 0) {
            currentIndex = $results1.length - 1;
        }
        if (currentIndex > $results1.length - 1) {
            currentIndex = 0;
        }

        if (currentIndex >= 0 && currentIndex < $results1.length - 1) {
            $nextBtn1.removeClass('disabled');
        } else {
            $nextBtn1.addClass('disabled');
        }

        if (currentIndex > 0) {
            $prevBtn1.removeClass('disabled');
        } else {
            $prevBtn1.addClass('disabled');
        }
        $textTracuu1.text((currentIndex + 1) + '/' + $results1.length);
        jumpTo();
    }
});

function jumpTo() {
    if ($results1.length) {
        var position,
            $current = $results1.eq(currentIndex);
        $results1.removeClass(currentClass);
        if ($current.length) {
            $current.addClass(currentClass);
            position = $current.offset().top - offsetTop;
            window.scrollTo(0, position);
        }
    }
}

$.fn.DocDetail = function (options) {
    var defaults = {
        contentClass: '.tab-item-content',
        newVersonDocItem:'#newVersonDocItem',
        divTheodoihieulucvb: '.divTheodoihieulucvb',
        tabClass: '.tab-item-doc',
        linkPhuluc: '.phu-luc-dinh-kem',
        item_mucluc: 'div[class*=demuc]',
        mucluc: '#mucluc',
        print: '.print-content',
        printLd: '.print-ld',
        btnPopupMucluc: '#closePopupa',
        btnPopupMuclucMobi: '#btnDocIndexesm',
        btnSosanhVb: '.doc-so-sanhvb',
        muclucChidan: '#mucluc2',
        muclucMix: '#mucluc3',
        appearance: '.appearance',
        changeFontsize: '.change-fontsize',
        btnSearchContent: '.search-content',
        textSize: '.text-size',
        chuthichmauchidan: '.chuthichmauchidan',
        tabs: {
            tomtat: '#tomtat',
            noidung: '#noidung',
            lienquan: '#lienquan',
            hieuluc: '#hieuluc',
            luocdo: '#luocdo',
            tienganh: '#tienganh',
            taive: '#taive',
            chidanthaydoi: '#chidanthaydoi',
            noidungmix: '#noidungmix'
        },
        arrTabs: ['#tomtat', '#noidung', '#lienquan', '#hieuluc', '#luocdo', '#tienganh', '#taive', '#chidanthaydoi', '#noidungmix'],
        logs: {
            docId: 0,
            docGroupId: 0
        },
        customerId: 0,
        documentSaved: 0,
        hasTrackedDocumentEffect: 0,
        hasEffectTrackingsAll: 0,
        languageId: 1,
        localStorageCustomerDocsExpires: 15 * 60,
        localStorageExpires: 24 * 60 * 60 * 30
    }, opts = $.extend(defaults, options);
    var activeTab = '', currentTab = '', currentPos = { '#noidung': -1, '#chidanthaydoi': -1, '#noidungmix': -1 },
       
        getHash = function () {
            if (location.href.indexOf('#') !== -1) {
                var hash = location.href.substr(location.href.indexOf('#'));
                return hash;
            }
            else
                if (window.location.hash) {
                    return window.location.hash;
                }
            return '';
        }, currentPageY, maxHeight, expiry = 3600 * 24 * 30, viewMix = false, isMobile = lawsVn.isMobile(), section, factor = 0.9, timelineMix2 = '', tabClick = false, currentFontsize = 17, targetIndex = null, intonghop = null, intonghop_cochuthich = null,
        isNewVersion = $(newVersonDocItem).val(),
        showTab = function (tab, isScroll, islog) {
            if (opts.arrTabs.indexOf(tab) === -1 && tab) {
                return;
            }
            currentPageY = 0;
            isScroll = isScroll === void 0 ? (window.location.href.split('?')[0].indexOf('-trial.html') > -1 || $('#doc-sticky').hasClass('doc-sticky')) : isScroll;
            if (!tab) {
                isScroll = false;
            }
            activeTab = tab || getHash();
            var activeDemuc = activeTab;
            if (opts.arrTabs.indexOf(activeTab) === -1) {
                activeTab = $(opts.tabs.chidanthaydoi).length === 0 ? opts.tabs.noidung : opts.tabs.chidanthaydoi;
                if ($(opts.tabs.chidanthaydoi).is(':visible')) activeTab = $(opts.tabs.chidanthaydoi).length === 0 ? opts.tabs.noidung : opts.tabs.chidanthaydoi;
                else if (activeTab.length <= 0) activeTab = opts.tabs.tomtat;
            }
            if (activeTab === opts.tabs.chidanthaydoi || activeTab === opts.tabs.noidung || activeTab === opts.tabs.tienganh || activeTab === opts.tabs.noidungmix) {
                if ($(activeTab).find('.text_vb').length || $(activeTab).find('.not-have-access').length || $(activeTab).find('.text-thongbao').length || $(activeTab).find('.no-content').length || $(activeTab).find('.thong-bao-2').length || $(activeTab).find('.thong-bao-3').length || $(activeTab).find('.embedContent').length || $(activeTab).find('embed').length || $(activeTab).find('iframe').length || $(activeTab).find('canvas').length) {
                    $(opts.changeFontsize).lawsExists(function () {
                        $(this).hide();
                    });

                    $(opts.chuthichmauchidan).lawsExists(function () {
                        $(this).hide();
                    });

                    $(opts.appearance).lawsExists(function () {
                        $(this).hide();
                    });

                    if (isMobile) {
                        $(opts.btnSearchContent).lawsExists(function () {
                            $(this).hide();
                        });
                    }

                    if (activeTab === opts.tabs.noidung) {
                        var docContent = $(activeTab).find('.docContent').first();
                        if (docContent.length && docContent.children().length > 0 &&
                            docContent.children('p').text() !=
                            'Đang tải nội dung văn bản. Vui lòng đợi...' && docContent.children('div.content-entry').text() != 'Quý khách vui lòng thử lại sau.') {
                            $(opts.print).lawsExists(function () {
                                $(this).show();
                            });
                            $(opts.btnPopupMucluc).lawsExists(function () {
                                $(this).show();
                                $('.tab-panel').lawsExists(function () {
                                    $(this).removeClass('fixedd');
                                });
                            });
                            if ($('.the-tab-panel').hasClass('doc-sticky') && isMobile) {
                                $(opts.btnPopupMuclucMobi).lawsExists(function () {
                                    $(this).show();
                                });
                            }
                        } else {
                            $(opts.print).lawsExists(function () {
                                $(this).hide();
                            });
                            $(opts.btnPopupMucluc).lawsExists(function () {
                                $(this).hide();
                                $('.tab-panel').lawsExists(function () {
                                    $(this).addClass('fixedd');
                                });
                            });

                            $(opts.btnPopupMuclucMobi).lawsExists(function () {
                                $(this).hide();
                            });
                        }
                    }
                } else {
                    if (activeTab === opts.tabs.chidanthaydoi || activeTab === opts.tabs.noidungmix) {
                        if (activeTab == opts.tabs.chidanthaydoi) {
                            setTimeout(printDocIndexes('#chidanthaydoind', '#DocIndexes3'), 0);
                        } else {
                            setTimeout(printDocIndexes('#noidungtoanvan', '#DocIndexes4'), 0);
                        }
                        $(opts.chuthichmauchidan).lawsExists(function () {
                            $(this).show();
                        });
                        if (viewMix) {
                            $('#noidungtoanvan').lawsExists(function () {
                                $(this).addClass('hidden');
                            });
                            $('.print_item').lawsExists(function () {
                                $(this).addClass('hidden');
                            });
                            $('#timeline-mix').lawsExists(function () {
                                $(this).removeClass('hidden');
                            });
                            $('.title_vb_mix2').lawsExists(function () {
                                $($('.title_vb_mix2')[0]).removeClass('active_mixvb');
                            });
                        } else {
                            $('#noidungtoanvan').lawsExists(function () {
                                $(this).removeClass('hidden');
                            });
                            $('.print_item').lawsExists(function () {
                                $(this).removeClass('hidden');
                            });
                            $('#timeline-mix').lawsExists(function () {
                                $(this).addClass('hidden');
                            });
                            $('.title_vb_mix2').lawsExists(function () {
                                $('.rows-mixvb').removeClass('active_mixvb');
                                $($('.title_vb_mix2')[0]).addClass('active_mixvb');
                            });
                        }
                    }
                    displayCurrentFontSize();
                    $(opts.changeFontsize).lawsExists(function () {
                        $(this).show();
                    });

                    $(opts.appearance).lawsExists(function () {
                        $(this).show();
                    });

                    $(opts.print).lawsExists(function () {
                        $(this).show();
                    });

                    if (isMobile) {
                        $(opts.btnSearchContent).lawsExists(function () {
                            $(this).show();
                        });
                    }

                    $(opts.btnPopupMucluc).lawsExists(function () {
                        $(this).show();
                        $('.tab-panel').lawsExists(function () {
                            $(this).removeClass('fixedd');
                        });
                    });

                    if ($('.the-tab-panel').hasClass('doc-sticky') && isMobile) {
                        $(opts.btnPopupMuclucMobi).lawsExists(function () {
                            $(this).show();
                        });
                    }
                }
            } else {
                $(opts.appearance).lawsExists(function () {
                    $(this).hide();
                });

                $(opts.changeFontsize).lawsExists(function () {
                    $(this).hide();
                });

                $(opts.print).lawsExists(function () {
                    $(this).hide();
                });

                $(opts.btnPopupMucluc).lawsExists(function () {
                    $(this).hide();
                    $('.tab-panel').lawsExists(function () {
                        $(this).addClass('fixedd');
                    });
                });
                $(opts.btnPopupMuclucMobi).lawsExists(function () {
                    $(this).hide();
                });
                $(opts.chuthichmauchidan).lawsExists(function () {
                    $(this).hide();
                });
            }

            if (activeTab === opts.tabs.chidanthaydoi || activeTab === opts.tabs.noidungmix) {
                $(opts.btnSosanhVb).show();
                if (activeTab === opts.tabs.chidanthaydoi) {
                    if ($(opts.muclucChidan).length || $(opts.mucluc).length) {
                        $(opts.btnPopupMucluc).show();
                        if ($('.the-tab-panel').hasClass('doc-sticky') && isMobile) {
                            $(opts.btnPopupMuclucMobi).show();
                        }
                        $('.tab-panel').lawsExists(function () {
                            $(this).removeClass('fixedd');
                        });
                    } else {
                        $(opts.btnPopupMucluc).hide();
                        $(opts.btnPopupMuclucMobi).hide();
                        $('.tab-panel').lawsExists(function () {
                            $(this).addClass('fixedd');
                        });
                    }
                    var embed = $(activeTab).find('.embedContent');
                    var checkContent = 'content'
                    if (embed.length) {
                        console.log(123456)
                        loadIframe(embed, checkContent);
                    }
                } else if (activeTab === opts.noidungmixTab) {
                    if ($(opts.muclucMix).length) {
                        $(opts.btnPopupMucluc).show();
                        if ($('.the-tab-panel').hasClass('doc-sticky') && isMobile) {
                            $(opts.btnPopupMuclucMobi).show();
                        }
                        $('.tab-panel').lawsExists(function () {
                            $(this).removeClass('fixedd');
                        });
                    } else {
                        $(opts.btnPopupMucluc).hide();
                        $(opts.btnPopupMuclucMobi).hide();
                        $('.tab-panel').lawsExists(function () {
                            $(this).addClass('fixedd');
                        });
                    }
                }

                $(opts.btnPopupMucluc).lawsExists(function () {
                    $(this).addClass('mixx');
                });
                $(opts.btnPopupMuclucMobi).lawsExists(function () {
                    $(this).addClass('mixx');
                });
            }
            else {
                $(opts.btnSosanhVb).hide();
                if (activeTab === opts.tabs.noidung) {
                    var embed = $(activeTab).find('.embedContent');
                    if (embed.length) {
                        loadIframe(embed);
                    }

                } else {
                    if (activeTab == opts.tabs.luocdo) {
                        loadDiagramContent();
                    } else if (activeTab == opts.tabs.lienquan) {
                        loadDocRelateContent();
                    }
                    else if (activeTab == opts.tabs.hieuluc) {
                        loadDocEffectContent();
                    }
                    else if (activeTab == opts.tabs.tienganh) {
                        var embedEng = $(activeTab).find('.embedContent');
                        if (embedEng.length) {
                            loadIframe(embedEng);
                        }

                        if ($('#english-content-private', $(activeTab)).length > 0) {
                            loadDocPrivateEngContent();
                        } else {
                            loadDocEngContent();
                        }
                    }

                    if (isMobile) {
                        $(opts.btnSearchContent).lawsExists(function () {
                            $(this).hide();
                        });
                    }

                    $(opts.btnPopupMucluc).lawsExists(function () {
                        $(this).hide();
                    });

                    $(opts.btnPopupMuclucMobi).lawsExists(function () {
                        $(this).hide();
                    });
                }

                $(opts.btnPopupMucluc).lawsExists(function () {
                    $(this).removeClass('mixx');
                });

                $(opts.btnPopupMuclucMobi).lawsExists(function () {
                    $(this).removeClass('mixx');
                });

                if (viewMix) {
                    $('.title_vb_mix2').lawsExists(function () {
                        $($('.title_vb_mix2')[0]).removeClass('active_mixvb');
                    });
                } else {
                    $('.title_vb_mix2').lawsExists(function () {
                        $('.rows-mixvb').removeClass('active_mixvb');
                        $($('.title_vb_mix2')[0]).addClass('active_mixvb');
                    });
                }

                $(opts.chuthich).hide();
                $(opts.divTheodoihieulucvb).lawsExists(function () {
                    $(this).show();
                });

            }

            if (currentTab === opts.tabs.noidung || currentTab === opts.tabs.chidanthaydoi || currentTab === opts.tabs.noidungmix) {
                if ($(currentTab).find('.text_vb').length || $(currentTab).find('.not-have-access').length || $(currentTab).find('.text-thongbao').length || $(currentTab).find('.no-content').length || $(currentTab).find('.thong-bao-2').length || $(currentTab).find('.embedContent').length || $(currentTab).find('embed').length || $(currentTab).find('iframe').length || $(currentTab).find('canvas').length) {
                    currentPos[currentTab] = -1;
                } else {
                    currentPos[currentTab] = $(document).scrollTop();
                }
            }

            currentTab = activeTab;

            $(opts.contentClass).hide();
            $(opts.tabClass).removeClass('active');
            $(opts.tabClass + '[data-tab-target="' + activeTab + '"]').addClass('active');
            $(activeTab).show();
            lawsVn.preventAnchorScroll();
            var demucTab = false;
            if (activeDemuc.indexOf('demuc') !== -1) {
                target = $(activeDemuc);
                targetElement = $('[data-id="' + activeDemuc.replace("#demuc", "") + '"]')
                isScroll = true;
                demucTab = true;

                if (typeof target != "undefined" && target != null) {
                    var height = 0, elNav = $('#doc-sticky'), divMucluc = $('#btnDocIndexesm');
                    if (elNav.length) {
                        height = elNav.outerHeight();
                        if (!elNav.hasClass('.doc-sticky')) {
                            height = height + 50;
                        }
                    }
                    if (divMucluc.length) {
                        height = height + 40;
                    }
                    if (targetElement.offset())
                        currentPageY = targetElement.offset().top - height;
                    if (target.offset())
                        currentPageY = target.offset().top - height;
                }
            }

            var note = $(currentTab).find('.tab-gchu').first();
            if (note.is(':hidden')) {
                note.show();
            }

            if ((activeTab == opts.tabs.noidung || activeTab == opts.tabs.chidanthaydoi ||
                activeTab === opts.tabs.noidungmix) && (currentPos[currentTab] > -1)) {
                $(window).scrollTop(currentPos[currentTab] - 40)
                //$('html, body').animate({
                //    scrollTop: currentPos[currentTab] - 40
                //}, 500);
            } else if (isScroll) {
                if (demucTab) {
                    $('html, body').animate({
                        scrollTop: currentPageY > 0 ? currentPageY : 0
                    }, 500);
                } else {
                    $(window).scrollTop(currentPageY > 0 ? currentPageY : 0)
                }
            }

            if (islog || typeof islog === "undefined") {
                if (activeTab == opts.tabs.tienganh) {
                    var titleTA = '';
                    if ($(activeTab).find('.text_vb.not-have-access').length) {
                        titleTA = "#tienganh - Không có quyền truy cập tab Tiếng Anh";
                    } else if ($(activeTab).find('.text_vb.no-content.have-access').length) {
                        titleTA = "#tienganh - Có quyền nhưng không có nội dung";
                    }
                    else if ($(activeTab).find('.content-entry.boxtienganh').length) {
                        titleTA = "#tienganh - Có quyền, có nội dung";
                    }
                    lawsVn.logs.webpagelogs("docsview", pageUrl, titleTA, source, activeTab.substring(1));
                } else {
                    if (tab) {
                        lawsVn.logs.webpagelogs("docsview", pageUrl, pageTitle, source, activeTab.substring(1));
                    }
                }
                lawsVn.logs.docViewLogs(opts.logs.docId, opts.logs.docGroupId, activeTab.substring(1));
            }
            return false;
        },
        loadIframe = function (element, check) {
            var embedUrl = element.data('url'), embedUrlDownload = element.data('download'), embedHtml = element.html();
            var embedTitle = element.data('docname');
            if (embedHtml.indexOf('<embed ') < 0 && embedHtml.indexOf('<iframe ') < 0 && embedHtml.indexOf('download-file') < 0) {
                if (lawsVn.isMobile()) {
                    if (check == "content") {
                        var location = window.location.href.replace('#noidung', '').replace('#taive', '');
                        var html = `<div class="section-hotline">
                                    <div class="block-hotline f16 text-center">
                                        <div class="col-hotl">
                                            <p>LuatVietnam đang cập nhật nội dung bản Word của văn bản.</p>
                                            <p>Để tải văn bản quý khách truy cập <a href="javascript:void(0)" rel="nofollow" data-tab-target="#taive" title="Tải về" class="color-law phu-luc-dinh-kem link-color"><strong>Tải về</strong></a>.</p>
                                        </div>
                                    </div>
                                    </div>`
                        element.html(html);
                    }
                    else {
                        var counter = 0, iframeUrl = 'https://docs.google.com/viewer?url=' + embedUrl + '&embedded=true',
                            iframeContent = document.createElement('iframe');
                        element.html(iframeContent);
                        iframeContent.width = '100%';
                        iframeContent.height = Math.round(0.8 * lawsVn.getWindowDims().height) + 'px';

                        //var iframeLoadInterval = setInterval(function () {
                        //    try {
                        //        iframeContent.src = iframeUrl;
                        //        if (element.find('iframe').contents().find('body').children().length > 0) {
                        //            clearInterval(iframeLoadInterval);
                        //        }
                        //        if (counter > 3) {
                        //            clearInterval(iframeLoadInterval);
                        //            element.html('<div class="row-please-log download-file"> <div class="please-log"> <p>Quý khách vui lòng click <a href="' + embedUrlDownload + '" title="Tải file" target="_blank" class="link-color"><strong>vào đây</strong></a> để tải file. </p> </div> </div>');
                        //        }
                        //        counter++;
                        //    } catch (error) {
                        //        clearInterval(iframeLoadInterval);
                        //    }

                        //}, 5000);
                        iframeContent.src = iframeUrl;
                    }
                }
                else {
                    var counter = 0, iframeUrl = embedUrl,
                        iframeContent = document.createElement('iframe');
                    //embedHtml = '<iframe class="page-content content-fixed" id="pdf-iframe" src="' + embedUrl + '" width="875" height="1000" type="application/pdf" >' + embedHtml;
                    element.html(iframeContent);
                    if (check == "eng") {
                        $('.the-document-vbgoc.english').html(iframeContent);
                    }
                    iframeContent.width = '875px';
                    iframeContent.height = '1000px';
                    iframeContent.title = embedTitle;
                    //var iframeLoadInterval = setInterval(function () {
                    //    try {
                    //        iframeContent.src = iframeUrl;
                    //        if (element.find('iframe').contents().find('body').children().length > 0) {
                    //            clearInterval(iframeLoadInterval);
                    //        }
                    //        if (counter > 3) {
                    //            clearInterval(iframeLoadInterval);
                    //            element.html('<div class="row-please-log download-file"> <div class="please-log"> <p>Quý khách vui lòng click <a href="' + embedUrlDownload + '" title="Tải file" target="_blank" class="link-color"><strong>vào đây</strong></a> để tải file. </p> </div> </div>');
                    //        }
                    //        element.find('iframe').contents().find('head').append('<title>' + embedTitle + '</title>')
                    //        counter++;
                    //    } catch (error) {
                    //        clearInterval(iframeLoadInterval);
                    //    }

                    //}, 5000);
                    iframeContent.src = iframeUrl;
                }
            }
        },
        nightModeKey = "luatvietnam_night_mode", customerDocsKey = 'luatvietnam_customerdocs', nightModeValue = 0, customerDocsResponse,
        nightMode = function () {
            luatVietnamStore.getItem(nightModeKey, function (response) {
                if (response !== null) {
                    nightModeValue = response;
                    $('.noidungtracuu').closest('.the-document-entry').lawsExists(function () {
                        if (nightModeValue === 1) {
                            $(this).addClass('dark-mode');
                            $('.text-light').removeClass('active');
                            $('.text-dark').addClass('active');
                        }
                        else {
                            $(this).removeClass('dark-mode');
                            $('.text-light').addClass('active');
                            $('.text-dark').removeClass('active');
                        }
                    });
                }
            });
        },
        displayCurrentFontSize = function () {
            try {
                var currentFontSize = window.getComputedStyle(
                    document.querySelector(activeTab + ' .noidungtracuu'), ':first-line'
                ).getPropertyValue('font-size');
                var fs = $(activeTab).find('.noidungtracuu').not('.hidden').attr('data-fs');
                if (typeof fs != 'undefined') {
                    currentFontSize = fs + '';
                }
                $(opts.textSize).lawsExists(function () {
                    $(this).text(currentFontSize.replace('px', ''));
                });
            } catch (e) {

            }
        },
        getFontSize = function (el) {
            var fs = $(el).css('font-size');
            if (!el.originalFontSize) el.originalFontSize = fs;
            return parseFloat(fs);
        },
        setFontSize = function (el, fact, min, max) {
            var newsize, fs;
            min = min || 16, max = max || 35;
            section = el.find('*')
                .filter(
                    function () {
                        return $(this).clone()
                            .children()
                            .remove()
                            .end()
                            .text().trim().length >
                            0;
                    });
            section.each(function () {
                if ($(this).is(':visible')) {
                    newsize = fact ? getFontSize(this) * fact : this.originalFontSize;
                    if (newsize >= min && newsize <= max) {
                        if (newsize) {
                            fs = newsize;
                            $(this).css('cssText', 'font-size: ' + newsize + 'px !important;line-height:1.6 !important;');
                            //$(this).attr('style', function (i, s) { return (s || '') + `font-size:${newsize}px!important;line-height:1.6 !important;` });
                        }
                    }
                }
            });
            if (fs)
                $(el).attr('data-fs', parseInt(fs))
        },
        customerDocs = function () {
            try {
                if (opts.customerId > 0 && opts.logs.docId > 0) {
                    luatVietnamStore.getItem(
                        customerDocsKey + '_' + opts.logs.docId + '_' + opts.customerId + '_' + opts.languageId,
                        function (response) {
                            if (response !== null) {
                                customerDocsResponse = response;
                            }
                        });
                    if (customerDocsResponse === undefined) {
                        luatVietnamStore.setItem(
                            customerDocsKey + '_' + opts.logs.docId + '_' + opts.customerId + '_' + opts.languageId,
                            {
                                'documentSaved': opts.documentSaved,
                                'hasTrackedDocumentEffect': opts.hasTrackedDocumentEffect,
                                'hasEffectTrackingsAll': opts.hasEffectTrackingsAll,
                            },
                            opts.localStorageCustomerDocsExpires);
                        documentSavedSetText(opts.documentSaved);
                        hasTrackedDocumentEffectSetText(opts.hasTrackedDocumentEffect);
                        hasEffectTrackingsAllSetText(opts.hasEffectTrackingsAll);
                    } else {
                        documentSavedSetText(customerDocsResponse.documentSaved);
                        hasTrackedDocumentEffectSetText(customerDocsResponse.hasTrackedDocumentEffect);
                        hasEffectTrackingsAllSetText(customerDocsResponse.hasEffectTrackingsAll);
                    }
                } else {
                    documentSavedSetText(0);
                    hasTrackedDocumentEffectSetText(0);
                    hasEffectTrackingsAllSetText(0);
                }
            } catch (e) {
                console.log('no localStorage available' + e)
            }
        },
        customerPrivateDocs = function () {
            try {
                if (opts.customerId > 0 && opts.logs.docId > 0) {
                    luatVietnamStore.getItem(
                        'luatvietnam_customerprivatedocs' + '_' + opts.logs.docId + '_' + opts.customerId + '_' + opts.languageId,
                        function (response) {
                            if (response !== null) {
                                customerDocsResponse = response;
                            }
                        });
                    if (customerDocsResponse === undefined) {
                        luatVietnamStore.setItem(
                            'luatvietnam_customerprivatedocs' + '_' + opts.logs.docId + '_' + opts.customerId + '_' + opts.languageId,
                            {
                                'documentSaved': opts.documentSaved,
                                'hasTrackedDocumentEffect': opts.hasTrackedDocumentEffect,
                                'hasEffectTrackingsAll': opts.hasEffectTrackingsAll,
                            },
                            opts.localStorageCustomerDocsExpires);
                        documentPrivateSavedSetText(opts.documentSaved);
                        hasTrackedDocumentPrivateEffectSetText(opts.hasTrackedDocumentEffect);
                        //hasEffectTrackingsAllSetText(opts.hasEffectTrackingsAll);
                    } else {
                        documentPrivateSavedSetText(customerDocsResponse.documentSaved);
                        hasTrackedDocumentPrivateEffectSetText(customerDocsResponse.hasTrackedDocumentEffect);
                        //hasEffectTrackingsAllSetText(customerDocsResponse.hasEffectTrackingsAll);
                    }
                } else {
                    documentPrivateSavedSetText(0);
                    hasTrackedDocumentPrivateEffectSetText(0);
                    //hasEffectTrackingsAllSetText(0);
                }
            } catch (e) {
                console.log('no localStorage available' + e)
            }
        },
        documentSavedSetText = function (type) {
            $('#customerDocs_ccnmjq6o6h').lawsExists(function () {
                if (type > 0) {
                    $(this).removeClass('save').addClass('active unsave').find('span').text('Bỏ lưu');
                    $(this).next().find('.content_bgfff').text('Bỏ lưu văn bản');
                } else {
                    $(this).removeClass('active unsave').addClass('save').find('span').text('Lưu');
                    $(this).next().find('.content_bgfff').text('Lưu văn bản');
                }
            });
            $('.btn-doc.customer-doc').lawsExists(function () {
                if (type > 0) {
                    $(this).removeClass('save').addClass('active unsave').find('span').text('Bỏ lưu');
                    $(this).next().find('.content_bgfff').text('Bỏ lưu văn bản');
                } else {
                    $(this).removeClass('active unsave').addClass('save').find('span').text('Lưu');
                    $(this).next().find('.content_bgfff').text('Lưu văn bản');
                }
            });
        },
        documentPrivateSavedSetText = function (type) {
            $('#customerDocs_ccnmjq6o66').lawsExists(function () {
                if (type > 0) {
                    $(this).removeClass('save').addClass('active unsave').find('span').text('Bỏ lưu');
                    $(this).next().find('.content_bgfff').text('Bỏ lưu văn bản');
                } else {
                    $(this).removeClass('active unsave').addClass('save').find('span').text('Lưu');
                    $(this).next().find('.content_bgfff').text('Lưu văn bản');
                }
            });
            $('.private.customer-doc').lawsExists(function () {
                if (type > 0) {
                    $(this).removeClass('save').addClass('active unsave').find('span').text('Bỏ lưu');
                } else {
                    $(this).removeClass('active unsave').addClass('save').find('span').text('Lưu');
                }
            });
        },
        hasTrackedDocumentEffectSetText = function (type) {
            $('#customerDocs_5um68a24jk').lawsExists(function () {
                if (type > 0) {
                    $(this).removeClass('save').addClass('active unsave').find('span').text('Bỏ theo dõi hiệu lực VB');
                    $(this).next().find('.content_bgfff').text('Bỏ theo dõi hiệu lực VB');
                } else {
                    $(this).removeClass('active unsave').addClass('save').find('span').text('Theo dõi hiệu lực VB');
                    $(this).next().find('.content_bgfff').text('Theo dõi hiệu lực VB');
                }
            });
            $('#customerDocs_5um68a24jj').lawsExists(function () {
                var btnDoc = $(this).closest('.document-item').find('.btn-doc').first();
                if (type > 0) {
                    $(this).prop('checked', true);
                    btnDoc.removeClass('save').addClass('active unsave');
                } else {
                    $(this).prop('checked', false);
                    if (!$('#customerDocs_5um68a24ji').is(':checked')) {
                        btnDoc.removeClass('active unsave').addClass('save');
                    }
                }
            });
        },
        hasTrackedDocumentPrivateEffectSetText = function (type) {
            $('#customerDocs_5um68a24').lawsExists(function () {
                var btnDoc = $(this).closest('.document-item').find('.btn-doc').first();
                if (type > 0) {
                    $(this).prop('checked', true);
                    btnDoc.removeClass('save').addClass('active unsave');
                } else {
                    $(this).prop('checked', false);
                    if (!$('#customerDocs_5um68a24ii').is(':checked')) {
                        btnDoc.removeClass('active unsave').addClass('save');
                    }
                }
            });
        },
        hasEffectTrackingsAllSetText = function (type) {
            $('#customerDocs_5um68a24ji').lawsExists(function () {
                var btnDoc = $(this).closest('.document-item').find('.btn-doc').first();
                if (type > 0) {
                    $(this).prop('checked', true);
                    btnDoc.removeClass('save').addClass('active unsave');
                } else {
                    $(this).prop('checked', false);
                    if (!$('#customerDocs_5um68a24jj').is(':checked')) {
                        btnDoc.removeClass('active unsave').addClass('save');
                    }
                }
            });
        },
        loadDocContent = function (el) {
            try {
                var parent = el.closest('.tab-item-content'), container = parent.find('.docContent').first();
                var docId = el.data('id'), embedContent = container.prev('.embedContent'), embed = embedContent.find('embed').first(), iframe = embedContent.find('iframe').first(),
                    dropDownViewFile = parent.find('.item-status-btn').first();
                el.hide();
                dropDownViewFile.lawsExists(function () {
                    $(this).first().html('<img alt="download" class="icvbgoc" src="/assets/images/download-docx.svg">  Văn bản gốc (Word)<i class="iconlvn-arrow-down"></i>');
                });
                $('.btn-xem-vbword').lawsExists(function () {
                    $(this).show();
                });
                $(opts.appearance).lawsExists(function () {
                    $(this).show();
                });
                container.show();
                if (embed.length || iframe.length) {
                    embedContent.hide();
                }

                if (container.children().length === 0 ||
                    container.children('p').text() ===
                    'Đang tải nội dung văn bản. Vui lòng đợi...' || container.children('div.content-entry').text() === 'Quý khách vui lòng thử lại sau.') {
                    if (typeof docId !== 'undefined') {
                        window.setTimeout(function () {
                            $.ajax({
                                url: lawsVnConfig.rootPath + 'Ajax/Docs_GetContentViewDetailResponsive',
                                type: 'post',
                                data: { docId: docId },
                                dataType: 'html',
                                cache: true,
                                timeout: 35000,
                                success: function (data) {
                                    if (data !== null && data.length > 0) {
                                        var nightModeKey = 'luatvietnam_night_mode', nightModeValue = 0;
                                        container.html(data);
                                        luatVietnamStore.getItem(nightModeKey,
                                            function (response) {
                                                if (response !== null) {
                                                    nightModeValue = response;
                                                    $('.noidungtracuu').closest('.the-document-entry').lawsExists(function () {
                                                        if (nightModeValue === 1) {
                                                            $(this).addClass('dark-mode');
                                                        }
                                                        else {
                                                            $(this).removeClass('dark-mode');
                                                        }
                                                    });
                                                }
                                            });
                                        //if ($(activeTab).find('embed').length) {
                                        //    $('.innoidung').hide();
                                        //    $('.loadcontent').lawsExists(function () {
                                        //        $(this).hide();
                                        //    });
                                        //    $('.fixmucluc_new').lawsExists(function () {
                                        //        $(this).hide();
                                        //    });
                                        //} else {
                                        $('.innoidung').show();
                                        $('.loadcontent').lawsExists(function () {
                                            $(this).show();
                                        });
                                        $('.fixmucluc_new').lawsExists(function () {
                                            $(this).show();
                                        });
                                        //}
                                    }
                                },
                                error: function (jqXhr, errorMessage) {
                                    container.html(
                                        '<div class="content-entry content-fixed boxnoidung v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                                    $('.innoidung').hide();
                                    $('.loadcontent').lawsExists(function () {
                                        $(this).hide();
                                    });
                                }
                            });
                        },
                            0);
                    }
                } else {
                    $('.innoidung').show();
                    $('.loadcontent').lawsExists(function () {
                        $(this).show();
                    });
                    $('.fixmucluc_new').lawsExists(function () {
                        $(this).show();
                    });
                    container.show();
                }
            }
            catch (err) {

            }
        },
        loadDiagramContent = function () {
            try {
                var el = $('#diagram-content');
                el.show();
                var docId = el.data('id'),
                    languageId = el.data('lang'), docGroupId = el.data('group'),
                    urlRequest = '/Ajax/Docs_GetDiagramViewDetailResponsive';
                if (docGroupId == 5) {
                    urlRequest = '/Ajax/DocsConsolidation_GetDiagramViewDetailResponsive';
                } else if (docGroupId == 3) {
                    urlRequest = '/Ajax/DocsVietNamStandard_GetDiagramViewDetailResponsive';
                }
                if (el.children().length === 0 ||
                    el.children('p').text() ===
                    'Đang tải lược đồ văn bản. Quý khách vui lòng đợi...' || el.children('div.content-entry').text() === 'Quý khách vui lòng thử lại sau.') {
                    if (typeof docId !== 'undefined' && typeof languageId !== 'undefined') {
                        window.setTimeout(function () {
                            $.ajax({
                                url: urlRequest,
                                type: 'post',
                                data: { docId: docId, languageId: languageId },
                                dataType: 'html',
                                cache: true,
                                timeout: 35000,
                                success: function (resp) {
                                    if (resp !== null && resp.length > 0) {
                                        el.html(resp);
                                        //$('#ReverseEffect').lawsExists(function () {
                                        //    var messages = $(this).text();
                                        //    $('.ReverseEffect_').html('<span style="color: #bb6b0a;font-style: italic;">' + messages + '</span>');
                                        //    if ($('.ReverseEffect'))
                                        //    $('.ReverseEffect').append('<div class="item-meta" style="color: #bb6b0a;font-style: italic;">' + messages.replace('Khoản 4 -', 'Khoản 4-') + '</div>');
                                        //});
                                        lawsVn.docComment($('#diagram-doc-comment'));
                                        $('.doc-properties').tooltip({
                                            //content: 'Vui lòng đợi...',
                                            track: true,
                                            content: function (response) {
                                                var id = this.id;
                                                var splitId = id.split('-');
                                                var languageId = splitId[1];
                                                var docId = splitId[2];
                                                $.ajax({
                                                    url: lawsVn.virtualPath('/Ajax/GetDocProperties'),
                                                    data: { docId: docId, languageId: languageId },
                                                    type: 'Post'
                                                })
                                                    .then(function (data) {
                                                        response(data);
                                                    });
                                            },
                                            items: "*"
                                        });
                                    }
                                },
                                error: function (jqXhr, errorMessage) {
                                    el.html(
                                        '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                                }
                            });
                        },
                            0);
                    }
                } else {
                    el.show();
                }
            } catch (e) {

            }
        },
        loadDocEffectContent = function () {
            try {
                var el = $('#effect-content');
                el.show();
                var docId = el.data('id'),
                    languageId = el.data('lang');
                if (el.children().length === 0 ||
                    el.children('p').text() ===
                    'Đang tải dữ liệu. Quý khách vui lòng đợi...' || el.children('div.content-entry').text() === 'Quý khách vui lòng thử lại sau.') {
                    if (typeof docId !== 'undefined' && typeof languageId !== 'undefined') {
                        window.setTimeout(function () {
                            $.ajax({
                                url: lawsVnConfig.rootPath + 'Ajax/Docs_GetEffectViewDetailResponsive',
                                type: 'post',
                                data: { docId: docId, languageId: languageId, trial: location.href.indexOf('-trial.html') !== -1 ? 1 : 0 },
                                dataType: 'html',
                                cache: true,
                                timeout: 35000,
                                success: function (resp) {
                                    if (resp !== null && resp.length > 0) {
                                        el.html(resp);
                                        lawsVn.docComment($('#effect-doc-comment'));
                                    }
                                },
                                error: function (jqXhr, errorMessage) {
                                    el.html(
                                        '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                                }
                            });
                        },
                            0);
                    }
                } else {
                    el.show();
                }
            } catch (e) {

            }
        },
        loadDocRelateContent = function () {
            try {
                var el = $('#relate-content');
                el.show();
                var docId = el.data('id'),
                    relateTypeId = el.data('relatetypeid'),
                    languageId = el.data('lang');
                if (el.children().length === 0 ||
                    el.children('p').text() ===
                    'Đang tải dữ liệu. Quý khách vui lòng đợi...' || el.children('div.content-entry').text() === 'Quý khách vui lòng thử lại sau.') {
                    if (typeof docId !== 'undefined' && typeof relateTypeId !== 'undefined' && typeof languageId !== 'undefined') {
                        window.setTimeout(function () {
                            $.ajax({
                                url: lawsVnConfig.rootPath + 'Ajax/Docs_GetRelateViewDetailResponsive',
                                type: 'post',
                                data: { docId: docId, relateTypeId: relateTypeId, languageId: languageId, trial: location.href.indexOf('-trial.html') !== -1 ? 1 : 0 },
                                dataType: 'html',
                                cache: true,
                                timeout: 35000,
                                success: function (resp) {
                                    if (resp !== null && resp.length > 0) {
                                        el.html(resp);
                                    }
                                },
                                error: function (jqXhr, errorMessage) {
                                    el.html(
                                        '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                                }
                            });
                        },
                            0);
                    }
                } else {
                    el.show();
                }
            } catch (e) {

            }
        },
        loadDocEngContent = function () {
            try {
                var el = $('#english-content');
                el.show();
                var docId = el.data('id');
                if (el.children().length === 0 ||
                    el.children('p').text() ===
                    'Đang tải dữ liệu. Quý khách vui lòng đợi...' || el.children('div.content-entry').text() === 'Quý khách vui lòng thử lại sau.') {
                    if (typeof docId !== 'undefined') {
                        window.setTimeout(function () {
                            lawsVn.fetchData({
                                url: lawsVnConfig.rootPath + 'Ajax/Docs_GetEngContentViewDetailResponsive',
                                type: 'post',
                                data: { docId: docId },
                                dataType: 'html',
                                cache: true,
                                timeout: 35000,
                                beforeSend: function () { },
                                always: function () { }
                            }).then((resp) => {
                                if (resp !== null && resp.length > 0) {
                                    el.html(resp);
                                    $('#DocumentsTranslationRequiredForm').lawsExists(function () {
                                        var cookieValue = lawsVn.getValueFromCookie('DocumentsTranslationRequired');
                                        if (cookieValue.length > 0) {
                                            var fullname = cookieValue['FullName'],
                                                email = cookieValue['Email'],
                                                mobile = cookieValue['Mobile'];
                                            if (typeof fullname !== 'undefined') {
                                                $(this).find(':input[name=FullName]').val(fullname);
                                            }
                                            if (typeof email !== 'undefined') {
                                                $(this).find(':input[name=Email]').val(email);
                                            }
                                            if (typeof mobile !== 'undefined') {
                                                $(this).find(':input[name=Mobile]').val(mobile);
                                            }
                                        }
                                    });
                                    var form = $('#DocumentsTranslationRequiredForm');
                                    form.removeData('validator');
                                    form.removeData('unobtrusiveValidation');
                                    $.validator.unobtrusive.parse(form);

                                    var vbgoc = $(resp).filter('.the-document-vbgoc'),
                                        embed = $(vbgoc).find('.embedContent').first(),
                                        check = "eng";

                                    if (embed.length) {
                                        loadIframe(embed, check);
                                    }
                                }
                            })
                                .catch((error) => {
                                    console.log(error)
                                    el.html(
                                        '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                                })
                            //$.ajax({
                            //    url: lawsVnConfig.rootPath + 'Ajax/Docs_GetEngContentViewDetailResponsive',
                            //    type: 'post',
                            //    data: { docId: docId },
                            //    dataType: 'html',
                            //    cache: true,
                            //    timeout: 35000,
                            //    success: function (resp) {
                            //        if (resp !== null && resp.length > 0) {
                            //            el.html(resp);
                            //            $('#DocumentsTranslationRequiredForm').lawsExists(function () {
                            //                var cookieValue = lawsVn.getValueFromCookie('DocumentsTranslationRequired');
                            //                if (cookieValue.length > 0) {
                            //                    var fullname = cookieValue['FullName'],
                            //                        email = cookieValue['Email'],
                            //                        mobile = cookieValue['Mobile'];
                            //                    if (typeof fullname !== 'undefined') {
                            //                        $(this).find(':input[name=FullName]').val(fullname);
                            //                    }
                            //                    if (typeof email !== 'undefined') {
                            //                        $(this).find(':input[name=Email]').val(email);
                            //                    }
                            //                    if (typeof mobile !== 'undefined') {
                            //                        $(this).find(':input[name=Mobile]').val(mobile);
                            //                    }
                            //                }
                            //            });
                            //            var form = $('#DocumentsTranslationRequiredForm');
                            //            form.removeData('validator');
                            //            form.removeData('unobtrusiveValidation');
                            //            $.validator.unobtrusive.parse(form);
                            //        }
                            //    },
                            //    error: function (jqXhr, errorMessage) {
                            //        el.html(
                            //            '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                            //    }
                            //});
                        },
                            0);
                    }
                } else {
                    el.show();
                }
            } catch (e) {

            }
        },
        loadDocPrivateEngContent = function () {
            try {
                var el = $('#english-content-private');
                el.show();
                var docId = el.data('id');
                if (el.children().length === 0 ||
                    el.children('p').text() ===
                    'Đang tải dữ liệu. Quý khách vui lòng đợi...' || el.children('div.content-entry').text() === 'Quý khách vui lòng thử lại sau.') {
                    if (typeof docId !== 'undefined') {
                        window.setTimeout(function () {
                            lawsVn.fetchData({
                                url: lawsVnConfig.rootPath + 'Ajax/DocsPrivate_GetEngContentViewDetail',
                                type: 'post',
                                data: { docId: docId },
                                dataType: 'html',
                                cache: true,
                                timeout: 35000,
                                beforeSend: function () { },
                                always: function () { }
                            }).then((resp) => {
                                if (resp !== null && resp.length > 0) {
                                    el.html(resp);

                                    var vbgoc = $(resp).filter('.the-document-vbgoc'),
                                        embed = $(vbgoc).find('.embedContent').first(),
                                        check = "eng";

                                    if (embed.length) {
                                        loadIframe(embed, check);
                                    }
                                }
                            })
                                .catch((error) => {
                                    console.log(error)
                                    el.html(
                                        '<div class="content-entry content-fixed v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                                })
                        },
                            0);
                    }
                } else {
                    el.show();
                }
            } catch (e) {

            }
        },
        printDocContent = function (el) {
            try {
                if (el.children().length > 0 ||
                    el.children('.content-entry').children('p').text() !==
                    'Đang tải nội dung văn bản. Vui lòng đợi...') {
                    var printContent = el,
                        cssLink = $('link'),
                        printWindow = window.open('',
                            '',
                            'height=' + window.outerHeight * 0.6 + ', width=' + window.outerWidth * 0.6);
                    printWindow.document.write('<html><head><title>luatvietnam.vn</title>');
                    for (var i = 0; i < cssLink.length; i++) {
                        printWindow.document.write(cssLink[i].outerHTML);
                    }
                    printWindow.document.write('<link rel="stylesheet" type="text/css" href="/assets/css/css.css"><link rel="stylesheet" type="text/css" href="/assets/css/custom.css"><link rel="stylesheet" type="text/css" href="/assets/print.css"><style>.print_item, .print-content{ display: none !important;}li.has-sub ul{display: block !important; overflow: initial !important;}.content-scroll-luocdo,.mCustomScrollbar,.mCustomScrollBox{max-height:unset !important;}.section-content{float:left;width:100%;position:relative}.layout-luoc-do{display:grid;float:left;grid-column-gap:24px;width:100%;grid-row-gap:24px;margin-bottom:24px;grid-template-columns:repeat(3,1fr)}.layout-luoc-do:last-child{margin-bottom:0}.post-luocdo{padding:8px 16px;border-top:solid 1px #e6e6e6;float:left;width:100%}.list-luocdo{border:solid 1px #e6e6e6;margin-bottom:12px}.list-luocdo:last-child{margin-bottom:0}.luocdo-scrol{max-height:227px;overflow-y:auto}.title-blt{background:#f9f9f9;color:#fff;background:#49c5c7;font-size:14px;padding:10px;text-decoration:none;width:100%}.title-ld{float:left;font-size:15px;font-weight:700;color:#fff;padding:8px 32px 8px 16px;background-color:#49c5c7;width:100%}.text-luocdo{width:100%;float:left;background:#e0f6f7;padding:8px 16px}.text-luocdo p{padding:4px 0}.text-luocdo hr{border:0;border-bottom:solid 1px #ddd}.head-ld{width:100%;float:left}.print-ld{display:inline-block;border:solid 1px #a67942;padding:4px 8px;color:#a67942;font-size:14px;font-weight:700;border-radius:2px}.print-ld i{margin-right:4px}.fix-tipdownload{width:340px}.tooltip-text-1{font-size:16px;border:solid 1px #444;background-color:#fff;width:100%;color:#222;float:left;padding:12px;cursor:initial;position:relative}.tooltip-text-2{font-size:15px;border:0;background-color:#f6e7b8;width:100%;float:left;padding:12px;cursor:initial;position:relative;text-align:center}.the-document-heading.fixhead{margin-bottom:24px;border-bottom:solid 1px #ddd;padding-bottom:12px}.block-vbhn{background:#fafafa;float:left;width:100%;border:solid 1px #ddd;margin-bottom:12px}.vbhn-title{padding:8px 16px;background:#a67942;float:left;width:100%;color:#fff;font-size:16px;text-align:center;font-weight:700}.vbhn-content{width:100%;float:left}.arrow-icon{width:100%;text-align:center;margin-bottom:12px;float:left}.bgvb-hopnhat{background:#437566}.block-hopnhat{width:100%;float:left}.block-list-title{background:unset}.block-list-open .block-list-title{background:unset}.block-list-title.fixfont{font-size:14px;padding:12px 36px 12px 16px}.luocdo-scrol{max-height:unset}.block-bandich { position: absolute; margin-left: 555px; z-index: 2; }.block-bandich img { height: 58px; }.taive{display:none;}</style>');
                    printWindow.document.write('</head><body >');
                    printWindow.document.write(
                        '<div class="hearder-logo-print"><div class="logo-print"><img alt="luat viet nam" src="' +
                        lawsVn.virtualPath('/assets/images/logo.png') +
                        '"></div></div>');
                    printWindow.document.write(printContent.html());
                    printWindow.document.write('</body></html>');
                    printWindow.document.close();
                    printWindow.onload = function () {
                        printWindow.focus();
                        setTimeout(function () {
                            printWindow.print();
                            printWindow.close();
                        },
                            100);
                    }
                }
            } catch (e) {
                console.log(e);
            }
        }
    printDocIndexes = function (id, mucluc) {
        try {
            let permission = true;
            $('.text-thongbao', $('#hieuluc')).lawsExists(function () {
                if ($(this).hasClass('not-loggedin')) {
                    permission = false;
                }
                else if ($(this).hasClass('not-have-access'))
                    permission = false;
            });

            if (!permission) {
                return;
            }

            var chidanthaydoind = $(id).first(), docIndex = $(mucluc).first();
            if (chidanthaydoind.length > 0 && docIndex.length > 0) {
                var items = chidanthaydoind.find('[class^="popupRelate"]:not(.text-link):not(.text-binhluan)').parents('div[class*="docitem"]').not('.docitem-2'),//.not('.docitem-5'),
                    docIndexItems = docIndex.find('.item-article');

                for (var i = items.length - 1; i >= 0; i--) {

                    let item = $(items[i]), //chuong = $(item).hasClass('docitem-2') ? $(item) : $(item).prevAll('.docitem-2').first(),
                        //dieu = $(item).hasClass('docitem-5') ? $(item) : $(item).prevAll('.docitem-5').first(), result = ''
                        dieu = $(item).hasClass('docitem-10') ? $(item) : $(item).prevAll('.docitem-10').first()
                    if (dieu.length == 0) {
                        dieu = $(item).hasClass('docitem-5') ? $(item) : $(item).prevAll('.docitem-5').first()
                    }
                    if (dieu.length > 0) {
                        let dieuText, mucluc
                        let demuc = item.attr('id')

                        if (!demuc) {
                            demuc = dieu.attr('id')
                        }
                        if (demuc) {
                            mucluc = docIndexItems.filter(function () {
                                return $(this).hasClass(demuc);
                            })
                        } else {
                            dieuText = dieu.find('b, strong').first()
                                .text().toLowerCase().trim()
                            mucluc = docIndexItems.filter(function () {
                                return $(this).clone()
                                    .children()
                                    .remove()
                                    .end()
                                    .text().toLowerCase().trim() == dieuText;
                            })
                        }
                     
                        //let dieuText = dieu.find('b').first()
                        //    .text().toLowerCase().trim()

                        //let mucluc = docIndexItems.filter(function () {
                        //    return $(this).clone()
                        //        .children()
                        //        .remove()
                        //        .end()
                        //        .text().toLowerCase().trim() == dieuText;
                        //})

                        if (mucluc.length > 0) {
                            let parent = mucluc.closest('.popup-content'),

                                result = '', content = '';
                            let popupRelates = $(item).find('[class*="popupRelate"]');

                            const addedTitles = new Set();

                            $(popupRelates).each(function (i, pRelate) {
                                if (!$(pRelate).hasClass('text-link') && $(pRelate).closest('.docitemadd').length == 0) {

                                    let title = $(pRelate).attr('data-title') || $(pRelate).attr('title'),
                                        className = $(pRelate).attr('class').replace('popupRelate2', '').replace('popupRelate', '').replace('docitem-', 'color-').replace('text-thaythecumtu', 'text-thaythecumtu-index').trim()

                                    if (title && title.length > 0) {
                                        //result = ''
                                        if (title.startsWith('<br/>')) {
                                            title = title.substr(5);
                                        } else if (title.startsWith('<br />')) {
                                            title = title.substr(6);
                                        } else if (title.startsWith('<br>')) {
                                            title = title.substr(4);
                                        }
                                        if ($(title).is('span')) {
                                            var titleClassName = $(title).attr('class') || '',
                                                array = $(title).html().split('<br>')

                                            for (var i = 0; i < array.length; i++) {

                                                var tempElement = $('<div>').html(array[i]);
                                                tempElement.find('*').not('.tooltipexpired').each(function () {
                                                    $(this).replaceWith($(this).text());
                                                });

                                                title = tempElement.html().trim();// array[i].replace(/(<([^>]+)>)/gi, '')

                                                if ($(pRelate).hasClass('text-bosungcumtu') || $(pRelate).hasClass('text-baibocumtu')) {

                                                    title = title.replace('Cụm từ này', `Cụm từ ${$(pRelate).clone()
                                                        .children()
                                                        .remove()
                                                        .end()
                                                        .text()}`)
                                                }

                                                var exists = mucluc.find('.ul-chuthich-mucluc li').filter(function () {
                                                    return $(this).text().replace(/^\- /, '').trim() === title.trim();
                                                });

                                                if (exists.length == 0) {

                                                    const muclucClassName = mucluc.attr('class');

                                                    if (muclucClassName && muclucClassName.indexOf('mucluclv2') != -1) {
                                                        result += `<li class='li-news-tip'><a href="javascript:void(0)" class="${titleClassName}">${title}</a></li>`;
                                                    }
                                                    else
                                                    {
                                                        result += `<li class='li-news-tip'><a href="javascript:void(0)" class="${titleClassName}">- ${title}</a></li>`;
                                                    }
                                                }
                                            }

                                        } else {
                                            //title = title.replace(/(<([^>]+)>)/gi, '')
                                            var tempElement = $('<div>').html(title);
                                            tempElement.find('*').not('.tooltipexpired').each(function () {
                                                $(this).replaceWith($(this).text());
                                            });

                                            title = tempElement.html().trim();
                                            if ($(pRelate).hasClass('text-bosungcumtu') || $(pRelate).hasClass('text-baibocumtu')) {

                                                title = title.replace('Cụm từ này', `Cụm từ ${$(pRelate).clone()
                                                    .children()
                                                    .remove()
                                                    .end()
                                                    .text()}`)
                                            }

                                            var exists = mucluc.find('.ul-chuthich-mucluc li').filter(function () {
                                                return $(this).text().replace(/^\- /, '').trim() === title.trim();
                                            })

                                            if (exists.length == 0) {
                                                result += `<li class='li-news-tip'><a href="javascript:void(0)" class="${className}">- ${title}</a></li>`;
                                            }
                                        }
                                    }
                                }

                            })

                            if (result.length > 0) {

                                let prevElement = parent.prev('.row-head-status');

                                if (prevElement.length == 0) {
                                    let chkId = id.replace('#', '');
                                    $(`<div class="row-head-status">
                                        <div class="item-status">
                                            <input class="tgl tgl-light" id="chkTOC_${chkId}" type="checkbox" checked="checkbox">
                                            <label class="tgl-btn" for="chkTOC_${chkId}"></label>
                                            Hiện chú thích
                                        </div>
                                        <div class="item-status">
                                            <span title="In mục lục" class="btn-printdoc toc-print"><i class="iconlvn-printer"></i> In mục lục</span>
                                        </div>
                                    </div>`).insertBefore(parent);
                                }

                                let chuthich = mucluc.find('.ul-chuthich-mucluc');

                                const muclucClassName = mucluc.attr('class');
                                const mucLucText = mucluc.clone().children('.ul-chuthich-mucluc').remove().end().text().trim();

                                if (muclucClassName && muclucClassName.indexOf('mucluclv2') != -1) {
                                    if (mucLucText.length <= 5) {
                                        mucluc.contents().filter(function () {
                                            return this.nodeType === 3 || (this.nodeType === 1 && !$(this).is('.ul-chuthich-mucluc'));
                                        }).remove();
                                    }
                                }

                                if (chuthich.length == 0) {
                                    $(mucluc).append('<ul class="ul-chuthich-mucluc"></ul>');
                                    chuthich = mucluc.find('.ul-chuthich-mucluc');
                                }

                                chuthich.append(result);
                            }
                        }
                    }

                }
            }
        } catch (e) {
            console.log(e)
        }
    }
    $(function () {
        maxHeight = 0;
        if ($(activeTab + ' .content-entry').length > 0) {
            maxHeight = $(activeTab + ' .content-entry').height();
        }

        setTimeout(customerDocs(), 0);
        setTimeout(customerPrivateDocs(), 0);
        showTab();
        setTimeout(nightMode(), 0);
    });
    $(document).on('change', '#chkTOC_chidanthaydoind, #chkTOC_noidungtoanvan', function () {
        var self = $(this), parent = self.closest('.popup-body'),
            mucluc = parent.find('.toc-document .ul-chuthich-mucluc')

        if (self.is(':checked')) {
            mucluc.show();
        } else {
            mucluc.hide();
        }
    })
    $(document).on('click', '.toc-print', function () {
        var self = $(this), parent = self.closest('.popup-body'),
            mucluc = parent.find('.toc-document')

        var printContent = mucluc,
            cssLink = $('link'),
            printWindow = window.open('',
                '',
                'height=' + window.outerHeight * 0.6 + ', width=' + window.outerWidth * 0.6);
        printWindow.document.write('<html><head><title>luatvietnam.vn</title>');
        for (var i = 0; i < cssLink.length; i++) {
            printWindow.document.write(cssLink[i].outerHTML);
        }
        printWindow.document.write('<link rel="stylesheet" type="text/css" href="/assets/css/css.css"><link rel="stylesheet" type="text/css" href="/assets/css/custom.css"><link rel="stylesheet" type="text/css" href="/assets/print.css"><style>.print_item, .print-content{ display: none !important;}li.has-sub ul{display: block !important; overflow: initial !important;}.content-scroll-luocdo,.mCustomScrollbar,.mCustomScrollBox{max-height:unset !important;}.section-content{float:left;width:100%;position:relative}.layout-luoc-do{display:grid;float:left;grid-column-gap:24px;width:100%;grid-row-gap:24px;margin-bottom:24px;grid-template-columns:repeat(3,1fr)}.layout-luoc-do:last-child{margin-bottom:0}.post-luocdo{padding:8px 16px;border-top:solid 1px #e6e6e6;float:left;width:100%}.list-luocdo{border:solid 1px #e6e6e6;margin-bottom:12px}.list-luocdo:last-child{margin-bottom:0}.luocdo-scrol{max-height:227px;overflow-y:auto}.title-blt{background:#f9f9f9;color:#fff;background:#49c5c7;font-size:14px;padding:10px;text-decoration:none;width:100%}.title-ld{float:left;font-size:15px;font-weight:700;color:#fff;padding:8px 32px 8px 16px;background-color:#49c5c7;width:100%}.text-luocdo{width:100%;float:left;background:#e0f6f7;padding:8px 16px}.text-luocdo p{padding:4px 0}.text-luocdo hr{border:0;border-bottom:solid 1px #ddd}.head-ld{width:100%;float:left}.print-ld{display:inline-block;border:solid 1px #a67942;padding:4px 8px;color:#a67942;font-size:14px;font-weight:700;border-radius:2px}.print-ld i{margin-right:4px}.fix-tipdownload{width:340px}.tooltip-text-1{font-size:16px;border:solid 1px #444;background-color:#fff;width:100%;color:#222;float:left;padding:12px;cursor:initial;position:relative}.tooltip-text-2{font-size:15px;border:0;background-color:#f6e7b8;width:100%;float:left;padding:12px;cursor:initial;position:relative;text-align:center}.the-document-heading.fixhead{margin-bottom:24px;border-bottom:solid 1px #ddd;padding-bottom:12px}.block-vbhn{background:#fafafa;float:left;width:100%;border:solid 1px #ddd;margin-bottom:12px}.vbhn-title{padding:8px 16px;background:#a67942;float:left;width:100%;color:#fff;font-size:16px;text-align:center;font-weight:700}.vbhn-content{width:100%;float:left}.arrow-icon{width:100%;text-align:center;margin-bottom:12px;float:left}.bgvb-hopnhat{background:#437566}.block-hopnhat{width:100%;float:left}.block-list-title{background:unset}.block-list-open .block-list-title{background:unset}.block-list-title.fixfont{font-size:14px;padding:12px 36px 12px 16px}.luocdo-scrol{max-height:unset}.block-bandich { position: absolute; margin-left: 555px; z-index: 2; }.block-bandich img { height: 58px; }.taive{display:none;}</style>');
        printWindow.document.write('</head><body >');
        printWindow.document.write(
            '<div class="hearder-logo-print"><div class="logo-print"><img alt="luat viet nam" src="' +
            lawsVn.virtualPath('/assets/images/logo.png') +
            '"></div></div>');
        printWindow.document.write(printContent.html());
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.onload = function () {
            printWindow.focus();
            setTimeout(function () {
                printWindow.print();
                printWindow.close();
            },
                100);
        }
    })
    $(document).on('click',
        '.btn-xem-vbgoc',
        function () {
            loadDocContent($(this));
        });
    $('.cat-more-icon').click(function () {
        $("#tabs-scroll").animate({ scrollLeft: "+=100px" });
    });
    $(document).on('click',
        '.btn-xem-vb2, .btn-xem-vbword',
        function (e) {
            e.preventDefault();
            var self = $(this), parent = self.closest(opts.tabs.noidung), dropDownViewFile = parent.find('.item-status-btn').first();
            self.hide();
            dropDownViewFile.lawsExists(function () {
                $(this).first().html('<img alt="download" class="icvbgoc" src="/assets/images/download-pdf.svg"> Văn bản gốc có dấu (PDF)<i class="iconlvn-arrow-down"></i>');
            });
            $('.btn-xem-vbgoc').lawsExists(function () {
                $(this).data('id', 1).show();
            });
            $(opts.appearance).lawsExists(function () {
                $(this).hide();
            });
            parent.find('.embedContent').lawsExists(function () {
                $(this).show();
            });
            parent.find('.docContent').lawsExists(function () {
                $(this).hide();
            });
            $('.innoidung').hide();
            $('.loadcontent').lawsExists(function () {
                $(this).hide();
            });
            $('.fixmucluc_new').lawsExists(function () {
                $(this).hide();
            });
        });
    $(document).on('click',
        '.text-light',
        function (event) {
            event.preventDefault();
            luatVietnamStore.setItem(nightModeKey, 0, expiry);
            nightMode();
        });
    $(document).on('click',
        '.text-dark',
        function (event) {
            event.preventDefault();
            luatVietnamStore.setItem(nightModeKey, 1, expiry);
            nightMode();
        });

    $(window).on('hashchange', function () {
        var hash = location.hash;
        $(opts.tabClass).removeClass('active');
        var el = $('.tab-nav-item-ad[data-tab-target="' + hash + '"]');
        if (!el.hasClass('unavailable')) {
            el.addClass('active');
            showTab(hash, false, false);
        }
    });
    $(document).on('click',
        opts.tabClass,
        function (e) {
            e.preventDefault();
            viewMix = false;
            var hash = $(this).attr('data-tab-target');
            if (typeof hash !== 'undefined' && !$(this).hasClass('unavailable')) {
                tabClick = true;
                showTab(hash);
            }
        });
    $(document).on('click',
        opts.linkPhuluc,
        function (e) {
            e.preventDefault();
            viewMix = false;
            var hash = $(this).attr('data-tab-target');
            showTab(hash);
        });
    $(document).on('click', '.btn-more-relate', function (event) {
        event.preventDefault();
        const self = $(this), parent = self.closest('.luocdo-item'),
            hiddenItems = parent.find('div.target-hidden'),
            availableItems = parent.find('div[data-available="1"]'),
            initialItems = availableItems.length

        if (hiddenItems.length) {
            hiddenItems.removeClass('target-hidden')
            self.text('Thu gọn')
        } else {
            parent.find('div.post-luocdo').addClass('target-hidden')

            availableItems.slice(0, initialItems).removeClass('target-hidden')

            if (availableItems.length < initialItems) {
                parent.find('div:not([data-available])')
                    .slice(0, initialItems - availableItems.length)
                    .removeClass('target-hidden')
            }

            self.text('Xem thêm')
        }
    })
    $(document).on('click',
        opts.item_mucluc,
        function (e) {

            e.preventDefault();
            var className = $(this).attr('class').replace(/\s{2,}/g, ' ').split(' '), target = $('#' + className[1].replace('-', ''));

            $('#mucluc2').lawsExists(function () {
                $(this).hide();
            }); $('#mucluc3').lawsExists(function () {
                $(this).hide();
            });

            if (activeTab === opts.tabs.chidanthaydoi) {
                target = $('#' + className[1], $('#chidanthaydoind'));
            } else target = $('#' + className[1], $('#noidungtoanvan'));

            if ($(activeTab).find('.row-loadmore').first().length > 0 && target.length <= 0) {
                targetIndex = '#' + className[1];
                if (activeTab === opts.tabs.chidanthaydoi) {
                    $('.loadmore-btn.ndchidan').trigger('click');
                } else {
                    $('.loadmore-btn.ndmix').trigger('click');
                }
            }

            if (target.length) {
                $('#closePopup').lawsExists(function () {
                    $(this).find('a').text('Mục Lục');
                    $('#mucluc').lawsExists(function () {
                        $(this).hide();
                    });
                });
                $('#closePopup2').lawsExists(function () {
                    $(this).find('a').text('Mục Lục');
                    $('#mucluc2').lawsExists(function () {
                        $(this).hide();
                    });
                });
                $('#closePopup3').lawsExists(function () {
                    $(this).find('a').text('Mục Lục');
                    $('#mucluc3').lawsExists(function () {
                        $(this).hide();
                    });
                });
                showTab(activeTab, false);
                var height = 0, elNav = $('#doc-sticky');
                if (elNav.length) {
                    height = elNav.outerHeight();
                    if (!elNav.hasClass('fixed-tabvb')) {
                        height = height + 50;
                    }
                }

                $('html, body').animate({
                    scrollTop: target.offset().top - height
                },
                    500);
            } else {
                $('#closePopup').lawsExists(function () {
                    $(this).find('a').text('Mục Lục');
                    $('#mucluc').lawsExists(function () {
                        $(this).hide();
                    });
                });
                $('#closePopup2').lawsExists(function () {
                    $(this).find('a').text('Mục Lục');
                    $('#mucluc2').lawsExists(function () {
                        $(this).hide();
                    });
                });
            }
        });
    $(document).on('click', '.r4xc0t0ksm', function () {
        $(this).closest('.w_content2').find('.ul_w_content2').slideToggle('fast');
    });
    $(document).on('click', 'div[class*=demucsosanh]', function (e) {
        e.preventDefault();
        var className = $(this).attr('class').replace(/\s{2,}/g, ' ').split(' '), target = $('#' + className[1].replace('-', ''));
        console.log(className)
        $('#mucluc5').lawsExists(function () {
            $(this).hide();
        });
        var target = $('#' + className[1], $('#_vbsongngu'));
        var parent = $('.l08fyuscmy', $('#_vbsongngu'));
        if (target.length) {
            parent.animate({
                scrollTop: target.position().top + parent.scrollTop()
            }, 1000);
        }
    })
    $(document).on('click',
        opts.print,
        function (event) {
            event.preventDefault();
            $(activeTab).find('.noidungtracuu').first().lawsExists(function () {
                printDocContent($(this));
            })
            $(activeTab).find('.docContent').lawsExists(function () {
                var el = $(this), docId = el.data('id');
                if (el.children().length === 0 ||
                    el.children('p').text() ===
                    'Đang tải nội dung văn bản. Vui lòng đợi...' || el.children('div.content-entry').text() === 'Quý khách vui lòng thử lại sau.') {
                    if (typeof docId !== 'undefined') {
                        window.setTimeout(function () {
                            $.ajax({
                                url: lawsVnConfig.rootPath + 'Ajax/Docs_GetContentViewDetailResponsive',
                                type: 'post',
                                data: { docId: docId },
                                dataType: 'html',
                                cache: true,
                                async: false,
                                timeout: 35000,
                                success: function (data) {
                                    if (data !== null && data.length > 0) {
                                        el.html(data);
                                        try {
                                            var cssLink = $('link'),
                                                printWindow = window.open('',
                                                    '',
                                                    'height=' +
                                                    window.outerHeight * 0.6 +
                                                    ', width=' +
                                                    window.outerWidth * 0.6);
                                            printWindow.document.write('<html><head><title>luatvietnam.vn</title>');
                                            for (var i = 0; i < cssLink.length; i++) {
                                                printWindow.document.write(cssLink[i].outerHTML);
                                            }
                                            printWindow.document.write(
                                                '<link rel="stylesheet" type="text/css" href="/assets/css/css.css"><link rel="stylesheet" type="text/css" href="/assets/css/custom.css"><link rel="stylesheet" type="text/css" href="/assets/print.css"><style>.print_item{ display: none;}</style>');
                                            printWindow.document.write('</head><body >');
                                            printWindow.document.write(
                                                '<div class="hearder-logo-print"><div class="logo-print"><img alt="luat viet nam" src="' +
                                                lawsVn.virtualPath('/assets/images/logo.png') +
                                                '"></div></div>');
                                            printWindow.document.write(data);
                                            printWindow.document.write('</body></html>');
                                            printWindow.document.close();
                                            printWindow.onload = function () {
                                                printWindow.focus();
                                                setTimeout(function () {
                                                    printWindow.print();
                                                    printWindow.close();
                                                },
                                                    100);
                                            }
                                        } catch (e) {
                                            console.log(e);
                                        }
                                    }
                                },
                                error: function (jqXhr, errorMessage) {
                                    el.html(
                                        '<div class="content-entry content-fixed boxnoidung v4"><p>Quý khách vui lòng thử lại sau.</p></div>');
                                }
                            });
                        },
                            300);
                    }
                } else {
                    printDocContent(el);
                }
            });
        });
    $(document).on('click',
        opts.printLd,
        function (event) {
            event.preventDefault();
            printDocContent($(activeTab).find('.boxluocdo'));
        });
    $(document).on('click',
        '#tang-font',
        function () {
            var target = $('#noidung .noidungtracuu');
            if ($('#chidanthaydoi').is(':visible')) {
                if ($('#chidanthaydoind').length)
                    target = $('#chidanthaydoind');
                else target = $('#chidanthaydoi .noidungtracuu');
            }
            else if ($('#noidungmix').is(':visible'))
                target = $('#noidungmix .noidungtracuu').not('.hidden');
            else if ($('#tienganh').is(':visible'))
                target = $('#tienganh .noidungtracuu');
            console.log(target)
            setFontSize(target, 1 / factor, 13, 35);
            displayCurrentFontSize();
        });
    $(document).on('click',
        '#giam-font',
        function () {
            var target = $('#noidung .boxnoidung');
            if ($('#chidanthaydoi').is(':visible')) {
                if ($('#chidanthaydoind').length)
                    target = $('#chidanthaydoind');
                else target = $('#chidanthaydoi .boxnoidung');
            }
            else if ($('#noidungmix').is(':visible'))
                target = $('#noidungmix .noidungtracuu').not('.hidden');
            else if ($('#tienganh').is(':visible'))
                target = $('#tienganh .boxtienganh');
            setFontSize(target, factor, 13, 35);
            displayCurrentFontSize();
        });
    $(document).on('click',
        '.increase-font',
        function () {
            var self = $(this), parent = self.closest('.phantichvb'), target = parent.find('.ptvb');
            setFontSize(target, 1 / factor, 14, 35);
        });
    $(document).on('click',
        '.increase-font-left',
        function () {
            var self = $(this), target = $('.entry-phan-tich.left');
            setFontSize(target, 1 / factor, 14, 35);
        });
    $(document).on('click',
        '.increase-font-right',
        function () {
            var target = $('.entry-phan-tich.right');
            setFontSize(target, 1 / factor, 14, 35);
        });
    $(document).on('click',
        '.increase-font-center',
        function () {
            var target = $('.entry-phan-tich.centerr');
            setFontSize(target, 1 / factor, 14, 35);
        });
    $(document).on('click',
        '.font-reduction',
        function () {
            var self = $(this), parent = self.closest('.phantichvb'), target = parent.find('.ptvb');
            setFontSize(target, factor, 14, 35);
        });
    $(document).on('click',
        '.font-reduction-left',
        function () {
            var target = $('.entry-phan-tich.left');
            setFontSize(target, factor, 14, 35);
        });
    $(document).on('click',
        '.font-reduction-right',
        function () {
            var target = $('.entry-phan-tich.right');
            setFontSize(target, factor, 14, 35);
        });
    $(document).on('click',
        '.font-reduction-center',
        function () {
            var target = $('.entry-phan-tich.centerr');
            setFontSize(target, factor, 14, 35);
        });
    $(document).on('click',
        '#show-only-terms-of-analysis',
        function () {
            if ($(this).is(':checked')) {
                $('.fix_docquyen').hide();
                $('.doc-item', $('.the-document-body.ptvb')).hide();
            } else {
                $('.fix_docquyen').show();
                $('.doc-item', $('.the-document-body.ptvb')).show();
            }
        });
    $(document).on('click',
        '#couo67lvea',
        function () {
            setFontSize($('.l08fyuscmy'), 1 / factor);
        });
    $(document).on('click',
        '#yh7kdsgdf1',
        function () {
            setFontSize($('.l08fyuscmy'), factor);
        });
    $(document).on('click',
        '#yk9amnid3q',
        function () {
            setFontSize($('.bz2r9a68x5'), 1 / factor);
        });
    $(document).on('click',
        '#qf9onljzbt',
        function () {
            setFontSize($('.bz2r9a68x5'), factor);
        });
    $(document).on('click',
        '.muclucvb',
        function () {
            var className = $(this).attr('class').replace(/\s{2,}/g, ' ').split(' '), target = $('#' + className[0].replace('-', ''), $(activeTab));
            $('#mucluc').lawsExists(function () {
                $(this).hide();
            });
            if ($(activeTab).find('.row-loadmore').first().length > 0 && target.length <= 0) {
                targetIndex = '#' + className[0];
                $('.loadmore-btn.nodungvb').trigger('click');
            }
            $('#closePopup').lawsExists(function () {
                $(this).find('a').text('Mục Lục');
                $('#mucluc').lawsExists(function () {
                    $(this).hide();
                });
            });
            $('#closePopup2').lawsExists(function () {
                $(this).find('a').text('Mục Lục');
                $('#mucluc2').lawsExists(function () {
                    $(this).hide();
                });
            });
            //showTab(activeTab, false);
            var height = 0, elNav = $('#doc-sticky');
            if (elNav.length) {
                height = elNav.outerHeight();
                if (!elNav.hasClass('fixed-tabvb')) {
                    height = height + 50;
                }
            }
            $('html, body').animate({
                scrollTop: target.offset().top - height
            },
                500);
        });
    $(document).on('click',
        '.view-timeline-mix',
        function (event) {
            event.preventDefault();
            viewMix = true;
            var self = $(this),
                docId = self.attr('data-id'),
                time = self.attr('data-time'),
                timeline_mix = $('#timeline-mix');
            timeline_mix.lawsExists(function () {
                var time_timeline_mix = $(this).attr('data-time');
                if (time_timeline_mix == time && $(this).children().length > 0) {
                    showTab('#noidungmix', true, false);
                } else {
                    if (typeof docId !== 'undefined' && typeof time !== 'undefined') {
                        if (self.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        self.attr('requestRunning', true);
                        $.ajax({
                            type: 'post',
                            async: true,
                            timeout: 35000,
                            url: lawsVn.virtualPath('/Ajax/DocItems_GetUnionTimeLineResponsive_View'),
                            dataType: 'html',
                            data: { docId: docId, time: time },
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    if (data != null && data.length) {
                                        timeline_mix.lawsExists(function () {
                                            $(this).html(data);
                                            $(this).attr('data-time', time);
                                            $(this).removeAttr('data-fs');
                                            showTab('#noidungmix', true, false);
                                        });
                                    }
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status !== 403) {
                                    if (jqXhr.status === 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                            showIcon: false
                                        });
                                    } else if (jqXhr.status === 404) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                            showIcon: false
                                        });
                                    } else {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Quý khách vui lòng thử lại sau.'],
                                            showIcon: false
                                        });
                                    }
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            self.removeAttr('requestRunning');
                        });
                    }
                }
            });
        });
    $(document).on('click',
        '.view-timeline-mix2',
        function (e) {
            e.preventDefault();
            $('#noidungtoanvan').lawsExists(function () {
                $(this).addClass('hidden');
            });
            $('#timeline-mix').lawsExists(function () {
                $(this).removeClass('hidden');
                if (timelineMix2 == '')
                    timelineMix2 = $(this).html();
                else if (timelineMix2 != '' && typeof $(this).data('time') !== 'undefined') {
                    $(this).removeAttr('data-time');
                    $(this).html(timelineMix2);
                }
            });
        });
    $(document).on('click',
        '#closePopupa, #btnDocIndexesm',
        function (e) {
            e.preventDefault();
            var seft = $(this),
                type = seft.hasClass('mixx'),
                duthao = typeof seft.data('type') !== 'undefined' && seft.data('type') == 2,
                pos = seft.position(),
                width = seft.outerWidth(),
                height = seft.outerHeight(),
                panel = $('#tabPannel');
            seft.closest('.fix_ghichu2').css({ 'zIndex': 9999999 });
            if (type) {
                if (activeTab === opts.tabs.chidanthaydoi) {
                    if ($('#mucluc2').length == 0) {
                        $('#mucluc').lawsExists(function () {
                            $(this).show();
                        });
                        $('#doccontentindex').lawsExists(function () {
                            $(this).show();
                        });
                    } else {
                        $('#mucluc2').lawsExists(function () {
                            $(this).show();
                        });
                        $('#doccontentindex2').lawsExists(function () {
                            $(this).show();
                        });
                    }
                } else if (activeTab === opts.tabs.noidungmix) {
                    $('#mucluc3').lawsExists(function () {
                        $(this).show();
                    });
                    $('#doccontentindex3').lawsExists(function () {
                        $(this).show();
                    });
                }
            } else
                $('#mucluc').lawsExists(function () {
                    $(this).show();
                });
        });
    $(document).on('click',
        '.doc-song-ngu',
        function (event) {
            var docId = $(this).attr('data-id');
            event.preventDefault();
            if (!lawsVn.isMobile()) {
                vanbansongngu(docId);
                fontSize = 14;
            }
            if (docId > 0) {
                lawsVn.logs.docViewLogs(docId, 1, 'vbsongngu');
            }
        });
    function vanbansongngu (docId) {
        $('#noteloading').html("Đang tải dữ liệu ...");
        if (typeof docId != 'undefined') {
            $.lawsAjax({
                type: 'GET',
                url: lawsVn.virtualPath('/Ajax/BilingualDocument'),
                data: { docId: docId },
                dataType: 'html',
                async: true,
                cache: true,
                timeout: 90000,
                beforeSend: {},
                success: function (resp) {
                    if (resp.length > 0) {
                        $('#_vbsongngu').html(resp)

                        //$('.popupRelate, .popupRelate2', $('#ndsongngu')).each(function (i, element) {
                        //console.log(e)
                        //popupChiDan(element, e);
                        //});

                        $('#ndsongngu').on({
                            mouseenter: function (e) {
                                popupChiDan($(this), e);
                            },
                            mouseleave: function () {
                                $('.dropdown-tips-content-2', $(this)).css('visibility', 'hidden');
                            }
                        }, '.popupRelate, .popupRelate2, .noi-dung-tham-chieu');

                        //$('.vbsongngu-vn', $("#_vbsongngu")).html($(resp).filter('#docsongngu-vn').html());
                        //$('.vbsongngu-en', $("#_vbsongngu")).html($(resp).filter('#docsongngu-en').html());
                        //s$('.toc-document', $("#_vbsongngu")).html($(resp).filter('#mucluc').html());
                    }
                }
            });
        }

    }
    function popupChiDan(el, e, isPrint) {
        var me = $(el),
            dd = me.children('.dropdown-tips-content-2'),
            contentEntry = me.closest('.content-entry'),
            title = typeof me.attr('data-title') === "undefined" ? me.attr('title') : me.attr('data-title'),
            href = me.data('href'),
            content,
            bosung = me.hasClass('docitem-58'),
            huongdan = me.hasClass('docitem-45'),
            thamchieu = title.includes('Nội dung tham chiếu') || me.hasClass('docitem-54'); 
            baibocumtu = me.hasClass('text-baibocumtu'),
            thaythecumtu = me.hasClass('text-thaythecumtu'),
            bosungcumtu = me.hasClass('text-bosungcumtu'),
            paragraphClass = '',
            flag = false,
            left = 0,
            email = $('.row-user-mail').text(),
            maincontentOffset = $('.main-content').offset(),
            isTrial = window.location.href.split('?')[0].indexOf('-trial.html') > -1,
            contentEntryRight = maincontentOffset.left + contentEntry.outerWidth();
        left = (e.pageX - maincontentOffset.left) / 2;
        if (e.pageX + 100 > contentEntryRight) {
            left = e.pageX - contentEntryRight;
            if (left <= contentEntryRight)
                left = contentEntryRight;
        }
        if (baibocumtu) {
            paragraphClass = 'class="text-baibocumtu-tooltip"';
        } else if (thaythecumtu) {
            paragraphClass = 'class="text-thaythecumtu-tooltip"';
        }
        else if (bosungcumtu) {
            paragraphClass = 'class="text-bosungcumtu-tooltip"';
        }
        if (typeof me.attr('title') !== 'undefined') {
            me.attr('data-title', me.attr('title'));
            me.removeAttr('title');
        }
        if ($('#check2').is(':checked') && activeTab == opts.arrTabs[7]) {
            $('.dropdown-tips-content-2', $('.chidanthaydoind')).not('.bosung').css('visibility', 'hidden');
        }
        else if ($('#check21').is(':checked') && activeTab == opts.arrTabs[8]) {
            $('.dropdown-tips-content-2', $('.noidungtoanvan')).not('.bosung').css('visibility', 'hidden');
        }
        else $('.dropdown-tips-content-2').not('.bosung').css('visibility', 'hidden');
        if (typeof title !== 'undefined') {
            content = $(title).map(function () {
                var e = $(this), temp = '';
                if (e.is('span')) {
                    flag = true;
                    if (e.html().length > 0 && typeof href !== 'undefined') {
                        if (huongdan) {
                            var arrHd = e.html().split('<br>');
                            for (var i = 0; i < arrHd.length; i++) {
                                var tempElement = $('<div>').html(arrHd[i]);
                                tempElement.find('*').not('.tooltipexpired').each(function () {
                                    $(this).replaceWith($(this).text());
                                });

                                temp +=
                                    '<li class="li-news-tip"><a  class="popupRelate" data-href="' +
                                    href +
                                    '" style="font-size:13px !important;text-decoration: none !important;">' +
                                    '<span class="' +
                                    e.attr("class") +
                                    '">- ' +
                                    tempElement.html().trim() +//arrHd[i].replace(/(<([^>]+)>)/ig, '') +
                                    '</span>' +
                                    (arrHd.length > 1
                                        ? '<br/>'
                                        : '') +
                                    '</a></li>';
                            }
                        } else {
                            var tempElement = $('<div>').html(e.html());
                            tempElement.find('*').not('.tooltipexpired').each(function () {
                                $(this).replaceWith($(this).text());
                            });

                            temp =
                                '<li class="li-news-tip"><a class="popupRelate" data-href="' +
                                href +
                                '" style="font-size:13px !important;text-decoration: none !important;"><span class="' +
                                e.attr("class") +
                                '">- ' +
                                tempElement.html().trim() + //e.html() +
                                '</span></a></li>';
                        }
                    } else if (e.html().length > 0 && typeof title !== 'undefined') {
                        var tempElement = $('<div>').html(title);
                        tempElement.find('*').not('.tooltipexpired').each(function () {
                            $(this).replaceWith($(this).text());
                        });
                        temp = '<li class="li-news-tip"><span "' + (tempElement.attr("class") ? 'class="' + tempElement.attr("class") + '"' : '') + '">- ' +
                            tempElement.html().trim() +
                            '</span></li>';
                    }
                };
                return temp;
            });
        }
        if (typeof content !== 'undefined') {
            var messageNotLoggedin = '</div><div class="form-login-hd fix-font fontbold2">Vui lòng <a href="javascript:void(0)" data-toggle-target="#login-form-target" class="login-action" style="font-size:13px !important;text-decoration: none !important;font-weight:bold;"> đăng nhập</a> tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a> để xem chi tiết.<br/> Nếu chưa có tài khoản Quý khách đăng ký <a href="/user/dang-ky-tai-khoan.html" title="Đăng ký tài khoản" target="_blank" class="cl67942 bold form-login-color" style="font-size:13px !important;text-decoration: none !important;">tại đây</a>!</div>',
                messageNoPerrmission = '</div><div class="form-login-hd fix-font fontbold2"> Để xem chi tiết, vui lòng nâng cấp tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>',
                messageOutOfDate = '', messageNoServices = '';

            if (serviceId == 17 || serviceId == 28 || serviceId == 25) {
                messageOutOfDate =
                    '</div><div class="form-login-hd fix-font fontbold2">Để xem chi tiết, vui lòng nâng cấp tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                permission = false;
            }
            else if (serviceId == 15 || serviceId == 27 || serviceId == 26) {
                messageNoPerrmission = "";
            }
            if (endTime.length > 0) {
                if (serviceId == 15 || serviceId == 27 || serviceId == 26) {
                    messageOutOfDate = '</div><div class="form-login-hd">Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' + endTime + '.<br/> Vui lòng gia hạn gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                } else if (serviceId == 17 || serviceId == 28 || serviceId == 25) {
                    messageOutOfDate = '</div><div class="form-login-hd ">Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' + endTime + '.<br/> Vui lòng nâng cấp gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                }
                else if (serviceId == 23 || serviceId == 24) {
                    messageOutOfDate = '</div><div class="form-login-hd">Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' +
                        endTime +
                        '.<br/> Vui lòng gia hạn gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                } else {
                    messageOutOfDate = '</div><div class="form-login-hd">Tài khoản <span class="form-login-color">' + userName + '</span> đã hết hạn sử dụng vào ngày ' + endTime + '.<br/> Vui lòng nâng cấp gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                }
            }
            const isNotCompanyEmail = email && (
                email.includes("@gmail") ||
                email.includes("@hotmail") ||
                email.includes("@yahoo")
            );
            if (isTrial) {
                isLogin = true;
                permission = true; 
                flag = true;
            }
            if (isLogin && !permission && !isTrial && isNotCompanyEmail) {
                messageNoServices = ` <div class="tip-goidvlvn2">
                        <div class="block"><strong style="color: #000;">Bạn cần nâng cấp để tiếp tục sử dụng tính năng nâng cao này.</strong></div>
                              <div class="goidvlvn2-list active">
                                  <a href="/user/dang-ky-goi-dich-vu.html?serviceId=23&servicePackageId=764&step=2" class="redirect-url" target="_blank">
                                      <div class="goidvlvn2-price">Mua Gói Ngày - 68.000đ</div>
                          
                                      <div class="goidvlvn2-text">Truy cập 24h - không giới hạn các tính năng nâng cao</div>
                                  </a>
                              </div>
                              <div class="goidvlvn2-list">
                                  <a href="/user/dang-ky-goi-dich-vu.html?serviceId=23&servicePackageId=765&step=2" class="redirect-url" target="_blank">
                                      <div class="goidvlvn2-price">Mua Gói Tuần - 99.000đ</div>
                                      <div class="goidvlvn2-text">Truy cập 7 ngày - không giới hạn các tính năng nâng cao</div>
                                  </a>
                              </div>
                              <div class="goidvlvn2-list">
                                  <a href="/user/dang-ky-goi-dich-vu.html?serviceId=23&servicePackageId=114&step=2" class="redirect-url" target="_blank">
                                      <div class="goidvlvn2-price">Mua Gói Tháng - 186.000đ</div>
                                      <div class="goidvlvn2-text">Không giới hạn các tính năng nâng cao trong tháng</div>
                                  </a>
                              </div>
                          </div>`
            }
            if (flag) {
                if (bosung) {
                    dd = me.next('.dropdown-tips-content-2.bosung');
                    if (dd.length === 0) {
                        me.wrap('<div class="dropdown-tips-2"></div>');
                        $('<div class="dropdown-tips-content-2 bosung" style="left:' +
                            me.position().left +
                            'px;top:' +
                            (me.position().top + me.height() + 7) +
                            'px">' +
                            '<div class="tooltip-boxs2 div-relatevb2">' +
                            (permission ? '' : '<div class="fix-hight-tooltip">') +
                            '<ul>' +
                            content.get().join(' ') +
                            '</ul>' +
                            (permission
                                ? ''
                                : (isLogin ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                            ) +
                            messageNoServices +
                            '</div>' +

                            '</div>').insertAfter(me);
                    }
                } else if (dd.length === 0) {
                    if (thamchieu) {
                        var thamchieutext = content.get().join('').length > 0
                            ? content.get().join(' ')
                            : 'Nội dung tham chiếu. Click để xem chi tiết.';
                        me.append('<div class="dropdown-tips-content-2 n1" style="' + (typeof isPrint !== 'undefined' ? '' : 'visibility:visible;') + 'left:' +
                            left +
                            'px;top:' +
                            (e.pageY - 30) +
                            'px">' +


                            '<div class="tooltip-boxs2 div-relatevb2">' +
                            '<ul>' +
                            thamchieutext +
                            '</ul>' +
                            messageNoServices +
                            '</div>' +
                            '</div>');
                    } else {
                        me.append('<div class="dropdown-tips-content-2 n2" style="' + (typeof isPrint !== 'undefined' ? '' : 'visibility:visible;') + 'left:' +
                            left +
                            'px;top:' +
                            (e.pageY - 30) +
                            'px">' +
                            '<div class="tooltip-boxs2 div-relatevb2">' +
                            (permission ? '' : '<div class="fix-hight-tooltip">') +
                            '<ul>' +
                            content.get().join(' ') +
                            '</ul>' +
                            (permission
                                ? ''
                                : (isLogin ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                            ) +
                            messageNoServices +
                            '</div>' +
                            '</div>');

                    }
                }
            } else {
                if (dd.length === 0)
                    me.append('<div class="dropdown-tips-content-2 n3" style="visibility:visible;left:' +
                        left +
                        'px;top:' +
                        (e.pageY + 10) +
                        'px">' +
                        '<div class="tooltip-boxs2 div-relatevb2">' +
                        (permission ? '' : '<div class="fix-hight-tooltip">') +
                        '<p ' +
                        paragraphClass +
                        '>' +
                        title +
                        '</p>' +
                        (permission
                            ? ''
                            : (isLogin ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                        ) +
                        messageNoServices +
                        '</div>' +
                        '</div>');
            }

            if (!bosung) {
                dd.css({ left: left, top: e.pageY - 90, visibility: 'visible' });
            }
        }
    }

    if ($('.ndthaydoi').length) {
        var permission = true;
        var isLogin = true,
            endTime = '', serviceId = 0, userName = '';
        $(function () {
            $('.text-thongbao', $('#hieuluc')).lawsExists(function () {
                if ($(this).hasClass('not-loggedin')) {
                    isLogin = false;
                    permission = false;
                }
                else if ($(this).hasClass('not-have-access'))
                    permission = false;
            });
            $('.user_myluat_acount').find('.font-user').lawsExists(function () {
                if (typeof $(this).data('endtime') != 'undefined' && $(this).data('serviceid') != 'undefined') {
                    endTime = $(this).data('endtime');
                    serviceId = $(this).data('serviceid');
                    userName = $(this).attr('title');
                }
            });
            
            function popupChidanMobi(el, e, login, permission, serviceId, endTime) {
                var me = $(el),
                    dd = me.next('.popup-chidan'),
                    title = typeof me.attr('data-title') === "undefined" ? me.attr('title') : me.attr('data-title'),
                    href = typeof me.attr('data-href') === "undefined" ? me.attr('href') : me.attr('data-href'),
                    content,
                    bosung = me.hasClass('docitem-58'),
                    huongdan = me.hasClass('docitem-45'),
                    thamchieu = title === 'Nội dung tham chiếu' || me.hasClass('docitem-54'),
                    baibocumtu = me.hasClass('text-baibocumtu'),
                    thaythecumtu = me.hasClass('text-thaythecumtu'),
                    bosungcumtu = me.hasClass('text-bosungcumtu'),
                    paragraphClass = '',
                    email = $('.row-user-mail').text(),
                    isRoleFree = $('.isRoleFree').val(),
                    flag = false;
                if (typeof me.attr('title') !== 'undefined') {
                    me.attr('data-title', me.attr('title'));
                    me.removeAttr('title');
                }
                if (typeof serviceId === "undefined") {
                    serviceId = $("#serviceid").text();
                }
                var username = $("#username").text();
                var messageNotLoggedin =
                    '</div><div class="form-login-hd">Vui lòng <a href="javascript:void(0)" class="form-login-color lawsVnLogin" style="font-size:13px !important;text-decoration: none !important;"> đăng nhập</a> tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a> để xem chi tiết.<br> Nếu chưa có tài khoản Quý khách đăng ký <a href="/user/dang-ky-tai-khoan.html" title="Đăng ký tài khoản" target="_blank" class="cl67942 bold form-login-color" style="font-size:13px !important;text-decoration: none !important;">tại đây</a>!</div>',
                    messageNoPerrmission =
                        '</div><div class="form-login-hd">Để xem chi tiết, vui lòng nâng cấp tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>',
                    messageOutOfDate = '', messageNoServices = '';
                if (serviceId == 17 || serviceId == 28 || serviceId == 25) {//25:NVTA
                    messageOutOfDate =
                        '</div><div class="form-login-hd">Để xem chi tiết, vui lòng nâng cấp tài khoản gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                    permission = false;
                }
                if (endTime.length > 0) {
                    if (serviceId == 15 || serviceId == 27 || serviceId == 26) {//26:NVTC
                        messageOutOfDate = '</div><div class="form-login-hd">Tài khoản <span class="form-login-color">' + username + '</span> đã hết hạn sử dụng vào ngày ' + endTime + '. Vui lòng gia hạn gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                    } else if (serviceId == 17 || serviceId == 28 || serviceId == 25) {
                        messageOutOfDate = '</div><div class="form-login-hd">Tài khoản <span class="form-login-color">' + username + '</span> đã hết hạn sử dụng vào ngày ' + endTime + '. Vui lòng nâng cấp gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                    }
                    else if (serviceId == 23 || serviceId == 24) {//24:NVNC
                        messageOutOfDate = '</div><div class="form-login-hd">Tài khoản <span class="form-login-color">' + username + '</span> đã hết hạn sử dụng vào ngày ' +
                            endTime +
                            '. Vui lòng gia hạn gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                    } else {
                        messageOutOfDate = '</div><div class="form-login-hd">Tài khoản <span class="form-login-color">' + username + '</span> đã hết hạn sử dụng vào ngày ' + endTime + '. Vui lòng đăng ký gói <a href="/goi-dich-vu/goi-tra-cuu-tieu-chuan.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Tiêu chuẩn</a> hoặc <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color" style="font-size:13px !important;text-decoration: none !important;"> Nâng cao</a>.</div>';
                    }
                }
                if (email && (email.includes("@gmail") || email.includes("@hotmail") || email.includes("@yahoo")) && isRoleFree == 1) {
                    messageNoServices = ` <div class="tip-goidvlvn2">
                        <div class="block"><strong style="color: #000;">Bạn cần nâng cấp để tiếp tục sử dụng tính năng nâng cao này.</strong></div>
                        <div class="goidvlvn2-list active">
                            <a href="/user/dang-ky-goi-dich-vu.html?serviceId=23&servicePackageId=764&step=2">
                                <div class="goidvlvn2-price">Mua Gói Ngày - 68.000đ</div>
                    
                                <div class="goidvlvn2-text">Truy cập 24h - không giới hạn các tính năng nâng cao</div>
                            </a>
                        </div>
                        <div class="goidvlvn2-list">
                            <a href="/user/dang-ky-goi-dich-vu.html?serviceId=23&servicePackageId=765&step=2">
                                <div class="goidvlvn2-price">Mua Gói Tuần - 99.000đ</div>
                                <div class="goidvlvn2-text">Truy cập 7 ngày - không giới hạn các tính năng nâng cao</div>
                            </a>
                        </div>
                        <div class="goidvlvn2-list">
                            <a href="/user/dang-ky-goi-dich-vu.html?serviceId=23&servicePackageId=114&step=2">
                                <div class="goidvlvn2-price">Mua Gói Tháng - 186.000đ</div>
                                <div class="goidvlvn2-text">Không giới hạn các tính năng nâng cao trong tháng</div>
                            </a>
                        </div>
                    </div>`
                }
                if (baibocumtu) {
                    paragraphClass = 'class="popupRelateDetail text-baibocumtu-tooltip"';
                } else if (thaythecumtu) {
                    paragraphClass = 'class="popupRelateDetail text-thaythecumtu-tooltip"';
                }
                else if (bosungcumtu) {
                    paragraphClass = 'class="popupRelateDetail text-bosungcumtu-tooltip"';
                }
                if (typeof title !== 'undefined') {
                    content = $(title).map(function () {
                        var e = $(this), temp = '';
                        if (e.is('span')) {
                            flag = true;
                            if (e.html().length > 0 && typeof href !== 'undefined') {
                                if (huongdan) {
                                    var arrHd = e.html().split('<br>');
                                    for (var i = 0; i < arrHd.length; i++) {
                                        var tempElement = $('<div>').html(arrHd[i]);
                                        tempElement.find('*').not('.tooltipexpired').each(function () {
                                            $(this).replaceWith($(this).text());
                                        });
                                        temp += '<li class="li-news-tip">' +
                                            '<span data-href="' +
                                            href +
                                            '" class="popupRelateDetailHD ' +
                                            e.attr("class") +
                                            '">- ' +
                                            tempElement.html().trim() + //arrHd[i].replace(/(<([^>]+)>)/ig, '') +
                                            '</span></li>';
                                    }
                                } else {
                                    var tempElement = $('<div>').html(e.html());
                                    tempElement.find('*').not('.tooltipexpired').each(function () {
                                        $(this).replaceWith($(this).text());
                                    });
                                    temp =
                                        '<li class="li-news-tip"><span data-href="' + href + '" class="popupRelateDetail ' +
                                        e.attr("class") +
                                        '">- ' +
                                        tempElement.html().trim() + //e.html() +
                                        '</span></li>';
                                }
                            } else if (e.html().length > 0 && typeof title !== 'undefined') {
                                var tempElement = $('<div>').html(e.html());
                                tempElement.find('*').not('.tooltipexpired').each(function () {
                                    $(this).replaceWith($(this).text());
                                });
                                temp = '<li class="li-news-tip"><span class="popupRelateDetail ' +
                                    e.attr("class") +
                                    '">- ' +
                                    tempElement.html().trim() + //e.html() +
                                    '</span></li>';
                            }
                        };
                        return temp;
                    });
                }
                if (typeof content !== 'undefined' && content !== null) {
                    if (flag) {
                        if (dd.length === 0) {
                            me.after('<div class="popup-bg fix_bgpopup popup-chidan" style="display: block;' + (isNaN(e.pageY) ? '' : 'top:' + (e.pageY) + 'px;') + '">' +
                                '<div class= "popup-wrapper fix_bgpopup">' +
                                '<div class="popup_container fix_bgpopup">' +
                                '<button class="close-popup close-popup-chidan closefix2">' +
                                '<i class="ic icon-e-removelvn ic_close_popup2"></i>' +
                                '</button>' +
                                '<div class="tooltip-boxs">' +
                                (permission ? '' : '<div class="fix-hight-tooltip">') +
                                '<ul>' +
                                content.get().join(' ') +
                                '</ul>' +
                                (permission
                                    ? ''
                                    : (login ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                                ) +
                                (permission && !thamchieu ? '<div class="text-hd">*Chạm vào nội dung bôi màu để xem chi tiết</div>' : '') +
                                messageNoServices +
                                '</div>' +

                                '</div>' +

                                '</div>' +
                                '</div>');
                        }
                    } else {
                        if (dd.length === 0)
                            me.after('<div class="tooltip-chidan popup-bg fix_bgpopup popup-chidan" style="display: block;' + (isNaN(e.pageY) ? '' : 'top:' + (e.pageY) + 'px;') + '">' +
                                '<div class= "popup-wrapper fix_bgpopup">' +
                                '<div class="popup_container fix_bgpopup">' +
                                '<button class="close-popup close-popup-chidan closefix2">' +
                                '<i class="ic icon-e-removelvn ic_close_popup2"></i>' +
                                '</button>' +
                                '<div class="tooltip-boxs">' +
                                (permission ? '' : '<div class="fix-hight-tooltip">') +
                                '<p class="popupRelateDetail"' +
                                paragraphClass +
                                ' data-href="' + href + '"><b>' +
                                title +
                                '</b></p>' +
                                (permission
                                    ? ''
                                    : (login ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                                ) +
                                (permission && !thamchieu ? '<div class="text-hd">*Chạm vào nội dung bôi màu để xem chi tiết</div>' : '') +
                                messageNoServices +
                                '</div>' +

                                '</div>' +
                                '</div>' +
                                '</div>');
                    }
                    dd.css({ top: e.pageY - 90 });
                }
            }
            $(document).on('click',
                '.close-popup-chidan',
                function (e) {
                    e.preventDefault();
                    $(this).closest('.popup-chidan').lawsExists(function () {
                        $(this).hide();
                    });
                });
            $(document).on('click',
                '.xem-nd-bi-suadoi-m',
                function (e) {
                    e.preventDefault();
                    var content = '';
                    $('.noidung1col').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    $('.noidung2cols').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                    $('.noidungthaydoi').lawsExists(function () {
                        if ($(this).children().length > 0) {
                            content = $(this).html();
                            $('.nd-suadoi').find('.noidung_100').lawsExists(function () {
                                $(this).html(content);
                                $(this).removeClass('hidden');
                            });
                        }
                    });
                    $('body').addClass('fixedPos');
                });
            $(document).on('click',
                '.title-chidan-2',
                function (e) {
                    e.preventDefault();
                    var me = $(this),
                        parent = me.closest('.box1-popup'),
                        content = parent.find('.content-drop-cd'),
                        icon = parent.find('.downlvn-ic3'),
                        title = icon.attr('title') == 'Thu gọn' ? 'Mở rộng' : 'Thu gọn';
                    content.toggleClass('hidden');
                    $('#chidan-col2').lawsExists(function () {
                        $(this).toggleClass('hidden');
                    });
                    icon.lawsExists(function () {
                        $(this).attr('title', title);
                        if ($(this).hasClass('opendownlvn')) {
                            $(this).removeClass('opendownlvn').addClass('openuplvn');
                        } else if ($(this).hasClass('openuplvn')) {
                            $(this).removeClass('openuplvn').addClass('opendownlvn');
                        } else $(this).addClass('opendownlvn');
                    });
                });
            $(document).on('click',
                '.close-chidan-tools',
                function (e) {
                    e.preventDefault();
                    $('#chuthichthaydoinoidung').lawsExists(function () {
                        $(this).removeClass('target-expanded').addClass('target-hidden');
                        $('body').removeClass('fixedPos');
                    });
                });
            $(document).on('click',
                '.dong-nd-bi-suadoi',
                function (e) {
                    e.preventDefault();
                    var content = '', el = $('.noidung1col').find('.noidungthaydoi');
                    if (el.children().length === 0) {
                        $('.nd-suadoi').find('.noidung_100.fix-top0').lawsExists(function () {
                            content = $(this).html();
                            el.html(content);
                        });
                    }

                    $('.noidung1col').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                    $('.noidung2cols').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                });
            $(document).on('click',
                '.dong-nd-duoc-huongdan',
                function (e) {
                    e.preventDefault();
                    $('.noidung2cols').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    $('.tonghop-content').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    $('.noidung1col').find('.col-1').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                    $('.noidung1col').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                });
            $(document).on('click',
                '.xem-nd-bi-suadoi',
                function (e) {
                    e.preventDefault();
                    var content = '';
                    $('.noidung1col').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    $('.noidung2cols').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                    $('.noidungthaydoi').lawsExists(function () {
                        if ($(this).children().length > 0) {
                            content = $(this).html();
                            $('.nd-suadoi').find('.noidung_100').lawsExists(function () {
                                $(this).html(content);
                                $(this).removeClass('hidden');
                            });
                        }
                    });
                    $('body').addClass('fixedPos');
                });

            $(document).on('click',
                '.noi-dung-tham-chieu',
                function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log(212122, isNewVersion )
                    if (e.target !== e.currentTarget) {
                        if (e.target.hasClass('form-login-color')) {
                            if (typeof $(e.target).attr('href') != 'undefined')
                                window.open($(e.target).attr('href'));
                            return false;
                        }
                    };

                    if (isLogin && !permission) {
                        return false;
                    }

                    var me = $(this),
                        href = me.attr('data-url'),
                        dataHref = me.attr('data-href'),
                        title = me.attr('title'),
                        dataTitle = me.attr('data-title'),
                        popupHtml = '',
                        dataUrl = me.attr('data-url'),
                        valid = me.closest('.nd-suadoi').length == 0,
                        url = (typeof href !== 'undefined' && href) ? href : (typeof dataHref !== 'undefined' && dataHref ? dataHref : ''),
                        _title = (typeof title !== 'undefined' && title) ? title : (typeof dataTitle !== 'undefined' && dataTitle ? dataTitle : ''),
                        popup = me.next('.popup-bg'), docLink = url.indexOf('/v1/api/docs/reference-content') != -1;

                    if (url.length > 0 && valid) {
                        if (isNewVersion == "true") {
                            url = url.replace('/v1/api/docs/reference-content','/van-ban/get/noi-dung-tham-chieu.html')
                        }
                        console.log(url)
                        if (me.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        me.attr('requestRunning', true);
                        $.ajax({
                            type: 'get',
                             url: lawsVn.virtualPath(url),
                            //url: url,
                            dataType: 'html',
                            async: true,
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    popupHtml = data;
                                    var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
                                    activeDialogs.dialog('close');
                                    $('<div id="popupRelate"></div>').lawsDialog({
                                        isHtmlTitle: true,
                                        title: docLink ? '<div class="title_sosanh2">Nội dung tham chiếu</div>' : (_title == 'Nội dung tham chiếu' || _title == 'Nội dung được hướng dẫn') ? '<div class="title_sosanh2">* Nội dung tham chiếu</div>' : '<div class="box1-popup-title">' +
                                            '<div class="title-chidan-1"> Danh mục chỉ dẫn</div>' +
                                            '<div class="title-chidan-2">Nội dung chỉ dẫn</div>' +
                                            '</div>',
                                        width: 800,
                                        minHeight: 550,
                                        position: { my: 'top', at: 'top+20' },
                                        //position: { my: "center", at: "center+10", of: window.top },
                                        hideClose: false,
                                        buttons: {},
                                        onOpen: function () {
                                            $('#popupRelate').html(popupHtml);
                                            $('#loading').fadeOut('normal');
                                        }
                                    });
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status !== 403) {
                                    if (jqXhr.status === 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                            showIcon: false
                                        });
                                    } else if (jqXhr.status === 404) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                            showIcon: false
                                        });
                                    } else {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Quý khách vui lòng thử lại sau.'],
                                            showIcon: false
                                        });
                                    }
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            me.removeAttr('requestRunning');
                        });
                    }
                    //var tabId = $(this).parents('.tab-item-content').attr('id').replace('chidanthaydoi', 'noidung');
                    //lawsVn.logs.webpagelogs("OpenPopupRelate", pageUrl, "ChiDanThayDoi - Tab " + tabId, source, "Chỉ dẫn thay đổi");

                });

            $(document).on('click',
                '.popupRelate, .popupRelateCutom',
                function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    var parentRefer = e.target.closest('.block-refer-content');
                    if (parentRefer != null && !e.target.hasClass('text-link')) {
                        return false;
                    }

                    if (e.target !== e.currentTarget) {
                        if (e.target.hasClass('form-login-color')) {
                            if (typeof $(e.target).attr('href') != 'undefined')
                                window.open($(e.target).attr('href'));
                            return false;
                        }
                    };

                    //if (isLogin && !permission) {
                    //    return false;
                    //}

                    var me = $(this),
                        href = me.attr('href'),
                        dataHref = me.attr('data-href'),
                        title = me.attr('title'),
                        dataTitle = me.attr('data-title'),
                        popupHtml = '',
                        popupWidth = me.hasClass('popupRelate') ? 1200 : 800,
                        dataUrl = me.attr('data-url'),
                        valid = me.closest('.nd-suadoi').length == 0,
                        url = (typeof href !== 'undefined' && href) ? href : (typeof dataHref !== 'undefined' && dataHref ? dataHref : ''),
                        _title = (typeof title !== 'undefined' && title) ? title : (typeof dataTitle !== 'undefined' && dataTitle ? dataTitle : ''),
                        popup = me.next('.popup-bg');
                    if (url.indexOf('noi-dung-tham-chieu.html') != -1) {
                        popupWidth = 800;
                    }
                    if (url.length > 0 && valid) {
                        if (lawsVn.isMobile()) {
                            $('.popup-chidan').hide();
                            if (popup.length > 0) {
                                popup.show();
                            } else {
                                if (me.attr('requestRunning')) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                                    });
                                    return false;
                                }
                                me.attr('requestRunning', true);
                                $.ajax({
                                    type: 'get',
                                    async: true,
                                    url: lawsVn.virtualPath('/Ajax/DocItemViewChangeContentCheck'),
                                    beforeSend: function () {
                                        $('#loading').fadeIn('normal');
                                    },
                                    success: function (data, status, xhr) {
                                        if (xhr.status !== 403) {
                                            popupChidanMobi(me, e, true, true, data.ServiceId, '', data.userName);
                                        }
                                    },
                                    error: function (jqXhr, errorMessage) {
                                        if (jqXhr.status !== 403) {
                                            if (jqXhr.status === 0) {
                                                $().lawsDialog({
                                                    dialogClass: 'lawsVnDialogTitle',
                                                    messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                                    showIcon: false
                                                });
                                            } else if (jqXhr.status === 404) {
                                                $().lawsDialog({
                                                    dialogClass: 'lawsVnDialogTitle',
                                                    messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                                    showIcon: false
                                                });
                                            } else {
                                                $().lawsDialog({
                                                    dialogClass: 'lawsVnDialogTitle',
                                                    messages: ['Quý khách vui lòng thử lại sau.'],
                                                    showIcon: false
                                                });
                                            }
                                        } else {
                                            var resp = JSON.parse(jqXhr.responseText), isLogin = true, serviceId = 0, endTime = '', userName = '';
                                            if (resp.Message == 'ChiDanThayDoiNotLoggedin') {
                                                isLogin = false;
                                            }
                                            if (resp.ServiceId !== null && resp.ServiceId > 0) {
                                                serviceId = resp.ServiceId;
                                            } if (resp.EndTime !== null && resp.EndTime.length > 0) {
                                                endTime = resp.EndTime;
                                            }
                                            if (resp.userName) {
                                                userName = resp.userName;
                                            }
                                            popupChidanMobi(me, e, isLogin, false, serviceId, endTime, userName);
                                        }
                                    }
                                }).always(function () {
                                    $('#loading').fadeOut('normal');
                                    me.removeAttr('requestRunning');
                                });
                            }
                        } else {
                            if (isNewVersion == "true") {
                                url = url.replace('/noi-dung-thay-doi.html', '/van-ban/get/docitem-view-change-content')
                            }
                            console.log(url, isNewVersion)
                            if (me.attr('requestRunning')) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                                });
                                return false;
                            }
                            me.attr('requestRunning', true);
                            $.ajax({
                                type: 'get',
                                url: lawsVn.virtualPath(url),
                                //url: url,
                                dataType: 'html',
                                async: true,
                                beforeSend: function () {
                                    $('#loading').fadeIn('normal');
                                },
                                success: function (data, status, xhr) {
                                    if (xhr.status !== 403) {
                                        popupHtml = data;
                                        var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
                                        activeDialogs.dialog('close');
                                        $('<div id="popupRelate"></div>').lawsDialog({
                                            isHtmlTitle: true,
                                            title: (_title == 'Nội dung tham chiếu' || _title == 'Nội dung được hướng dẫn') ? '<div class="title_sosanh2">* Nội dung tham chiếu</div>' : '<div class="box1-popup-title">' +
                                                '<div class="title-chidan-1"> Danh mục chỉ dẫn</div>' +
                                                '<div class="title-chidan-2">Nội dung chỉ dẫn</div>' +
                                                '</div>',
                                            width: popupWidth,
                                            minHeight: 550,
                                            position: { my: 'top', at: 'top+20' },
                                            //position: { my: "center", at: "center+10", of: window.top },
                                            hideClose: false,
                                            buttons: {},
                                            onOpen: function () {
                                                $('#popupRelate').html(popupHtml);
                                                $('#loading').fadeOut('normal');
                                            }
                                        });
                                    }
                                },
                                error: function (jqXhr, errorMessage) {
                                    if (jqXhr.status !== 403) {
                                        if (jqXhr.status === 0) {
                                            $().lawsDialog({
                                                dialogClass: 'lawsVnDialogTitle',
                                                messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                                showIcon: false
                                            });
                                        } else if (jqXhr.status === 404) {
                                            $().lawsDialog({
                                                dialogClass: 'lawsVnDialogTitle',
                                                messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                                showIcon: false
                                            });
                                        } else {
                                            $().lawsDialog({
                                                dialogClass: 'lawsVnDialogTitle',
                                                messages: ['Quý khách vui lòng thử lại sau.'],
                                                showIcon: false
                                            });
                                        }
                                    }
                                }
                            }).always(function () {
                                $('#loading').fadeOut('normal');
                                me.removeAttr('requestRunning');
                            });

                        }
                    }
                    var tabId = $(this).parents('.tab-item-content').attr('id').replace('chidanthaydoi', 'noidung');
                    lawsVn.logs.webpagelogs("OpenPopupRelate", pageUrl, "ChiDanThayDoi - Tab " + tabId, source, "Chỉ dẫn thay đổi");

                });
            $(document).on('click',
                '.popupRelateDetail',
                function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    var me = $(this),
                        href = me.attr('href'),
                        dataHref = me.attr('data-href'),
                        title = me.attr('title'),
                        dataTitle = me.attr('data-title'),
                        valid = me.closest('.nd-suadoi').length === 0,
                        url = (typeof href !== 'undefined' && href) ? href : (typeof dataHref !== 'undefined' && dataHref ? dataHref : ''),
                        _title = (typeof title !== 'undefined' && title) ? title : (typeof dataTitle !== 'undefined' && dataTitle ? dataTitle : '');
                    $('body').addClass('fixedPos');
                    if (url.length > 0 && valid) {
                        if (me.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        me.attr('requestRunning', true);
                        $.ajax({
                            type: 'get',
                            async: true,
                            url: lawsVn.virtualPath(url),
                            dataType: 'html',
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    if (data !== null && data.length > 0) {
                                        if ($('#popup-chidan').length === 0) {
                                            var html = $('<div class="popup-bg target-hidden"><div class="popup-wrapper full"><div class="popup_container full">' + data + '</div></div></div>').attr('id', 'popup-chidan');
                                            html.appendTo('body');
                                        }
                                        else {
                                            $('#popup-chidan-content').html(data);
                                        }
                                        $('#popup-chidan').removeClass('target-hidden').addClass('target-expanded');
                                    }
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status !== 403) {
                                    if (jqXhr.status === 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                            showIcon: false
                                        });
                                    } else if (jqXhr.status === 404) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                            showIcon: false
                                        });
                                    } else {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Quý khách vui lòng thử lại sau.'],
                                            showIcon: false
                                        });
                                    }
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            me.removeAttr('requestRunning');
                        });
                    }
                    var tabId = $(this).parents('.tab-item-content').attr('id').replace('chidanthaydoi', 'noidung');
                    lawsVn.logs.webpagelogs("OpenPopupRelate", pageUrl, "ChiDanThayDoi - Tab " + tabId, source, "Mobile - chỉ dẫn thay đổi");
                });
            $(document).on('click',
                '.popupRelateDetailHD',
                function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    var me = $(this),
                        href = me.attr('href'),
                        dataHref = me.attr('data-href'),
                        title = me.attr('title'),
                        dataTitle = me.attr('data-title'),
                        valid = me.closest('.nd-suadoi').length === 0,
                        url = (typeof href !== 'undefined' && href) ? href : (typeof dataHref !== 'undefined' && dataHref ? dataHref : ''),
                        _title = (typeof title !== 'undefined' && title) ? title : (typeof dataTitle !== 'undefined' && dataTitle ? dataTitle : '');
                    if (isNewVersion == "true") {
                        url = url.replace('/noi-dung-thay-doi.html', '/van-ban/get/noi-dung-huong-dan')
                    }
                    console.log(url, isNewVersion)
                    $('body').addClass('fixedPos');
                    if (url.length > 0 && valid) {
                        if (me.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        me.attr('requestRunning', true);
                        $.ajax({
                            type: 'get',
                            async: true,
                            url: lawsVn.virtualPath(url.replace('/noi-dung-thay-doi.html', '/noi-dung-huong-dan.html')),
                            //url: url,
                            dataType: 'html',
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    if (data !== null && data.length > 0) {
                                        if ($('#popup-chidan').length === 0) {
                                            var html = $('<div class="popup-bg target-hidden"><div class="popup-wrapper full"><div class="popup_container full">' + data + '</div></div></div>').attr('id', 'popup-chidan');
                                            html.appendTo('body');
                                        }
                                        else {
                                            $('#popup-chidan-content').html(data);
                                        }
                                        $('#popup-chidan').removeClass('target-hidden').addClass('target-expanded');
                                    }
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status !== 403) {
                                    if (jqXhr.status === 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                            showIcon: false
                                        });
                                    } else if (jqXhr.status === 404) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                            showIcon: false
                                        });
                                    } else {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Quý khách vui lòng thử lại sau.'],
                                            showIcon: false
                                        });
                                    }
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            me.removeAttr('requestRunning');
                        });
                    }
                    var tabId = $(this).parents('.tab-item-content').attr('id').replace('chidanthaydoi', 'noidung');
                    lawsVn.logs.webpagelogs("OpenPopupRelate", pageUrl, "ChiDanHuongDan - Tab " + tabId, source, "Mobile - chỉ dẫn hướng dẫn");
                });
            $(document).on('click',
                '.popupRelate2',
                function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    if (lawsVn.isMobile()) {
                        var me = $(this);
                        if ($(e.target).hasClass('ic_close_popup2')) {
                            return;
                        }
                        if (e.target !== this) {
                            if (!me.hasClass('popupRelate'))
                                me = $(this).closest(opts.popupRelate);
                        }
                        var href = me.attr('href'),
                            dataHref = me.attr('data-href'),
                            title = me.attr('title'),
                            dataTitle = me.attr('data-title'),
                            content,
                            url = (typeof href !== 'undefined' && href) ? href : (typeof dataHref !== 'undefined' && dataHref ? dataHref : ''),
                            _title = (typeof title !== 'undefined' && title) ? title : (typeof dataTitle !== 'undefined' && dataTitle ? dataTitle : ''),
                            popup = me.next('.popup-bg');
                        $('#popup-chidan').lawsExists(function () {
                            $('.popup-chidan').hide();
                            if (url.length > 0) {
                                if (popup.length > 0) {
                                    popup.show();
                                } else {
                                    if (me.attr('requestRunning')) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                                        });
                                        return false;
                                    }
                                    me.attr('requestRunning', true);
                                    $.ajax({
                                        type: 'get',
                                        async: true,
                                        url: lawsVn.virtualPath('/Ajax/DocItemViewChangeContentCheck'),
                                        beforeSend: function () {
                                            $('#loading').fadeIn('normal');
                                        },
                                        success: function (data, status, xhr) {
                                            if (xhr.status !== 403) {
                                                popupChidanMobi(me, e, true, true, data.ServiceId, '', data.userName);
                                            }
                                        },
                                        error: function (jqXhr, errorMessage) {
                                            if (jqXhr.status !== 403) {
                                                if (jqXhr.status === 0) {
                                                    $().lawsDialog({
                                                        dialogClass: 'lawsVnDialogTitle',
                                                        messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                                        showIcon: false
                                                    });
                                                } else if (jqXhr.status === 404) {
                                                    $().lawsDialog({
                                                        dialogClass: 'lawsVnDialogTitle',
                                                        messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                                        showIcon: false
                                                    });
                                                } else {
                                                    $().lawsDialog({
                                                        dialogClass: 'lawsVnDialogTitle',
                                                        messages: ['Quý khách vui lòng thử lại sau.'],
                                                        showIcon: false
                                                    });
                                                }
                                            } else {
                                                var resp = JSON.parse(jqXhr.responseText), isLogin = true, serviceId = 0, endTime = '', userName = '';
                                                if (resp.Message == 'ChiDanThayDoiNotLoggedin') {
                                                    isLogin = false;
                                                }
                                                if (resp.ServiceId !== null && resp.ServiceId > 0) {
                                                    serviceId = resp.ServiceId;
                                                } if (resp.EndTime !== null && resp.EndTime.length > 0) {
                                                    endTime = resp.EndTime;
                                                }
                                                if (resp.userName) {
                                                    userName = resp.userName;
                                                }
                                                popupChidanMobi(me, e, isLogin, false, serviceId, endTime, userName);
                                            }
                                        }
                                    }).always(function () {
                                        $('#loading').fadeOut('normal');
                                        me.removeAttr('requestRunning');
                                    });
                                }
                            }
                        });
                    } else {
                        if (e.target !== e.currentTarget) {
                            if (e.target.hasClass('form-login-color')) {
                                if (typeof $(e.target).attr('href') != 'undefined')
                                    window.open($(e.target).attr('href'));
                            }
                        };
                        var me = $(this),
                            href = me.attr('href'),
                            dataHref = me.attr('data-href'),
                            dataUrl = me.attr('data-url'),
                            popupHtml = '',
                            valid = me.closest('.nd-suadoi').length == 0,
                            url = (typeof href !== 'undefined' && href) ? href : (typeof dataHref !== 'undefined' && dataHref ? dataHref : '');

                        if (url.length > 0 && valid) {
                            if (me.attr('requestRunning')) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Yêu cầu đang được xử lý. Quý khách vui lòng đợi...']
                                });
                                return false;
                            }
                            me.attr('requestRunning', true);
                            if (isNewVersion == "true") {
                                url = url.replace('/noi-dung-thay-doi.html', '/van-ban/get/noi-dung-huong-dan')
                            }
                            console.log(url, isNewVersion)
                            $.ajax({
                                type: 'get',
                                url: lawsVn.virtualPath(url.replace('noi-dung-thay-doi.html', 'noi-dung-huong-dan.html')),
                                //url: url,
                                dataType: 'html',
                                async: true,
                                beforeSend: function () {
                                    $('#loading').fadeIn('normal');
                                },
                                success: function (data, status, xhr) {
                                    if (xhr.status !== 403 && isNewVersion == "true") {
                                        console.log(123)
                                        $('body').append(`<div id="_chidanthaydoi" class="popup-bg target-hidden target-expanded">${data}</div>`);
                                        //$('<div id="_chidanthaydoi"></div>').lawsDialog()
                                    }

                                    else if (xhr.status !== 403) {
                                        popupHtml = data;
                                        var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
                                        activeDialogs.dialog('close');
                                        $('<div id="popupRelate"></div>').lawsDialog({
                                            isHtmlTitle: true,
                                            title: '<div class="box1-popup-title">' +
                                                '<div class="title-chidan-1"> Danh mục chỉ dẫn</div>' +
                                                '<div class="title-chidan-2">Nội dung chỉ dẫn</div>' +
                                                '</div>',
                                            width: 1200,
                                            minHeight: 550,
                                            position: { my: 'top', at: 'top+20' },
                                            hideClose: false,
                                            buttons: {},
                                            onOpen: function () {
                                                $('#popupRelate').html(popupHtml);
                                                $('#loading').fadeOut('normal');
                                            }
                                        });
                                    }
                                },
                                error: function (jqXhr, errorMessage) {
                                    if (jqXhr.status !== 403) {
                                        if (jqXhr.status === 0) {
                                            $().lawsDialog({
                                                dialogClass: 'lawsVnDialogTitle',
                                                messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                                showIcon: false
                                            });
                                        } else if (jqXhr.status === 404) {
                                            $().lawsDialog({
                                                dialogClass: 'lawsVnDialogTitle',
                                                messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                                showIcon: false
                                            });
                                        } else {
                                            $().lawsDialog({
                                                dialogClass: 'lawsVnDialogTitle',
                                                messages: ['Quý khách vui lòng thử lại sau.'],
                                                showIcon: false
                                            });
                                        }
                                    }
                                }
                            }).always(function () {
                                $('#loading').fadeOut('normal');
                                me.removeAttr('requestRunning');
                            });
                        }
                        var tabId = $(this).parents('.tab-item-content').attr('id').replace('chidanthaydoi', 'noidung');
                        lawsVn.logs.webpagelogs("OpenPopupRelate", pageUrl, "ChiDanHuongDan - Tab " + tabId, source, "Chỉ dẫn hướng dẫn");
                    }
                });
            $(document).on('click',
                '.getContentReference-',
                function (e) {
                    e.preventDefault();
                    var self = $(this),
                        docItemId = self.data('id'),
                        docItemReferenceId = self.data('referenceid');
                    $('.post-conten-2 .getContentReference').removeClass('DocItemActive');
                    self.addClass('DocItemActive');
                    if (self.attr('requestRunning')) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                        });
                        return false;
                    }
                    self.attr('requestRunning', true);
                    $.lawsAjax({
                        url: lawsVn.virtualPath('/Ajax/DocItems_GetContentReference'),
                        async: true,
                        data: { docItemId: docItemId, docItemReferenceId: docItemReferenceId },
                        dataType: 'html',
                        success: function (resp) {
                            if (resp.length) {
                                $('#popupRelateResult').html(resp);
                                self.removeAttr('requestRunning');
                            }
                        },
                        error: function (resp) {
                            console.log('articleLogs Error: ' + resp.Message);
                        }
                    });
                });
            $(document).on('click',
                '.xem-nd-duoc-hd-m',
                function (e) {
                    e.preventDefault();
                    var content = '', el = $($('.scrollmenu-link3', $('.scrollmenu3'))[0]);
                    $('.noidung1col').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    $('.noidung2cols').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                    $('.noidungthaydoi').lawsExists(function () {
                        if ($(this).children().length > 0) {
                            content = $(this).html();
                            $('.nd-suadoi').find('.noidung_100').lawsExists(function () {
                                $(this).html(content);
                                $(this).removeClass('hidden');
                            });
                        }
                    });
                    el.lawsExists(function () {
                        $(this).addClass('active');
                        $(this).siblings().removeClass('active');
                    });
                    $('body').addClass('fixedPos');
                });
            $(document).on('click',
                '.GetContentReference',
                function (e) {
                    e.preventDefault();
                    var self = $(this),
                        docItemId = self.data('id'),
                        docItemReferenceId = self.data('referenceid'),
                        relateTypeId = self.data('type'),
                        box = lawsVn.isMobile() ? self.closest('.box1-popup') : self.closest('.box1-popup-content'),
                        parent = self.closest('div[class^=li_list]');
                    if (!parent.hasClass('loaded')) {
                        $('div[class^=li_list]', box).removeClass('active loaded');
                        parent.addClass('active loaded');
                        if (self.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        self.attr('requestRunning', true);
                        $.ajax({
                            type: 'get',
                            async: true,
                            url: lawsVn.virtualPath('/Ajax/DocItems_GetContentReference'),
                            dataType: 'html',
                            data: {
                                docItemId: docItemId,
                                docItemReferenceId: docItemReferenceId,
                                relateTypeId: relateTypeId
                            },
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    if (data.length) {
                                        if (lawsVn.isMobile()) {
                                            $('#chidan-col2').html(data);
                                            $('.title-chidan-2').trigger('click');
                                        } else {
                                            $('#popupRelateResult').html(data);
                                        }
                                    }
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status === 0) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                        showIcon: false
                                    });
                                } else if (jqXhr.status === 404) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                        showIcon: false
                                    });
                                } else {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau.'],
                                        showIcon: false
                                    });
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            self.removeAttr('requestRunning');
                        });
                    } else {
                        $('div[class^=li_list]', box).removeClass('active loaded');
                        parent.addClass('active loaded');
                        $('.title-chidan-2').trigger('click');
                    }
                });
            $(document).on('click',
                '.GetContentReferenceGuide',
                function (e) {
                    e.preventDefault();
                    var self = $(this),
                        docItemId = self.data('id'),
                        docItemRelateId = self.data('docitemrelateid'),
                        docItemReferenceId = self.data('referenceid'),
                        box = lawsVn.isMobile() ? self.closest('.box1-popup') : self.closest('.box1-popup-content'),
                        parent = self.closest('div[class^=li_list]');
                    if (!parent.hasClass('loaded')) {
                        $('div[class^=li_list]', box).removeClass('active loaded');
                        parent.addClass('active loaded');
                        if (self.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        self.attr('requestRunning', true);
                        $.ajax({
                            type: 'get',
                            async: true,
                            url: lawsVn.virtualPath('/Ajax/DocItems_GetContentReferenceGuide'),
                            dataType: 'html',
                            data: {
                                docItemId: docItemId,
                                docItemRelateId: docItemRelateId,
                                docItemReferenceId: docItemReferenceId
                            },
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    if (data.length) {
                                        if (lawsVn.isMobile()) {
                                            $('#chidan-col2').html(data);
                                            $('.title-chidan-2').trigger('click');
                                        } else {
                                            $('#popupRelateResult').html(data);
                                        }
                                    }
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status === 0) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                        showIcon: false
                                    });
                                } else if (jqXhr.status === 404) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                        showIcon: false
                                    });
                                } else {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau.'],
                                        showIcon: false
                                    });
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            self.removeAttr('requestRunning');
                        });
                    } else {
                        $('div[class^=li_list]', box).removeClass('active loaded');
                        parent.addClass('active loaded');
                        $('.title-chidan-2').trigger('click');
                    }
                });
            $(document).on('click',
                '.GetUnionByDocItemId',
                function (e) {
                    e.preventDefault();
                    var self = $(this),
                        docItemId = self.data('id'),
                        docItemRelateId = self.data('docitemrelateid'),
                        el = $('.tonghop-content');
                    $('.link_tab1', $('.nd-suadoi')).removeClass('active');
                    self.addClass('active');
                    if (typeof docItemId !== 'undefined' && typeof docItemRelateId !== 'undefined' && el.length && el.children().length == 0) {
                        if (self.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        self.attr('requestRunning', true);
                        $.ajax({
                            type: 'get',
                            async: true,
                            url: lawsVn.virtualPath('/Ajax/DocItems_GetUnionByDocItemId'),
                            dataType: 'html',
                            data: {
                                docItemId: docItemId,
                                docItemRelateId: docItemRelateId
                            },
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    if (data.length) {
                                        $('.thaydoi-content').lawsExists(function () {
                                            $(this).addClass('hidden');
                                        });
                                        el.removeClass('hidden').html(data);
                                    }
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status === 0) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                        showIcon: false
                                    });
                                } else if (jqXhr.status === 404) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                        showIcon: false
                                    });
                                } else {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau.'],
                                        showIcon: false
                                    });
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            self.removeAttr('requestRunning');
                        });
                    }
                    if (el.children().length > 0) {
                        $('.thaydoi-content').lawsExists(function () {
                            $(this).addClass('hidden');
                        });
                        el.removeClass('hidden');
                    }
                });
            $(document).on('click',
                '.TabGetContentReference',
                function (e) {
                    e.preventDefault();
                    var self = $(this),
                        el = $('.thaydoi-content');
                    $('.link_tab1', $('.nd-suadoi')).removeClass('active');
                    self.addClass('active');
                    $('.tonghop-content').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    el.removeClass('hidden');
                });

            $(document).on('click',
                '.TabGetContentReference-m',
                function (e) {
                    e.preventDefault();
                    var self = $(this);
                    $('.scrollmenu-link3', $('#chidan-col2')).removeClass('active');
                    self.addClass('active');
                    $('.noidung2cols').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    $('.tonghop-content').lawsExists(function () {
                        $(this).addClass('hidden');
                    });
                    $('.noidung1col').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                    $('.noidung1col').find('.col-1').lawsExists(function () {
                        $(this).removeClass('hidden');
                    });
                });
            $(document).on('click',
                '.GetUnionByDocItemId-m',
                function (e) {
                    e.preventDefault();
                    var self = $(this),
                        docItemId = self.data('id'),
                        docItemRelateId = self.data('docitemrelateid'),
                        el = $('.tonghop-content');
                    $('.scrollmenu-link3', $('#chidan-col2')).removeClass('active');
                    self.addClass('active');
                    if (typeof docItemId !== 'undefined' && typeof docItemRelateId !== 'undefined' && el.length && el.children().length === 0) {
                        if (self.attr('requestRunning')) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Yêu cầu đang được xử lý. Xin quý khách vui lòng đợi...']
                            });
                            return false;
                        }
                        self.attr('requestRunning', true);
                        $.ajax({
                            type: 'get',
                            async: true,
                            url: lawsVn.virtualPath('/Ajax/DocItems_GetUnionByDocItemId'),
                            dataType: 'html',
                            data: {
                                docItemId: docItemId,
                                docItemRelateId: docItemRelateId
                            },
                            beforeSend: function () {
                                $('#loading').fadeIn('normal');
                            },
                            success: function (data, status, xhr) {
                                if (xhr.status !== 403) {
                                    if (data.length) {
                                        $('.noidung2cols').lawsExists(function () {
                                            $(this).addClass('hidden');
                                        });
                                        $('.noidung1col').lawsExists(function () {
                                            $(this).removeClass('hidden');
                                            $(this).find('.col-1').lawsExists(function () {
                                                $(this).addClass('hidden');
                                            });
                                            $(this).find('.tonghop-content').lawsExists(function () {
                                                $(this).removeClass('hidden');
                                            });
                                        });
                                        el.removeClass('hidden').html(data);
                                    }
                                }
                            },
                            error: function (jqXhr, errorMessage) {
                                if (jqXhr.status === 0) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không có kết nối mạng. Vui lòng kiểm tra lại.'],
                                        showIcon: false
                                    });
                                } else if (jqXhr.status === 404) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Không tìm thấy trang yêu cầu. [404]'],
                                        showIcon: false
                                    });
                                } else {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: ['Quý khách vui lòng thử lại sau.'],
                                        showIcon: false
                                    });
                                }
                            }
                        }).always(function () {
                            $('#loading').fadeOut('normal');
                            self.removeAttr('requestRunning');
                        });
                    }
                    if (el.children().length > 0) {
                        $('.noidung1col').lawsExists(function () {
                            $(this).removeClass('hidden');
                        });
                        $('.noidung1col').find('.col-1').lawsExists(function () {
                            $(this).addClass('hidden');
                        });
                        $('.noidung2cols').lawsExists(function () {
                            $(this).addClass('hidden');
                        });
                        el.removeClass('hidden');
                    }
                });

            $(document).on('change', '#doc-view-mode', function (e) {
                const self = $(this), parent = $('#chidanthaydoind')

                $('.docitem-gccn').addClass('target-hidden')

                $('#lvn-tooltip').lawsExists(function () {
                    $(this).show();
                });
                $('.dropdown-tips-content-2', parent).lawsExists(function () {
                    $('.dropdown-tips-content-2', parent).removeClass('fixedd');
                    $('.dropdown-tips-content-2', parent).not('.bosung').css('visibility', 'hidden');
                });

                $('#chidanthaydoind > div').not('.docitem-gccn-head').removeClass('target-hidden')
                $('#chidanthaydoind').find('.show-personal-notes-terms-only').remove();
                if (self.val() == 1) {
                    $('#lvn-tooltip').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.popupRelate, .popupRelate2', parent).each(function (i, element) {
                        popupChiDan(element, e);
                    });
                    $('.dropdown-tips-content-2', parent).lawsExists(function () {
                        $('.dropdown-tips-content-2', parent).addClass('fixedd');
                        $('.dropdown-tips-content-2', parent).not('.bosung').css('visibility', 'visible');
                    });
                }
                else if (self.val() == 2) {
                    $('.docitem-gccn').removeClass('target-hidden')
                } else if (self.val() == 3) {
                    let counter3 = 0;
                    $('#chidanthaydoind > div').each((index, item) => {
                        if ($(item).find('.tooltip-button.note').length > 0) {
                            $(item).removeClass('target-hidden');
                            counter3++;
                        } else {
                            $(item).addClass('target-hidden');
                        }
                    })
                    $('.docitem-gccn').removeClass('target-hidden')
                    if (counter3 == 0) {
                        $('#chidanthaydoind').append('<div class="show-personal-notes-terms-only">Không tìm thấy điều khoản có ghi chú cá nhân.</div>')
                    }
                } else if (self.val() == 4) {
                    let counter = 0;
                    $('#chidanthaydoind > div').each((index, item) => {
                        if ($(item).find('.docitem-47').length > 0 || $(item).find('.docitem-57').length > 0 || $(item).find('.docitem-58').length > 0 ||
                            $(item).find('.docitem-61').length > 0 || $(item).find('.docitem-49').length > 0 || $(item).find('.docitem-53').length > 0 || $(item).find('.docitem-62').length > 0 || $(item).find('.docitem-46').length > 0) {
                            $(item).removeClass('target-hidden');
                            counter++;
                        } else {
                            $(item).addClass('target-hidden');
                        }
                    })
                    if (counter == 0) {
                        $('#chidanthaydoind').append('<div class="show-personal-notes-terms-only">Không tìm thấy điều khoản sửa đổi, bổ sung, đính chính.</div>')
                    }
                    //$('#lvn-tooltip').lawsExists(function () {
                    //    $(this).show();
                    //});
                    //$('.dropdown-tips-content-2', parent).lawsExists(function () {
                    //    $('.dropdown-tips-content-2', parent).removeClass('fixedd');
                    //    $('.dropdown-tips-content-2', parent).not('.bosung').css('visibility', 'hidden');
                    //});
                } else if (self.val() == 5) {
                    let counter = 0;
                    $('#chidanthaydoind > div').each((index, item) => {
                        if ($(item).find('.docitem-45').length > 0) {
                            $(item).removeClass('target-hidden');
                            counter++;
                        } else {
                            $(item).addClass('target-hidden');
                        }
                    })
                    if (counter == 0) {
                        $('#chidanthaydoind').append('<div class="show-personal-notes-terms-only">Không tìm thấy điều khoản hướng dẫn.</div>')
                    }
                } else if (self.val() == 6) {
                    let counter = 0;
                    $('#chidanthaydoind > div').each((index, item) => {
                        if ($(item).find('.docitem-55').length > 0 || $(item).find('.docitem-56').length > 0) {
                            $(item).removeClass('target-hidden');
                            counter++;
                        } else {
                            $(item).addClass('target-hidden');
                        }
                    })
                    if (counter == 0) {
                        $('#chidanthaydoind').append('<div class="show-personal-notes-terms-only">Không tìm thấy điều khoản bị bãi bỏ.</div>')
                    }
                } else if (self.val() == 7) {
                    let counter = 0;
                    $('#chidanthaydoind > div').each((index, item) => {
                        if ($(item).find('.docitem-51').length > 0 || $(item).find('.docitem-52').length > 0) {
                            $(item).removeClass('target-hidden');
                            counter++;
                        } else {
                            $(item).addClass('target-hidden');
                        }
                    })
                    if (counter == 0) {
                        $('#chidanthaydoind').append('<div class="show-personal-notes-terms-only">Không tìm thấy điều khoản thay thế.</div>')
                    }
                }
            });
            $(document).on('click', '', function (e) {
                var element = $('#chidanthaydoind');

                //var HTML_Width = element.width();
                //var HTML_Height = element.height();
                //var top_left_margin = 15;
                //var PDF_Width = HTML_Width + (top_left_margin * 2);
                //var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
                //var canvas_image_width = HTML_Width;
                //var canvas_image_height = HTML_Height;

                //var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;


                //html2canvas(element[0], { allowTaint: true }).then(function (canvas) {
                //    canvas.getContext('2d');

                //    console.log(canvas.height + "  " + canvas.width);


                //    var imgData = canvas.toDataURL("image/jpeg", 1.0);
                //    var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
                //    pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);


                //    for (var i = 1; i <= totalPDFPages; i++) {
                //        pdf.addPage(PDF_Width, PDF_Height);
                //        pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
                //    }

                //    pdf.save("ghich.pdf");
                //});
            })
            $(document).on('change', '#check2', function (e) {
                var parent = $('#chidanthaydoind');
                if ($(this).is(':checked')) {
                    $('#lvn-tooltip').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.popupRelate, .popupRelate2', parent).each(function (i, element) {
                        popupChiDan(element, e);
                    });
                    $('.dropdown-tips-content-2', parent).lawsExists(function () {
                        $('.dropdown-tips-content-2', parent).addClass('fixedd');
                        $('.dropdown-tips-content-2', parent).not('.bosung').css('visibility', 'visible');
                        //$('.dropdown-tips-content-2.bosung', parent).css('visibility', 'visible');
                    });
                } else {
                    $('#lvn-tooltip').lawsExists(function () {
                        $(this).show();
                    });
                    $('.dropdown-tips-content-2', parent).lawsExists(function () {
                        $('.dropdown-tips-content-2', parent).removeClass('fixedd');
                        $('.dropdown-tips-content-2', parent).not('.bosung').css('visibility', 'hidden');
                        //$('.dropdown-tips-content-2.bosung', parent).css('visibility', 'hidden');
                    });
                }
            });

            $(document).on('change', '#check21', function (e) {
                var parent = $('#noidungtoanvan');
                if ($(this).is(':checked')) {
                    $('#lvn-tooltip').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.popupRelate, .popupRelate2', parent).each(function (i, element) {
                        popupChiDan(element, e);
                    });
                    $('.dropdown-tips-content-2', parent).lawsExists(function () {
                        $('.dropdown-tips-content-2', parent).addClass('fixedd');
                        $('.dropdown-tips-content-2', parent).not('.bosung').css('visibility', 'visible');
                    });
                } else {
                    $('#lvn-tooltip').lawsExists(function () {
                        $(this).show();
                    });
                    $('.dropdown-tips-content-2', parent).lawsExists(function () {
                        $('.dropdown-tips-content-2', parent).removeClass('fixedd');
                        $('.dropdown-tips-content-2', parent).not('.bosung').css('visibility', 'hidden');
                    });
                }
            });

            if (permission && !lawsVn.isMobile()) {
                $(document).on({
                    mouseover: function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var paused = false;
                        enabletip = true;

                        var parentRefer = e.target.closest('.block-refer-content');
                        if (parentRefer != null) {
                            return false;
                        }

                        //tipobj = $(e.target).children('.dropdown-tips-content-2')[0];
                        //$('.dropdown-tips-content-2').not('.bosung').css('visibility', 'hidden');
                        if ($('#check2').is(':checked') && activeTab == opts.arrTabs[7]) {
                            paused = true;
                        }
                        else if ($('#check21').is(':checked') && activeTab == opts.arrTabs[8]) {
                            paused = true;
                        }
                        if (!paused) {
                            popupChiDan($(this), e);
                        }
                    }, mouseout: function (e) {
                        e.preventDefault();
                        e.stopPropagation();

                        var parentRefer = e.target.closest('.block-refer-content');
                        if (parentRefer != null) {
                            return false;
                        }

                        var paused = false;
                        if ($('#check2').is(':checked') && activeTab == opts.arrTabs[7]) {
                            paused = true;
                        }
                        else if ($('#check21').is(':checked') && activeTab == opts.arrTabs[8]) {
                            paused = true;
                        }
                        if (!paused)
                            hideddrivetip();
                    }
                }, '.popupRelate, .popupRelate2, .noi-dung-tham-chieu');

                var body = document.body,
                    timer;

                window.addEventListener('scroll', function () {
                    clearTimeout(timer);
                    if (!body.classList.contains('disable-hover')) {
                        body.classList.add('disable-hover');
                    }

                    timer = setTimeout(function () {
                        body.classList.remove('disable-hover');
                    }, 500);
                }, false);

            } else if (!lawsVn.isMobile()) {
                $(document).on({
                    mouseenter: function (e) {
                        var paused = false;
                        if ($('#check2').is(':checked') && activeTab == opts.arrTabs[7]) {
                            paused = true;
                        }
                        else if ($('#check21').is(':checked') && activeTab == opts.arrTabs[8]) {
                            paused = true;
                        }
                        if (!paused)
                            popupChiDan($(this), e);
                    }, mouseleave: function () {
                        var paused = false;
                        if ($('#check2').is(':checked') && activeTab == opts.arrTabs[7]) {
                            paused = true;
                        }
                        else if ($('#check21').is(':checked') && activeTab == opts.arrTabs[8]) {
                            paused = true;
                        }
                        if (!paused) {
                            $('.dropdown-tips-content-2', $(this)).css('visibility', 'hidden');
                        }
                    }
                }, '.popupRelate, .popupRelate2, .noi-dung-tham-chieu');
            }

        });
        var offsetxpoint = -60;
        var offsetypoint = 20;
        var ie = document.all;
        var ns6 = document.getElementById && !document.all;
        var enabletip = false;
        if (ie || ns6)
            var tipobj;

        function ietruebody() {
            return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
        }

        function positiontip(e) {
            if ($('#check2').is(':checked') && activeTab == opts.arrTabs[7]) {
                enabletip = false;
            }
            else if ($('#check21').is(':checked') && activeTab == opts.arrTabs[8]) {
                enabletip = false;
            }
            if ($(e.target).hasClass('docitem-58')) {
                enabletip = false;
            }
            if (permission)
                $('.dropdown-tips-content-2').not('.bosung').css('visibility', 'hidden')
            if (enabletip) {
                if (typeof tipobj !== 'undefined') {
                    var curX = (ns6) ? e.pageX : event.clientX + ietruebody().scrollLeft;
                    var curY = (ns6) ? e.pageY : event.clientY + ietruebody().scrollTop;

                    var rightedge = ie && !window.opera
                        ? ietruebody().clientWidth - event.clientX - offsetxpoint
                        : window.innerWidth - e.clientX - offsetxpoint - 20;
                    var bottomedge = ie && !window.opera
                        ? ietruebody().clientHeight - event.clientY - offsetypoint
                        : window.innerHeight - e.clientY - offsetypoint - 20;

                    var leftedge = (offsetxpoint < 0) ? offsetxpoint * (-1) : -1000;

                    if (rightedge < tipobj.offsetWidth)
                        tipobj.style.left =
                            ie
                                ? ietruebody().scrollLeft + event.clientX - tipobj.offsetWidth + "px"
                                : window.pageXOffset + e.clientX - tipobj.offsetWidth + "px";
                    else if (curX < leftedge)
                        tipobj.style.left = "5px";
                    else
                        tipobj.style.left = (curX + offsetxpoint) / 1.5 + "px";

                    if (bottomedge < tipobj.offsetHeight)
                        tipobj.style.top =
                            ie
                                ? ietruebody().scrollTop + event.clientY - tipobj.offsetHeight - offsetypoint + "px"
                                : window.pageYOffset + e.clientY - tipobj.offsetHeight - offsetypoint + "px";
                    else
                        tipobj.style.top = curY + offsetypoint + "px";
                    tipobj.style.visibility = "visible";

                } else {
                    if (permission) {
                        $('.dropdown-tips-content-2').not('.bosung').css('visibility', 'hidden');
                    }
                }
            }

            if (permission) {
                if ($(e.target).hasClass('popupRelate') || $(e.target).hasClass('popupRelate2') || $(e.target).hasClass('noi-dung-tham-chieu')) {
                    tipobj = $(e.target).children('.dropdown-tips-content-2')[0];
                } else {
                    tipobj = $(e.target).closest('[class^="popupRelate"]').children('.dropdown-tips-content-2')[0];
                }
            }
        }

        function hideddrivetip() {
            if (ns6 || ie) {
                enabletip = false;
                if (typeof tipobj !== 'undefined') {
                    tipobj.style.visibility = "hidden";
                    tipobj.style.left = "-1000px";
                    tipobj.style.backgroundColor = '';
                    tipobj.style.width = '';
                }
            }
        }
        if (!lawsVn.isMobile())
            document.onmousemove = positiontip;
    }
}
var fontSize = 14;
function handleFontSize(element) {
    return new Promise(function (resolve, reject) {
        timeOut = setTimeout(function () {
            element.find('*').each(function () {
                handleUpdateFontSize($(this))
            })
            clearTimeout(timeOut)
            resolve()
        }, 0)
    })
}
function handleUpdateFontSize(element) {
    element.css('cssText', 'font-size: ' + fontSize + 'px !important;line-height:1.6 !important;')
    return new Promise(resolve => setTimeout(requestAnimationFrame(resolve), 0))
}
function isInAppBrowser() {
    const ua = navigator.userAgent || "";
    return ua.includes("FBAN") || ua.includes("FBAV") || ua.includes("Zalo") || ua.includes("Instagram") || ua.includes("TikTok");
}
$(document).ready(function () {
    if (isInAppBrowser()) {
        $('.section-content').each(function () {
            const $section = $(this);

            // Chỉ xử lý nếu có ít nhất một list-download
            if ($section.find('.list-download').length > 0) {
                // Ẩn toàn bộ danh sách file
                $section.find('.list-download').hide();

                // Chèn thông báo cảnh báo
                const warningHtml = `
                       <div class="text-thongbao text-center">
                            <p>⚠ Bạn đang mở trang web trong <strong class="link-color">trình duyệt tích hợp của ứng dụng (in-app browser)</strong> như Facebook, Zalo hoặc TikTok.</p>
                            <p>Trình duyệt này <strong class="link-color">không hỗ trợ tải file</strong>. Vui lòng mở trang bằng <strong class="link-color">trình duyệt mặc định trên thiết bị</strong> (như Chrome, Safari...) để thực hiện tải file.</p>
                        </div>
                    `;
                $section.append(warningHtml);
            }
        });
    }
});;
