/* Minification failed. Returning unminified contents.
(23195,11-12): run-time error JS1010: Expected identifier: .
(23195,11-12): run-time error JS1195: Expected expression: .
(23464,11-12): run-time error JS1010: Expected identifier: .
(23464,11-12): run-time error JS1195: Expected expression: .
 */
/*! jQuery v1.7.1 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},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(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};
f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.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(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.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(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={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,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function()
{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);;
/*! jQuery UI - v1.12.1 - 2020-11-06
* 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/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 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(c){c.extend(c.fn,{validate:function(a){if(this.length){var b=c.data(this[0],"validator");if(b)return b;this.attr("novalidate","novalidate");b=new c.validator(a,this[0]);c.data(this[0],"validator",b);if(b.settings.onsubmit){a=this.find("input, button");a.filter(".cancel").click(function(){b.cancelSubmit=true});b.settings.submitHandler&&a.filter(":submit").click(function(){b.submitButton=this});this.submit(function(d){function e(){if(b.settings.submitHandler){if(b.submitButton)var f=c("<input type='hidden'/>").attr("name",
b.submitButton.name).val(b.submitButton.value).appendTo(b.currentForm);b.settings.submitHandler.call(b,b.currentForm);b.submitButton&&f.remove();return false}return true}b.settings.debug&&d.preventDefault();if(b.cancelSubmit){b.cancelSubmit=false;return e()}if(b.form()){if(b.pendingRequest){b.formSubmitted=true;return false}return e()}else{b.focusInvalid();return false}})}return b}else a&&a.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing")},valid:function(){if(c(this[0]).is("form"))return this.validate().form();
else{var a=true,b=c(this[0].form).validate();this.each(function(){a&=b.element(this)});return a}},removeAttrs:function(a){var b={},d=this;c.each(a.split(/\s/),function(e,f){b[f]=d.attr(f);d.removeAttr(f)});return b},rules:function(a,b){var d=this[0];if(a){var e=c.data(d.form,"validator").settings,f=e.rules,g=c.validator.staticRules(d);switch(a){case "add":c.extend(g,c.validator.normalizeRule(b));f[d.name]=g;if(b.messages)e.messages[d.name]=c.extend(e.messages[d.name],b.messages);break;case "remove":if(!b){delete f[d.name];
return g}var h={};c.each(b.split(/\s/),function(j,i){h[i]=g[i];delete g[i]});return h}}d=c.validator.normalizeRules(c.extend({},c.validator.metadataRules(d),c.validator.classRules(d),c.validator.attributeRules(d),c.validator.staticRules(d)),d);if(d.required){e=d.required;delete d.required;d=c.extend({required:e},d)}return d}});c.extend(c.expr[":"],{blank:function(a){return!c.trim(""+a.value)},filled:function(a){return!!c.trim(""+a.value)},unchecked:function(a){return!a.checked}});c.validator=function(a,
b){this.settings=c.extend(true,{},c.validator.defaults,a);this.currentForm=b;this.init()};c.validator.format=function(a,b){if(arguments.length==1)return function(){var d=c.makeArray(arguments);d.unshift(a);return c.validator.format.apply(this,d)};if(arguments.length>2&&b.constructor!=Array)b=c.makeArray(arguments).slice(1);if(b.constructor!=Array)b=[b];c.each(b,function(d,e){a=a.replace(RegExp("\\{"+d+"\\}","g"),e)});return a};c.extend(c.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",
validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:c([]),errorLabelContainer:c([]),onsubmit:true,ignore:":hidden",ignoreTitle:false,onfocusin:function(a){this.lastActive=a;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(a)).hide()}},onfocusout:function(a){if(!this.checkable(a)&&(a.name in this.submitted||!this.optional(a)))this.element(a)},
onkeyup:function(a){if(a.name in this.submitted||a==this.lastElement)this.element(a)},onclick:function(a){if(a.name in this.submitted)this.element(a);else a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).addClass(b).removeClass(d):c(a).addClass(b).removeClass(d)},unhighlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).removeClass(b).addClass(d):c(a).removeClass(b).addClass(d)}},setDefaults:function(a){c.extend(c.validator.defaults,
a)},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:c.validator.format("Please enter no more than {0} characters."),
minlength:c.validator.format("Please enter at least {0} characters."),rangelength:c.validator.format("Please enter a value between {0} and {1} characters long."),range:c.validator.format("Please enter a value between {0} and {1}."),max:c.validator.format("Please enter a value less than or equal to {0}."),min:c.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){function a(e){var f=c.data(this[0].form,"validator"),g="on"+e.type.replace(/^validate/,
"");f.settings[g]&&f.settings[g].call(f,this[0],e)}this.labelContainer=c(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||c(this.currentForm);this.containers=c(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var b=this.groups={};c.each(this.settings.groups,function(e,f){c.each(f.split(/\s/),function(g,h){b[h]=e})});var d=
this.settings.rules;c.each(d,function(e,f){d[e]=c.validator.normalizeRule(f)});c(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",a).validateDelegate("[type='radio'], [type='checkbox'], select, option","click",
a);this.settings.invalidHandler&&c(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){this.checkForm();c.extend(this.submitted,this.errorMap);this.invalid=c.extend({},this.errorMap);this.valid()||c(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(a){this.lastElement=
a=this.validationTargetFor(this.clean(a));this.prepareElement(a);this.currentElements=c(a);var b=this.check(a);if(b)delete this.invalid[a.name];else this.invalid[a.name]=true;if(!this.numberOfInvalids())this.toHide=this.toHide.add(this.containers);this.showErrors();return b},showErrors:function(a){if(a){c.extend(this.errorMap,a);this.errorList=[];for(var b in a)this.errorList.push({message:a[b],element:this.findByName(b)[0]});this.successList=c.grep(this.successList,function(d){return!(d.name in a)})}this.settings.showErrors?
this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){c.fn.resetForm&&c(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(a){var b=0,d;for(d in a)b++;return b},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{c(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(a){}},findLastActive:function(){var a=this.lastActive;return a&&c.grep(this.errorList,function(b){return b.element.name==a.name}).length==1&&a},elements:function(){var a=this,b={};return c(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&
a.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in b||!a.objectLength(c(this).rules()))return false;return b[this.name]=true})},clean:function(a){return c(a)[0]},errors:function(){return c(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=c([]);this.toHide=c([]);this.currentElements=c([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},
prepareElement:function(a){this.reset();this.toHide=this.errorsFor(a)},check:function(a){a=this.validationTargetFor(this.clean(a));var b=c(a).rules(),d=false,e;for(e in b){var f={method:e,parameters:b[e]};try{var g=c.validator.methods[e].call(this,a.value.replace(/\r/g,""),a,f.parameters);if(g=="dependency-mismatch")d=true;else{d=false;if(g=="pending"){this.toHide=this.toHide.not(this.errorsFor(a));return}if(!g){this.formatAndAdd(a,f);return false}}}catch(h){this.settings.debug&&window.console&&console.log("exception occured when checking element "+
a.id+", check the '"+f.method+"' method",h);throw h;}}if(!d){this.objectLength(b)&&this.successList.push(a);return true}},customMetaMessage:function(a,b){if(c.metadata){var d=this.settings.meta?c(a).metadata()[this.settings.meta]:c(a).metadata();return d&&d.messages&&d.messages[b]}},customMessage:function(a,b){var d=this.settings.messages[a];return d&&(d.constructor==String?d:d[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==undefined)return arguments[a]},defaultMessage:function(a,
b){return this.findDefined(this.customMessage(a.name,b),this.customMetaMessage(a,b),!this.settings.ignoreTitle&&a.title||undefined,c.validator.messages[b],"<strong>Warning: No message defined for "+a.name+"</strong>")},formatAndAdd:function(a,b){var d=this.defaultMessage(a,b.method),e=/\$?\{(\d+)\}/g;if(typeof d=="function")d=d.call(this,b.parameters,a);else if(e.test(d))d=jQuery.format(d.replace(e,"{$1}"),b.parameters);this.errorList.push({message:d,element:a});this.errorMap[a.name]=d;this.submitted[a.name]=
d},addWrapper:function(a){if(this.settings.wrapper)a=a.add(a.parent(this.settings.wrapper));return a},defaultShowErrors:function(){for(var a=0;this.errorList[a];a++){var b=this.errorList[a];this.settings.highlight&&this.settings.highlight.call(this,b.element,this.settings.errorClass,this.settings.validClass);this.showLabel(b.element,b.message)}if(this.errorList.length)this.toShow=this.toShow.add(this.containers);if(this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);
if(this.settings.unhighlight){a=0;for(b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],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 c(this.errorList).map(function(){return this.element})},showLabel:function(a,b){var d=this.errorsFor(a);if(d.length){d.removeClass(this.settings.validClass).addClass(this.settings.errorClass);
d.attr("generated")&&d.html(b)}else{d=c("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(a),generated:true}).addClass(this.settings.errorClass).html(b||"");if(this.settings.wrapper)d=d.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();this.labelContainer.append(d).length||(this.settings.errorPlacement?this.settings.errorPlacement(d,c(a)):d.insertAfter(a))}if(!b&&this.settings.success){d.text("");typeof this.settings.success=="string"?d.addClass(this.settings.success):this.settings.success(d)}this.toShow=
this.toShow.add(d)},errorsFor:function(a){var b=this.idOrName(a);return this.errors().filter(function(){return c(this).attr("for")==b})},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(a){if(this.checkable(a))a=this.findByName(a.name).not(this.settings.ignore)[0];return a},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(a){var b=this.currentForm;return c(document.getElementsByName(a)).map(function(d,
e){return e.form==b&&e.name==a&&e||null})},getLength:function(a,b){switch(b.nodeName.toLowerCase()){case "select":return c("option:selected",b).length;case "input":if(this.checkable(b))return this.findByName(b.name).filter(":checked").length}return a.length},depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):true},dependTypes:{"boolean":function(a){return a},string:function(a,b){return!!c(a,b.form).length},"function":function(a,b){return a(b)}},optional:function(a){return!c.validator.methods.required.call(this,
c.trim(a.value),a)&&"dependency-mismatch"},startRequest:function(a){if(!this.pending[a.name]){this.pendingRequest++;this.pending[a.name]=true}},stopRequest:function(a,b){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[a.name];if(b&&this.pendingRequest==0&&this.formSubmitted&&this.form()){c(this.currentForm).submit();this.formSubmitted=false}else if(!b&&this.pendingRequest==0&&this.formSubmitted){c(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=
false}},previousValue:function(a){return c.data(a,"previousValue")||c.data(a,"previousValue",{old:null,valid:true,message:this.defaultMessage(a,"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(a,b){a.constructor==String?this.classRuleSettings[a]=b:c.extend(this.classRuleSettings,
a)},classRules:function(a){var b={};(a=c(a).attr("class"))&&c.each(a.split(" "),function(){this in c.validator.classRuleSettings&&c.extend(b,c.validator.classRuleSettings[this])});return b},attributeRules:function(a){var b={};a=c(a);for(var d in c.validator.methods){var e;if(e=d==="required"&&typeof c.fn.prop==="function"?a.prop(d):a.attr(d))b[d]=e;else if(a[0].getAttribute("type")===d)b[d]=true}b.maxlength&&/-1|2147483647|524288/.test(b.maxlength)&&delete b.maxlength;return b},metadataRules:function(a){if(!c.metadata)return{};
var b=c.data(a.form,"validator").settings.meta;return b?c(a).metadata()[b]:c(a).metadata()},staticRules:function(a){var b={},d=c.data(a.form,"validator");if(d.settings.rules)b=c.validator.normalizeRule(d.settings.rules[a.name])||{};return b},normalizeRules:function(a,b){c.each(a,function(d,e){if(e===false)delete a[d];else if(e.param||e.depends){var f=true;switch(typeof e.depends){case "string":f=!!c(e.depends,b.form).length;break;case "function":f=e.depends.call(b,b)}if(f)a[d]=e.param!==undefined?
e.param:true;else delete a[d]}});c.each(a,function(d,e){a[d]=c.isFunction(e)?e(b):e});c.each(["minlength","maxlength","min","max"],function(){if(a[this])a[this]=Number(a[this])});c.each(["rangelength","range"],function(){if(a[this])a[this]=[Number(a[this][0]),Number(a[this][1])]});if(c.validator.autoCreateRanges){if(a.min&&a.max){a.range=[a.min,a.max];delete a.min;delete a.max}if(a.minlength&&a.maxlength){a.rangelength=[a.minlength,a.maxlength];delete a.minlength;delete a.maxlength}}a.messages&&delete a.messages;
return a},normalizeRule:function(a){if(typeof a=="string"){var b={};c.each(a.split(/\s/),function(){b[this]=true});a=b}return a},addMethod:function(a,b,d){c.validator.methods[a]=b;c.validator.messages[a]=d!=undefined?d:c.validator.messages[a];b.length<3&&c.validator.addClassRules(a,c.validator.normalizeRule(a))},methods:{required:function(a,b,d){if(!this.depend(d,b))return"dependency-mismatch";switch(b.nodeName.toLowerCase()){case "select":return(a=c(b).val())&&a.length>0;case "input":if(this.checkable(b))return this.getLength(a,
b)>0;default:return c.trim(a).length>0}},remote:function(a,b,d){if(this.optional(b))return"dependency-mismatch";var e=this.previousValue(b);this.settings.messages[b.name]||(this.settings.messages[b.name]={});e.originalMessage=this.settings.messages[b.name].remote;this.settings.messages[b.name].remote=e.message;d=typeof d=="string"&&{url:d}||d;if(this.pending[b.name])return"pending";if(e.old===a)return e.valid;e.old=a;var f=this;this.startRequest(b);var g={};g[b.name]=a;c.ajax(c.extend(true,{url:d,
mode:"abort",port:"validate"+b.name,dataType:"json",data:g,success:function(h){f.settings.messages[b.name].remote=e.originalMessage;var j=h===true;if(j){var i=f.formSubmitted;f.prepareElement(b);f.formSubmitted=i;f.successList.push(b);f.showErrors()}else{i={};h=h||f.defaultMessage(b,"remote");i[b.name]=e.message=c.isFunction(h)?h(a):h;f.showErrors(i)}e.valid=j;f.stopRequest(b,j)}},d));return"pending"},minlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)>=d},maxlength:function(a,
b,d){return this.optional(b)||this.getLength(c.trim(a),b)<=d},rangelength:function(a,b,d){a=this.getLength(c.trim(a),b);return this.optional(b)||a>=d[0]&&a<=d[1]},min:function(a,b,d){return this.optional(b)||a>=d},max:function(a,b,d){return this.optional(b)||a<=d},range:function(a,b,d){return this.optional(b)||a>=d[0]&&a<=d[1]},email:function(a,b){return this.optional(b)||/^((([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(a)},
url:function(a,b){return this.optional(b)||/^(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(a)},
date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a))},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9 -]+/.test(a))return false;var d=0,e=0,f=false;a=a.replace(/\D/g,"");for(var g=a.length-1;g>=
0;g--){e=a.charAt(g);e=parseInt(e,10);if(f)if((e*=2)>9)e-=9;d+=e;f=!f}return d%10==0},accept:function(a,b,d){d=typeof d=="string"?d.replace(/,/g,"|"):"png|jpe?g|gif";return this.optional(b)||a.match(RegExp(".("+d+")$","i"))},equalTo:function(a,b,d){d=c(d).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){c(b).valid()});return a==d.val()}}});c.format=c.validator.format})(jQuery);
(function(c){var a={};if(c.ajaxPrefilter)c.ajaxPrefilter(function(d,e,f){e=d.port;if(d.mode=="abort"){a[e]&&a[e].abort();a[e]=f}});else{var b=c.ajax;c.ajax=function(d){var e=("port"in d?d:c.ajaxSettings).port;if(("mode"in d?d:c.ajaxSettings).mode=="abort"){a[e]&&a[e].abort();return a[e]=b.apply(this,arguments)}return b.apply(this,arguments)}}})(jQuery);
(function(c){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.handle.call(this,e)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)},handler:function(e){arguments[0]=c.event.fix(e);arguments[0].type=b;return c.event.handle.apply(this,arguments)}}});c.extend(c.fn,{validateDelegate:function(a,
b,d){return this.bind(b,function(e){var f=c(e.target);if(f.is(a))return d.apply(f,arguments)})}})})(jQuery);
;
/*
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,d){var b=a(this).find("[data-valmsg-for='"+f(d[0].name)+"']"),e=a.parseJSON(b.attr("data-valmsg-replace"))!==false;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(e){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("<li />").html(this.message).appendTo(b)})}}function k(c){var b=c.data("unobtrusiveContainer"),d=a.parseJSON(b.attr("data-valmsg-replace"));if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");c.removeData("unobtrusiveContainer");d&&b.empty()}}function n(){var b=a(this);b.data("validator").resetForm();b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(c){var b=a(c),d=b.data(e),f=a.proxy(n,c);if(!d){d={options:{errorClass:"input-validation-error",errorElement:"span",errorPlacement:a.proxy(m,c),invalidHandler:a.proxy(l,c),messages:{},rules:{},success:a.proxy(k,c)},attachValidation:function(){b.unbind("reset."+e,f).bind("reset."+e,f).validate(this.options)},validate:function(){b.validate();return b.valid()}};b.data(e,d)}return d}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(b){var c=a(b).parents("form").andSelf().add(a(b).find("form")).filter("form");a(b).find(":input[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});c.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});b.addSingleVal("accept","exts").addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){return a(b.form).find(":input[name='"+f(c)+"']").val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery);;
/// <reference path="alawsvn.js" />
$(function () {
    lawsVn.init();
    lawsInfo();
    $(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 (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 (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 == 'VanBanNoiDungThayDoi') && 1===2) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['<em> Để xem Nội dung toàn văn đã tổng hợp nội dung thay đổi <br></em><em>Quý khách vui lòng <a href="#" class="lawsVnLogin" style="color: #a67942" title="Đăng nhập tài khoản"><strong>Đăng nhập</strong></a> tài khoản LuatVietnam và <a href="/dich-vu.html" title="Đăng ký phần mềm"><strong style="color: #a67942">đăng ký sử dụng Phần mềm tra cứu văn bản</strong></a>.</em>'],
                    buttons: [
                        {
                            text: lawsVn.Resource.getMessages('Login'),
                            'class': 'btn-thongbao1 lawsVnLogin'
                        },
                        {
                            text: lawsVn.Resource.getMessages('Close'),
                            click: function () {
                                $(this).dialog('close');
                            }
                        }
                    ],
                    onOpen: function () {
                        if ($('.popupRelate').length) {
                            $('.popupRelate').removeAttr('requestRunning');
                        }
                    }
                });
                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);
            });
            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
};
var lawterminConfig = {
    rootPath: '/',
    docContentViewLimit: 10,
    pathName: window.location.pathname
};

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'
                });
        }
        
        if (jQuery().lazyload) {
            $('.lazyload').lazyload({
                effect: 'fadeIn'
            });
        }
        $('.popup-wrapper.navigation-top').lawsExists(function () {
            var p = $(this);
            $('.theme-header').lawsExists(function () {
                $(window).scroll(function () {
                    if ($(window).scrollTop() > 0) {
                        p.css('top', '12px');
                    } else {
                        p.css('top', '74px');
                    }
                });
            });
        });
        
        $('#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>');
        });
        
        //$(document).tooltip();
        if ($('[data-toggle-target]').length) {
            $('[data-toggle-target]').each(function () {
                $(this).toggleTarget();
            });
        }
        $('.google-login').googleLogin({ accountInfoType: 2 });
        $('.facebook-login').facebookLogin({ accountInfoType: 2 });
        $('.google-loginV2').googleLogin();
        $('.facebook-loginV2').facebookLogin();
        $('.zalo-login').zaloLogin();
        $('#ScrollToFixed').lawsExists(function () {
            var me = $(this),
                i = $('.sidebar-nav.v4 > .widget'),
                isHome = lawsVn.isHome(),
                footer = isHome ? $('.partner') : $('.theme-footer'),
                left = $('.main-content'),
                nav = $('.sidebar-nav'),
                right = $('#rightboxContent'),
                tieudiem = $('.box-tieudiem'),
                isArticle = typeof me.data('article') !== 'undefined' ? true : false,
                isFocus = typeof me.data('focus') !== 'undefined' ? true : false,
                initialPos = isArticle || isFocus ? me.offset().top : i.position().top + i.offset().top + i.outerHeight(true),
                tabPannel = $('#tabPannel');
            $(window).bind('scroll resize', function () {
                var footerTop = footer.offset().top,
                    scroll = $(window).scrollTop(),
                    navBottom = scroll + me.height() + 22;
                if (isFocus) {
                    $('.wg-tieudiem.focus').lawsExists(function() {
                        initialPos = ($(this).offset().top + $(this).outerHeight(true));
                    });
                }
                //$('.article-right-box').lawsExists(function () {
                //    initialPos = ($(this).offset().top + $(this).outerHeight(true));
                //});
                if (scroll > initialPos && scroll < navBottom) {
                    
                    me.css({
                        'position': 'fixed',
                        'top': (footerTop - navBottom > 0 ? (isHome || tabPannel.length ? 0 : 42) : footerTop - navBottom) + 'px',
                        'left': (isArticle ? right.offset().left : isFocus ? tieudiem.offset().left : (left.offset().left - $(window).scrollLeft())) + 'px',
                        'width': isArticle ? right.width() : isFocus ? tieudiem.width() : nav.width()
                    });
                } else {
                    me.css({
                        'position': 'static'
                    });
                }
            });
        });
       
        if (!$('#tabPannel').length) {
            $('#ma-code-auto').lawsExists(function () {
                $(this).autofix_anything({ customOffset: Math.round($(this).offset().top + $(this).innerHeight()) });
            });
        } else
            $('#tabPannel').lawsExists(function () {
                $(this).autofix_anything({ customOffset: Math.round($(this).offset().top + $(this).innerHeight()) });
            });
        $('#DocFields').lawsExists(function () {
            var self = $(this);
            $('.DocFields').lawsExists(function () {
                $(this).html(self.html());
            });
        });
      
        $(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) {

                }
            });
        $('.content-drop-fields').lawsExists(function () {
            $('input[type=hidden][name=lFieldId]').lawsExists(function () {
                var array,
                    fieldId;
                fieldId = $(this).val();
                array = fieldId.split(',');
                $(':checkbox.field-items2').prop('checked', false);
                $(':checkbox.field-items2').lawsExists(function () {
                    $(this).prop('checked',
                        function () {
                            return $.inArray(this.value, array) !== -1;
                        });
                });
                if ($(':checkbox.field-items2:not(:checked)').length == 0)
                    $(':checkbox.selectAll2[name=lFieldId]').prop('checked', true);
            });
        });
        $(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('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',
            '#btn_attachmentGopY_10w2p3',
            function (e) {
                e.preventDefault();
                $('#input_attachmentGopY_6cnnq3').trigger('click');
            });
        $(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('change',
            '#input_attachmentGopY_6cnnq3',
            function (e) {
                e.preventDefault();
                if (lawsVn.supportAjaxUploadWithProgress() && this.files.length > 0) {
                    var formData = new FormData(),
                        fileUploads = this.files,
                        maxSize = 20,
                        limitNumberUploads = 5,
                        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) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [
                                    'Vui lòng chọn tối đa ' + limitNumberUploads + ' file đính kèm (PDF, word, ảnh).'
                                ],
                                showIcon: false
                            });
                            return;
                        }
                        for (; index < fileUploads.length; index++) {
                            fileNameExt = fileUploads[index].name.split('.').pop().toLowerCase();
                            if (validExtensions.indexOf(fileNameExt) == -1) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Vui lòng chọn file đính kèm (PDF, word, ảnh).'],
                                    showIcon: false
                                });
                                return;
                            }
                            if (fileUploads[index].size / 1024 / 1024 > maxSize) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Dung lượng file đính kèm vượt quá ' + maxSize + 'MB cho phép.'],
                                    showIcon: false
                                });
                                return;
                            }
                            formData.append('listFiles', fileUploads[index]);
                        }
                        $.ajax({
                            url: lawsVn.virtualPath('/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++) {
                                            if (resp.Data[i].FilePath != null && resp.Data[i].FilePath.length > 0) {
                                                var fileId = Math.random().toString(36).substring(7);
                                                $('#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"><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) {
                                    $().lawsDialog({
                                        dialogClass: 'lawsVnDialogTitle',
                                        messages: [resp.Message],
                                        showIcon: false
                                    });
                                }
                            },
                            error: function () {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: ['Quý khách vui lòng thử lại sau.'],
                                    showIcon: false
                                });
                            }
                        });
                    } else {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách vui lòng chọn tối đa ' + limitNumberUploads + ' file đính kèm.'],
                            showIcon: false
                        });
                    }
                } else
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Quý khách vui lòng nâng cấp trình duyệt web để sử dụng tính năng này.'],
                        showIcon: false
                    });
            });
        //
        $(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');
            });
        $('form#RegisterFormTarget').on('submit', function (e) {
            e.preventDefault();
            return lawsVn.CheckboxTermsAndConditionsRequired();
        });
        $('[id*=TermsAndConditions]').click(function () {
            lawsVn.CheckboxTermsAndConditionsRequired();
        });
        $('input.paramKeywords').on('keypress keyup blur',
            function () {
                $('.searchByParam').trigger('click');
            });
      
        $(document).on('keyup change',
            '#text-search-field',
            function () {
                var searchTerm = $(this).val();
                $('#search-fields').removeHighlight();
                if (searchTerm) {
                    $('#search-fields').highlight(searchTerm);
                }
            });
        $(document).on('click','.search-field',
            function() {
                $('#SearchFormStatistic').lawsExists(function() {
                    $(this).submit();
                });
            });
        $(document).on('keypress keyup blur', '.paramFieldsKeywords',
            function () {
                var me = $(this),
                    parent = me.closest('.md_col2'),
                    li = parent.find('li'),
                    value = lawsVn.KhongDau(me.val()), valueCompare;
                li.each(function () {
                    var t = $(this);
                    valueCompare = lawsVn.KhongDau($(this).find('a').text().trim());
                    if (valueCompare.search(value) > -1) {
                        t.show();
                    } else {
                        t.hide();
                    }
                });
            });
        $('.searchByParam').click(function (e) {
            e.preventDefault();
            var me = $(this),
                root = me.closest('.dropdowncontent'),
                param = root.find('input.paramKeywords'),
                value,
                valueCompare,
                li = root.find('li.item-select'),
                selectAll = root.find('.search-select.pad2'),
                index = 0,
                type = 1;
            if (param.length) {
                value = lawsVn.KhongDau(param.val());
                li.each(function () {
                    var t = $(this);
                    $(t.find('label.label-input')).lawsExists(function () {
                        type = 2;
                        valueCompare = lawsVn.KhongDau($(this).text().trim());
                        if (valueCompare.search(value) > -1) {
                            t.show();
                            index++;
                        } else {
                            t.hide();
                        }
                    });
                    if (type != 2) {
                        valueCompare = lawsVn.KhongDau(t.text().trim());
                        if (valueCompare.search(value) > -1) {
                            t.show();
                            index++;
                        } else {
                            t.hide();
                        }
                    }
                });
                selectAll.lawsExists(function () {
                    if (index > 0) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
                $('.scrollbar-content', $('.scrollbars1')).lawsExists(function () {
                    $(this).css({ 'top': '0px' });
                });
            }
            return false;
        });
        $(document).on('click',
            '.param-items',
            function (e) {
                e.preventDefault();
                var me = $(this),
                    root = me.closest('.btn-dropdown1.fix_select'),
                    value = me.data('value'),
                    id = me.data('id'),
                    name = me.data('name');
                $('.param-items').removeClass('active');
                me.addClass('active');
                if (typeof id !== 'undefined' && typeof value !== 'undefined' && typeof name !== 'undefined') {
                    var input = $('input[type="hidden"][name="' + value + '"]', root);
                    if (input.length === 0) {
                        root.append('<input type="hidden" name="' + value + '" value="' + id + '" />');
                    } else {
                        if (id != '' && id != 0) {
                            $('input[type="hidden"][name="' + value + '"]', root).lawsExists(function () {
                                $(this).val(id);
                            });
                        } else {
                            input.remove();
                        }
                    }
                    $('.' + name, root).lawsExists(function () {
                        $(this).text(me.text());
                    });
                    me.closest('form').trigger('submit');
                }
                $(".content-drop.fix_select").hide();
                $(".btn-dropdown1 .btn-toggle1").removeClass("active");
            });
        $(document).on('click',
            '.param-items2',
            function (e) {
                e.preventDefault();
                var me = $(this),
                    form = $('.search-filter').find('form'),
                    value = me.data('value'),
                    id = me.data('id');
                if (typeof id !== 'undefined' && typeof value !== 'undefined') {
                    $('input[type=hidden][name=' + value + ']', form).lawsExists(function () {
                        $(this).val(id);
                    });
                    $('input[type=hidden][name=page]', form).lawsExists(function () {
                        $(this).val(1);
                    });
                    form.trigger('submit');
                }
            });
        $(document).on('change',
            '.field-items',
            function (e) {
                e.preventDefault();
                //$(this).closest('.content-drop').hide();
                var list = $(this).closest('ul'),
                    origOrder = list.children();

                var i, checked = document.createDocumentFragment(),
                    unchecked = document.createDocumentFragment();
                for (i = 0; i < origOrder.length; i++) {
                    if (origOrder[i].getElementsByTagName('input')[0].checked) {
                        checked.appendChild(origOrder[i]);
                    } else {
                        unchecked.appendChild(origOrder[i]);
                    }
                }
                list.append(checked).append(unchecked);
                $('.scrollbar-content', $('.scrollbars1')).lawsExists(function () {
                    $(this).css({ 'top': '0px' });
                });
                $(this).closest('form').trigger('submit');
            });
        $(document).on('change',
            '.field-items2',
            function (e) {
                e.preventDefault();
                var form = $('.search-filter').find('form');
                var fieldIdValues = $('input.field-items2:checked').map(function () {
                    return this.value;
                }).get().join(',');
                $('input[type=hidden][name=lFieldId]', form).lawsExists(function () {
                    $(this).val(fieldIdValues);
                });
                $('input[type=hidden][name=page]', form).lawsExists(function () {
                    $(this).val(1);
                });
                lawsVn.createCookie('FieldIdSearch', '1', 1);
                form.trigger('submit');
            });
        $(document).on('change',
            '.keyword-items_9o9p1f2wx2',
            function (e) {
                e.preventDefault();
                var me = $(this), form = $('.form-locvb').find('form'), keywords = $('input[type=hidden][name=lKeywordId]', form),
                keywordIdValues = $('input.keyword-items_9o9p1f2wx2:checked').map(function () {
                    return this.value;
                }).get().join(',');
                if (keywords.length > 0) {
                    keywords.val(keywordIdValues);
                } else {
                    form.append('<input type="hidden" name="lKeywordId" value="' + keywordIdValues + '" />');
                }
                if (me.not(':checked')) {
                    $('.selectAll_u5xra611hk').prop('checked', false);
                }
            });
        $(document).on('change',
            '.organ-items_kqe1kds8r8',
            function (e) {
                e.preventDefault();
                var form = $('.form-locvb').find('form'), organs = $('input[type=hidden][name=lOrganId]', form),
                organIdValues = $('input.organ-items_kqe1kds8r8:checked').map(function () {
                    return this.value;
                }).get().join(',');
                if (organs.length > 0) {
                    organs.val(organIdValues);
                } else {
                    form.append('<input type="hidden" name="lOrganId" value="' + organIdValues + '" />');
                }
            });
        $(document).on('click',
            '.ul_w_content2 .w_item',
            function (e) {
                e.preventDefault();
                $('.ul_w_content2 .w_info').hide();
                $(this).next().show();
            });
        $(document).on('change',
            '.province-items_b2atv5engb',
            function (e) {
                e.preventDefault();
                var me = $(this), form = $('.form-locvb').find('form'), provinces = $('input[type=hidden][name=lProvinceId]', form),
                provinceIdValues = $('input.province-items_b2atv5engb:checked').map(function () {
                    return this.value;
                }).get().join(',');
                if (provinceIdValues.length > 0) {
                    if (provinces.length > 0) {
                        provinces.val(provinceIdValues);
                    } else {
                        form.append('<input type="hidden" name="lProvinceId" value="' + provinceIdValues + '" />');
                    }
                } else provinces.remove();
                if (me.not(':checked')) {
                    $('.selectAll_u6m8usfyh3').prop('checked', false);
                }
            });
        
        $('.formlocvb-wavzbth20w').submit(function (e) {
            var me = $(this),
                keywords = me.find(':input[type="hidden"][name="lKeywordId"]'),
                organs = me.find(':input[type="hidden"][name="lOrganId"]'),
                provinces = me.find(':input[type="hidden"][name="lProvinceId"]');
            keywords.lawsExists(function () {
                if ($(this).val().trim().length == 0) {
                    $(this).remove();
                }
            });
            organs.lawsExists(function () {
                if ($(this).val().trim().length == 0) {
                    $(this).remove();
                }
            });
            provinces.lawsExists(function () {
                if ($(this).val().trim().length == 0) {
                    $(this).remove();
                }
            });
        });
        $('.div-dang-ky-dv').lawsExists(function () {
            $('.div-dang-ky-dv').each(function (i, el) {
                if ($(el).find('button').length == 0) $(el).css('height', '30px');
            });
        });
       
        $(document).on('keyup change',
            '#text-search-field',
            function() {
                var searchTerm = $(this).val();
                $('#search-fields').removeHighlight();
                if (searchTerm) {
                    $('#search-fields').highlight(searchTerm);
                }
            });
        $('#text-search-field-register').bind('keyup change',
            function (ev) {
                var searchTerm = $(this).val();
                $('#search-fields-register').removeHighlight();
                if (searchTerm) {
                    $('#search-fields-register').highlight(searchTerm);
                }
            });
        //$('div.content-entry').lawsExists(function () {
        //    lawsVn.GetFontSize(this);
        //});
        $('.btn-redirect').on("click", function (e) {
            e.preventDefault();
            var url = $(this).data('target');
            location.replace(url);
        });
        $(document).on('click', '.img_theodoivb', function (e) {
            e.preventDefault();
            var me = $(this), docId = me.data('id'), save = me.data('save');
            if (typeof docId !== 'undefined' && $.isNumeric(docId)) {
                $.lawsAjax({
                    type: 'Post',
                    url: save === 1 ? lawsVn.virtualPath('/Ajax/SubscriptionNoticeOfValidity3') : lawsVn.virtualPath('/Ajax/UnSubscriptionNoticeOfValidity'),
                    data: { docId: docId },
                    success: function (resp) {
                        if (resp.Message != null && resp.Message.length > 0) {
                            if (save === 0) {
                                me.removeClass('active');
                                me.attr('title', 'Theo dõi hiệu lực văn bản này');
                                me.data('save', 1);
                            } else if (save === 1) {
                                me.addClass('active');
                                me.attr('title', 'Hủy theo dõi hiệu lực văn bản này');
                                me.data('save', 0);
                            }
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [resp.Message]
                            });
                        }
                    }
                });
            }
        });
        $('select.select-list-fields').on('change',
            function (e) {
                e.preventDefault();
                var optionSelected = $('option:selected', this),
                    form = $('.hoi_dap_search.w_search').find('form');
                form.lawsExists(function () {
                    $('input[type="hidden"][name="FieldId"]', $(this)).
                        lawsExists(function () {
                            $(this).val(optionSelected.val());
                            form.trigger('submit');
                        });
                });
            });
        $('#btnDanhmuc').on('click',
            function (e) {
                e.preventDefault();
                var content = $('#danhmucContent');
                if (content.children().length > 0) {
                    content.show();
                } else {
                    $('#loading').fadeIn('normal');
                    $.ajax({
                        dataType: 'html',
                        url: lawsVn.virtualPath('/ajax/DanhMucPartialViewResult')
                    }).done(function (data) {
                        content.lawsExists(function() {
                            $(this).html(data);
                            $(this).show();
                        });
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách vui lòng thử lại sau'],
                            buttons: [
                                {
                                    text: lawsVn.Resource.getMessages('Close'),
                                    click: function () {
                                        $(this).dialog('close');
                                    }
                                }
                            ]
                        });
                    });
                    $('#loading').fadeOut('normal');
                }
            });
        $('select.load-organs').on('change',
            function (e) {
                e.preventDefault();
                var optionSelected = $('option:selected', this),
                    valueSelected = optionSelected.val(), textSelected = optionSelected.text();
                lawsVn.createCookie('OrganSearch', '{OrganId:' + valueSelected + ',OrganDesc:"' + textSelected + '"}', 1);
            });
        $('select.load-organs').on('click focus', function (e) {
            e.preventDefault();
            var self = $(this), options = self.children('option').length, displayTypeId = self.attr('data-displaytypeId') && self.attr('data-displaytypeId') !== '' ? self.attr('data-displaytypeId') : 0;
            if (options <= 2) {
                self.children('[value="0"]').html('Đang tải dữ liệu...');
                $.ajax({
                    type: 'get',
                    dataType: 'json',
                    async: false,
                    url: lawsVn.virtualPath('/ajax/getOrgans?displayTypeId=' + displayTypeId),
                    beforeSend: function () {
                        $('#loading').fadeIn('normal');
                    },
                    success: function (resp) {
                        if (resp.Data != null && resp.Data.length > 0) {
                            self.children('[value="0"]').html('Cơ quan ban hành');
                            $.each(resp.Data, function (i, obj) {
                                self.append(
                                    $('<option></option>')
                                        .val(obj.OrganId)
                                        .html(obj.OrganDesc));
                            });
                        }
                    },
                    error: function () {
                        self.children('[value="0"]').html('Cơ quan ban hành');
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách vui lòng thử lại sau']
                        });
                    }
                }).always(function () {
                    $('#loading').fadeOut('normal');
                });
            }
        });
        $('select.load-draftingAgency').on('change',
            function (e) {
                e.preventDefault();
                var optionSelected = $('option:selected', this),
                    valueSelected = optionSelected.val(), textSelected = optionSelected.text();
                lawsVn.createCookie('DraftingAgencySearch', '{DraftingAgencyId:' + valueSelected + ',DraftingAgencyDesc:"' + textSelected + '"}', 1);
            });
        $('select.load-draftingAgency').on('click focus', function (e) {
            e.preventDefault();
            var self = $(this), options = self.children('option').length, displayTypeId = self.attr('data-displaytypeId') && self.attr('data-displaytypeId') !== '' ? self.attr('data-displaytypeId') : 0;
            if (options <= 2) {
                self.children('[value="0"]').html('Đang tải dữ liệu...');
                $.ajax({
                    type: 'get',
                    dataType: 'json',
                    async: false,
                    url: lawsVn.virtualPath('/ajax/getDraftingAgency?displayTypeId=' + displayTypeId),
                    beforeSend: function () {
                        $('#loading').fadeIn('normal');
                    },
                    success: function (resp) {
                        if (resp.Data != null && resp.Data.length > 0) {
                            self.children('[value="0"]').html('Cơ quan soạn thảo');
                            $.each(resp.Data, function (i, obj) {
                                self.append(
                                    $('<option></option>')
                                        .val(obj.DraftingAgencyId)
                                        .html(obj.DraftingAgencyDesc));
                            });
                        }
                    },
                    error: function () {
                        self.children('[value="0"]').html('Cơ quan soạn thảo');
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách vui lòng thử lại sau']
                        });
                    }
                }).always(function () {
                    $('#loading').fadeOut('normal');
                });
            }
        });
        $(".statistic-field-rows").on("click", function () {
            if ($(this).find('input[type="radio"]').is(':checked')) {
                $('.statistic-field-rows').removeClass('setcolor');
                $(this).addClass('setcolor');
            }
        });
        $(".statistic-doctype-rows").on("click", function () {
            if ($(this).find('input[type="radio"]').is(':checked')) {
                $('.statistic-doctype-rows').removeClass('setcolor');
                $(this).addClass('setcolor');
            }
        });
        $(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();
                        });
                    }
                }
            });
        
        $('.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;
                    }
                });
            });
           
        });
        $('.pagination-container').lawsExists(function () {
            $(this).postPaginate({ itemsPerPage: 8 });
        });
        $(".btn-toggle1").click(function () {
            var t = $(this).parents(".btn-dropdown1").children(".btn-menu1").is(":hidden");
            $(".btn-dropdown1 .btn-menu1").hide();
            $(".btn-dropdown1 .btn-toggle1").removeClass("active");
            if (t) {
                $(this).parents(".btn-dropdown1").children(".btn-menu1").toggle().parents(".btn-dropdown1")
                    .children(".btn-toggle1").addClass("active");
            }
        });
        $(document).bind("click",
            function (t) {
                var n = $(t.target);
                if (!n.parents().hasClass("btn-dropdown1")) $(".btn-dropdown1 .btn-menu1").hide();
            });
        $(document).bind("click",
            function (t) {
                var n = $(t.target);
                if (!n.parents().hasClass("btn-dropdown1")) $(".btn-dropdown1 .btn-toggle1").removeClass("active");
            });
        
        $('.accordion-menu .accordion').lawsExists(function () {
            $('.accordion-menu .accordion').slice(2).hide();
        });
        $(document).on('click',
            '.accordion-menu > li > a.accor',
            function (e) {
                e.preventDefault();
                var accordion = $(this).next();
                if (accordion.is(':hidden') === true) {
                    $('.accordion-menu .accordion').slideUp();
                    accordion.slideDown();
                } else {
                    accordion.slideUp();
                }
            });
        this.widgetUser();        
        $(document).on('click',
            '.tab-nav a[data-content="dangnhap"], .tab-nav a[data-content="dangky"]',
            function (event) {
                event.preventDefault();
                var me = $(this), content = me.data('content'), li = $('li[data-content*="dang"], li[data-content="dangky"]'), liActive = $('li[data-content="' + content + '"]');
                $('.tab-item2').removeClass('tab-active');
                me.addClass('tab-active');
                li.removeClass('tab-active');
                liActive.addClass('tab-active');
            });
        $(document).on('click',
            '.tab-nav-item1',
            function (event) {
                event.preventDefault();
                $('.tab-nav-item1').removeClass('active');
                $(this).addClass('active');
                var tabActive = $(this).data('id');
                $('.tab-item').hide();
                $(tabActive).show();
            });
        $(document).on('click',
            '.tab-nav-item2',
            function (event) {
                event.preventDefault();
                $('.tab-nav-item2').removeClass('active');
                $(this).addClass('active');
            });
        $(document).on('click',
            '.tab-myluat-item',
            function (event) {
                //event.preventDefault();
                $('.tab-myluat-item').removeClass('active');
                $(this).addClass('active');
            });
        $(document).on('click',
            '.btn-notlogin',
            function (event) {
                event.preventDefault();
                var me = $(this), parent = me.closest('.rows_thoanhtoan_1'), tips = parent.find('.text_tips2')
                parent.lawsExists(function () {
                    tips.lawsExists(function () {
                        $(this).toggleClass('hidden');
                    });
                });
            });
        $(document).on('click',
            '.row-item.fix',
            function () {
                $('.row-item.fix').css('color', '#222');
                $(this).css('color', '#a67942');
            });
        $(document).on('click',
            '#closePopup',
            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');
                    $('#mucluc').lawsExists(function () {
                        $(this).hide();
                    });
                } else {
                    link.html('<img src="/assets/images/x.png" alt="close">');
                    $('#mucluc').lawsExists(function () {
                        $(this).show();
                    });
                }
            });
        $(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();
                    });
                }
            });
        $('#FieldStatisticRowsOthers').lawsExists(function () {
            $(this).loadmoreContent({ rowClass: '.statistic-field-rows', pageSize: 5 });
        });
        $('#DocTypeStatisticRowsOthers').lawsExists(function () {
            $(this).loadmoreContent({ rowClass: '.statistic-doctype-rows', pageSize: 5 });
        });
        $('#OrganStatisticRowsOthers').lawsExists(function () {
            $(this).loadmoreContent({ rowClass: '.statistic-organ-rows', pageSize: 5 });
        });
        $('#FieldRowsHomeOthers').lawsExists(function () {
            $(this).loadmoreContent({ rowClass: '.field-rows-home', pageSize: 7 });
        });
        $(document).on('click',
            '.icon-huy',
            function (e) {
                e.preventDefault();
                $('#UpdateCustomerFields2').lawsExists(function () {
                    $(this).removeClass('target-expanded').addClass('target-hidden');
                });
            });        
        $(document).on('click',
            '#btn-search-advanced',
            function (event) {
                event.preventDefault();
                //document.getElementById("searchAdvanced").classList.toggle("show");
                var text = $(this);
                $('#searchAdvanced').toggle('fast',
                    function () {
                        if ($(this).is(':visible')) {
                            text.html('Thu gọn <img alt="img-tk" src="/assets/images/mt.png">');
                        } else {
                            text.html('Tìm nâng cao <img alt="img-tk" src="/assets/images/mt.png">');
                        }
                    });
                return false;
            });
        $(document).on('click',
            '.ListFieldDisplays input[type="checkbox"]',
            function () {
                //$('input[value="' + this.value + '"]:checkbox').prop('checked', this.checked);
                $('input[data-fieldname="' + $(this).data('fieldname') + '"]:checkbox').prop('checked', this.checked);
            });
        
        $(document).on('click',
            '.dropbtn-2',
            function (event) {
                event.preventDefault();
                var text = $('#searchAdvanceText');
                $('#myDropdown').toggle('fast',
                    function () {
                        if ($(this).is(':visible')) {
                            text.text('Thu gọn');
                        } else {
                            text.text('Tìm nâng cao');
                        }
                    });
            });
        $(document).on('click',
            '.dropbtn_myluat',
            function (event) {
                event.preventDefault();
                var text = $('#searchAdvanceText');
                $('#myDropdown').toggle('fast',
                    function () {
                        if ($(this).is(':visible')) {
                            text.text('Thu gọn');
                        } else {
                            text.text('Tìm nâng cao');
                        }
                        if ($(this).hasClass('show_myluat')) {
                            $(this).removeClass('show_myluat');
                        } else {
                            $(this).addClass('show_myluat');
                        }
                    });
            });
        $('#checkAll').click(function () {
            if (this.checked) {
                $('.customervips-del, #rwolhygzyn, .newlettermember-del').lawsExists(function() {
                    $(this).css('color', '#222');
                });
            } else {
                $('.customervips-del, #rwolhygzyn, .newlettermember-del').lawsExists(function () {
                    $(this).css('color', '#9f9f9f');
                });
            }
            $('.table-user input:checkbox').not(this).prop('checked', this.checked);
        });
        
        $('.select-example.yearrange').lawsExists(function () {
            var me = $(this);
            me.selectX({
                onSelect: function (objSelected) {
                    var form = me.closest('form');
                    form.find(':input[type="hidden"][name="YearRange"]').lawsExists(function () {
                        $(this).val(objSelected.value);
                    });
                }
            });
        });
        $(document).on('click',
            '.tab-nav-item3',
            function (event) {
                event.preventDefault();
                $('.tab-nav-item3').removeClass('active');
                $(this).addClass('active');
            });

        $('.tab-nav-widget1,.tab-wg-item').off('click').on('click',
            function (event) {
                event.preventDefault();
                $('.tab-nav-widget1,.tab-wg-item').removeClass('active');
                $(this).addClass('active');
            });
       
        $('.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);
        });
        
        $(document).keyup(function (e) {
            if (e.keyCode == 27 && $(".overlay").css("display") != "none") {
                event.preventDefault();
                $('.login-wrapper, .overlay').hide(300);
                //$(".overlay").fadeToggle("fast");
            }
        });

        $('.lawsVnChangePassword').off('click').on('click',
            function (event) {
                event.preventDefault();
                lawsVn.changePassword();
            });
        $('.lawsVnChangePasswordVIP').off('click').on('click',
            function (event) {
                event.preventDefault();
                lawsVn.changePasswordVIP();
            });
        $('.lawsVnLogOut').off('click').on('click',
            function (event) {
                event.preventDefault();
                lawsVn.logOut();
            });
        //tham số share 
        https://www.facebook.com/dialog/share?
        //app_id = [your - app - id]
        //    & display=popup
        //        & title=This + is + the + title + parameter
        //            & description=This + is + the + description + parameter
        //                & quote=This + is + the + quote + parameter
        //                    & caption=This + is + the + caption + parameter
        //                        & href=https % 3A % 2F % 2Fdevelopers.facebook.com % 2Fdocs % 2F
        //                            & redirect_uri=https % 3A % 2F % 2Fwww.[url -in -your - accepted - list].com




        $('.sub-menu2-item').off('click').on('click',
            function () {
                $('.sub-menu2-item').removeClass('active');
                $(this).addClass('active');
            });
        $('.tab-nav-item-ad').off('click').on('click',
            function () {
                $('.tab-nav-item-ad').removeClass('active');
                $(this).not('.unavailable').addClass('active');
            });
        $(document).on('click',
            '.fontpage',
            function() {
                $('.fontpage').removeClass('active');
                $(this).addClass('active');
            });
        $('.post-tag-abc').off('click').on('click',
            function () {
                $('.post-tag-abc').removeClass('active');
                $(this).addClass('active');
            });
        $(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();
                });
            });
        $('.dv-tieuchuan').lawsExists(function () {
            $(this).find('p').slice(0, 7).show();
        });
        $('.law-step:first').lawsExists(function () {
            $(this).fadeIn();
        });
        $(document).mouseup(function (e) {
            var popup = $(".login-wrappe");
            if (!$('.login-wrappe').is(e.target) && !popup.is(e.target) && popup.has(e.target).length === 0) {
                $('.login-wrappe, .overlay').hide(300);
                //$('.login-wrappe, .overlay').fadeToggle('fast')
            }
        });
        $(document).on('click',
            '.forgot-password',
            function (event) {
                event.preventDefault();
                lawsVn.forgotPassword();
            });
        
        $('.xemthemdv-tieuchuan').on('click',
            function (e) {
                e.preventDefault();
                var item = $('.dv-tieuchuan').find('p:hidden');
                $(item).slice(0, 8).slideDown();
                //if (item.length === 0) {
                $(this).fadeOut('slow');
                //var childHeight = $('.rowsxemthem').outerHeight(true);
                //$(this).css('height', childHeight);
                //}
                $('.dv-tieuchuan').animate({
                    scrollTop: $(this).offset().top
                },
                    1500).css('overflow-y', 'scroll');
            });
       
        
        
        $(document).on('click',
            '.getcaptcha',
            function (event) {
                event.preventDefault();
                var id = $(this).data('id');
                var prefix = $(this).data('prefix');
                $('#' + id).lawsExists(function () {
                    lawsVn.getCaptcha(id, prefix);
                });
            });
       
        $(document).on('click',
            '.btn-submit',
            function (event) {
                event.preventDefault();
                $(this).closest('form').submit();
            });
        
        $(document).on('click',
            '.icondel.dateFrom',
            function (event) {
                event.preventDefault();
                $('input[type="hidden"][name="DateFrom"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val('');
                    $('#DateFrom').val('');
                    $('input[type="hidden"][name="DateFrom"]', $('#SearchFormV4')).lawsExists(function () {
                        $(this).val('');
                    });
                    //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                    //lawsVn.ajaxEvents.ListOnCompleteV2('DateFrom', '');
                    $(this).closest('#SearchFormStatistic').submit();
                });
            });
        $(document).on('click',
            '.icondel.dateTo',
            function (event) {
                event.preventDefault();
                $('input[type="hidden"][name="DateTo"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val('');
                    $('#DateTo').val('');
                    $('input[type="hidden"][name="DateTo"]', $('#SearchFormV4')).lawsExists(function () {
                        $(this).val('');
                    });
                    $('.searchByIssueYear').lawsExists(function () {
                        var urlAjax = $(this).data('ajax-url'); console.log(urlAjax);
                        //console.log(lawsVn.updateQueryStringParameter(urlAjax, 'DateTo', ''));
                        $(this).data('ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateTo', ''));
                    });
                    //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                    //lawsVn.ajaxEvents.ListOnCompleteV2('DateTo', '');
                    $(this).closest('#SearchFormStatistic').submit();
                });
            });
        $(document).on('click', '.icondel.fieldId', function (event) {
            event.preventDefault();
            var id = $(this).attr("data-id");
            $('#SearchFormStatistic').lawsExists(function () {
                console.log(id);
                $('input[type="checkbox"][name="lFieldId"][value="' + id + '"]').prop('checked', false);
                $('input[type="hidden"][name="FieldId"][value="' + id + '"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="lFieldId"]', $('#SearchFormStatistic')).val('');
                $('select[name="FieldId"]', $('#SearchFormV4')).lawsExists(function () {
                    $(this)
                        .removeAttr('selected')
                        .find(':first')
                        .attr('selected', 'selected');
                });
                $(this).closest('#SearchFormStatistic').submit();
            });
        });
        $(document).on('click',
            '.icondel.docgroupId2',
            function (event) {
                event.preventDefault();
                $('input[type="hidden"][name="DocgroupId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val('');
                    $('input[type="radio"][name="rb-statistic-docgroup-rows"]').prop('checked', false);
                    $('input[type="hidden"][name="DocgroupName"]', $('#SearchFormStatistic')).val('');
                    //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                    //lawsVn.ajaxEvents.ListOnCompleteV2('FieldId', 0);
                    $(this).closest('#SearchFormStatistic').submit();
                });
            });
        $(document).on('click', '.icondel.organId', function (event) {
            event.preventDefault();
            var organId = $(this).attr("data-id");
            $('#SearchFormStatistic').lawsExists(function () {
                $(this).val(0);
                $('input[type="checkbox"][name="lOrganId"][value="' + organId + '"]').prop('checked', false);
                $('input[type="hidden"][name="OrganName"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="lOrganId"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="OrganId"]', $('#SearchFormStatistic')).val('');
                $('select[name="OrganId"]', $('#SearchFormV4')).lawsExists(function () {
                    $(this)
                        .removeAttr('selected')
                        .find(':first')
                        .attr('selected', 'selected');
                });
                $(this).closest('#SearchFormStatistic').submit();
            });
        });
        
        $(document).on('click', '.icondel.dateFrom', function (event) {
            event.preventDefault();
            $('#SearchFormStatistic').lawsExists(function () {
                $(this).val(0);
                $('#DateFrom').val('');
                $('input[type="hidden"][name="dateFrom"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="SearchByTime"]', $('#SearchFormStatistic')).val('0');
                $('.linkSearchByEffectStatus').lawsExists(function () {
                    var urlAjax = $(this).data('ajax-url');
                    $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateFrom', ''));
                });
                $('.linkSearchByDocGroup').lawsExists(function () {
                    var urlAjax = $(this).data('ajax-url');
                    $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateFrom', ''));
                });
                $('.linkSearchByOrgan').lawsExists(function () {
                    var urlAjax = $(this).data('ajax-url');
                    $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateFrom', ''));
                });
                $('.linkSearchByIssueYear').lawsExists(function () {
                    var urlAjax = $(this).data('ajax-url');
                    $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateFrom', ''));
                });
                $(this).closest('#SearchFormStatistic').submit();
            });
        });
        $(document).on('click',
            '.icondel.dateTo',
            function (event) {
                event.preventDefault();
                $('input[type="hidden"][name="dateTo"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(0);
                    $('#DateTo').val('');
                    $('input[type="hidden"][name="dateTo"]', $('#SearchFormStatistic')).val('');
                    $('input[type="hidden"][name="SearchByTime"]', $('#SearchFormStatistic')).val('0');
                    $('.linkSearchByEffectStatus').lawsExists(function () {
                        var urlAjax = $(this).data('ajax-url');
                        $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateTo', ''));
                    });
                    $('.linkSearchByDocGroup').lawsExists(function () {
                        var urlAjax = $(this).data('ajax-url');
                        $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateTo', ''));
                    });
                    $('.linkSearchByOrgan').lawsExists(function () {
                        var urlAjax = $(this).data('ajax-url');
                        $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateTo', ''));
                    });
                    $('.linkSearchByIssueYear').lawsExists(function () {
                        var urlAjax = $(this).data('ajax-url');
                        $(this).attr('data-ajax-url', lawsVn.updateQueryStringParameter(urlAjax, 'DateTo', ''));
                    });
                    $(this).closest('#SearchFormStatistic').submit();
                });
            });
        $(document).on('click', '.icondel.effectStatusId', function (event) {
            event.preventDefault();
            var effectStatusId = $(this).attr("data-id");
            $('#SearchFormStatistic').lawsExists(function () {
                $(this).val(0);
                $('input[type="checkbox"][name="lEffectStatusId"][value="' + effectStatusId + '"]').prop('checked', false);
                $('input[type="hidden"][name="EffectStatusName"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="EffectStatusId"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="lEffectStatusId"]', $('#SearchFormStatistic')).val('');
                $('select[name="EffectStatusId"]', $('#SearchFormV4')).lawsExists(function () {
                    $(this)
                        .removeAttr('selected')
                        .find(':first')
                        .attr('selected', 'selected');
                });
                $(this).closest('#SearchFormStatistic').submit();
            });
        });
        $(document).on('click', '.icondel.docGroupId', function (event) {
            event.preventDefault();
            var docGroupId = $(this).attr("data-id");
            $('#SearchFormStatistic').lawsExists(function () {
                $(this).val(0);
                $('input[type="checkbox"][name="lDocGroupId"][value="' + docGroupId + '"]').prop('checked', false);
                $('input[type="hidden"][name="DocGroupName"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="lDocGroupId"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="DocGroupId"]', $('#SearchFormStatistic')).val('');
                $(this).closest('#SearchFormStatistic').submit();
            });
        });
        $(document).on('click',
            '.icondel.provinceId',
            function (event) {
                event.preventDefault();
                $('input[type="hidden"][name="ProvinceId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(0);
                    $('input[type="radio"][name="rb-statistic-province-rows"]').prop('checked', false);
                    $('input[type="hidden"][name="ProvinceName"]', $('#SearchFormStatistic')).val('');
                    //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                    //awsVn.ajaxEvents.ListOnCompleteV2('DocGroupId', 0);
                    $(this).closest('#SearchFormStatistic').submit();
                });
            });
        $(document).on('click', '.icondel.docTypeId', function (event) {
            event.preventDefault();
            var docTypeId = $(this).attr("data-id");
            console.log(docTypeId);
            $('#SearchFormStatistic').lawsExists(function () {
                $(this).val(0);
                $('input[type="checkbox"][name="lDocTypeId"][value="' + docTypeId + '"]').prop('checked', false);
                $('input[type="hidden"][name="DocTypeName"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="DocTypeId"]', $('#SearchFormStatistic')).val('');
                $('input[type="hidden"][name="lDocTypeId"]', $('#SearchFormStatistic')).val('');
                $('select[name="DocTypeId"]', $('#SearchFormV4')).lawsExists(function () {
                    $(this)
                        .removeAttr('selected')
                        .find(':first')
                        .attr('selected', 'selected');
                });
                $(this).closest('#SearchFormStatistic').submit();
            });
        });
        $(document).on('click', '.icondel.year', function (event) {
            event.preventDefault();
            var year = $(this).attr("data-id");
            $('#SearchFormStatistic').lawsExists(function () {
                $(this).val(0);
                $('input[type="checkbox"][name="lYear"][value="' + year + '"]').prop('checked', false);
                $(this).closest('#SearchFormStatistic').submit();
            });
        });
        
       
      
        
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-field-rows222"]',
            function () {
                var id = $(this).data('id'), name = $(this).data('name');
                $('input[type="hidden"][name="FieldId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                $('input[type="hidden"][name="FieldName"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(name);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('FieldId', id);
                $(this).closest('#SearchFormStatistic').submit();
            });
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-doctype-rows"]',
            function () {
                var id = $(this).data('id'), name = $(this).data('name');
                $('input[type="hidden"][name="DocTypeId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                $('input[type="hidden"][name="DocTypeName"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(name);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('DocTypeId', id);
                $(this).closest('#SearchFormStatistic').submit();
            });
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-province-rows"]',
            function () {
                var id = $(this).data('id'), name = $(this).data('name');
                $('input[type="hidden"][name="ProvinceId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                $('input[type="hidden"][name="ProvinceName"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(name);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('DocTypeId', id);
                $(this).closest('#SearchFormStatistic').submit();
            });
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-docgroup-rows"]',
            function () {
                var id = $(this).data('id'), name = $(this).data('name');
                $('input[type="hidden"][name="DocGroupId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                $('input[type="hidden"][name="DocGroupName"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(name);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('DocGroupId', id);
                $(this).closest('#SearchFormStatistic').submit();
            });
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-effectstatus-rows"]',
            function () {
                var id = $(this).data('id'), name = $(this).data('name');
                $('input[type="hidden"][name="EffectStatusId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                $('input[type="hidden"][name="EffectStatusName"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(name);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('EffectStatusId', id);
                $(this).closest('#SearchFormStatistic').submit();
            });
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-organ-rows"]',
            function () {
                var id = $(this).data('id'), name = $(this).data('name');
                $('input[type="hidden"][name="OrganId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                $('input[type="hidden"][name="OrganName"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(name);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('OrganId', id);
                $(this).closest('#SearchFormStatistic').submit();
            });
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-DraftingAgency-rows"]',
            function () {
                var id = $(this).data('id'), name = $(this).data('name');
                $('input[type="hidden"][name="DraftingAgencyId"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                $('input[type="hidden"][name="DraftingAgencyName"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(name);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('OrganId', id);
                $(this).closest('#SearchFormStatistic').submit();
            });
        $(document).on('click',
            'input[type="radio"][name="rb-statistic-year-rows"]',
            function () {
                var id = $(this).data('id');
                $('input[type="hidden"][name="Year"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(id);
                });
                //lawsVn.ajaxEvents.pageIndex = 1; //reset page
                //lawsVn.ajaxEvents.ListOnCompleteV2('Year', id);
                $(this).closest('#SearchFormStatistic').submit();
            });

        $(document).on('click',
            '.label-radio111',
            function (event) {
                event.preventDefault();
                $('.rows-pay').removeClass('active');
                $('.radio-111').find('.dash-o').remove();
                var radio = $(this).find('.radio-111'),
                    id = radio.data('id'),
                    item = radio.data('item');
                if (typeof item != 'undefined') {
                    $('.radio-111[data-id="' + id + '"][data-item="' + item + '"]').append('<i class="dash-o"></i>');
                    if (item > 0 || id == 0 && item == 0)
                        $('.radio-111[data-id=' + id + '][data-item="' + item + '"]').closest('.rows-pay')
                            .addClass('active');
                    else
                        radio.closest('.rows-pay').addClass('active');
                } else {
                    $('.radio-111[data-id="' + id + '"]').append('<i class="dash-o"></i>');
                    $('.radio-111[data-id=' + id + ']').closest('.rows-pay').addClass('active');
                }
                $('.transfer-item').lawsExists(function () {
                    $(this).hide();
                    $($('.transfer-item')[id]).show();
                });
                $('.payment-method-items').lawsExists(function () {
                    if (typeof item != 'undefined') {
                        $('#TransferInformation').lawsExists(function () {
                            if (item == 0) {
                                $(this).text(lawsVn.Resource.getMessages('TransferInformation'));
                            } else
                                $(this).text(lawsVn.Resource.getMessages('CommentInformation'));
                        });
                        $(this).hide();
                        $($('.payment-method-items')[item]).show();
                    }
                });
            });

        
        $(document).on('change',
            '#ddlListByFieldV2',
            function (event) {
                event.preventDefault();
                var url = $(this).find(':selected').attr('data-url');
                if (typeof url != undefined && url.length > 0)
                    window.location.href = url;
            });

        $(document).on('click', '#ddlProvinces', function () {
            $('#loading').fadeIn('normal');
            var url = $(this + ' a').attr('href');
            if (typeof url != undefined && url.length > 0)
                window.location.href = url;
        });
        $(document).on('change',
            '#ddlListByProvinceV2',
            function (event) {
                event.preventDefault();
                var url = $(this).find(':selected').attr('data-url');
                if (typeof url != undefined && url.length > 0)
                    window.location.href = url;
            });
        $(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',
            '.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('click',
            '.tab-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',
            '.myDropdownTCVN',
            function (e) {
                e.preventDefault();
                var fieldId = $(this).data('id');
                $('.myDropdownTCVN').removeClass('active');
                $(this).addClass('active');
                lawsVn.CustomerInterFaceTCVNC(fieldId);
                var element = document.getElementById("myDropdown_myluat2");
                element.classList.remove("show_myluat");
            });
        $(document).on('change',
            'select[name="OrderByClause"]',
            function (event) {
                event.preventDefault();
                var form = $('#SearchFormStatistic');
                form.find('input[type=hidden][name=OrderBy]').val($(this).val());
                form.trigger('submit');
            });
        $(document).on('change',
            '#ddlFieldTCVN',
            function (event) {
                event.preventDefault();
                var fieldId = $(this).val();
                $('.fieldIdTCVN').removeClass('active');
                lawsVn.CustomerInterFaceTCVNC(fieldId);
            });
        $(document).on('change',
            'select[name="OrderBy"]',
            function (event) {
                event.preventDefault();
                var orderBy = $(this).val();
                $('input[type="hidden"][name="OrderBy"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(orderBy);
                    $(this).closest('#SearchFormStatistic').submit();
                });
            });
        $(document).on('change',
            'select[name="SearchByTime"]',
            function (event) {
                event.preventDefault();
                var orderBy = $(this).val();
                $('input[type="hidden"][name="SearchByTime"]', $('#SearchFormStatistic')).lawsExists(function () {
                    $(this).val(orderBy);
                    $(this).closest('#SearchFormStatistic').submit();
                });
            });
        $(document).on('click',
            '.btn-close',
            function () {
                $(this).closest('.ui-dialog-content').dialog('close');
                return false;
            });
       
        $('.lawAdvs a').lawsExists(function () {
            var img = $(this).find('img');
            img.hover(lawsVn.swapImageUrl);
        });
        
        //tim kiem: đưa kết quả chứa từ khóa lên đầu
        $('.row-first-news').lawsExists(function () {
            //lawsVn.search.prioritizeKeyword();
        });

        $('.thugon').off('click').on('click',
            function (event) {
                event.preventDefault();
                $('table.table-tk-boder').find('tr.row-first-news-tk-boder').not('.title').slideToggle();
            }).toggle(function () {
                $(this).html(
                    'Hiện gợi ý tìm kiếm <img class="thugon-img" alt="thugon" src="/Assets/Images/thu-gon-tk.png">');
            },
                function () {
                    $(this).html('Thu gọn <img class="thugon-img" alt="thugon" src="/Assets/Images/thu-gon-tk.png">');
                });
        //lawsVnConfig.arrAdvs = advsite_240;
        //if (typeof advsite_240 !== 'undefined') {
        //    $('#partnerLink').lawsExists(function() {
        //        advsite_240 = advsite_240.replace(new RegExp('quang-cao-right', 'g'), "col-mb-4 lawAdvs");
        //        var tmp = $(advsite_240).slice($(advsite_240));
        //        for (var i = 0; i < 8; i++) {
        //            var index = Math.floor(Math.random() * tmp.length);
        //            var removed = tmp.splice(index, 1);
        //            //if (i === 3 || i === 7) $(removed[0]).css('margin-right', '0');
        //            $(this).append(removed[0]);
        //        }
        //    });
        //}
       

        $('.tab-docgroupid').off('click').on('click',
            function (event) {
                event.preventDefault();
                $('.tab-docgroupid').removeClass('active');
                $(this).addClass('active');
                var id = $(this).data('id');
                var docGroupId = $('input[type="hidden"][id="DocGroupId"]');
                $('select[name="LanguageId"] option')
                    .removeAttr('selected')
                    .filter('[value=0]')
                    .attr('selected', true);
                switch (id) {
                    case 0:
                        docGroupId.val(0); //Tất cả
                        $('select[name="DocTypeId"] option')
                            .removeAttr('selected')
                            .filter('[value=0]')
                            .attr('selected', true);
                        break;
                    case 1:
                        docGroupId.val(1); //VBPL
                        $('select[name="DocTypeId"] option')
                            .removeAttr('selected')
                            .filter('[value=0]')
                            .attr('selected', true);
                        break;
                    case 2:
                        docGroupId.val(2); //UBND
                        break;
                    case 6:
                        docGroupId.val(6); //Công văn
                        break;
                    case 3:
                        docGroupId.val(1); //Vb tiếng anh
                        $('select[name="LanguageId"] option')
                            .removeAttr('selected')
                            .filter('[value=2]')
                            .attr('selected', true);
                        $('select[name="DocTypeId"] option')
                            .removeAttr('selected')
                            .filter('[value=0]')
                            .attr('selected', true);
                        break;
                    default:
                        docGroupId.val(3); //TCVN
                        $('select[name="DocTypeId"] option')
                            .removeAttr('selected')
                            .filter('[value=0]')
                            .attr('selected', true);
                        break;
                }
                $(this).closest('form').submit();
            });
        
        $(document).on('click',
            '.customername-check',
            function (event) {
                event.preventDefault();
                $('#CustomerName').lawsExists(function () {
                    if ($(this).val().length === 0) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách vui lòng nhập tên truy cập cần kiểm tra.']
                        });
                        return false;
                    }
                    $.lawsAjax({
                        url: lawsVn.virtualPath('/Ajax/CustomerNameCheck'),
                        type: 'Post',
                        data: { customerName: $(this).val() },
                        success: function (resp) {
                            if (resp.Message != null && resp.Message.length > 0) {
                                $().lawsDialog({
                                    dialogClass: 'lawsVnDialogTitle',
                                    messages: [resp.Message]
                                });
                            }
                        }
                    });
                });
                return false;
            });

      
        $(document).on('click',
            '.radio input[type="radio"][class="Others"]',
            function () {
                var fieldId = $(this).data('id');
                $(this).closest('.radio').find('a').trigger('click');
                //$('#rbOthersId' + fieldId).lawsExists(function () {
                //    $(this).click();
                //});
            });
        
        $(document).on('click',
            '.btn-reset',
            function (event) {
                event.preventDefault();
                lawsVn.ResetForm($(this).closest('form'));
            });

        $('.UncheckSearchAll').off('click').on('click',
            function (e) {
                e.preventDefault();
                lawsVnConfig.DocGroupId = 0;
                lawsVnConfig.FieldId = 0;
                lawsVnConfig.EffectStatusId = 0;
                lawsVnConfig.DocTypeId = 0;
                lawsVnConfig.OrganId = 0;
                lawsVnConfig.Year = 0;
                lawsVn.search.start();
                $('input[id^="DocGroupId_"]', $('#radio_DocGroupId')).prop('checked', false);
                $('#nhomvanban').empty().removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="FieldId_"]', $('#radio_FieldId')).prop('checked', false);
                $('input[id^="FieldId_"]', $('#radio_FieldId_Tooltip')).prop('checked', false);
                $('#linhvuctracuu').empty().removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="EffectStatusId_"]', $('#radio_EffectStatusId')).prop('checked', false);
                $('#trangthaihieuluc').empty().removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="DocTypeId_"]', $('#radio_DocTypeId')).prop('checked', false);
                $('input[id^="DocTypeId_"]', $('#radio_DocTypeId_Tooltip')).prop('checked', false);
                $('#loaivanban').empty().removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="OrganId_"]', $('#radio_OrganId')).prop('checked', false);
                $('input[id^="OrganId_"]', $('#radio_OrganId_Tooltip')).prop('checked', false);
                $('#coquanbanhanh').empty().removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="Year_"]', $('#radio_Year')).prop('checked', false);
                $('#nambanhanh').empty().removeClass('item-kqtk').addClass('item-kqtk-noitem');
                lawsVn.showResultsFilterBy();
            });

        $('#radio_DocGroupId').on('change',
            '.DocGroupIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.DocGroupId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var docGroupName = label.attr('title');
                var parrent = $('#nhomvanban');
                var html = '';
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    docGroupName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-nhomvanban" title="Xóa điều kiện lọc theo nhóm văn bản: ' +
                    docGroupName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
            });

        $('#radio_FieldId').on('change',
            '.FieldIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.FieldId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var fieldName = label.attr('title');
                var parrent = $('#linhvuctracuu');
                var html = '';
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    fieldName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-linhvuctracuu" title="Xóa điều kiện lọc theo lĩnh vực tra cứu: ' +
                    fieldName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
                $('select[id="ddlFieldId"] option').removeAttr('selected').filter('[value=0]').attr('selected', true);
            });

        $('#radio_FieldId_Tooltip').on('change',
            '.FieldIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.FieldId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var fieldName = label.attr('title');
                var parrent = $('#linhvuctracuu');
                var html = '';
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    fieldName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-linhvuctracuu" title="Xóa điều kiện lọc theo lĩnh vực tra cứu: ' +
                    fieldName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
                $('select[id="ddlFieldId"] option').removeAttr('selected').filter('[value=0]').attr('selected', true);
            });

        $('#radio_EffectStatusId').on('change',
            '.EffectStatusIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.EffectStatusId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var effectStatusName = label.attr('title');
                var parrent = $('#trangthaihieuluc');
                var html = '';
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    effectStatusName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-trangthaihieuluc" title="Xóa điều kiện lọc theo trạng thái hiệu lực: ' +
                    effectStatusName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
                $('select[id="ddlEffectStatusId"] option').removeAttr('selected').filter('[value=0]')
                    .attr('selected', true);
            });

        $('#radio_DocTypeId').on('change',
            '.DocTypeIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.DocTypeId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var docTypeName = label.attr('title');
                var parrent = $('#loaivanban');
                var html = '';
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    docTypeName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-loaivb" title="Xóa điều kiện lọc theo loại văn bản: ' +
                    docTypeName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
                $('select[id="ddlDocTypeId"] option').removeAttr('selected').filter('[value=0]').attr('selected', true);
            });

        $('#radio_DocTypeId_Tooltip').on('change',
            '.DocTypeIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.DocTypeId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var docTypeName = label.attr('title');
                var parrent = $('#loaivanban');
                var html = '';
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    docTypeName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-loaivb" title="Xóa điều kiện lọc theo loại văn bản: ' +
                    docTypeName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
                $('select[id="ddlDocTypeId"] option').removeAttr('selected').filter('[value=0]').attr('selected', true);
            });

        $('#radio_OrganId').on('change',
            '.OrganIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.OrganId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var organName = label.attr('title');
                var parrent = $('#coquanbanhanh');
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                var html = '';
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    organName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-cqbh" title="Xóa điều kiện lọc theo cơ quan ban hành: ' +
                    organName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
            });

        $('#radio_OrganId_Tooltip').on('change',
            '.OrganIdS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.OrganId = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var organName = label.attr('title');
                var parrent = $('#coquanbanhanh');
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                var html = '';
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    organName +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-cqbh" title="Xóa điều kiện lọc theo cơ quan ban hành: ' +
                    organName +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
            });

        $('#radio_Year').on('change',
            '.YearS',
            function (e) {
                e.preventDefault();
                var self = $(this);
                lawsVnConfig.Year = self.val();
                lawsVn.search.start();
                var label = self.closest('.radio').find('label');
                var year = label.attr('title');
                var parrent = $('#nambanhanh');
                parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
                var html = '';
                html += '<div class="item-sub-qktk">' +
                    '<span class="texttk" > ' +
                    year +
                    '</span >' +
                    '<a href="#" id="xoa-dk-loc-nambanhanh" title="Xóa điều kiện lọc theo năm ban hành: ' +
                    year +
                    '" class="xoa"><img alt="xóa" src="' +
                    lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                    '"></a>' +
                    '</div>';
                parrent.html(html);
                $('.resultsFilterBy').show();
            });

        $(document).on('click',
            '#xoa-dk-loc-nhomvanban',
            function (event) {
                event.preventDefault();
                lawsVnConfig.DocGroupId = 0;
                lawsVn.search.start();
                var parrent = $('#nhomvanban');
                parrent.removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="DocGroupId_"]', $('#radio_DocGroupId')).prop('checked', false);
                parrent.html('');
                lawsVn.showResultsFilterBy();
            });

        $(document).on('click',
            '#xoa-dk-loc-linhvuctracuu',
            function (event) {
                event.preventDefault();
                lawsVnConfig.FieldId = 0;
                lawsVn.search.start();
                var parrent = $('#linhvuctracuu');
                parrent.removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="FieldId_"]', $('#radio_FieldId')).prop('checked', false);
                $('input[id^="FieldId_"]', $('#radio_FieldId_Tooltip')).prop('checked', false);
                parrent.html('');
                lawsVn.showResultsFilterBy();
            });

        $(document).on('click',
            '#xoa-dk-loc-trangthaihieuluc',
            function (event) {
                event.preventDefault();
                lawsVnConfig.EffectStatusId = 0;
                lawsVn.search.start();
                var parrent = $('#trangthaihieuluc');
                parrent.removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="EffectStatusId_"]', $('#radio_EffectStatusId')).prop('checked', false);
                parrent.empty();
                lawsVn.showResultsFilterBy();
            });

        $(document).on('click',
            '#xoa-dk-loc-loaivb',
            function (event) {
                event.preventDefault();
                lawsVnConfig.DocTypeId = 0;
                lawsVn.search.start();
                var parrent = $('#loaivanban');
                parrent.removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="DocTypeId_"]', $('#radio_DocTypeId')).prop('checked', false);
                $('input[id^="DocTypeId_"]', $('#radio_DocTypeId_Tooltip')).prop('checked', false);
                parrent.empty();
                lawsVn.showResultsFilterBy();
            });

        $(document).on('click',
            '#xoa-dk-loc-cqbh',
            function (event) {
                event.preventDefault();
                lawsVnConfig.OrganId = 0;
                lawsVn.search.start();
                var parrent = $('#coquanbanhanh');
                parrent.removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="OrganId_"]', $('#radio_OrganId')).prop('checked', false);
                $('input[id^="OrganId_"]', $('#radio_OrganId_Tooltip')).prop('checked', false);
                parrent.empty();
                lawsVn.showResultsFilterBy();
            });

        $(document).on('click',
            '#xoa-dk-loc-nambanhanh',
            function (event) {
                event.preventDefault();
                lawsVnConfig.Year = 0;
                lawsVn.search.start();
                var parrent = $('#nambanhanh');
                parrent.removeClass('item-kqtk').addClass('item-kqtk-noitem');
                $('input[id^="Year_"]', $('#radio_Year')).prop('checked', false);
                parrent.empty();
                lawsVn.showResultsFilterBy();
            });

        $('#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('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',
            '#checkbox_All',
            function () {
                $(".mail-content,.mail-content2 input:checkbox").prop('checked', $(this).prop("checked"));
            });
        $(document).on('change',
            'input[type=checkbox][id^="chkFieldId_"]',
            function () {
                if (this.checked) {
                    var label = $(this).prop('labels');
                    $('#FieldSelected').append($('<div id="field-selected-' + this.value + '" class="item-ms3"><span class= "title-list-vbqt"> ' +
                        $(label).text() +
                        '</span> <a href="#" data-id="' + this.value + '" title="Xóa lĩnh vực đã chọn" class="xoa-linh-vuc-chon del2"><img src="/assets/images/user/xoa.png" alt="xoa" class="mCS_img_loaded" /></a></div>'));
                } else {
                    $('#field-selected-' + this.value).remove();
                }
            });
        $(document).on('click',
            '.xoa-linh-vuc-chon',
            function (e) {
                e.preventDefault();
                var me = $(this), id = me.data('id');
                me.closest('.item-ms3').remove();
                $('input[type="checkbox"][id="chkFieldId_' + id + '"]').removeAttr('checked');
            });
        $(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();
            });
        $('.time-mixvb-left').hover(function (e) {
            var idx = $(this).index();
            var me = $(this), el = me.find('.a-time-mixvb-left'),
                parent = me.closest('.time-mixvb '),
                outofdate = el.data('outofdate'),
                serviceId = el.data('serviceid'),
                role = el.data('role'),
                login = el.data('login'), popup;
            if (typeof role !== 'undefined' || typeof login !== 'undefined' || typeof outofdate !== 'undefined') {
                popup = parent.find('.tooltip-boxs');
                var pos = $(this).position();
                var width = $(this).outerWidth();
                var height = $(this).outerHeight();
                if (typeof login !== 'undefined') {
                    if (popup.length > 0) {
                        popup.show();
                    } else {
                        me.append('<div class="tooltip-boxs fixwg">' +
                            '<div class= "form-login-mixvb">' +
                            'Quý khách vui lòng <a href="#" data-toggle-target="#login-form-target" class="form-login-color login-action"> Đăng nhập</a> tài khoản quyền <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" target="_blank" class="form-login-color"> Nâng cao</a> để xem chi tiết.' +
                            '<br> Nếu quý khách 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="text-decoration: none !important;">tại đây</a>!</div>' +
                            '</div>');
                    }
                } else if (typeof role !== 'undefined' || typeof outofdate !== 'undefined') {
                    if (popup.length > 0) {
                        popup.css('visibility', 'visible');
                    } else {
                        if (typeof outofdate !== 'undefined') {
                            if (serviceId == 23) {
                                me.append('<div class="tooltip-boxs fixwg">' +
                                    '<div class="form-login-mixvb" >' +
                                    'Tài khoản của Quý khách đã hết hạn vào ngày ' +
                                    outofdate +
                                    '.<br/>Quý khách vui lòng gia hạn gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" title="Tra cứu Nâng cao" target="_blank" class="cl67942 bold">Nâng cao</a> để tiếp tục sử dụng phần mềm. </div>' +
                                    '</div>');
                            } else {
                                me.append('<div class="tooltip-boxs fixwg">' +
                                    '<div class="form-login-mixvb" >' +
                                    'Tài khoản của Quý khách đã hết hạn vào ngày ' +
                                    outofdate +
                                    '.<br/>Quý khách vui lòng nâng cấp gói <a href="/goi-dich-vu/goi-tra-cuu-nang-cao.html" title="Tra cứu Nâng cao" target="_blank" class="cl67942 bold">Nâng cao</a> để tiếp tục sử dụng phần mềm. </div>' +
                                    '</div>');
                            }
                        } else {
                            me.append('<div class="tooltip-boxs fixwg">' +
                                '<div class="form-login-mixvb" >' +
                                'Tài khoản Quý khách bị giới hạn xem nội dung này. 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"> Nâng cao</a>.' +
                                '</div>' +
                                '</div>');
                        }
                    }
                }
                popup.css({
                    display: 'block',
                    visibility: 'visible',
                    //position: "absolute",
                    top: pos.top + height + "px",
                    //left: pos.left - width + "px",
                    zIndex: 9999
                });
            }
        }, function (e) {
                $(this).closest('.time-mixvb ').find('.tooltip-boxs').css({
                    display: 'none',
                    visibility: 'hidden'
                });
        });

        $(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');
                                }
                            }
                        ]
                    });
                }
            });
        $(document).on('click',
            '.resetCheckboxField',
            function (event) {
                event.preventDefault();
                $('input[type="checkbox"][name="FieldId"]').prop("checked", false);
                $('div[id^=field-selected-]').remove();
            });
        $(document).on('click',
            '.icon-e-remove-2lvn',
            function (e) {
                e.preventDefault();
                var me = $(this);
                if (!me.hasClass('dong-nd-bi-suadoi') && !me.hasClass('nd-duoc-hd-thugon') && !me.hasClass('yeucaubosungvb') && !me.hasClass('btn-hea-cpas') && !me.hasClass('btn-hea-cpas2') && !me.hasClass('order-tcvn')) {
                    $('.input-on-keypress').lawsExists(function () {
                        $(this).val('');
                        me.remove();
                    });
                    $('.inputsearch-keypress').lawsExists(function () {
                        $(this).val('');
                        me.remove();
                    });
                    $('.inputFaqSearch-keypress').lawsExists(function () {
                        $(this).val('');
                        me.remove();
                    });
                    $('.input').lawsExists(function () {
                        $(this).val('');
                        me.remove();
                    });
                }
                if (me.hasClass('yeucaubosungvb')) {
                    $('.wrapper-yeucaubosungvb').lawsExists(function () {
                        $(this).show();
                    });
                    $('.thongbao-send').lawsExists(function () {
                        $(this).closest('.popup-wrapper').css('width', '600px');
                        $(this).empty();
                    });
                }
            });
        $('input.input-on-keypress').on('keypress keyup blur',
            function (e) {
                var me = $(this), root = $(this).closest('.tracuu-form'), close = root.find('.icon-e-remove-2lvn');
                if (me.val().length > 0) {
                    if (close.length == 0)
                        root.append('<span class="ic icon-e-remove-2lvn ic-x2"></span>');
                } else {
                    close.remove();
                }
            });
        $('input.inputsearch-keypress').on('keypress keyup blur',
            function (e) {
                var me = $(this), root = $(this).closest('.tracuu-form'), close = root.find('.icon-e-remove-2lvn');
                if (me.val().length > 0) {
                    if (close.length == 0)
                        root.append('<span class="ic icon-e-remove-2lvn ic-x"></span>');
                } else {
                    close.remove();
                }
            });
        $('input.inputFaqSearch-keypress').on('keypress keyup blur',
            function (e) {
                var me = $(this), root = $(this).parent();
                var close = root.find('.icon-e-remove-2lvn');
                if (me.val().length > 0) {
                    if (close.length == 0)
                        root.append('<span class="ic icon-e-remove-2lvn icx"></span>');
                } else {
                    close.remove();
                }
            });
        $('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');
                //$('option', $(this)).each(function (index) {
                //    if ($(this).is(":selected") && $(this).val() > 0) {
                //        $(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 },
                                    15 * 60);
                            } else {
                                respCustomerDoc.documentSaved++;
                                luatVietnamStore.setItem(
                                    'luatvietnam_customerdocs_' +
                                    resp.Data.DocId +
                                    '_' +
                                    resp.Data.CustomerId +
                                    '_' +
                                    resp.Data.LanguageId,
                                    { 'documentSaved': respCustomerDoc.documentSaved, 'hasTrackedDocumentEffect': respCustomerDoc.hasTrackedDocumentEffect },
                                    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 },
                                    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 },
                                    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]
                            });
                        }
                        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 },
                                    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 },
                                    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',
            '#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 },
                                    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 },
                                    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',
            '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();
                $(this).closest('form').submit();
                $('.row-item.fix').lawsExists(function () {
                    $(this).css('color', '#222');
                });
            });
        $(document).on('change',
            'form .select-onchangeV2',
            function (event) {
                event.preventDefault();
                $('input[name="page"]').lawsExists(function () {
                    $(this).val(1);
                    lawsVn.ajaxEvents.pageIndex = 1; //reset page
                });
                lawsVn.ajaxEvents.showNumberOfResults = $(this).val();
                if (lawsVnConfig.resetParams == 1)
                    lawsVn.ajaxEvents.ListOnCompleteV2($(this).attr('name'),
                        $(this).val() == 0 ? '' : $(this).val(),
                        1);
                else lawsVn.ajaxEvents.ListOnCompleteV2($(this).attr('name'), $(this).val() == 0 ? '' : $(this).val());
                lawsVnConfig.resetParams = 0;
                $(this).closest('form').submit();
                $('.row-item.fix').lawsExists(function () {
                    $(this).css('color', '#222');
                });
            });
        $(document).on('change',
            'form .select-onchangeV3',
            function (event) {
                event.preventDefault();
                $(this).closest('form').submit();
            });
        $(document).on('change',
            'form .select-onchangeV4',
            function (event) {
                event.preventDefault();
                event.preventDefault();
                $('input[name="page"]').lawsExists(function () {
                    $(this).val(1);
                    lawsVn.ajaxEvents.pageIndex = 1; //reset page
                });
                lawsVn.ajaxEvents.showNumberOfResults = 12;
                $('select[name=ShowNumberOfResults] option:selected').lawsExists(function () {
                    lawsVn.ajaxEvents.showNumberOfResults = $(this).val();
                });
                if (lawsVnConfig.resetParams == 1)
                    lawsVn.ajaxEvents.ListOnCompleteV2($(this).attr('name'),
                        $(this).val() == 0 ? '' : $(this).val(),
                        1);
                else lawsVn.ajaxEvents.ListOnCompleteV2($(this).attr('name'), $(this).val() == 0 ? '' : $(this).val());
                lawsVnConfig.resetParams = 0;
                $(this).closest('form').submit();
            });
        $(document).on('change',
            '.select-onchangeV5',
            function () {
                var url = $(this).val();
                if (url) {
                    window.location = url;
                }
                return false;
            });
        $(document).on('change',
            'form .select-service-packages-onchange',
            function (event) {
                event.preventDefault();
                $('input[name="page"]').lawsExists(function () {
                    $(this).val(1);
                });
                $('input[name="typeChange"]').lawsExists(function () {
                    $(this).val(1);
                });
                $(this).closest('form').submit();
            });

        $(document).on('change',
            '.newslettergroup-onchange',
            function (event) {
                event.preventDefault();
                var id = $(this).val();
                if (id == 4 || id == 6) { //Đăng ký nhận tin văn bản mới: Tiếng Anh, Tiếng Việt và tiếng Anh
                    $('.newsLetterInfo').show();
                } else $('.newsLetterInfo').hide();
            });

        $(document).on('change',
            '.select-filterbyfield-onchange',
            function (event) {
                event.preventDefault();
                var fieldId = $(this).data('fieldid');
                var selectFieldId = $('#ddlFieldId option:selected').val();
                var effectStatusId = $('#ddlEffectStatusId option:selected').val();
                var effectStatusName = $('input[name="effectStatusName"]').val();
                var organsId = $('#ddlOrganId option:selected').val();
                var docTypesId = $('#ddlDocTypeId option:selected').val();
                if (selectFieldId > 0) {
                    fieldId = selectFieldId;
                }
                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/Docs_GetViewSearch'),
                    dataType: 'html',
                    data: {
                        fieldId: fieldId,
                        effectStatusId: effectStatusId,
                        effectStatusName: effectStatusName,
                        organId: organsId,
                        docTypeId: docTypesId
                    },
                    success: function (resp) {
                        $("#ListByField").html(resp);
                        var totalpage = $("#tblcontent").attr('data-totalpage');
                        var pageindex = $("#tblcontent").attr('data-pageindex');
                        var pageCount = $("#tblcontent").attr('data-pagecount');
                        if (totalpage === undefined) {
                            totalpage = 0;
                        }
                        if (pageindex === undefined) {
                            pageindex = 0;
                        }
                        if (pageindex <= 0) {
                            pageindex = 1;
                        }
                        var data = '';
                        if (pageCount > 0) {
                            data += "<span>Tìm thấy <strong> " +
                                totalpage +
                                " văn bản </strong>(" +
                                pageindex +
                                "/" +
                                pageCount +
                                " trang)";
                        } else data = "<span>Không tìm thấy kết quả.</strong>";
                        data += "</span>";
                        $("#txtnumberresultfound").html(data);
                    }
                });
            });

        $(document).on('change',
            'form .select-province-onchange',
            function (event) {
                event.preventDefault();
                $('select[name="DistrictId"]').html($('<option></option>').val(0).html('Quận / huyện'));
                $('select[name="WardId"]').html($('<option></option>').val(0).html('Phường / xã'));
                $('input[name="page"]').lawsExists(function () {
                    $(this).val(1);
                });
                $('select[name="DistrictId"]').load(
                    lawsVn.virtualPath('/Ajax/GetDistrictsByProvinceId?provinceId=' + $(this).val()),
                    function (resp, status, xhr) {
                        if (status == 'success') {
                            $(this).html(resp).promise().done(function () {
                                $(this).closest('form').submit();
                            });
                        }
                    });
            });

        $(document).on('change',
            'form .select-district-onchange',
            function (event) {
                event.preventDefault();
                $('input[name="page"]').lawsExists(function () {
                    $(this).val(1);
                });
                $('select[name="WardId"]').load(
                    lawsVn.virtualPath('/Ajax/GetWardsByDistrictId?districtId=' + $(this).val()),
                    function (resp, status, xhr) {
                        if (status == 'success') {
                            $(this).html(resp).promise().done(function () {
                                $(this).closest('form').submit();
                            });
                        }
                    });
            });

        $(document).on('change', 'input[type=file]:not(.d-none)', lawsVn.fileUpload);
        $(document).on('click',
            '#uploadAvatar',
            function (e) {
                e.preventDefault();
                $('#avatarFile').click();
            });
        $(document).on('click',
            '#MyLuatUploadAvatar',
            function (e) {
                e.preventDefault();
                $('#MyLuatAvatarFile').click();
            });
        $(document).on('click',
            '#MyLuatUploadCoverImage',
            function (e) {
                e.preventDefault();
                $('#MyLuatCoverImageFile').click();
            });

        $(document).on('drop dragover',
            function (e) {
                e.preventDefault();
            });
        $('#SignerName').on('focus',
            function () {
                var input = $(this);
                input.data('SignerIdValue', input.val());
            });
        $('#SignerName').on('blur',
            function () {
                var input = $(this);
                if (input.val().trim() == '0') {
                    input.val('');
                }
                if (input.val() != input.data('SignerIdValue')) {
                    if (input.val() == '') {
                        $('#SignerId').val(0);
                    }
                }
            });
        $('#SignerName').lawsExists(function () {
            $(this).autocomplete({
                minLength: 1,
                dataType: "json",
                async: false,
                cache: false,
                source: function (request, response) {
                    //var signers = new Array();
                    $('#SignerId').val(0);
                    $('#signer-message').text('');
                    var dataGetter = { signerName: request.term };
                    var url = lawsVn.virtualPath('/Ajax/AutocompleteSignerByName');
                    $.ajaxSetup({ cache: false, async: false });
                    $.lawsVnAjax(url,
                        'Get',
                        dataGetter,
                        function (data) {
                            var json = JSON.parse(data.jsonRetval);
                            if (json.length == 0)
                                $('#signer-message')
                                    .html(
                                        '<span class="text-danger field-validation-error"><span>Không tìm thấy người ký phù hợp.</span></span>');
                            response($.map(json,
                                function (item) {
                                    return {
                                        label: item.SignerName,
                                        val: item.SignerId
                                    }
                                }));
                            //for (var i = 0; i < json.length; i++) {
                            //signers[i] = { label: json[i].SignerName, id: json[i].SignerId };
                            //}
                        });
                    //response(signers); 
                },
                search: function () {
                    $(this).addClass('ui-autocomplete-loading');
                },
                open: function () { $(this).removeClass('ui-autocomplete-loading'); },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    $('#SignerId').val(ui.item.val);
                }
            });
        });

        $("#txtTNPL").autocomplete({
            minLength: 1,
            dataType: "json",
            async: false,
            cache: false,
            source: function (request, response) {
                //var signers = new Array();
                $('#LawTerminId').val(0);
                $('#signer-message').text('');
                var dataGetter = { lawterminName: request.term };
                var url = lawsVn.virtualPath('/Ajax/AutocompleteTNPLByName');
                $.ajaxSetup({ cache: false, async: false });
                $.lawsVnAjax(url,
                    'Get',
                    dataGetter,
                    function (data) {
                        var json = JSON.parse(data.jsonRetval);
                        if (json.length == 0)
                            $('#signer-message')
                                .html(
                                    '<span class="text-danger field-validation-error"><span>Không tìm thấy thuật ngữ pháp lý phù hợp.</span></span>');
                        response($.map(json,
                            function (item) {
                                return {
                                    label: item.TermName,
                                    val: item.LawTerminId
                                }
                            }));
                    });
            },
            search: function () {
                $(this).addClass('ui-autocomplete-loading');
            },
            open: function () { $(this).removeClass('ui-autocomplete-loading'); },
            focus: function () {
                return false;
            },
            select: function (event, ui) {
                $('#LawTerminId').val(ui.item.val);
            }
        });


        $('#cssmenu ul ul li:odd').addClass('odd');
        $('#cssmenu ul ul li:even').addClass('even');
        $(document).on('click',
            '#cssmenu > ul > li > a, .cssmenu > ul > li > a',
            function(e) {
                e.preventDefault();
                var parent_cssmenu = $(this).parent().parent().parent().parent().parent();
                if (parent_cssmenu.length) {
                    var cssmenu = parent_cssmenu.children().children();
                    cssmenu.each(function () {
                        var item_cssmenu = $(this);
                        item_cssmenu.find('.has-sub').removeClass('active');
                        item_cssmenu.find('.has-sub').first().children('ul').slideUp('normal');
                    });
                }
                $(this).closest('li').addClass('active');
                var checkElement = $(this).closest('li').find('ul').first();
                if (checkElement.length) {
                    if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                        $(this).closest('li').removeClass('active');
                        checkElement.slideUp('normal');
                    }
                    if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                        $('#cssmenu ul ul:visible').slideUp('normal');
                        checkElement.slideDown('normal', function () {
                            checkElement.css('overflow', 'visible');
                        });
                    }
                }
                if ($(this).closest('li').find('ul').children().length == 0) {
                    return true;
                } else {
                    return false;
                }
            });
        $(document).on('change',
            '#txtChangePage',
            function () {
                var newValue = parseInt($(this).val());
                if (isNaN(newValue) || newValue <= 0) {
                    newValue = 1;
                }
                $(this).val(newValue);
                lawsVn.ajaxEvents.pageIndex = newValue;
                $(this.form).submit();
            });

        $(document).on('change',
            '#txtChangeYear',
            function () {
                var newValue = parseInt($(this).val()), d = new Date();
                if (isNaN(newValue) || newValue <= 0) {
                    newValue = d.getFullYear();
                }
                $(this).val(newValue);
                if (newValue != d.getFullYear()) {
                    $('#monthBtin').val(1);
                }
                lawsVn.ajaxEvents.pageIndex = newValue;
                $(this.form).submit();
            });

        $(document).on('click',
            '#prevPage',
            function (event) {
                event.preventDefault();
                lawsVn.ajaxEvents.pageIndex = lawsVn.ajaxEvents.pageIndex > 1 ? lawsVn.ajaxEvents.pageIndex - 1 : 1;
                lawsVn.ajaxEvents.showNumberOfResults = $('#dllNumberOfResults option:selected').val();
                var newValue = $('#txtChangePage').val();
                $('#txtChangePage').val(parseInt(newValue) - 1);
                var $form = $(this).closest('form');
                $form.submit();
            });

        $(document).on('click',
            '#nextPage',
            function (event) {
                event.preventDefault();
                lawsVn.ajaxEvents.pageIndex++;
                lawsVn.ajaxEvents.showNumberOfResults = $('#dllNumberOfResults option:selected').val();
                var newValue = $('#txtChangePage').val();
                $('#txtChangePage').val(parseInt(newValue) + 1);
                var $form = $(this).closest('form');
                $form.submit();
            });
        $(document).on('click',
            '#prevDate',
            function (event) {
                event.preventDefault();
                var year = $('#txtChangeYear').val(),
                    month = $('#monthBtin').val(),
                    moment = year > 0 && month > 0 ? new Date(year + '/' + month + '/' + '1') : new Date(),
                    m = moment.getMonth();
                moment.setMonth(m - 1);
                $('#txtChangeYear').val(moment.getFullYear());
                $('#monthBtin').val(moment.getMonth() + 1);
                var $form = $(this).closest('form');
                $form.submit();
            });

        $(document).on('click',
            '#nextDate',
            function (event) {
                event.preventDefault();
                var year = $('#txtChangeYear').val(),
                    month = $('#monthBtin').val(),
                    moment = year > 0 && month > 0 ? new Date(year + '/' + month + '/' + '1') : new Date(),
                    m = moment.getMonth();
                moment.setMonth(m + 1);
                $('#txtChangeYear').val(moment.getFullYear());
                $('#monthBtin').val(moment.getMonth() + 1);
                var $form = $(this).closest('form');
                $form.submit();
            });
        //loadpage with full url
        $(document).on('click',
            '#prevPage1',
            function (event) {
                event.preventDefault();
                //lawsVn.ajaxEvents.pageIndex = lawsVn.ajaxEvents.pageIndex > 1 ? lawsVn.ajaxEvents.pageIndex - 1 : 1;
                lawsVn.ajaxEvents.showNumberOfResults = $('#dllNumberOfResults option:selected').val();
                var fieldId = $('#ddlListByFieldV2 option:selected').val();
                var keywords = $("input[name=keywords]").val();
                var orderBy = $('select[name="OrderBy"] option:selected').val();
                var page = parseInt($(".pagination-item.active").text()) - 1;
                var url = window.location.pathname;
                window.location.href = url + "?fieldId=" + fieldId + "&keywords=" + keywords + "&orderBy=" + orderBy + "&page=" + page;
            });
        $(document).on('click',
            '#nextPage1',
            function (event) {
                event.preventDefault();
                //lawsVn.ajaxEvents.pageIndex = lawsVn.ajaxEvents.pageIndex > 1 ? lawsVn.ajaxEvents.pageIndex - 1 : 1;
                lawsVn.ajaxEvents.showNumberOfResults = $('#dllNumberOfResults option:selected').val();
                var fieldId = $('#ddlListByFieldV2 option:selected').val();
                var keywords = $("input[name=keywords]").val();
                var orderBy = $('select[name="OrderBy"] option:selected').val();
                var page = parseInt($(".pagination-item.active").text()) + 1;
                var url = window.location.pathname;
                window.location.href = url + "?fieldId=" + fieldId + "&keywords=" + keywords + "&orderBy=" + orderBy + "&page=" + page;
            });
        $(document).on('click',
            '.loadurl',
            function (event) {
                event.preventDefault();
                var newValue = parseInt($(this).val())
                lawsVn.ajaxEvents.showNumberOfResults = $('#dllNumberOfResults option:selected').val();
                var fieldId = $('#ddlListByFieldV2 option:selected').val();
                var keywords = $("input[name=keywords]").val();
                var orderBy = $('select[name="OrderBy"] option:selected').val();
                var page = newValue;
                var url = window.location.pathname;
                window.location.href = url + "?fieldId=" + fieldId + "&keywords=" + keywords + "&orderBy=" + orderBy + "&page=" + page;
            });
    },
    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;
        }
    },
    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>');
        });
    },
    getFontSize: function (el) {
        var fs = $(el).css('font-size');
        if (!el.originalFontSize) el.originalFontSize = fs;
        return parseFloat(fs);
    },
    setFontSize: function (el, fact) {
        var section = el.find('*')
            .filter(
                function () {
                    return $(this).clone()
                        .children()
                        .remove()
                        .end()
                        .text().trim().length >
                        0;
                });
        section.each(function () {
            var newsize = fact ? lawsVn.getFontSize(this) * fact : this.originalFontSize;
            if (newsize >= 16 && newsize <= 35)
                if (newsize) $(this).css('cssText', 'font-size: ' + newsize + 'px !important;line-height:1.6 !important');
        });
    },
    supportAjaxUploadWithProgress: function() {
        return lawsVn.supportFileAPI() && lawsVn.supportAjaxUploadProgressEvents() && lawsVn.supportFormData();
    },
    supportFileAPI: function() {
        var fi = document.createElement('INPUT');
        fi.type = 'file';
        return 'files' in fi;
    },
    supportAjaxUploadProgressEvents: function() {
        var xhr = new XMLHttpRequest();
        return !!(xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
    },
    supportFormData: function() {
        return !!window.FormData;
    },
    toBase64: function (file, fileNameExt, callBack) {
        //file = file.files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            var dataImage = reader.result;
            if (['jpeg', 'jpg', 'png', 'gif', 'bmp'].indexOf(fileNameExt) != -1) {
                var maxWidth = 800;
                var maxHeight = 800;
                var image = new Image();
                image.src = dataImage;

                image.onload = function () {
                    var width = image.width;
                    var height = image.height;
                    var shouldResize = (width > maxWidth) || (height > maxHeight);
                    if (shouldResize) {
                        var newWidth;
                        var newHeight;

                        if (width > height) {
                            newHeight = height * (maxWidth / width);
                            newWidth = maxWidth;
                        } else {
                            newWidth = width * (maxHeight / height);
                            newHeight = maxHeight;
                        }

                        var canvas = document.createElement('canvas');

                        canvas.width = newWidth;
                        canvas.height = newHeight;

                        var context = canvas.getContext('2d');

                        context.drawImage(this, 0, 0, newWidth, newHeight);

                        dataImage = canvas.toDataURL(file.type);
                        callBack(file, dataImage);
                    }
                };
            }
            else callBack(file, dataImage);
        };
        reader.onerror = function (error) {
            console.log('Error: ', error);
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Quý khách vui lòng thử lại sau.'],
                showIcon: false
            });
        };
    },
    sendXHRequest: function (formData, uri, callback) {
        var xhr = new XMLHttpRequest(),
            progress = $('#progress_container_ku8ufw'),
            progressBar = $('#progress_bar_835j9x');
        progress.show();
        xhr.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);
        xhr.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);
        xhr.addEventListener('readystatechange', function (evt) {
            var status, responseText, readyState;

            try {
                readyState = evt.target.readyState;
                responseText = evt.target.responseText;
                status = evt.target.status;
            }
            catch (e) {
                return;
            }

            if (readyState == 4 && status == '200' && evt.target.responseText) {
                callback(status, responseText);
            }
        }, false);
        xhr.open('POST', uri, true);
        xhr.send(formData);
    },
    PaymentFormValidation: function () {
        $('form').lawsExists(function () {
            $('form').each(function (i, el) {
                if (typeof $(el).attr('id') != 'underfine' && $(el).attr('id') != 'NewsLetterEmailForm')
                    lawsVn.FormValidation(el);
            });
        });
    },
    PersonalIncomeTaxCalculator: function() {
        var tongthunhap = 0,
            songuoiphuthuoc = 0,
            giamtrugiacanhbanthan = 11000000,
            giamtrugiacanhnguoiphuthuoc = 0,
            tongcackhoanduocgiamtru = 0,
            thunhaptinhthuethunhapcanhan = 0,
            thuephainop = 0, tax = 0;
        $('input[name="tongthunhap"]', $('.tinhthuethunhapcanhan')).lawsExists(function () {
            tongthunhap = $(this).val().replace(/\./g, '');
            if (!$.isNumeric(tongthunhap)) {
                tongthunhap = 0;
            }
        });
        $('input[name="songuoiphuthuoc"]', $('.tinhthuethunhapcanhan')).lawsExists(function () {
            songuoiphuthuoc = $(this).val();
            if (!$.isNumeric(songuoiphuthuoc)) {
                songuoiphuthuoc = 0;
            }
        });
        if (songuoiphuthuoc > 0) {
            giamtrugiacanhnguoiphuthuoc = songuoiphuthuoc * 4400000;
        }
        tongcackhoanduocgiamtru = giamtrugiacanhbanthan + giamtrugiacanhnguoiphuthuoc;
        thunhaptinhthuethunhapcanhan = tongthunhap - tongcackhoanduocgiamtru;
        if (thunhaptinhthuethunhapcanhan > 0) {
            tax = thunhaptinhthuethunhapcanhan;
            if (tax <= 5000000) {
                thuephainop = tax * 5 / 100;
            }
            else if (tax > 5000000 && tax <= 10000000) {
                thuephainop = tax * 10 / 100 - 250000;
            } 
            else if (tax > 10000000 && tax <= 18000000) {
                thuephainop = tax * 15 / 100 - 750000;
            } 
            else if (tax > 18000000 && tax <= 32000000) {
                thuephainop = tax * 20 / 100 - 1650000;
            } 
            else if (tax > 32000000 && tax <= 52000000) {
                thuephainop = tax * 25 / 100 - 3250000;
            }
            else if (tax > 52000000 && tax <= 80000000) {
                thuephainop = tax * 30 / 100 - 5850000;
            }
            else if (tax > 80000000) {
                thuephainop = tax * 35 / 100 - 9850000;
            }
        }
        $('.thuethunhapcanhan').lawsExists(function () {
            $(this).text('0 VNĐ');
            if (thuephainop > 0) {
                $(this).text(lawsVn.formatNumber(Math.round(thuephainop), '.', '.') + ' VNĐ');
            }
        });
    },
    FormValidation: function (form) {
        var $form = $(form);
        var $validate = $form.validate();
        var errorClass = "has-error";
        $validate.settings.errorClass = errorClass;
        var previousErrorPlacementMethod = $validate.settings.errorPlacement;
        $validate.settings.errorPlacement = $.proxy(function (error, inputElement) {
            var formGroup = $(inputElement).closest('.form-group');
            formGroup.removeClass('has-error'), icon = formGroup.find('.ic.icon-validator'),
                span = formGroup.find('span.field-validation-valid');
            if (previousErrorPlacementMethod) {
                previousErrorPlacementMethod(error, inputElement);
            }
            formGroup.addClass(errorClass);
            $(inputElement).removeClass('boder_green').addClass('boder_red');
            $(span).removeClass('text_valideate_active').addClass('text_valideate');
            if (!icon.length) {
                $('<i class="ic icon-validator icon-e-remove-2lvn ic_boder_red"></i>').insertAfter($(inputElement));
            } else icon.removeClass('ic_boder_green').removeClass('icon-checklvn').addClass('ic_boder_red').addClass('icon-e-remove-2lvn');
        }, $form[0]);

        var previousSuccessMethod = $validate.settings.success;
        $validate.settings.success = $.proxy(function (error) {
            var formGroup = $(error).closest('.form-group');
            formGroup.removeClass('has-error'), icon = formGroup.find('.ic.icon-e-remove-2lvn'),
                span = formGroup.find('span.field-validation-valid'), input = formGroup.find('input, textarea');
            if (previousSuccessMethod) {
                previousSuccessMethod(error);
            }
            input.removeClass('boder_red').addClass('boder_green');
            $(span).removeClass('text_valideate').addClass('text_valideate_active');
            if (!icon.length) {
                $('<i class="ic icon-validator icon-checklvn ic_boder_green"></i>').insertAfter($(input));
            } else icon.removeClass('ic_boder_red').removeClass('icon-e-remove-2lvn').addClass('ic_boder_green').addClass('icon-checklvn');
        });

        $('input[data-val-remote-url]').lawsExists(function () {
            $('input[data-val-remote-url]').each(function (i, el) {
                el = $(el);
                var root = el.closest('.form-group'), span = root.find('span.text-danger');
                $(el).rules().remote.complete = function (xhr) {
                    if (xhr.status == 200 && xhr.responseText === 'true') {
                        span.lawsExists(function () {
                            $(this).addClass('span-success').html('<span for="Email">' + lawsVn.Resource.getMessages('Available') + '</span>');
                        });
                    }
                };
            });
        });

    },
    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;
    },
    PromotionReset: function () {
        var price = 0,
            vat = 0,
            promotionCode = $('input[name="PromotionCode"]');
        $('input[type="hidden"][name="Price"]').lawsExists(function () {
            if ($.isNumeric($(this).val())) {
                price = parseInt($(this).val());
            }
        });
        promotionCode.val('');
        $('.thong-tin-khuyen-mai').lawsExists(function () {
            $(this).remove();
        });
        $('.DiscountDiv').lawsExists(function () {
            $(this).empty();
        });
        promotionCode.removeClass('boder_green').removeClass('boder_red');
        promotionCode.next().removeClass('span-success').text('');
        vat = 0;//bỏ vat price * 10 / 100;
        //tính lại tổng tiền
        $('.TotalAmountText').lawsExists(function () {
            $(this).text(lawsVn.formatNumber(price, '.', '.'));
        });
        $('.VATText').lawsExists(function () {
            $(this).text(lawsVn.formatNumber(vat, '.', '.'));
        });
        $('.TotalPriceText').lawsExists(function () {
            $(this).text(lawsVn.formatNumber(price + vat, '.', '.'));
        });
        $('.DiscountOnOnlinePaymentText').lawsExists(function () {
            $(this).text(lawsVn.formatNumber((price + vat) * 10 / 100, '.', '.'));
        });
        $('.TotalPriceEndTextZaloPay').lawsExists(function () {
            $(this).text(lawsVn.formatNumber((price + vat) * 0.9, '.', '.'));
        });
        //set value
        $('input[type="hidden"][name="PromotionCodeValid"]').lawsExists(function () {
            $(this).val('');
        });
    },
    KhongDau: function (value) {
        var str = value.toLowerCase();
        str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a");
        str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
        str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
        str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o");
        str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
        str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
        str = str.replace(/đ/g, "d");
        str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'|\"|\&|\#|\[|\]|~|\$|_|`|-|{|}|\||\\/g, " ");
        str = str.replace(/ + /g, " ");
        str = str.trim();
        return str;
    },
    CustomerRegisterOnSubmit: function (token) {
        //$('#RegisterV2Form').submit();
    },
    isHome: function () {
        return window.location.pathname == '/';
    },
    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, " "));
    },
    preventAnchorScroll: function () {
        var scrollToTop = function () {
            $(window).scrollTop(0);
        };
        if (window.location.hash) {
            $(window).one('scroll', scrollToTop);
        }
        $(function () {
            setTimeout(
                function () {
                    $(window).off('scroll', scrollToTop);
                },
                1000
            );
        });
    },
    serviceGetPercentageDiscount: function (month) {
        if (month == 12)
            return 100 - 5;
        else if (month == 24)
            return 100 - 7.5;
        else if (month == 36)
            return 100 - 10;
        else if (month == 48)
            return 100 - 12.5;
        else if (month == 60)
            return 100 - 15;
        else return 0;
    },
    fileUpload: function (event) {
        var id = event.currentTarget.id, type = $(event.target).data('type');
        if (typeof type != 'undefined' && type == 'pwi') return;
        if (id != 'MyLuatCoverImageFile' && id != 'MyLuatAvatarFile') {
            console.log(id);
            var fileApiSupported = !!(window.File && window.FileReader && window.FileList && window.Blob);
            if (fileApiSupported) {
                var files = event.target.files;
                var file = files[0];
                if (file) {
                    if (/^image\//i.test(file.type)) {
                        if (file.size > 10485760) {
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: ['Dung lượng ảnh vượt quá 10MB cho phép.'],
                                showIcon: false
                            });
                            return;
                        } else {
                            lawsVn.readFile(file, id);
                        }
                    } else {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: ['Quý khách vui lòng chọn file ảnh.'],
                            showIcon: false
                        });
                        return;
                    }
                }
            } else {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: [
                        'Trình duyệt hiện tại đã cũ. Quý khách vui lòng nâng cấp trình duyệt để sử dụng chức năng này.'
                    ],
                    showIcon: false
                });
                return;
            }
        }
    },
    readFile: function (file, id) {
        var reader = new FileReader();
        reader.onloadend = function () {
            lawsVn.processFile(reader.result, file.type, file.name, id);
        }
        reader.onerror = function () {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Quý khách vui lòng thử lại sau.'],
                showIcon: false
            });
            return;
        }
        reader.readAsDataURL(file);
    },
    processFile: function (dataUrl, fileType, fileName, id) {
        var maxWidth = 800;
        var maxHeight = 600;
        if (id == 'MyLuatCoverImageFile') {
            maxWidth = 1200;
            maxHeight = 200;
        }
        var image = new Image();
        image.src = dataUrl;

        image.onload = function () {
            var width = image.width;
            var height = image.height;
            var shouldResize = (width > maxWidth) || (height > maxHeight);

            if (!shouldResize) {
                lawsVn.sendFile(dataUrl, fileName, id);
                return;
            }

            var newWidth;
            var newHeight;

            if (width > height) {
                newHeight = height * (maxWidth / width);
                newWidth = maxWidth;
            } else {
                newWidth = width * (maxHeight / height);
                newHeight = maxHeight;
            }

            var canvas = document.createElement('canvas');

            canvas.width = newWidth;
            canvas.height = newHeight;

            var context = canvas.getContext('2d');

            context.drawImage(this, 0, 0, newWidth, newHeight);

            dataUrl = canvas.toDataURL(fileType);

            lawsVn.sendFile(dataUrl, fileName, id);
        };

        image.onerror = function () {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Quý khách vui lòng thử lại sau.'],
                showIcon: false
            });
        };
    },
    sendFile: function (fileData, fileName, id) {
        var formData = new FormData();
        fileData = fileData.replace(/^data:image\/[a-z]+;base64,/, '');
        formData.append('imageData', fileData);
        formData.append('imageName', fileName);
        var progress = $('.container-bar');
        var progressBar = $('.progress > .progress-bar');
        progress.show();
        $('#loading').fadeIn('normal');
        $.ajax({
            url: lawsVn.virtualPath('/Ajax/UploadFile'),
            type: 'POST',
            contentType: false,
            cache: false,
            processData: false,
            data: formData,
            xhr: function () {
                var jqXHR = null;
                if (window.ActiveXObject) {
                    jqXHR = new window.ActiveXObject("Microsoft.XMLHTTP");
                } else {
                    jqXHR = new window.XMLHttpRequest();
                }
                //Upload progress
                jqXHR.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);
                //Download progress
                jqXHR.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 jqXHR;
            },
            success: function (resp) {
                if (resp.Completed) {
                    $('#loading').fadeOut('normal');
                    if (resp.Data != null && resp.Data.length > 0) {
                        if (id == 'MyLuatAvatarFile') {
                            $('#MyLuatAccountAvatar').attr('src', resp.Data);
                            lawsVn.updateImage(resp.Data, 1)
                        }
                        else if (id == 'MyLuatCoverImageFile') {
                            $('#MyLuatAccountCoverImage').attr('src', resp.Data);
                            lawsVn.updateImage(resp.Data, 2)
                        }
                        else {
                            $('input#Avatar').val(resp.Data);
                            $('#AccountAvatar').attr('src', resp.Data);
                        }

                    }
                } else {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Quý khách vui lòng thử lại sau.'],
                        showIcon: false
                    });
                }
            }
        });
    },
    updateImage: function (patch, type) {
        $.ajax({
            url: lawsVn.virtualPath('/Account/UpdateImage'),
            data: { patch: patch, type: type },
            type: 'Post'
        })
            .then(function (data) {
                console.log(data);
            });
    },
    virtualPath: function (patch) {
        var host = window.location.protocol + '//' + window.location.host;
        return host + patch;
    },
    Round: function (value, decimals) {
        return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
    },
    SetValueForTag: function (value) {
        var target = $('#SearchArticleTagId');
        if (target != null) {
            target.val(value);
            target.closest('form').submit();
        }
    },
    SetValueForField: function (value) {
        var target = $('#SearchArticleFieldId');
        if (target != null) {
            target.val(value);
            target.closest('form').submit();
        }
    },
    SetValueForSearchByTime: function () {
        var SearchByTime = $('#dllSearchByTime option:selected').val();
        var PublicDate = $('#PublicDateSelect');
        var target = $('#SearchArticleSearchByTime');
        if (target != null) {
            var date = new Date();
            var newdate = new Date(date);
            var number = 30;
            var someFormattedDate = '';
            if (SearchByTime > 0) {
                var dayofweek = date.getDay();
                var numberdate = date.getDate();
                switch (SearchByTime) {
                    case '1': number = 0; break;//hom nay
                    case '2': number = 1; break;//hom qua
                    case '3': number = dayofweek - 1; break;//tuan nay
                    case '4': number = dayofweek + 6; break;//tuan truoc
                    case '5': number = numberdate - 1; break;//thang nay
                    case '6': number = numberdate - 1; newdate.setMonth(newdate.getMonth() - 1); break;//thang truoc
                    case '7': number = 30; break;//30 ngay
                }
                newdate.setDate(newdate.getDate() - number);
                var dd = newdate.getDate();
                var mm = newdate.getMonth() + 1;
                var y = newdate.getFullYear();
                someFormattedDate = (dd < 10 ? '0' + dd : dd) + '/' + (mm < 10 ? '0' + mm : mm) + '/' + y;
            }
            PublicDate.val(someFormattedDate);
            target.val(SearchByTime);
            target.closest('form').submit();
        }
    },
    GetFontSize: function () {
        var target = $('.boxnoidung *');
        if ($('#chidanthaydoi').is(':visible'))
            target = $('#chidanthaydoind *');
        else if ($('#noidungmix').is(':visible'))
            target = $('#noidungtoanvan *');
        var currentFontSize = target.css('font-size'),
            currentFontSizeNum = parseFloat(currentFontSize, 10);
        $('#font-size').lawsExists(function () {
            $(this).text(currentFontSizeNum);
        });
    },
    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: 'Quý khách vui lòng đồng ý với Quy ước sử dụng của LuatVietnam.vn' } },
            { 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] : '';
        }
    },
    registerServiceFormReset: function () {
        var countSteps = $('div.law-steps', '.law-wizard').length;
        var i = countSteps == 3 ? 1 : (countSteps == 4 ? 2 : 1);
        $('div.law-steps', '.law-wizard').animate({
            opacity: 0
        },
            250,
            function () {
                $('div.law-steps' + ':nth-child(' + i + ')', '.law-wizard').animate({
                    opacity: 1
                },
                    250,
                    function () {
                        $('.navstep').LawScrollTo();
                    }).show();
            }).hide();
        $('select[name="ServicePackageParentId"]').lawsExists(function () {
            $(this).removeClass('border-warning');
        });
        $('select[name="ServicePackageId"]').lawsExists(function () {
            $(this).removeClass('border-warning');
        });
        $('#price-selected-span').lawsExists(function () {
            $(this).text(0);
        });
        //form khuyến mại
        $('#PromotionCode').lawsExists(function () {
            $(this).val('');
        });
        $('#PromotionCodeCheckForm input').lawsExists(function () {
            $('#PromotionCodeCheckForm input').clearErrors();
        });
        $('input[type="hidden"][name="ServicePackageId"]').lawsExists(function () {
            $(this).val(0);
        });
        $('#promotionCodeCheckResult').lawsExists(function () {
            $(this).html('');
        });
        //thông tin đơn hàng
        $('#termOfSubscription-span').lawsExists(function () {
            $(this).text('');
        });
        $('#numberOfUsers-span').lawsExists(function () {
            $(this).text('');
        });
        $('#expiryDate-span').lawsExists(function () {
            $(this).text('');
        });
        $('.price-td').lawsExists(function () {
            $(this).text(0);
        });
        $('.priceVat-td').lawsExists(function () {
            $(this).text(0);
        });
        $('.promotionPrice-td').lawsExists(function () {
            $(this).text(0);
        });
        $('.total-td').lawsExists(function () {
            $(this).text(0);
        });
        //thanh toán đơn hàng qua thẻ atm

        $('input[type="hidden"][name="ServicePackageName"]').lawsExists(function () {
            $(this).val('');
        });
        $('input[type="hidden"][name="Total"]').lawsExists(function () {
            $(this).val(0);
        });
        $('input[type="hidden"][name="Price"]').lawsExists(function () {
            $(this).val(0);
        });
        $('input[type="hidden"][name="Amount"]').lawsExists(function () {
            $(this).val(0);
        });
        $('input[type="hidden"][name="PercentDecrease"]').lawsExists(function () {
            $(this).val(0);
        });
        $('input[type="hidden"][name="PromotionCodeBankAccount"]').lawsExists(function () {
            $(this).val('');
        });
        $('input[type="hidden"][name="CompanyName"]').lawsExists(function () {
            $(this).val('');
        });
        $('input[type="hidden"][name="CompanyAddress"]').lawsExists(function () {
            $(this).val('');
        });
        $('input[type="hidden"][name="CompanyTaxCode"]').lawsExists(function () {
            $(this).val('');
        });
        $('input[type="hidden"][name="InternalContent"]').lawsExists(function () {
            $(this).val('');
        });
    },
    removeVal: function (arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == val)
                arr.splice(i, 1);
        }
    },
    numbersResultFound: function () {
        var totalpage = $('#tblcontent').data('totalpage');
        var pageindex = $('#tblcontent').data('pageindex');
        var pageCount = $('#tblcontent').data('pageCount');
        if (totalpage === undefined) {
            totalpage = 0;
        }
        if (pageindex === undefined) {
            pageindex = 0;
        }
        if (pageindex <= 0) {
            pageindex = 1;
        }
        var data = '';
        if (pageCount > 0) {
            data += '<span>Tìm thấy <strong> ' +
                totalpage +
                ' văn bản </strong>(' +
                pageindex +
                '/' +
                pageCount +
                ' trang)</span>';
        }
        $('#txtnumberresultfound').html(data);
    },
    showResultsFilterBy: function () {
        if (lawsVnConfig.FieldId > 0 ||
            lawsVnConfig.EffectStatusId > 0 ||
            lawsVnConfig.DocTypeId > 0 ||
            lawsVnConfig.OrganId > 0 ||
            lawsVnConfig.Year > 0 ||
            lawsVnConfig.DocGroupId > 0)
            $('.resultsFilterBy').show();
        else $('.resultsFilterBy').hide();
    },
    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');
            });
        },
        OnBeginStatisticBy: function (id) {
            var ret = true;
            $('#' + id).lawsExists(function () {
                var li = $(this).find('li');
                if (li.length) ret = false;
            });
            if (ret) $('#loading').fadeIn('normal');
            return ret;
        },
        OnBeginV3: 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');
                });
            });
        },
        FaqsOnComplete: function (element) {
            $('#loading').fadeOut('normal');
            $('#CreateFaqsForm').lawsExists(function () {
                var form = $(this);
                form.find('input:text, select, textarea').not(':input[name=FullName], :input[name=Email], :input[name=Mobile]').val('');
            });
            $('#lawEditFaqs').lawsExists(function () {
                $(this).remove();
            });
        },
        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);
        },
        OnCompleteStatisticBy: function (id) {
            $('#loading').fadeOut('normal');
            if (id && typeof id == 'string' && lawsVn.isDomElement($('#' + id))) {
                $('#' + id).lawsExists(function () {
                    if (!$(this).hasClass('accordion')) {
                        var self = $(this).closest('li').find('.content-scroll-1');
                        self.closest('li').find('a').addClass('accor');
                        if (self.is(':hidden') === true) {
                            $('.accordion-menu .accordion').slideUp();
                            self.slideDown();
                        } else {
                            self.slideUp();
                        }
                    } else {
                        $(this).closest('li').find('a').addClass('accor');
                        if ($(this).is(':hidden') === true) {
                            $('.accordion-menu .accordion').slideUp();
                            $(this).slideDown();
                        } else {
                            $(this).slideUp();
                        }
                    }
                    //$(this).closest('li').LawScrollTo();
                });
            }

        },
        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');
                        }
                    });
            }
        },
        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).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);
                    }
                });
                $('#tienganh > .page-content.box-content').lawsExists(function () {
                    $(this).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 (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
                });
            }
        },
        ConsultingQuestionsWithFeeOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $('#ConsultingQuestionsWithFeeForm').lawsExists(function () {
                    var frm = $(this);
                    var cookieValue = 'FullName=' +
                        frm.find(':input[name=FullName]').val() +
                        '&CustomerEmail=' +
                        frm.find(':input[name=CustomerEmail]').val() +
                        '&PhoneNumber=' +
                        frm.find(':input[name=PhoneNumber]').val() +
                        '&Address=' + frm.find(':input[name=Address]').val();
                    lawsVn.createCookie('ConsultingQuestionsWithFee', cookieValue, 90);
                    if (data.Message != null && data.Message.length > 0) {
                        $().lawsDialog({
                            messages: [data.Message],
                            dialogClass: 'lawsVnDialogTitle',
                            onClose: function () {
                                $(':input[name=Comment]', frm).lawsExists(function () {
                                    $(this).val('');
                                });
                                $(':input[name=FilePath]', frm).remove();
                                $('#attachment_name_fdk7tn').lawsExists(function () {
                                    $('p.ptext2', $(this)).remove();
                                    $(this).css('display', 'none');
                                });
                            }
                        });
                    }
                });
            } 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
                });
            }
        },
        AdditionalRequirementsDocumentOnSuccess: function(data, status, xhr) {
            if (data.Completed) {
                $('#AdditionalRequirementsDocumentForm').lawsExists(function () {
                    var frm = $(this);
                    if (data.Message != null && data.Message.length > 0) {
                        $('.wrapper-yeucaubosungvb').lawsExists(function () {
                            $(this).hide();
                        });
                        $('.thongbao-send', frm).lawsExists(function () {
                            $(this).closest('.popup-wrapper').css('width', '30%');
                            $(this).html('<p class="p-sucess"><strong>' + data.Message + '</strong></p>');
                        });
                    }
                    $('#Content', frm).lawsExists(function () {
                        $(this).val('');
                    });
                });
            } 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
                });
            }
        },
        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
                });
            }
        },
        AdditionalRequirementsDocumentOnFailure: function (jqXhr, errorMessage) {
            $('#loading').fadeOut('normal');
            //if (jqXhr.status !== 403) {
                $('#AdditionalRequirementsDocumentForm').lawsExists(function() {
                    var frm = $(this);
                    $('.wrapper-yeucaubosungvb').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.thongbao-send', frm).lawsExists(function () {
                        $(this).closest('.popup-wrapper').css('width', '30%');
                        $(this).html(
                                '<p class="p-text1"><strong>Yêu cầu của Quý khách chưa được gửi đi!</strong></p><p class="p-text2"><em>Có thể do lỗi kết nối mạng hoặc sever phản hồi chậm.<br />Xin Quý khách thông cảm và thực hiện lại!</em></p>')
                            .show();
                    });
                });
            //}
        },
        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 {
                        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>Để đượ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>';
                $().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));
                                }
                            });
                    }
                });
            }
        },
        ServiceAccountLoginOnSuccess: function (data, status, xhr) {
            $('#tabPannel').lawsExists(function () {
                lawsVn.preventAnchorScroll();
            });
            if (data.Completed) {
                $('#login-form-target').lawsExists(function () {
                    $(this).removeClass('target-expanded').addClass('target-hidden');
                });
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                    setTimeout(function () {
                        window.location.href = lawsVn.replaceUrlParam({ 'step': '3' });
                    }, 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];
                }
                $().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
                });
            }
        },
        SubscriptionNoticeOfValidityOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $().lawsDialog({
                    messages: [data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            } else if (data.Message != null && data.Message.length > 0) {
                $().lawsDialog({
                    messages: [data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
        },
        FaqsOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                var msg = '<p>GỬI CÂU HỎI THÀNH CÔNG!</p>' +
                    '<div style=" text-align: left; font-weight: normal;max-width: 500px; font-size:13px;"><p>Mã câu hỏi của Quý khách là <b>#' + data.Data.FaqId + '</b></p>' +
                    '<p>LuatVietnam sẽ hỗ trợ trả lời các câu hỏi có đủ thông tin. Thời gian chờ trả lời có thể là 1-3 ngày, hoặc lâu hơn tuỳ theo tình huống, lĩnh vực tư vấn.</p>' +
                    '<p><i>Cảm ơn Quý khách đã sử dụng phần mềm của Luật Việt Nam.<i></p></div>';
                $().lawsDialog({
                    messages: [msg],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false,
                    onClose: function () {
                        $('#lawsVnLawerQuestion').lawsExists(function () {
                            $(this).dialog('close');
                        });
                    }
                });
            } else if (data.Message != null && data.Message.length > 0) {
                if (data.Message === 'Unauthorized') {
                    lawsVn.login();
                    return;
                } else {
                    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
                    });
                }
            }
        },
        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;
            }
        },
        NewsLetterEmailOnSuccess: function (data, status, xhr) {
            $('#Email', $('#NewsLetterEmailForm')).lawsExists(function () {
                $(this).val('');
            });
            if (data.Completed) {
                if (data.Message != null && data.Message.length > 0) {
                    $().lawsDialog({
                        messages: [data.Message],
                        dialogClass: 'lawsVnDialogTitle',
                        onOpen: function () {
                            $("#RegisterMailForm").dialog("close");
                        },
                        showIcon: false
                    }); 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
                });
            }
        },
        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
                });
            }
        },
        VipRedirectOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $('#mmk01niq8h').lawsExists(function () {
                    $(this).remove();
                });
                $('.theme-green .popup-bg').lawsExists(function () {
                    $(this).remove();
                });
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                    setTimeout(function () {
                        window.location.href = data.ReturnUrl;
                    }, 100);
                }
                if (data.Message !== null && data.Message.length > 0) {
                    $().vipAlert({
                        messages: [data.Message],
                        buttons: [
                            {
                                'Name': 'Xong', ClassName: 'btn-xoa', ClickEvent: function () {
                                    setTimeout(function () {
                                        window.location.href = window.location.href;
                                    }, 10);
                                }
                            }
                        ], callback: function () {
                            window.location.href = window.location.href;
                        }
                    });
                }
            } 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];
                }
                $().vipAlert({
                    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],
                    buttons: [
                        {
                            'Name': 'Đóng', ClassName: 'btn-xoa', ClickEvent: function () {
                                $('.customer-vip').lawsExists(function () {
                                    $(this).remove();
                                });
                            }
                        }
                    ]
                });
            }
        },
        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
                });
            }
        },
        VIPOnSuccessful: function (data, status, xhr) {
            if (data.Completed) {
                $().vipAlert({
                    messages: [data.Message],
                    buttons: [
                        {
                            'Name': 'Đóng', ClassName: 'btn-xoa', ClickEvent: function () {
                                $('.customer-vip').lawsExists(function () {
                                    window.location.href = data.ReturnUrl;
                                    $(this).remove();
                                });
                            }
                        }
                    ], callback: 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
                });
            }
        },
        VIPChangePassWordSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $('#changePassword').remove();
                $().vipAlert({
                    messages: [data.Message],
                    buttons: [
                        {
                            'Name': 'Đóng', ClassName: 'btn-xoa', ClickEvent: function () {
                                $('.customer-vip').lawsExists(function () {
                                    
                                    $(this).remove();
                                });
                            }
                        }
                    ], callback: function () {
                    }
                });
            } 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];
                }
            }
            $('#loading').fadeOut('normal');
        },
        LoginOnSuccess: function (data, status, xhr) {
            if (data.Completed) {
                $().lawsDialog({
                    messages: [data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    onOpen: function () {
                        $("#lawsVnLogin").lawsExists(function () {
                            $(this).dialog("close");
                        });
                        $("#changePassword").lawsExists(function () {
                            $(this).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;
                    }
                });
                $('#gopy').lawsExists(function () {
                    lawsVn.closeDialogById('gopy');
                });
                $('#docSendMail').lawsExists(function () {
                    lawsVn.closeDialogById('docSendMail');
                });
            } else {
                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',
                        showIcon: false
                    });
                } else
                    $().lawsDialog({
                        messages: [data.Message],
                        dialogClass: 'lawsVnDialogTitle',
                        showIcon: false
                    });
            }
        },
        AddFieldsOnSuccessful: function (data, status, xhr) {
            if (data.Completed) {
                $().lawsDialog({
                    messages: [data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false,
                    onOpen: function () {
                        $("#lawsVnLogin").dialog("close");
                    },
                    onClose: function () {
                        if (data.Data != null) {
                            var resultHtml = '<div class="tag_lv content-scroll-1" style="max-height: 350px">', obj = data.Data, item, item2;
                            if (obj.ListFields != null && obj.ListFields.length) {
                                if (obj.ListCustomerFields != null && obj.ListCustomerFields.length) {
                                    for (var i = 0; i < obj.ListFields.length; i++) {
                                        item = obj.ListFields[i];
                                        for (var j = 0; j < obj.ListCustomerFields.length; j++) {
                                            item2 = obj.ListCustomerFields[j];
                                            if (item.FieldId == item2.FieldId && item2.DocGroupId == 1) {
                                                resultHtml += '<span class="tag_a">' +
                                                    '<i class="icontag fixxx xoa-linh-vuc" title="Xóa lĩnh vực ' + item.FieldName + '" data-id="' + item2.CustomerFieldId + '">' +
                                                    '<img src="/assets/images/icondell.png" alt="xoa linh vuc"/></i>' + item.FieldName + '</span>';
                                            }
                                        }
                                    }
                                }
                            }
                            resultHtml += '</div>';
                            $('#popupThemlinhvuc').find('.ct_popup2').html('<p>Đang tải dữ liệu. Quý khách vui lòng đợi trong giây lát...</p>');
                            $('#popupThemlinhvuc').hide();
                            $('#linhvucvanbanquantam').html(resultHtml).promise().done(function () {
                                $('.content-scroll-1').lawsExists(function () {
                                    $(this).mCustomScrollbar({
                                        snapAmount: 40,
                                        scrollButtons: { enable: true },
                                        keyboard: { scrollAmount: 40 },
                                        mouseWheel: { deltaFactor: 40 },
                                        scrollInertia: 400
                                    });
                                });
                            });
                        }
                    }
                });
            } 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
                });
            }
        },
        ServiceRegistrationOnSuccess: function (data, status, xh) {
            if (data.Completed) {
                $('#OrderCode').html('Mã đơn hàng phần mềm của Quý khách:<strong style="color: #a67942;"> ' +
                    data.Message +
                    ' </strong>');
            } else {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: [data.Message],
                    showIcon: false
                });
            }
        },
        PromotionCodeCheckOnSuccess: function (data, status, xhr) {
            var total = 0;
            $('input[type="hidden"][name="Total"]').lawsExists(function () {
                if ($.isNumeric($(this).val())) {
                    total = parseInt($(this).val());
                }
            });
            if (data.Completed) {
                if (data.Data != null) {
                    var result =
                        '<p style="padding-left: 180px; margin-top:10px; line-height: 24px; color: #222;">Thông tin mã khuyến mại:<strong style="color:#a67942;"> ' +
                        data.Data.PromotionDesc +
                        ' </strong></p>';
                    if (data.Data.NumMonthFree > 0) {
                        result +=
                            '<p style="padding-left: 180px; line-height: 24px; color: #222;">Khuyến mại:<strong style="color:#a67942;"> ' +
                            data.Data.NumMonthFree +
                            ' tháng</strong></p>';
                    }
                    if (data.Data.NumDayFree > 0) {
                        result +=
                            '<p style="padding-left: 180px; line-height: 24px; color: #222;">Khuyến mại:<strong style="color:#a67942;"> ' +
                            data.Data.NumDayFree +
                            ' ngày</strong></p>';
                    }
                    if (data.Data.PercentDecrease > 0) {
                        result +=
                            '<p style="padding-left: 180px; line-height: 24px; color: #222;">Khuyến mại:<strong style="color:#a67942;"> ' +
                            data.Data.PercentDecrease +
                            '%</strong></p>';
                    } else {
                        if (data.Data.Amount > 0) {
                            result +=
                                '<p style="padding-left: 180px; line-height: 24px; color: #222;">Khuyến mại:<strong style="color:#a67942;"> ' +
                                lawsVn.formatNumber(data.Data.Amount, '.', '.') +
                                ' VNĐ</strong></p>';
                        }
                    }
                    $('#promotionCodeCheckResult').lawsExists(function () {
                        $(this).html(result);
                    });
                    $('input[type="hidden"][name="PromotionCodeBankAccount"]').lawsExists(function () {
                        $(this).val(data.Data.PromotionDesc);
                    });
                    $('input[type="hidden"][name="PromotionCodeScratchCard"]').lawsExists(function () {
                        $(this).val(data.Data.PromotionDesc);
                    });
                    if (data.Data.Amount > 0) {
                        $('input[type="hidden"][name="Amount"]').lawsExists(function () {
                            $(this).val(data.Data.Amount);
                        });
                    } else {
                        $('input[type="hidden"][name="PercentDecrease"]').lawsExists(function () {
                            $(this).val(data.Data.PercentDecrease);
                        });
                    }
                    $('.promotionPrice-td').lawsExists(function () {
                        if (total > 0) {
                            $(this).text(data.Data.Amount > 0
                                ? lawsVn.formatNumber(data.Data.Amount, '.', '.')
                                : (data.Data.PercentDecrease > 0
                                    ? lawsVn.formatNumber(total * data.Data.PercentDecrease / 100, '.', '.') + ' VNĐ'
                                    : 0));
                        }
                    });
                    $('.total-td').lawsExists(function () {
                        if (total > 0) {
                            //var vat = price * 10 / 100;
                            var pricePromotion = data.Data.Amount > 0
                                ? data.Data.Amount
                                : (data.Data.PercentDecrease > 0
                                    ? total * data.Data.PercentDecrease / 100
                                    : 0);
                            $(this).text(lawsVn.formatNumber(total - pricePromotion, '.', '.') + ' VNĐ');
                        }
                    });
                }
            } else {
                if (data.Message != null && data.Message.length > 0) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [data.Message]
                    });
                }
                $('#promotionCodeCheckResult').lawsExists(function () {
                    $(this).empty();
                });
                $('#PromotionCodeBankAccount').lawsExists(function () {
                    $(this).val('');
                });
                $('#PromotionCodeScratchCard').lawsExists(function () {
                    $(this).val('');
                });
                //tính lại tổng tiền
                $('.promotionPrice-td').lawsExists(function () {
                    $(this).text(0);
                });
                $('.total-td').lawsExists(function () {
                    //var vat = price * 10 / 100;
                    //var total = price + vat;
                    $(this).text(lawsVn.formatNumber(total, '.', '.'));
                });
            }
        },
        TaxInvoiceOnComplete: function (data, status, xhr) {
            if (data.Completed) {
                if (data.Data !== void 0 && data.Data !== null) {
                    $('input[name="CompanyName"]').val(data.Data.CompanyName);
                    $('input[name="CompanyAddress"]').val(data.Data.CompanyAddress);
                    $('input[name="CompanyTaxCode"]').val(data.Data.CompanyTaxCode);
                    $('input[name="InternalContent"]').val(data.Data.InternalContent);
                }
                $('#TaxInvoiceFormLoad').dialog('close');
            } else if (data.Message != null && data.Message.length > 0) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: [data.Message],
                    showIcon: false
                });
            }

        },
        PaymentServiceUsingBankAccountOnSuccess: function (data, status, xhr) {
            if (data.Completed && data.Data != null) {
                if (data.Data.PayGateUrl != null && data.Data.PayGateUrl != '') {
                    window.location = data.Data.PayGateUrl;
                    return;
                } else if (data.Message != null && data.Message.length > 0) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [data.Message],
                        showIcon: false
                    });
                }
            } else if (data.Message != null && data.Message.length > 0) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: [data.Message],
                    showIcon: false
                });
            }
        },
        PaymentServiceUsingBankAccountOnSuccessV2: function (data, status, xhr) {
            if (data.Completed) {
                if (data.ReturnUrl != null && data.ReturnUrl.length > 0) {
                    window.location = data.ReturnUrl;
                    return;
                } else if (data.Message != null && data.Message.length > 0) {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: [data.Message],
                        showIcon: false
                    });
                }
            } else if (data.Message != null && data.Message.length > 0) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: [data.Message],
                    showIcon: false
                });
            }
        },
        OnSuccessValid: function (element) {
            $('#loading').fadeOut('normal');
            $('#' + element).lawsExists(function () {
                var form = $('#' + element);
                form.removeData('validator');
                form.removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse(form);
            });
        },
        LawTerminsOnSuccess: function (data, status, xhr) {
            if (status == 'success') {
                $('#txtnumberresultfound').html('');
                $("#txtnumberpage").html('');
                $('#tblcontent').lawsExists(function () {
                    var totalpage = $(this).data('totalpage');
                    var pageIndex = $(this).data('pageindex');
                    var pageCount = $(this).data('pagecount');
                    var data = '';
                    if (typeof totalpage == 'undefined') {
                        totalpage = 0;
                    }
                    if (typeof pageIndex == 'undefined') {
                        pageIndex = 1;
                    }
                    if (pageIndex <= 0) {
                        pageIndex = 1;
                    }
                    if (totalpage > 0) {
                        data = " <span>Tìm thấy <span class='color22'><strong>" +
                            lawsVn.formatNumber(totalpage, '.', '.') +
                            "</span> thuật ngữ</strong></span>";
                        data += ' (' + pageIndex + '/' + pageCount + ' trang)';
                        $('#txtnumberresultfound').lawsExists(function () {
                            $(this).html(data);
                        });
                    }
                });

                var keyword = '', keywordTemp = '';
                var lawTerminsTitle = '';
                var temp = '';
                $('#Tername').lawsExists(function () {
                    keyword = $(this).val();
                });
                keywordTemp = lawsVn.stringUtils(keyword);
                $('td.xs3').each(function (i, item) {
                    lawTerminsTitle = $(item).html();
                    temp = lawsVn.stringUtils(lawTerminsTitle);
                    var location = temp.indexOf(keywordTemp);
                    if (location > 0) {
                        var str1 = lawTerminsTitle.substr(location, keyword.length);
                        lawTerminsTitle =
                            lawTerminsTitle.replace(str1, '<span style="background-color:Yellow;">' + str1 + '</span>');
                        $(this).html(lawTerminsTitle);
                    }
                });
            };
        },
        SearchOnSuccess: function (data, status, xhr) {
            lawsVn.searchOnSuccess();
        },
        FeedBackOnSuccess: function (data, status, xhr) {
            var form = $('#FormGopYv2'), msg = form.find('#FeedBacksMessages');
            if (data.Completed) {
                if (data.Message !== null && data.Message.length > 0) {
                    if (msg.length) {
                        msg.find('span.bggopy').text(data.Message);
                    } else
                        form.append('<div id="FeedBacksMessages" class="form_group"><span class="bggopy">' + data.Message + '</span></div>');
                } 
                $('#Comment', form).val('');
                $('#CaptchaCode', form).val(''); 
                    $('input[type=hidden][name=FilePath]').remove();
                    $('#attachment_name_fdk7tn p.ptext2').remove();
                    if ($('#attachment_name_fdk7tn p.ptext2').length == 0)
                        $('#attachment_name_fdk7tn').css('display', 'none'); 
            } else if (data.Message !== null && data.Message.length > 0) {
                $().lawsDialog({
                    messages: [data.Message],
                    dialogClass: 'lawsVnDialogTitle',
                    showIcon: false
                });
            }
            $('.getcaptcha', form).trigger('click');
        },
        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({
                    mainClass: 'lvn-alert-tcvn',
                    success: true,
                    buttons: [],
                    //callback: function () {
                    //    window.location.href = window.location.href;
                    //},
                    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>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>'
                    ]
                });
            }
        },
        SearchByField: function (fieldId) {
            var self = $('#radio-' + fieldId);
            var label = self.closest('.radio').find('label');
            var fieldName = label.attr('title');
            var parrent = $('#linhvuctracuu');
            lawsVnConfig.FieldId = self.val();
            var html = '';
            parrent.removeClass('item-kqtk-noitem').addClass('item-kqtk');
            html += '<div class="item-sub-qktk">' +
                '<span class="texttk" > ' +
                fieldName +
                '</span >' +
                '<a href="#" id="xoa-dk-loc-linhvuctracuu" title="Xóa điều kiện lọc theo lĩnh vực tra cứu: ' +
                fieldName +
                '" class="xoa"><img alt="xóa" src="' +
                lawsVn.virtualPath('/assets/Images/xoa-tiemkiem.png') +
                '"></a>' +
                '</div>';
            parrent.html(html);
            $('.resultsFilterBy').show();
            $('select[id="ddlFieldId"] option').removeAttr('selected').filter('[value=0]').attr('selected', true);
        },
        ListOnSuccess: function (data, status, xhr) {
            lawsVn.listOnSuccess();
        },
        ListOnComplete: function (key, value) {
            lawsVn.ajaxEvents.pageIndex = 1;
            var idx = lawsVn.ajaxEvents.pageTitle.indexOf('- trang');
            if (idx > 0)
                lawsVn.ajaxEvents.pageTitle = lawsVn.ajaxEvents.pageTitle.substring(0, idx);
            var pageTitle = lawsVn.ajaxEvents.pageTitle;
            var obj = { 'page': '', 'pSize': '' };
            obj[key] = value;
            lawsVn.setTitleAndHistory(pageTitle, lawsVn.replaceUrlParam(obj, 1));
        },
        ListOnCompleteV2: function (key, value, reset) {
            lawsVn.ajaxEvents.pageIndex = 1;
            var idx = lawsVn.ajaxEvents.pageTitle.indexOf('- trang');
            if (idx > 0)
                lawsVn.ajaxEvents.pageTitle = lawsVn.ajaxEvents.pageTitle.substring(0, idx);
            var pageTitle = lawsVn.ajaxEvents.pageTitle;
            var obj = { 'page': '', 'pSize': '' };
            obj[key] = value;
            lawsVn.setTitleAndHistory(pageTitle, lawsVn.replaceUrlParam(obj, reset));
        },
        ListOnCompleteParamsObject: function (obj, reset) {
            lawsVn.ajaxEvents.pageIndex = 1;
            var idx = lawsVn.ajaxEvents.pageTitle.indexOf('- trang');
            if (idx > 0)
                lawsVn.ajaxEvents.pageTitle = lawsVn.ajaxEvents.pageTitle.substring(0, idx);
            var pageTitle = lawsVn.ajaxEvents.pageTitle;
            obj['page'] = '';
            obj['pSize'] = '';
            if (window.location.href.indexOf('van-ban-uy-ban-nhan-dan') > 0) {
                if (obj.hasOwnProperty('provinceId')) {
                    obj['provinceId'] = '';
                }
            }
            lawsVn.setTitleAndHistory(pageTitle, lawsVn.replaceUrlParam(obj, reset));
        },
        resetValidateForm: function (element) {
            $('#' + element).lawsExists(function () {
                var form = $('#' + element);
                form.removeData('validator');
                form.removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse(form);
            });
        },
        renameButton: function (type) {
            $('button#btn-step1').lawsExists(function () {
                if (type == 1) {
                    $(this).text(lawsVn.Resource.getMessages('LoginAccountAndPay'));
                } else {
                    $(this).text(lawsVn.Resource.getMessages('CreateAccountAndPay'));
                }
            });
        }
    },
    updateQueryStringParameter: function (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;
        }
    },
    replaceUrlParam: function (obj, reset) {
        var url = document.URL,
            tab = document.URL.indexOf('#') > -1 ? document.URL.substr(document.URL.indexOf('#')) : '',
            baseUrl = url.split('?')[0],
            query = url.split('?')[1],
            params = {},
            hash,
            index = 0, arrTabs = ['#tomtat', '#noidung', '#hieuluc', '#lienquan', '#luocdo', '#taive', '#chidanthaydoi', '#noidungmix'];
        for (var i = 0; i < arrTabs.length; i++) {
            if (tab.startsWith(arrTabs[i])) {
                tab = arrTabs[i];
                break;
            }
        }
        baseUrl = baseUrl.replace(tab, '');
        if (typeof (obj) == 'object') {
            if (query != undefined) {
                query = query.replace(tab, '');
                if (reset == undefined || reset !== 1) {
                    query = query.split('&');
                    for (var i = 0; i < query.length; i++) {
                        hash = query[i].split('=');
                        params[hash[0]] = hash[1];
                    }
                }
            }

            for (var key in obj) {
                params[key] = obj[key];
            }

            for (var key in params) {
                if (params[key] !== '') {
                    baseUrl += (index == 0 ? '?' : '&') + key + '=' + params[key];
                    index++;
                }
            }
            return baseUrl + tab;
        }
        return url;
    },
    setTitleAndHistory: function (title, path) {
        // Set history
        if (window.history && window.history.pushState) {
            history.pushState(null, title, path);
        }
        // Set title
        $('title').html(title);
    },
    LawTerminsReset: function () {
        $('input[name="Tername"]').lawsExists(function () {
            $(this).val('');
        });
    },
    LawTerminTagReset: function () {
        $('a.post-tag-abc').lawsExists(function () {
            $(this).removeClass('active');
        });
    },
    LawTerminSubmit: function () {
        var tername = $('#Tername').val(),
            lawTerminGroupId = $('#ddlLawTerminGroups option:selected').val();
        lawsVn.ajaxEvents.ListOnCompleteParamsObject({ 'tername': tername, 'lawTerminGroupId': lawTerminGroupId > 0 ? lawTerminGroupId : '' }, 1);
    },
    isDomElement: function (el) {
        return el instanceof HTMLElement ||
            el[0] instanceof HTMLElement
            ? true
            : false;
    },
    stringUtils: function (string) {
        var str = string;
        str = str.toLowerCase();
        str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ  |ặ|ẳ|ẵ/g, "a");
        str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
        str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
        str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ  |ợ|ở|ỡ/g, "o");
        str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
        str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
        str = str.replace(/đ/g, "d");
        str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g, " ");
        /* tìm và thay thế các kí tự đặc biệt trong chuỗi sang kí tự - */
        str = str.replace(/-+-/g, " "); //thay thế 2- thành 1-
        str = str.replace(/^\-+|\-+$/g, "");
        //cắt bỏ ký tự - ở đầu và cuối chuỗi 
        return str;
    },
    searchOnSuccess: function () {
        var keywords = '';
        $('#Keywords', $('.row-tim-kiem')).lawsExists(function () {
            keywords = $(this).val();
        });
        $('#txtnumberresultfound').html('');
        $("#txtnumberpage").html('');
        $('#tblcontent').lawsExists(function () {
            var totalpage = $(this).data('totalpage');
            var indexFrom = $(this).find(' th:first').text();
            var indexTo = $(this).find('th:last').text();
            if (typeof totalpage == 'undefined') {
                totalpage = 0;
            }
            if (totalpage > 0) {
                var data;
                if (keywords.length > 0) {
                    data = " <strong>Tìm thấy <span class='color2'>" +
                        lawsVn.formatNumber(totalpage, '.', '.') +
                        "</span> văn bản với từ khóa \"<span class='color2'>" +
                        keywords +
                        "</span>\"</strong>";
                    $('#txtnumberresultfound').html(data);
                } else {
                    data = " <strong>Tìm thấy <span class='color2'>" +
                        lawsVn.formatNumber(totalpage, '.', '.') +
                        "</span> văn bản.</strong>";
                    $('#txtnumberresultfound').html(data);
                }
                if (indexFrom != indexTo) {
                    var datanumerpage = "<strong>Kết quả " +
                        indexFrom +
                        "-" +
                        indexTo +
                        " trong " +
                        lawsVn.formatNumber(totalpage, '.', '.') +
                        " văn bản </strong>";
                    $("#txtnumberpage").html(datanumerpage);
                }
            }
        });
    },
    listOnSuccess: function () {
        $('#txtnumberresultfound').html('');
        $("#txtnumberpage").html('');
        $('#tblcontent').lawsExists(function () {
            var totalpage = $(this).data('totalpage');
            var pageIndex = $(this).data('pageindex');
            var pageCount = $(this).data('pagecount');
            var data = '';
            if (typeof totalpage == 'undefined') {
                totalpage = 0;
            }
            if (typeof pageIndex == 'undefined') {
                pageIndex = 1;
            }
            if (pageIndex <= 0) {
                pageIndex = 1;
            }
            if (totalpage > 0) {
                data = " <span>Tìm thấy <span class='color22'><strong>" +
                    lawsVn.formatNumber(totalpage, '.', '.') +
                    "</span> văn bản</strong></span>";
                data += ' (' + pageIndex + '/' + pageCount + ' trang)';
                $('#txtnumberresultfound').lawsExists(function () {
                    $(this).html(data);
                });
            }
        });
    },
    closeDialog: function () {
        var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
        activeDialogs.dialog('close');
    },
    closeDialogById: function (id) {
        $('#' + id).dialog('close');
    },
    getCaptcha: function (id, prefix) {
        var uuid = this.generateUUID();
        var captchaUrl = lawsVn.virtualPath('/lawvn-captcha.html?id=' + uuid + '&prefix=' + prefix);
        $('#' + id).attr('src', captchaUrl);
        return false;
    },
    openTerms: function () {
        return;
    },
    generateUUID: function () {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now();
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
            function (c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
        return uuid;
    },
    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;
    },
    swapImageUrl: function () {
        var $this = $(this);
        var newUrl = $this.data('hover');
        $this.data('hover', $this.attr('src'));
        $this.attr('src', newUrl);
    },
    topFunction: function () {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    },
    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";
            }
        }
    },
    successfulNewsletter: function (text) {
        if (text != null && text.length) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: [text],
                showIcon: false,
                onClose: function () {
                    $('#Email').val('');
                    var activeDialogs = $(".ui-dialog:visible").find('.ui-dialog-content');
                    activeDialogs.dialog('close');
                }
            });
        }
    },
    delay: function () {
        var timer = 0;
        return function (callback, ms) {
            clearTimeout(timer);
            timer = setTimeout(callback, ms);
        };
    },
    clearAvatar: function () {
        $('input[id="avatarFile"]').lawsExists(function () {
            $(this).val('');
            $('input#Avatar').val('');
            $('#AccountAvatar').attr('src', lawsVn.virtualPath('/assets/images/150x180.png'));
        });
    },
    RegisterAccount: function () {
        lawsValidate.termsAndConditions();
        lawsValidate.multiCheckboxRequired();
        lawsValidate.fileType();
        lawsValidate.maxFileSize();
        //lawsValidate.age();
        lawsValidate.formatDate();
    },
    FormReset: function () {
        lawsVn.clearAvatar();
        $('#RegisterForm')[0].reset();
        return false;
    },
    ResetForm: function (form) {
        form.find('input:text, input:password, input:file, select, textarea').val('');
        form.find('input:radio, input:checkbox')
            .removeAttr('checked').removeAttr('selected');
    },
    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());
            });
        });
    },
    TCVNFilter: function (doctypeid) {
        var url = lawsVn.virtualPath('/Ajax/TCVN_GetViewSearch');
        var fieldId = $("#dllField option:selected").val();
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var OrgansId = $("#dllOrgans option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        if (DocTypesId > 61) {
            doctypeid = DocTypesId;
        }
        var dataGetter = {
            'fieldId': fieldId,
            'effectStatusId': EffectStatusId,
            'organId': OrgansId,
            'docTypeId': doctypeid,
            'updateTargetId': "ListByField",
            'actionName': "TCVN_GetViewSearch"
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#ListByField").html(resp);
            });
    },

    VBHNFilter: function (doctypeid) { //cancel
        var url = lawsVn.virtualPath('/Ajax/DocsConsolidation_GetViewSearch');
        var fieldId = $("#dllField option:selected").val();
        //var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var OrgansId = $("#dllOrgans option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var dataGetter = {
            'fieldId': fieldId,
            'organId': OrgansId,
            'docTypeId': doctypeid,
            'updateTargetId': "ListByField",
            'actionName': "DocsConsolidation_GetViewSearch"
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#ListByField").html(resp).focus();
            });
    },
    LawerFilter: function () {
        var url = lawsVn.virtualPath('/Ajax/Lawer_GetViewSearch');
        var fieldId = $("#dllFields option:selected").val();
        //var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var ProvinceId = $("#dllProvinces option:selected").val();
        var DistrictId = $("#dllDistricts option:selected").val();
        var WardId = $("#dllWards option:selected").val();
        var Keyword = $("#Keyword").val();
        var dataGetter = {
            'ProvinceId': ProvinceId,
            'DistrictId': DistrictId,
            'WardId': WardId,
            'Keyword': Keyword,
            'FieldId': fieldId,
            'updateTargetId': "ListByField",
            'actionName': "Lawer_GetViewSearch"
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#ListByField").html(resp).focus();
            });
    },
    LawerQuestion: function (lawerid) {
        $('<div id="lawsVnLawerQuestion"></div>').lawsDialog({
            title: '',
            width: 640,
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#lawsVnLawerQuestion').load(lawsVn.virtualPath('/Ajax/PartialLawerQuestion?lawerid=' + lawerid),
                    function () {
                        var form = $('#lawsVnQuestionForm');
                        $('#ReturnUrl').val(lawsVnConfig.returnUrl);
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    FaqViewDetail: function (faqId) {
        $('<div id="lawsVnFaqViewDetail"></div>').lawsDialog({
            title: '',
            width: 800,
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#lawsVnFaqViewDetail').load(lawsVn.virtualPath('/Ajax/FaqViewDetail?FaqId=' + faqId),
                    function () {
                        var form = $('#lawsVnFaqViewDetailForm');
                        $('#ReturnUrl').val(lawsVnConfig.returnUrl);
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);

                        $(".content-scroll-1").mCustomScrollbar({
                            snapAmount: 40,
                            scrollButtons: { enable: true },
                            keyboard: { scrollAmount: 40 },
                            mouseWheel: { deltaFactor: 40 },
                            scrollInertia: 400
                        });
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    UBNDFilter: function (doctypeid) {
        var url = lawsVn.virtualPath('/Ajax/DocsUBND_GetViewSearch');
        var Provinceid = 0;
        var Year = 0;
        var fieldId = $("#dllField option:selected").val();
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var searchParams = new URLSearchParams(window.location.search);
        if (searchParams.get("provinceid") != null) {
            Provinceid = searchParams.get("provinceid");
        } else if (searchParams.get("year") != null) {
            Year = searchParams.get("year");
        } else if (searchParams.get("fieldid") != null && fieldId == 0) {
            fieldId = searchParams.get("fieldid");
        }

        var dataGetter = {
            'fieldId': fieldId,
            'effectStatusId': EffectStatusId,
            'docTypeId': DocTypesId,
            'ProvinceId': Provinceid,
            'year': Year,
            'updateTargetId': "ListByField",
            'actionName': "DocsUBND_GetViewSearch"
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#ListByField").html(resp);
            });
    },
    CustomerUBNDFilter: function (DocGroupId) {
        var url = lawsVn.virtualPath('/Ajax/Customers_InterfaceLocation');
        var Provinceid = 0;
        var Year = 0;
        var fieldId = $("#dllField option:selected").val();
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        Provinceid = $("#dllProvinces option:selected").val();
        var OrderByClauses = $("#dllOrderByClauses option:selected");
        var datefrom = OrderByClauses.val();
        var dateto = OrderByClauses.attr('id');

        var dataGetter = {
            'docGroupId': DocGroupId,
            'fieldId': fieldId,
            'effectStatusId': EffectStatusId,
            'docTypeId': DocTypesId,
            'ProvinceId': Provinceid,
            'datefrom': datefrom,
            'dateto': dateto,
            'updateTargetId': "FirstBox",
            'actionName': "Customers_InterfaceLocation",
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#FirstBox").html(resp);
            });
    },

    CustomerUBNDFilterSecond: function (DocGroupId, Provinceid) {
        var url = lawsVn.virtualPath('/Ajax/Customers_InterfaceLocation');
        var Year = 0;
        var fieldId = $("#dllFieldSecond option:selected").val();
        var organId = $("#dllOrgansSecond option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var OrderByClauses = "";
        var datefrom = "";
        var dateto = "";
        var dataGetter = {
            'docGroupId': DocGroupId,
            'fieldId': fieldId,
            'organId': organId,
            'docTypeId': DocTypesId,
            //'ProvinceId': Provinceid,
            'pageSize': 10,
            'datefrom': datefrom,
            'dateto': dateto,
            'updateTargetId': "SecondBox",
            'actionName': "Customers_InterfaceLocation",
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#SecondBox").html(resp);
            });
    },
    CustomerInterFaceChangeField: function (fieldId) {
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var ProvinceId = $("#dllCustomerProvinces option:selected").val();
        //var fieldId = $("#sectionContent").attr('data-fieldid');
        $("#sectionContent").attr("data-fieldid", fieldId);
        lawsVn.CustomerInterFaceChangeUpdate(fieldId, EffectStatusId, DocTypesId, ProvinceId);
    },
    CustomerInterFaceChangeUpdate: function (fieldId, EffectStatusId, DocTypesId, ProvinceId) {
        var url = lawsVn.virtualPath('/Ajax/Customers_InterfaceByField');
        var Provinceid = 0;
        var Year = 0;
        if (fieldId == null) {
            fieldId = 0;
        }
        if (EffectStatusId == null) {
            EffectStatusId = 0;
        }
        if (DocTypesId == null) {
            DocTypesId = 0;
        }
        if (ProvinceId == null) {
            ProvinceId = 0;
        }
        var dataGetter = {
            'ProvinceId': ProvinceId,
            'fieldId': fieldId,
            'effectStatusId': EffectStatusId,
            'docTypeId': DocTypesId,
            'updateTargetId': "ContentByField",
            'actionName': "Customers_InterfaceByField",
            'pageSize': 10,
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#ContentByField").html(resp);
                $("#sectionContent").attr("data-fieldid", fieldId);
            });
    },
    CustomerInterFaceChangeDllField: function () {
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var fieldId = $("#dllAllField option:selected").val();
        var ProvinceId = $("#dllCustomerProvinces option:selected").val();
        if (fieldId == 0) {
            fieldId = $("#sectionContent").attr('data-fieldid');
        }
        lawsVn.CustomerInterFaceChangeUpdate(fieldId, EffectStatusId, DocTypesId, ProvinceId);
    },
    CustomerInterFaceChange: function () {
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var ProvinceId = $("#dllCustomerProvinces option:selected").val();
        var fieldId = $("#sectionContent").attr('data-fieldid');
        lawsVn.CustomerInterFaceChangeUpdate(fieldId, EffectStatusId, DocTypesId, ProvinceId);
    },
    CustomerInterFaceChangeFieldv2: function (fieldId) {
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var ProvinceId = $("#dllCustomerProvinces option:selected").val();
        //var fieldId = $("#sectionContent").attr('data-fieldid');
        $("#sectionContent").attr("data-fieldid", fieldId);
        lawsVn.CustomerInterFaceChangeUpdatev2(fieldId, EffectStatusId, DocTypesId, ProvinceId);
    },
    CustomerInterFaceChangeDllFieldv2: function (value) {
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var fieldId = value;//$("#dllAllField option:selected").val();
        var ProvinceId = $("#dllCustomerProvinces option:selected").val();
        //if (fieldId == 0) {
        //    fieldId = $(".tab-myluat-item.active").attr('data-fieldid');
        //}
        lawsVn.CustomerInterFaceChangeUpdatev2(fieldId, EffectStatusId, DocTypesId, ProvinceId);
    },
    CustomerInterFaceChangev2: function () {
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var DocTypesId = $("#dllDocTypes option:selected").val();
        var ProvinceId = $("#dllCustomerProvinces option:selected").val();
        var fieldId = $(".tab-myluat-item.active").attr("data-fieldid");//$("#tabItemFields").attr('data-fieldid');
        lawsVn.CustomerInterFaceChangeUpdatev2(fieldId, EffectStatusId, DocTypesId, ProvinceId);
    },
    CustomerInterFaceChangeUpdatev2: function (fieldId, EffectStatusId, DocTypesId, ProvinceId) {
        var url = lawsVn.virtualPath('/Ajax/Customers_InterfaceByFieldV2');
        var Provinceid = 0;
        var Year = 0;
        if (fieldId == null) {
            fieldId = 0;
        }
        if (EffectStatusId == null) {
            EffectStatusId = 0;
        }
        if (DocTypesId == null) {
            DocTypesId = 0;
        }
        if (ProvinceId == null) {
            ProvinceId = 0;
        }
        var dataGetter = {
            'ProvinceId': ProvinceId,
            'fieldId': fieldId,
            'effectStatusId': EffectStatusId,
            'docTypeId': DocTypesId,
            'updateTargetId': "ContentByField",
            'actionName': "Customers_InterfaceByFieldV2",
            'pageSize': 20,
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#ContentByField").html(resp);
                $("#sectionContent").attr("data-fieldid", fieldId);
            });
    },
    TCVNResetField: function () {
        $('.fieldIdTCVN').removeClass('active');
        $("#ddlFieldTCVN")
            .removeAttr('selected')
            .find(':first') //find('[value=0]')
            .attr('selected', 'selected');
    },
    CustomerInterFaceTCVNC: function (fieldId) {
        var docTypeId = 0;
        $('#tblcontent').lawsExists(function () {
            docTypeId = $(this).data('doctype');
            if (typeof docTypeId == 'undefined') {
                docTypeId = 61;
            }
        });
        $.lawsAjax({
            url: lawsVn.virtualPath('/Ajax/Customers_InterfaceTCVN'),
            type: 'Get',
            dataType: 'html',
            data: {
                fieldId: fieldId,
                docTypeId: docTypeId
            },
            success: function (resp) {
                $("#Content").html(resp);
                $("#Content").LawScrollTo();
            }
        });
    },
    CustomerInterFaceTCVNCChangeDoctype: function (docTypesId, fieldId) {
        $("#tabcontentDoctype").attr("data-doctype", docTypesId);
        lawsVn.CustomerInterFaceTCVNC(fieldId, docTypesId);
    },
    CustomerInterFaceTCVNChangeField: function (fieldId) {
        lawsVn.CustomerInterFaceTCVNC(fieldId);
        $("#ddlFieldTCVN")
            .removeAttr('selected')
            .find(':first') //find('[value=0]')
            .attr('selected', 'selected');
    },
    CustomerInterFaceTCVNFieldFilter: function () {
        var fieldId = $("#dllField option:selected").val();
        lawsVn.CustomerInterFaceTCVNC(fieldId);
    },
    CustomerProvincesDelete: function (customerProvinceId) {
        var url = lawsVn.virtualPath('/Ajax/DeleteCustomerProvinces');
        var dataGetter = {
            'CustomerProvinceId': customerProvinceId
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                if (resp > 0) {
                    //alert("Xóa Tỉnh/TP thành công!");
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Xóa Tỉnh/TP thành công!'],
                        showIcon: false
                    });
                    $("#CustomerProvinces" + customerProvinceId).remove();
                } else {
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Xóa Tỉnh/TP lỗi. Xin vui lòng thử lại.'],
                        showIcon: false
                    });
                    //alert("Xóa Tỉnh/TP lỗi. Xin vui lòng thử lại.");
                }
            });
    },
    AddCustomerProvince: function (customerId) {

        var url = lawsVn.virtualPath('/Ajax/AddCustomerProvinces');
        var province = $("#dllProvince option:selected");
        var provinceId = province.val();
        var provinceName = province.attr('data-title');
        if (provinceId > 0) {
            var dataGetter = {
                'CustomerId': customerId,
                'ProvinceId': provinceId,
            };
            $.lawsVnAjax(url,
                'Get',
                dataGetter,
                function (resp) {
                    if (resp > 0) {
                        alert("Thêm Tỉnh/TP thành công!");
                        var addhtml = "<div class='item-vbdp' id='CustomerProvinces" +
                            resp +
                            "'>" +
                            provinceName +
                            "<a href='javascript:lawsVn.CustomerProvincesDelete(\"" +
                            resp +
                            "\")' class='icon-my'><img alt='avata-canhan' src='" +
                            lawsVnConfig.rootPath +
                            "assets/images/xoa2.png')\"/></a>" +
                            "</div>";
                        $("#ListProvinces").html($("#ListProvinces").html() + addhtml);
                    } else {
                        alert("Thêm Tỉnh/TP lỗi. Xin vui lòng thử lại.");
                    }
                });
        } else {
            alert("Xin vui lòng chọn Tỉnh/TP!");
        }
    },
    ListByFieldFilter: function (fieldId) {
        var selectFieldId = $("#dllField option:selected").val();
        var effectStatusId = $("#dllEffectStatus option:selected").val();
        var effectStatusName = $('input[name="effectStatusName"]').val();
        var organsId = $("#dllOrgans option:selected").val();
        var docTypesId = $("#dllDocTypes option:selected").val();
        if (selectFieldId > 0) {
            fieldId = selectFieldId;
        }
        $.lawsAjax({
            url: lawsVn.virtualPath('/Ajax/Docs_GetViewSearch'),
            dataType: 'html',
            data: {
                fieldId: fieldId,
                effectStatusId: effectStatusId,
                effectStatusName: effectStatusName,
                organId: organsId,
                docTypeId: docTypesId
            },
            success: function (resp) {
                $("#ListByField").html(resp);
                var totalpage = $("#tblcontent").attr('data-totalpage');
                var pageindex = $("#tblcontent").attr('data-pageindex');
                var pageCount = $("#tblcontent").attr('data-pagecount');
                if (totalpage === undefined) {
                    totalpage = 0;
                }
                if (pageindex === undefined) {
                    pageindex = 0;
                }
                if (pageindex <= 0) {
                    pageindex = 1;
                }
                var data = '';
                if (pageCount > 0) {
                    data += "<span>Tìm thấy <strong> " +
                        totalpage +
                        " văn bản </strong>(" +
                        pageindex +
                        "/" +
                        pageCount +
                        " trang)";
                } else data = "<span>Không tìm thấy kết quả.</strong>";
                data += "</span>";
                $("#txtnumberresultfound").html(data);
            }
        });
    },
    DropdownlistDefaulValue: function () {
        $('#ddlFieldId').lawsExists(function () {
            $('#ddlFieldId option')
                .removeAttr('selected')
                .filter('[value=0]')
                .attr('selected', true);
        });

        $('#ddlEffectStatusId').lawsExists(function () {
            $('#ddlEffectStatusId option')
                .removeAttr('selected')
                .filter('[value=0]')
                .attr('selected', true);
        });

        $('#ddlDocTypeId').lawsExists(function () {
            $('#ddlDocTypeId option')
                .removeAttr('selected')
                .filter('[value=0]')
                .attr('selected', true);
        });

        $('#ddlOrganId').lawsExists(function () {
            $('#ddlOrganId option')
                .removeAttr('selected')
                .filter('[value=0]')
                .attr('selected', true);
        });
    },
    ListByFieldUpdate: function (fieldId) {
        $('#ddlFieldId option')
            .removeAttr('selected')
            .filter('[value=' + fieldId + ']')
            .attr('selected', true);
        $('#ddlEffectStatusId option')
            .removeAttr('selected')
            .filter('[value=0]')
            .attr('selected', true);
        $('#ddlDocTypeId option')
            .removeAttr('selected')
            .filter('[value=0]')
            .attr('selected', true);
        $('#ddlOrganId option')
            .removeAttr('selected')
            .filter('[value=0]')
            .attr('selected', true);
    },
    updateEffectStatusName: function (effectStatusName) {
        $('input[name="effectStatusName"]').lawsExists(function () {
            $(this).val(effectStatusName);
        });
    },
    selectBankCode: function (BankCode, obj) {
        $("div.gallery a").find("img").removeClass("bankselected");
        $(obj).find("img").addClass("bankselected");
        $('input[id="hdfBankCode"]').lawsExists(function () {
            $(this).val(BankCode);
        });
        $('#bankSelectedName').lawsExists(function () {
            $(this).html($(obj).attr('title'));
        });

    },
    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
                    });
                }
            }
        });
    },
    searchfieldchange: function () {
        var keyword = $('#searchfield').val();
        var listfieldPQ = $('[id^="FieldIdVb_"]');
        var id;
        var name;
        var fieldPQ;
        if (listfieldPQ.length > 0) {
            for (var index = 0; index < listfieldPQ.length; index++) {
                fieldPQ = listfieldPQ[index];
                id = fieldPQ.getAttribute('value');
                name = fieldPQ.getAttribute('name');
                if (name.indexOf(keyword) == -1) {
                    $('#lirootvb_' + id).hide();
                } else {
                    $('#lirootvb_' + id).show();
                }
            }
        }
    },
    editCustomerFields: function () {
        $('<div id="editCustomerFields"></div>').lawsDialog({
            title: 'Lĩnh vực văn bản quan tâm',
            width: 800,
            dialogClass: 'lawsVnDialogTitle',
            hideClose: true,
            buttons: {},
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#editCustomerFields').load(lawsVn.virtualPath('/Ajax/EditCustomerFields'),
                    function () {
                        $(".content-scroll-1").mCustomScrollbar({
                            snapAmount: 40,
                            scrollButtons: { enable: true },
                            keyboard: { scrollAmount: 40 },
                            mouseWheel: { deltaFactor: 40 },
                            scrollInertia: 400
                        });
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    editCustomerFieldsTCVN: function () {
        $('<div id="editCustomerFields"></div>').lawsDialog({
            title: 'Lĩnh vực Tiêu chuẩn Việt Nam quan tâm',
            width: 800,
            dialogClass: 'lawsVnDialogTitle',
            hideClose: true,
            buttons: {},
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#editCustomerFields').load(lawsVn.virtualPath('/Ajax/EditCustomerFieldsTCVN'),
                    function () {
                        $(".content-scroll-1").mCustomScrollbar({
                            snapAmount: 40,
                            scrollButtons: { enable: true },
                            keyboard: { scrollAmount: 40 },
                            mouseWheel: { deltaFactor: 40 },
                            scrollInertia: 400
                        });
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    editCustomerFieldsV2: function (isvip) {
        var url = '/Ajax/EditCustomerFieldsV2';
        if (isvip == null) {isvip = false;}
        if (isvip) { url += "?layout=vip"; }
        $('<div id="editCustomerFieldsV2"></div>').lawsDialog({
            title: 'Chọn lĩnh vực văn bản quan tâm',
            width: 1110,
            position: { my: "center", at: "top+10", of: window.top },
            dialogClass: 'lawsVnDialogTitle',
            hideClose: false,
            buttons: {},
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#editCustomerFieldsV2').load(lawsVn.virtualPath(url),
                    function () {
                        $(".content-scroll-1").mCustomScrollbar({
                            snapAmount: 40,
                            scrollButtons: { enable: true },
                            keyboard: { scrollAmount: 40 },
                            mouseWheel: { deltaFactor: 40 },
                            scrollInertia: 400
                        });
                        lawsValidate.multiCheckboxRequired();
                        var form = $('#EditCustomerFieldsV2');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    editCustomerProvince: function () {
        $('<div id="editCustomerProvinces"></div>').lawsDialog({
            title: 'Tỉnh/ Thành phố quan tâm',
            width: 800,
            top: 20,
            position: { my: "center", at: "top+50", of: window.top },
            dialogClass: 'lawsVnDialogTitle',
            hideClose: false,
            buttons: {},
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#editCustomerProvinces').load(lawsVn.virtualPath('/Ajax/EditCustomerProvices'),
                    function () {
                        $(".content-scroll-1").mCustomScrollbar({
                            snapAmount: 40,
                            scrollButtons: { enable: true },
                            keyboard: { scrollAmount: 40 },
                            mouseWheel: { deltaFactor: 40 },
                            scrollInertia: 400
                        });
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    openPopupCropImg: function () {
        $('<div id="PopupCropImg"></div>').lawsDialog({
            title: 'Cập nhật ảnh đại diện',
            width: 500,
            height: 550,
            top: 20,
            position: { my: "center", at: "top+100", of: window.top },
            dialogClass: 'lawsVnDialogTitle',
            hideClose: false,
            buttons: {},
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#PopupCropImg').load(lawsVn.virtualPath('/Ajax/GetCropImg'),
                    function () {
                        $(".content-scroll-1").mCustomScrollbar({
                            snapAmount: 40,
                            scrollButtons: { enable: true },
                            keyboard: { scrollAmount: 40 },
                            mouseWheel: { deltaFactor: 40 },
                            scrollInertia: 400
                        });
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    openPopupCropCoverImg: function () {
        $('<div id="PopupCropCoverImg"></div>').lawsDialog({
            title: 'Cập nhật ảnh bìa',
            width: 500,
            height: 550,
            top: 20,
            position: { my: "center", at: "top+100", of: window.top },
            dialogClass: 'lawsVnDialogTitle',
            hideClose: false,
            buttons: {},
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#PopupCropCoverImg').load(lawsVn.virtualPath('/Ajax/GetCropCoverImg'),
                    function () {
                        $(".content-scroll-1").mCustomScrollbar({
                            snapAmount: 40,
                            scrollButtons: { enable: true },
                            keyboard: { scrollAmount: 40 },
                            mouseWheel: { deltaFactor: 40 },
                            scrollInertia: 400
                        });
                    });
                $('#loading').fadeOut('normal');
            }
        });
    },
    login: function () {
        $('#login-form-target').lawsExists(function () {
            $(this).removeClass('target-hidden').addClass('target-expanded');
        });
        //$('<div id="lawsVnLogin"></div>').lawsDialog({
        //    title: '',
        //    width: 300,
        //    buttons: {},
        //    hideClose: true,
        //    closeText: 'Đóng',
        //    onCreate: function () {
        //        $('#loading').fadeIn('normal');
        //    },
        //    onOpen: function () {
        //        $('#lawsVnLogin').load(lawsVn.virtualPath('/Ajax/PartialLogin'),
        //            function () {
        //                var form = $('#lawsVnLoginForm');
        //                form.preventDoubleSubmitForm();
        //                $('#ReturnUrl').val(lawsVnConfig.returnUrl);
        //                form.removeData('validator');
        //                form.removeData('unobtrusiveValidation');
        //                $.validator.unobtrusive.parse(form);
        //                var returnUrl = window.location.href.replace(/.*\/\/[^\/]*/, '');
        //                $('#lawsVnLoginForm #ReturnUrl').val(returnUrl);
        //            });
        //        $('#loading').fadeOut('normal');
        //    }
        //});
    },
    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');
            }
        });
    },
    changePasswordVIP: function () {
        var $div = $('<div />').appendTo('body');
        $div.attr('id', 'changePassword');
        $('#loading').fadeIn('normal');
        $('#changePassword').load(lawsVn.virtualPath('/Ajax/PartialChangePasswordVIP'),
            function () {
                var form = $('#lawsVnChangePasswordForm');
                form.removeData('validator');
                form.removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse(form);
                $('#loading').fadeOut('normal');
            });
        //$('<div id="changePassword"></div>').lawsDialog({
        //    onCreate: function () {
        //        $('#loading').fadeIn('normal');
        //    },
        //    onOpen: function () {
                
        //        $('#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');
            }
        });
    },
    sendQuestion: function () {
        $('<div id="lawSendQuestions"></div>').lawsDialog({
            title: '',
            width: 800,
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#lawSendQuestions').load(lawsVn.virtualPath('/Ajax/PartialSendQuestions'),
                    function () {
                        var form = $('#SendQuestionForm');
                        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');
            }
        });
    }, docRegistMail: function () {
        $('<div id="docRegistMail"></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 () {
                $('#docRegistMail').load(lawsVn.virtualPath('/Ajax/PartialRegisterMail'),
                    function () {
                        var form = $('#RegisterMailForm');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                        if (typeof grecaptcha !== 'undefined' && grecaptcha && grecaptcha.reset) {
                            grecaptcha.render('NewsLetterEmailReCaptchaToken', {
                                'sitekey': '6Ld_KKgUAAAAALzeQ_4iQZKotSGsnX0EjtP6IjEw',
                                'callback': function (token) {
                                    $('#NewsLetterEmailReCaptchaToken').val(token);
                                },
                                'size': 'invisible'
                            });
                            //grecaptcha.reset(); 
                        }
                    });
                $('#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');
                    }
                }
            ]
        });
    },
    promotionCodeCheckForm: function (a) {
        $('#promotionCodeCheckForm').lawsExists(function () {
            if (a === 1) {
                $(this).show();
            } else if (a === 2) {
                $(this).hide();
            }
        });
    },
    SearchFilter: function () {
        var keyword = $("#divcontent").attr('data-keyword');
        var SearchOptions = $("#divcontent").attr('data-searchoptions');
        var docgroupId = $("#divcontent").attr('data-docgroupid');
        var datefrom = $("#divcontent").attr('data-datefrom');
        var dateto = $("#divcontent").attr('data-dateto');
        var OrganId = $("#divcontent").attr('data-organid');
        var LanguageId = $("#divcontent").attr('data-languageid');
        var SignerName = $("#divcontent").attr('data-signername');
        var doctypeId = $("#dllDocTypes option:selected").val();
        var EffectStatusId = $("#dllEffectStatus option:selected").val();
        var FieldId = $("#dllField option:selected").val();

        lawsVn.SearchSelect(keyword,
            SearchOptions,
            docgroupId,
            datefrom,
            dateto,
            OrganId,
            LanguageId,
            SignerName,
            doctypeId,
            EffectStatusId,
            FieldId);
    },
    SearchSelect: function (keyword,
        SearchOptions,
        docgroupId,
        datefrom,
        dateto,
        OrganId,
        LanguageId,
        SignerName,
        doctypeId,
        EffectStatusId,
        FieldId) {
        var url = lawsVn.virtualPath('/Ajax/Search_GetViewSearch');
        if (keyword == null) {
            keyword = "";
        }
        if (docgroupId == null) {
            docgroupId = 0;
        }
        if (SearchOptions == null) {
            SearchOptions = 0;
        }
        if (doctypeId == null) {
            doctypeId = 0;
        }
        if (OrganId == null) {
            OrganId = 0;
        }
        if (EffectStatusId == null) {
            EffectStatusId = 0;
        }
        if (FieldId == null) {
            FieldId = 0;
        }
        if (LanguageId == null) {
            LanguageId = 0;
        }
        if (SignerName == null) {
            OrganId = "";
        }
        if (datefrom == null) {
            datefrom = "";
        }
        if (dateto == null) {
            dateto = "";
        }
        var OrderBy = $("#dllOrderByClauses option:selected").val();
        if (OrderBy == null) {
            OrderBy = "";
        }
        var dataGetter = {
            'keyword': keyword, //encodeURIComponent(keyword),
            'DocGroupId': docgroupId,
            'SearchOptions': SearchOptions,
            'DateFrom': datefrom,
            'DateTo': dateto,
            'languageid': LanguageId,
            'SignerName': SignerName,
            'fieldId': FieldId,
            'effectStatusId': EffectStatusId,
            'organId': OrganId,
            'docTypeId': doctypeId,
            'OrderBy': OrderBy
        };
        $.lawsVnAjax(url,
            'Get',
            dataGetter,
            function (resp) {
                $("#ListDocsViews").html(resp);
                var totalpage = $("#tblcontent").attr('data-totalpage');
                var pageindex = $("#tblcontent").attr('data-pageindex');
                var pageCount = $("#tblcontent").attr('data-pagecount');
                var pagesize = $("#tblcontent").attr('data-pagesize');
                if (totalpage === undefined) {
                    totalpage = 0;
                }
                if (pageindex === undefined) {
                    pageindex = 0;
                }
                if (pagesize === undefined) {
                    pageindex = 0;
                }
                if (pageindex <= 0) {
                    pageindex = 1;
                }
                var data = " <strong>Tìm thấy <span class='color2'>" +
                    totalpage +
                    "</span> văn bản với từ khóa \"<span class='color2'>" +
                    keyword +
                    "</span>\"</strong>";
                if (pageCount >= 0) {
                    data += "(" + pageindex + "/" + pageCount + " trang)";
                }
                var datanumerpage = "<strong>Kết quả 1-" + pagesize + " trong " + totalpage + " văn bản </strong>";
                $("#txtnumberresultfound").html(data);
                $("#txtnumberpage").html(datanumerpage);

            });
    },
    accountProfile: {
        deleteOneFieldById: function (customerFieldId) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                width: 360,
                messages: ['Xác nhận xóa lĩnh vực đã chọn ?'],
                onCreate: function () {
                    var elem = $('.content-thongbao');
                    elem.removeAttr('width');
                    elem.css('width', '91.7%');
                },
                buttons: [
                    {
                        text: lawsVn.Resource.getMessages('Close'),
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: lawsVn.Resource.getMessages('Agree'),
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/DeleteOneFieldById'),
                                data: { customerFieldId: customerFieldId },
                                success: function (data) {
                                    if (data.Completed) {
                                        $().lawsDialog({
                                            messages: [data.Message],
                                            dialogClass: 'lawsVnDialogTitle',
                                            showIcon: false,
                                            onOpen: function () {
                                                $("#lawsVnLogin").dialog("close");
                                            },
                                            onClose: function () {
                                                if (data.Data != null) {
                                                    var resultHtml = '<div class="tag_lv content-scroll-1" style="max-height: 350px">', obj = data.Data, item, item2;
                                                    if (obj.ListFields != null && obj.ListFields.length) {
                                                        if (obj.ListCustomerFields != null && obj.ListCustomerFields.length) {
                                                            for (var i = 0; i < obj.ListFields.length; i++) {
                                                                item = obj.ListFields[i];
                                                                for (var j = 0; j < obj.ListCustomerFields.length; j++) {
                                                                    item2 = obj.ListCustomerFields[j];
                                                                    if (item.FieldId == item2.FieldId && item2.DocGroupId == 1) {
                                                                        resultHtml += '<span class="tag_a">' +
                                                                            '<i class="icontag fixxx xoa-linh-vuc" title="Xóa lĩnh vực ' + item.FieldName + '" data-id="' + item2.CustomerFieldId + '">' +
                                                                            '<img src="/assets/images/icondell.png" alt="xoa linh vuc"/></i>' + item.FieldName + '</span>';
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    resultHtml += '</div>';
                                                    $('#popupThemlinhvuc').find('.ct_popup2').html('<p>Đang tải dữ liệu. Quý khách vui lòng đợi trong giây lát...</p>');
                                                    $('#popupThemlinhvuc').hide();
                                                    $('#linhvucvanbanquantam').html(resultHtml).promise().done(function () {
                                                        $('.content-scroll-1').lawsExists(function () {
                                                            $(this).mCustomScrollbar({
                                                                snapAmount: 40,
                                                                scrollButtons: { enable: true },
                                                                keyboard: { scrollAmount: 40 },
                                                                mouseWheel: { deltaFactor: 40 },
                                                                scrollInertia: 400
                                                            });
                                                        });
                                                    });
                                                }
                                            }
                                        });
                                    } 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
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        }
    },
    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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
    },
    myMesssages: {
        deleteMessage: function (messageId) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận xóa tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/MessageDelete'),
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId, actionTypeId: 1 },
                                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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        deleteMessages: function (actionTypeId) {
            var messageId = $('input[type=checkbox][name=chkMessages]:checked').map(function (_, el) {
                return $(el).val();
            }).get();
            if (!messageId.length) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách chưa chọn tin nhắn cần xóa.'],
                    showIcon: false
                });
                return;
            }
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận xóa tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/MessageDelete'),
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId, actionTypeId: actionTypeId },
                                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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        saveMessage: function (messageId) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận lưu tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVnConfig.rootPath + 'Ajax/MessageSave',
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId },
                                success: function (resp) {
                                    if (resp.Message !== null && resp.Message.length > 0) {
                                        $().lawsDialog({
                                            dialogClass: 'lawsVnDialogTitle',
                                            messages: [resp.Message],
                                            onClose: function () {
                                                if (resp.Completed && resp.ReturnUrl != null && resp.ReturnUrl.length > 0) {
                                                    window.location.href = resp.ReturnUrl;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        saveMessages: function (actionTypeId) {
            var messageId = $('.checkbox-mail input[type=checkbox]:checked').map(function (_, el) {
                return $(el).val();
            }).get();
            if (!messageId.length) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách chưa chọn tin nhắn cần lưu.'],
                    showIcon: false
                });
                return;
            }
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận lưu tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVnConfig.rootPath + 'Ajax/MessageSave',
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId, actionTypeId: actionTypeId },
                                success: function (resp) {
                                    if (resp.Message !== void 0 && 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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        unsaveMessage: function (messageId) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận bỏ lưu tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVnConfig.rootPath + 'Ajax/MessageUnSave',
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId },
                                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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        unsaveMessages: function (actionTypeId) {
            var messageId = $('.checkbox-mail input[type=checkbox]:checked').map(function (_, el) {
                return $(el).val();
            }).get();
            if (!messageId.length) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách chưa chọn tin nhắn cần bỏ lưu.'],
                    showIcon: false
                });
                return;
            }
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận bỏ lưu tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVnConfig.rootPath + 'Ajax/MessageUnSave',
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId, actionTypeId: actionTypeId },
                                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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        readMessage: function (messageId) {
            $('<div id="readMessage"></div>').lawsDialog({
                title: 'Nội dung tin nhắn:',
                dialogClass: 'lawsVnDialogTitle',
                width: 600,
                minHeight: 300,
                onCreate: function () {
                    $('#loading').fadeIn('normal');
                },
                onOpen: function () {
                    $('#readMessage').load(lawsVn.virtualPath('/Ajax/MessageRead?messageId=' + messageId), function () {
                        var count = $('#RowCountNotifyMessages').text();
                        if (!$.isNumeric(count)) {
                            count = 0;
                        } else count = parseInt(count);
                        if (count > 0) {
                            $('#RowCountNotifyMessages').text(count - 1);
                            $('#thongbao-' + messageId).remove();
                            $('.countMyMessages').text('(' + (count - 1) + ')');
                        }
                        $('#message-' + messageId).addClass('fontnomal');
                        $('#message-time-' + messageId).addClass('fontnomal');

                    });
                    $('#loading').fadeOut('normal');
                }
            });
        },
        setStart: function (messageId, actionType) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận gắn sao cho tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/MessagesSetStar'),
                                data: { messageId: messageId, actionType: actionType },
                                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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        setStarts: function (actionTypeId) {
            var messageId = $('.checkbox-mail input[type=checkbox]:checked').map(function (_, el) {
                return $(el).val();
            }).get();
            if (!messageId.length) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách chưa chọn tin nhắn gắn sao.'],
                    showIcon: false
                });
                return;
            }
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận gắn sao tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVnConfig.rootPath + 'Ajax/StarMessage',
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId, actionTypeId: actionTypeId },
                                success: function (resp) {
                                    if (resp.Message !== void 0 && 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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        unStart: function (messageId, actionType) {
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận bỏ gắn sao cho tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/MessagesUnStar'),
                                data: { messageId: messageId, actionType: actionType },
                                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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        unStarMessages: function (actionTypeId) {
            var messageId = $('.checkbox-mail input[type=checkbox]:checked').map(function (_, el) {
                return $(el).val();
            }).get();
            if (!messageId.length) {
                $().lawsDialog({
                    dialogClass: 'lawsVnDialogTitle',
                    messages: ['Quý khách chưa chọn tin nhắn cần bỏ gắn sao.'],
                    showIcon: false
                });
                return;
            }
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                messages: ['Xác nhận bỏ gắn sao tin nhắn ?'],
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVnConfig.rootPath + 'Ajax/UnStarMessage',
                                type: 'Post',
                                traditional: true,
                                data: { messageId: messageId, actionTypeId: actionTypeId },
                                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;
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        }
    },
    myDocuments: {
        getPage: function (docGroupId, showNumberOfResults, languageId) {
            var url = lawsVnConfig.rootPath + '';
            var dataGetter = {
                docGroupId: docGroupId,
                fieldId: $('select[name="fieldId"] option:selected').val(),
                organId: $('select[name="organId"] option:selected').val(),
                effectStatusId: $('select[name="effectStatusId"] option:selected').val(),
                docTypeId: $('select[name="docTypeId"] option:selected').val(),
                showNumberOfResults: showNumberOfResults
            }
        },
        deleteCustomerDocs: function (docGroupId, docId, type) { //type = 1 : Vb quan tâm, 2: thông báo hiệu lực
            $().lawsDialog({
                dialogClass: 'lawsVnDialogTitle',
                width: 360,
                messages: ['Xác nhận xóa ' + (type === 1 ? ' văn bản quan tâm' : (type === 2 ? ' thông báo hiệu lực' : '')) + ' ?'],
                onCreate: function () {
                    var elem = $('.content-thongbao');
                    elem.removeAttr('width');
                    elem.css('width', '91.7%');
                },
                buttons: [
                    {
                        text: 'Đóng',
                        'class': 'btn-thongbao1',
                        click: function () {
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: 'Đồng ý',
                        click: function () {
                            $(this).dialog('close');
                            $.lawsAjax({
                                url: lawsVn.virtualPath('/Ajax/DeleteDocument'),
                                data: { docGroupId: docGroupId, docId: docId, type: type },
                                success: function (resp) {
                                    if (resp.Completed &&
                                        resp.ReturnUrl != null &&
                                        resp.ReturnUrl.length > 0) {
                                        if (resp.Data != null) {
                                            var customerDocsResponse;
                                            luatVietnamStore.getItem(
                                                'luatvietnam_customerdocs_' + resp.Data.DocId + '_' + resp.Data.CustomerId + '_' + resp.Data.LanguageId,
                                                function (response) {
                                                    if (response !== null) {
                                                        customerDocsResponse = response;
                                                    }
                                                });
                                            if (customerDocsResponse === undefined) {
                                                luatVietnamStore.setItem(
                                                    'luatvietnam_customerdocs_' +
                                                    resp.Data.DocId +
                                                    '_' +
                                                    resp.Data.CustomerId +
                                                    '_' +
                                                    resp.Data.LanguageId,
                                                    {
                                                        'documentSaved': 0,
                                                        'hasTrackedDocumentEffect': 0
                                                    },
                                                    15 * 60);
                                            } else {
                                                luatVietnamStore.setItem(
                                                    'luatvietnam_customerdocs_' +
                                                    resp.Data.DocId +
                                                    '_' +
                                                    resp.Data.CustomerId +
                                                    '_' +
                                                    resp.Data.LanguageId,
                                                    {
                                                        'documentSaved': type == 1 ? 0 : customerDocsResponse.documentSaved,
                                                        'hasTrackedDocumentEffect': type == 2 ? 0 :customerDocsResponse.hasTrackedDocumentEffect
                                                    },
                                                    15 * 60);
                                            }
                                        }
                                        setTimeout(function() {
                                            window.location.href = resp.ReturnUrl;
                                        },300);
                                    }
                                }
                            });
                        }
                    }
                ]
            });
        },
        subscriptionNoticeOfValidity: function (docId) {
            $.lawsAjax({
                url: lawsVn.virtualPath('/Ajax/SubscriptionNoticeOfValidity'),
                data: { docId: docId },
                success: function (resp) {
                    if (resp.Message != null && resp.Message.length > 0) {
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: [resp.Message],
                            showIcon: false
                        });
                    }
                }
            });
        }
    },
    logs: {
        articleLogs: function (articleId, categoryId) {
            window.setTimeout(function () {

                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/ArticleLogs'),
                    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);
                    }
                });

            }, 0);
        },
        docViewLogs: function (docId, docGroupId, actionTypeId) {
            window.setTimeout(function () {

                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/DocViewLogs'),
                    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);
                    }
                });

            }, 0);
        },
        docSearchLogs: function (keywords, dateFrom, dateTo, docTypeId, organId, signerId, fieldId) {
            window.setTimeout(function () {

                $.lawsAjax({
                    url: lawsVn.virtualPath('/Ajax/DocSearchLogs'),
                    data: { keywords: keywords, dateFrom: dateFrom, dateTo: dateTo, docTypeId: docTypeId, organId: organId, signerId: signerId, fieldId: fieldId },
                    beforeSend: {},
                    success: function (resp) {
                        if (!resp.Completed) {
                            if (resp.Message != null && resp.Message.length > 0) {
                                console.log('docSearchLogs Error: ' + resp.Message);
                            }
                        }
                    },
                    error: function (resp) {
                        console.log('docSearchLogs Error: ' + resp.Message);
                    }
                });

            }, 0);
        },
        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);
        }
    },
    search: {
        getId: function (el) {
            var id = 0;
            $('.xoa.' + el).lawsExists(function () {
                var item = $('.item-sub-qktk').children('.xoa.' + el).last();
                id = item.data('id');
            });
            return id;
        },
        start: function () {
            //trả về tất cả elements input theo form
            var form = $('#SearchForm').lawFields();
            var isSearchExact = 0;
            if (typeof form.SearchExact == 'undefined') {
                isSearchExact = 0;
            } else isSearchExact = form.SearchExact.val();
            var docGroupId = form.DocGroupId.val();
            if (lawsVnConfig.DocGroupId > 0) {
                docGroupId = lawsVnConfig.DocGroupId;
            }
            $.lawsAjax({
                url: lawsVn.virtualPath('/Ajax/Docs_GetViewSearchWithKeyword'),
                type: 'Post',
                dataType: 'html',
                data: {
                    keywords: form.Keywords.val(),
                    docGroupId: docGroupId,
                    searchOptions: form.SearchOptions.val(),
                    isSearchExact: isSearchExact,
                    dateFrom: form.DateFrom.val(),
                    dateTo: form.DateTo.val(),
                    languageid: form.LanguageId.val(),
                    signerId: form.SignerId.val(),
                    fieldId: lawsVnConfig.FieldId == 0 ? form.FieldId.val() : lawsVnConfig.FieldId,
                    effectStatusId: lawsVnConfig.EffectStatusId == 0 ? form.EffectStatusId.val() : lawsVnConfig.EffectStatusId,
                    organId: lawsVnConfig.OrganId == 0 ? form.OrganId.val() : lawsVnConfig.OrganId,
                    docTypeId: lawsVnConfig.DocTypeId == 0 ? form.DocTypeId.val() : lawsVnConfig.DocTypeId,
                    year: lawsVnConfig.Year
                },
                success: function (resp) {
                    $('#ListDocsViews').html(resp);
                    lawsVn.searchOnSuccess();
                    $('#ListDocsViews').LawScrollTo();
                }
            });

        },
        prioritizeKeyword: function () {
            var temp = { left: null, right: null };
            var temp2 = { left: null, right: null };
            var swap = true;
            var keywords = '';
            $('#Keywords').lawsExists(function () {
                keywords = $(this).val().toLowerCase();
            });
            $('.row-first-news').lawsExists(function () {
                var n = $('.row-first-news');
                var l = n.length;
                for (var i = 0; i < l && swap === true; i++) {
                    swap = false;
                    for (var k = 0; k < l - 1; k++) {
                        var e = $(n[k]);
                        var h = $(n[k + 1]);
                        var f = e.find('.news-left-post>a');
                        var g = h.find('.news-left-post>a');
                        if (f.text().toLowerCase().indexOf(keywords) === -1 && g.text().toLowerCase().indexOf(keywords) !== -1) {
                            swap = true;
                            temp.left = f.html();
                            temp.right = e.find('.post-time-right-timkiem').html();
                            temp2.left = g.html();
                            temp2.right = h.find('.post-time-right-timkiem').html();

                            f.html(temp2.left);
                            e.find('.post-time-right-timkiem').html(temp2.right);
                            g.html(temp.left);
                            h.find('.post-time-right-timkiem').html(temp.right);
                        }
                    }
                }
            });
        }
    },
    progressInView: function () {
        var pageTop = $(window).scrollTop();
        var pageBottom = pageTop + $(window).innerHeight();
        var globalList = $(window).data('globalListDocIndex');
        for (var i = 0; i < globalList.length; i++) {
            var diList = globalList[i].docIndexList;
            for (var j = 0; j < diList.length; j++) {
                var di = diList[j];
                var el = $('a.' + di.obj[0].id);
                if (el.length) {
                    if ((di.bottom >= pageTop) &&
                        (di.top <= pageBottom) &&
                        (di.bottom <= pageBottom) &&
                        (di.top >= pageTop)) {
                        setTimeout(function () {
                            $('.content-scroll-1').mCustomScrollbar('scrollTo', el.position().top - $('.hearder-fix').outerHeight());
                        }, 300);
                        el.closest('.item-article').prevAll().find('a').css({ 'color': '#0077bf !important', 'font-weight': 'bold' });
                    } else if (pageTop <= di.top) {
                        el.closest('.item-article').nextAll().find('a').removeAttr('style');
                        return false;
                    }
                }
            }
        }
    }
}
//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);
            });
        }
    }
});

(function ($) {
    $.fn.lawsVnContentViewed = function (options) {
        var defaultOptions = {
            limit: 10,
            image: lawsVn.virtualPath('/assets/images/van-ban.png'),
            doc: {}
        }
        options = $.extend(defaultOptions, options);
        var proc = {
            getAllDocs: function () {
                try {
                    var lawsVnContentViewed =
                        localStorage.lawsVnContentViewed ? localStorage.lawsVnContentViewed : '[]';
                    var doc = JSON.parse(lawsVnContentViewed);
                    return doc;
                } catch (e) {
                    return [];
                }
            },
            setAllDocs: function (docs) {
                localStorage.lawsVnContentViewed = JSON.stringify(docs);
            },
            setDoc: function () {
                var index = proc.getIndexDoc(options.doc.id);
                if (index < 0) {
                    proc.addDoc();
                }
            },
            getIndexDoc: function (id) {
                var index = -1;
                var docs = proc.getAllDocs();
                $.each(docs, function (i, value) {
                    if (value.id === id) {
                        index = i;
                        return;
                    }
                });
                return index;
            },
            removeDoc: function (id) {
                var docs = proc.getAllDocs();
                //lọc các văn bản có id khác id vb muốn xóa
                docs = $.grep(docs,
                    function (value) {
                        return value.id !== id;
                    });
                proc.setAllDocs(docs);
            },
            addDoc: function () {
                var docs = proc.getAllDocs();
                docs.push({
                    id: options.doc.id,
                    name: options.doc.name,
                    title: options.doc.title,
                    summary: options.doc.summary,
                    datetime: options.doc.datetime,
                    url: options.doc.url,
                    image: options.doc.image.length > 0 ? options.doc.image : options.image
                });
                proc.setAllDocs(docs);
                if (docs.length > options.limit) {
                    proc.removeDoc(docs[0].id);
                }
            },
            resetAllDocs: function () {
                proc.setAllDocs([]);
            },
            getTotalDocs: function () {
                var docs = proc.getAllDocs();
                return docs.length;
            },
            getContent: function (el) {
                var docs = proc.getAllDocs();
                el.append(
                    '<div class="cat-box content-recent"><section class="view-post-content">' +
                    '<div class="padding-view">' +
                    '<div class="cat-title">' +
                    '<h4><span class="cat-box-title vien">NỘI DUNG ĐÃ XEM</span></h4>' +
                    '</div>' +
                    '<div id="owl-demo-c3" class="owl-carousel"></div>' +
                    '<div class="customNavigation">' +
                    '<a class="btn prev33 btn1"></a>' +
                    '<a class="btn next33 btn2"></a>' +
                    '</div>' +
                    '</div>' +
                    '</section></div>'
                );
                for (var i = docs.length - 1; i >= 0; i--) {
                    $('#owl-demo-c3').append(
                        '<div class="item-recent-post">' +
                        '<div class="post-thumbnail wg">' +
                        '<a href="' + docs[i].url + '" title="' + docs[i].title + '" class="thumb80"><img alt="thumb90" src="' + docs[i].image + '"></a>' +
                        '</div>' +
                        '<div class="recent-view">' +
                        '<a href="' + docs[i].url + '" title="' + docs[i].title + '" class="post-title normal">' + docs[i].name + '</a>' +
                        '<p class="tie-date daxem"> (' + docs[i].datetime + ') </p>' +
                        '</div>' +
                        '</div>'
                    );
                }
            }
        }
        return this.each(function () {
            var self = $(this);
            self.lawsExists(function () {
                proc.setDoc();
                proc.getContent(self);
            });
        });
    }
})(jQuery);

(function ($) {
    $.fn.extend({
        lawsVnFlip: function (options) {
            var defaults = {
                btnFront: '.lawsVnFlipFront',
                divFront: '.divFront',
                btnBack: '.lawsVnFlipBack',
                divBack: '.divBack',
                duration: 300
            };
            options = $.extend({}, defaults, options);
            return this.each(function () {
                var front = $(options.divFront);
                var back = $(options.divBack);

                var margin = front.width() / 2;
                var width = front.width();
                var height = front.height();
                back.css({
                    width: '0',
                    height: '' + height + 'px',
                    marginLeft: '' + margin + 'px',
                    opacity: '0'
                });


                $(options.btnFront).on('click', function (e) {
                    e.preventDefault();
                    //hiện div back, ẩn div front
                    var toShow = back,
                        toHide = front;

                    // ẩn slide
                    (toHide).animate({
                        width: 0,
                        height: height,
                        marginLeft: margin,
                        opacity: 0
                    }, options.duration, function () {

                        // hiện slide
                        (toShow).animate({
                            width: width,
                            height: height,
                            marginLeft: 0,
                            opacity: 1
                        }, options.duration).show();
                    });
                });

                $(options.btnBack).on('click', function (e) {
                    e.preventDefault();
                    //hiện div front, ẩn div back
                    var toShow = front,
                        toHide = back;

                    // ẩn slide
                    (toHide).animate({
                        width: 0,
                        height: height,
                        marginLeft: margin,
                        opacity: 0
                    }, options.duration, function () {

                        // hiện slide
                        (toShow).animate({
                            width: width,
                            height: height,
                            marginLeft: 0,
                            opacity: 1
                        }, options.duration).show();
                    });
                });
            });
        }
    });

})(jQuery);

$.fn.extend({
    LawScrollTo: function () {
        $(this).lawsExists(function () {
            var x = $(this).offset().top - 100;
            jQuery('html,body').animate({ scrollTop: x }, 100);
        });
    }
});
$(document).on('click',
    '#gopyv2',
    function (event) {
        event.preventDefault();
        console.log('gopyv2 click');
        $('<div id="GopYv2"></div>').lawsDialog({
            title: '',
            width: 650,
            position: { my: "center", at: "top+50", of: window.top },
            buttons: {},
            hideClose: false,
            closeText: 'Đóng',
            onCreate: function () {
                $('#loading').fadeIn('normal');
            },
            onOpen: function () {
                $('#GopYv2').load(lawsVn.virtualPath('/Ajax/PartialGopY2'),
                    function () {
                        var form = $('#FormGopYv2');
                        form.removeData('validator');
                        form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse(form);
                    });
                $('#loading').fadeOut('normal');
            }
        });
    });
$.fn.clearErrors = function () {
    $(this).each(function () {
        $(this).trigger('reset.unobtrusiveValidation');
    });
};
$.fn.DocDetailTrialV2 = function (options) {
    var defaults = {
        contentClass: '.tabcontent',
        defaultTab: '#chidanthaydoi',
        chidanthaydoiTab: '#chidanthaydoi',
        noidungmixTab: '#noidungmix',
        rightBoxNotShowInDiagram: '#rightBoxNotShowInDiagram',
        divDocFields: 'DocFields',
        divDocOthers: 'DocOthers',
        divTheodoihieulucvb: '.divTheodoihieulucvb',
        boxLienket: '#lk_huuich',
        tabClass: '.tab-nav-item-ad',
        tabClass2: '.tab-nav-item-ad2',
        item_mucluc: 'div[class*=demuc]',
        chuthich: '.fix_ghichu',
        mucluc: '#muclucvanban',
        print: '.docPrint_v2',
        btnPopupMucluc: '#closePopupa',
        mucluc2: '#mucluc2',
        fontsize: '.fontsize-config',
        arrTabs: ['#tomtat', '#noidung', '#lienquan', '#hieuluc', '#luocdo', '#tienganh', '#taive', '#chidanthaydoi', '#noidungmix'],
        logs: {
            docId: 0,
            docGroupId: 0
        },
        customerId: 0,
        documentSaved: 0,
        hasTrackedDocumentEffect: 0,
        languageId: 1,
        localStorageCustomerDocsExpires: 15 * 60, //15 phút
        localStorageExpires: 24 * 60 * 60 * 30 //30 ngày
    }, opts = $.extend(defaults, options);
    var activeTab = '',
        getHash = function () {
            if (location.href.indexOf('#') !== -1) {
                var hash = location.href.substr(location.href.indexOf('#'));
                //for (var i = 0; i < opts.arrTabs.length; i++) {
                //    if (hash != '#noidungmix' && hash.startsWith(opts.arrTabs[i])) {
                //        hash = opts.arrTabs[i];
                //        break;
                //    }
                //}
                return hash;
            }
            else
                if (window.location.hash) {
                    return window.location.hash;
                }
            return '';
        }, currentPageY, maxHeight, expiry = 3600 * 24 * 30, viewMix = false, section, factor = 0.8, timelineMix2 = '', tabClick = false,
        showTab = function (tab, isScroll, islog) {
            
            currentPageY = 0;
            isScroll = isScroll === void 0 ? $('#tabPannel').hasClass('navsticky') : isScroll;
            if (!tab) {
                isScroll = false;
            }
            activeTab = tab || getHash();
            var activeDemuc = activeTab;
            scrollPagePosition();
            if (opts.arrTabs.indexOf(activeTab) === -1) {
                activeTab = $(opts.chidanthaydoiTab).length === 0 ? opts.arrTabs[1] : opts.defaultTab;
                if ($(opts.defaultTab).is(':visible')) activeTab = $(opts.chidanthaydoiTab).length === 0 ? opts.arrTabs[1] : opts.defaultTab;
                else activeTab = '#tomtat';
                //document.location.hash = activeTab;
            }
            if (activeTab === opts.chidanthaydoiTab && $(opts.chidanthaydoiTab).length === 0 || activeTab === opts.noidungmixTab && $(opts.noidungmixTab).length === 0) {
                activeTab = opts.arrTabs[1];
                if ($(opts.defaultTab).is(':visible')) activeTab = opts.arrTabs[1];
                else activeTab = '#tomtat';
                //document.location.hash = activeTab;
            }
            $('.doc-widget-bar').lawsExists(function () {
                $(this).removeClass('mucluc_rows2').addClass('mucluc_rows');
                $(this).children('.bell-c1.bell-c1-fix').hide();
            });
            if (activeTab === opts.chidanthaydoiTab || activeTab === opts.noidungmixTab) {
                $(opts.chuthich).show();
                if (activeTab === opts.chidanthaydoiTab) {
                    if ($(opts.mucluc2).length) {
                        $(opts.btnPopupMucluc).show();
                    } else {
                        $(opts.btnPopupMucluc).hide();
                    }
                    if ($(activeTab).find('embed').length) {
                        $('.doc-widget-bar').lawsExists(function () {
                            $(this).removeClass('mucluc_rows').addClass('mucluc_rows2');
                            $(this).children('.bell-c1.bell-c1-fix').show();
                        });
                    }
                } else if (activeTab === opts.noidungmixTab) {
                    if ($('#mucluc3').length) {
                        $(opts.btnPopupMucluc).show();
                    } else {
                        $(opts.btnPopupMucluc).hide();
                    }
                }

                $(opts.btnPopupMucluc).lawsExists(function () {
                    $(this).addClass('mixx');
                });
                //$(opts.divTheodoihieulucvb).lawsExists(function () {
                //    $(this).hide();
                //});
                $('.btn-xem-vb').lawsExists(function () {
                    $(this).hide();
                });
                //if (activeTab === opts.chidanthaydoiTab) {
                //    $('#doccontentindex2').lawsExists(function () {
                //        $(this).show();
                //    });
                //}
                //else {
                //    $('#doccontentindex3').lawsExists(function () {
                //        $(this).show();
                //    });
                //}
                $('#doccontentindex').lawsExists(function () {
                    $(this).hide();
                });
                if ($(activeTab).find('.text_vb').length || $(activeTab).find('embed').length) {
                    //$(opts.fontsize).lawsExists(function () {
                    //    $(this).hide();
                    //});
                    $('.fontsizea').closest('.item-tien-ich').hide();
                    $('.loadcontent').lawsExists(function () {
                        $(this).hide();
                    });
                    maxHeight = $(activeTab + '.text_vb').height();
                    $('#slider').slider('value', 0);
                    $('.fixmucluc_new').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.innoidung').lawsExists(function () {
                        $(this).hide();
                    });
                } else {
                    //$(opts.fontsize).lawsExists(function () {
                    //    $(this).show();
                    //});
                    $('.fontsizea').closest('.item-tien-ich').show();
                    maxHeight = $(activeTab + '.content-entry').height();
                    $('.loadcontent').lawsExists(function () {
                        $(this).show();
                    });
                    $('.fixmucluc_new').lawsExists(function () {
                        $(this).show();
                    });
                    $('.innoidung').lawsExists(function () {
                        $(this).show();
                    });
                }
                if (activeTab === opts.chidanthaydoiTab) {
                    if ($(activeTab).find('.docContentRelated0').length == 0) {
                        $('.progress_w').addClass('fixx');
                        $('.fix_w').addClass('w88');
                    } else {
                        $('.progress_w').removeClass('fixx');
                        $('.fix_w').removeClass('w88');
                    }
                } else if (activeTab === opts.noidungmixTab) {
                    if ($('.tab-nav-item-ad', $('#tabPannel')).hasClass('unavailable')) {
                        $('.progress_w').removeClass('fixx');
                        $('.fix_w').removeClass('w88');
                    } else {
                        $('.progress_w').addClass('fixx');
                        $('.fix_w').addClass('w88');
                    }
                }
                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');
                    });
                }
            }
            else {
                if (activeTab === opts.arrTabs[1]) {
                    //$('#doccontentindex').lawsExists(function () {
                    //    $(this).show();
                    //});
                    $('#doccontentindex2').lawsExists(function () {
                        $(this).hide();
                    });
                    //$('.fixmucluc_new').lawsExists(function () {
                    //    $(this).show();
                    //});
                    if ($(activeTab).find('.thongbao-item2').length) {
                        $('.fontsizea').closest('.item-tien-ich').hide();
                    }
                    else $('.fontsizea').closest('.item-tien-ich').show();
                    if ($(activeTab).find('embed').length) {
                        $('.loadcontent').hide();
                        $('.fixmucluc_new').lawsExists(function () {
                            $(this).hide();
                        });
                        if ($(activeTab).find('#doc-content').length) {
                            $(activeTab).find('embed').show();
                            $('.btn-xem-vb').lawsExists(function () {
                                $(this).show();
                            });
                            $('#doc-content').lawsExists(function () {
                                $(this).hide();
                            });
                        };
                        $('.innoidung').lawsExists(function () {
                            $(this).hide();
                        });
                    } else {
                        $('.loadcontent').show();
                        $('.fixmucluc_new').lawsExists(function () {
                            $(this).show();
                        });
                        $('.innoidung').lawsExists(function () {
                            $(this).show();
                        });
                    }
                    $('.fontsize').lawsExists(function () {
                        $(this).show();
                    });
                    $('#advsTabNoidung').lawsExists(function () {
                        $(this).show();
                    });
                    $('.progress_w').removeClass('fixx');
                    $('.fix_w').removeClass('w88');
                } else {
                    if (activeTab == opts.arrTabs[4]) {
                        loadDiagramContent();
                    } else if (activeTab == opts.arrTabs[2]) {
                        loadDocRelateContent();
                    }
                    else if (activeTab == opts.arrTabs[3]) {
                        loadDocEffectContent();
                    }
                    else if (activeTab == opts.arrTabs[5]) {
                        /*if ($(activeTab).find('.no-content').length) {
                            $('.loadcontent').hide();
                            $('.fixmucluc_new').lawsExists(function () {
                                $(this).hide();
                            });
                        } else {
                            $('.loadcontent').show();
                        }*/
                        //loadDocEngContent();
                    }
                    if ($(activeTab).find('.text_vb').length) {
                        if (activeTab !== '#tomtat')
                            $('.innoidung').hide();
                        if (activeTab != opts.arrTabs[5]) {//khong phai tab tieng anh
                            //$('.doc-widget-bar').lawsExists(function () {
                            //    $(this).removeClass('mucluc_rows').addClass('mucluc_rows2');
                            //    $(this).children('.bell-c1.bell-c1-fix').show();
                            //});
                        }
                    }
                    else $('.innoidung').show();
                    $('.fontsize').lawsExists(function () {
                        $(this).hide();
                    });
                    $('#advsTabNoidung').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.loadcontent').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.fontsizea').closest('.item-tien-ich').hide();
                    $('.fixmucluc_new').lawsExists(function () {
                        $(this).hide();
                    });
                    $('.btn-xem-vb').lawsExists(function () {
                        $(this).hide();
                    });
                }
                //
                $(opts.btnPopupMucluc).lawsExists(function () {
                    //if (!$(this).is(':visible')) {
                    //    $(this).show();
                    //}
                    $(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');
                    });
                }
                $('#doccontentindex').lawsExists(function () {
                    $(this).show();
                });
                $('#doccontentindex2').lawsExists(function () {
                    $(this).hide();
                });
                $('#doccontentindex3').lawsExists(function () {
                    $(this).hide();
                });
                $(opts.chuthich).hide();
                $(opts.divTheodoihieulucvb).lawsExists(function () {
                    $(this).show();
                });
            }
            if ($('.tab-nav-item-ad[data-href=#noidung]').hasClass('unavailable')) {
                $('.docPrint_v2').closest('.li-print').lawsExists(function () {
                    $(this).hide();
                });
            }
            if (activeTab === '#luocdo') {
                var DocgroupOfTab = 1;
                var attrDocgroup = $(activeTab).attr('data-docgroup');
                if (typeof attrDocgroup !== typeof undefined && attrDocgroup !== false) {
                    DocgroupOfTab = attrDocgroup;
                }
                if (DocgroupOfTab == 5) {//neu la tab luoc do cua van ban hop nhat
                    $('.' + opts.divDocOthers).hide();
                    $('#' + opts.divDocOthers).next().show();
                    $('.innoidung').lawsExists(function () {
                        $(this).hide();
                    });
                }
                else {
                    $(opts.rightBoxNotShowInDiagram).hide();
                    $('#' + opts.divDocFields).hide();
                    $('.' + opts.divDocFields).show();
                    $('#' + opts.divDocOthers).hide();
                    $('.' + opts.divDocOthers).show();
                    $(opts.boxLienket).lawsExists(function () {
                        $(this).hide();
                    });
                    $('.innoidung').lawsExists(function () {
                        $(this).hide();
                    });
                    $('#' + opts.divDocOthers).next().hide();
                }
            }
            else {
                $(opts.rightBoxNotShowInDiagram).show();
                $('#' + opts.divDocFields).show();
                $('.' + opts.divDocFields).hide();
                $('#' + opts.divDocOthers).show();
                $('.' + opts.divDocOthers).hide();
                $('#' + opts.divDocOthers).next().show();
                $(opts.boxLienket).lawsExists(function () {
                    $(this).show();
                });
                if (activeTab == opts.arrTabs[6]) {
                    $('.doc-widget-bar').lawsExists(function () {
                        $(this).removeClass('mucluc_rows').addClass('mucluc_rows2');
                        $(this).children('.bell-c1.bell-c1-fix').show();
                    });
                }
            }
            if (!tabClick && activeTab == opts.arrTabs[7]) {
                $(opts.contentClass + ':not("#tomtat")').hide();
            } else {
                $(opts.contentClass).hide();
            }
            $(opts.tabClass).removeClass('active');
            $(opts.tabClass + '[data-href="' + activeTab + '"]').addClass('active');
            $(activeTab).show();
            //lawsVn.GetFontSize();
            lawsVn.preventAnchorScroll();
            //scrollPagePosition();
            if (activeDemuc.indexOf('demuc') !== -1) {
                target = $(activeDemuc);
                isScroll = true;
                var height = 0, elNav = $('#tabPannel');
                if (elNav.length) {
                    height = elNav.outerHeight();
                    if (!elNav.hasClass('fixed-tabvb')) {
                        height = height + 180;
                    }
                }
                currentPageY = target.offset().top - height;
            }
            if (isScroll) {
                $('html, body').animate({
                    scrollTop: currentPageY > 0 ? currentPageY : 0  //$('.breadcrumb').offset().top
                }, 500);
            }

            if (islog || typeof islog === "undefined") {
                if (activeTab === '#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;
        },
        nightModeKey = "luatvietnam_night_mode", pageYKey = "luatvietnam_page_y", customerDocsKey = 'luatvietnam_customerdocs', nightModeValue = 0, pageYValue = 0, customerDocsResponse,
        sliderPositionChange = function () {
            if (activeTab === '#noidung' || $('#doc-content').is(':visible').length > 0 || (activeTab === '#chidanthaydoi' && $('#chidanthaydoi .content-entry').length > 0) || (activeTab === '#noidungmix' && $('#noidungmix .content-entry').length > 0)) {
                var val = $('#sliderPageY').slider('value');
                if ($(activeTab + ' .content-entry').length > 0) {
                    maxHeight = $(activeTab + ' .content-entry').height();
                    maxHeight = maxHeight - 250;
                    $('#sliderPageY').slider("option", "max", maxHeight);
                }
                $('.text_progress').text((maxHeight > 0 ? Math.round(val * 100 / maxHeight) : 0) + '%');
            }
        },
        sliderPosition = function () {
            if (activeTab === '#noidung' || $('#doc-content').is(':visible').length > 0 || (activeTab === '#chidanthaydoi' && $('#chidanthaydoi .content-entry').length > 0) || (activeTab === '#noidungmix' && $('#noidungmix .content-entry').length > 0)) {
                var val = $('#sliderPageY').slider('value');
                setTimeout(function () {
                    luatVietnamStore.setItem(pageYKey + '_' + opts.logs.docId + '_' + activeTab.substring(1),
                        val,
                        expiry);
                    $('html, body').animate({
                        scrollTop: val
                    },
                        30);
                },
                    1000);
            }
        },
        nightMode = function () {
            luatVietnamStore.getItem(nightModeKey, function (response) {
                if (response !== null) {
                    nightModeValue = response;
                    $('.content-entry').lawsExists(function () {
                        if (nightModeValue === 1) {
                            $(this).addClass('bandem');
                            $('.icon_caidat.banngay').find('img').attr('src', '/assets/images/sun.svg');
                            $('.icon_caidat.ban-dem').find('img').attr('src', '/assets/images/moon2.svg');
                        }
                        else {
                            $(this).removeClass('bandem');
                            $('.icon_caidat.banngay').find('img').attr('src', '/assets/images/sun2.svg');
                            $('.icon_caidat.ban-dem').find('img').attr('src', '/assets/images/moon.svg');
                        }
                    });
                }
            });
        }, storePagePosition = function () {
            if ((activeTab === '#noidung' && $('#noidung .content-entry').length > 0) || (activeTab === '#chidanthaydoi' && $('#chidanthaydoi .content-entry').length > 0) || (activeTab === '#noidungmix' && $('#noidungmix .content-entry').length > 0)) {
                var page_y = window.pageYOffset;
                $('#sliderPageY').slider('value', page_y);
                luatVietnamStore.setItem(pageYKey + '_' + opts.logs.docId + '_' + activeTab.substring(1), page_y, expiry);
            }
        }, scrollPagePosition = function () {
            try {
                if (opts.arrTabs.indexOf(activeTab) === -1) {
                    activeTab = opts.defaultTab;
                    if ($(opts.defaultTab).is(':visible')) activeTab = opts.defaultTab;
                    else activeTab = '#tomtat';
                }
                if (activeTab === opts.chidanthaydoiTab && $(opts.chidanthaydoiTab).length === 0 || activeTab === opts.noidungmixTab && $(opts.noidungmixTab).length === 0) {
                    activeTab = opts.defaultTab;
                    if ($(opts.defaultTab).is(':visible')) activeTab = opts.defaultTab;
                    else activeTab = '#tomtat';
                }
                if ((activeTab === '#noidung' && $('#noidung .content-entry').length > 0 && $('#doc-content').is(':visible').length > 0) || (activeTab === '#chidanthaydoi' && $('#chidanthaydoi .content-entry').length > 0) || (activeTab === '#noidungmix' && $('#noidungmix .content-entry').length > 0)) {
                    luatVietnamStore.getItem(pageYKey + '_' + opts.logs.docId + '_' + activeTab.substring(1), function (response) {
                        if (response !== null) {
                            currentPageY = response;
                        }
                    });
                    if (currentPageY === undefined) {
                        luatVietnamStore.setItem(pageYKey + '_' + opts.logs.docId + '_' + activeTab.substring(1), 1, expiry);
                        currentPageY = 1;
                    } $('#sliderPageY').slider('value', currentPageY);
                } else {
                    $('.text_progress').text('0%');
                    $('#sliderPageY').slider('value', 0);
                }
            } catch (e) {
                console.log('no localStorage available' + e)
            }
        }, getFontSize = function (el) {
            var fs = $(el).css('font-size');
            if (!el.originalFontSize) el.originalFontSize = fs;
            return parseFloat(fs);
        }, setFontSize = function (el, fact) {
            section = el.find('*')
                .filter(
                    function () {
                        return $(this).clone()
                            .children()
                            .remove()
                            .end()
                            .text().trim().length >
                            0;
                    });
            section.each(function () {
                var newsize = fact ? getFontSize(this) * fact : this.originalFontSize;
                if (newsize >= 16 && newsize <= 35)
                    if (newsize) $(this).css('cssText', 'font-size: ' + newsize + 'px !important;line-height:1.6 !important;');
            });
        }, 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
                            },
                            opts.localStorageCustomerDocsExpires);
                        documentSavedSetText(opts.documentSaved);
                        hasTrackedDocumentEffectSetText(opts.hasTrackedDocumentEffect);
                    } else {
                        documentSavedSetText(customerDocsResponse.documentSaved);
                        hasTrackedDocumentEffectSetText(customerDocsResponse.hasTrackedDocumentEffect);
                    }
                } else {
                    documentSavedSetText(0);
                    hasTrackedDocumentEffectSetText(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');
                }
            });
        }, 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');
                }
            });
        },
        loadDocContent = function (el, container) {
            try {
                el.hide();
                container.show();
                var docId = el.data('id'), embed = container.prev('embed');
                embed.lawsExists(function () {
                    $(this).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_GetContentViewDetail',
                                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;
                                                    $('.content-entry').lawsExists(function () {
                                                        if (nightModeValue === 1) {
                                                            $(this).addClass('bandem');
                                                        } else {
                                                            $(this).removeClass('bandem');
                                                        }
                                                    });
                                                }
                                            });
                                        //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 = $('#luocdo-content');
                el.show();
                var docId = el.data('id'),
                    languageId = el.data('lang');
                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: lawsVnConfig.rootPath + 'Ajax/Docs_GetDiagramViewDetail',
                                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'));
                                        $('.content-scroll-luocdo').mCustomScrollbar({ theme: 'minimal-dark' });
                                        $('.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 = $('#hieuluc-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_GetEffectViewDetail',
                                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 = $('#lienquan-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_GetRelateViewDetail',
                                    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 = $('#tienganh-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 () {
                            $.ajax({
                                url: lawsVnConfig.rootPath + 'Ajax/Docs_GetEngContentViewDetail',
                                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) {

            }
        },
        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, .docPrint_v2{ display: none !important;}li.has-sub ul{display: block !important; overflow: initial !important;}.content-scroll-luocdo,.mCustomScrollbar,.mCustomScrollBox{max-height:unset !important;}</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);
            }
        }
    $(function () {
        maxHeight = 0;
        if ($(activeTab + ' .content-entry').length > 0) {
            maxHeight = $(activeTab + ' .content-entry').height();
        }
        //var sliderTitle = $("<div/>")
        //    .css({ position: 'absolute', top: -20, left: 0, width: 150 })
        //    .text('Giữ và kéo để sử dụng')
        //    .hide()
        $('#sliderPageY').slider({
            orientation: 'horizontal',
            range: 'min',
            max: maxHeight,
            value: 0,
            slide: sliderPosition,
            change: sliderPositionChange
        });
        //$('#sliderPageY').slider()
        //    .find(".ui-slider-handle")
        //    .append(sliderTitle)
        //    .hover(function () { sliderTitle.show() },
        //        function () {
        //            sliderTitle.stop().hide()
        //        })
        customerDocs();
        showTab();
        nightMode(); window.addEventListener('scroll', storePagePosition);
        $(".content-scroll-1fix").mCustomScrollbar({
            snapAmount: 40,
            scrollButtons: { enable: true },
            keyboard: { scrollAmount: 40 },
            mouseWheel: { deltaFactor: 40 },
            scrollInertia: 400,
            styleGrey: true
        });
    });
    
    $(document).on('click',
        '.btn-xem-vb',
        function() {
            loadDocContent($(this), $('#doc-content'));
        });
    $(document).on('click',
        '.btn-xem-vb2, .btn-xem-word',
        function (e) {
            e.preventDefault();
            var me = $(this), parent = me.closest('#noidung');
            $('.btn-xem-vb').lawsExists(function () {
                $(this).data('id',1).show();
            });
            parent.find('embed').lawsExists(function () {
                $(this).show();
            });
            parent.find('#doc-content').lawsExists(function () {
                $(this).hide();
            });
            $('.innoidung').hide();
            $('.loadcontent').lawsExists(function () {
                $(this).hide();
            });
            $('.fixmucluc_new').lawsExists(function () {
                $(this).hide();
            });
        });
    $(document).on('click',
        '.icon_caidat.banngay',
        function (event) {
            event.preventDefault();
            luatVietnamStore.setItem(nightModeKey, 0, expiry);
            nightMode();
            $(this).find('img').attr('src', '/assets/images/sun2.svg');
            $('.icon_caidat.ban-dem').find('img').attr('src', '/assets/images/moon.svg');
        });
    $(document).on('click',
        '.icon_caidat.ban-dem',
        function (event) {
            event.preventDefault();
            luatVietnamStore.setItem(nightModeKey, 1, expiry);
            nightMode();
            $(this).find('img').attr('src', '/assets/images/moon2.svg');
            $('.icon_caidat.banngay').find('img').attr('src', '/assets/images/sun.svg');
        });    
    $(window).on('hashchange', function () {
        var hash = location.hash;
        $(opts.tabClass).removeClass('active');
        var el = $('.tab-nav-item-ad[data-href="' + 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-href');
            if (typeof hash !== 'undefined' && !$(this).hasClass('unavailable')) {
                //document.location.hash = hash;
                tabClick = true;
                showTab(hash);
            }
        });
    $(document).on('click',
        opts.tabClass2,
        function (e) {
            e.preventDefault();
            viewMix = false;
            var hash = $(this).attr('data-href');
            //document.location.hash = hash;
            showTab(hash);
        });
    $(document).on('click',
        '.taive-link',
        function (e) {
            e.preventDefault();
            viewMix = false;
            var hash = $(this).attr('data-href');
            //document.location.hash = hash;
            showTab(hash);
        });
    $(document).on('click',
        opts.item_mucluc,
        function (e) {
            e.preventDefault();
            var className = $(this).attr('class').replace(/\s{2,}/g, ' ').split(' '), target = $('#' + className[1]);
            $('#mucluc2').lawsExists(function () {
                $(this).hide();
            }); $('#mucluc3').lawsExists(function () {
                $(this).hide();
            });
            if (activeTab === opts.chidanthaydoiTab) {
                target = $('#' + className[1], $('#chidanthaydoind'));
            } else target = $('#' + className[1], $('#noidungtoanvan'));
            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 = $('#tabPannel');
                if (elNav.length) {
                    height = elNav.outerHeight();
                    if (!elNav.hasClass('fixed-tabvb')) {
                        height = height + 100;
                    }
                }
                $('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',
        opts.print,
        function (event) {
            event.preventDefault();
            if (activeTab == opts.arrTabs[4]) {
                printDocContent($(activeTab).find('.boxluocdo'));
            }
            else if ($('.ndgoc').find('.content-entry').length) {
                printDocContent($('.ndgoc').find('.content-entry'));
            }
            else if ($(opts.arrTabs[1]).find('.content-entry').length) {
                printDocContent($(opts.arrTabs[1]).find('.content-entry'));
            } else {
                $('#doc-content').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_GetContentViewDetail',
                                    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',
        '#tangfont_zdprnmr352',
        function () {
            var target = $('#noidung .boxnoidung');
            if ($('#chidanthaydoi').is(':visible')) {
                if ($('#chidanthaydoind').length)
                    target = $('#chidanthaydoind');
                else target = $('#chidanthaydoi .boxnoidung');
            }
            else if ($('#noidungmix').is(':visible'))
                target = $('#noidungtoanvan');
            else if ($('#tienganh').is(':visible'))
                target = $('#tienganh .box-content');
            setFontSize(target, 1 / factor);
        });
    $(document).on('click',
        '#giamfont_lzayo2dc86',
        function () {
            var target = $('#noidung .boxnoidung');
            if ($('#chidanthaydoi').is(':visible')) {
                if ($('#chidanthaydoind').length)
                    target = $('#chidanthaydoind');
                else target = $('#chidanthaydoi .boxnoidung');
            }
            else if ($('#noidungmix').is(':visible'))
                target = $('#noidungtoanvan');
            else if ($('#tienganh').is(':visible'))
                target = $('#tienganh .box-content');
            setFontSize(target, factor);
        });
    $(document).on('click',
        '.muclucvb',
        function () {
            var className = $(this).attr('class').replace(/\s{2,}/g, ' ').split(' '), target = $('#' + className[0], $(activeTab));
            $('#mucluc').lawsExists(function () {
                $(this).hide();
            });
            $('#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 = $('#tabPannel');
            if (elNav.length) {
                height = elNav.outerHeight();
                if (!elNav.hasClass('fixed-tabvb')) {
                    height = height + 80;
                }
            }
            $('html, body').animate({
                scrollTop: target.offset().top - height
            },
                500);
        });
    $(document).on('click',
        '.view-timeline-mix',
        function (event) {
            event.preventDefault();
            viewMix = true;
            var me = $(this),
                id = me.attr('data-id'),
                time = me.attr('data-time'),
                el = $('#timeline-mix'),
                row = me.closest('.rows-mixvb');
            el.lawsExists(function () {
                $('.rows-mixvb').removeClass('active_mixvb');
                row.addClass('active_mixvb');
                var t = $(this).attr('data-time');
                if (t == time && $(this).children().length > 0) {
                    //document.location.hash = '#noidungmix';
                    showTab('#noidungmix', true, false);
                } else {
                    if (typeof id !== 'undefined' && typeof time !== '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);
                        $.ajax({
                            type: 'post',
                            async: true,
                            url: lawsVn.virtualPath('/Ajax/DocItems_GetUnionTimeLine_View'),
                            dataType: 'html',
                            data: { docId: id, 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);
                                            //document.location.hash = '#noidungmix';
                                            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');
                            me.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',
        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.chidanthaydoiTab) {
                    if ($('#mucluc2').length == 0) {
                        $('#mucluc').lawsExists(function () {
                            if (panel.hasClass('navsticky')) {
                                $(this).find('.popup-wrapper').css({
                                    top: pos.top + height + 5 + "px",
                                    left: pos.left - width - 20 + "px"
                                });
                            } else {
                                $(this).find('.popup-wrapper').css({
                                    top: "20%",
                                    left: "50%"
                                });
                            }
                            $(this).show();
                        });
                        $('#doccontentindex').lawsExists(function () {
                            $(this).show();
                        });
                    } else {
                        $('#mucluc2').lawsExists(function () {
                            if (panel.hasClass('navsticky')) {
                                $(this).find('.popup-wrapper').css({
                                    top: pos.top + height + 5 + "px",
                                    left: pos.left - width - 20 + "px"
                                });
                            } else {
                                $(this).find('.popup-wrapper').css({
                                    top: "20%",
                                    left: "50%"
                                });
                            }
                            $(this).show();
                        });
                        $('#doccontentindex2').lawsExists(function () {
                            $(this).show();
                        });
                    }
                } else if (activeTab === opts.noidungmixTab) {
                    $('#mucluc3').lawsExists(function () {
                        if (panel.hasClass('navsticky')) {
                            $(this).find('.popup-wrapper').css({
                                top: pos.top + height + 5 + "px",
                                left: pos.left - width - 20 + "px"
                            });
                        } else {
                            $(this).find('.popup-wrapper').css({
                                top: "20%",
                                left: "50%"
                            });
                        }
                        $(this).show();
                    });
                    $('#doccontentindex3').lawsExists(function () {
                        $(this).show();
                    });
                }
            } else
                $('#mucluc').lawsExists(function () {
                    if (!duthao) {
                        if (panel.hasClass('navsticky')) {
                            $(this).find('.popup-wrapper').css({
                                top: pos.top + height + 5 + "px",
                                left: pos.left - width - 20 + "px"
                            });
                        } else {
                            $(this).find('.popup-wrapper').css({
                                top: "20%",
                                left: "50%"
                            });
                        }
                    } else {
                        if (panel.hasClass('navsticky')) {
                            $(this).find('.popup-wrapper').css({
                                top: pos.top + height + 5 + "px"
                            });
                        } else {
                            $(this).find('.popup-wrapper').css({
                                top: "20%"
                            });
                        }
                    }
                    $(this).show();
                });
        });
    if ($('.ndthaydoi').length) {
        var permission = true;
        var isLogin = true,
            endTime = '', serviceId = 0, userName = '';
        $(function () {
            $('.text_vb', $('#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 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 === '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,
                    maincontentOffset = $('.main-content').offset(),
                    contentEntryRight = maincontentOffset.left + contentEntry.outerWidth();
                left = (e.pageX - maincontentOffset.left) / 2;
                if (e.pageX + 100 > contentEntryRight) {
                    left = e.pageX - 420;
                }
                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++) {
                                        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") +
                                            '">- ' +
                                            arrHd[i].replace(/(<([^>]+)>)/ig, '') +
                                            '</span>' +
                                            (arrHd.length > 1
                                                ? '<br/>'
                                                : '') +
                                            '</a></li>';
                                    }
                                } else {
                                    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") +
                                        '">- ' +
                                        e.html() +
                                        '</span></a></li>';
                                }
                            } else if (e.html().length > 0 && typeof title !== 'undefined') {
                                temp = '<li class="li-news-tip"><span class="' +
                                    e.attr("class") +
                                    '">- ' +
                                    e.html() +
                                    '</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 = '';
                    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>';
                        }
                    }
                    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">' +
                                    (permission ? '' : '<div class="fix-hight-tooltip">') +
                                    '<ul>' +
                                    content.get().join(' ') +
                                    '</ul>' +
                                    (permission
                                        ? ''
                                        : (isLogin ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                                    ) + 
                                    '</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';
                                me.append('<div class="dropdown-tips-content-2" style="' + (typeof isPrint !== 'undefined' ? '' : 'visibility:visible;') + 'left:' +
                                    left +
                                    'px;top:' +
                                    (e.pageY - 90) +
                                    'px">' +


                                    '<div class="tooltip-boxs2">' +
                                    '<ul>' +
                                    thamchieutext +
                                    '</ul>' +
                                    '</div>' +
                                    '</div>');
                            } else {
                                me.append('<div class="dropdown-tips-content-2" style="' + (typeof isPrint !== 'undefined' ? '' : 'visibility:visible;') + 'left:' +
                                    left +
                                    'px;top:' +
                                    (e.pageY - 90) +
                                    'px">' +
                                    '<div class="tooltip-boxs2">' +
                                    (permission ? '' : '<div class="fix-hight-tooltip">') +
                                    '<ul>' +
                                    content.get().join(' ') +
                                    '</ul>' +
                                    (permission
                                        ? ''
                                        : (isLogin ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                                    ) +
                                    '</div>' +
                                    '</div>');

                            }
                        }
                    } else {
                        if (dd.length === 0)
                            me.append('<div class="dropdown-tips-content-2" style="visibility:visible;left:' +
                                left +
                                'px;top:' +
                                (e.pageY - 90) +
                                'px">' +
                                '<div class="tooltip-boxs2">' +
                                (permission ? '' : '<div class="fix-hight-tooltip">') +
                                '<p ' +
                                paragraphClass +
                                '>' +
                                title +
                                '</p>' +
                                (permission
                                    ? ''
                                    : (isLogin ? messageOutOfDate.length > 0 ? messageOutOfDate : messageNoPerrmission : messageNotLoggedin)
                                ) +
                                '</div>' +
                                '</div>');
                    }

                    if (!bosung) {
                        dd.css({ left: left, top: e.pageY - 90, visibility: 'visible' });
                    }
                }
            }

            $(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');
                    });
                }
            });

            $(document).on('click',
                '.intonghop',
                function (event) {
                    event.preventDefault();
                    $('#noidungtoanvan').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"><style>.dropdown-tips-content-2{display:none !important;}.content-entry * {line-height: 1.6;}</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);
                        }
                    });
                });
            $(document).on('click',
                '.intonghop_cochuthich',
                function (event) {
                    event.preventDefault();
                    $('#noidungtoanvan').lawsExists(function () {
                        try {
                            var parent = $('#noidungtoanvan');
                            $('.popupRelate, .popupRelate2', parent).each(function (i, element) {
                                popupChiDan(element, event, print);
                            });
                            $('.dropdown-tips-content-2', parent).lawsExists(function () {
                                $('.dropdown-tips-content-2', parent);
                            });

                            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(
                                '<style>.dropdown-tips-content-2 {position: unset;float: left;width: 100%;padding: 20px;display: unset;visibility: visible !important;}.dropdown-tips-content-2.fixedd{visibility: visible !important;} .content-entry * { line-height: 1.6; } </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);
                        }
                    });
                });
            if (permission) {
                $(document).on({
                    mouseover: function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var paused = false;
                        enabletip = true;
                        //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 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');

                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 {
                $(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');
            }

        });
        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 - 100 + "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')) {
                    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 = '';
                }
            }
        }
        document.onmousemove = positiontip;
    }
}
$.fn.DocDetailTrial = function (options) {
    var defaults = {
        parentContentClass: '.docdetail-trial',
        contentClass: '.page-content',
        defaultTab: '#noidung',
        chidanthaydoiTab: '#chidannoidung',
        tabClass: '.rows-triall.tab',
        item_mucluc: 'div[class*=demuc]',
        chuthich: '#chuthich',
        mucluc: '#muclucvanban',
        fixDiv: '.widgetFix'
    }, opts = $.extend(defaults, options);
    var activeTab = '',
        getHash = function () {
            if (window.location.hash) {
                return window.location.hash;
            }
            return '';
        },
        showTab = function (tab) {
            activeTab = tab || getHash();
            if (activeTab === '') {
                activeTab = opts.defaultTab;
            }
            if ($('#stopSticky').length) $('#stopSticky').remove();
            $('<div id="stopSticky" style="float:left;width:100%"></div>').insertAfter(activeTab);
            if (activeTab === '#noidung' || activeTab === '#chidannoidung') $(opts.chuthich).show();
            else $(opts.chuthich).hide();
            $(opts.contentClass, $(opts.parentContentClass)).hide();
            $(opts.tabClass).removeClass('active');
            $(opts.tabClass + '[href="' + activeTab + '"]').addClass('active');
            $(activeTab).show();
        }, stickIt = function () {
            var y = $(this).scrollTop(),
                wrap = $('#leftboxWrap'),
                content = $('#leftboxContent'),
                contentLeft = $('#leftboxContent').offset().left,
                startPosition = wrap.offset().top,
                stopPosition = $('#stopSticky').offset().top - content.outerHeight();
            if (y > startPosition) {
                content.addClass('sticky');
                content.css('left', contentLeft + 'px');
                if (y > stopPosition) {
                    content.css('top', stopPosition - y);
                } else {
                    content.css('top', -26 + 'px');
                }
            } else {
                content.removeClass('sticky');
                content.css('left', 'auto');
            }
        };
    showTab();
    window.onpopstate = function () {
        showTab();
    };
    
    $(document).scroll(stickIt).scroll();
    $(document).on('click',
        opts.tabClass,
        function (e) {
            e.preventDefault();
            $(opts.tabClass).removeClass('active');
            $(this).addClass('active');
            showTab($(this).attr('href'));
            $('html, body').animate({
                scrollTop: $('.breadcrumb').offset().top
            }, 500); return false;
        });
    $(document).on('click',
        opts.item_mucluc,
        function (e) {
            e.preventDefault();
            var className = $(this).attr('class'), target = $('#' + className.split(' ')[1]);
            showTab(opts.chidanthaydoiTab);
            $(opts.mucluc).hide();
            var h = 0, elNav = $('.hearder-fix');
            if (elNav.length) {
                h = elNav.outerHeight();
            }
            $('#leftboxContent').lawsExists(function () {
                $(this).css({ 'zIndex': 998 });
            });
            $('html, body').animate({
                scrollTop: target.offset().top - h
            }, 500); return false;
        });
}
$.fn.followTo = function (top, height) {
    var self = this;
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();
        if (scroll > top && scroll < height) {
            self.addClass('fixed');
        } else if (scroll <= top || scroll >= height - 200) {
            self.removeClass('fixed');
        }
    });
};

(function ($) {
    $.fn.lawServicesWizard = function (options) {
        var defaults = {
            itemNav: '.navstep',
            navStep: '.nav-step',
            itemstep: 'span.itemstep',
            divSteps: 'div.law-steps',
            backStep: '.back-step',
            nextStep: '.next-step',
            duration: 250,
            validate: false,
            fnValidate: function () {
                var servicePackageParentId = $('select[name="ServicePackageParentId"] option:selected').val();
                var servicePackageId = $('select[name="ServicePackageId"] option:selected').val();

                if (servicePackageParentId > 0 && servicePackageId > 0) {
                    if (servicePackageParentId > 0) {
                        $('select[name="ServicePackageParentId"]').lawsExists(function () {
                            $(this).removeClass('border-warning');
                        });
                    }
                    if (servicePackageId > 0) {
                        $('select[name="ServicePackageId"]').lawsExists(function () {
                            $(this).removeClass('border-warning');
                        });
                    }
                    return true;
                }
                else if (servicePackageParentId == 0) {
                    $('select[name="ServicePackageParentId"]').lawsExists(function () {
                        $(this).addClass('border-warning');
                    });
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Quý khách vui lòng chọn số người sử dụng.']
                    });
                } else if (servicePackageId == 0) {
                    $('select[name="ServicePackageId"]').lawsExists(function () {
                        $(this).addClass('border-warning');
                    });
                    $().lawsDialog({
                        dialogClass: 'lawsVnDialogTitle',
                        messages: ['Quý khách vui lòng chọn thời hạn thuê bao.']
                    });
                }
                return false;
            },
            stepValidate: 1
        };
        options = $.extend({}, defaults, options);
        var el = this;
        var i = 1;
        var length = $(options.divSteps, el).size();
        var proc = {
            displayStep: function (index) {
                var s = index > 0 ? index - 1 : index;
                $(options.itemstep).removeClass('active').addClass('undone');
                $($(options.itemstep)[s]).removeClass('undone').addClass('active');

                $(options.divSteps, el).animate({
                    opacity: 0
                }, 50, function () {
                    $(options.divSteps + ':nth-child(' + index + ')', el).animate({
                        opacity: 1
                    }, 50, function () {
                        $(options.itemNav).LawScrollTo();
                    }).show();
                }).hide();
            }
        }
        $(options.itemstep).removeClass('active').addClass('undone');
        $(options.navStep, $(options.itemNav)).unbind().click(function (event) {
            event.preventDefault();
            var id = $(this).data('id');
            if (options.validate && id > options.stepValidate) {
                var execOnValid = $.isFunction(options.fnValidate) ? options.fnValidate : $.noop;
                if (!execOnValid()) {
                    return;
                }
            }
            i = id;
            proc.displayStep(id);
            $('#PromotionCodeCheckForm input').lawsExists(function () {
                $('#PromotionCodeCheckForm input').clearErrors();
            });
            $('#ValidPaymentMethodsBankAccountForm input').lawsExists(function () {
                $('#ValidPaymentMethodsBankAccountForm input').clearErrors();
            });
        });
        $(options.nextStep, el).unbind().click(function (event) {
            event.preventDefault();
            if (options.validate && options.stepValidate == i) {
                var execOnValid = $.isFunction(options.fnValidate) ? options.fnValidate : $.noop;
                if (!execOnValid()) {
                    return;
                }
            }
            if (i < length) i++;
            lawsVnConfig.currentStep = i;
            proc.displayStep(i);
            $('#PromotionCodeCheckForm input').lawsExists(function () {
                $('#PromotionCodeCheckForm input').clearErrors();
            });
            $('#ValidPaymentMethodsBankAccountForm input').lawsExists(function () {
                $('#ValidPaymentMethodsBankAccountForm input').clearErrors();
            });
        });

        $(options.backStep, el).unbind().click(function (event) {
            event.preventDefault();
            if (i > 1) i--;
            lawsVnConfig.currentStep = i;
            proc.displayStep(i);
            $('#PromotionCodeCheckForm input').lawsExists(function () {
                $('#PromotionCodeCheckForm input').clearErrors();
            });
            $('#ValidPaymentMethodsBankAccountForm input').lawsExists(function () {
                $('#ValidPaymentMethodsBankAccountForm input').clearErrors();
            });
        });

        return this.each(function () {
            proc.displayStep(1);
        });
    }
    $.fn.lawServicesWizardV2 = function (options) {
        var defaults = {
            itemNav: '.navstepv2',
            navStep: '.nav-step',
            itemstep: 'span.itemstepv2',
            divSteps: 'div.law-steps',
            backStep: '.back-step',
            nextStep: '.next-step',
            itemValidate: 'input[name="Phone"]',
            duration: 250,
            validate: false,
            fnValidate: function () {
                var phone = $(options.itemValidate);
                if (phone.length) {
                    if (phone.val().length > 0) {
                        var reg = /^(84|0)\d{9,10}$/;
                        if (!reg.test(phone.val())) {
                            phone.addClass('border-warning');
                            $().lawsDialog({
                                dialogClass: 'lawsVnDialogTitle',
                                messages: [lawsVn.Resource.getMessages('InvalidPhoneNumber')]
                            });
                            return false;
                        }
                        phone.removeClass('border-warning');
                    } else {
                        phone.addClass('border-warning');
                        $().lawsDialog({
                            dialogClass: 'lawsVnDialogTitle',
                            messages: [lawsVn.Resource.getMessages('PleaseEnterAPhoneNumber')]
                        });
                        return false;
                    }
                }
                return true;
            },
            stepValidate: 1
        };
        options = $.extend({}, defaults, options);
        var el = this;
        var i = 1;
        var length = $(options.divSteps, el).size();
        window.dataLayer = window.dataLayer || [];
        $('input[name="Phone"]').blur(function (e) {
            return options.fnValidate();
        });
        var proc = {
            displayStep: function (index) {
                var s = index > 0 ? index - 1 : index;
                $($(options.itemstep)[index]).removeClass('ok');
                $($(options.itemstep)[s]).addClass('ok');
                $(options.divSteps, el).animate({
                    opacity: 0
                }, 50, function () {
                    $(options.divSteps + ':nth-child(' + index + ')', el).animate({
                        opacity: 1
                    }, 50, function () {
                        $(options.itemNav).LawScrollTo();
                    }).show();
                }).hide();
            }
        }
        $(options.itemstep).removeClass('ok');
        $(options.nextStep, el).unbind().click(function (event) {
            event.preventDefault();
            if (options.validate && options.stepValidate == i) {
                var execOnValid = $.isFunction(options.fnValidate) ? options.fnValidate : $.noop;
                if (!execOnValid()) {
                    return;
                }
            }
            if (i < length) i++;
            lawsVnConfig.currentStep = i;
            proc.displayStep(i);
            history.replaceState({
                id: 'Services'
            }, 'Văn bản Pháp luật - Hệ thống Văn bản Quy phạm Pháp Luật Việt Nam', lawsVn.replaceUrlParam({ 'step': '4' }));
            window.dataLayer.push({
                'event': 'LuatVietNamTrackEvent',
                'eventCategory': 'Services',
                'eventAction': 'Step',
                'eventLabel': 'Thanh toán bước 4',
                'eventValue': window.location.href
            });
        });

        $(options.backStep, el).unbind().click(function (event) {
            event.preventDefault();
            if (i > 1) i--;
            lawsVnConfig.currentStep = i;
            proc.displayStep(i);
            history.replaceState({
                id: 'Services'
            }, 'Văn bản Pháp luật - Hệ thống Văn bản Quy phạm Pháp Luật Việt Nam', lawsVn.replaceUrlParam({ 'step': '3' }));
            window.dataLayer.push({
                'event': 'LuatVietNamTrackEvent',
                'eventCategory': 'Services',
                'eventAction': 'Step',
                'eventLabel': 'Thanh toán bước 3',
                'eventValue': window.location.href
            });
        });
        window.addEventListener('popstate', function (event) {
            if (history.state && history.state.id === 'Services') {
                var step = $.urlParam('step');
                if (step != null) {
                    if (step == 3) {
                        proc.displayStep(1);
                    } else if (step == 4) {
                        proc.displayStep(2);
                    }
                }
            }
        }, false);
        return this.each(function () {
            proc.displayStep(1);
        });
    }
})(jQuery);

(function () {
    $.fn.lawFields = function (data) {
        var el = $(this).find(':input').get();
        var fields;
        if (arguments.length === 0) {
            fields = {};
            $.each(el, function () {
                if (this.name && !this.disabled && (this.checked
                    || /select|textarea/i.test(this.nodeName)
                    || /text|hidden|password/i.test(this.type))) {
                    if (fields[this.name] == undefined) {
                        fields[this.name] = [];
                    }
                    fields[this.name] = $(this);
                }
            });
            return fields;
        } else {
            $.each(el, function () {
                if (this.name && data[this.name]) {
                    var names = data[this.name];
                    var self = $(this);
                    if (Object.prototype.toString.call(names) !== '[object Array]') {
                        names = [names];
                    }
                    if (this.type == 'checkbox' || this.type == 'radio') {
                        var val = self.val();
                        var found = false;
                        for (var i = 0; i < names.length; i++) {
                            if (names[i] == val) {
                                found = true;
                                break;
                            }
                        }
                        self.attr('checked', found);
                    } else {
                        self.val(names[0]);
                    }
                }
            });
            return this;
        }
    };
})(jQuery);

(function () {
    $.fn.lawFixAuto = function (options) {
        var defaults = {
            classFixed: 'fixed',
            content: '.content-fixed',
            width: '300px'
        }
        options = $.extend(defaults, options);
        var el = this;
        el.width(options.width);
        var content = $(options.content);
        if (content.length) {
            $(window).scroll(function () {
                var scroll = $(window).scrollTop();
                var offset = content.offset();
                var height = content.height();
                if (offset.top <= scroll && scroll <= offset.top + height) {
                    $(el, content).addClass(options.classFixed);
                } else {
                    $(el, content).removeClass(options.classFixed);
                }
            });
        }
    }

    $.fn.posFixed = function (options) {
        var defaults = {
            classFixed: 'fixed',
            elementCompare: ''
        }, settings = $.extend(defaults, options), self = this;
        if (settings.elementCompare !== '') {
            if ($(settings.elementCompare).length) {
                var height = $(settings.elementCompare).height(), top = $(settings.elementCompare).offset().top,
                    selfHeight = self.height();
                if (height > selfHeight) {
                    $(window).scroll(function () {
                        var scroll = $(window).scrollTop();
                        if (scroll > top && scroll + 250 < height) {
                            self.addClass(settings.classFixed);
                        } else if (scroll <= top || scroll + 250 >= height) {
                            self.removeClass(settings.classFixed);
                        }
                    });
                }
            }
        }
    };

    $.fn.postPaginate = function (options) {
        var defaults = {
            postItem: '.post-items',
            next: '#next-post',
            prev: '#prev-post',
            itemsPerPage: 10
        }, settings = $.extend(defaults, options), self = this;

        var showPage = function (page) {
            $(settings.postItem).hide();
            $(settings.postItem).each(function (n) {
                if (n >= settings.itemsPerPage * (page - 1) && n < settings.itemsPerPage * page)
                    $(this).show();
            });
        }
        showPage(1);
        var page = 1;
        setTitle(1);
        function setTitle(page) {
            var n, pr = 1;
            if (page > 1) {
                pr = page - 1;
            } else pr = 1;
            if (page < Math.ceil($(settings.postItem, self).length / settings.itemsPerPage)) {
                n = page + 1;
            } else n = page;
            $(settings.prev).attr('title', 'Trang ' + pr);
            $(settings.next).attr('title', 'Trang ' + n);
        }
        function prevPage() {
            if (page > 1) {
                //page = Math.ceil($(settings.postItem, self).length / settings.itemsPerPage);
                page--;
                showPage(page);
                setTitle(page);
                $('.widget-container.pagination-container').LawScrollTo();
            }
        }

        function nextPage() {
            if (page < Math.ceil($(settings.postItem, self).length / settings.itemsPerPage)) {
                page++;
                showPage(page);
                setTitle(page);
                $('.widget-container.pagination-container').LawScrollTo();
            }
        }

        $(settings.next).unbind().click(function (event) {
            event.preventDefault();
            nextPage();
        });

        $(settings.prev).unbind().click(function (event) {
            event.preventDefault();
            prevPage();
        });
    }
})();

jQuery.fn.preventDoubleSubmitForm = function () {
    $(this).on('submit', function (e) {
        var $form = $(this);
        if ($form.data('submitted') === true) {
            e.preventDefault();
        } else {
            if ($form.valid()) {
                $form.data('submitted', true);
            }
        }
    });
    return this;
};

(function ($) {
    $.fn.DocIndexInView = function (options) {
        var defaults = {
            DocIndexesElement: '#DocIndexes .item-article > a'
        }
        options = $.extend(defaults, options);
        var docIndexList = [], listLinks = [];
        this.each(function () {
            var self = $(this);
            var docIndex = {};
            docIndex.top = self.offset().top;
            docIndex.height = self.innerHeight();
            docIndex.bottom = docIndex.top + docIndex.height;
            docIndex.id = self[0].id;
            docIndex.percent = ((self.offset().top / ($(document).height() - $(window).height())) * 100).toFixed(1),
                docIndex.obj = self;
            docIndex.inView = null;
            if (checkdemuc(self[0].id, docIndexList) < 0)
                docIndexList.push(docIndex);
        });
        if ($(options.DocIndexesElement).length) {
            $(options.DocIndexesElement).each(function () {
                listLinks.push($(this));
            });
        } else return;

        function checkdemuc(value, arr) {
            var status = -1;
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].id == value) {
                    status = 1;
                    break;
                }
            }
            return status;
        }
        var globalList = $(window).data('globalListDocIndex') || [];
        globalList.push({
            'options': options,
            'docIndexList': docIndexList
        });
        $(window).data('globalListDocIndex', globalList);
        $(window).data('globalListLinks', listLinks);

        //if (!$(window).data('DocIndexInView.initialized')) {
        //    $(window).data('DocIndexInView.initialized', true);
        //    $(window).on({
        //        'scroll': lawsVn.progressInView,
        //        'resize': lawsVn.progressInView
        //    });
        //} 
        //$(window).trigger('resize');
    }
})(jQuery);

(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) : requestAccountInfo2(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);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });
    }
}

$.fn.facebookLogin = function (options) {
    var defaults = {
        AppId: '1523947861021721',
        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 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) : fBOnSuccess2(response);
        }, this));
    }
}
$.fn.zaloLogin = function (options) {
    var defaults = {
        BASE_URL: 'https://graph.zalo.me',
        OAUTH_URL: 'https://oauth.zaloapp.com/v3',
        appId: '3742299663912142579',
        authKey: location.hostname + '_zoauth',
        ACCESS_TOKEN_KEY: location.hostname + '_zaccesstoken',
        ACCESS_TOKEN_VALIDTIME_KEY: location.hostname + '_zaccesstoken_validtime',
        authenticationCode: '',
        accessToken: '',
        redirectUrl: 'https://luatvietnam.vn/zalo/oauth',
        param: 'luatvietnam',
        scope: 'id,name,gender,birthday,picture'
    }
    options = $.extend(defaults, options);
    $(this).on('click',
        function (e) {
            e.preventDefault();
            createCookie('zaloUrl', window.location, 1);
            getLoginStatus();
        });
    function getLoginStatus(callback) {
        parseAuthenticationCode();
        parseAccessTokenFromLocal();
        if (options.authenticationCode && options.authenticationCode != null) {

        } else {
            window.location = options.OAUTH_URL + '/auth?app_id=' + options.appId + '&redirect_uri=' + options.redirectUrl + '&state=' + encodeURIComponent(options.param) + '&scope=' + encodeURIComponent(options.scope);
        }
    }
    function parseAuthenticationCode() {
        options.authenticationCode = lawsVn.readCookie(options.authKey);
        //Authentication code chưa có trong Cookie, lấy từ param url
        if (!options.authenticationCode) {
            options.authenticationCode = lawsVn.getParameterByName('code');
            cleanURI();
        }
    }
    function parseAccessTokenFromLocal() {
        var accessToken = localStorage.getItem(options.ACCESS_TOKEN_KEY) ? localStorage.getItem(options.ACCESS_TOKEN_KEY) : null;
        if (accessToken) {
            var validTime = parseInt(localStorage.getItem(options.ACCESS_TOKEN_VALIDTIME_KEY));
            if (validTime && new Date().getTime() < validTime) {
                options.accessToken = accessToken;
            }
        }
    }
    function cleanURI() {
        var uri = window.location.toString();
        if (uri.indexOf("?") > 0) {
            var clean_uri = uri.substring(0, uri.indexOf("?"));
            window.history.replaceState({}, document.title, clean_uri);
        }
    }
    function setAuthenticationCode(value, time) {
        if (time) {
            createCookie(options.authKey, value);
        } else {
            createCookie(options.authKey, value, time);
        }
    }
    function createCookie(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=/";
    }
}
$.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;
    }
}

var lawsInfo = function () {
    console.log("%c LuatVietnam.Vn - Cơ sở dữ liệu văn bản pháp luật lớn nhất Việt Nam. %c \n Bản quyền \xa9 2000-2017 bởi LuatVietnam - Thành viên INCOM Communications ., JSC \n Giấy phép thiết lập trang Thông tin điện tử tổng hợp số: 692/GP-TTĐT cấp ngày 29/10/2010 bởi Sở TT-TT Hà Nội, thay thế giấy phép số: 322/GP - BC, ngày 26/07/2007, cấp bởi Bộ Thông tin và Truyền thông \n" +
        "Chứng nhận bản quyền tác giả số 280/ 2009 / QTG ngày 16/ 02 / 2009, cấp bởi Bộ Văn hoá - Thể thao - Du lịch \n" +
        "Cơ quan chủ quản: Công ty Cổ phần Truyền thông Quốc tế INCOM.Chịu trách nhiệm: Ông Vũ Mạnh Cường \n" +
        "Giấy chứng nhận đăng ký DN số: 0102011152, do Sở Kế hoạch và Đầu tư Hà Nội cấp ngày 11/ 08 / 2006.\n" +
        "Địa chỉ: Tầng 3, Tòa nhà IC, 82 phố Duy Tân, Cầu Giấy, Hà Nội.\n" +
        "Điện thoại: 0938 36 1919 * Hỗ trợ: 1900561589 * Email: cskh@luatvietnam.vn", 'font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size:24px;color:#a67942;-webkit-text-fill-color:#a67942;-webkit-text-stroke: 1px #a67942;', "font-size:12px;color:#000;");
}

$.fn.toggleTarget = function (options) {
    var defaults = {
        dataAttr: 'data-toggle-target',
        classHidden: 'target-hidden',
        classShow: 'target-expanded'
    } 
    options = $.extend(defaults, options);
    var target = $(this).attr(options.dataAttr);
    $(target).addClass(options.classHidden);
    $(this).click(function(e) {
        e.preventDefault();
        try {
            //if (target.indexOf('login') !== -1 && !$(target).hasClass(options.classShow)) {
            //    $.ajax({
            //        url: '/ajax/fwpdxfizeh',
            //        type: 'POST',
            //        dataType: 'json',
            //        cache: false
            //    });
            //}
            $(target).toggleClass(options.classShow).css('display', '');
        } catch (e) {

        }
    });
}
if (typeof module !== 'undefined') {
    module.exports = luatVietnamStore;
}

(function ($) {
    $.fn.vipAlert = function (options) {
        var defaults = {
            mainClass: 'customer-vip',
            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 w_460"><div class="popup-body"><div class="box_padding">';
        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><span title="Đóng" class="ic icon-e-remove-2lvn btn-hea-cpas2" name="close"></span></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('span[name=close]').on('click', function () {
            $('.' + options.mainClass).remove();
            if ($.isFunction(options.callback)) {
                window.setTimeout(function () {
                        options.callback();
                    },
                    10);
            }
            return false;
        });
    }
})(jQuery);

(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: 390px;"><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 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;
        }
    }
};
if (typeof module !== 'undefined') {
    module.exports = luatVietnamStore;
}

/* bengin select*/
; (function ($, document, window) {
    "use strict";

    // close select extended on clicking anywhere
    $(document).on("click.selectX", function () {
        $(".jq-selectx").each(function () {
            $(this).data("SelectX").close();
        });
    });

    // close on pressing "esc"
    $(window).on("keyup.selectX", function (event) {
        if (event.which === 27) {
            $(".jq-selectx").each(function () {
                $(this).data("SelectX").close();
            });
        }
    });

    

}(jQuery || window.jQuery, document, window));
$('.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();
                    });
            });
    }
});;
(function ($) {
    $(window).on("load", function () {
        $.mCustomScrollbar.defaults.scrollButtons.enable = false; //enable scrolling buttons by default
        $.mCustomScrollbar.defaults.axis = "y"; //enable 2 axis scrollbars by default
        $(".scrollbar-defau").mCustomScrollbar({ theme: "dark-3" });
        $(".scrollbar-defau2").mCustomScrollbar({ theme: "minimal-dark" });
        $('.content-scroll-1').mCustomScrollbar({ theme: "minimal-dark" });
        $('.content-scroll-11').mCustomScrollbar({ theme: "minimal-dark" });
        $('.content-scroll-2').mCustomScrollbar({ theme: "minimal-dark" });
        $(".content-scroll-luocdo").mCustomScrollbar({ theme: "minimal-dark" });
    });
})(jQuery);

!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : "object" == typeof exports ? module.exports = a : a(jQuery) }(function (a) { function b(b) { var g = b || window.event, h = i.call(arguments, 1), j = 0, l = 0, m = 0, n = 0, o = 0, p = 0; if (b = a.event.fix(g), b.type = "mousewheel", "detail" in g && (m = -1 * g.detail), "wheelDelta" in g && (m = g.wheelDelta), "wheelDeltaY" in g && (m = g.wheelDeltaY), "wheelDeltaX" in g && (l = -1 * g.wheelDeltaX), "axis" in g && g.axis === g.HORIZONTAL_AXIS && (l = -1 * m, m = 0), j = 0 === m ? l : m, "deltaY" in g && (m = -1 * g.deltaY, j = m), "deltaX" in g && (l = g.deltaX, 0 === m && (j = -1 * l)), 0 !== m || 0 !== l) { if (1 === g.deltaMode) { var q = a.data(this, "mousewheel-line-height"); j *= q, m *= q, l *= q } else if (2 === g.deltaMode) { var r = a.data(this, "mousewheel-page-height"); j *= r, m *= r, l *= r } if (n = Math.max(Math.abs(m), Math.abs(l)), (!f || f > n) && (f = n, d(g, n) && (f /= 40)), d(g, n) && (j /= 40, l /= 40, m /= 40), j = Math[j >= 1 ? "floor" : "ceil"](j / f), l = Math[l >= 1 ? "floor" : "ceil"](l / f), m = Math[m >= 1 ? "floor" : "ceil"](m / f), k.settings.normalizeOffset && this.getBoundingClientRect) { var s = this.getBoundingClientRect(); o = b.clientX - s.left, p = b.clientY - s.top } return b.deltaX = l, b.deltaY = m, b.deltaFactor = f, b.offsetX = o, b.offsetY = p, b.deltaMode = 0, h.unshift(b, j, l, m), e && clearTimeout(e), e = setTimeout(c, 200), (a.event.dispatch || a.event.handle).apply(this, h) } } function c() { f = null } function d(a, b) { return k.settings.adjustOldDeltas && "mousewheel" === a.type && b % 120 === 0 } var e, f, g = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], h = "onwheel" in document || document.documentMode >= 9 ? ["wheel"] : ["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], i = Array.prototype.slice; if (a.event.fixHooks) for (var j = g.length; j;)a.event.fixHooks[g[--j]] = a.event.mouseHooks; var k = a.event.special.mousewheel = { version: "3.1.12", setup: function () { if (this.addEventListener) for (var c = h.length; c;)this.addEventListener(h[--c], b, !1); else this.onmousewheel = b; a.data(this, "mousewheel-line-height", k.getLineHeight(this)), a.data(this, "mousewheel-page-height", k.getPageHeight(this)) }, teardown: function () { if (this.removeEventListener) for (var c = h.length; c;)this.removeEventListener(h[--c], b, !1); else this.onmousewheel = null; a.removeData(this, "mousewheel-line-height"), a.removeData(this, "mousewheel-page-height") }, getLineHeight: function (b) { var c = a(b), d = c["offsetParent" in a.fn ? "offsetParent" : "parent"](); return d.length || (d = a("body")), parseInt(d.css("fontSize"), 10) || parseInt(c.css("fontSize"), 10) || 16 }, getPageHeight: function (b) { return a(b).height() }, settings: { adjustOldDeltas: !0, normalizeOffset: !0 } }; a.fn.extend({ mousewheel: function (a) { return a ? this.bind("mousewheel", a) : this.trigger("mousewheel") }, unmousewheel: function (a) { return this.unbind("mousewheel", a) } }) }); !function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : "object" == typeof exports ? module.exports = a : a(jQuery) }(function (a) { function b(b) { var g = b || window.event, h = i.call(arguments, 1), j = 0, l = 0, m = 0, n = 0, o = 0, p = 0; if (b = a.event.fix(g), b.type = "mousewheel", "detail" in g && (m = -1 * g.detail), "wheelDelta" in g && (m = g.wheelDelta), "wheelDeltaY" in g && (m = g.wheelDeltaY), "wheelDeltaX" in g && (l = -1 * g.wheelDeltaX), "axis" in g && g.axis === g.HORIZONTAL_AXIS && (l = -1 * m, m = 0), j = 0 === m ? l : m, "deltaY" in g && (m = -1 * g.deltaY, j = m), "deltaX" in g && (l = g.deltaX, 0 === m && (j = -1 * l)), 0 !== m || 0 !== l) { if (1 === g.deltaMode) { var q = a.data(this, "mousewheel-line-height"); j *= q, m *= q, l *= q } else if (2 === g.deltaMode) { var r = a.data(this, "mousewheel-page-height"); j *= r, m *= r, l *= r } if (n = Math.max(Math.abs(m), Math.abs(l)), (!f || f > n) && (f = n, d(g, n) && (f /= 40)), d(g, n) && (j /= 40, l /= 40, m /= 40), j = Math[j >= 1 ? "floor" : "ceil"](j / f), l = Math[l >= 1 ? "floor" : "ceil"](l / f), m = Math[m >= 1 ? "floor" : "ceil"](m / f), k.settings.normalizeOffset && this.getBoundingClientRect) { var s = this.getBoundingClientRect(); o = b.clientX - s.left, p = b.clientY - s.top } return b.deltaX = l, b.deltaY = m, b.deltaFactor = f, b.offsetX = o, b.offsetY = p, b.deltaMode = 0, h.unshift(b, j, l, m), e && clearTimeout(e), e = setTimeout(c, 200), (a.event.dispatch || a.event.handle).apply(this, h) } } function c() { f = null } function d(a, b) { return k.settings.adjustOldDeltas && "mousewheel" === a.type && b % 120 === 0 } var e, f, g = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], h = "onwheel" in document || document.documentMode >= 9 ? ["wheel"] : ["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], i = Array.prototype.slice; if (a.event.fixHooks) for (var j = g.length; j;)a.event.fixHooks[g[--j]] = a.event.mouseHooks; var k = a.event.special.mousewheel = { version: "3.1.12", setup: function () { if (this.addEventListener) for (var c = h.length; c;)this.addEventListener(h[--c], b, !1); else this.onmousewheel = b; a.data(this, "mousewheel-line-height", k.getLineHeight(this)), a.data(this, "mousewheel-page-height", k.getPageHeight(this)) }, teardown: function () { if (this.removeEventListener) for (var c = h.length; c;)this.removeEventListener(h[--c], b, !1); else this.onmousewheel = null; a.removeData(this, "mousewheel-line-height"), a.removeData(this, "mousewheel-page-height") }, getLineHeight: function (b) { var c = a(b), d = c["offsetParent" in a.fn ? "offsetParent" : "parent"](); return d.length || (d = a("body")), parseInt(d.css("fontSize"), 10) || parseInt(c.css("fontSize"), 10) || 16 }, getPageHeight: function (b) { return a(b).height() }, settings: { adjustOldDeltas: !0, normalizeOffset: !0 } }; a.fn.extend({ mousewheel: function (a) { return a ? this.bind("mousewheel", a) : this.trigger("mousewheel") }, unmousewheel: function (a) { return this.unbind("mousewheel", a) } }) });
/* == malihu jquery custom scrollbar plugin == Version: 3.1.5, License: MIT License (MIT) */
!function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : "undefined" != typeof module && module.exports ? module.exports = e : e(jQuery, window, document) }(function (e) {
    !function (t) { var o = "function" == typeof define && define.amd, a = "undefined" != typeof module && module.exports, n = "https:" == document.location.protocol ? "https:" : "http:", i = "cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"; o || (a ? require("jquery-mousewheel")(e) : e.event.special.mousewheel || e("head").append(decodeURI("%3Cscript src=" + n + "//" + i + "%3E%3C/script%3E"))), t() }(function () {
        var t, o = "mCustomScrollbar", a = "mCS", n = ".mCustomScrollbar", i = { setTop: 0, setLeft: 0, axis: "y", scrollbarPosition: "inside", scrollInertia: 950, autoDraggerLength: !0, alwaysShowScrollbar: 0, snapOffset: 0, mouseWheel: { enable: !0, scrollAmount: "auto", axis: "y", deltaFactor: "auto", disableOver: ["select", "option", "keygen", "datalist", "textarea"] }, scrollButtons: { scrollType: "stepless", scrollAmount: "auto" }, keyboard: { enable: !0, scrollType: "stepless", scrollAmount: "auto" }, contentTouchScroll: 25, documentTouchScroll: !0, advanced: { autoScrollOnFocus: "input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']", updateOnContentResize: !0, updateOnImageLoad: "auto", autoUpdateTimeout: 60 }, theme: "light", callbacks: { onTotalScrollOffset: 0, onTotalScrollBackOffset: 0, alwaysTriggerOffsets: !0 } }, r = 0, l = {}, s = window.attachEvent && !window.addEventListener ? 1 : 0, c = !1, d = ["mCSB_dragger_onDrag", "mCSB_scrollTools_onDrag", "mCS_img_loaded", "mCS_disabled", "mCS_destroyed", "mCS_no_scrollbar", "mCS-autoHide", "mCS-dir-rtl", "mCS_no_scrollbar_y", "mCS_no_scrollbar_x", "mCS_y_hidden", "mCS_x_hidden", "mCSB_draggerContainer", "mCSB_buttonUp", "mCSB_buttonDown", "mCSB_buttonLeft", "mCSB_buttonRight"], u = { init: function (t) { var t = e.extend(!0, {}, i, t), o = f.call(this); if (t.live) { var s = t.liveSelector || this.selector || n, c = e(s); if ("off" === t.live) return void m(s); l[s] = setTimeout(function () { c.mCustomScrollbar(t), "once" === t.live && c.length && m(s) }, 500) } else m(s); return t.setWidth = t.set_width ? t.set_width : t.setWidth, t.setHeight = t.set_height ? t.set_height : t.setHeight, t.axis = t.horizontalScroll ? "x" : p(t.axis), t.scrollInertia = t.scrollInertia > 0 && t.scrollInertia < 17 ? 17 : t.scrollInertia, "object" != typeof t.mouseWheel && 1 == t.mouseWheel && (t.mouseWheel = { enable: !0, scrollAmount: "auto", axis: "y", preventDefault: !1, deltaFactor: "auto", normalizeDelta: !1, invert: !1 }), t.mouseWheel.scrollAmount = t.mouseWheelPixels ? t.mouseWheelPixels : t.mouseWheel.scrollAmount, t.mouseWheel.normalizeDelta = t.advanced.normalizeMouseWheelDelta ? t.advanced.normalizeMouseWheelDelta : t.mouseWheel.normalizeDelta, t.scrollButtons.scrollType = g(t.scrollButtons.scrollType), h(t), e(o).each(function () { var o = e(this); if (!o.data(a)) { o.data(a, { idx: ++r, opt: t, scrollRatio: { y: null, x: null }, overflowed: null, contentReset: { y: null, x: null }, bindEvents: !1, tweenRunning: !1, sequential: {}, langDir: o.css("direction"), cbOffsets: null, trigger: null, poll: { size: { o: 0, n: 0 }, img: { o: 0, n: 0 }, change: { o: 0, n: 0 } } }); var n = o.data(a), i = n.opt, l = o.data("mcs-axis"), s = o.data("mcs-scrollbar-position"), c = o.data("mcs-theme"); l && (i.axis = l), s && (i.scrollbarPosition = s), c && (i.theme = c, h(i)), v.call(this), n && i.callbacks.onCreate && "function" == typeof i.callbacks.onCreate && i.callbacks.onCreate.call(this), e("#mCSB_" + n.idx + "_container img:not(." + d[2] + ")").addClass(d[2]), u.update.call(null, o) } }) }, update: function (t, o) { var n = t || f.call(this); return e(n).each(function () { var t = e(this); if (t.data(a)) { var n = t.data(a), i = n.opt, r = e("#mCSB_" + n.idx + "_container"), l = e("#mCSB_" + n.idx), s = [e("#mCSB_" + n.idx + "_dragger_vertical"), e("#mCSB_" + n.idx + "_dragger_horizontal")]; if (!r.length) return; n.tweenRunning && Q(t), o && n && i.callbacks.onBeforeUpdate && "function" == typeof i.callbacks.onBeforeUpdate && i.callbacks.onBeforeUpdate.call(this), t.hasClass(d[3]) && t.removeClass(d[3]), t.hasClass(d[4]) && t.removeClass(d[4]), l.css("max-height", "none"), l.height() !== t.height() && l.css("max-height", t.height()), _.call(this), "y" === i.axis || i.advanced.autoExpandHorizontalScroll || r.css("width", x(r)), n.overflowed = y.call(this), M.call(this), i.autoDraggerLength && S.call(this), b.call(this), T.call(this); var c = [Math.abs(r[0].offsetTop), Math.abs(r[0].offsetLeft)]; "x" !== i.axis && (n.overflowed[0] ? s[0].height() > s[0].parent().height() ? B.call(this) : (G(t, c[0].toString(), { dir: "y", dur: 0, overwrite: "none" }), n.contentReset.y = null) : (B.call(this), "y" === i.axis ? k.call(this) : "yx" === i.axis && n.overflowed[1] && G(t, c[1].toString(), { dir: "x", dur: 0, overwrite: "none" }))), "y" !== i.axis && (n.overflowed[1] ? s[1].width() > s[1].parent().width() ? B.call(this) : (G(t, c[1].toString(), { dir: "x", dur: 0, overwrite: "none" }), n.contentReset.x = null) : (B.call(this), "x" === i.axis ? k.call(this) : "yx" === i.axis && n.overflowed[0] && G(t, c[0].toString(), { dir: "y", dur: 0, overwrite: "none" }))), o && n && (2 === o && i.callbacks.onImageLoad && "function" == typeof i.callbacks.onImageLoad ? i.callbacks.onImageLoad.call(this) : 3 === o && i.callbacks.onSelectorChange && "function" == typeof i.callbacks.onSelectorChange ? i.callbacks.onSelectorChange.call(this) : i.callbacks.onUpdate && "function" == typeof i.callbacks.onUpdate && i.callbacks.onUpdate.call(this)), N.call(this) } }) }, scrollTo: function (t, o) { if ("undefined" != typeof t && null != t) { var n = f.call(this); return e(n).each(function () { var n = e(this); if (n.data(a)) { var i = n.data(a), r = i.opt, l = { trigger: "external", scrollInertia: r.scrollInertia, scrollEasing: "mcsEaseInOut", moveDragger: !1, timeout: 60, callbacks: !0, onStart: !0, onUpdate: !0, onComplete: !0 }, s = e.extend(!0, {}, l, o), c = Y.call(this, t), d = s.scrollInertia > 0 && s.scrollInertia < 17 ? 17 : s.scrollInertia; c[0] = X.call(this, c[0], "y"), c[1] = X.call(this, c[1], "x"), s.moveDragger && (c[0] *= i.scrollRatio.y, c[1] *= i.scrollRatio.x), s.dur = ne() ? 0 : d, setTimeout(function () { null !== c[0] && "undefined" != typeof c[0] && "x" !== r.axis && i.overflowed[0] && (s.dir = "y", s.overwrite = "all", G(n, c[0].toString(), s)), null !== c[1] && "undefined" != typeof c[1] && "y" !== r.axis && i.overflowed[1] && (s.dir = "x", s.overwrite = "none", G(n, c[1].toString(), s)) }, s.timeout) } }) } }, stop: function () { var t = f.call(this); return e(t).each(function () { var t = e(this); t.data(a) && Q(t) }) }, disable: function (t) { var o = f.call(this); return e(o).each(function () { var o = e(this); if (o.data(a)) { o.data(a); N.call(this, "remove"), k.call(this), t && B.call(this), M.call(this, !0), o.addClass(d[3]) } }) }, destroy: function () { var t = f.call(this); return e(t).each(function () { var n = e(this); if (n.data(a)) { var i = n.data(a), r = i.opt, l = e("#mCSB_" + i.idx), s = e("#mCSB_" + i.idx + "_container"), c = e(".mCSB_" + i.idx + "_scrollbar"); r.live && m(r.liveSelector || e(t).selector), N.call(this, "remove"), k.call(this), B.call(this), n.removeData(a), $(this, "mcs"), c.remove(), s.find("img." + d[2]).removeClass(d[2]), l.replaceWith(s.contents()), n.removeClass(o + " _" + a + "_" + i.idx + " " + d[6] + " " + d[7] + " " + d[5] + " " + d[3]).addClass(d[4]) } }) } }, f = function () { return "object" != typeof e(this) || e(this).length < 1 ? n : this }, h = function (t) { var o = ["rounded", "rounded-dark", "rounded-dots", "rounded-dots-dark"], a = ["rounded-dots", "rounded-dots-dark", "3d", "3d-dark", "3d-thick", "3d-thick-dark", "inset", "inset-dark", "inset-2", "inset-2-dark", "inset-3", "inset-3-dark"], n = ["minimal", "minimal-dark"], i = ["minimal", "minimal-dark"], r = ["minimal", "minimal-dark"]; t.autoDraggerLength = e.inArray(t.theme, o) > -1 ? !1 : t.autoDraggerLength, t.autoExpandScrollbar = e.inArray(t.theme, a) > -1 ? !1 : t.autoExpandScrollbar, t.scrollButtons.enable = e.inArray(t.theme, n) > -1 ? !1 : t.scrollButtons.enable, t.autoHideScrollbar = e.inArray(t.theme, i) > -1 ? !0 : t.autoHideScrollbar, t.scrollbarPosition = e.inArray(t.theme, r) > -1 ? "outside" : t.scrollbarPosition }, m = function (e) { l[e] && (clearTimeout(l[e]), $(l, e)) }, p = function (e) { return "yx" === e || "xy" === e || "auto" === e ? "yx" : "x" === e || "horizontal" === e ? "x" : "y" }, g = function (e) { return "stepped" === e || "pixels" === e || "step" === e || "click" === e ? "stepped" : "stepless" }, v = function () { var t = e(this), n = t.data(a), i = n.opt, r = i.autoExpandScrollbar ? " " + d[1] + "_expand" : "", l = ["<div id='mCSB_" + n.idx + "_scrollbar_vertical' class='mCSB_scrollTools mCSB_" + n.idx + "_scrollbar mCS-" + i.theme + " mCSB_scrollTools_vertical" + r + "'><div class='" + d[12] + "'><div id='mCSB_" + n.idx + "_dragger_vertical' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>", "<div id='mCSB_" + n.idx + "_scrollbar_horizontal' class='mCSB_scrollTools mCSB_" + n.idx + "_scrollbar mCS-" + i.theme + " mCSB_scrollTools_horizontal" + r + "'><div class='" + d[12] + "'><div id='mCSB_" + n.idx + "_dragger_horizontal' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"], s = "yx" === i.axis ? "mCSB_vertical_horizontal" : "x" === i.axis ? "mCSB_horizontal" : "mCSB_vertical", c = "yx" === i.axis ? l[0] + l[1] : "x" === i.axis ? l[1] : l[0], u = "yx" === i.axis ? "<div id='mCSB_" + n.idx + "_container_wrapper' class='mCSB_container_wrapper' />" : "", f = i.autoHideScrollbar ? " " + d[6] : "", h = "x" !== i.axis && "rtl" === n.langDir ? " " + d[7] : ""; i.setWidth && t.css("width", i.setWidth), i.setHeight && t.css("height", i.setHeight), i.setLeft = "y" !== i.axis && "rtl" === n.langDir ? "989999px" : i.setLeft, t.addClass(o + " _" + a + "_" + n.idx + f + h).wrapInner("<div id='mCSB_" + n.idx + "' class='mCustomScrollBox mCS-" + i.theme + " " + s + "'><div id='mCSB_" + n.idx + "_container' class='mCSB_container' style='position:relative; top:" + i.setTop + "; left:" + i.setLeft + ";' dir='" + n.langDir + "' /></div>"); var m = e("#mCSB_" + n.idx), p = e("#mCSB_" + n.idx + "_container"); "y" === i.axis || i.advanced.autoExpandHorizontalScroll || p.css("width", x(p)), "outside" === i.scrollbarPosition ? ("static" === t.css("position") && t.css("position", "relative"), t.css("overflow", "visible"), m.addClass("mCSB_outside").after(c)) : (m.addClass("mCSB_inside").append(c), p.wrap(u)), w.call(this); var g = [e("#mCSB_" + n.idx + "_dragger_vertical"), e("#mCSB_" + n.idx + "_dragger_horizontal")]; g[0].css("min-height", g[0].height()), g[1].css("min-width", g[1].width()) }, x = function (t) { var o = [t[0].scrollWidth, Math.max.apply(Math, t.children().map(function () { return e(this).outerWidth(!0) }).get())], a = t.parent().width(); return o[0] > a ? o[0] : o[1] > a ? o[1] : "100%" }, _ = function () { var t = e(this), o = t.data(a), n = o.opt, i = e("#mCSB_" + o.idx + "_container"); if (n.advanced.autoExpandHorizontalScroll && "y" !== n.axis) { i.css({ width: "auto", "min-width": 0, "overflow-x": "scroll" }); var r = Math.ceil(i[0].scrollWidth); 3 === n.advanced.autoExpandHorizontalScroll || 2 !== n.advanced.autoExpandHorizontalScroll && r > i.parent().width() ? i.css({ width: r, "min-width": "100%", "overflow-x": "inherit" }) : i.css({ "overflow-x": "inherit", position: "absolute" }).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({ width: Math.ceil(i[0].getBoundingClientRect().right + .4) - Math.floor(i[0].getBoundingClientRect().left), "min-width": "100%", position: "relative" }).unwrap() } }, w = function () { var t = e(this), o = t.data(a), n = o.opt, i = e(".mCSB_" + o.idx + "_scrollbar:first"), r = oe(n.scrollButtons.tabindex) ? "tabindex='" + n.scrollButtons.tabindex + "'" : "", l = ["<a href='#' class='" + d[13] + "' " + r + " />", "<a href='#' class='" + d[14] + "' " + r + " />", "<a href='#' class='" + d[15] + "' " + r + " />", "<a href='#' class='" + d[16] + "' " + r + " />"], s = ["x" === n.axis ? l[2] : l[0], "x" === n.axis ? l[3] : l[1], l[2], l[3]]; n.scrollButtons.enable && i.prepend(s[0]).append(s[1]).next(".mCSB_scrollTools").prepend(s[2]).append(s[3]) }, S = function () { var t = e(this), o = t.data(a), n = e("#mCSB_" + o.idx), i = e("#mCSB_" + o.idx + "_container"), r = [e("#mCSB_" + o.idx + "_dragger_vertical"), e("#mCSB_" + o.idx + "_dragger_horizontal")], l = [n.height() / i.outerHeight(!1), n.width() / i.outerWidth(!1)], c = [parseInt(r[0].css("min-height")), Math.round(l[0] * r[0].parent().height()), parseInt(r[1].css("min-width")), Math.round(l[1] * r[1].parent().width())], d = s && c[1] < c[0] ? c[0] : c[1], u = s && c[3] < c[2] ? c[2] : c[3]; r[0].css({ height: d, "max-height": r[0].parent().height() - 10 }).find(".mCSB_dragger_bar").css({ "line-height": c[0] + "px" }), r[1].css({ width: u, "max-width": r[1].parent().width() - 10 }) }, b = function () { var t = e(this), o = t.data(a), n = e("#mCSB_" + o.idx), i = e("#mCSB_" + o.idx + "_container"), r = [e("#mCSB_" + o.idx + "_dragger_vertical"), e("#mCSB_" + o.idx + "_dragger_horizontal")], l = [i.outerHeight(!1) - n.height(), i.outerWidth(!1) - n.width()], s = [l[0] / (r[0].parent().height() - r[0].height()), l[1] / (r[1].parent().width() - r[1].width())]; o.scrollRatio = { y: s[0], x: s[1] } }, C = function (e, t, o) { var a = o ? d[0] + "_expanded" : "", n = e.closest(".mCSB_scrollTools"); "active" === t ? (e.toggleClass(d[0] + " " + a), n.toggleClass(d[1]), e[0]._draggable = e[0]._draggable ? 0 : 1) : e[0]._draggable || ("hide" === t ? (e.removeClass(d[0]), n.removeClass(d[1])) : (e.addClass(d[0]), n.addClass(d[1]))) }, y = function () { var t = e(this), o = t.data(a), n = e("#mCSB_" + o.idx), i = e("#mCSB_" + o.idx + "_container"), r = null == o.overflowed ? i.height() : i.outerHeight(!1), l = null == o.overflowed ? i.width() : i.outerWidth(!1), s = i[0].scrollHeight, c = i[0].scrollWidth; return s > r && (r = s), c > l && (l = c), [r > n.height(), l > n.width()] }, B = function () { var t = e(this), o = t.data(a), n = o.opt, i = e("#mCSB_" + o.idx), r = e("#mCSB_" + o.idx + "_container"), l = [e("#mCSB_" + o.idx + "_dragger_vertical"), e("#mCSB_" + o.idx + "_dragger_horizontal")]; if (Q(t), ("x" !== n.axis && !o.overflowed[0] || "y" === n.axis && o.overflowed[0]) && (l[0].add(r).css("top", 0), G(t, "_resetY")), "y" !== n.axis && !o.overflowed[1] || "x" === n.axis && o.overflowed[1]) { var s = dx = 0; "rtl" === o.langDir && (s = i.width() - r.outerWidth(!1), dx = Math.abs(s / o.scrollRatio.x)), r.css("left", s), l[1].css("left", dx), G(t, "_resetX") } }, T = function () { function t() { r = setTimeout(function () { e.event.special.mousewheel ? (clearTimeout(r), W.call(o[0])) : t() }, 100) } var o = e(this), n = o.data(a), i = n.opt; if (!n.bindEvents) { if (I.call(this), i.contentTouchScroll && D.call(this), E.call(this), i.mouseWheel.enable) { var r; t() } P.call(this), U.call(this), i.advanced.autoScrollOnFocus && H.call(this), i.scrollButtons.enable && F.call(this), i.keyboard.enable && q.call(this), n.bindEvents = !0 } }, k = function () { var t = e(this), o = t.data(a), n = o.opt, i = a + "_" + o.idx, r = ".mCSB_" + o.idx + "_scrollbar", l = e("#mCSB_" + o.idx + ",#mCSB_" + o.idx + "_container,#mCSB_" + o.idx + "_container_wrapper," + r + " ." + d[12] + ",#mCSB_" + o.idx + "_dragger_vertical,#mCSB_" + o.idx + "_dragger_horizontal," + r + ">a"), s = e("#mCSB_" + o.idx + "_container"); n.advanced.releaseDraggableSelectors && l.add(e(n.advanced.releaseDraggableSelectors)), n.advanced.extraDraggableSelectors && l.add(e(n.advanced.extraDraggableSelectors)), o.bindEvents && (e(document).add(e(!A() || top.document)).unbind("." + i), l.each(function () { e(this).unbind("." + i) }), clearTimeout(t[0]._focusTimeout), $(t[0], "_focusTimeout"), clearTimeout(o.sequential.step), $(o.sequential, "step"), clearTimeout(s[0].onCompleteTimeout), $(s[0], "onCompleteTimeout"), o.bindEvents = !1) }, M = function (t) { var o = e(this), n = o.data(a), i = n.opt, r = e("#mCSB_" + n.idx + "_container_wrapper"), l = r.length ? r : e("#mCSB_" + n.idx + "_container"), s = [e("#mCSB_" + n.idx + "_scrollbar_vertical"), e("#mCSB_" + n.idx + "_scrollbar_horizontal")], c = [s[0].find(".mCSB_dragger"), s[1].find(".mCSB_dragger")]; "x" !== i.axis && (n.overflowed[0] && !t ? (s[0].add(c[0]).add(s[0].children("a")).css("display", "block"), l.removeClass(d[8] + " " + d[10])) : (i.alwaysShowScrollbar ? (2 !== i.alwaysShowScrollbar && c[0].css("display", "none"), l.removeClass(d[10])) : (s[0].css("display", "none"), l.addClass(d[10])), l.addClass(d[8]))), "y" !== i.axis && (n.overflowed[1] && !t ? (s[1].add(c[1]).add(s[1].children("a")).css("display", "block"), l.removeClass(d[9] + " " + d[11])) : (i.alwaysShowScrollbar ? (2 !== i.alwaysShowScrollbar && c[1].css("display", "none"), l.removeClass(d[11])) : (s[1].css("display", "none"), l.addClass(d[11])), l.addClass(d[9]))), n.overflowed[0] || n.overflowed[1] ? o.removeClass(d[5]) : o.addClass(d[5]) }, O = function (t) { var o = t.type, a = t.target.ownerDocument !== document && null !== frameElement ? [e(frameElement).offset().top, e(frameElement).offset().left] : null, n = A() && t.target.ownerDocument !== top.document && null !== frameElement ? [e(t.view.frameElement).offset().top, e(t.view.frameElement).offset().left] : [0, 0]; switch (o) { case "pointerdown": case "MSPointerDown": case "pointermove": case "MSPointerMove": case "pointerup": case "MSPointerUp": return a ? [t.originalEvent.pageY - a[0] + n[0], t.originalEvent.pageX - a[1] + n[1], !1] : [t.originalEvent.pageY, t.originalEvent.pageX, !1]; case "touchstart": case "touchmove": case "touchend": var i = t.originalEvent.touches[0] || t.originalEvent.changedTouches[0], r = t.originalEvent.touches.length || t.originalEvent.changedTouches.length; return t.target.ownerDocument !== document ? [i.screenY, i.screenX, r > 1] : [i.pageY, i.pageX, r > 1]; default: return a ? [t.pageY - a[0] + n[0], t.pageX - a[1] + n[1], !1] : [t.pageY, t.pageX, !1] } }, I = function () { function t(e, t, a, n) { if (h[0].idleTimer = d.scrollInertia < 233 ? 250 : 0, o.attr("id") === f[1]) var i = "x", s = (o[0].offsetLeft - t + n) * l.scrollRatio.x; else var i = "y", s = (o[0].offsetTop - e + a) * l.scrollRatio.y; G(r, s.toString(), { dir: i, drag: !0 }) } var o, n, i, r = e(this), l = r.data(a), d = l.opt, u = a + "_" + l.idx, f = ["mCSB_" + l.idx + "_dragger_vertical", "mCSB_" + l.idx + "_dragger_horizontal"], h = e("#mCSB_" + l.idx + "_container"), m = e("#" + f[0] + ",#" + f[1]), p = d.advanced.releaseDraggableSelectors ? m.add(e(d.advanced.releaseDraggableSelectors)) : m, g = d.advanced.extraDraggableSelectors ? e(!A() || top.document).add(e(d.advanced.extraDraggableSelectors)) : e(!A() || top.document); m.bind("contextmenu." + u, function (e) { e.preventDefault() }).bind("mousedown." + u + " touchstart." + u + " pointerdown." + u + " MSPointerDown." + u, function (t) { if (t.stopImmediatePropagation(), t.preventDefault(), ee(t)) { c = !0, s && (document.onselectstart = function () { return !1 }), L.call(h, !1), Q(r), o = e(this); var a = o.offset(), l = O(t)[0] - a.top, u = O(t)[1] - a.left, f = o.height() + a.top, m = o.width() + a.left; f > l && l > 0 && m > u && u > 0 && (n = l, i = u), C(o, "active", d.autoExpandScrollbar) } }).bind("touchmove." + u, function (e) { e.stopImmediatePropagation(), e.preventDefault(); var a = o.offset(), r = O(e)[0] - a.top, l = O(e)[1] - a.left; t(n, i, r, l) }), e(document).add(g).bind("mousemove." + u + " pointermove." + u + " MSPointerMove." + u, function (e) { if (o) { var a = o.offset(), r = O(e)[0] - a.top, l = O(e)[1] - a.left; if (n === r && i === l) return; t(n, i, r, l) } }).add(p).bind("mouseup." + u + " touchend." + u + " pointerup." + u + " MSPointerUp." + u, function () { o && (C(o, "active", d.autoExpandScrollbar), o = null), c = !1, s && (document.onselectstart = null), L.call(h, !0) }) }, D = function () { function o(e) { if (!te(e) || c || O(e)[2]) return void (t = 0); t = 1, b = 0, C = 0, d = 1, y.removeClass("mCS_touch_action"); var o = I.offset(); u = O(e)[0] - o.top, f = O(e)[1] - o.left, z = [O(e)[0], O(e)[1]] } function n(e) { if (te(e) && !c && !O(e)[2] && (T.documentTouchScroll || e.preventDefault(), e.stopImmediatePropagation(), (!C || b) && d)) { g = K(); var t = M.offset(), o = O(e)[0] - t.top, a = O(e)[1] - t.left, n = "mcsLinearOut"; if (E.push(o), W.push(a), z[2] = Math.abs(O(e)[0] - z[0]), z[3] = Math.abs(O(e)[1] - z[1]), B.overflowed[0]) var i = D[0].parent().height() - D[0].height(), r = u - o > 0 && o - u > -(i * B.scrollRatio.y) && (2 * z[3] < z[2] || "yx" === T.axis); if (B.overflowed[1]) var l = D[1].parent().width() - D[1].width(), h = f - a > 0 && a - f > -(l * B.scrollRatio.x) && (2 * z[2] < z[3] || "yx" === T.axis); r || h ? (U || e.preventDefault(), b = 1) : (C = 1, y.addClass("mCS_touch_action")), U && e.preventDefault(), w = "yx" === T.axis ? [u - o, f - a] : "x" === T.axis ? [null, f - a] : [u - o, null], I[0].idleTimer = 250, B.overflowed[0] && s(w[0], R, n, "y", "all", !0), B.overflowed[1] && s(w[1], R, n, "x", L, !0) } } function i(e) { if (!te(e) || c || O(e)[2]) return void (t = 0); t = 1, e.stopImmediatePropagation(), Q(y), p = K(); var o = M.offset(); h = O(e)[0] - o.top, m = O(e)[1] - o.left, E = [], W = [] } function r(e) { if (te(e) && !c && !O(e)[2]) { d = 0, e.stopImmediatePropagation(), b = 0, C = 0, v = K(); var t = M.offset(), o = O(e)[0] - t.top, a = O(e)[1] - t.left; if (!(v - g > 30)) { _ = 1e3 / (v - p); var n = "mcsEaseOut", i = 2.5 > _, r = i ? [E[E.length - 2], W[W.length - 2]] : [0, 0]; x = i ? [o - r[0], a - r[1]] : [o - h, a - m]; var u = [Math.abs(x[0]), Math.abs(x[1])]; _ = i ? [Math.abs(x[0] / 4), Math.abs(x[1] / 4)] : [_, _]; var f = [Math.abs(I[0].offsetTop) - x[0] * l(u[0] / _[0], _[0]), Math.abs(I[0].offsetLeft) - x[1] * l(u[1] / _[1], _[1])]; w = "yx" === T.axis ? [f[0], f[1]] : "x" === T.axis ? [null, f[1]] : [f[0], null], S = [4 * u[0] + T.scrollInertia, 4 * u[1] + T.scrollInertia]; var y = parseInt(T.contentTouchScroll) || 0; w[0] = u[0] > y ? w[0] : 0, w[1] = u[1] > y ? w[1] : 0, B.overflowed[0] && s(w[0], S[0], n, "y", L, !1), B.overflowed[1] && s(w[1], S[1], n, "x", L, !1) } } } function l(e, t) { var o = [1.5 * t, 2 * t, t / 1.5, t / 2]; return e > 90 ? t > 4 ? o[0] : o[3] : e > 60 ? t > 3 ? o[3] : o[2] : e > 30 ? t > 8 ? o[1] : t > 6 ? o[0] : t > 4 ? t : o[2] : t > 8 ? t : o[3] } function s(e, t, o, a, n, i) { e && G(y, e.toString(), { dur: t, scrollEasing: o, dir: a, overwrite: n, drag: i }) } var d, u, f, h, m, p, g, v, x, _, w, S, b, C, y = e(this), B = y.data(a), T = B.opt, k = a + "_" + B.idx, M = e("#mCSB_" + B.idx), I = e("#mCSB_" + B.idx + "_container"), D = [e("#mCSB_" + B.idx + "_dragger_vertical"), e("#mCSB_" + B.idx + "_dragger_horizontal")], E = [], W = [], R = 0, L = "yx" === T.axis ? "none" : "all", z = [], P = I.find("iframe"), H = ["touchstart." + k + " pointerdown." + k + " MSPointerDown." + k, "touchmove." + k + " pointermove." + k + " MSPointerMove." + k, "touchend." + k + " pointerup." + k + " MSPointerUp." + k], U = void 0 !== document.body.style.touchAction && "" !== document.body.style.touchAction; I.bind(H[0], function (e) { o(e) }).bind(H[1], function (e) { n(e) }), M.bind(H[0], function (e) { i(e) }).bind(H[2], function (e) { r(e) }), P.length && P.each(function () { e(this).bind("load", function () { A(this) && e(this.contentDocument || this.contentWindow.document).bind(H[0], function (e) { o(e), i(e) }).bind(H[1], function (e) { n(e) }).bind(H[2], function (e) { r(e) }) }) }) }, E = function () { function o() { return window.getSelection ? window.getSelection().toString() : document.selection && "Control" != document.selection.type ? document.selection.createRange().text : 0 } function n(e, t, o) { d.type = o && i ? "stepped" : "stepless", d.scrollAmount = 10, j(r, e, t, "mcsLinearOut", o ? 60 : null) } var i, r = e(this), l = r.data(a), s = l.opt, d = l.sequential, u = a + "_" + l.idx, f = e("#mCSB_" + l.idx + "_container"), h = f.parent(); f.bind("mousedown." + u, function () { t || i || (i = 1, c = !0) }).add(document).bind("mousemove." + u, function (e) { if (!t && i && o()) { var a = f.offset(), r = O(e)[0] - a.top + f[0].offsetTop, c = O(e)[1] - a.left + f[0].offsetLeft; r > 0 && r < h.height() && c > 0 && c < h.width() ? d.step && n("off", null, "stepped") : ("x" !== s.axis && l.overflowed[0] && (0 > r ? n("on", 38) : r > h.height() && n("on", 40)), "y" !== s.axis && l.overflowed[1] && (0 > c ? n("on", 37) : c > h.width() && n("on", 39))) } }).bind("mouseup." + u + " dragend." + u, function () { t || (i && (i = 0, n("off", null)), c = !1) }) }, W = function () { function t(t, a) { if (Q(o), !z(o, t.target)) { var r = "auto" !== i.mouseWheel.deltaFactor ? parseInt(i.mouseWheel.deltaFactor) : s && t.deltaFactor < 100 ? 100 : t.deltaFactor || 100, d = i.scrollInertia; if ("x" === i.axis || "x" === i.mouseWheel.axis) var u = "x", f = [Math.round(r * n.scrollRatio.x), parseInt(i.mouseWheel.scrollAmount)], h = "auto" !== i.mouseWheel.scrollAmount ? f[1] : f[0] >= l.width() ? .9 * l.width() : f[0], m = Math.abs(e("#mCSB_" + n.idx + "_container")[0].offsetLeft), p = c[1][0].offsetLeft, g = c[1].parent().width() - c[1].width(), v = "y" === i.mouseWheel.axis ? t.deltaY || a : t.deltaX; else var u = "y", f = [Math.round(r * n.scrollRatio.y), parseInt(i.mouseWheel.scrollAmount)], h = "auto" !== i.mouseWheel.scrollAmount ? f[1] : f[0] >= l.height() ? .9 * l.height() : f[0], m = Math.abs(e("#mCSB_" + n.idx + "_container")[0].offsetTop), p = c[0][0].offsetTop, g = c[0].parent().height() - c[0].height(), v = t.deltaY || a; "y" === u && !n.overflowed[0] || "x" === u && !n.overflowed[1] || ((i.mouseWheel.invert || t.webkitDirectionInvertedFromDevice) && (v = -v), i.mouseWheel.normalizeDelta && (v = 0 > v ? -1 : 1), (v > 0 && 0 !== p || 0 > v && p !== g || i.mouseWheel.preventDefault) && (t.stopImmediatePropagation(), t.preventDefault()), t.deltaFactor < 5 && !i.mouseWheel.normalizeDelta && (h = t.deltaFactor, d = 17), G(o, (m - v * h).toString(), { dir: u, dur: d })) } } if (e(this).data(a)) { var o = e(this), n = o.data(a), i = n.opt, r = a + "_" + n.idx, l = e("#mCSB_" + n.idx), c = [e("#mCSB_" + n.idx + "_dragger_vertical"), e("#mCSB_" + n.idx + "_dragger_horizontal")], d = e("#mCSB_" + n.idx + "_container").find("iframe"); d.length && d.each(function () { e(this).bind("load", function () { A(this) && e(this.contentDocument || this.contentWindow.document).bind("mousewheel." + r, function (e, o) { t(e, o) }) }) }), l.bind("mousewheel." + r, function (e, o) { t(e, o) }) } }, R = new Object, A = function (t) { var o = !1, a = !1, n = null; if (void 0 === t ? a = "#empty" : void 0 !== e(t).attr("id") && (a = e(t).attr("id")), a !== !1 && void 0 !== R[a]) return R[a]; if (t) { try { var i = t.contentDocument || t.contentWindow.document; n = i.body.innerHTML } catch (r) { } o = null !== n } else { try { var i = top.document; n = i.body.innerHTML } catch (r) { } o = null !== n } return a !== !1 && (R[a] = o), o }, L = function (e) { var t = this.find("iframe"); if (t.length) { var o = e ? "auto" : "none"; t.css("pointer-events", o) } }, z = function (t, o) { var n = o.nodeName.toLowerCase(), i = t.data(a).opt.mouseWheel.disableOver, r = ["select", "textarea"]; return e.inArray(n, i) > -1 && !(e.inArray(n, r) > -1 && !e(o).is(":focus")) }, P = function () { var t, o = e(this), n = o.data(a), i = a + "_" + n.idx, r = e("#mCSB_" + n.idx + "_container"), l = r.parent(), s = e(".mCSB_" + n.idx + "_scrollbar ." + d[12]); s.bind("mousedown." + i + " touchstart." + i + " pointerdown." + i + " MSPointerDown." + i, function (o) { c = !0, e(o.target).hasClass("mCSB_dragger") || (t = 1) }).bind("touchend." + i + " pointerup." + i + " MSPointerUp." + i, function () { c = !1 }).bind("click." + i, function (a) { if (t && (t = 0, e(a.target).hasClass(d[12]) || e(a.target).hasClass("mCSB_draggerRail"))) { Q(o); var i = e(this), s = i.find(".mCSB_dragger"); if (i.parent(".mCSB_scrollTools_horizontal").length > 0) { if (!n.overflowed[1]) return; var c = "x", u = a.pageX > s.offset().left ? -1 : 1, f = Math.abs(r[0].offsetLeft) - u * (.9 * l.width()) } else { if (!n.overflowed[0]) return; var c = "y", u = a.pageY > s.offset().top ? -1 : 1, f = Math.abs(r[0].offsetTop) - u * (.9 * l.height()) } G(o, f.toString(), { dir: c, scrollEasing: "mcsEaseInOut" }) } }) }, H = function () { var t = e(this), o = t.data(a), n = o.opt, i = a + "_" + o.idx, r = e("#mCSB_" + o.idx + "_container"), l = r.parent(); r.bind("focusin." + i, function () { var o = e(document.activeElement), a = r.find(".mCustomScrollBox").length, i = 0; o.is(n.advanced.autoScrollOnFocus) && (Q(t), clearTimeout(t[0]._focusTimeout), t[0]._focusTimer = a ? (i + 17) * a : 0, t[0]._focusTimeout = setTimeout(function () { var e = [ae(o)[0], ae(o)[1]], a = [r[0].offsetTop, r[0].offsetLeft], s = [a[0] + e[0] >= 0 && a[0] + e[0] < l.height() - o.outerHeight(!1), a[1] + e[1] >= 0 && a[0] + e[1] < l.width() - o.outerWidth(!1)], c = "yx" !== n.axis || s[0] || s[1] ? "all" : "none"; "x" === n.axis || s[0] || G(t, e[0].toString(), { dir: "y", scrollEasing: "mcsEaseInOut", overwrite: c, dur: i }), "y" === n.axis || s[1] || G(t, e[1].toString(), { dir: "x", scrollEasing: "mcsEaseInOut", overwrite: c, dur: i }) }, t[0]._focusTimer)) }) }, U = function () { var t = e(this), o = t.data(a), n = a + "_" + o.idx, i = e("#mCSB_" + o.idx + "_container").parent(); i.bind("scroll." + n, function () { 0 === i.scrollTop() && 0 === i.scrollLeft() || e(".mCSB_" + o.idx + "_scrollbar").css("visibility", "hidden") }) }, F = function () { var t = e(this), o = t.data(a), n = o.opt, i = o.sequential, r = a + "_" + o.idx, l = ".mCSB_" + o.idx + "_scrollbar", s = e(l + ">a"); s.bind("contextmenu." + r, function (e) { e.preventDefault() }).bind("mousedown." + r + " touchstart." + r + " pointerdown." + r + " MSPointerDown." + r + " mouseup." + r + " touchend." + r + " pointerup." + r + " MSPointerUp." + r + " mouseout." + r + " pointerout." + r + " MSPointerOut." + r + " click." + r, function (a) { function r(e, o) { i.scrollAmount = n.scrollButtons.scrollAmount, j(t, e, o) } if (a.preventDefault(), ee(a)) { var l = e(this).attr("class"); switch (i.type = n.scrollButtons.scrollType, a.type) { case "mousedown": case "touchstart": case "pointerdown": case "MSPointerDown": if ("stepped" === i.type) return; c = !0, o.tweenRunning = !1, r("on", l); break; case "mouseup": case "touchend": case "pointerup": case "MSPointerUp": case "mouseout": case "pointerout": case "MSPointerOut": if ("stepped" === i.type) return; c = !1, i.dir && r("off", l); break; case "click": if ("stepped" !== i.type || o.tweenRunning) return; r("on", l) } } }) }, q = function () { function t(t) { function a(e, t) { r.type = i.keyboard.scrollType, r.scrollAmount = i.keyboard.scrollAmount, "stepped" === r.type && n.tweenRunning || j(o, e, t) } switch (t.type) { case "blur": n.tweenRunning && r.dir && a("off", null); break; case "keydown": case "keyup": var l = t.keyCode ? t.keyCode : t.which, s = "on"; if ("x" !== i.axis && (38 === l || 40 === l) || "y" !== i.axis && (37 === l || 39 === l)) { if ((38 === l || 40 === l) && !n.overflowed[0] || (37 === l || 39 === l) && !n.overflowed[1]) return; "keyup" === t.type && (s = "off"), e(document.activeElement).is(u) || (t.preventDefault(), t.stopImmediatePropagation(), a(s, l)) } else if (33 === l || 34 === l) { if ((n.overflowed[0] || n.overflowed[1]) && (t.preventDefault(), t.stopImmediatePropagation()), "keyup" === t.type) { Q(o); var f = 34 === l ? -1 : 1; if ("x" === i.axis || "yx" === i.axis && n.overflowed[1] && !n.overflowed[0]) var h = "x", m = Math.abs(c[0].offsetLeft) - f * (.9 * d.width()); else var h = "y", m = Math.abs(c[0].offsetTop) - f * (.9 * d.height()); G(o, m.toString(), { dir: h, scrollEasing: "mcsEaseInOut" }) } } else if ((35 === l || 36 === l) && !e(document.activeElement).is(u) && ((n.overflowed[0] || n.overflowed[1]) && (t.preventDefault(), t.stopImmediatePropagation()), "keyup" === t.type)) { if ("x" === i.axis || "yx" === i.axis && n.overflowed[1] && !n.overflowed[0]) var h = "x", m = 35 === l ? Math.abs(d.width() - c.outerWidth(!1)) : 0; else var h = "y", m = 35 === l ? Math.abs(d.height() - c.outerHeight(!1)) : 0; G(o, m.toString(), { dir: h, scrollEasing: "mcsEaseInOut" }) } } } var o = e(this), n = o.data(a), i = n.opt, r = n.sequential, l = a + "_" + n.idx, s = e("#mCSB_" + n.idx), c = e("#mCSB_" + n.idx + "_container"), d = c.parent(), u = "input,textarea,select,datalist,keygen,[contenteditable='true']", f = c.find("iframe"), h = ["blur." + l + " keydown." + l + " keyup." + l]; f.length && f.each(function () { e(this).bind("load", function () { A(this) && e(this.contentDocument || this.contentWindow.document).bind(h[0], function (e) { t(e) }) }) }), s.attr("tabindex", "0").bind(h[0], function (e) { t(e) }) }, j = function (t, o, n, i, r) { function l(e) { u.snapAmount && (f.scrollAmount = u.snapAmount instanceof Array ? "x" === f.dir[0] ? u.snapAmount[1] : u.snapAmount[0] : u.snapAmount); var o = "stepped" !== f.type, a = r ? r : e ? o ? p / 1.5 : g : 1e3 / 60, n = e ? o ? 7.5 : 40 : 2.5, s = [Math.abs(h[0].offsetTop), Math.abs(h[0].offsetLeft)], d = [c.scrollRatio.y > 10 ? 10 : c.scrollRatio.y, c.scrollRatio.x > 10 ? 10 : c.scrollRatio.x], m = "x" === f.dir[0] ? s[1] + f.dir[1] * (d[1] * n) : s[0] + f.dir[1] * (d[0] * n), v = "x" === f.dir[0] ? s[1] + f.dir[1] * parseInt(f.scrollAmount) : s[0] + f.dir[1] * parseInt(f.scrollAmount), x = "auto" !== f.scrollAmount ? v : m, _ = i ? i : e ? o ? "mcsLinearOut" : "mcsEaseInOut" : "mcsLinear", w = !!e; return e && 17 > a && (x = "x" === f.dir[0] ? s[1] : s[0]), G(t, x.toString(), { dir: f.dir[0], scrollEasing: _, dur: a, onComplete: w }), e ? void (f.dir = !1) : (clearTimeout(f.step), void (f.step = setTimeout(function () { l() }, a))) } function s() { clearTimeout(f.step), $(f, "step"), Q(t) } var c = t.data(a), u = c.opt, f = c.sequential, h = e("#mCSB_" + c.idx + "_container"), m = "stepped" === f.type, p = u.scrollInertia < 26 ? 26 : u.scrollInertia, g = u.scrollInertia < 1 ? 17 : u.scrollInertia; switch (o) { case "on": if (f.dir = [n === d[16] || n === d[15] || 39 === n || 37 === n ? "x" : "y", n === d[13] || n === d[15] || 38 === n || 37 === n ? -1 : 1], Q(t), oe(n) && "stepped" === f.type) return; l(m); break; case "off": s(), (m || c.tweenRunning && f.dir) && l(!0) } }, Y = function (t) { var o = e(this).data(a).opt, n = []; return "function" == typeof t && (t = t()), t instanceof Array ? n = t.length > 1 ? [t[0], t[1]] : "x" === o.axis ? [null, t[0]] : [t[0], null] : (n[0] = t.y ? t.y : t.x || "x" === o.axis ? null : t, n[1] = t.x ? t.x : t.y || "y" === o.axis ? null : t), "function" == typeof n[0] && (n[0] = n[0]()), "function" == typeof n[1] && (n[1] = n[1]()), n }, X = function (t, o) { if (null != t && "undefined" != typeof t) { var n = e(this), i = n.data(a), r = i.opt, l = e("#mCSB_" + i.idx + "_container"), s = l.parent(), c = typeof t; o || (o = "x" === r.axis ? "x" : "y"); var d = "x" === o ? l.outerWidth(!1) - s.width() : l.outerHeight(!1) - s.height(), f = "x" === o ? l[0].offsetLeft : l[0].offsetTop, h = "x" === o ? "left" : "top"; switch (c) { case "function": return t(); case "object": var m = t.jquery ? t : e(t); if (!m.length) return; return "x" === o ? ae(m)[1] : ae(m)[0]; case "string": case "number": if (oe(t)) return Math.abs(t); if (-1 !== t.indexOf("%")) return Math.abs(d * parseInt(t) / 100); if (-1 !== t.indexOf("-=")) return Math.abs(f - parseInt(t.split("-=")[1])); if (-1 !== t.indexOf("+=")) { var p = f + parseInt(t.split("+=")[1]); return p >= 0 ? 0 : Math.abs(p) } if (-1 !== t.indexOf("px") && oe(t.split("px")[0])) return Math.abs(t.split("px")[0]); if ("top" === t || "left" === t) return 0; if ("bottom" === t) return Math.abs(s.height() - l.outerHeight(!1)); if ("right" === t) return Math.abs(s.width() - l.outerWidth(!1)); if ("first" === t || "last" === t) { var m = l.find(":" + t); return "x" === o ? ae(m)[1] : ae(m)[0] } return e(t).length ? "x" === o ? ae(e(t))[1] : ae(e(t))[0] : (l.css(h, t), void u.update.call(null, n[0])) } } }, N = function (t) {
            function o() { return clearTimeout(f[0].autoUpdate), 0 === l.parents("html").length ? void (l = null) : void (f[0].autoUpdate = setTimeout(function () { return c.advanced.updateOnSelectorChange && (s.poll.change.n = i(), s.poll.change.n !== s.poll.change.o) ? (s.poll.change.o = s.poll.change.n, void r(3)) : c.advanced.updateOnContentResize && (s.poll.size.n = l[0].scrollHeight + l[0].scrollWidth + f[0].offsetHeight + l[0].offsetHeight + l[0].offsetWidth, s.poll.size.n !== s.poll.size.o) ? (s.poll.size.o = s.poll.size.n, void r(1)) : !c.advanced.updateOnImageLoad || "auto" === c.advanced.updateOnImageLoad && "y" === c.axis || (s.poll.img.n = f.find("img").length, s.poll.img.n === s.poll.img.o) ? void ((c.advanced.updateOnSelectorChange || c.advanced.updateOnContentResize || c.advanced.updateOnImageLoad) && o()) : (s.poll.img.o = s.poll.img.n, void f.find("img").each(function () { n(this) })) }, c.advanced.autoUpdateTimeout)) } function n(t) {
                function o(e, t) {
                    return function () {
                        return t.apply(e, arguments)
                    }
                } function a() { this.onload = null, e(t).addClass(d[2]), r(2) } if (e(t).hasClass(d[2])) return void r(); var n = new Image; n.onload = o(n, a), n.src = t.src
            } function i() { c.advanced.updateOnSelectorChange === !0 && (c.advanced.updateOnSelectorChange = "*"); var e = 0, t = f.find(c.advanced.updateOnSelectorChange); return c.advanced.updateOnSelectorChange && t.length > 0 && t.each(function () { e += this.offsetHeight + this.offsetWidth }), e } function r(e) { clearTimeout(f[0].autoUpdate), u.update.call(null, l[0], e) } var l = e(this), s = l.data(a), c = s.opt, f = e("#mCSB_" + s.idx + "_container"); return t ? (clearTimeout(f[0].autoUpdate), void $(f[0], "autoUpdate")) : void o()
        }, V = function (e, t, o) { return Math.round(e / t) * t - o }, Q = function (t) { var o = t.data(a), n = e("#mCSB_" + o.idx + "_container,#mCSB_" + o.idx + "_container_wrapper,#mCSB_" + o.idx + "_dragger_vertical,#mCSB_" + o.idx + "_dragger_horizontal"); n.each(function () { Z.call(this) }) }, G = function (t, o, n) { function i(e) { return s && c.callbacks[e] && "function" == typeof c.callbacks[e] } function r() { return [c.callbacks.alwaysTriggerOffsets || w >= S[0] + y, c.callbacks.alwaysTriggerOffsets || -B >= w] } function l() { var e = [h[0].offsetTop, h[0].offsetLeft], o = [x[0].offsetTop, x[0].offsetLeft], a = [h.outerHeight(!1), h.outerWidth(!1)], i = [f.height(), f.width()]; t[0].mcs = { content: h, top: e[0], left: e[1], draggerTop: o[0], draggerLeft: o[1], topPct: Math.round(100 * Math.abs(e[0]) / (Math.abs(a[0]) - i[0])), leftPct: Math.round(100 * Math.abs(e[1]) / (Math.abs(a[1]) - i[1])), direction: n.dir } } var s = t.data(a), c = s.opt, d = { trigger: "internal", dir: "y", scrollEasing: "mcsEaseOut", drag: !1, dur: c.scrollInertia, overwrite: "all", callbacks: !0, onStart: !0, onUpdate: !0, onComplete: !0 }, n = e.extend(d, n), u = [n.dur, n.drag ? 0 : n.dur], f = e("#mCSB_" + s.idx), h = e("#mCSB_" + s.idx + "_container"), m = h.parent(), p = c.callbacks.onTotalScrollOffset ? Y.call(t, c.callbacks.onTotalScrollOffset) : [0, 0], g = c.callbacks.onTotalScrollBackOffset ? Y.call(t, c.callbacks.onTotalScrollBackOffset) : [0, 0]; if (s.trigger = n.trigger, 0 === m.scrollTop() && 0 === m.scrollLeft() || (e(".mCSB_" + s.idx + "_scrollbar").css("visibility", "visible"), m.scrollTop(0).scrollLeft(0)), "_resetY" !== o || s.contentReset.y || (i("onOverflowYNone") && c.callbacks.onOverflowYNone.call(t[0]), s.contentReset.y = 1), "_resetX" !== o || s.contentReset.x || (i("onOverflowXNone") && c.callbacks.onOverflowXNone.call(t[0]), s.contentReset.x = 1), "_resetY" !== o && "_resetX" !== o) { if (!s.contentReset.y && t[0].mcs || !s.overflowed[0] || (i("onOverflowY") && c.callbacks.onOverflowY.call(t[0]), s.contentReset.x = null), !s.contentReset.x && t[0].mcs || !s.overflowed[1] || (i("onOverflowX") && c.callbacks.onOverflowX.call(t[0]), s.contentReset.x = null), c.snapAmount) { var v = c.snapAmount instanceof Array ? "x" === n.dir ? c.snapAmount[1] : c.snapAmount[0] : c.snapAmount; o = V(o, v, c.snapOffset) } switch (n.dir) { case "x": var x = e("#mCSB_" + s.idx + "_dragger_horizontal"), _ = "left", w = h[0].offsetLeft, S = [f.width() - h.outerWidth(!1), x.parent().width() - x.width()], b = [o, 0 === o ? 0 : o / s.scrollRatio.x], y = p[1], B = g[1], T = y > 0 ? y / s.scrollRatio.x : 0, k = B > 0 ? B / s.scrollRatio.x : 0; break; case "y": var x = e("#mCSB_" + s.idx + "_dragger_vertical"), _ = "top", w = h[0].offsetTop, S = [f.height() - h.outerHeight(!1), x.parent().height() - x.height()], b = [o, 0 === o ? 0 : o / s.scrollRatio.y], y = p[0], B = g[0], T = y > 0 ? y / s.scrollRatio.y : 0, k = B > 0 ? B / s.scrollRatio.y : 0 }b[1] < 0 || 0 === b[0] && 0 === b[1] ? b = [0, 0] : b[1] >= S[1] ? b = [S[0], S[1]] : b[0] = -b[0], t[0].mcs || (l(), i("onInit") && c.callbacks.onInit.call(t[0])), clearTimeout(h[0].onCompleteTimeout), J(x[0], _, Math.round(b[1]), u[1], n.scrollEasing), !s.tweenRunning && (0 === w && b[0] >= 0 || w === S[0] && b[0] <= S[0]) || J(h[0], _, Math.round(b[0]), u[0], n.scrollEasing, n.overwrite, { onStart: function () { n.callbacks && n.onStart && !s.tweenRunning && (i("onScrollStart") && (l(), c.callbacks.onScrollStart.call(t[0])), s.tweenRunning = !0, C(x), s.cbOffsets = r()) }, onUpdate: function () { n.callbacks && n.onUpdate && i("whileScrolling") && (l(), c.callbacks.whileScrolling.call(t[0])) }, onComplete: function () { if (n.callbacks && n.onComplete) { "yx" === c.axis && clearTimeout(h[0].onCompleteTimeout); var e = h[0].idleTimer || 0; h[0].onCompleteTimeout = setTimeout(function () { i("onScroll") && (l(), c.callbacks.onScroll.call(t[0])), i("onTotalScroll") && b[1] >= S[1] - T && s.cbOffsets[0] && (l(), c.callbacks.onTotalScroll.call(t[0])), i("onTotalScrollBack") && b[1] <= k && s.cbOffsets[1] && (l(), c.callbacks.onTotalScrollBack.call(t[0])), s.tweenRunning = !1, h[0].idleTimer = 0, C(x, "hide") }, e) } } }) } }, J = function (e, t, o, a, n, i, r) { function l() { S.stop || (x || m.call(), x = K() - v, s(), x >= S.time && (S.time = x > S.time ? x + f - (x - S.time) : x + f - 1, S.time < x + 1 && (S.time = x + 1)), S.time < a ? S.id = h(l) : g.call()) } function s() { a > 0 ? (S.currVal = u(S.time, _, b, a, n), w[t] = Math.round(S.currVal) + "px") : w[t] = o + "px", p.call() } function c() { f = 1e3 / 60, S.time = x + f, h = window.requestAnimationFrame ? window.requestAnimationFrame : function (e) { return s(), setTimeout(e, .01) }, S.id = h(l) } function d() { null != S.id && (window.requestAnimationFrame ? window.cancelAnimationFrame(S.id) : clearTimeout(S.id), S.id = null) } function u(e, t, o, a, n) { switch (n) { case "linear": case "mcsLinear": return o * e / a + t; case "mcsLinearOut": return e /= a, e-- , o * Math.sqrt(1 - e * e) + t; case "easeInOutSmooth": return e /= a / 2, 1 > e ? o / 2 * e * e + t : (e-- , -o / 2 * (e * (e - 2) - 1) + t); case "easeInOutStrong": return e /= a / 2, 1 > e ? o / 2 * Math.pow(2, 10 * (e - 1)) + t : (e-- , o / 2 * (-Math.pow(2, -10 * e) + 2) + t); case "easeInOut": case "mcsEaseInOut": return e /= a / 2, 1 > e ? o / 2 * e * e * e + t : (e -= 2, o / 2 * (e * e * e + 2) + t); case "easeOutSmooth": return e /= a, e-- , -o * (e * e * e * e - 1) + t; case "easeOutStrong": return o * (-Math.pow(2, -10 * e / a) + 1) + t; case "easeOut": case "mcsEaseOut": default: var i = (e /= a) * e, r = i * e; return t + o * (.499999999999997 * r * i + -2.5 * i * i + 5.5 * r + -6.5 * i + 4 * e) } } e._mTween || (e._mTween = { top: {}, left: {} }); var f, h, r = r || {}, m = r.onStart || function () { }, p = r.onUpdate || function () { }, g = r.onComplete || function () { }, v = K(), x = 0, _ = e.offsetTop, w = e.style, S = e._mTween[t]; "left" === t && (_ = e.offsetLeft); var b = o - _; S.stop = 0, "none" !== i && d(), c() }, K = function () { return window.performance && window.performance.now ? window.performance.now() : window.performance && window.performance.webkitNow ? window.performance.webkitNow() : Date.now ? Date.now() : (new Date).getTime() }, Z = function () { var e = this; e._mTween || (e._mTween = { top: {}, left: {} }); for (var t = ["top", "left"], o = 0; o < t.length; o++) { var a = t[o]; e._mTween[a].id && (window.requestAnimationFrame ? window.cancelAnimationFrame(e._mTween[a].id) : clearTimeout(e._mTween[a].id), e._mTween[a].id = null, e._mTween[a].stop = 1) } }, $ = function (e, t) { try { delete e[t] } catch (o) { e[t] = null } }, ee = function (e) { return !(e.which && 1 !== e.which) }, te = function (e) { var t = e.originalEvent.pointerType; return !(t && "touch" !== t && 2 !== t) }, oe = function (e) { return !isNaN(parseFloat(e)) && isFinite(e) }, ae = function (e) { var t = e.parents(".mCSB_container"); return [e.offset().top - t.offset().top, e.offset().left - t.offset().left] }, ne = function () { function e() { var e = ["webkit", "moz", "ms", "o"]; if ("hidden" in document) return "hidden"; for (var t = 0; t < e.length; t++)if (e[t] + "Hidden" in document) return e[t] + "Hidden"; return null } var t = e(); return t ? document[t] : !1 }; e.fn[o] = function (t) { return u[t] ? u[t].apply(this, Array.prototype.slice.call(arguments, 1)) : "object" != typeof t && t ? void e.error("Method " + t + " does not exist") : u.init.apply(this, arguments) }, e[o] = function (t) { return u[t] ? u[t].apply(this, Array.prototype.slice.call(arguments, 1)) : "object" != typeof t && t ? void e.error("Method " + t + " does not exist") : u.init.apply(this, arguments) }, e[o].defaults = i, window[o] = !0, e(window).bind("load", function () { e(n)[o](), e.extend(e.expr[":"], { mcsInView: e.expr[":"].mcsInView || function (t) { var o, a, n = e(t), i = n.parents(".mCSB_container"); if (i.length) return o = i.parent(), a = [i[0].offsetTop, i[0].offsetLeft], a[0] + ae(n)[0] >= 0 && a[0] + ae(n)[0] < o.height() - n.outerHeight(!1) && a[1] + ae(n)[1] >= 0 && a[1] + ae(n)[1] < o.width() - n.outerWidth(!1) }, mcsInSight: e.expr[":"].mcsInSight || function (t, o, a) { var n, i, r, l, s = e(t), c = s.parents(".mCSB_container"), d = "exact" === a[3] ? [[1, 0], [1, 0]] : [[.9, .1], [.6, .4]]; if (c.length) return n = [s.outerHeight(!1), s.outerWidth(!1)], r = [c[0].offsetTop + ae(s)[0], c[0].offsetLeft + ae(s)[1]], i = [c.parent()[0].offsetHeight, c.parent()[0].offsetWidth], l = [n[0] < i[0] ? d[0] : d[1], n[1] < i[1] ? d[0] : d[1]], r[0] - i[0] * l[0][0] < 0 && r[0] + n[0] - i[0] * l[0][1] >= 0 && r[1] - i[1] * l[1][0] < 0 && r[1] + n[1] - i[1] * l[1][1] >= 0 }, mcsOverflow: e.expr[":"].mcsOverflow || function (t) { var o = e(t).data(a); if (o) return o.overflowed[0] || o.overflowed[1] } }) })
    })
});
/* End mCustomScrollbar */;
/*Bengin custom*/
       $(document).ready(function() {
        var owl = $("#owl-demo-c1");
        owl.owlCarousel({items : 1});
        // Custom Navigation Events
        $(".next11").click(function(){
          owl.trigger('owl.next');
        })
        $(".prev11").click(function(){
          owl.trigger('owl.prev');
        })
      });
       
      $(document).ready(function() {
        var owl = $("#owl-demo-c2");
        owl.owlCarousel({items : 1});
        // Custom Navigation Events
        $(".next22").click(function(){
          owl.trigger('owl.next');
        })
        $(".prev22").click(function(){
          owl.trigger('owl.prev');
        })
      });

       $(document).ready(function() {
        var owl = $("#owl-demo-c3");
        owl.owlCarousel({items : 4});
        // Custom Navigation Events
        $(".next33").click(function(){
          owl.trigger('owl.next');
        })
        $(".prev33").click(function(){
          owl.trigger('owl.prev');
        })
      });
/*End custom*/

/*Bengin carousel*/
if (typeof Object.create !== "function") {
    Object.create = function (obj) {
        function F() {}
        F.prototype = obj;
        return new F();
    };
}
(function ($, window, document) {

    var Carousel = {
        init : function (options, el) {
            var base = this;

            base.$elem = $(el);
            base.options = $.extend({}, $.fn.owlCarousel.options, base.$elem.data(), options);

            base.userOptions = options;
            base.loadContent();
        },

        loadContent : function () {
            var base = this, url;

            function getData(data) {
                var i, content = "";
                if (typeof base.options.jsonSuccess === "function") {
                    base.options.jsonSuccess.apply(this, [data]);
                } else {
                    for (i in data.owl) {
                        if (data.owl.hasOwnProperty(i)) {
                            content += data.owl[i].item;
                        }
                    }
                    base.$elem.html(content);
                }
                base.logIn();
            }

            if (typeof base.options.beforeInit === "function") {
                base.options.beforeInit.apply(this, [base.$elem]);
            }

            if (typeof base.options.jsonPath === "string") {
                url = base.options.jsonPath;
                $.getJSON(url, getData);
            } else {
                base.logIn();
            }
        },

        logIn : function () {
            var base = this;

            base.$elem.data("owl-originalStyles", base.$elem.attr("style"));
            base.$elem.data("owl-originalClasses", base.$elem.attr("class"));

            base.$elem.css({opacity: 0});
            base.orignalItems = base.options.items;
            base.checkBrowser();
            base.wrapperWidth = 0;
            base.checkVisible = null;
            base.setVars();
        },

        setVars : function () {
            var base = this;
            if (base.$elem.children().length === 0) {return false; }
            base.baseClass();
            base.eventTypes();
            base.$userItems = base.$elem.children();
            base.itemsAmount = base.$userItems.length;
            base.wrapItems();
            base.$owlItems = base.$elem.find(".owl-item");
            base.$owlWrapper = base.$elem.find(".owl-wrapper");
            base.playDirection = "next";
            base.prevItem = 0;
            base.prevArr = [0];
            base.currentItem = 0;
            base.customEvents();
            base.onStartup();
        },

        onStartup : function () {
            var base = this;
            base.updateItems();
            base.calculateAll();
            base.buildControls();
            base.updateControls();
            base.response();
            base.moveEvents();
            base.stopOnHover();
            base.owlStatus();

            if (base.options.transitionStyle !== false) {
                base.transitionTypes(base.options.transitionStyle);
            }
            if (base.options.autoPlay === true) {
                base.options.autoPlay = 5000;
            }
            base.play();

            base.$elem.find(".owl-wrapper").css("display", "block");

            if (!base.$elem.is(":visible")) {
                base.watchVisibility();
            } else {
                base.$elem.css("opacity", 1);
            }
            base.onstartup = false;
            base.eachMoveUpdate();
            if (typeof base.options.afterInit === "function") {
                base.options.afterInit.apply(this, [base.$elem]);
            }
        },

        eachMoveUpdate : function () {
            var base = this;

            if (base.options.lazyLoad === true) {
                base.lazyLoad();
            }
            if (base.options.autoHeight === true) {
                base.autoHeight();
            }
            base.onVisibleItems();

            if (typeof base.options.afterAction === "function") {
                base.options.afterAction.apply(this, [base.$elem]);
            }
        },

        updateVars : function () {
            var base = this;
            if (typeof base.options.beforeUpdate === "function") {
                base.options.beforeUpdate.apply(this, [base.$elem]);
            }
            base.watchVisibility();
            base.updateItems();
            base.calculateAll();
            base.updatePosition();
            base.updateControls();
            base.eachMoveUpdate();
            if (typeof base.options.afterUpdate === "function") {
                base.options.afterUpdate.apply(this, [base.$elem]);
            }
        },

        reload : function () {
            var base = this;
            window.setTimeout(function () {
                base.updateVars();
            }, 0);
        },

        watchVisibility : function () {
            var base = this;

            if (base.$elem.is(":visible") === false) {
                base.$elem.css({opacity: 0});
                window.clearInterval(base.autoPlayInterval);
                window.clearInterval(base.checkVisible);
            } else {
                return false;
            }
            base.checkVisible = window.setInterval(function () {
                if (base.$elem.is(":visible")) {
                    base.reload();
                    base.$elem.animate({opacity: 1}, 200);
                    window.clearInterval(base.checkVisible);
                }
            }, 500);
        },

        wrapItems : function () {
            var base = this;
            base.$userItems.wrapAll("<div class=\"owl-wrapper\">").wrap("<div class=\"owl-item\"></div>");
            base.$elem.find(".owl-wrapper").wrap("<div class=\"owl-wrapper-outer\">");
            base.wrapperOuter = base.$elem.find(".owl-wrapper-outer");
            base.$elem.css("display", "block");
        },

        baseClass : function () {
            var base = this,
                hasBaseClass = base.$elem.hasClass(base.options.baseClass),
                hasThemeClass = base.$elem.hasClass(base.options.theme);

            if (!hasBaseClass) {
                base.$elem.addClass(base.options.baseClass);
            }

            if (!hasThemeClass) {
                base.$elem.addClass(base.options.theme);
            }
        },

        updateItems : function () {
            var base = this, width, i;

            if (base.options.responsive === false) {
                return false;
            }
            if (base.options.singleItem === true) {
                base.options.items = base.orignalItems = 1;
                base.options.itemsCustom = false;
                base.options.itemsDesktop = false;
                base.options.itemsDesktopSmall = false;
                base.options.itemsTablet = false;
                base.options.itemsTabletSmall = false;
                base.options.itemsMobile = false;
                return false;
            }

            width = $(base.options.responsiveBaseWidth).width();

            if (width > (base.options.itemsDesktop[0] || base.orignalItems)) {
                base.options.items = base.orignalItems;
            }
            if (base.options.itemsCustom !== false) {
                //Reorder array by screen size
                base.options.itemsCustom.sort(function (a, b) {return a[0] - b[0]; });

                for (i = 0; i < base.options.itemsCustom.length; i += 1) {
                    if (base.options.itemsCustom[i][0] <= width) {
                        base.options.items = base.options.itemsCustom[i][1];
                    }
                }

            } else {

                if (width <= base.options.itemsDesktop[0] && base.options.itemsDesktop !== false) {
                    base.options.items = base.options.itemsDesktop[1];
                }

                if (width <= base.options.itemsDesktopSmall[0] && base.options.itemsDesktopSmall !== false) {
                    base.options.items = base.options.itemsDesktopSmall[1];
                }

                if (width <= base.options.itemsTablet[0] && base.options.itemsTablet !== false) {
                    base.options.items = base.options.itemsTablet[1];
                }

                if (width <= base.options.itemsTabletSmall[0] && base.options.itemsTabletSmall !== false) {
                    base.options.items = base.options.itemsTabletSmall[1];
                }

                if (width <= base.options.itemsMobile[0] && base.options.itemsMobile !== false) {
                    base.options.items = base.options.itemsMobile[1];
                }
            }

            //if number of items is less than declared
            if (base.options.items > base.itemsAmount && base.options.itemsScaleUp === true) {
                base.options.items = base.itemsAmount;
            }
        },

        response : function () {
            var base = this,
                smallDelay,
                lastWindowWidth;

            if (base.options.responsive !== true) {
                return false;
            }
            lastWindowWidth = $(window).width();

            base.resizer = function () {
                if ($(window).width() !== lastWindowWidth) {
                    if (base.options.autoPlay !== false) {
                        window.clearInterval(base.autoPlayInterval);
                    }
                    window.clearTimeout(smallDelay);
                    smallDelay = window.setTimeout(function () {
                        lastWindowWidth = $(window).width();
                        base.updateVars();
                    }, base.options.responsiveRefreshRate);
                }
            };
            $(window).resize(base.resizer);
        },

        updatePosition : function () {
            var base = this;
            base.jumpTo(base.currentItem);
            if (base.options.autoPlay !== false) {
                base.checkAp();
            }
        },

        appendItemsSizes : function () {
            var base = this,
                roundPages = 0,
                lastItem = base.itemsAmount - base.options.items;

            base.$owlItems.each(function (index) {
                var $this = $(this);
                $this
                    .css({"width": base.itemWidth})
                    .data("owl-item", Number(index));

                if (index % base.options.items === 0 || index === lastItem) {
                    if (!(index > lastItem)) {
                        roundPages += 1;
                    }
                }
                $this.data("owl-roundPages", roundPages);
            });
        },

        appendWrapperSizes : function () {
            var base = this,
                width = base.$owlItems.length * base.itemWidth;

            base.$owlWrapper.css({
                "width": width * 2,
                "left": 0
            });
            base.appendItemsSizes();
        },

        calculateAll : function () {
            var base = this;
            base.calculateWidth();
            base.appendWrapperSizes();
            base.loops();
            base.max();
        },

        calculateWidth : function () {
            var base = this;
            base.itemWidth = Math.round(base.$elem.width() / base.options.items);
        },

        max : function () {
            var base = this,
                maximum = ((base.itemsAmount * base.itemWidth) - base.options.items * base.itemWidth) * -1;
            if (base.options.items > base.itemsAmount) {
                base.maximumItem = 0;
                maximum = 0;
                base.maximumPixels = 0;
            } else {
                base.maximumItem = base.itemsAmount - base.options.items;
                base.maximumPixels = maximum;
            }
            return maximum;
        },

        min : function () {
            return 0;
        },

        loops : function () {
            var base = this,
                prev = 0,
                elWidth = 0,
                i,
                item,
                roundPageNum;

            base.positionsInArray = [0];
            base.pagesInArray = [];

            for (i = 0; i < base.itemsAmount; i += 1) {
                elWidth += base.itemWidth;
                base.positionsInArray.push(-elWidth);

                if (base.options.scrollPerPage === true) {
                    item = $(base.$owlItems[i]);
                    roundPageNum = item.data("owl-roundPages");
                    if (roundPageNum !== prev) {
                        base.pagesInArray[prev] = base.positionsInArray[i];
                        prev = roundPageNum;
                    }
                }
            }
        },

        buildControls : function () {
            var base = this;
            if (base.options.navigation === true || base.options.pagination === true) {
                base.owlControls = $("<div class=\"owl-controls\"/>").toggleClass("clickable", !base.browser.isTouch).appendTo(base.$elem);
            }
            if (base.options.pagination === true) {
                base.buildPagination();
            }
            if (base.options.navigation === true) {
                base.buildButtons();
            }
        },

        buildButtons : function () {
            var base = this,
                buttonsWrapper = $("<div class=\"owl-buttons\"/>");
            base.owlControls.append(buttonsWrapper);

            base.buttonPrev = $("<div/>", {
                "class" : "owl-prev",
                "html" : base.options.navigationText[0] || ""
            });

            base.buttonNext = $("<div/>", {
                "class" : "owl-next",
                "html" : base.options.navigationText[1] || ""
            });

            buttonsWrapper
                .append(base.buttonPrev)
                .append(base.buttonNext);

            buttonsWrapper.on("touchstart.owlControls mousedown.owlControls", "div[class^=\"owl\"]", function (event) {
                event.preventDefault();
            });

            buttonsWrapper.on("touchend.owlControls mouseup.owlControls", "div[class^=\"owl\"]", function (event) {
                event.preventDefault();
                if ($(this).hasClass("owl-next")) {
                    base.next();
                } else {
                    base.prev();
                }
            });
        },

        buildPagination : function () {
            var base = this;

            base.paginationWrapper = $("<div class=\"owl-pagination\"/>");
            base.owlControls.append(base.paginationWrapper);

            base.paginationWrapper.on("touchend.owlControls mouseup.owlControls", ".owl-page", function (event) {
                event.preventDefault();
                if (Number($(this).data("owl-page")) !== base.currentItem) {
                    base.goTo(Number($(this).data("owl-page")), true);
                }
            });
        },

        updatePagination : function () {
            var base = this,
                counter,
                lastPage,
                lastItem,
                i,
                paginationButton,
                paginationButtonInner;

            if (base.options.pagination === false) {
                return false;
            }

            base.paginationWrapper.html("");

            counter = 0;
            lastPage = base.itemsAmount - base.itemsAmount % base.options.items;

            for (i = 0; i < base.itemsAmount; i += 1) {
                if (i % base.options.items === 0) {
                    counter += 1;
                    if (lastPage === i) {
                        lastItem = base.itemsAmount - base.options.items;
                    }
                    paginationButton = $("<div/>", {
                        "class" : "owl-page"
                    });
                    paginationButtonInner = $("<span></span>", {
                        "text": base.options.paginationNumbers === true ? counter : "",
                        "class": base.options.paginationNumbers === true ? "owl-numbers" : ""
                    });
                    paginationButton.append(paginationButtonInner);

                    paginationButton.data("owl-page", lastPage === i ? lastItem : i);
                    paginationButton.data("owl-roundPages", counter);

                    base.paginationWrapper.append(paginationButton);
                }
            }
            base.checkPagination();
        },
        checkPagination : function () {
            var base = this;
            if (base.options.pagination === false) {
                return false;
            }
            base.paginationWrapper.find(".owl-page").each(function () {
                if ($(this).data("owl-roundPages") === $(base.$owlItems[base.currentItem]).data("owl-roundPages")) {
                    base.paginationWrapper
                        .find(".owl-page")
                        .removeClass("active");
                    $(this).addClass("active");
                }
            });
        },

        checkNavigation : function () {
            var base = this;

            if (base.options.navigation === false) {
                return false;
            }
            if (base.options.rewindNav === false) {
                if (base.currentItem === 0 && base.maximumItem === 0) {
                    base.buttonPrev.addClass("disabled");
                    base.buttonNext.addClass("disabled");
                } else if (base.currentItem === 0 && base.maximumItem !== 0) {
                    base.buttonPrev.addClass("disabled");
                    base.buttonNext.removeClass("disabled");
                } else if (base.currentItem === base.maximumItem) {
                    base.buttonPrev.removeClass("disabled");
                    base.buttonNext.addClass("disabled");
                } else if (base.currentItem !== 0 && base.currentItem !== base.maximumItem) {
                    base.buttonPrev.removeClass("disabled");
                    base.buttonNext.removeClass("disabled");
                }
            }
        },

        updateControls : function () {
            var base = this;
            base.updatePagination();
            base.checkNavigation();
            if (base.owlControls) {
                if (base.options.items >= base.itemsAmount) {
                    base.owlControls.hide();
                } else {
                    base.owlControls.show();
                }
            }
        },

        destroyControls : function () {
            var base = this;
            if (base.owlControls) {
                base.owlControls.remove();
            }
        },

        next : function (speed) {
            var base = this;

            if (base.isTransition) {
                return false;
            }

            base.currentItem += base.options.scrollPerPage === true ? base.options.items : 1;
            if (base.currentItem > base.maximumItem + (base.options.scrollPerPage === true ? (base.options.items - 1) : 0)) {
                if (base.options.rewindNav === true) {
                    base.currentItem = 0;
                    speed = "rewind";
                } else {
                    base.currentItem = base.maximumItem;
                    return false;
                }
            }
            base.goTo(base.currentItem, speed);
        },

        prev : function (speed) {
            var base = this;

            if (base.isTransition) {
                return false;
            }

            if (base.options.scrollPerPage === true && base.currentItem > 0 && base.currentItem < base.options.items) {
                base.currentItem = 0;
            } else {
                base.currentItem -= base.options.scrollPerPage === true ? base.options.items : 1;
            }
            if (base.currentItem < 0) {
                if (base.options.rewindNav === true) {
                    base.currentItem = base.maximumItem;
                    speed = "rewind";
                } else {
                    base.currentItem = 0;
                    return false;
                }
            }
            base.goTo(base.currentItem, speed);
        },

        goTo : function (position, speed, drag) {
            var base = this,
                goToPixel;

            if (base.isTransition) {
                return false;
            }
            if (typeof base.options.beforeMove === "function") {
                base.options.beforeMove.apply(this, [base.$elem]);
            }
            if (position >= base.maximumItem) {
                position = base.maximumItem;
            } else if (position <= 0) {
                position = 0;
            }

            base.currentItem = base.owl.currentItem = position;
            if (base.options.transitionStyle !== false && drag !== "drag" && base.options.items === 1 && base.browser.support3d === true) {
                base.swapSpeed(0);
                if (base.browser.support3d === true) {
                    base.transition3d(base.positionsInArray[position]);
                } else {
                    base.css2slide(base.positionsInArray[position], 1);
                }
                base.afterGo();
                base.singleItemTransition();
                return false;
            }
            goToPixel = base.positionsInArray[position];

            if (base.browser.support3d === true) {
                base.isCss3Finish = false;

                if (speed === true) {
                    base.swapSpeed("paginationSpeed");
                    window.setTimeout(function () {
                        base.isCss3Finish = true;
                    }, base.options.paginationSpeed);

                } else if (speed === "rewind") {
                    base.swapSpeed(base.options.rewindSpeed);
                    window.setTimeout(function () {
                        base.isCss3Finish = true;
                    }, base.options.rewindSpeed);

                } else {
                    base.swapSpeed("slideSpeed");
                    window.setTimeout(function () {
                        base.isCss3Finish = true;
                    }, base.options.slideSpeed);
                }
                base.transition3d(goToPixel);
            } else {
                if (speed === true) {
                    base.css2slide(goToPixel, base.options.paginationSpeed);
                } else if (speed === "rewind") {
                    base.css2slide(goToPixel, base.options.rewindSpeed);
                } else {
                    base.css2slide(goToPixel, base.options.slideSpeed);
                }
            }
            base.afterGo();
        },

        jumpTo : function (position) {
            var base = this;
            if (typeof base.options.beforeMove === "function") {
                base.options.beforeMove.apply(this, [base.$elem]);
            }
            if (position >= base.maximumItem || position === -1) {
                position = base.maximumItem;
            } else if (position <= 0) {
                position = 0;
            }
            base.swapSpeed(0);
            if (base.browser.support3d === true) {
                base.transition3d(base.positionsInArray[position]);
            } else {
                base.css2slide(base.positionsInArray[position], 1);
            }
            base.currentItem = base.owl.currentItem = position;
            base.afterGo();
        },

        afterGo : function () {
            var base = this;

            base.prevArr.push(base.currentItem);
            base.prevItem = base.owl.prevItem = base.prevArr[base.prevArr.length - 2];
            base.prevArr.shift(0);

            if (base.prevItem !== base.currentItem) {
                base.checkPagination();
                base.checkNavigation();
                base.eachMoveUpdate();

                if (base.options.autoPlay !== false) {
                    base.checkAp();
                }
            }
            if (typeof base.options.afterMove === "function" && base.prevItem !== base.currentItem) {
                base.options.afterMove.apply(this, [base.$elem]);
            }
        },

        stop : function () {
            var base = this;
            base.apStatus = "stop";
            window.clearInterval(base.autoPlayInterval);
        },

        checkAp : function () {
            var base = this;
            if (base.apStatus !== "stop") {
                base.play();
            }
        },

        play : function () {
            var base = this;
            base.apStatus = "play";
            if (base.options.autoPlay === false) {
                return false;
            }
            window.clearInterval(base.autoPlayInterval);
            base.autoPlayInterval = window.setInterval(function () {
                base.next(true);
            }, base.options.autoPlay);
        },

        swapSpeed : function (action) {
            var base = this;
            if (action === "slideSpeed") {
                base.$owlWrapper.css(base.addCssSpeed(base.options.slideSpeed));
            } else if (action === "paginationSpeed") {
                base.$owlWrapper.css(base.addCssSpeed(base.options.paginationSpeed));
            } else if (typeof action !== "string") {
                base.$owlWrapper.css(base.addCssSpeed(action));
            }
        },

        addCssSpeed : function (speed) {
            return {
                "-webkit-transition": "all " + speed + "ms ease",
                "-moz-transition": "all " + speed + "ms ease",
                "-o-transition": "all " + speed + "ms ease",
                "transition": "all " + speed + "ms ease"
            };
        },

        removeTransition : function () {
            return {
                "-webkit-transition": "",
                "-moz-transition": "",
                "-o-transition": "",
                "transition": ""
            };
        },

        doTranslate : function (pixels) {
            return {
                "-webkit-transform": "translate3d(" + pixels + "px, 0px, 0px)",
                "-moz-transform": "translate3d(" + pixels + "px, 0px, 0px)",
                "-o-transform": "translate3d(" + pixels + "px, 0px, 0px)",
                "-ms-transform": "translate3d(" + pixels + "px, 0px, 0px)",
                "transform": "translate3d(" + pixels + "px, 0px,0px)"
            };
        },

        transition3d : function (value) {
            var base = this;
            base.$owlWrapper.css(base.doTranslate(value));
        },

        css2move : function (value) {
            var base = this;
            base.$owlWrapper.css({"left" : value});
        },

        css2slide : function (value, speed) {
            var base = this;

            base.isCssFinish = false;
            base.$owlWrapper.stop(true, true).animate({
                "left" : value
            }, {
                duration : speed || base.options.slideSpeed,
                complete : function () {
                    base.isCssFinish = true;
                }
            });
        },

        checkBrowser : function () {
            var base = this,
                translate3D = "translate3d(0px, 0px, 0px)",
                tempElem = document.createElement("div"),
                regex,
                asSupport,
                support3d,
                isTouch;

            tempElem.style.cssText = "  -moz-transform:" + translate3D +
                                  "; -ms-transform:"     + translate3D +
                                  "; -o-transform:"      + translate3D +
                                  "; -webkit-transform:" + translate3D +
                                  "; transform:"         + translate3D;
            regex = /translate3d\(0px, 0px, 0px\)/g;
            asSupport = tempElem.style.cssText.match(regex);
            support3d = (asSupport !== null && asSupport.length === 1);

            isTouch = "ontouchstart" in window || window.navigator.msMaxTouchPoints;

            base.browser = {
                "support3d" : support3d,
                "isTouch" : isTouch
            };
        },

        moveEvents : function () {
            var base = this;
            if (base.options.mouseDrag !== false || base.options.touchDrag !== false) {
                base.gestures();
                base.disabledEvents();
            }
        },

        eventTypes : function () {
            var base = this,
                types = ["s", "e", "x"];

            base.ev_types = {};

            if (base.options.mouseDrag === true && base.options.touchDrag === true) {
                types = [
                    "touchstart.owl mousedown.owl",
                    "touchmove.owl mousemove.owl",
                    "touchend.owl touchcancel.owl mouseup.owl"
                ];
            } else if (base.options.mouseDrag === false && base.options.touchDrag === true) {
                types = [
                    "touchstart.owl",
                    "touchmove.owl",
                    "touchend.owl touchcancel.owl"
                ];
            } else if (base.options.mouseDrag === true && base.options.touchDrag === false) {
                types = [
                    "mousedown.owl",
                    "mousemove.owl",
                    "mouseup.owl"
                ];
            }

            base.ev_types.start = types[0];
            base.ev_types.move = types[1];
            base.ev_types.end = types[2];
        },

        disabledEvents :  function () {
            var base = this;
            base.$elem.on("dragstart.owl", function (event) { event.preventDefault(); });
            base.$elem.on("mousedown.disableTextSelect", function (e) {
                return $(e.target).is('input, textarea, select, option');
            });
        },

        gestures : function () {
            /*jslint unparam: true*/
            var base = this,
                locals = {
                    offsetX : 0,
                    offsetY : 0,
                    baseElWidth : 0,
                    relativePos : 0,
                    position: null,
                    minSwipe : null,
                    maxSwipe: null,
                    sliding : null,
                    dargging: null,
                    targetElement : null
                };

            base.isCssFinish = true;

            function getTouches(event) {
                if (event.touches !== undefined) {
                    return {
                        x : event.touches[0].pageX,
                        y : event.touches[0].pageY
                    };
                }

                if (event.touches === undefined) {
                    if (event.pageX !== undefined) {
                        return {
                            x : event.pageX,
                            y : event.pageY
                        };
                    }
                    if (event.pageX === undefined) {
                        return {
                            x : event.clientX,
                            y : event.clientY
                        };
                    }
                }
            }

            function swapEvents(type) {
                if (type === "on") {
                    $(document).on(base.ev_types.move, dragMove);
                    $(document).on(base.ev_types.end, dragEnd);
                } else if (type === "off") {
                    $(document).off(base.ev_types.move);
                    $(document).off(base.ev_types.end);
                }
            }

            function dragStart(event) {
                var ev = event.originalEvent || event || window.event,
                    position;

                if (ev.which === 3) {
                    return false;
                }
                if (base.itemsAmount <= base.options.items) {
                    return;
                }
                if (base.isCssFinish === false && !base.options.dragBeforeAnimFinish) {
                    return false;
                }
                if (base.isCss3Finish === false && !base.options.dragBeforeAnimFinish) {
                    return false;
                }

                if (base.options.autoPlay !== false) {
                    window.clearInterval(base.autoPlayInterval);
                }

                if (base.browser.isTouch !== true && !base.$owlWrapper.hasClass("grabbing")) {
                    base.$owlWrapper.addClass("grabbing");
                }

                base.newPosX = 0;
                base.newRelativeX = 0;

                $(this).css(base.removeTransition());

                position = $(this).position();
                locals.relativePos = position.left;

                locals.offsetX = getTouches(ev).x - position.left;
                locals.offsetY = getTouches(ev).y - position.top;

                swapEvents("on");

                locals.sliding = false;
                locals.targetElement = ev.target || ev.srcElement;
            }

            function dragMove(event) {
                var ev = event.originalEvent || event || window.event,
                    minSwipe,
                    maxSwipe;

                base.newPosX = getTouches(ev).x - locals.offsetX;
                base.newPosY = getTouches(ev).y - locals.offsetY;
                base.newRelativeX = base.newPosX - locals.relativePos;

                if (typeof base.options.startDragging === "function" && locals.dragging !== true && base.newRelativeX !== 0) {
                    locals.dragging = true;
                    base.options.startDragging.apply(base, [base.$elem]);
                }

                if ((base.newRelativeX > 8 || base.newRelativeX < -8) && (base.browser.isTouch === true)) {
                    if (ev.preventDefault !== undefined) {
                        ev.preventDefault();
                    } else {
                        ev.returnValue = false;
                    }
                    locals.sliding = true;
                }

                if ((base.newPosY > 10 || base.newPosY < -10) && locals.sliding === false) {
                    $(document).off("touchmove.owl");
                }

                minSwipe = function () {
                    return base.newRelativeX / 5;
                };

                maxSwipe = function () {
                    return base.maximumPixels + base.newRelativeX / 5;
                };

                base.newPosX = Math.max(Math.min(base.newPosX, minSwipe()), maxSwipe());
                if (base.browser.support3d === true) {
                    base.transition3d(base.newPosX);
                } else {
                    base.css2move(base.newPosX);
                }
            }

            function dragEnd(event) {
                var ev = event.originalEvent || event || window.event,
                    newPosition,
                    handlers,
                    owlStopEvent;

                ev.target = ev.target || ev.srcElement;

                locals.dragging = false;

                if (base.browser.isTouch !== true) {
                    base.$owlWrapper.removeClass("grabbing");
                }

                if (base.newRelativeX < 0) {
                    base.dragDirection = base.owl.dragDirection = "left";
                } else {
                    base.dragDirection = base.owl.dragDirection = "right";
                }

                if (base.newRelativeX !== 0) {
                    newPosition = base.getNewPosition();
                    base.goTo(newPosition, false, "drag");
                    if (locals.targetElement === ev.target && base.browser.isTouch !== true) {
                        $(ev.target).on("click.disable", function (ev) {
                            ev.stopImmediatePropagation();
                            ev.stopPropagation();
                            ev.preventDefault();
                            $(ev.target).off("click.disable");
                        });
                        handlers = $._data(ev.target, "events").click;
                        owlStopEvent = handlers.pop();
                        handlers.splice(0, 0, owlStopEvent);
                    }
                }
                swapEvents("off");
            }
            base.$elem.on(base.ev_types.start, ".owl-wrapper", dragStart);
        },

        getNewPosition : function () {
            var base = this,
                newPosition = base.closestItem();

            if (newPosition > base.maximumItem) {
                base.currentItem = base.maximumItem;
                newPosition  = base.maximumItem;
            } else if (base.newPosX >= 0) {
                newPosition = 0;
                base.currentItem = 0;
            }
            return newPosition;
        },
        closestItem : function () {
            var base = this,
                array = base.options.scrollPerPage === true ? base.pagesInArray : base.positionsInArray,
                goal = base.newPosX,
                closest = null;

            $.each(array, function (i, v) {
                if (goal - (base.itemWidth / 20) > array[i + 1] && goal - (base.itemWidth / 20) < v && base.moveDirection() === "left") {
                    closest = v;
                    if (base.options.scrollPerPage === true) {
                        base.currentItem = $.inArray(closest, base.positionsInArray);
                    } else {
                        base.currentItem = i;
                    }
                } else if (goal + (base.itemWidth / 20) < v && goal + (base.itemWidth / 20) > (array[i + 1] || array[i] - base.itemWidth) && base.moveDirection() === "right") {
                    if (base.options.scrollPerPage === true) {
                        closest = array[i + 1] || array[array.length - 1];
                        base.currentItem = $.inArray(closest, base.positionsInArray);
                    } else {
                        closest = array[i + 1];
                        base.currentItem = i + 1;
                    }
                }
            });
            return base.currentItem;
        },

        moveDirection : function () {
            var base = this,
                direction;
            if (base.newRelativeX < 0) {
                direction = "right";
                base.playDirection = "next";
            } else {
                direction = "left";
                base.playDirection = "prev";
            }
            return direction;
        },

        customEvents : function () {
            /*jslint unparam: true*/
            var base = this;
            base.$elem.on("owl.next", function () {
                base.next();
            });
            base.$elem.on("owl.prev", function () {
                base.prev();
            });
            base.$elem.on("owl.play", function (event, speed) {
                base.options.autoPlay = speed;
                base.play();
                base.hoverStatus = "play";
            });
            base.$elem.on("owl.stop", function () {
                base.stop();
                base.hoverStatus = "stop";
            });
            base.$elem.on("owl.goTo", function (event, item) {
                base.goTo(item);
            });
            base.$elem.on("owl.jumpTo", function (event, item) {
                base.jumpTo(item);
            });
        },

        stopOnHover : function () {
            var base = this;
            if (base.options.stopOnHover === true && base.browser.isTouch !== true && base.options.autoPlay !== false) {
                base.$elem.on("mouseover", function () {
                    base.stop();
                });
                base.$elem.on("mouseout", function () {
                    if (base.hoverStatus !== "stop") {
                        base.play();
                    }
                });
            }
        },

        lazyLoad : function () {
            var base = this,
                i,
                $item,
                itemNumber,
                $lazyImg,
                follow;

            if (base.options.lazyLoad === false) {
                return false;
            }
            for (i = 0; i < base.itemsAmount; i += 1) {
                $item = $(base.$owlItems[i]);

                if ($item.data("owl-loaded") === "loaded") {
                    continue;
                }

                itemNumber = $item.data("owl-item");
                $lazyImg = $item.find(".lazyOwl");

                if (typeof $lazyImg.data("src") !== "string") {
                    $item.data("owl-loaded", "loaded");
                    continue;
                }
                if ($item.data("owl-loaded") === undefined) {
                    $lazyImg.hide();
                    $item.addClass("loading").data("owl-loaded", "checked");
                }
                if (base.options.lazyFollow === true) {
                    follow = itemNumber >= base.currentItem;
                } else {
                    follow = true;
                }
                if (follow && itemNumber < base.currentItem + base.options.items && $lazyImg.length) {
                    base.lazyPreload($item, $lazyImg);
                }
            }
        },

        lazyPreload : function ($item, $lazyImg) {
            var base = this,
                iterations = 0,
                isBackgroundImg;

            if ($lazyImg.prop("tagName") === "DIV") {
                $lazyImg.css("background-image", "url(" + $lazyImg.data("src") + ")");
                isBackgroundImg = true;
            } else {
                $lazyImg[0].src = $lazyImg.data("src");
            }

            function showImage() {
                $item.data("owl-loaded", "loaded").removeClass("loading");
                $lazyImg.removeAttr("data-src");
                if (base.options.lazyEffect === "fade") {
                    $lazyImg.fadeIn(400);
                } else {
                    $lazyImg.show();
                }
                if (typeof base.options.afterLazyLoad === "function") {
                    base.options.afterLazyLoad.apply(this, [base.$elem]);
                }
            }

            function checkLazyImage() {
                iterations += 1;
                if (base.completeImg($lazyImg.get(0)) || isBackgroundImg === true) {
                    showImage();
                } else if (iterations <= 100) {//if image loads in less than 10 seconds 
                    window.setTimeout(checkLazyImage, 100);
                } else {
                    showImage();
                }
            }

            checkLazyImage();
        },

        autoHeight : function () {
            var base = this,
                $currentimg = $(base.$owlItems[base.currentItem]).find("img"),
                iterations;

            function addHeight() {
                var $currentItem = $(base.$owlItems[base.currentItem]).height();
                base.wrapperOuter.css("height", $currentItem + "px");
                if (!base.wrapperOuter.hasClass("autoHeight")) {
                    window.setTimeout(function () {
                        base.wrapperOuter.addClass("autoHeight");
                    }, 0);
                }
            }

            function checkImage() {
                iterations += 1;
                if (base.completeImg($currentimg.get(0))) {
                    addHeight();
                } else if (iterations <= 100) { //if image loads in less than 10 seconds 
                    window.setTimeout(checkImage, 100);
                } else {
                    base.wrapperOuter.css("height", ""); //Else remove height attribute
                }
            }

            if ($currentimg.get(0) !== undefined) {
                iterations = 0;
                checkImage();
            } else {
                addHeight();
            }
        },

        completeImg : function (img) {
            var naturalWidthType;

            if (!img.complete) {
                return false;
            }
            naturalWidthType = typeof img.naturalWidth;
            if (naturalWidthType !== "undefined" && img.naturalWidth === 0) {
                return false;
            }
            return true;
        },

        onVisibleItems : function () {
            var base = this,
                i;

            if (base.options.addClassActive === true) {
                base.$owlItems.removeClass("active");
            }
            base.visibleItems = [];
            for (i = base.currentItem; i < base.currentItem + base.options.items; i += 1) {
                base.visibleItems.push(i);

                if (base.options.addClassActive === true) {
                    $(base.$owlItems[i]).addClass("active");
                }
            }
            base.owl.visibleItems = base.visibleItems;
        },

        transitionTypes : function (className) {
            var base = this;
            //Currently available: "fade", "backSlide", "goDown", "fadeUp"
            base.outClass = "owl-" + className + "-out";
            base.inClass = "owl-" + className + "-in";
        },

        singleItemTransition : function () {
            var base = this,
                outClass = base.outClass,
                inClass = base.inClass,
                $currentItem = base.$owlItems.eq(base.currentItem),
                $prevItem = base.$owlItems.eq(base.prevItem),
                prevPos = Math.abs(base.positionsInArray[base.currentItem]) + base.positionsInArray[base.prevItem],
                origin = Math.abs(base.positionsInArray[base.currentItem]) + base.itemWidth / 2,
                animEnd = 'webkitAnimationEnd oAnimationEnd MSAnimationEnd animationend';

            base.isTransition = true;

            base.$owlWrapper
                .addClass('owl-origin')
                .css({
                    "-webkit-transform-origin" : origin + "px",
                    "-moz-perspective-origin" : origin + "px",
                    "perspective-origin" : origin + "px"
                });
            function transStyles(prevPos) {
                return {
                    "position" : "relative",
                    "left" : prevPos + "px"
                };
            }

            $prevItem
                .css(transStyles(prevPos, 10))
                .addClass(outClass)
                .on(animEnd, function () {
                    base.endPrev = true;
                    $prevItem.off(animEnd);
                    base.clearTransStyle($prevItem, outClass);
                });

            $currentItem
                .addClass(inClass)
                .on(animEnd, function () {
                    base.endCurrent = true;
                    $currentItem.off(animEnd);
                    base.clearTransStyle($currentItem, inClass);
                });
        },

        clearTransStyle : function (item, classToRemove) {
            var base = this;
            item.css({
                "position" : "",
                "left" : ""
            }).removeClass(classToRemove);

            if (base.endPrev && base.endCurrent) {
                base.$owlWrapper.removeClass('owl-origin');
                base.endPrev = false;
                base.endCurrent = false;
                base.isTransition = false;
            }
        },

        owlStatus : function () {
            var base = this;
            base.owl = {
                "userOptions"   : base.userOptions,
                "baseElement"   : base.$elem,
                "userItems"     : base.$userItems,
                "owlItems"      : base.$owlItems,
                "currentItem"   : base.currentItem,
                "prevItem"      : base.prevItem,
                "visibleItems"  : base.visibleItems,
                "isTouch"       : base.browser.isTouch,
                "browser"       : base.browser,
                "dragDirection" : base.dragDirection
            };
        },

        clearEvents : function () {
            var base = this;
            base.$elem.off(".owl owl mousedown.disableTextSelect");
            $(document).off(".owl owl");
            $(window).off("resize", base.resizer);
        },

        unWrap : function () {
            var base = this;
            if (base.$elem.children().length !== 0) {
                base.$owlWrapper.unwrap();
                base.$userItems.unwrap().unwrap();
                if (base.owlControls) {
                    base.owlControls.remove();
                }
            }
            base.clearEvents();
            base.$elem
                .attr("style", base.$elem.data("owl-originalStyles") || "")
                .attr("class", base.$elem.data("owl-originalClasses"));
        },

        destroy : function () {
            var base = this;
            base.stop();
            window.clearInterval(base.checkVisible);
            base.unWrap();
            base.$elem.removeData();
        },

        reinit : function (newOptions) {
            var base = this,
                options = $.extend({}, base.userOptions, newOptions);
            base.unWrap();
            base.init(options, base.$elem);
        },

        addItem : function (htmlString, targetPosition) {
            var base = this,
                position;

            if (!htmlString) {return false; }

            if (base.$elem.children().length === 0) {
                base.$elem.append(htmlString);
                base.setVars();
                return false;
            }
            base.unWrap();
            if (targetPosition === undefined || targetPosition === -1) {
                position = -1;
            } else {
                position = targetPosition;
            }
            if (position >= base.$userItems.length || position === -1) {
                base.$userItems.eq(-1).after(htmlString);
            } else {
                base.$userItems.eq(position).before(htmlString);
            }

            base.setVars();
        },

        removeItem : function (targetPosition) {
            var base = this,
                position;

            if (base.$elem.children().length === 0) {
                return false;
            }
            if (targetPosition === undefined || targetPosition === -1) {
                position = -1;
            } else {
                position = targetPosition;
            }

            base.unWrap();
            base.$userItems.eq(position).remove();
            base.setVars();
        }

    };

    $.fn.owlCarousel = function (options) {
        return this.each(function () {
            if ($(this).data("owl-init") === true) {
                return false;
            }
            $(this).data("owl-init", true);
            var carousel = Object.create(Carousel);
            carousel.init(options, this);
            $.data(this, "owlCarousel", carousel);
        });
    };

    $.fn.owlCarousel.options = {

        items : 5,
        itemsCustom : false,
        itemsDesktop : [1199, 4],
        itemsDesktopSmall : [979, 3],
        itemsTablet : [768, 2],
        itemsTabletSmall : false,
        itemsMobile : [479, 1],
        singleItem : false,
        itemsScaleUp : false,

        slideSpeed : 200,
        paginationSpeed : 800,
        rewindSpeed : 1000,

        autoPlay : true,
        stopOnHover : false,

        navigation : false,
        navigationText : ["prev", "next"],
        rewindNav : true,
        scrollPerPage : false,

        pagination : true,
        paginationNumbers : false,

        responsive : true,
        responsiveRefreshRate : 200,
        responsiveBaseWidth : window,

        baseClass : "owl-carousel",
        theme : "owl-theme",

        lazyLoad : false,
        lazyFollow : true,
        lazyEffect : "fade",

        autoHeight : false,

        jsonPath : false,
        jsonSuccess : false,

        dragBeforeAnimFinish : true,
        mouseDrag : true,
        touchDrag : true,

        addClassActive : false,
        transitionStyle : false,

        beforeUpdate : false,
        afterUpdate : false,
        beforeInit : false,
        afterInit : false,
        beforeMove : false,
        afterMove : false,
        afterAction : false,
        startDragging : false,
        afterLazyLoad: false
    };
}(jQuery, window, document));
/*End carousel*/


;
/* ===========================================================
 * jquery.autofix_anything.js v1
 * ===========================================================
 * Copyright 2013 Pete Rojwongsuriya.
 * http://www.thepetedesign.com
 *
 * Fix position of anything on your website automatically
 * with one js call
 *
 * https://github.com/peachananr/autofix_anything
 *
 * ========================================================== */

!function ($) {

    var defaults = {
        customOffset: false,
        manual: false,
        onlyInContainer: true
    };

    $.fn.autofix_anything = function (options) {
        var settings = $.extend({}, defaults, options),
            el = $(this),
            curpos = el.position(),
            offset = settings.customOffset,
            pos = el.offset();

        el.addClass("autofix_sb")

        $.fn.manualfix = function () {
            var el = $(this),
                pos = el.offset();
            if (el.hasClass("fixed")) {
                el.removeClass("fixed")
            } else {
                el.addClass("fixed").css({
                    top: 0,
                    left: pos.left,
                    right: "auto",
                    bottom: "auto"
                });
            }

        }

        fixAll = function (el, settings, curpos, pos) {
            if (settings.customOffset == false) offset = el.offset().top
            var duthao = $('#closePopupa').length > 0 &&
                typeof $('#closePopupa').data('type') !== 'undefined' &&
                $('#closePopupa').data('type') == 2;
            if ($(document).scrollTop() > offset && $(document).scrollTop() <= (el.parent().height() + (offset - $(window).height()))) {
                el.removeClass("bottom").addClass("fixed").css({
                    top: 0,
                    left: pos.left,
                    right: "auto",
                    bottom: "auto"
                });
                if ($('#tabPannel').length) {
                    el.addClass('navsticky');
                    //if (el.find('.tab-nav-item-ad[data-href=#noidung]').is(':visible')) {
                    //    $('.btn-xem-vb', el).hide();
                    //}
                    $('a.tab-nav-item-ad', el).addClass('fix_navsticky');
                    $('.btn-toanvan', el).addClass('fix_navsticky');
                    if ($('.mucluc_rows', el).length) {
                        $('.mucluc_rows', el).addClass('fix_navsticky');
                        $('.mucluc_new', el).addClass('fix_navsticky');
                        $('.gachd', el).show();
                        $('.fixmucluc_new', el).addClass('fix_navsticky');
                        $('.btn-ssvb', el).addClass('fix_navsticky');
                        $('.icon-bullet-listlvn', el).addClass('fix_navsticky');
                    }
                    if ($('.mucluc_rows2', el).length) {
                        $('.mucluc_rows2', el).addClass('fix_navsticky');
                        $('.mucluc_new', el).addClass('fix_navsticky');
                        $('.fixmucluc_new', el).addClass('fix_navsticky');
                        $('.gachd', el).show();
                        $('.btn-ssvb', el).addClass('fix_navsticky');
                        $('.icon-bullet-listlvn', el).addClass('fix_navsticky');
                    }
                    if ($('.box-tien-ich.fix2',el).length) {
                        $('.box-tien-ich.fix2',el).addClass('fix_navsticky');
                        $('.dropdown-tips', el).addClass('fix_navsticky');
                        $('.dropdown-tips-content', el).addClass('fix_navsticky');
                        $('.item-tien-ich', el).addClass('fix_navsticky');
                    }
                    if ($('.item-tien-ich span',el).length) {
                        $('.item-tien-ich span', el).addClass('hide_fix_navsticky');
                    }
                    if ($('.icon-huongdan', el).length) {
                        $('.icon-huongdan', el).addClass('fix_navsticky');
                    }

                    if ($('.mucluc_new').length && !$('.mucluc_new').hasClass('sosanh'))
                        $('.mucluc_new').addClass('mgl10');
                    if ($('.popup-bg').is(':visible'))
                        $('#tabPannel').css({ 'zIndex': 9 });
                    //bỏ 11/08/2021 - vị trí nút mục lục thay đổi
                    //if ($('#closePopupa').length > 0) {
                    //    var poss = $('#closePopupa').position(),
                    //        width = $('#closePopupa').outerWidth(),
                    //        height = $('#closePopupa').outerHeight();
                    //    if (!duthao) {
                    //        if ($('#mucluc').length > 0) {
                    //            $('#mucluc').find('.popup-wrapper').css({
                    //                top: poss.top + height + 5 + "px",
                    //                left: poss.left - width - 20 + "px"
                    //            });
                    //        }
                    //        if ($('#mucluc2').length > 0) {
                    //            $('#mucluc2').find('.popup-wrapper').css({
                    //                top: poss.top + height + 5 + "px",
                    //                left: poss.left - width - 20 + "px"
                    //            });
                    //        }
                    //        if ($('#mucluc3').length > 0) {
                    //            $('#mucluc3').find('.popup-wrapper').css({
                    //                top: poss.top + height + 5 + "px",
                    //                left: poss.left - width - 20 + "px"
                    //            });
                    //        }
                    //    }
                    //}
                    $('.thongbao.tc', el).css({'position' : 'fixed', 'top' : '-10000px'});
                }
                el.find('.to123').hide();
                el.find('.to234').show();
            } else {
                if ($(document).scrollTop() > offset) {
                    if (settings.onlyInContainer == true) {
                        if ($(document).scrollTop() > (el.parent().height() - $(window).height())) {
                            var id = el.attr('id');
                            if (typeof id !== 'undefined' && id == 'tabPannel') {
                                el.addClass("bottom fixed fixed-tabvb").removeAttr('style');
                            } else {
                                el.addClass("bottom fixed fixed-tabvb").removeAttr('style').css({
                                    left: curpos.left
                                });
                            }
                            if (el.find('.tab-nav-item-ad[data-href=#luocdo]').is(':visible')) {
                                el.addClass('navsticky');
                                $('a.tab-nav-item-ad', el).addClass('fix_navsticky');
                                $('.btn-toanvan', el).addClass('fix_navsticky');
                                if ($('.mucluc_rows', el).length) {
                                    $('.mucluc_rows', el).addClass('fix_navsticky');
                                    $('.mucluc_new', el).addClass('fix_navsticky');
                                    $('.gachd', el).show();
                                    $('.fixmucluc_new', el).addClass('fix_navsticky');
                                    $('.btn-ssvb', el).addClass('fix_navsticky');
                                    $('.icon-bullet-listlvn', el).addClass('fix_navsticky');
                                }
                                if ($('.mucluc_rows2', el).length) {
                                    $('.mucluc_rows2', el).addClass('fix_navsticky');
                                    $('.mucluc_new', el).addClass('fix_navsticky');
                                    $('.gachd', el).show();
                                    $('.fixmucluc_new', el).addClass('fix_navsticky');
                                    $('.btn-ssvb', el).addClass('fix_navsticky');
                                    $('.icon-bullet-listlvn', el).addClass('fix_navsticky');
                                }
                                if ($('.box-tien-ich.fix2', el).length) {
                                    $('.box-tien-ich.fix2', el).addClass('fix_navsticky');
                                    $('.dropdown-tips', el).addClass('fix_navsticky');
                                    $('.dropdown-tips-content', el).addClass('fix_navsticky');
                                    $('.item-tien-ich', el).addClass('fix_navsticky');
                                }
                                if ($('.item-tien-ich span', el).length) {
                                    $('.item-tien-ich span', el).addClass('hide_fix_navsticky');
                                }
                                if ($('.icon-huongdan', el).length) {
                                    $('.icon-huongdan', el).addClass('fix_navsticky');
                                }
                            }
                            if ($('.mucluc_new').length && !$('.mucluc_new').hasClass('sosanh'))
                                $('.mucluc_new').addClass('mgl10');
                            el.find('.to123').hide();
                            el.find('.to234').show();
                        } else {
                            el.removeClass("bottom fixed navsticky").removeAttr('style');
                            $('a.tab-nav-item-ad', el).removeClass('fix_navsticky');
                            $('.btn-toanvan', el).removeClass('fix_navsticky');
                            if ($('#chidanthaydoi').is(':visible')) {
                                $('.thongbao.tc', el).css('position', 'unset');
                            }
                            if ($('.mucluc_rows', el).length) {
                                $('.mucluc_rows', el).removeClass('fix_navsticky');
                                $('.mucluc_new', el).removeClass('fix_navsticky');
                                $('.gachd', el).hide();
                                $('.fixmucluc_new', el).removeClass('fix_navsticky');
                                $('.btn-ssvb', el).removeClass('fix_navsticky');
                                $('.icon-bullet-listlvn', el).removeClass('fix_navsticky');
                            }
                            if ($('.mucluc_rows2', el).length) {
                                $('.mucluc_rows2', el).removeClass('fix_navsticky');
                                $('.mucluc_new', el).removeClass('fix_navsticky');
                                $('.gachd', el).hide();
                                $('.fixmucluc_new', el).removeClass('fix_navsticky');
                                $('.btn-ssvb', el).removeClass('fix_navsticky');
                                $('.icon-bullet-listlvn', el).removeClass('fix_navsticky');
                            }
                            if ($('.box-tien-ich.fix2', el).length) {
                                $('.box-tien-ich.fix2', el).removeClass('fix_navsticky');
                                $('.dropdown-tips', el).removeClass('fix_navsticky');
                                $('.dropdown-tips-content', el).removeClass('fix_navsticky');
                                $('.item-tien-ich', el).removeClass('fix_navsticky');
                            }
                            if ($('.item-tien-ich span', el).length) {
                                $('.item-tien-ich span', el).removeClass('hide_fix_navsticky');
                            }
                            if ($('.icon-huongdan', el).length) {
                                $('.icon-huongdan', el).removeClass('fix_navsticky');
                            }

                            el.find('.to123').show();
                            el.find('.to234').hide();
                            if ($('.mucluc_new').length)
                                $('.mucluc_new').removeClass('mgl10');
                            //if (!duthao) {
                            //    if ($('#mucluc').length > 0) {
                            //        $('#mucluc').find('.popup-wrapper').css({
                            //            top: "20%",
                            //            left: "50%"
                            //        });
                            //    }
                            //    if ($('#mucluc2').length > 0) {
                            //        $('#mucluc2').find('.popup-wrapper').css({
                            //            top: "20%",
                            //            left: "50%"
                            //        });
                            //    }
                            //    if ($('#mucluc3').length > 0) {
                            //        $('#mucluc3').find('.popup-wrapper').css({
                            //            top: "20%",
                            //            left: "50%"
                            //        });
                            //    }
                            //}
                        }
                    }
                } else {
                    el.removeClass("bottom fixed navsticky").removeAttr('style');
                    $('a.tab-nav-item-ad', el).removeClass('fix_navsticky');
                    $('.btn-toanvan', el).removeClass('fix_navsticky');
                    if ($('#chidanthaydoi').is(':visible')) {
                        $('.thongbao.tc', el).css('position', 'unset');
                    }
                    if ($('.mucluc_rows', el).length) {
                        $('.mucluc_rows', el).removeClass('fix_navsticky');
                        $('.mucluc_new', el).removeClass('fix_navsticky');
                        $('.gachd', el).hide();
                        $('.fixmucluc_new', el).removeClass('fix_navsticky');
                        $('.btn-ssvb', el).removeClass('fix_navsticky');
                        $('.icon-bullet-listlvn', el).removeClass('fix_navsticky');
                    }
                    if ($('.mucluc_rows2', el).length) {
                        $('.mucluc_rows2', el).removeClass('fix_navsticky');
                        $('.mucluc_new', el).removeClass('fix_navsticky');
                        $('.gachd', el).hide();
                        $('.fixmucluc_new', el).removeClass('fix_navsticky');
                        $('.btn-ssvb', el).removeClass('fix_navsticky');
                        $('.icon-bullet-listlvn', el).removeClass('fix_navsticky');
                    }
                    if ($('.box-tien-ich.fix2', el).length) {
                        $('.box-tien-ich.fix2', el).removeClass('fix_navsticky');
                        $('.dropdown-tips', el).removeClass('fix_navsticky');
                        $('.dropdown-tips-content', el).removeClass('fix_navsticky');
                        $('.item-tien-ich', el).removeClass('fix_navsticky');
                    }
                    if ($('.item-tien-ich span', el).length) {
                        $('.item-tien-ich span', el).removeClass('hide_fix_navsticky');
                    }
                    if ($('.icon-huongdan', el).length) {
                        $('.icon-huongdan', el).removeClass('fix_navsticky');
                    }
                    //if ($('#noidung').find('embed').is(':visible')) {
                    //    $('.btn-xem-vb', el).show();
                    //}
                    el.find('.to123').show();
                    el.find('.to234').hide();
                    if ($('.mucluc_new').length)
                        $('.mucluc_new').removeClass('mgl10');
                    //if (!duthao) {
                    //    if ($('#mucluc').length > 0) {
                    //        $('#mucluc').find('.popup-wrapper').css({
                    //            top: "20%",
                    //            left: "50%"
                    //        });
                    //    }
                    //    if ($('#mucluc2').length > 0) {
                    //        $('#mucluc2').find('.popup-wrapper').css({
                    //            top: "20%",
                    //            left: "50%"
                    //        });
                    //    }
                    //    if ($('#mucluc3').length > 0) {
                    //        $('#mucluc3').find('.popup-wrapper').css({
                    //            top: "20%",
                    //            left: "50%"
                    //        });
                    //    }
                    //}
                }
            }
        }
        if (settings.manual == false) {
            $(window).scroll(function () {
                fixAll(el, settings, curpos, pos)
            });
        }


    }
}(window.jQuery);

;
var reg;
var sub;
var isSubscribed = false;
var isBlock = false;
var autoRegist = true;
var domainName = 'https://luatvietnam.vn';

//regist js file control notify
var isInit = false;
function firtInitialiseUI() {
    if (isInit === true) {
        return;
    }
    // Set the initial subscription value
    if (Notification.permission === 'denied') {
        isSubscribed = false;
        console.log('User is BLOCK Notify.');
        isBlock = true;
        return;
    }
    if (!reg) {
        console.log('reg is null.');
        $("#NotifyPannel").hide();// uncoment when public
        return;
    }
    reg.pushManager.getSubscription()
        .then(function (subscription) {
            isSubscribed = !(subscription === null);

            if (isSubscribed) {
                console.log('User IS subscribed.');                
            } else {
                console.log('User is NOT subscribed.' + isSubscribed);
            }
            if (autoRegist && isSubscribed === false && localStorage.getItem("RegistNotify") !== "1" && sessionStorage.getItem("RegistNotify") !== "1") {
                console.log('Start subscribed.');
                subscribeNotify();
                //$("#NotifyRegistAds").show();
            }

        });

}
function initialiseUI() {
    if (isInit === true) {
        return;
    }
    isInit = true;
    // Set the initial subscription value
    if (Notification.permission === 'denied') {
        isSubscribed = false;
        $("#NotifyNote").html("Bạn đã khóa tính năng nhận thông báo mới từ luatvietnam.vn");
        $("#NotifyNote").show();
        console.log('User is BLOCK Notify.');
        isBlock = true;
        return;
    }
    if (!reg) {
        console.log('reg is null.');
        $("#NotifyNote").html("Trình duyệt bạn dùng không hỗ trợ tính năng nhận thông báo trực tiếp.");
        $("#NotifyNote").show();
        $("#NotifyPannel").hide();// uncoment when public
        return;
    }
    reg.pushManager.getSubscription()
        .then(function (subscription) {
            isSubscribed = !(subscription === null);

            if (isSubscribed) {
                $("#NotifyNote").html("Bạn đã đăng ký nhận thông báo mới từ luatvietnam.vn. Cảm ơn bạn đã quan tâm theo dõi!");
                $("#NotifyNote").show();
                console.log('User IS subscribed.');                
            } else {
                $("#NotifyNote").html("Đăng ký nhận thông báo mới từ luatvietnam.vn");
                $("#NotifyNote").show();
                console.log('User is NOT subscribed.');

            }
            if (autoRegist && isSubscribed === false && localStorage.getItem("RegistNotify") !== "1" && sessionStorage.getItem("RegistNotify") !== "1") {
                subscribeNotify();
                //$("#NotifyRegistAds").show();
            }
        });

}
function showNote() {
    if (isInit === false) {
        initialiseUI();
    }
    $("#NotifyNote").show();
}
function hideNote() {
    $("#NotifyNote").hide();
}
if ('serviceWorker' in navigator && 'PushManager' in window) {
    console.log('Service Worker is supported');
    navigator.serviceWorker.register('/sw.js').then(function () {
        return navigator.serviceWorker.ready;

    }).then(function (serviceWorkerRegistration) {
        $("#NotifyPannel").show();
        console.log('Service Worker is ready :^)');
        reg = serviceWorkerRegistration;
        if (isInit === false) {
            firtInitialiseUI();
        }
    }).catch(function (error) {
        console.log('Service Worker Error hide pannel :^(', error);
        //$("#NotifyPannel").hide();// uncoment when public
    });
}
else {
    console.log('Service Worker is Not supported');
    //$("#NotifyPannel").hide();// uncoment when public
}
function ShowNotifyConfig() {
    if (isInit === false) {
        initialiseUI();
    }
    if (isSubscribed === false) {
        if (isBlock) {
            $("#NoteLockNotify").show();
        }
        else {
            $("#NoteLockNotify").hide();
        }
        $("#NotifyConfigUnRegist").hide();
        $("#NotifyConfigRegist").show();
    }
    else {
        $("#NotifyConfigRegist").hide();
        $("#NotifyConfigUnRegist").show();
    }
    $("#NotifyConfig").toggle('fast');
}
function CancelAds() {
    $("#NotifyRegistAds").hide();
    sessionStorage.setItem("RegistNotify", "1");
}
function subscribeNotify() {
    isInit = false;
    console.log('Đang đăng ký...');
    reg.pushManager.subscribe({ userVisibleOnly: true }).
        then(function (pushSubscription) {
            console.log('Đang đăng ký 2...');
            sub = pushSubscription;
            console.log(sub);
            var key = btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('p256dh'))));
            var auth = btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('auth'))));
            console.log(key);
            console.log(auth);
            $.ajax({
                url: domainName + '/Notify/Regist?endpoint=' + sub.endpoint + '&key=' + key + '&auth=' + auth,
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    $("#NotifyNote").html("Bạn đã đăng ký thành công. Cảm ơn bạn đã quan tâm theo dõi luatvietnam.vn");
                    $("#NotifyNote").show();
                    console.log('Đăng ký: ' + sub.endpoint);
                },
                error: function () {
                    $("#NotifyNote").html("Bạn chưa đăng ký thành công. Vui lòng thử lại sau");
                    $("#NotifyNote").show();
                    console.log('Xảy ra lỗi: Sự kiện Click nút đăng ký');

                }
            });
            isSubscribed = true;
        });
    $("#NotifyConfig").hide();
    $("#NotifyRegistAds").hide();
    localStorage.setItem("RegistNotify", "1");
    sessionStorage.setItem("RegistNotify", "1");
}

function unsubscribe() {
    isInit = false;
    reg.pushManager.getSubscription()
        .then(function (subscription) {
            if (subscription) {
                console.log('subscription: ', subscription);
                var endPoint = subscription.endpoint;
                var unsubDes = subscription.unsubscribe();

                console.log('unsubDes: ', unsubDes);
                $.ajax({
                    url: domainName + '/Notify/UnRegist?m_event=' + endPoint,
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        console.log('Hủy Đăng ký: ');
                        console.log(unsubDes);
                        $("#NotifyNote").html("Bạn đã hủy đăng ký nhận tin mới từ luatvietnam.vn");
                        $("#NotifyNote").show();
                    },
                    error: function () {
                        console.log('Xảy ra lỗi: Sự kiện Click nút hủy đăng ký');
                        $("#NotifyNote").html("Bạn đã hủy đăng ký nhận tin mới từ luatvietnam.vn");
                        $("#NotifyNote").show();
                    }
                });
            }
        })
        .catch(function (error) {
            console.log('Error unsubscribing', error);
        })
        .then(function () {
            $("#NotifyNote").html("Bạn đã hủy đăng ký nhận tin mới từ luatvietnam.vn");
            $("#NotifyNote").show();
            console.log('User is unsubscribed.');
            isSubscribed = false;

        });
    $("#NotifyConfig").hide();
};
/*! Lazy Load 2.0.0-beta.2 - MIT license - Copyright 2007-2017 Mika Tuupola */
!function(t,e){"object"==typeof exports?module.exports=e(t):"function"==typeof define&&define.amd?define([],e(t)):t.LazyLoad=e(t)}("undefined"!=typeof global?global:this.window||this.global,function(t){"use strict";function e(t,e){this.settings=r(s,e||{}),this.images=t||document.querySelectorAll(this.settings.selector),this.observer=null,this.init()}const s={src:"data-src",srcset:"data-srcset",selector:".lazyload"},r=function(){let t={},e=!1,s=0,o=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(e=arguments[0],s++);for(;s<o;s++)!function(s){for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&(e&&"[object Object]"===Object.prototype.toString.call(s[o])?t[o]=r(!0,t[o],s[o]):t[o]=s[o])}(arguments[s]);return t};if(e.prototype={init:function(){if(!t.IntersectionObserver)return void this.loadImages();let e=this,s={root:null,rootMargin:"0px",threshold:[0]};this.observer=new IntersectionObserver(function(t){t.forEach(function(t){if(t.intersectionRatio>0){e.observer.unobserve(t.target);let s=t.target.getAttribute(e.settings.src),r=t.target.getAttribute(e.settings.srcset);"img"===t.target.tagName.toLowerCase()?(s&&(t.target.src=s),r&&(t.target.srcset=r)):t.target.style.backgroundImage="url("+s+")"}})},s),this.images.forEach(function(t){e.observer.observe(t)})},loadAndDestroy:function(){this.settings&&(this.loadImages(),this.destroy())},loadImages:function(){if(!this.settings)return;let t=this;this.images.forEach(function(e){let s=e.getAttribute(t.settings.src),r=e.getAttribute(t.settings.srcset);"img"===e.tagName.toLowerCase()?(s&&(e.src=s),r&&(e.srcset=r)):e.style.backgroundImage="url("+s+")"})},destroy:function(){this.settings&&(this.observer.disconnect(),this.settings=null)}},t.lazyload=function(t,s){return new e(t,s)},t.jQuery){const s=t.jQuery;s.fn.lazyload=function(t){return t=t||{},t.attribute=t.attribute||"data-src",new e(s.makeArray(this),t),this}}return e});
;
