/* Minification failed. Returning unminified contents.
(12174,9,12177,10): run-time error JS1314: Implicit property name must be identifier: startProductLoad(loadLink) {
            loading = true;
            loadLink.find('i').removeClass('hidden');
        }
(12179,9,12182,10): run-time error JS1314: Implicit property name must be identifier: endProductLoad(loadLink) {
            loadLink.find('i').addClass('hidden');
            loading = false;
        }
(12184,9,12186,10): run-time error JS1314: Implicit property name must be identifier: getNoOfProductRows() {
            return $('#js-product-list .row').length;
        }
(12188,9,12190,10): run-time error JS1314: Implicit property name must be identifier: getQuery() {
            return $('#search-query').text().replace(/"/g, "");
        }
(12192,9,12196,10): run-time error JS1314: Implicit property name must be identifier: doProductOnHandAndLazyLoad() {
            var onhand = new OnHand();
            onhand.updateonhand();
            lazyload();
        }
(12198,9,12205,10): run-time error JS1314: Implicit property name must be identifier: syncPaging(loadLink, productsBefore) {
            var productsAfter = helpers.getNoOfProductRows();
            $('#js-product-count').text(productsAfter);
            var added = productsAfter - productsBefore;
            if (added < 50) {
                loadLink.addClass('hidden');
            }
        }
(12416,9,12433,10): run-time error JS1314: Implicit property name must be identifier: getServicesFiltered() {

            let filteredItems = [...window.serviceList];

            if (customServiceSortIds != null) {
                customServiceSortIds.forEach(id => {
                    for (var i = filteredItems.length-1; i >= 0; i--) {
                        if (filteredItems[i].Id === id) {
                            var removedElement = filteredItems.splice(i, 1)[0];
                            filteredItems.splice(0, 0, removedElement);
                            break; 
                        }
                    }
                });
            }

            return filteredItems;
        }
(12440,9,12447,10): run-time error JS1314: Implicit property name must be identifier: showServicesForPreselectedOrFirstTab() {
            let $tabItem = $tabPreselected.length ? $tabPreselected : $tabs.first();
            $tabItem.click();

            $servicList.removeClass('hidden');
            if ($tabs.length > 1)
                $(tabsContainerQ).removeClass('hidden');
        }
 */
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t
}({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle);
u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.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(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
;
/*	

	jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)

	Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.

	Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
	http://dojofoundation.org/license for more information.

*/	

;(function(d){

	// the topic/subscription hash
	var cache = {};

	d.publish = function(/* String */topic, /* Array? */args){
		// summary: 
		//		Publish some data on a named topic.
		// topic: String
		//		The channel to publish on
		// args: Array?
		//		The data to publish. Each array item is converted into an ordered
		//		arguments on the subscribed functions. 
		//
		// example:
		//		Publish stuff on '/some/topic'. Anything subscribed will be called
		//		with a function signature like: function(a,b,c){ ... }
		//
		//	|		$.publish("/some/topic", ["a","b","c"]);
		cache[topic] && d.each(cache[topic], function(){
			this.apply(d, args || []);
		});
	};

	d.subscribe = function(/* String */topic, /* Function */callback){
		// summary:
		//		Register a callback on a named topic.
		// topic: String
		//		The channel to subscribe to
		// callback: Function
		//		The handler event. Anytime something is $.publish'ed on a 
		//		subscribed channel, the callback will be called with the
		//		published array as ordered arguments.
		//
		// returns: Array
		//		A handle which can be used to unsubscribe this particular subscription.
		//	
		// example:
		//	|	$.subscribe("/some/topic", function(a, b, c){ /* handle data */ });
		//
		if(!cache[topic]){
			cache[topic] = [];
		}
		cache[topic].push(callback);
		return [topic, callback]; // Array
	};

	d.unsubscribe = function(/* Array */handle){
		// summary:
		//		Disconnect a subscribed function for a topic.
		// handle: Array
		//		The return value from a $.subscribe call.
		// example:
		//	|	var handle = $.subscribe("/something", function(){});
		//	|	$.unsubscribe(handle);
		
		var t = handle[0];
		cache[t] && d.each(cache[t], function(idx){
			if(this == handle[1]){
				cache[t].splice(idx, 1);
			}
		});
	};

})(jQuery);

;
/* Placeholders.js v4.0.1 */
/*!
 * The MIT License
 *
 * Copyright (c) 2012 James Allardice
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
!function(a){"use strict";function b(){}function c(){try{return document.activeElement}catch(a){}}function d(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return!0;return!1}function e(a,b,c){return a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent?a.attachEvent("on"+b,c):void 0}function f(a,b){var c;a.createTextRange?(c=a.createTextRange(),c.move("character",b),c.select()):a.selectionStart&&(a.focus(),a.setSelectionRange(b,b))}function g(a,b){try{return a.type=b,!0}catch(c){return!1}}function h(a,b){if(a&&a.getAttribute(B))b(a);else for(var c,d=a?a.getElementsByTagName("input"):N,e=a?a.getElementsByTagName("textarea"):O,f=d?d.length:0,g=e?e.length:0,h=f+g,i=0;h>i;i++)c=f>i?d[i]:e[i-f],b(c)}function i(a){h(a,k)}function j(a){h(a,l)}function k(a,b){var c=!!b&&a.value!==b,d=a.value===a.getAttribute(B);if((c||d)&&"true"===a.getAttribute(C)){a.removeAttribute(C),a.value=a.value.replace(a.getAttribute(B),""),a.className=a.className.replace(A,"");var e=a.getAttribute(I);parseInt(e,10)>=0&&(a.setAttribute("maxLength",e),a.removeAttribute(I));var f=a.getAttribute(D);return f&&(a.type=f),!0}return!1}function l(a){var b=a.getAttribute(B);if(""===a.value&&b){a.setAttribute(C,"true"),a.value=b,a.className+=" "+z;var c=a.getAttribute(I);c||(a.setAttribute(I,a.maxLength),a.removeAttribute("maxLength"));var d=a.getAttribute(D);return d?a.type="text":"password"===a.type&&g(a,"text")&&a.setAttribute(D,"password"),!0}return!1}function m(a){return function(){P&&a.value===a.getAttribute(B)&&"true"===a.getAttribute(C)?f(a,0):k(a)}}function n(a){return function(){l(a)}}function o(a){return function(){i(a)}}function p(a){return function(b){return v=a.value,"true"===a.getAttribute(C)&&v===a.getAttribute(B)&&d(x,b.keyCode)?(b.preventDefault&&b.preventDefault(),!1):void 0}}function q(a){return function(){k(a,v),""===a.value&&(a.blur(),f(a,0))}}function r(a){return function(){a===c()&&a.value===a.getAttribute(B)&&"true"===a.getAttribute(C)&&f(a,0)}}function s(a){var b=a.form;b&&"string"==typeof b&&(b=document.getElementById(b),b.getAttribute(E)||(e(b,"submit",o(b)),b.setAttribute(E,"true"))),e(a,"focus",m(a)),e(a,"blur",n(a)),P&&(e(a,"keydown",p(a)),e(a,"keyup",q(a)),e(a,"click",r(a))),a.setAttribute(F,"true"),a.setAttribute(B,T),(P||a!==c())&&l(a)}var t=document.createElement("input"),u=void 0!==t.placeholder;if(a.Placeholders={nativeSupport:u,disable:u?b:i,enable:u?b:j},!u){var v,w=["text","search","url","tel","email","password","number","textarea"],x=[27,33,34,35,36,37,38,39,40,8,46],y="#ccc",z="placeholdersjs",A=new RegExp("(?:^|\\s)"+z+"(?!\\S)"),B="data-placeholder-value",C="data-placeholder-active",D="data-placeholder-type",E="data-placeholder-submit",F="data-placeholder-bound",G="data-placeholder-focus",H="data-placeholder-live",I="data-placeholder-maxlength",J=100,K=document.getElementsByTagName("head")[0],L=document.documentElement,M=a.Placeholders,N=document.getElementsByTagName("input"),O=document.getElementsByTagName("textarea"),P="false"===L.getAttribute(G),Q="false"!==L.getAttribute(H),R=document.createElement("style");R.type="text/css";var S=document.createTextNode("."+z+" {color:"+y+";}");R.styleSheet?R.styleSheet.cssText=S.nodeValue:R.appendChild(S),K.insertBefore(R,K.firstChild);for(var T,U,V=0,W=N.length+O.length;W>V;V++)U=V<N.length?N[V]:O[V-N.length],T=U.attributes.placeholder,T&&(T=T.nodeValue,T&&d(w,U.type)&&s(U));var X=setInterval(function(){for(var a=0,b=N.length+O.length;b>a;a++)U=a<N.length?N[a]:O[a-N.length],T=U.attributes.placeholder,T?(T=T.nodeValue,T&&d(w,U.type)&&(U.getAttribute(F)||s(U),(T!==U.getAttribute(B)||"password"===U.type&&!U.getAttribute(D))&&("password"===U.type&&!U.getAttribute(D)&&g(U,"text")&&U.setAttribute(D,"password"),U.value===U.getAttribute(B)&&(U.value=T),U.setAttribute(B,T)))):U.getAttribute(C)&&(k(U),U.removeAttribute(B));Q||clearInterval(X)},J);e(a,"beforeunload",function(){M.disable()})}}(this);;
/*!
 * Bootstrap v3.1.1 (http://getbootstrap.com)
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.isLoading=!1};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",f.resetText||d.data("resetText",d[e]()),d[e](f[b]||this.options[b]),setTimeout(a.proxy(function(){"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},b.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}a&&this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}if(e.hasClass("active"))return this.sliding=!1;var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});return this.$element.trigger(j),j.isDefaultPrevented()?void 0:(this.sliding=!0,f&&this.pause(),this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid.bs.carousel",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")?(e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid.bs.carousel")},0)}).emulateTransitionEnd(1e3*d.css("transition-duration").slice(0,-1))):(d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid.bs.carousel")),f&&this.cycle(),this)};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("collapse in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?void this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);!e&&f.toggle&&"show"==c&&(c=!c),e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(jQuery),+function(a){"use strict";function b(b){a(d).remove(),a(e).each(function(){var d=c(a(this)),e={relatedTarget:this};d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown",e)),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown",e))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;f.toggleClass("open").trigger("shown.bs.dropdown",h),e.focus()}return!1}},f.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var f=c(d),g=f.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&f.find(e).focus(),d.click();var h=" li:not(.divider):visible a",i=f.find("[role=menu]"+h+", [role=listbox]"+h);if(i.length){var j=i.index(i.filter(":focus"));38==b.keyCode&&j>0&&j--,40==b.keyCode&&j<i.length-1&&j++,~j||(j=0),i.eq(j).focus()}}}};var g=a.fn.dropdown;a.fn.dropdown=function(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new f(this)),"string"==typeof b&&d[b].call(c)})},a.fn.dropdown.Constructor=f,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=g,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",e,f.prototype.toggle).on("keydown.bs.dropdown.data-api",e+", [role=menu], [role=listbox]",f.prototype.keydown)}(jQuery),+function(a){"use strict";var b=function(b,c){this.options=c,this.$element=a(b),this.$backdrop=this.isShown=null,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};b.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},b.prototype.toggle=function(a){return this[this.isShown?"hide":"show"](a)},b.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.escape(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(document.body),c.$element.show().scrollTop(0),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one(a.support.transition.end,function(){c.$element.focus().trigger(e)}).emulateTransitionEnd(300):c.$element.focus().trigger(e)}))},b.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one(a.support.transition.end,a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},b.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.focus()},this))},b.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},b.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.removeBackdrop(),a.$element.trigger("hidden.bs.modal")})},b.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},b.prototype.backdrop=function(b){var c=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var d=a.support.transition&&c;if(this.$backdrop=a('<div class="modal-backdrop '+c+'" />').appendTo(document.body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),d&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;d?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()):b&&b()};var c=a.fn.modal;a.fn.modal=function(c,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},b.DEFAULTS,e.data(),"object"==typeof c&&c);f||e.data("bs.modal",f=new b(this,g)),"string"==typeof c?f[c](d):g.show&&f.show(d)})},a.fn.modal.Constructor=b,a.fn.modal.noConflict=function(){return a.fn.modal=c,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(b){var c=a(this),d=c.attr("href"),e=a(c.attr("data-target")||d&&d.replace(/.*(?=#[^\s]+$)/,"")),f=e.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(d)&&d},e.data(),c.data());c.is("a")&&b.preventDefault(),e.modal(f,this).one("hide",function(){c.is(":visible")&&c.focus()})}),a(document).on("show.bs.modal",".modal",function(){a(document.body).addClass("modal-open")}).on("hidden.bs.modal",".modal",function(){a(document.body).removeClass("modal-open")})}(jQuery),+function(a){"use strict";var b=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};b.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1},b.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},b.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},b.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);return clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show()},b.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},b.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){if(this.$element.trigger(b),b.isDefaultPrevented())return;var c=this,d=this.tip();this.setContent(),this.options.animation&&d.addClass("fade");var e="function"==typeof this.options.placement?this.options.placement.call(this,d[0],this.$element[0]):this.options.placement,f=/\s?auto?\s?/i,g=f.test(e);g&&(e=e.replace(f,"")||"top"),d.detach().css({top:0,left:0,display:"block"}).addClass(e),this.options.container?d.appendTo(this.options.container):d.insertAfter(this.$element);var h=this.getPosition(),i=d[0].offsetWidth,j=d[0].offsetHeight;if(g){var k=this.$element.parent(),l=e,m=document.documentElement.scrollTop||document.body.scrollTop,n="body"==this.options.container?window.innerWidth:k.outerWidth(),o="body"==this.options.container?window.innerHeight:k.outerHeight(),p="body"==this.options.container?0:k.offset().left;e="bottom"==e&&h.top+h.height+j-m>o?"top":"top"==e&&h.top-m-j<0?"bottom":"right"==e&&h.right+i>n?"left":"left"==e&&h.left-i<p?"right":e,d.removeClass(l).addClass(e)}var q=this.getCalculatedOffset(e,h,i,j);this.applyPlacement(q,e),this.hoverState=null;var r=function(){c.$element.trigger("shown.bs."+c.type)};a.support.transition&&this.$tip.hasClass("fade")?d.one(a.support.transition.end,r).emulateTransitionEnd(150):r()}},b.prototype.applyPlacement=function(b,c){var d,e=this.tip(),f=e[0].offsetWidth,g=e[0].offsetHeight,h=parseInt(e.css("margin-top"),10),i=parseInt(e.css("margin-left"),10);isNaN(h)&&(h=0),isNaN(i)&&(i=0),b.top=b.top+h,b.left=b.left+i,a.offset.setOffset(e[0],a.extend({using:function(a){e.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),e.addClass("in");var j=e[0].offsetWidth,k=e[0].offsetHeight;if("top"==c&&k!=g&&(d=!0,b.top=b.top+g-k),/bottom|top/.test(c)){var l=0;b.left<0&&(l=-2*b.left,b.left=0,e.offset(b),j=e[0].offsetWidth,k=e[0].offsetHeight),this.replaceArrow(l-f+j,j,"left")}else this.replaceArrow(k-g,k,"top");d&&e.offset(b)},b.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},b.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach(),c.$element.trigger("hidden.bs."+c.type)}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one(a.support.transition.end,b).emulateTransitionEnd(150):b(),this.hoverState=null,this)},b.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},b.prototype.hasContent=function(){return this.getTitle()},b.prototype.getPosition=function(){var b=this.$element[0];return a.extend({},"function"==typeof b.getBoundingClientRect?b.getBoundingClientRect():{width:b.offsetWidth,height:b.offsetHeight},this.$element.offset())},b.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},b.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},b.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},b.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},b.prototype.enable=function(){this.enabled=!0},b.prototype.disable=function(){this.enabled=!1},b.prototype.toggleEnabled=function(){this.enabled=!this.enabled},b.prototype.toggle=function(b){var c=b?a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type):this;c.tip().hasClass("in")?c.leave(c):c.enter(c)},b.prototype.destroy=function(){clearTimeout(this.timeout),this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var c=a.fn.tooltip;a.fn.tooltip=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof c&&c;(e||"destroy"!=c)&&(e||d.data("bs.tooltip",e=new b(this,f)),"string"==typeof c&&e[c]())})},a.fn.tooltip.Constructor=b,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=c,this}}(jQuery),+function(a){"use strict";var b=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");b.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;(e||"destroy"!=c)&&(e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]())})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(a(c).is("body")?window:c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);{var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})}},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);if(g&&b<=e[0])return g!=(a=f[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parentsUntil(this.options.target,".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(b.RESET).addClass("affix");var a=this.$window.scrollTop(),c=this.$element.offset();return this.pinnedOffset=c.top-a},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"top"==this.affixed&&(e.top+=d),"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top(this.$element)),"function"==typeof h&&(h=f.bottom(this.$element));var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;if(this.affixed!==i){this.unpin&&this.$element.css("top","");var j="affix"+(i?"-"+i:""),k=a.Event(j+".bs.affix");this.$element.trigger(k),k.isDefaultPrevented()||(this.affixed=i,this.unpin="bottom"==i?this.getPinnedOffset():null,this.$element.removeClass(b.RESET).addClass(j).trigger(a.Event(j.replace("affix","affixed"))),"bottom"==i&&this.$element.offset({top:c-h-this.$element.height()}))}}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(jQuery);;
/*
  SlidesJS 3.0.4 http://slidesjs.com
  (c) 2013 by Nathan Searles http://nathansearles.com
  Updated: June 26th, 2013
  Apache License: http://www.apache.org/licenses/LICENSE-2.0
*/
(function(){(function(e,t,n){var r,i,s;s="slidesjs";i={width:940,height:528,start:1,navigation:{active:!0,effect:"slide"},pagination:{active:!0,effect:"slide"},play:{active:!1,effect:"slide",interval:5e3,auto:!1,swap:!0,pauseOnHover:!1,restartDelay:2500},effect:{slide:{speed:500},fade:{speed:300,crossfade:!0}},callback:{loaded:function(){},start:function(){},complete:function(){}}};r=function(){function t(t,n){this.element=t;this.options=e.extend(!0,{},i,n);this._defaults=i;this._name=s;this.init()}return t}();r.prototype.init=function(){var n,r,i,s,o,u,a=this;n=e(this.element);this.data=e.data(this);e.data(this,"animating",!1);e.data(this,"total",n.children().not(".slidesjs-navigation",n).length);e.data(this,"current",this.options.start-1);e.data(this,"vendorPrefix",this._getVendorPrefix());if(typeof TouchEvent!="undefined"){e.data(this,"touch",!0);this.options.effect.slide.speed=this.options.effect.slide.speed/2}n.css({overflow:"hidden"});n.slidesContainer=n.children().not(".slidesjs-navigation",n).wrapAll("<div class='slidesjs-container'>",n).parent().css({overflow:"hidden",position:"relative"});e(".slidesjs-container",n).wrapInner("<div class='slidesjs-control'>",n).children();e(".slidesjs-control",n).css({position:"relative",left:0});e(".slidesjs-control",n).children().addClass("slidesjs-slide").css({position:"absolute",top:0,left:0,width:"100%",zIndex:0,display:"none",webkitBackfaceVisibility:"hidden"});e.each(e(".slidesjs-control",n).children(),function(t){var n;n=e(this);return n.attr("slidesjs-index",t)});if(this.data.touch){e(".slidesjs-control",n).on("touchstart",function(e){return a._touchstart(e)});e(".slidesjs-control",n).on("touchmove",function(e){return a._touchmove(e)});e(".slidesjs-control",n).on("touchend",function(e){return a._touchend(e)})}n.fadeIn(0);this.update();this.data.touch&&this._setuptouch();e(".slidesjs-control",n).children(":eq("+this.data.current+")").eq(0).fadeIn(0,function(){return e(this).css({zIndex:10})});if(this.options.navigation.active){o=e("<a>",{"class":"slidesjs-previous slidesjs-navigation",href:"#",title:"Previous",text:"Previous"}).appendTo(n);r=e("<a>",{"class":"slidesjs-next slidesjs-navigation",href:"#",title:"Next",text:"Next"}).appendTo(n)}e(".slidesjs-next",n).click(function(e){e.preventDefault();a.stop(!0);return a.next(a.options.navigation.effect)});e(".slidesjs-previous",n).click(function(e){e.preventDefault();a.stop(!0);return a.previous(a.options.navigation.effect)});if(this.options.play.active){s=e("<a>",{"class":"slidesjs-play slidesjs-navigation",href:"#",title:"Play",text:"Play"}).appendTo(n);u=e("<a>",{"class":"slidesjs-stop slidesjs-navigation",href:"#",title:"Stop",text:"Stop"}).appendTo(n);s.click(function(e){e.preventDefault();return a.play(!0)});u.click(function(e){e.preventDefault();return a.stop(!0)});this.options.play.swap&&u.css({display:"none"})}if(this.options.pagination.active){i=e("<ul>",{"class":"slidesjs-pagination"}).appendTo(n);e.each(new Array(this.data.total),function(t){var n,r;n=e("<li>",{"class":"slidesjs-pagination-item"}).appendTo(i);r=e("<a>",{href:"#","data-slidesjs-item":t,html:t+1}).appendTo(n);return r.click(function(t){t.preventDefault();a.stop(!0);return a.goto(e(t.currentTarget).attr("data-slidesjs-item")*1+1)})})}e(t).bind("resize",function(){return a.update()});this._setActive();this.options.play.auto&&this.play();return this.options.callback.loaded(this.options.start)};r.prototype._setActive=function(t){var n,r;n=e(this.element);this.data=e.data(this);r=t>-1?t:this.data.current;e(".active",n).removeClass("active");return e(".slidesjs-pagination li:eq("+r+") a",n).addClass("active")};r.prototype.update=function(){var t,n,r;t=e(this.element);this.data=e.data(this);e(".slidesjs-control",t).children(":not(:eq("+this.data.current+"))").css({display:"none",left:0,zIndex:0});r=t.width();n=this.options.height/this.options.width*r;this.options.width=r;this.options.height=n;return e(".slidesjs-control, .slidesjs-container",t).css({width:r,height:n})};r.prototype.next=function(t){var n;n=e(this.element);this.data=e.data(this);e.data(this,"direction","next");t===void 0&&(t=this.options.navigation.effect);return t==="fade"?this._fade():this._slide()};r.prototype.previous=function(t){var n;n=e(this.element);this.data=e.data(this);e.data(this,"direction","previous");t===void 0&&(t=this.options.navigation.effect);return t==="fade"?this._fade():this._slide()};r.prototype.goto=function(t){var n,r;n=e(this.element);this.data=e.data(this);r===void 0&&(r=this.options.pagination.effect);t>this.data.total?t=this.data.total:t<1&&(t=1);if(typeof t=="number")return r==="fade"?this._fade(t):this._slide(t);if(typeof t=="string"){if(t==="first")return r==="fade"?this._fade(0):this._slide(0);if(t==="last")return r==="fade"?this._fade(this.data.total):this._slide(this.data.total)}};r.prototype._setuptouch=function(){var t,n,r,i;t=e(this.element);this.data=e.data(this);i=e(".slidesjs-control",t);n=this.data.current+1;r=this.data.current-1;r<0&&(r=this.data.total-1);n>this.data.total-1&&(n=0);i.children(":eq("+n+")").css({display:"block",left:this.options.width});return i.children(":eq("+r+")").css({display:"block",left:-this.options.width})};r.prototype._touchstart=function(t){var n,r;n=e(this.element);this.data=e.data(this);r=t.originalEvent.touches[0];this._setuptouch();e.data(this,"touchtimer",Number(new Date));e.data(this,"touchstartx",r.pageX);e.data(this,"touchstarty",r.pageY);return t.stopPropagation()};r.prototype._touchend=function(t){var n,r,i,s,o,u,a,f=this;n=e(this.element);this.data=e.data(this);u=t.originalEvent.touches[0];s=e(".slidesjs-control",n);if(s.position().left>this.options.width*.5||s.position().left>this.options.width*.1&&Number(new Date)-this.data.touchtimer<250){e.data(this,"direction","previous");this._slide()}else if(s.position().left<-(this.options.width*.5)||s.position().left<-(this.options.width*.1)&&Number(new Date)-this.data.touchtimer<250){e.data(this,"direction","next");this._slide()}else{i=this.data.vendorPrefix;a=i+"Transform";r=i+"TransitionDuration";o=i+"TransitionTimingFunction";s[0].style[a]="translateX(0px)";s[0].style[r]=this.options.effect.slide.speed*.85+"ms"}s.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd",function(){i=f.data.vendorPrefix;a=i+"Transform";r=i+"TransitionDuration";o=i+"TransitionTimingFunction";s[0].style[a]="";s[0].style[r]="";return s[0].style[o]=""});return t.stopPropagation()};r.prototype._touchmove=function(t){var n,r,i,s,o;n=e(this.element);this.data=e.data(this);s=t.originalEvent.touches[0];r=this.data.vendorPrefix;i=e(".slidesjs-control",n);o=r+"Transform";e.data(this,"scrolling",Math.abs(s.pageX-this.data.touchstartx)<Math.abs(s.pageY-this.data.touchstarty));if(!this.data.animating&&!this.data.scrolling){t.preventDefault();this._setuptouch();i[0].style[o]="translateX("+(s.pageX-this.data.touchstartx)+"px)"}return t.stopPropagation()};r.prototype.play=function(t){var n,r,i,s=this;n=e(this.element);this.data=e.data(this);if(!this.data.playInterval){if(t){r=this.data.current;this.data.direction="next";this.options.play.effect==="fade"?this._fade():this._slide()}e.data(this,"playInterval",setInterval(function(){r=s.data.current;s.data.direction="next";return s.options.play.effect==="fade"?s._fade():s._slide()},this.options.play.interval));i=e(".slidesjs-container",n);if(this.options.play.pauseOnHover){i.unbind();i.bind("mouseenter",function(){return s.stop()});i.bind("mouseleave",function(){return s.options.play.restartDelay?e.data(s,"restartDelay",setTimeout(function(){return s.play(!0)},s.options.play.restartDelay)):s.play()})}e.data(this,"playing",!0);e(".slidesjs-play",n).addClass("slidesjs-playing");if(this.options.play.swap){e(".slidesjs-play",n).hide();return e(".slidesjs-stop",n).show()}}};r.prototype.stop=function(t){var n;n=e(this.element);this.data=e.data(this);clearInterval(this.data.playInterval);this.options.play.pauseOnHover&&t&&e(".slidesjs-container",n).unbind();e.data(this,"playInterval",null);e.data(this,"playing",!1);e(".slidesjs-play",n).removeClass("slidesjs-playing");if(this.options.play.swap){e(".slidesjs-stop",n).hide();return e(".slidesjs-play",n).show()}};r.prototype._slide=function(t){var n,r,i,s,o,u,a,f,l,c,h=this;n=e(this.element);this.data=e.data(this);if(!this.data.animating&&t!==this.data.current+1){e.data(this,"animating",!0);r=this.data.current;if(t>-1){t-=1;c=t>r?1:-1;i=t>r?-this.options.width:this.options.width;o=t}else{c=this.data.direction==="next"?1:-1;i=this.data.direction==="next"?-this.options.width:this.options.width;o=r+c}o===-1&&(o=this.data.total-1);o===this.data.total&&(o=0);this._setActive(o);a=e(".slidesjs-control",n);t>-1&&a.children(":not(:eq("+r+"))").css({display:"none",left:0,zIndex:0});a.children(":eq("+o+")").css({display:"block",left:c*this.options.width,zIndex:10});this.options.callback.start(r+1);if(this.data.vendorPrefix){u=this.data.vendorPrefix;l=u+"Transform";s=u+"TransitionDuration";f=u+"TransitionTimingFunction";a[0].style[l]="translateX("+i+"px)";a[0].style[s]=this.options.effect.slide.speed+"ms";return a.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd",function(){a[0].style[l]="";a[0].style[s]="";a.children(":eq("+o+")").css({left:0});a.children(":eq("+r+")").css({display:"none",left:0,zIndex:0});e.data(h,"current",o);e.data(h,"animating",!1);a.unbind("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd");a.children(":not(:eq("+o+"))").css({display:"none",left:0,zIndex:0});h.data.touch&&h._setuptouch();return h.options.callback.complete(o+1)})}return a.stop().animate({left:i},this.options.effect.slide.speed,function(){a.css({left:0});a.children(":eq("+o+")").css({left:0});return a.children(":eq("+r+")").css({display:"none",left:0,zIndex:0},e.data(h,"current",o),e.data(h,"animating",!1),h.options.callback.complete(o+1))})}};r.prototype._fade=function(t){var n,r,i,s,o,u=this;n=e(this.element);this.data=e.data(this);if(!this.data.animating&&t!==this.data.current+1){e.data(this,"animating",!0);r=this.data.current;if(t){t-=1;o=t>r?1:-1;i=t}else{o=this.data.direction==="next"?1:-1;i=r+o}i===-1&&(i=this.data.total-1);i===this.data.total&&(i=0);this._setActive(i);s=e(".slidesjs-control",n);s.children(":eq("+i+")").css({display:"none",left:0,zIndex:10});this.options.callback.start(r+1);if(this.options.effect.fade.crossfade){s.children(":eq("+this.data.current+")").stop().fadeOut(this.options.effect.fade.speed);return s.children(":eq("+i+")").stop().fadeIn(this.options.effect.fade.speed,function(){s.children(":eq("+i+")").css({zIndex:0});e.data(u,"animating",!1);e.data(u,"current",i);return u.options.callback.complete(i+1)})}return s.children(":eq("+r+")").stop().fadeOut(this.options.effect.fade.speed,function(){s.children(":eq("+i+")").stop().fadeIn(u.options.effect.fade.speed,function(){return s.children(":eq("+i+")").css({zIndex:10})});e.data(u,"animating",!1);e.data(u,"current",i);return u.options.callback.complete(i+1)})}};r.prototype._getVendorPrefix=function(){var e,t,r,i,s;e=n.body||n.documentElement;r=e.style;i="transition";s=["Moz","Webkit","Khtml","O","ms"];i=i.charAt(0).toUpperCase()+i.substr(1);t=0;while(t<s.length){if(typeof r[s[t]+i]=="string")return s[t];t++}return!1};return e.fn[s]=function(t){return this.each(function(){if(!e.data(this,"plugin_"+s))return e.data(this,"plugin_"+s,new r(this,t))})}})(jQuery,window,document)}).call(this);
;
/*! noUiSlider - 7.0.10 - 2014-12-27 14:50:47 */
!function (a) { "use strict"; function b(a, b) { return Math.round(a / b) * b } function c(a) { return "number" == typeof a && !isNaN(a) && isFinite(a) } function d(a) { var b = Math.pow(10, 7); return Number((Math.round(a * b) / b).toFixed(7)) } function e(a, b, c) { a.addClass(b), setTimeout(function () { a.removeClass(b) }, c) } function f(a) { return Math.max(Math.min(a, 100), 0) } function g(b) { return a.isArray(b) ? b : [b] } function h(a) { var b = a.split("."); return b.length > 1 ? b[1].length : 0 } function i(a, b) { return 100 / (b - a) } function j(a, b) { return 100 * b / (a[1] - a[0]) } function k(a, b) { return j(a, a[0] < 0 ? b + Math.abs(a[0]) : b - a[0]) } function l(a, b) { return b * (a[1] - a[0]) / 100 + a[0] } function m(a, b) { for (var c = 1; a >= b[c];) c += 1; return c } function n(a, b, c) { if (c >= a.slice(-1)[0]) return 100; var d, e, f, g, h = m(c, a); return d = a[h - 1], e = a[h], f = b[h - 1], g = b[h], f + k([d, e], c) / i(f, g) } function o(a, b, c) { if (c >= 100) return a.slice(-1)[0]; var d, e, f, g, h = m(c, b); return d = a[h - 1], e = a[h], f = b[h - 1], g = b[h], l([d, e], (c - f) * i(f, g)) } function p(a, c, d, e) { if (100 === e) return e; var f, g, h = m(e, a); return d ? (f = a[h - 1], g = a[h], e - f > (g - f) / 2 ? g : f) : c[h - 1] ? a[h - 1] + b(e - a[h - 1], c[h - 1]) : e } function q(a, b, d) { var e; if ("number" == typeof b && (b = [b]), "[object Array]" !== Object.prototype.toString.call(b)) throw new Error("noUiSlider: 'range' contains invalid value."); if (e = "min" === a ? 0 : "max" === a ? 100 : parseFloat(a), !c(e) || !c(b[0])) throw new Error("noUiSlider: 'range' value isn't numeric."); d.xPct.push(e), d.xVal.push(b[0]), e ? d.xSteps.push(isNaN(b[1]) ? !1 : b[1]) : isNaN(b[1]) || (d.xSteps[0] = b[1]) } function r(a, b, c) { return b ? void (c.xSteps[a] = j([c.xVal[a], c.xVal[a + 1]], b) / i(c.xPct[a], c.xPct[a + 1])) : !0 } function s(a, b, c, d) { this.xPct = [], this.xVal = [], this.xSteps = [d || !1], this.xNumSteps = [!1], this.snap = b, this.direction = c; var e, f = []; for (e in a) a.hasOwnProperty(e) && f.push([a[e], e]); for (f.sort(function (a, b) { return a[0] - b[0] }), e = 0; e < f.length; e++) q(f[e][1], f[e][0], this); for (this.xNumSteps = this.xSteps.slice(0), e = 0; e < this.xNumSteps.length; e++) r(e, this.xNumSteps[e], this) } function t(a, b) { if (!c(b)) throw new Error("noUiSlider: 'step' is not numeric."); a.singleStep = b } function u(b, c) { if ("object" != typeof c || a.isArray(c)) throw new Error("noUiSlider: 'range' is not an object."); if (void 0 === c.min || void 0 === c.max) throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'."); b.spectrum = new s(c, b.snap, b.dir, b.singleStep) } function v(b, c) { if (c = g(c), !a.isArray(c) || !c.length || c.length > 2) throw new Error("noUiSlider: 'start' option is incorrect."); b.handles = c.length, b.start = c } function w(a, b) { if (a.snap = b, "boolean" != typeof b) throw new Error("noUiSlider: 'snap' option must be a boolean.") } function x(a, b) { if (a.animate = b, "boolean" != typeof b) throw new Error("noUiSlider: 'animate' option must be a boolean.") } function y(a, b) { if ("lower" === b && 1 === a.handles) a.connect = 1; else if ("upper" === b && 1 === a.handles) a.connect = 2; else if (b === !0 && 2 === a.handles) a.connect = 3; else { if (b !== !1) throw new Error("noUiSlider: 'connect' option doesn't match handle count."); a.connect = 0 } } function z(a, b) { switch (b) { case "horizontal": a.ort = 0; break; case "vertical": a.ort = 1; break; default: throw new Error("noUiSlider: 'orientation' option is invalid.") } } function A(a, b) { if (!c(b)) throw new Error("noUiSlider: 'margin' option must be numeric."); if (a.margin = a.spectrum.getMargin(b), !a.margin) throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.") } function B(a, b) { if (!c(b)) throw new Error("noUiSlider: 'limit' option must be numeric."); if (a.limit = a.spectrum.getMargin(b), !a.limit) throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.") } function C(a, b) { switch (b) { case "ltr": a.dir = 0; break; case "rtl": a.dir = 1, a.connect = [0, 2, 1, 3][a.connect]; break; default: throw new Error("noUiSlider: 'direction' option was not recognized.") } } function D(a, b) { if ("string" != typeof b) throw new Error("noUiSlider: 'behaviour' must be a string containing options."); var c = b.indexOf("tap") >= 0, d = b.indexOf("drag") >= 0, e = b.indexOf("fixed") >= 0, f = b.indexOf("snap") >= 0; a.events = { tap: c || f, drag: d, fixed: e, snap: f } } function E(a, b) { if (a.format = b, "function" == typeof b.to && "function" == typeof b.from) return !0; throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.") } function F(b) { var c, d = { margin: 0, limit: 0, animate: !0, format: V }; return c = { step: { r: !1, t: t }, start: { r: !0, t: v }, connect: { r: !0, t: y }, direction: { r: !0, t: C }, snap: { r: !1, t: w }, animate: { r: !1, t: x }, range: { r: !0, t: u }, orientation: { r: !1, t: z }, margin: { r: !1, t: A }, limit: { r: !1, t: B }, behaviour: { r: !0, t: D }, format: { r: !1, t: E } }, b = a.extend({ connect: !1, direction: "ltr", behaviour: "tap", orientation: "horizontal" }, b), a.each(c, function (a, c) { if (void 0 === b[a]) { if (c.r) throw new Error("noUiSlider: '" + a + "' is required."); return !0 } c.t(d, b[a]) }), d.style = d.ort ? "top" : "left", d } function G(a, b, c) { var d = a + b[0], e = a + b[1]; return c ? (0 > d && (e += Math.abs(d)), e > 100 && (d -= e - 100), [f(d), f(e)]) : [d, e] } function H(a) { a.preventDefault(); var b, c, d = 0 === a.type.indexOf("touch"), e = 0 === a.type.indexOf("mouse"), f = 0 === a.type.indexOf("pointer"), g = a; return 0 === a.type.indexOf("MSPointer") && (f = !0), a.originalEvent && (a = a.originalEvent), d && (b = a.changedTouches[0].pageX, c = a.changedTouches[0].pageY), (e || f) && (f || void 0 !== window.pageXOffset || (window.pageXOffset = document.documentElement.scrollLeft, window.pageYOffset = document.documentElement.scrollTop), b = a.clientX + window.pageXOffset, c = a.clientY + window.pageYOffset), g.points = [b, c], g.cursor = e, g } function I(b, c) { var d = a("<div><div/></div>").addClass(U[2]), e = ["-lower", "-upper"]; return b && e.reverse(), d.children().addClass(U[3] + " " + U[3] + e[c]), d } function J(a, b, c) { switch (a) { case 1: b.addClass(U[7]), c[0].addClass(U[6]); break; case 3: c[1].addClass(U[6]); case 2: c[0].addClass(U[7]); case 0: b.addClass(U[6]) } } function K(a, b, c) { var d, e = []; for (d = 0; a > d; d += 1) e.push(I(b, d).appendTo(c)); return e } function L(b, c, d) { return d.addClass([U[0], U[8 + b], U[4 + c]].join(" ")), a("<div/>").appendTo(d).addClass(U[1]) } function M(b, c, d) { function i() { return C[["width", "height"][c.ort]]() } function j(a) { var b, c = [E.val()]; for (b = 0; b < a.length; b += 1) E.trigger(a[b], c) } function k(a) { return 1 === a.length ? a[0] : c.dir ? a.reverse() : a } function l(a) { return function (b, c) { E.val([a ? null : c, a ? c : null], !0) } } function m(b) { var c = a.inArray(b, N); E[0].linkAPI && E[0].linkAPI[b] && E[0].linkAPI[b].change(M[c], D[c].children(), E) } function n(b, d) { var e = a.inArray(b, N); return d && d.appendTo(D[e].children()), c.dir && c.handles > 1 && (e = 1 === e ? 0 : 1), l(e) } function o() { var a, b; for (a = 0; a < N.length; a += 1) this.linkAPI && this.linkAPI[b = N[a]] && this.linkAPI[b].reconfirm(b) } function p(a, b, d, e) { return a = a.replace(/\s/g, S + " ") + S, b.on(a, function (a) { return E.attr("disabled") ? !1 : E.hasClass(U[14]) ? !1 : (a = H(a), a.calcPoint = a.points[c.ort], void d(a, e)) }) } function q(a, b) { var c, d = b.handles || D, e = !1, f = 100 * (a.calcPoint - b.start) / i(), g = d[0][0] !== D[0][0] ? 1 : 0; c = G(f, b.positions, d.length > 1), e = v(d[0], c[g], 1 === d.length), d.length > 1 && (e = v(d[1], c[g ? 0 : 1], !1) || e), e && j(["slide"]) } function r(b) { a("." + U[15]).removeClass(U[15]), b.cursor && a("body").css("cursor", "").off(S), Q.off(S), E.removeClass(U[12]), j(["set", "change"]) } function s(b, c) { 1 === c.handles.length && c.handles[0].children().addClass(U[15]), b.stopPropagation(), p(T.move, Q, q, { start: b.calcPoint, handles: c.handles, positions: [F[0], F[D.length - 1]] }), p(T.end, Q, r, null), b.cursor && (a("body").css("cursor", a(b.target).css("cursor")), D.length > 1 && E.addClass(U[12]), a("body").on("selectstart" + S, !1)) } function t(b) { var d, f = b.calcPoint, g = 0; b.stopPropagation(), a.each(D, function () { g += this.offset()[c.style] }), g = g / 2 > f || 1 === D.length ? 0 : 1, f -= C.offset()[c.style], d = 100 * f / i(), c.events.snap || e(E, U[14], 300), v(D[g], d), j(["slide", "set", "change"]), c.events.snap && s(b, { handles: [D[g]] }) } function u(a) { var b, c; if (!a.fixed) for (b = 0; b < D.length; b += 1) p(T.start, D[b].children(), s, { handles: [D[b]] }); a.tap && p(T.start, C, t, { handles: D }), a.drag && (c = C.find("." + U[7]).addClass(U[10]), a.fixed && (c = c.add(C.children().not(c).children())), p(T.start, c, s, { handles: D })) } function v(a, b, d) { var e = a[0] !== D[0][0] ? 1 : 0, g = F[0] + c.margin, h = F[1] - c.margin, i = F[0] + c.limit, j = F[1] - c.limit; return D.length > 1 && (b = e ? Math.max(b, g) : Math.min(b, h)), d !== !1 && c.limit && D.length > 1 && (b = e ? Math.min(b, i) : Math.max(b, j)), b = I.getStep(b), b = f(parseFloat(b.toFixed(7))), b === F[e] ? !1 : (a.css(c.style, b + "%"), a.is(":first-child") && a.toggleClass(U[17], b > 50), F[e] = b, M[e] = I.fromStepping(b), m(N[e]), !0) } function w(a, b) { var d, e, f; for (c.limit && (a += 1), d = 0; a > d; d += 1) e = d % 2, f = b[e], null !== f && f !== !1 && ("number" == typeof f && (f = String(f)), f = c.format.from(f), (f === !1 || isNaN(f) || v(D[e], I.toStepping(f), d === 3 - c.dir) === !1) && m(N[e])) } function x(a) { if (E[0].LinkIsEmitting) return this; var b, d = g(a); return c.dir && c.handles > 1 && d.reverse(), c.animate && -1 !== F[0] && e(E, U[14], 300), b = D.length > 1 ? 3 : 1, 1 === d.length && (b = 1), w(b, d), j(["set"]), this } function y() { var a, b = []; for (a = 0; a < c.handles; a += 1) b[a] = c.format.to(M[a]); return k(b) } function z() { return a(this).off(S).removeClass(U.join(" ")).empty(), delete this.LinkUpdate, delete this.LinkConfirm, delete this.LinkDefaultFormatter, delete this.LinkDefaultFlag, delete this.reappend, delete this.vGet, delete this.vSet, delete this.getCurrentStep, delete this.getInfo, delete this.destroy, d } function A() { var b = a.map(F, function (a, b) { var c = I.getApplicableStep(a), d = h(String(c[2])), e = M[b], f = 100 === a ? null : c[2], g = Number((e - c[2]).toFixed(d)), i = 0 === a ? null : g >= c[1] ? c[2] : c[0] || !1; return [[i, f]] }); return k(b) } function B() { return d } var C, D, E = a(b), F = [-1, -1], I = c.spectrum, M = [], N = ["lower", "upper"].slice(0, c.handles); if (c.dir && N.reverse(), b.LinkUpdate = m, b.LinkConfirm = n, b.LinkDefaultFormatter = c.format, b.LinkDefaultFlag = "lower", b.reappend = o, E.hasClass(U[0])) throw new Error("Slider was already initialized."); C = L(c.dir, c.ort, E), D = K(c.handles, c.dir, C), J(c.connect, E, D), u(c.events), b.vSet = x, b.vGet = y, b.destroy = z, b.getCurrentStep = A, b.getOriginalOptions = B, b.getInfo = function () { return [I, c.style, c.ort] }, E.val(c.start) } function N(a) { var b = F(a, this); return this.each(function () { M(this, b, a) }) } function O(b) { return this.each(function () { if (!this.destroy) return void a(this).noUiSlider(b); var c = a(this).val(), d = this.destroy(), e = a.extend({}, d, b); a(this).noUiSlider(e), this.reappend(), d.start === e.start && a(this).val(c) }) } function P() { return this[0][arguments.length ? "vSet" : "vGet"].apply(this[0], arguments) } var Q = a(document), R = a.fn.val, S = ".nui", T = window.navigator.pointerEnabled ? { start: "pointerdown", move: "pointermove", end: "pointerup" } : window.navigator.msPointerEnabled ? { start: "MSPointerDown", move: "MSPointerMove", end: "MSPointerUp" } : { start: "mousedown touchstart", move: "mousemove touchmove", end: "mouseup touchend" }, U = ["noUi-target", "noUi-base", "noUi-origin", "noUi-handle", "noUi-horizontal", "noUi-vertical", "noUi-background", "noUi-connect", "noUi-ltr", "noUi-rtl", "noUi-dragable", "", "noUi-state-drag", "", "noUi-state-tap", "noUi-active", "", "noUi-stacking"]; s.prototype.getMargin = function (a) { return 2 === this.xPct.length ? j(this.xVal, a) : !1 }, s.prototype.toStepping = function (a) { return a = n(this.xVal, this.xPct, a), this.direction && (a = 100 - a), a }, s.prototype.fromStepping = function (a) { return this.direction && (a = 100 - a), d(o(this.xVal, this.xPct, a)) }, s.prototype.getStep = function (a) { return this.direction && (a = 100 - a), a = p(this.xPct, this.xSteps, this.snap, a), this.direction && (a = 100 - a), a }, s.prototype.getApplicableStep = function (a) { var b = m(a, this.xPct), c = 100 === a ? 2 : 1; return [this.xNumSteps[b - 2], this.xVal[b - c], this.xNumSteps[b - c]] }, s.prototype.convert = function (a) { return this.getStep(this.toStepping(a)) }; var V = { to: function (a) { return a.toFixed(2) }, from: Number }; a.fn.val = function (b) { function c(a) { return a.hasClass(U[0]) ? P : R } if (!arguments.length) { var d = a(this[0]); return c(d).call(d) } var e = a.isFunction(b); return this.each(function (d) { var f = b, g = a(this); e && (f = b.call(this, d, g.val())), c(g).call(g, f) }) }, a.fn.noUiSlider = function (a, b) { switch (a) { case "step": return this[0].getCurrentStep(); case "options": return this[0].getOriginalOptions() } return (b ? O : N).call(this, a) } }(window.jQuery || window.Zepto);;
if (fakewaffle === undefined) {
    var fakewaffle = {};
}

fakewaffle.responsiveTabs = function (collapseDisplayed) {
    "use strict";
    fakewaffle.currentPosition = 'tabs';

    var tabGroups = $('.nav-tabs.responsive'),
        hidden    = '',
        visible   = '';

    if (collapseDisplayed === undefined) {
        collapseDisplayed = ['xs', 'sm'];
    }

    $.each(collapseDisplayed, function () {
        hidden  += ' hidden-' + this;
        visible += ' visible-' + this;
    });

    $.each(tabGroups, function () {
        var $tabGroup   = $(this),
            tabs        = $tabGroup.find('li a'),
            collapseDiv = $("<div></div>", {
                "class" : "panel-group responsive" + visible,
                "id"    : 'collapse-' + $tabGroup.attr('id')
            });

        $.each(tabs, function () {
            var $this          = $(this),
                active         = '',
                oldLinkClass   = $this.attr('class') === undefined ? '' : $this.attr('class'),
                newLinkClass   = 'accordion-toggle',
                oldParentClass = $this.parent().attr('class') === undefined ? '' : $this.parent().attr('class'),
                newParentClass = 'panel panel-default';

            if (oldLinkClass.length > 0) {
                newLinkClass += ' ' + oldLinkClass;
            };

            if (oldParentClass.length > 0) {
                oldParentClass = oldParentClass.replace(/\bactive\b/g, '');
                newParentClass += ' ' + oldParentClass;
                newParentClass = newParentClass.replace(/\s{2,}/g, ' ');
                newParentClass = newParentClass.replace(/^\s+|\s+$/g, '');
            };

            if ($this.parent().hasClass('active')) {
                active = ' in';
            }

            collapseDiv.append(
                $('<div>').attr('class', newParentClass).html(
                    $('<div>').attr('class', 'panel-heading').html(
                        $('<h4>').attr('class', 'panel-title').html(
                            $('<a>', {
                                'class' : newLinkClass,
                                'data-toggle': 'collapse',
                                'data-parent' : '#collapse-' + $tabGroup.attr('id'),
                                'href' : '#collapse-' + $this.attr('href').replace(/#/g, ''),
                                'html': $this.html()
                            })
                        )
                    )
                ).append(
                    $('<div>', {
                        'id' : 'collapse-' + $this.attr('href').replace(/#/g, ''),
                        'class' : 'panel-collapse collapse' + active
                    }).html(
                        $('<div>').attr('class', 'panel-body').html('')
                    )
                )
            );
        });

        collapseDiv.insertAfter($tabGroup);
        $tabGroup.addClass(hidden);
        $('.tab-content.responsive').addClass(hidden);
    });

    fakewaffle.checkResize();
    fakewaffle.bindTabToCollapse();
};

fakewaffle.checkResize = function () {
    "use strict";
    if ($(".panel-group.responsive").is(":visible") === true && fakewaffle.currentPosition === 'tabs') {
        fakewaffle.toggleResponsiveTabContent();
        fakewaffle.currentPosition = 'panel';
    } else if ($(".panel-group.responsive").is(":visible") === false && fakewaffle.currentPosition === 'panel') {
        fakewaffle.toggleResponsiveTabContent();
        fakewaffle.currentPosition = 'tabs';
    }

};

fakewaffle.toggleResponsiveTabContent = function () {
    "use strict";
    var tabGroups = $('.nav-tabs.responsive');

    $.each(tabGroups, function () {
        var tabs = $(this).find('li a');

        $.each(tabs, function () {
            if (!$(this).attr('href').startsWith('http')) {
                var href = $(this).attr('href').replace(/#/g, ''),
                    tabId = "#" + href,
                    panelId = "#collapse-" + href,
                    tabContent = $(tabId).html(),
                    panelContent = $(panelId + " div:first-child").html();

                $(tabId).html(panelContent);
                $(panelId + " div:first-child").html(tabContent);
            }            
        });

    });
};

fakewaffle.bindTabToCollapse = function () {
    "use strict";
    var tabs     = $('.nav-tabs.responsive').find('li'),
        collapse = $(".panel-group.responsive").find('.panel-collapse');

    tabs.on('shown.bs.tab', function (e) {
        var $current  = $($(e.target)[0].hash.replace(/#/, '#collapse-'));
        $current.collapse('show');

        if($(window).width() < 768) {
            setTimeout(function() {
                $('html, body').animate({
                    scrollTop: $current.offset().top - 100
                }, 500);
            }, 600);
        }

        if(e.relatedTarget){
            var $previous = $($(e.relatedTarget)[0].hash.replace(/#/, '#collapse-'));
            $previous.collapse('hide');
        }
    });

    collapse.on('show.bs.collapse', function (e) {
        var current = $(e.target).context.id.replace(/collapse-/g, '#');
        $('a[href="' + current + '"]').tab('show');
        $(this).find('i.fa').toggleClass('fa-caret-up').toggleClass('fa-caret-down');

    });
}

$(window).resize(function () {
    "use strict";
    fakewaffle.checkResize();
});
;
/* =========================================================
 * bootstrap-datepicker.js
 * http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Copyright 2012 Stefan Petre
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

!function( $ ) {

    // Picker object

    var Datepicker = function(element, options){
        this.element = $(element);
        this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy');
        this.picker = $(DPGlobal.template)
                            .appendTo('body')
                            .on({
                                click: $.proxy(this.click, this)//,
                                //mousedown: $.proxy(this.mousedown, this)
                            });
        this.isInput = this.element.is('input');
        this.component = this.element.is('.date') ? this.element.find('.add-on') : false;

        if (this.isInput) {
            this.element.on({
                focus: $.proxy(this.show, this),
                //blur: $.proxy(this.hide, this),
                keyup: $.proxy(this.update, this)
            });
        } else {
            if (this.component){
                this.component.on('click', $.proxy(this.show, this));
            } else {
                this.element.on('click', $.proxy(this.show, this));
            }
        }

        this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
        if (typeof this.minViewMode === 'string') {
            switch (this.minViewMode) {
                case 'months':
                    this.minViewMode = 1;
                    break;
                case 'years':
                    this.minViewMode = 2;
                    break;
                default:
                    this.minViewMode = 0;
                    break;
            }
        }
        this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
        if (typeof this.viewMode === 'string') {
            switch (this.viewMode) {
                case 'months':
                    this.viewMode = 1;
                    break;
                case 'years':
                    this.viewMode = 2;
                    break;
                default:
                    this.viewMode = 0;
                    break;
            }
        }
        this.startViewMode = this.viewMode;
        this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
        this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
        this.onRender = options.onRender;
        this.fillDow();
        this.fillMonths();
        this.update();
        this.showMode();
    };

    Datepicker.prototype = {
        constructor: Datepicker,

        show: function(e) {
            this.picker.show();
            this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
            this.place();
            $(window).on('resize scroll', $.proxy(this.place, this));
            $('.modal').on('scroll', $.proxy(this.place, this));

            if (e ) {
                e.stopPropagation();
                e.preventDefault();
            }
            if (!this.isInput) {
            }
            var that = this;
            $(document).on('mousedown', function(ev){
                if ($(ev.target).closest('.datepicker').length == 0) {
                    that.hide();
                }
            });
            this.element.trigger({
                type: 'show',
                date: this.date
            });
        },

        hide: function(){
            this.picker.hide();
            $(window).off('resize', this.place);
            $('.modal').off('scroll', $.proxy(this.place, this));
            this.viewMode = this.startViewMode;
            this.showMode();
            if (!this.isInput) {
                $(document).off('mousedown', this.hide);
            }
            //this.set();
            this.element.trigger({
                type: 'hide',
                date: this.date
            });
        },

        set: function() {
            var formated = DPGlobal.formatDate(this.date, this.format);
            if (!this.isInput) {
                if (this.component){
                    this.element.find('input').prop('value', formated);
                }
                this.element.data('date', formated);
            } else {
                this.element.prop('value', formated);
            }
        },

        setValue: function(newDate) {
            if (typeof newDate === 'string') {
                this.date = DPGlobal.parseDate(newDate, this.format);
            } else {
                this.date = new Date(newDate);
            }
            this.set();
            this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
            this.fill();
        },

        place: function(){
            var offset = this.component ? this.component.offset() : this.element.offset();
            this.picker.css({
                top: offset.top + this.height,
                left: offset.left
            });
        },

        update: function(newDate){
            this.date = DPGlobal.parseDate(
                typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
                this.format
            );
            this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
            this.fill();
        },

        fillDow: function(){
            var dowCnt = this.weekStart;
            var html = '<tr>';
            while (dowCnt < this.weekStart + 7) {
                html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
            }
            html += '</tr>';
            this.picker.find('.datepicker-days thead').append(html);
        },

        fillMonths: function(){
            var html = '';
            var i = 0
            while (i < 12) {
                html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
            }
            this.picker.find('.datepicker-months td').append(html);
        },

        fill: function() {
            var d = new Date(this.viewDate),
                year = d.getFullYear(),
                month = d.getMonth(),
                currentDate = this.date.valueOf();
            this.picker.find('.datepicker-days th:eq(1)')
                        .text(DPGlobal.dates.months[month]+' '+year);
            var prevMonth = new Date(year, month-1, 28,0,0,0,0),
                day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
            prevMonth.setDate(day);
            prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
            var nextMonth = new Date(prevMonth);
            nextMonth.setDate(nextMonth.getDate() + 42);
            nextMonth = nextMonth.valueOf();
            var html = [];
            var clsName,
                prevY,
                prevM;
            while(prevMonth.valueOf() < nextMonth) {
                if (prevMonth.getDay() === this.weekStart) {
                    html.push('<tr>');
                }
                clsName = this.onRender(prevMonth);
                prevY = prevMonth.getFullYear();
                prevM = prevMonth.getMonth();
                if ((prevM < month &&  prevY === year) ||  prevY < year) {
                    clsName += ' old';
                } else if ((prevM > month && prevY === year) || prevY > year) {
                    clsName += ' new';
                }
                if (prevMonth.valueOf() === currentDate) {
                    clsName += ' active';
                }
                html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
                if (prevMonth.getDay() === this.weekEnd) {
                    html.push('</tr>');
                }
                prevMonth.setDate(prevMonth.getDate()+1);
            }
            this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
            var currentYear = this.date.getFullYear();

            var months = this.picker.find('.datepicker-months')
                        .find('th:eq(1)')
                            .text(year)
                            .end()
                        .find('span').removeClass('active');
            if (currentYear === year) {
                months.eq(this.date.getMonth()).addClass('active');
            }

            html = '';
            year = parseInt(year/10, 10) * 10;
            var yearCont = this.picker.find('.datepicker-years')
                                .find('th:eq(1)')
                                    .text(year + '-' + (year + 9))
                                    .end()
                                .find('td');
            year -= 1;
            for (var i = -1; i < 11; i++) {
                html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
                year += 1;
            }
            yearCont.html(html);
        },

        click: function(e) {
            e.stopPropagation();
            e.preventDefault();
            var target = $(e.target).closest('span, td, th');
            if (target.length === 1) {
                switch(target[0].nodeName.toLowerCase()) {
                    case 'th':
                        switch(target[0].className) {
                            case 'switch':
                                this.showMode(1);
                                break;
                            case 'prev':
                            case 'next':
                                this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
                                    this.viewDate,
                                    this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
                                    DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
                                );
                                this.fill();
                                this.set();
                                break;
                        }
                        break;
                    case 'span':
                        if (target.is('.month')) {
                            var month = target.parent().find('span').index(target);
                            this.viewDate.setMonth(month);
                        } else {
                            var year = parseInt(target.text(), 10)||0;
                            this.viewDate.setFullYear(year);
                        }
                        if (this.viewMode !== 0) {
                            this.date = new Date(this.viewDate);
                            this.element.trigger({
                                type: 'changeDate',
                                date: this.date,
                                viewMode: DPGlobal.modes[this.viewMode].clsName
                            });
                        }
                        this.showMode(-1);
                        this.fill();
                        this.set();
                        break;
                    case 'td':
                        if (target.is('.day') && !target.is('.disabled')){
                            var day = parseInt(target.text(), 10)||1;
                            var month = this.viewDate.getMonth();
                            if (target.is('.old')) {
                                month -= 1;
                            } else if (target.is('.new')) {
                                month += 1;
                            }
                            var year = this.viewDate.getFullYear();
                            this.date = new Date(year, month, day,0,0,0,0);
                            this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
                            this.fill();
                            this.set();
                            this.element.trigger({
                                type: 'changeDate',
                                date: this.date,
                                viewMode: DPGlobal.modes[this.viewMode].clsName
                            });
                        }
                        break;
                }
            }
        },

        mousedown: function(e){
            e.stopPropagation();
            e.preventDefault();
        },

        showMode: function(dir) {
            if (dir) {
                this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
            }
            this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
        }
    };

    $.fn.datepicker = function ( option, val ) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data('datepicker'),
                options = typeof option === 'object' && option;
            if (!data) {
                $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
            }
            if (typeof option === 'string') data[option](val);
        });
    };

    $.fn.datepicker.defaults = {
        onRender: function(date) {
            return '';
        }
    };
    $.fn.datepicker.Constructor = Datepicker;

    var DPGlobal = {
        modes: [
            {
                clsName: 'days',
                navFnc: 'Month',
                navStep: 1
            },
            {
                clsName: 'months',
                navFnc: 'FullYear',
                navStep: 1
            },
            {
                clsName: 'years',
                navFnc: 'FullYear',
                navStep: 10
        }],
        dates:{
            days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"],
            daysShort: ["Sön", "Mån", "Tis", "Ons", "Tors", "Fre", "Lör", "Sön"],
            daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö", "Sö"],
            months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"]
        },
        isLeapYear: function (year) {
            return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
        },
        getDaysInMonth: function (year, month) {
            return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
        },
        parseFormat: function(format){
            var separator = format.match(/[.\/\-\s].*?/),
                parts = format.split(/\W+/);
            if (!separator || !parts || parts.length === 0){
                throw new Error("Invalid date format.");
            }
            return {separator: separator, parts: parts};
        },
        parseDate: function(date, format) {
            var parts = date.split(format.separator),
                date = new Date(),
                val;
            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
            date.setMilliseconds(0);
            if (parts.length === format.parts.length) {
                var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
                for (var i=0, cnt = format.parts.length; i < cnt; i++) {
                    val = parseInt(parts[i], 10)||1;
                    switch(format.parts[i]) {
                        case 'dd':
                        case 'd':
                            day = val;
                            date.setDate(val);
                            break;
                        case 'mm':
                        case 'm':
                            month = val - 1;
                            date.setMonth(val - 1);
                            break;
                        case 'yy':
                            year = 2000 + val;
                            date.setFullYear(2000 + val);
                            break;
                        case 'yyyy':
                            year = val;
                            date.setFullYear(val);
                            break;
                    }
                }
                date = new Date(year, month, day, 0 ,0 ,0);
            }
            return date;
        },
        formatDate: function(date, format){
            var val = {
                d: date.getDate(),
                m: date.getMonth() + 1,
                yy: date.getFullYear().toString().substring(2),
                yyyy: date.getFullYear()
            };
            val.dd = (val.d < 10 ? '0' : '') + val.d;
            val.mm = (val.m < 10 ? '0' : '') + val.m;
            var date = [];
            for (var i=0, cnt = format.parts.length; i < cnt; i++) {
                date.push(val[format.parts[i]]);
            }
            return date.join(format.separator);
        },
        headTemplate: '<thead>'+
                            '<tr>'+
                                '<th class="prev">&lsaquo;</th>'+
                                '<th colspan="5" class="switch"></th>'+
                                '<th class="next">&rsaquo;</th>'+
                            '</tr>'+
                        '</thead>',
        contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
    };
    DPGlobal.template = '<div class="datepicker dropdown-menu">'+
                            '<div class="datepicker-days">'+
                                '<table class=" table-condensed">'+
                                    DPGlobal.headTemplate+
                                    '<tbody></tbody>'+
                                '</table>'+
                            '</div>'+
                            '<div class="datepicker-months">'+
                                '<table class="table-condensed">'+
                                    DPGlobal.headTemplate+
                                    DPGlobal.contTemplate+
                                '</table>'+
                            '</div>'+
                            '<div class="datepicker-years">'+
                                '<table class="table-condensed">'+
                                    DPGlobal.headTemplate+
                                    DPGlobal.contTemplate+
                                '</table>'+
                            '</div>'+
                        '</div>';

}( window.jQuery );;
!function(){function a(b,c,d){var e=a.resolve(b);if(null==e){d=d||b,c=c||"root";var f=new Error('Failed to require "'+d+'" from "'+c+'"');throw f.path=d,f.parent=c,f.require=!0,f}var g=a.modules[e];if(!g._resolving&&!g.exports){var h={};h.exports={},h.client=h.component=!0,g._resolving=!0,g.call(this,h.exports,a.relative(e),h),delete g._resolving,g.exports=h.exports}return g.exports}a.modules={},a.aliases={},a.resolve=function(b){"/"===b.charAt(0)&&(b=b.slice(1));for(var c=[b,b+".js",b+".json",b+"/index.js",b+"/index.json"],d=0;d<c.length;d++){var b=c[d];if(a.modules.hasOwnProperty(b))return b;if(a.aliases.hasOwnProperty(b))return a.aliases[b]}},a.normalize=function(a,b){var c=[];if("."!=b.charAt(0))return b;a=a.split("/"),b=b.split("/");for(var d=0;d<b.length;++d)".."==b[d]?a.pop():"."!=b[d]&&""!=b[d]&&c.push(b[d]);return a.concat(c).join("/")},a.register=function(b,c){a.modules[b]=c},a.alias=function(b,c){if(!a.modules.hasOwnProperty(b))throw new Error('Failed to alias "'+b+'", it does not exist');a.aliases[c]=b},a.relative=function(b){function c(a,b){for(var c=a.length;c--;)if(a[c]===b)return c;return-1}function d(c){var e=d.resolve(c);return a(e,b,c)}var e=a.normalize(b,"..");return d.resolve=function(d){var f=d.charAt(0);if("/"==f)return d.slice(1);if("."==f)return a.normalize(e,d);var g=b.split("/"),h=c(g,"deps")+1;return h||(h=0),d=g.slice(0,h+1).join("/")+"/deps/"+d},d.exists=function(b){return a.modules.hasOwnProperty(d.resolve(b))},d},a.register("component-classes/index.js",function(a,b,c){function d(a){if(!a)throw new Error("A DOM element reference is required");this.el=a,this.list=a.classList}var e=b("indexof"),f=/\s+/,g=Object.prototype.toString;c.exports=function(a){return new d(a)},d.prototype.add=function(a){if(this.list)return this.list.add(a),this;var b=this.array(),c=e(b,a);return~c||b.push(a),this.el.className=b.join(" "),this},d.prototype.remove=function(a){if("[object RegExp]"==g.call(a))return this.removeMatching(a);if(this.list)return this.list.remove(a),this;var b=this.array(),c=e(b,a);return~c&&b.splice(c,1),this.el.className=b.join(" "),this},d.prototype.removeMatching=function(a){for(var b=this.array(),c=0;c<b.length;c++)a.test(b[c])&&this.remove(b[c]);return this},d.prototype.toggle=function(a,b){return this.list?("undefined"!=typeof b?b!==this.list.toggle(a,b)&&this.list.toggle(a):this.list.toggle(a),this):("undefined"!=typeof b?b?this.add(a):this.remove(a):this.has(a)?this.remove(a):this.add(a),this)},d.prototype.array=function(){var a=this.el.className.replace(/^\s+|\s+$/g,""),b=a.split(f);return""===b[0]&&b.shift(),b},d.prototype.has=d.prototype.contains=function(a){return this.list?this.list.contains(a):!!~e(this.array(),a)}}),a.register("segmentio-extend/index.js",function(a,b,c){c.exports=function(a){for(var b,c=Array.prototype.slice.call(arguments,1),d=0;b=c[d];d++)if(b)for(var e in b)a[e]=b[e];return a}}),a.register("component-indexof/index.js",function(a,b,c){c.exports=function(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c<a.length;++c)if(a[c]===b)return c;return-1}}),a.register("component-event/index.js",function(a){var b=window.addEventListener?"addEventListener":"attachEvent",c=window.removeEventListener?"removeEventListener":"detachEvent",d="addEventListener"!==b?"on":"";a.bind=function(a,c,e,f){return a[b](d+c,e,f||!1),e},a.unbind=function(a,b,e,f){return a[c](d+b,e,f||!1),e}}),a.register("timoxley-to-array/index.js",function(a,b,c){function d(a){return"[object Array]"===Object.prototype.toString.call(a)}c.exports=function(a){if("undefined"==typeof a)return[];if(null===a)return[null];if(a===window)return[window];if("string"==typeof a)return[a];if(d(a))return a;if("number"!=typeof a.length)return[a];if("function"==typeof a&&a instanceof Function)return[a];for(var b=[],c=0;c<a.length;c++)(Object.prototype.hasOwnProperty.call(a,c)||c in a)&&b.push(a[c]);return b.length?b:[]}}),a.register("javve-events/index.js",function(a,b){var c=b("event"),d=b("to-array");a.bind=function(a,b,e,f){a=d(a);for(var g=0;g<a.length;g++)c.bind(a[g],b,e,f)},a.unbind=function(a,b,e,f){a=d(a);for(var g=0;g<a.length;g++)c.unbind(a[g],b,e,f)}}),a.register("javve-get-by-class/index.js",function(a,b,c){c.exports=function(){return document.getElementsByClassName?function(a,b,c){return c?a.getElementsByClassName(b)[0]:a.getElementsByClassName(b)}:document.querySelector?function(a,b,c){return b="."+b,c?a.querySelector(b):a.querySelectorAll(b)}:function(a,b,c){var d=[],e="*";null==a&&(a=document);for(var f=a.getElementsByTagName(e),g=f.length,h=new RegExp("(^|\\s)"+b+"(\\s|$)"),i=0,j=0;g>i;i++)if(h.test(f[i].className)){if(c)return f[i];d[j]=f[i],j++}return d}}()}),a.register("javve-get-attribute/index.js",function(a,b,c){c.exports=function(a,b){var c=a.getAttribute&&a.getAttribute(b)||null;if(!c)for(var d=a.attributes,e=d.length,f=0;e>f;f++)void 0!==b[f]&&b[f].nodeName===b&&(c=b[f].nodeValue);return c}}),a.register("javve-natural-sort/index.js",function(a,b,c){c.exports=function(a,b,c){var d,e,f=/(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,g=/(^[ ]*|[ ]*$)/g,h=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,i=/^0x[0-9a-f]+$/i,j=/^0/,c=c||{},k=function(a){return c.insensitive&&(""+a).toLowerCase()||""+a},l=k(a).replace(g,"")||"",m=k(b).replace(g,"")||"",n=l.replace(f,"\x00$1\x00").replace(/\0$/,"").replace(/^\0/,"").split("\x00"),o=m.replace(f,"\x00$1\x00").replace(/\0$/,"").replace(/^\0/,"").split("\x00"),p=parseInt(l.match(i))||1!=n.length&&l.match(h)&&Date.parse(l),q=parseInt(m.match(i))||p&&m.match(h)&&Date.parse(m)||null,r=c.desc?-1:1;if(q){if(q>p)return-1*r;if(p>q)return 1*r}for(var s=0,t=Math.max(n.length,o.length);t>s;s++){if(d=!(n[s]||"").match(j)&&parseFloat(n[s])||n[s]||0,e=!(o[s]||"").match(j)&&parseFloat(o[s])||o[s]||0,isNaN(d)!==isNaN(e))return isNaN(d)?1:-1;if(typeof d!=typeof e&&(d+="",e+=""),e>d)return-1*r;if(d>e)return 1*r}return 0}}),a.register("javve-to-string/index.js",function(a,b,c){c.exports=function(a){return a=void 0===a?"":a,a=null===a?"":a,a=a.toString()}}),a.register("component-type/index.js",function(a,b,c){var d=Object.prototype.toString;c.exports=function(a){switch(d.call(a)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}return null===a?"null":void 0===a?"undefined":a!==a?"nan":a&&1===a.nodeType?"element":typeof a.valueOf()}}),a.register("list.js/index.js",function(a,b,c){!function(a,d){"use strict";var e=a.document,f=b("get-by-class"),g=b("extend"),h=b("indexof"),i=function(a,c,i){var j,k=this,l=b("./src/item")(k),m=b("./src/add-async")(k),n=b("./src/parse")(k);j={start:function(){k.listClass="list",k.searchClass="search",k.sortClass="sort",k.page=200,k.i=1,k.items=[],k.visibleItems=[],k.matchingItems=[],k.searched=!1,k.filtered=!1,k.handlers={updated:[]},k.plugins={},k.helpers={getByClass:f,extend:g,indexOf:h},g(k,c),k.listContainer="string"==typeof a?e.getElementById(a):a,k.listContainer&&(k.list=f(k.listContainer,k.listClass,!0),k.templater=b("./src/templater")(k),k.search=b("./src/search")(k),k.filter=b("./src/filter")(k),k.sort=b("./src/sort")(k),this.items(),k.update(),this.plugins())},items:function(){n(k.list),i!==d&&k.add(i)},plugins:function(){for(var a=0;a<k.plugins.length;a++){var b=k.plugins[a];k[b.name]=b,b.init(k)}}},this.add=function(a,b){if(b)return m(a,b),void 0;var c=[],e=!1;a[0]===d&&(a=[a]);for(var f=0,g=a.length;g>f;f++){var h=null;a[f]instanceof l?(h=a[f],h.reload()):(e=k.items.length>k.page?!0:!1,h=new l(a[f],d,e)),k.items.push(h),c.push(h)}return k.update(),c},this.show=function(a,b){return this.i=a,this.page=b,k.update(),k},this.remove=function(a,b,c){for(var d=0,e=0,f=k.items.length;f>e;e++)k.items[e].values()[a]==b&&(k.templater.remove(k.items[e],c),k.items.splice(e,1),f--,e--,d++);return k.update(),d},this.get=function(a,b){for(var c=[],d=0,e=k.items.length;e>d;d++){var f=k.items[d];f.values()[a]==b&&c.push(f)}return c},this.size=function(){return k.items.length},this.clear=function(){return k.templater.clear(),k.items=[],k},this.on=function(a,b){return k.handlers[a].push(b),k},this.off=function(a,b){var c=k.handlers[a],d=h(c,b);return d>-1&&c.splice(d,1),k},this.trigger=function(a){for(var b=k.handlers[a].length;b--;)k.handlers[a][b](k);return k},this.reset={filter:function(){for(var a=k.items,b=a.length;b--;)a[b].filtered=!1;return k},search:function(){for(var a=k.items,b=a.length;b--;)a[b].found=!1;return k}},this.update=function(){var a=k.items,b=a.length;k.visibleItems=[],k.matchingItems=[],k.templater.clear();for(var c=0;b>c;c++)a[c].matching()&&k.matchingItems.length+1>=k.i&&k.visibleItems.length<k.page?(a[c].show(),k.visibleItems.push(a[c]),k.matchingItems.push(a[c])):a[c].matching()?(k.matchingItems.push(a[c]),a[c].hide()):a[c].hide();return k.trigger("updated"),k},j.start()};c.exports=i}(window)}),a.register("list.js/src/search.js",function(a,b,c){var d=b("events"),e=b("get-by-class"),f=b("to-string");c.exports=function(a){var b,c,g,h,i={resetList:function(){a.i=1,a.templater.clear(),h=void 0},setOptions:function(a){2==a.length&&a[1]instanceof Array?c=a[1]:2==a.length&&"function"==typeof a[1]?h=a[1]:3==a.length&&(c=a[1],h=a[2])},setColumns:function(){c=void 0===c?i.toArray(a.items[0].values()):c},setSearchString:function(a){a=f(a).toLowerCase(),a=a.replace(/[-[\]{}()*+?.,\\^$|#]/g,"\\$&"),g=a},toArray:function(a){var b=[];for(var c in a)b.push(c);return b}},j={list:function(){for(var b=0,c=a.items.length;c>b;b++)j.item(a.items[b])},item:function(a){a.found=!1;for(var b=0,d=c.length;d>b;b++)if(j.values(a.values(),c[b]))return a.found=!0,void 0},values:function(a,c){return a.hasOwnProperty(c)&&(b=f(a[c]).toLowerCase(),""!==g&&b.search(g)>-1)?!0:!1},reset:function(){a.reset.search(),a.searched=!1}},k=function(b){return a.trigger("searchStart"),i.resetList(),i.setSearchString(b),i.setOptions(arguments),i.setColumns(),""===g?j.reset():(a.searched=!0,h?h(g,c):j.list()),a.update(),a.trigger("searchComplete"),a.visibleItems};return a.handlers.searchStart=a.handlers.searchStart||[],a.handlers.searchComplete=a.handlers.searchComplete||[],d.bind(e(a.listContainer,a.searchClass),"keyup",function(b){var c=b.target||b.srcElement,d=""===c.value&&!a.searched;d||k(c.value)}),d.bind(e(a.listContainer,a.searchClass),"input",function(a){var b=a.target||a.srcElement;""===b.value&&k("")}),a.helpers.toString=f,k}}),a.register("list.js/src/sort.js",function(a,b,c){var d=b("natural-sort"),e=b("classes"),f=b("events"),g=b("get-by-class"),h=b("get-attribute");c.exports=function(a){a.sortFunction=a.sortFunction||function(a,b,c){return c.desc="desc"==c.order?!0:!1,d(a.values()[c.valueName],b.values()[c.valueName],c)};var b={els:void 0,clear:function(){for(var a=0,c=b.els.length;c>a;a++)e(b.els[a]).remove("asc"),e(b.els[a]).remove("desc")},getOrder:function(a){var b=h(a,"data-order");return"asc"==b||"desc"==b?b:e(a).has("desc")?"asc":e(a).has("asc")?"desc":"asc"},getInSensitive:function(a,b){var c=h(a,"data-insensitive");b.insensitive="true"===c?!0:!1},setOrder:function(a){for(var c=0,d=b.els.length;d>c;c++){var f=b.els[c];if(h(f,"data-sort")===a.valueName){var g=h(f,"data-order");"asc"==g||"desc"==g?g==a.order&&e(f).add(a.order):e(f).add(a.order)}}}},c=function(){a.trigger("sortStart"),options={};var c=arguments[0].currentTarget||arguments[0].srcElement||void 0;c?(options.valueName=h(c,"data-sort"),b.getInSensitive(c,options),options.order=b.getOrder(c)):(options=arguments[1]||options,options.valueName=arguments[0],options.order=options.order||"asc",options.insensitive="undefined"==typeof options.insensitive?!0:options.insensitive),b.clear(),b.setOrder(options),options.sortFunction=options.sortFunction||a.sortFunction,a.items.sort(function(a,b){return options.sortFunction(a,b,options)}),a.update(),a.trigger("sortComplete")};return a.handlers.sortStart=a.handlers.sortStart||[],a.handlers.sortComplete=a.handlers.sortComplete||[],b.els=g(a.listContainer,a.sortClass),f.bind(b.els,"click",c),a.on("searchStart",b.clear),a.on("filterStart",b.clear),a.helpers.classes=e,a.helpers.naturalSort=d,a.helpers.events=f,a.helpers.getAttribute=h,c}}),a.register("list.js/src/item.js",function(a,b,c){c.exports=function(a){return function(b,c,d){var e=this;this._values={},this.found=!1,this.filtered=!1;var f=function(b,c,d){if(void 0===c)d?e.values(b,d):e.values(b);else{e.elm=c;var f=a.templater.get(e,b);e.values(f)}};this.values=function(b,c){if(void 0===b)return e._values;for(var d in b)e._values[d]=b[d];c!==!0&&a.templater.set(e,e.values())},this.show=function(){a.templater.show(e)},this.hide=function(){a.templater.hide(e)},this.matching=function(){return a.filtered&&a.searched&&e.found&&e.filtered||a.filtered&&!a.searched&&e.filtered||!a.filtered&&a.searched&&e.found||!a.filtered&&!a.searched},this.visible=function(){return e.elm.parentNode==a.list?!0:!1},f(b,c,d)}}}),a.register("list.js/src/templater.js",function(a,b,c){var d=b("get-by-class"),e=function(a){function b(b){if(void 0===b){for(var c=a.list.childNodes,d=0,e=c.length;e>d;d++)if(void 0===c[d].data)return c[d];return null}if(-1!==b.indexOf("<")){var f=document.createElement("div");return f.innerHTML=b,f.firstChild}return document.getElementById(a.item)}var c=b(a.item),e=this;this.get=function(a,b){e.create(a);for(var c={},f=0,g=b.length;g>f;f++){var h=d(a.elm,b[f],!0);c[b[f]]=h?h.innerHTML:""}return c},this.set=function(a,b){if(!e.create(a))for(var c in b)if(b.hasOwnProperty(c)){var f=d(a.elm,c,!0);f&&("IMG"===f.tagName&&""!==b[c]?f.src=b[c]:f.innerHTML=b[c])}},this.create=function(a){if(void 0!==a.elm)return!1;var b=c.cloneNode(!0);return b.removeAttribute("id"),a.elm=b,e.set(a,a.values()),!0},this.remove=function(b){a.list.removeChild(b.elm)},this.show=function(b){e.create(b),a.list.appendChild(b.elm)},this.hide=function(b){void 0!==b.elm&&b.elm.parentNode===a.list&&a.list.removeChild(b.elm)},this.clear=function(){if(a.list.hasChildNodes())for(;a.list.childNodes.length>=1;)a.list.removeChild(a.list.firstChild)}};c.exports=function(a){return new e(a)}}),a.register("list.js/src/filter.js",function(a,b,c){c.exports=function(a){return a.handlers.filterStart=a.handlers.filterStart||[],a.handlers.filterComplete=a.handlers.filterComplete||[],function(b){if(a.trigger("filterStart"),a.i=1,a.reset.filter(),void 0===b)a.filtered=!1;else{a.filtered=!0;for(var c=a.items,d=0,e=c.length;e>d;d++){var f=c[d];f.filtered=b(f)?!0:!1}}return a.update(),a.trigger("filterComplete"),a.visibleItems}}}),a.register("list.js/src/add-async.js",function(a,b,c){c.exports=function(a){return function(b,c,d){var e=b.splice(0,100);d=d||[],d=d.concat(a.add(e)),b.length>0?setTimeout(function(){addAsync(b,c,d)},10):(a.update(),c(d))}}}),a.register("list.js/src/parse.js",function(a,b,c){c.exports=function(a){var c=b("./item")(a),d=function(a){for(var b=a.childNodes,c=[],d=0,e=b.length;e>d;d++)void 0===b[d].data&&c.push(b[d]);return c},e=function(b,d){for(var e=0,f=b.length;f>e;e++)a.items.push(new c(d,b[e]))},f=function(b,c){var d=b.splice(0,100);e(d,c),b.length>0?setTimeout(function(){init.items.indexAsync(b,c)},10):a.update()};return function(){var b=d(a.list),c=a.valueNames;a.indexAsync?f(b,c):e(b,c)}}}),a.alias("component-classes/index.js","list.js/deps/classes/index.js"),a.alias("component-classes/index.js","classes/index.js"),a.alias("component-indexof/index.js","component-classes/deps/indexof/index.js"),a.alias("segmentio-extend/index.js","list.js/deps/extend/index.js"),a.alias("segmentio-extend/index.js","extend/index.js"),a.alias("component-indexof/index.js","list.js/deps/indexof/index.js"),a.alias("component-indexof/index.js","indexof/index.js"),a.alias("javve-events/index.js","list.js/deps/events/index.js"),a.alias("javve-events/index.js","events/index.js"),a.alias("component-event/index.js","javve-events/deps/event/index.js"),a.alias("timoxley-to-array/index.js","javve-events/deps/to-array/index.js"),a.alias("javve-get-by-class/index.js","list.js/deps/get-by-class/index.js"),a.alias("javve-get-by-class/index.js","get-by-class/index.js"),a.alias("javve-get-attribute/index.js","list.js/deps/get-attribute/index.js"),a.alias("javve-get-attribute/index.js","get-attribute/index.js"),a.alias("javve-natural-sort/index.js","list.js/deps/natural-sort/index.js"),a.alias("javve-natural-sort/index.js","natural-sort/index.js"),a.alias("javve-to-string/index.js","list.js/deps/to-string/index.js"),a.alias("javve-to-string/index.js","list.js/deps/to-string/index.js"),a.alias("javve-to-string/index.js","to-string/index.js"),a.alias("javve-to-string/index.js","javve-to-string/index.js"),a.alias("component-type/index.js","list.js/deps/type/index.js"),a.alias("component-type/index.js","type/index.js"),"object"==typeof exports?module.exports=a("list.js"):"function"==typeof define&&define.amd?define(function(){return a("list.js")}):this.List=a("list.js")}();;
/* Chosen v1.1.0 | (c) 2011-2013 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */
!function(){var a,AbstractChosen,Chosen,SelectParser,b,c={}.hasOwnProperty,d=function(a,b){function d(){this.constructor=a}for(var e in b)c.call(b,e)&&(a[e]=b[e]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a};SelectParser=function(){function SelectParser(){this.options_index=0,this.parsed=[]}return SelectParser.prototype.add_node=function(a){return"OPTGROUP"===a.nodeName.toUpperCase()?this.add_group(a):this.add_option(a)},SelectParser.prototype.add_group=function(a){var b,c,d,e,f,g;for(b=this.parsed.length,this.parsed.push({array_index:b,group:!0,label:this.escapeExpression(a.label),children:0,disabled:a.disabled}),f=a.childNodes,g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(this.add_option(c,b,a.disabled));return g},SelectParser.prototype.add_option=function(a,b,c){return"OPTION"===a.nodeName.toUpperCase()?(""!==a.text?(null!=b&&(this.parsed[b].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:a.value,text:a.text,html:a.innerHTML,selected:a.selected,disabled:c===!0?c:a.disabled,group_array_index:b,classes:a.className,style:a.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1):void 0},SelectParser.prototype.escapeExpression=function(a){var b,c;return null==a||a===!1?"":/[\&\<\>\"\'\`]/.test(a)?(b={"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},c=/&(?!\w+;)|[\<\>\"\'\`]/g,a.replace(c,function(a){return b[a]||"&amp;"})):a},SelectParser}(),SelectParser.select_to_array=function(a){var b,c,d,e,f;for(c=new SelectParser,f=a.childNodes,d=0,e=f.length;e>d;d++)b=f[d],c.add_node(b);return c.parsed},AbstractChosen=function(){function AbstractChosen(a,b){this.form_field=a,this.options=null!=b?b:{},AbstractChosen.browser_is_supported()&&(this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers())}return AbstractChosen.prototype.set_default_values=function(){var a=this;return this.click_test_action=function(b){return a.test_active_click(b)},this.activate_action=function(b){return a.activate_field(b)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.allow_single_deselect=null!=this.options.allow_single_deselect&&null!=this.form_field.options[0]&&""===this.form_field.options[0].text?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.enable_split_word_search=null!=this.options.enable_split_word_search?this.options.enable_split_word_search:!0,this.group_search=null!=this.options.group_search?this.options.group_search:!0,this.search_contains=this.options.search_contains||!1,this.single_backstroke_delete=null!=this.options.single_backstroke_delete?this.options.single_backstroke_delete:!0,this.max_selected_options=this.options.max_selected_options||1/0,this.inherit_select_classes=this.options.inherit_select_classes||!1,this.display_selected_options=null!=this.options.display_selected_options?this.options.display_selected_options:!0,this.display_disabled_options=null!=this.options.display_disabled_options?this.options.display_disabled_options:!0},AbstractChosen.prototype.set_default_text=function(){return this.default_text=this.form_field.getAttribute("data-placeholder")?this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.options.placeholder_text_multiple||this.options.placeholder_text||AbstractChosen.default_multiple_text:this.options.placeholder_text_single||this.options.placeholder_text||AbstractChosen.default_single_text,this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||AbstractChosen.default_no_result_text},AbstractChosen.prototype.mouse_enter=function(){return this.mouse_on_container=!0},AbstractChosen.prototype.mouse_leave=function(){return this.mouse_on_container=!1},AbstractChosen.prototype.input_focus=function(){var a=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return a.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},AbstractChosen.prototype.input_blur=function(){var a=this;return this.mouse_on_container?void 0:(this.active_field=!1,setTimeout(function(){return a.blur_test()},100))},AbstractChosen.prototype.results_option_build=function(a){var b,c,d,e,f;for(b="",f=this.results_data,d=0,e=f.length;e>d;d++)c=f[d],b+=c.group?this.result_add_group(c):this.result_add_option(c),(null!=a?a.first:void 0)&&(c.selected&&this.is_multiple?this.choice_build(c):c.selected&&!this.is_multiple&&this.single_set_selected_text(c.text));return b},AbstractChosen.prototype.result_add_option=function(a){var b,c;return a.search_match?this.include_option_in_results(a)?(b=[],a.disabled||a.selected&&this.is_multiple||b.push("active-result"),!a.disabled||a.selected&&this.is_multiple||b.push("disabled-result"),a.selected&&b.push("result-selected"),null!=a.group_array_index&&b.push("group-option"),""!==a.classes&&b.push(a.classes),c=document.createElement("li"),c.className=b.join(" "),c.style.cssText=a.style,c.setAttribute("data-option-array-index",a.array_index),c.innerHTML=a.search_text,this.outerHTML(c)):"":""},AbstractChosen.prototype.result_add_group=function(a){var b;return a.search_match||a.group_match?a.active_options>0?(b=document.createElement("li"),b.className="group-result",b.innerHTML=a.search_text,this.outerHTML(b)):"":""},AbstractChosen.prototype.results_update_field=function(){return this.set_default_text(),this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.results_build(),this.results_showing?this.winnow_results():void 0},AbstractChosen.prototype.reset_single_select_options=function(){var a,b,c,d,e;for(d=this.results_data,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.selected?e.push(a.selected=!1):e.push(void 0);return e},AbstractChosen.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},AbstractChosen.prototype.results_search=function(){return this.results_showing?this.winnow_results():this.results_show()},AbstractChosen.prototype.winnow_results=function(){var a,b,c,d,e,f,g,h,i,j,k,l,m;for(this.no_results_clear(),e=0,g=this.get_search_text(),a=g.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),d=this.search_contains?"":"^",c=new RegExp(d+a,"i"),j=new RegExp(a,"i"),m=this.results_data,k=0,l=m.length;l>k;k++)b=m[k],b.search_match=!1,f=null,this.include_option_in_results(b)&&(b.group&&(b.group_match=!1,b.active_options=0),null!=b.group_array_index&&this.results_data[b.group_array_index]&&(f=this.results_data[b.group_array_index],0===f.active_options&&f.search_match&&(e+=1),f.active_options+=1),(!b.group||this.group_search)&&(b.search_text=b.group?b.label:b.html,b.search_match=this.search_string_match(b.search_text,c),b.search_match&&!b.group&&(e+=1),b.search_match?(g.length&&(h=b.search_text.search(j),i=b.search_text.substr(0,h+g.length)+"</em>"+b.search_text.substr(h+g.length),b.search_text=i.substr(0,h)+"<em>"+i.substr(h)),null!=f&&(f.group_match=!0)):null!=b.group_array_index&&this.results_data[b.group_array_index].search_match&&(b.search_match=!0)));return this.result_clear_highlight(),1>e&&g.length?(this.update_results_content(""),this.no_results(g)):(this.update_results_content(this.results_option_build()),this.winnow_results_set_highlight())},AbstractChosen.prototype.search_string_match=function(a,b){var c,d,e,f;if(b.test(a))return!0;if(this.enable_split_word_search&&(a.indexOf(" ")>=0||0===a.indexOf("["))&&(d=a.replace(/\[|\]/g,"").split(" "),d.length))for(e=0,f=d.length;f>e;e++)if(c=d[e],b.test(c))return!0},AbstractChosen.prototype.choices_count=function(){var a,b,c,d;if(null!=this.selected_option_count)return this.selected_option_count;for(this.selected_option_count=0,d=this.form_field.options,b=0,c=d.length;c>b;b++)a=d[b],a.selected&&(this.selected_option_count+=1);return this.selected_option_count},AbstractChosen.prototype.choices_click=function(a){return a.preventDefault(),this.results_showing||this.is_disabled?void 0:this.results_show()},AbstractChosen.prototype.keyup_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),b){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:if(a.preventDefault(),this.results_showing)return this.result_select(a);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:break;default:return this.results_search()}},AbstractChosen.prototype.clipboard_event_checker=function(){var a=this;return setTimeout(function(){return a.results_search()},50)},AbstractChosen.prototype.container_width=function(){return null!=this.options.width?this.options.width:""+this.form_field.offsetWidth+"px"},AbstractChosen.prototype.include_option_in_results=function(a){return this.is_multiple&&!this.display_selected_options&&a.selected?!1:!this.display_disabled_options&&a.disabled?!1:a.empty?!1:!0},AbstractChosen.prototype.search_results_touchstart=function(a){return this.touch_started=!0,this.search_results_mouseover(a)},AbstractChosen.prototype.search_results_touchmove=function(a){return this.touch_started=!1,this.search_results_mouseout(a)},AbstractChosen.prototype.search_results_touchend=function(a){return this.touch_started?this.search_results_mouseup(a):void 0},AbstractChosen.prototype.outerHTML=function(a){var b;return a.outerHTML?a.outerHTML:(b=document.createElement("div"),b.appendChild(a),b.innerHTML)},AbstractChosen.browser_is_supported=function(){return"Microsoft Internet Explorer"===window.navigator.appName?document.documentMode>=8:/iP(od|hone)/i.test(window.navigator.userAgent)?!1:/Android/i.test(window.navigator.userAgent)&&/Mobile/i.test(window.navigator.userAgent)?!1:!0},AbstractChosen.default_multiple_text="Select Some Options",AbstractChosen.default_single_text="Select an Option",AbstractChosen.default_no_result_text="No results match",AbstractChosen}(),a=jQuery,a.fn.extend({chosen:function(b){return AbstractChosen.browser_is_supported()?this.each(function(){var c,d;c=a(this),d=c.data("chosen"),"destroy"===b&&d?d.destroy():d||c.data("chosen",new Chosen(this,b))}):this}}),Chosen=function(c){function Chosen(){return b=Chosen.__super__.constructor.apply(this,arguments)}return d(Chosen,c),Chosen.prototype.setup=function(){return this.form_field_jq=a(this.form_field),this.current_selectedIndex=this.form_field.selectedIndex,this.is_rtl=this.form_field_jq.hasClass("chosen-rtl")},Chosen.prototype.set_up_html=function(){var b,c;return b=["chosen-container"],b.push("chosen-container-"+(this.is_multiple?"multi":"single")),this.inherit_select_classes&&this.form_field.className&&b.push(this.form_field.className),this.is_rtl&&b.push("chosen-rtl"),c={"class":b.join(" "),style:"width: "+this.container_width()+";",title:this.form_field.title},this.form_field.id.length&&(c.id=this.form_field.id.replace(/[^\w]/g,"_")+"_chosen"),this.container=a("<div />",c),this.is_multiple?this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'):this.container.html('<a class="chosen-single chosen-default" tabindex="-1"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'),this.form_field_jq.hide().after(this.container),this.dropdown=this.container.find("div.chosen-drop").first(),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chosen-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chosen-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chosen-search").first(),this.selected_item=this.container.find(".chosen-single").first()),this.results_build(),this.set_tab_index(),this.set_label_behavior(),this.form_field_jq.trigger("chosen:ready",{chosen:this})},Chosen.prototype.register_observers=function(){var a=this;return this.container.bind("mousedown.chosen",function(b){a.container_mousedown(b)}),this.container.bind("mouseup.chosen",function(b){a.container_mouseup(b)}),this.container.bind("mouseenter.chosen",function(b){a.mouse_enter(b)}),this.container.bind("mouseleave.chosen",function(b){a.mouse_leave(b)}),this.search_results.bind("mouseup.chosen",function(b){a.search_results_mouseup(b)}),this.search_results.bind("mouseover.chosen",function(b){a.search_results_mouseover(b)}),this.search_results.bind("mouseout.chosen",function(b){a.search_results_mouseout(b)}),this.search_results.bind("mousewheel.chosen DOMMouseScroll.chosen",function(b){a.search_results_mousewheel(b)}),this.search_results.bind("touchstart.chosen",function(b){a.search_results_touchstart(b)}),this.search_results.bind("touchmove.chosen",function(b){a.search_results_touchmove(b)}),this.search_results.bind("touchend.chosen",function(b){a.search_results_touchend(b)}),this.form_field_jq.bind("chosen:updated.chosen",function(b){a.results_update_field(b)}),this.form_field_jq.bind("chosen:activate.chosen",function(b){a.activate_field(b)}),this.form_field_jq.bind("chosen:open.chosen",function(b){a.container_mousedown(b)}),this.form_field_jq.bind("chosen:close.chosen",function(b){a.input_blur(b)}),this.search_field.bind("blur.chosen",function(b){a.input_blur(b)}),this.search_field.bind("keyup.chosen",function(b){a.keyup_checker(b)}),this.search_field.bind("keydown.chosen",function(b){a.keydown_checker(b)}),this.search_field.bind("focus.chosen",function(b){a.input_focus(b)}),this.search_field.bind("cut.chosen",function(b){a.clipboard_event_checker(b)}),this.search_field.bind("paste.chosen",function(b){a.clipboard_event_checker(b)}),this.is_multiple?this.search_choices.bind("click.chosen",function(b){a.choices_click(b)}):this.container.bind("click.chosen",function(a){a.preventDefault()})},Chosen.prototype.destroy=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.search_field[0].tabIndex&&(this.form_field_jq[0].tabIndex=this.search_field[0].tabIndex),this.container.remove(),this.form_field_jq.removeData("chosen"),this.form_field_jq.show()},Chosen.prototype.search_field_disabled=function(){return this.is_disabled=this.form_field_jq[0].disabled,this.is_disabled?(this.container.addClass("chosen-disabled"),this.search_field[0].disabled=!0,this.is_multiple||this.selected_item.unbind("focus.chosen",this.activate_action),this.close_field()):(this.container.removeClass("chosen-disabled"),this.search_field[0].disabled=!1,this.is_multiple?void 0:this.selected_item.bind("focus.chosen",this.activate_action))},Chosen.prototype.container_mousedown=function(b){return this.is_disabled||(b&&"mousedown"===b.type&&!this.results_showing&&b.preventDefault(),null!=b&&a(b.target).hasClass("search-choice-close"))?void 0:(this.active_field?this.is_multiple||!b||a(b.target)[0]!==this.selected_item[0]&&!a(b.target).parents("a.chosen-single").length||(b.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),a(this.container[0].ownerDocument).bind("click.chosen",this.click_test_action),this.results_show()),this.activate_field())},Chosen.prototype.container_mouseup=function(a){return"ABBR"!==a.target.nodeName||this.is_disabled?void 0:this.results_reset(a)},Chosen.prototype.search_results_mousewheel=function(a){var b;return a.originalEvent&&(b=-a.originalEvent.wheelDelta||a.originalEvent.detail),null!=b?(a.preventDefault(),"DOMMouseScroll"===a.type&&(b=40*b),this.search_results.scrollTop(b+this.search_results.scrollTop())):void 0},Chosen.prototype.blur_test=function(){return!this.active_field&&this.container.hasClass("chosen-container-active")?this.close_field():void 0},Chosen.prototype.close_field=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClass("chosen-container-active"),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},Chosen.prototype.activate_field=function(){return this.container.addClass("chosen-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val()),this.search_field.focus()},Chosen.prototype.test_active_click=function(b){var c;return c=a(b.target).closest(".chosen-container"),c.length&&this.container[0]===c[0]?this.active_field=!0:this.close_field()},Chosen.prototype.results_build=function(){return this.parsing=!0,this.selected_option_count=null,this.results_data=SelectParser.select_to_array(this.form_field),this.is_multiple?this.search_choices.find("li.search-choice").remove():this.is_multiple||(this.single_set_selected_text(),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?(this.search_field[0].readOnly=!0,this.container.addClass("chosen-container-single-nosearch")):(this.search_field[0].readOnly=!1,this.container.removeClass("chosen-container-single-nosearch"))),this.update_results_content(this.results_option_build({first:!0})),this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.parsing=!1},Chosen.prototype.result_do_highlight=function(a){var b,c,d,e,f;if(a.length){if(this.result_clear_highlight(),this.result_highlight=a,this.result_highlight.addClass("highlighted"),d=parseInt(this.search_results.css("maxHeight"),10),f=this.search_results.scrollTop(),e=d+f,c=this.result_highlight.position().top+this.search_results.scrollTop(),b=c+this.result_highlight.outerHeight(),b>=e)return this.search_results.scrollTop(b-d>0?b-d:0);if(f>c)return this.search_results.scrollTop(c)}},Chosen.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClass("highlighted"),this.result_highlight=null},Chosen.prototype.results_show=function(){return this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.container.addClass("chosen-with-drop"),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val()),this.winnow_results(),this.form_field_jq.trigger("chosen:showing_dropdown",{chosen:this}))},Chosen.prototype.update_results_content=function(a){return this.search_results.html(a)},Chosen.prototype.results_hide=function(){return this.results_showing&&(this.result_clear_highlight(),this.container.removeClass("chosen-with-drop"),this.form_field_jq.trigger("chosen:hiding_dropdown",{chosen:this})),this.results_showing=!1},Chosen.prototype.set_tab_index=function(){var a;return this.form_field.tabIndex?(a=this.form_field.tabIndex,this.form_field.tabIndex=-1,this.search_field[0].tabIndex=a):void 0},Chosen.prototype.set_label_behavior=function(){var b=this;return this.form_field_label=this.form_field_jq.parents("label"),!this.form_field_label.length&&this.form_field.id.length&&(this.form_field_label=a("label[for='"+this.form_field.id+"']")),this.form_field_label.length>0?this.form_field_label.bind("click.chosen",function(a){return b.is_multiple?b.container_mousedown(a):b.activate_field()}):void 0},Chosen.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices_count()<1&&!this.active_field?(this.search_field.val(this.default_text),this.search_field.addClass("default")):(this.search_field.val(""),this.search_field.removeClass("default"))},Chosen.prototype.search_results_mouseup=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c.length?(this.result_highlight=c,this.result_select(b),this.search_field.focus()):void 0},Chosen.prototype.search_results_mouseover=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c?this.result_do_highlight(c):void 0},Chosen.prototype.search_results_mouseout=function(b){return a(b.target).hasClass("active-result")?this.result_clear_highlight():void 0},Chosen.prototype.choice_build=function(b){var c,d,e=this;return c=a("<li />",{"class":"search-choice"}).html("<span>"+b.html+"</span>"),b.disabled?c.addClass("search-choice-disabled"):(d=a("<a />",{"class":"search-choice-close","data-option-array-index":b.array_index}),d.bind("click.chosen",function(a){return e.choice_destroy_link_click(a)}),c.append(d)),this.search_container.before(c)},Chosen.prototype.choice_destroy_link_click=function(b){return b.preventDefault(),b.stopPropagation(),this.is_disabled?void 0:this.choice_destroy(a(b.target))},Chosen.prototype.choice_destroy=function(a){return this.result_deselect(a[0].getAttribute("data-option-array-index"))?(this.show_search_field_default(),this.is_multiple&&this.choices_count()>0&&this.search_field.val().length<1&&this.results_hide(),a.parents("li").first().remove(),this.search_field_scale()):void 0},Chosen.prototype.results_reset=function(){return this.reset_single_select_options(),this.form_field.options[0].selected=!0,this.single_set_selected_text(),this.show_search_field_default(),this.results_reset_cleanup(),this.form_field_jq.trigger("change"),this.active_field?this.results_hide():void 0},Chosen.prototype.results_reset_cleanup=function(){return this.current_selectedIndex=this.form_field.selectedIndex,this.selected_item.find("abbr").remove()},Chosen.prototype.result_select=function(a){var b,c;return this.result_highlight?(b=this.result_highlight,this.result_clear_highlight(),this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.is_multiple?b.removeClass("active-result"):this.reset_single_select_options(),c=this.results_data[b[0].getAttribute("data-option-array-index")],c.selected=!0,this.form_field.options[c.options_index].selected=!0,this.selected_option_count=null,this.is_multiple?this.choice_build(c):this.single_set_selected_text(c.text),(a.metaKey||a.ctrlKey)&&this.is_multiple||this.results_hide(),this.search_field.val(""),(this.is_multiple||this.form_field.selectedIndex!==this.current_selectedIndex)&&this.form_field_jq.trigger("change",{selected:this.form_field.options[c.options_index].value}),this.current_selectedIndex=this.form_field.selectedIndex,this.search_field_scale())):void 0},Chosen.prototype.single_set_selected_text=function(a){return null==a&&(a=this.default_text),a===this.default_text?this.selected_item.addClass("chosen-default"):(this.single_deselect_control_build(),this.selected_item.removeClass("chosen-default")),this.selected_item.find("span").text(a)},Chosen.prototype.result_deselect=function(a){var b;return b=this.results_data[a],this.form_field.options[b.options_index].disabled?!1:(b.selected=!1,this.form_field.options[b.options_index].selected=!1,this.selected_option_count=null,this.result_clear_highlight(),this.results_showing&&this.winnow_results(),this.form_field_jq.trigger("change",{deselected:this.form_field.options[b.options_index].value}),this.search_field_scale(),!0)},Chosen.prototype.single_deselect_control_build=function(){return this.allow_single_deselect?(this.selected_item.find("abbr").length||this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>'),this.selected_item.addClass("chosen-single-with-deselect")):void 0},Chosen.prototype.get_search_text=function(){return this.search_field.val()===this.default_text?"":a("<div/>").text(a.trim(this.search_field.val())).html()},Chosen.prototype.winnow_results_set_highlight=function(){var a,b;return b=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),a=b.length?b.first():this.search_results.find(".active-result").first(),null!=a?this.result_do_highlight(a):void 0},Chosen.prototype.no_results=function(b){var c;return c=a('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>'),c.find("span").first().html(b),this.search_results.append(c),this.form_field_jq.trigger("chosen:no_results",{chosen:this})},Chosen.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},Chosen.prototype.keydown_arrow=function(){var a;return this.results_showing&&this.result_highlight?(a=this.result_highlight.nextAll("li.active-result").first())?this.result_do_highlight(a):void 0:this.results_show()},Chosen.prototype.keyup_arrow=function(){var a;return this.results_showing||this.is_multiple?this.result_highlight?(a=this.result_highlight.prevAll("li.active-result"),a.length?this.result_do_highlight(a.first()):(this.choices_count()>0&&this.results_hide(),this.result_clear_highlight())):void 0:this.results_show()},Chosen.prototype.keydown_backstroke=function(){var a;return this.pending_backstroke?(this.choice_destroy(this.pending_backstroke.find("a").first()),this.clear_backstroke()):(a=this.search_container.siblings("li.search-choice").last(),a.length&&!a.hasClass("search-choice-disabled")?(this.pending_backstroke=a,this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClass("search-choice-focus")):void 0)},Chosen.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus"),this.pending_backstroke=null},Chosen.prototype.keydown_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),8!==b&&this.pending_backstroke&&this.clear_backstroke(),b){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(a),this.mouse_on_container=!1;break;case 13:a.preventDefault();break;case 38:a.preventDefault(),this.keyup_arrow();break;case 40:a.preventDefault(),this.keydown_arrow()}},Chosen.prototype.search_field_scale=function(){var b,c,d,e,f,g,h,i,j;if(this.is_multiple){for(d=0,h=0,f="position:absolute; left: -1000px; top: -1000px; display:none;",g=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"],i=0,j=g.length;j>i;i++)e=g[i],f+=e+":"+this.search_field.css(e)+";";return b=a("<div />",{style:f}),b.text(this.search_field.val()),a("body").append(b),h=b.width()+25,b.remove(),c=this.container.outerWidth(),h>c-10&&(h=c-10),this.search_field.css({width:h+"px"})}},Chosen}(AbstractChosen)}.call(this);;
(function (e, t) { "use strict"; var n = e.History = e.History || {}, r = e.jQuery; if (typeof n.Adapter != "undefined") throw new Error("History.js Adapter has already been loaded..."); n.Adapter = { bind: function (e, t, n) { r(e).bind(t, n) }, trigger: function (e, t, n) { r(e).trigger(t, n) }, extractEventData: function (e, n, r) { var i = n && n.originalEvent && n.originalEvent[e] || r && r[e] || t; return i }, onDomLoad: function (e) { r(e) } }, typeof n.init != "undefined" && n.init() })(window), function (e, t) { "use strict"; var n = e.console || t, r = e.document, i = e.navigator, s = !1, o = e.setTimeout, u = e.clearTimeout, a = e.setInterval, f = e.clearInterval, l = e.JSON, c = e.alert, h = e.History = e.History || {}, p = e.history; try { s = e.sessionStorage, s.setItem("TEST", "1"), s.removeItem("TEST") } catch (d) { s = !1 } l.stringify = l.stringify || l.encode, l.parse = l.parse || l.decode; if (typeof h.init != "undefined") throw new Error("History.js Core has already been loaded..."); h.init = function (e) { return typeof h.Adapter == "undefined" ? !1 : (typeof h.initCore != "undefined" && h.initCore(), typeof h.initHtml4 != "undefined" && h.initHtml4(), !0) }, h.initCore = function (d) { if (typeof h.initCore.initialized != "undefined") return !1; h.initCore.initialized = !0, h.options = h.options || {}, h.options.hashChangeInterval = h.options.hashChangeInterval || 100, h.options.safariPollInterval = h.options.safariPollInterval || 500, h.options.doubleCheckInterval = h.options.doubleCheckInterval || 500, h.options.disableSuid = h.options.disableSuid || !1, h.options.storeInterval = h.options.storeInterval || 1e3, h.options.busyDelay = h.options.busyDelay || 250, h.options.debug = h.options.debug || !1, h.options.initialTitle = h.options.initialTitle || r.title, h.options.html4Mode = h.options.html4Mode || !1, h.options.delayInit = h.options.delayInit || !1, h.intervalList = [], h.clearAllIntervals = function () { var e, t = h.intervalList; if (typeof t != "undefined" && t !== null) { for (e = 0; e < t.length; e++)f(t[e]); h.intervalList = null } }, h.debug = function () { (h.options.debug || !1) && h.log.apply(h, arguments) }, h.log = function () { var e = typeof n != "undefined" && typeof n.log != "undefined" && typeof n.log.apply != "undefined", t = r.getElementById("log"), i, s, o, u, a; e ? (u = Array.prototype.slice.call(arguments), i = u.shift(), typeof n.debug != "undefined" ? n.debug.apply(n, [i, u]) : n.log.apply(n, [i, u])) : i = "\n" + arguments[0] + "\n"; for (s = 1, o = arguments.length; s < o; ++s) { a = arguments[s]; if (typeof a == "object" && typeof l != "undefined") try { a = l.stringify(a) } catch (f) { } i += "\n" + a + "\n" } return t ? (t.value += i + "\n-----\n", t.scrollTop = t.scrollHeight - t.clientHeight) : e || c(i), !0 }, h.getInternetExplorerMajorVersion = function () { var e = h.getInternetExplorerMajorVersion.cached = typeof h.getInternetExplorerMajorVersion.cached != "undefined" ? h.getInternetExplorerMajorVersion.cached : function () { var e = 3, t = r.createElement("div"), n = t.getElementsByTagName("i"); while ((t.innerHTML = "<!--[if gt IE " + ++e + "]><i></i><![endif]-->") && n[0]); return e > 4 ? e : !1 }(); return e }, h.isInternetExplorer = function () { var e = h.isInternetExplorer.cached = typeof h.isInternetExplorer.cached != "undefined" ? h.isInternetExplorer.cached : Boolean(h.getInternetExplorerMajorVersion()); return e }, h.options.html4Mode ? h.emulated = { pushState: !0, hashChange: !0 } : h.emulated = { pushState: !Boolean(e.history && e.history.pushState && e.history.replaceState && !/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent) && !/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)), hashChange: Boolean(!("onhashchange" in e || "onhashchange" in r) || h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 8) }, h.enabled = !h.emulated.pushState, h.bugs = { setHash: Boolean(!h.emulated.pushState && i.vendor === "Apple Computer, Inc." && /AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)), safariPoll: Boolean(!h.emulated.pushState && i.vendor === "Apple Computer, Inc." && /AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)), ieDoubleCheck: Boolean(h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 8), hashEscape: Boolean(h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 7) }, h.isEmptyObject = function (e) { for (var t in e) if (e.hasOwnProperty(t)) return !1; return !0 }, h.cloneObject = function (e) { var t, n; return e ? (t = l.stringify(e), n = l.parse(t)) : n = {}, n }, h.getRootUrl = function () { var e = r.location.protocol + "//" + (r.location.hostname || r.location.host); if (r.location.port || !1) e += ":" + r.location.port; return e += "/", e }, h.getBaseHref = function () { var e = r.getElementsByTagName("base"), t = null, n = ""; return e.length === 1 && (t = e[0], n = t.href.replace(/[^\/]+$/, "")), n = n.replace(/\/+$/, ""), n && (n += "/"), n }, h.getBaseUrl = function () { var e = h.getBaseHref() || h.getBasePageUrl() || h.getRootUrl(); return e }, h.getPageUrl = function () { var e = h.getState(!1, !1), t = (e || {}).url || h.getLocationHref(), n; return n = t.replace(/\/+$/, "").replace(/[^\/]+$/, function (e, t, n) { return /\./.test(e) ? e : e + "/" }), n }, h.getBasePageUrl = function () { var e = h.getLocationHref().replace(/[#\?].*/, "").replace(/[^\/]+$/, function (e, t, n) { return /[^\/]$/.test(e) ? "" : e }).replace(/\/+$/, "") + "/"; return e }, h.getFullUrl = function (e, t) { var n = e, r = e.substring(0, 1); return t = typeof t == "undefined" ? !0 : t, /[a-z]+\:\/\//.test(e) || (r === "/" ? n = h.getRootUrl() + e.replace(/^\/+/, "") : r === "#" ? n = h.getPageUrl().replace(/#.*/, "") + e : r === "?" ? n = h.getPageUrl().replace(/[\?#].*/, "") + e : t ? n = h.getBaseUrl() + e.replace(/^(\.\/)+/, "") : n = h.getBasePageUrl() + e.replace(/^(\.\/)+/, "")), n.replace(/\#$/, "") }, h.getShortUrl = function (e) { var t = e, n = h.getBaseUrl(), r = h.getRootUrl(); return h.emulated.pushState && (t = t.replace(n, "")), t = t.replace(r, "/"), h.isTraditionalAnchor(t) && (t = "./" + t), t = t.replace(/^(\.\/)+/g, "./").replace(/\#$/, ""), t }, h.getLocationHref = function (e) { return e = e || r, e.URL === e.location.href ? e.location.href : e.location.href === decodeURIComponent(e.URL) ? e.URL : e.location.hash && decodeURIComponent(e.location.href.replace(/^[^#]+/, "")) === e.location.hash ? e.location.href : e.URL.indexOf("#") == -1 && e.location.href.indexOf("#") != -1 ? e.location.href : e.URL || e.location.href }, h.store = {}, h.idToState = h.idToState || {}, h.stateToId = h.stateToId || {}, h.urlToId = h.urlToId || {}, h.storedStates = h.storedStates || [], h.savedStates = h.savedStates || [], h.normalizeStore = function () { h.store.idToState = h.store.idToState || {}, h.store.urlToId = h.store.urlToId || {}, h.store.stateToId = h.store.stateToId || {} }, h.getState = function (e, t) { typeof e == "undefined" && (e = !0), typeof t == "undefined" && (t = !0); var n = h.getLastSavedState(); return !n && t && (n = h.createStateObject()), e && (n = h.cloneObject(n), n.url = n.cleanUrl || n.url), n }, h.getIdByState = function (e) { var t = h.extractId(e.url), n; if (!t) { n = h.getStateString(e); if (typeof h.stateToId[n] != "undefined") t = h.stateToId[n]; else if (typeof h.store.stateToId[n] != "undefined") t = h.store.stateToId[n]; else { for (; ;) { t = (new Date).getTime() + String(Math.random()).replace(/\D/g, ""); if (typeof h.idToState[t] == "undefined" && typeof h.store.idToState[t] == "undefined") break } h.stateToId[n] = t, h.idToState[t] = e } } return t }, h.normalizeState = function (e) { var t, n; if (!e || typeof e != "object") e = {}; if (typeof e.normalized != "undefined") return e; if (!e.data || typeof e.data != "object") e.data = {}; return t = {}, t.normalized = !0, t.title = e.title || "", t.url = h.getFullUrl(e.url ? e.url : h.getLocationHref()), t.hash = h.getShortUrl(t.url), t.data = h.cloneObject(e.data), t.id = h.getIdByState(t), t.cleanUrl = t.url.replace(/\??\&_suid.*/, ""), t.url = t.cleanUrl, n = !h.isEmptyObject(t.data), (t.title || n) && h.options.disableSuid !== !0 && (t.hash = h.getShortUrl(t.url).replace(/\??\&_suid.*/, ""), /\?/.test(t.hash) || (t.hash += "?"), t.hash += "&_suid=" + t.id), t.hashedUrl = h.getFullUrl(t.hash), (h.emulated.pushState || h.bugs.safariPoll) && h.hasUrlDuplicate(t) && (t.url = t.hashedUrl), t }, h.createStateObject = function (e, t, n) { var r = { data: e, title: t, url: n }; return r = h.normalizeState(r), r }, h.getStateById = function (e) { e = String(e); var n = h.idToState[e] || h.store.idToState[e] || t; return n }, h.getStateString = function (e) { var t, n, r; return t = h.normalizeState(e), n = { data: t.data, title: e.title, url: e.url }, r = l.stringify(n), r }, h.getStateId = function (e) { var t, n; return t = h.normalizeState(e), n = t.id, n }, h.getHashByState = function (e) { var t, n; return t = h.normalizeState(e), n = t.hash, n }, h.extractId = function (e) { var t, n, r, i; return e.indexOf("#") != -1 ? i = e.split("#")[0] : i = e, n = /(.*)\&_suid=([0-9]+)$/.exec(i), r = n ? n[1] || e : e, t = n ? String(n[2] || "") : "", t || !1 }, h.isTraditionalAnchor = function (e) { var t = !/[\/\?\.]/.test(e); return t }, h.extractState = function (e, t) { var n = null, r, i; return t = t || !1, r = h.extractId(e), r && (n = h.getStateById(r)), n || (i = h.getFullUrl(e), r = h.getIdByUrl(i) || !1, r && (n = h.getStateById(r)), !n && t && !h.isTraditionalAnchor(e) && (n = h.createStateObject(null, null, i))), n }, h.getIdByUrl = function (e) { var n = h.urlToId[e] || h.store.urlToId[e] || t; return n }, h.getLastSavedState = function () { return h.savedStates[h.savedStates.length - 1] || t }, h.getLastStoredState = function () { return h.storedStates[h.storedStates.length - 1] || t }, h.hasUrlDuplicate = function (e) { var t = !1, n; return n = h.extractState(e.url), t = n && n.id !== e.id, t }, h.storeState = function (e) { return h.urlToId[e.url] = e.id, h.storedStates.push(h.cloneObject(e)), e }, h.isLastSavedState = function (e) { var t = !1, n, r, i; return h.savedStates.length && (n = e.id, r = h.getLastSavedState(), i = r.id, t = n === i), t }, h.saveState = function (e) { return h.isLastSavedState(e) ? !1 : (h.savedStates.push(h.cloneObject(e)), !0) }, h.getStateByIndex = function (e) { var t = null; return typeof e == "undefined" ? t = h.savedStates[h.savedStates.length - 1] : e < 0 ? t = h.savedStates[h.savedStates.length + e] : t = h.savedStates[e], t }, h.getCurrentIndex = function () { var e = null; return h.savedStates.length < 1 ? e = 0 : e = h.savedStates.length - 1, e }, h.getHash = function (e) { var t = h.getLocationHref(e), n; return n = h.getHashByUrl(t), n }, h.unescapeHash = function (e) { var t = h.normalizeHash(e); return t = decodeURIComponent(t), t }, h.normalizeHash = function (e) { var t = e.replace(/[^#]*#/, "").replace(/#.*/, ""); return t }, h.setHash = function (e, t) { var n, i; return t !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.setHash, args: arguments, queue: t }), !1) : (h.busy(!0), n = h.extractState(e, !0), n && !h.emulated.pushState ? h.pushState(n.data, n.title, n.url, !1) : h.getHash() !== e && (h.bugs.setHash ? (i = h.getPageUrl(), h.pushState(null, null, i + "#" + e, !1)) : r.location.hash = e), h) }, h.escapeHash = function (t) { var n = h.normalizeHash(t); return n = e.encodeURIComponent(n), h.bugs.hashEscape || (n = n.replace(/\%21/g, "!").replace(/\%26/g, "&").replace(/\%3D/g, "=").replace(/\%3F/g, "?")), n }, h.getHashByUrl = function (e) { var t = String(e).replace(/([^#]*)#?([^#]*)#?(.*)/, "$2"); return t = h.unescapeHash(t), t }, h.setTitle = function (e) { var t = e.title, n; t || (n = h.getStateByIndex(0), n && n.url === e.url && (t = n.title || h.options.initialTitle)); try { r.getElementsByTagName("title")[0].innerHTML = t.replace("<", "&lt;").replace(">", "&gt;").replace(" & ", " &amp; ") } catch (i) { } return r.title = t, h }, h.queues = [], h.busy = function (e) { typeof e != "undefined" ? h.busy.flag = e : typeof h.busy.flag == "undefined" && (h.busy.flag = !1); if (!h.busy.flag) { u(h.busy.timeout); var t = function () { var e, n, r; if (h.busy.flag) return; for (e = h.queues.length - 1; e >= 0; --e) { n = h.queues[e]; if (n.length === 0) continue; r = n.shift(), h.fireQueueItem(r), h.busy.timeout = o(t, h.options.busyDelay) } }; h.busy.timeout = o(t, h.options.busyDelay) } return h.busy.flag }, h.busy.flag = !1, h.fireQueueItem = function (e) { return e.callback.apply(e.scope || h, e.args || []) }, h.pushQueue = function (e) { return h.queues[e.queue || 0] = h.queues[e.queue || 0] || [], h.queues[e.queue || 0].push(e), h }, h.queue = function (e, t) { return typeof e == "function" && (e = { callback: e }), typeof t != "undefined" && (e.queue = t), h.busy() ? h.pushQueue(e) : h.fireQueueItem(e), h }, h.clearQueue = function () { return h.busy.flag = !1, h.queues = [], h }, h.stateChanged = !1, h.doubleChecker = !1, h.doubleCheckComplete = function () { return h.stateChanged = !0, h.doubleCheckClear(), h }, h.doubleCheckClear = function () { return h.doubleChecker && (u(h.doubleChecker), h.doubleChecker = !1), h }, h.doubleCheck = function (e) { return h.stateChanged = !1, h.doubleCheckClear(), h.bugs.ieDoubleCheck && (h.doubleChecker = o(function () { return h.doubleCheckClear(), h.stateChanged || e(), !0 }, h.options.doubleCheckInterval)), h }, h.safariStatePoll = function () { var t = h.extractState(h.getLocationHref()), n; if (!h.isLastSavedState(t)) return n = t, n || (n = h.createStateObject()), h.Adapter.trigger(e, "popstate"), h; return }, h.back = function (e) { return e !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.back, args: arguments, queue: e }), !1) : (h.busy(!0), h.doubleCheck(function () { h.back(!1) }), p.go(-1), !0) }, h.forward = function (e) { return e !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.forward, args: arguments, queue: e }), !1) : (h.busy(!0), h.doubleCheck(function () { h.forward(!1) }), p.go(1), !0) }, h.go = function (e, t) { var n; if (e > 0) for (n = 1; n <= e; ++n)h.forward(t); else { if (!(e < 0)) throw new Error("History.go: History.go requires a positive or negative integer passed."); for (n = -1; n >= e; --n)h.back(t) } return h }; if (h.emulated.pushState) { var v = function () { }; h.pushState = h.pushState || v, h.replaceState = h.replaceState || v } else h.onPopState = function (t, n) { var r = !1, i = !1, s, o; return h.doubleCheckComplete(), s = h.getHash(), s ? (o = h.extractState(s || h.getLocationHref(), !0), o ? h.replaceState(o.data, o.title, o.url, !1) : (h.Adapter.trigger(e, "anchorchange"), h.busy(!1)), h.expectedStateId = !1, !1) : (r = h.Adapter.extractEventData("state", t, n) || !1, r ? i = h.getStateById(r) : h.expectedStateId ? i = h.getStateById(h.expectedStateId) : i = h.extractState(h.getLocationHref()), i || (i = h.createStateObject(null, null, h.getLocationHref())), h.expectedStateId = !1, h.isLastSavedState(i) ? (h.busy(!1), !1) : (h.storeState(i), h.saveState(i), h.setTitle(i), h.Adapter.trigger(e, "statechange"), h.busy(!1), !0)) }, h.Adapter.bind(e, "popstate", h.onPopState), h.pushState = function (t, n, r, i) { if (h.getHashByUrl(r) && h.emulated.pushState) throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors)."); if (i !== !1 && h.busy()) return h.pushQueue({ scope: h, callback: h.pushState, args: arguments, queue: i }), !1; h.busy(!0); var s = h.createStateObject(t, n, r); return h.isLastSavedState(s) ? h.busy(!1) : (h.storeState(s), h.expectedStateId = s.id, p.pushState(s.id, s.title, s.url), h.Adapter.trigger(e, "popstate")), !0 }, h.replaceState = function (t, n, r, i) { if (h.getHashByUrl(r) && h.emulated.pushState) throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors)."); if (i !== !1 && h.busy()) return h.pushQueue({ scope: h, callback: h.replaceState, args: arguments, queue: i }), !1; h.busy(!0); var s = h.createStateObject(t, n, r); return h.isLastSavedState(s) ? h.busy(!1) : (h.storeState(s), h.expectedStateId = s.id, p.replaceState(s.id, s.title, s.url), h.Adapter.trigger(e, "popstate")), !0 }; if (s) { try { h.store = l.parse(s.getItem("History.store")) || {} } catch (m) { h.store = {} } h.normalizeStore() } else h.store = {}, h.normalizeStore(); h.Adapter.bind(e, "unload", h.clearAllIntervals), h.saveState(h.storeState(h.extractState(h.getLocationHref(), !0))), s && (h.onUnload = function () { var e, t, n; try { e = l.parse(s.getItem("History.store")) || {} } catch (r) { e = {} } e.idToState = e.idToState || {}, e.urlToId = e.urlToId || {}, e.stateToId = e.stateToId || {}; for (t in h.idToState) { if (!h.idToState.hasOwnProperty(t)) continue; e.idToState[t] = h.idToState[t] } for (t in h.urlToId) { if (!h.urlToId.hasOwnProperty(t)) continue; e.urlToId[t] = h.urlToId[t] } for (t in h.stateToId) { if (!h.stateToId.hasOwnProperty(t)) continue; e.stateToId[t] = h.stateToId[t] } h.store = e, h.normalizeStore(), n = l.stringify(e); try { s.setItem("History.store", n) } catch (i) { if (i.code !== DOMException.QUOTA_EXCEEDED_ERR) throw i; s.length && (s.removeItem("History.store"), s.setItem("History.store", n)) } }, h.intervalList.push(a(h.onUnload, h.options.storeInterval)), h.Adapter.bind(e, "beforeunload", h.onUnload), h.Adapter.bind(e, "unload", h.onUnload)); if (!h.emulated.pushState) { h.bugs.safariPoll && h.intervalList.push(a(h.safariStatePoll, h.options.safariPollInterval)); if (i.vendor === "Apple Computer, Inc." || (i.appCodeName || "") === "Mozilla") h.Adapter.bind(e, "hashchange", function () { h.Adapter.trigger(e, "popstate") }), h.getHash() && h.Adapter.onDomLoad(function () { h.Adapter.trigger(e, "hashchange") }) } }, (!h.options || !h.options.delayInit) && h.init() }(window);
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};

// Define then the messages
window.ParsleyConfig.i18n.sv = $.extend(window.ParsleyConfig.i18n.sv || {}, {
    defaultMessage: "Ogiltigt värde.",
    type: {
        email: "Ange en giltig e-postadress.",
        url: "Ange en giltig URL.",
        number: "Ange ett giltigt nummer.",
        integer: "Ange ett heltal.",
        digits: "Ange endast siffror.",
        alphanum: "Ange endast bokstäver och siffror."
    },
    notblank: "Värdet får inte vara tomt.",
    required: "Måste fyllas i.",
    pattern: "Värdet är ej giltigt.",
    min: "Värdet måste vara större än eller lika med %s.",
    max: "Värdet måste vara mindre än eller lika med %s.",
    range: "Värdet måste vara mellan %s och %s.",
    minlength: "Värdet måste vara minst %s tecken.",
    maxlength: "Värdet får maximalt innehålla %s tecken.",
    length: "Måste vara mellan %s och %s tecken.",
    mincheck: "Minst %s val måste göras.",
    maxcheck: "Maximalt %s val får göras.",
    check: "Mellan %s och %s val måste göras.",
    equalto: "Värdena måste vara lika."
});

// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
    window.ParsleyValidator.addCatalog('sv', window.ParsleyConfig.i18n.sv, true);
;
/*!
* Parsley.js
* Version 2.2.0-rc4 - built Thu, Oct 29th 2015, 4:25 pm
* http://parsleyjs.org
* Guillaume Potier - <guillaume@wisembly.com>
* Marc-Andre Lafortune - <petroselinum@marc-andre.ca>
* MIT Licensed
*/
!function (e, t) { "object" == typeof exports && "undefined" != typeof module ? module.exports = t(require("jquery")) : "function" == typeof define && define.amd ? define(["jquery"], t) : e.parsley = t(e.jQuery) }(this, function (e) {
    "use strict"; function t(e, t) { return e.parsleyAdaptedCallback || (e.parsleyAdaptedCallback = function () { var i = Array.prototype.slice.call(arguments, 0); i.unshift(this), e.apply(t || M, i) }), e.parsleyAdaptedCallback } function i(e) { return 0 === e.lastIndexOf(O, 0) ? e.substr(O.length) : e } var n = 1, r = {}, s = { attr: function (e, t, i) { var n, r, s, a = new RegExp("^" + t, "i"); if ("undefined" == typeof i) i = {}; else for (n in i) i.hasOwnProperty(n) && delete i[n]; if ("undefined" == typeof e || "undefined" == typeof e[0]) return i; for (s = e[0].attributes, n = s.length; n--;) r = s[n], r && r.specified && a.test(r.name) && (i[this.camelize(r.name.slice(t.length))] = this.deserializeValue(r.value)); return i }, checkAttr: function (e, t, i) { return e.is("[" + t + i + "]") }, setAttr: function (e, t, i, n) { e[0].setAttribute(this.dasherize(t + i), String(n)) }, generateID: function () { return "" + n++ }, deserializeValue: function (t) { var i; try { return t ? "true" == t || ("false" == t ? !1 : "null" == t ? null : isNaN(i = Number(t)) ? /^[\[\{]/.test(t) ? e.parseJSON(t) : t : i) : t } catch (n) { return t } }, camelize: function (e) { return e.replace(/-+(.)?/g, function (e, t) { return t ? t.toUpperCase() : "" }) }, dasherize: function (e) { return e.replace(/::/g, "/").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").replace(/_/g, "-").toLowerCase() }, warn: function () { window.console && "function" == typeof window.console.warn && window.console.warn.apply(window.console, arguments) }, warnOnce: function (e) { r[e] || (r[e] = !0, this.warn.apply(this, arguments)) }, _resetWarnings: function () { r = {} }, trimString: function (e) { return e.replace(/^\s+|\s+$/g, "") }, objectCreate: Object.create || function () { var e = function () { }; return function (t) { if (arguments.length > 1) throw Error("Second argument not supported"); if ("object" != typeof t) throw TypeError("Argument must be an object"); e.prototype = t; var i = new e; return e.prototype = null, i } }() }, a = s, o = { namespace: "data-parsley-", inputs: "input, textarea, select", excluded: "input[type=button], input[type=submit], input[type=reset], input[type=hidden]", priorityEnabled: !0, multiple: null, group: null, uiEnabled: !0, validationThreshold: 3, focus: "first", trigger: !1, errorClass: "parsley-error", successClass: "parsley-success", classHandler: function (e) { }, errorsContainer: function (e) { }, errorsWrapper: '<ul class="parsley-errors-list"></ul>', errorTemplate: "<li></li>" }, l = function () { }; l.prototype = { asyncSupport: !0, actualizeOptions: function () { return a.attr(this.$element, this.options.namespace, this.domOptions), this.parent && this.parent.actualizeOptions && this.parent.actualizeOptions(), this }, _resetOptions: function (e) { this.domOptions = a.objectCreate(this.parent.options), this.options = a.objectCreate(this.domOptions); for (var t in e) e.hasOwnProperty(t) && (this.options[t] = e[t]); this.actualizeOptions() }, _listeners: null, on: function (e, t) { this._listeners = this._listeners || {}; var i = this._listeners[e] = this._listeners[e] || []; return i.push(t), this }, subscribe: function (t, i) { e.listenTo(this, t.toLowerCase(), i) }, off: function (e, t) { var i = this._listeners && this._listeners[e]; if (i) if (t) for (var n = i.length; n--;) i[n] === t && i.splice(n, 1); else delete this._listeners[e]; return this }, unsubscribe: function (t, i) { e.unsubscribeTo(this, t.toLowerCase()) }, trigger: function (e, t, i) { t = t || this; var n, r = this._listeners && this._listeners[e]; if (r) for (var s = r.length; s--;) if (n = r[s].call(t, t, i), n === !1) return n; return this.parent ? this.parent.trigger(e, t, i) : !0 }, reset: function () { if ("ParsleyForm" !== this.__class__) return this._trigger("reset"); for (var e = 0; e < this.fields.length; e++) this.fields[e]._trigger("reset"); this._trigger("reset") }, destroy: function () { if ("ParsleyForm" !== this.__class__) return this.$element.removeData("Parsley"), this.$element.removeData("ParsleyFieldMultiple"), void this._trigger("destroy"); for (var e = 0; e < this.fields.length; e++) this.fields[e].destroy(); this.$element.removeData("Parsley"), this._trigger("destroy") }, asyncIsValid: function () { return a.warnOnce("asyncIsValid is deprecated; please use whenIsValid instead"), this.whenValid.apply(this, arguments) }, _findRelatedMultiple: function () { return this.parent.$element.find("[" + this.options.namespace + 'multiple="' + this.options.multiple + '"]') } }; var u = { string: function (e) { return e }, integer: function (e) { if (isNaN(e)) throw 'Requirement is not an integer: "' + e + '"'; return parseInt(e, 10) }, number: function (e) { if (isNaN(e)) throw 'Requirement is not a number: "' + e + '"'; return parseFloat(e) }, reference: function (t) { var i = e(t); if (0 === i.length) throw 'No such reference: "' + t + '"'; return i }, "boolean": function (e) { return "false" !== e }, object: function (e) { return a.deserializeValue(e) }, regexp: function (e) { var t = ""; return /^\/.*\/(?:[gimy]*)$/.test(e) ? (t = e.replace(/.*\/([gimy]*)$/, "$1"), e = e.replace(new RegExp("^/(.*?)/" + t + "$"), "$1")) : e = "^" + e + "$", new RegExp(e, t) } }, d = function (e, t) { var i = e.match(/^\s*\[(.*)\]\s*$/); if (!i) throw 'Requirement is not an array: "' + e + '"'; var n = i[1].split(",").map(a.trimString); if (n.length !== t) throw "Requirement has " + n.length + " values when " + t + " are needed"; return n }, h = function (e, t) { var i = u[e || "string"]; if (!i) throw 'Unknown requirement specification: "' + e + '"'; return i(t) }, p = function (e, t, i) { var n = null, r = {}; for (var s in e) if (s) { var a = i(s); "string" == typeof a && (a = h(e[s], a)), r[s] = a } else n = h(e[s], t); return [n, r] }, f = function (t) { e.extend(!0, this, t) }; f.prototype = { validate: function (t, i) { if (this.fn) return arguments.length > 3 && (i = [].slice.call(arguments, 1, -1)), this.fn.call(this, t, i); if (e.isArray(t)) { if (!this.validateMultiple) throw "Validator `" + this.name + "` does not handle multiple values"; return this.validateMultiple.apply(this, arguments) } if (this.validateNumber) return isNaN(t) ? !1 : (arguments[0] = parseFloat(arguments[0]), this.validateNumber.apply(this, arguments)); if (this.validateString) return this.validateString.apply(this, arguments); throw "Validator `" + this.name + "` only handles multiple values" }, parseRequirements: function (t, i) { if ("string" != typeof t) return e.isArray(t) ? t : [t]; var n = this.requirementType; if (e.isArray(n)) { for (var r = d(t, n.length), s = 0; s < r.length; s++) r[s] = h(n[s], r[s]); return r } return e.isPlainObject(n) ? p(n, t, i) : [h(n, t)] }, requirementType: "string", priority: 2 }; var c = function (e, t) { this.__class__ = "ParsleyValidatorRegistry", this.locale = "en", this.init(e || {}, t || {}) }, m = { email: /^((([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, number: /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, integer: /^-?\d+$/, digits: /^\d+$/, alphanum: /^\w+$/i, url: new RegExp("^(?:(?:https?|ftp)://)?(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:/\\S*)?$", "i") }; m.range = m.number, c.prototype = { init: function (t, i) { this.catalog = i, this.validators = e.extend({}, this.validators); for (var n in t) this.addValidator(n, t[n].fn, t[n].priority); window.Parsley.trigger("parsley:validator:init") }, setLocale: function (e) { if ("undefined" == typeof this.catalog[e]) throw new Error(e + " is not available in the catalog"); return this.locale = e, this }, addCatalog: function (e, t, i) { return "object" == typeof t && (this.catalog[e] = t), !0 === i ? this.setLocale(e) : this }, addMessage: function (e, t, i) { return "undefined" == typeof this.catalog[e] && (this.catalog[e] = {}), this.catalog[e][t] = i, this }, addMessages: function (e, t) { for (var i in t) this.addMessage(e, i, t[i]); return this }, addValidator: function (e, t, i) { if (this.validators[e]) a.warn('Validator "' + e + '" is already defined.'); else if (o.hasOwnProperty(e)) return void a.warn('"' + e + '" is a restricted keyword and is not a valid validator name.'); return this._setValidator.apply(this, arguments) }, updateValidator: function (e, t, i) { return this.validators[e] ? this._setValidator(this, arguments) : (a.warn('Validator "' + e + '" is not already defined.'), this.addValidator.apply(this, arguments)) }, removeValidator: function (e) { return this.validators[e] || a.warn('Validator "' + e + '" is not defined.'), delete this.validators[e], this }, _setValidator: function (e, t, i) { "object" != typeof t && (t = { fn: t, priority: i }), t.validate || (t = new f(t)), this.validators[e] = t; for (var n in t.messages || {}) this.addMessage(n, e, t.messages[n]); return this }, getErrorMessage: function (e) { var t; if ("type" === e.name) { var i = this.catalog[this.locale][e.name] || {}; t = i[e.requirements] } else t = this.formatMessage(this.catalog[this.locale][e.name], e.requirements); return t || this.catalog[this.locale].defaultMessage || this.catalog.en.defaultMessage }, formatMessage: function (e, t) { if ("object" == typeof t) { for (var i in t) e = this.formatMessage(e, t[i]); return e } return "string" == typeof e ? e.replace(new RegExp("%s", "i"), t) : "" }, validators: { notblank: { validateString: function (e) { return /\S/.test(e) }, priority: 2 }, required: { validateMultiple: function (e) { return e.length > 0 }, validateString: function (e) { return /\S/.test(e) }, priority: 512 }, type: { validateString: function (e, t) { var i = m[t]; if (!i) throw new Error("validator type `" + t + "` is not supported"); return i.test(e) }, priority: 256 }, pattern: { validateString: function (e, t) { return t.test(e) }, requirementType: "regexp", priority: 64 }, minlength: { validateString: function (e, t) { return e.length >= t }, requirementType: "integer", priority: 30 }, maxlength: { validateString: function (e, t) { return e.length <= t }, requirementType: "integer", priority: 30 }, length: { validateString: function (e, t, i) { return e.length >= t && e.length <= i }, requirementType: ["integer", "integer"], priority: 30 }, mincheck: { validateMultiple: function (e, t) { return e.length >= t }, requirementType: "integer", priority: 30 }, maxcheck: { validateMultiple: function (e, t) { return e.length <= t }, requirementType: "integer", priority: 30 }, check: { validateMultiple: function (e, t, i) { return e.length >= t && e.length <= i }, requirementType: ["integer", "integer"], priority: 30 }, min: { validateNumber: function (e, t) { return e >= t }, requirementType: "number", priority: 30 }, max: { validateNumber: function (e, t) { return t >= e }, requirementType: "number", priority: 30 }, range: { validateNumber: function (e, t, i) { return e >= t && i >= e }, requirementType: ["number", "number"], priority: 30 }, equalto: { validateString: function (t, i) { var n = e(i); return n.length ? t === n.val() : t === i }, priority: 256 } } }; var y = function (e) { this.__class__ = "ParsleyUI" }; y.prototype = { listen: function () { var e = this; return window.Parsley.on("form:init", function () { e.setupForm(this) }).on("field:init", function () { e.setupField(this) }).on("field:validated", function () { e.reflow(this) }).on("form:validated", function () { e.focus(this) }).on("field:reset", function () { e.reset(this) }).on("form:destroy", function () { e.destroy(this) }).on("field:destroy", function () { e.destroy(this) }), this }, reflow: function (e) { if ("undefined" != typeof e._ui && !1 !== e._ui.active) { var t = this._diff(e.validationResult, e._ui.lastValidationResult); e._ui.lastValidationResult = e.validationResult, e._ui.validatedOnce = !0, this.manageStatusClass(e), this.manageErrorsMessages(e, t), this.actualizeTriggers(e), (t.kept.length || t.added.length) && !0 !== e._ui.failedOnce && this.manageFailingFieldTrigger(e) } }, getErrorsMessages: function (e) { if (!0 === e.validationResult) return []; for (var t = [], i = 0; i < e.validationResult.length; i++) t.push(e.validationResult[i].errorMessage || this._getErrorMessage(e, e.validationResult[i].assert)); return t }, manageStatusClass: function (e) { e.hasConstraints() && e.needsValidation() && !0 === e.validationResult ? this._successClass(e) : e.validationResult.length > 0 ? this._errorClass(e) : this._resetClass(e) }, manageErrorsMessages: function (t, i) { if ("undefined" == typeof t.options.errorsMessagesDisabled) { if ("undefined" != typeof t.options.errorMessage) return i.added.length || i.kept.length ? (this._insertErrorWrapper(t), 0 === t._ui.$errorsWrapper.find(".parsley-custom-error-message").length && t._ui.$errorsWrapper.append(e(t.options.errorTemplate).addClass("parsley-custom-error-message")), t._ui.$errorsWrapper.addClass("filled").find(".parsley-custom-error-message").html(t.options.errorMessage)) : t._ui.$errorsWrapper.removeClass("filled").find(".parsley-custom-error-message").remove(); for (var n = 0; n < i.removed.length; n++) this.removeError(t, i.removed[n].assert.name, !0); for (n = 0; n < i.added.length; n++) this.addError(t, i.added[n].assert.name, i.added[n].errorMessage, i.added[n].assert, !0); for (n = 0; n < i.kept.length; n++) this.updateError(t, i.kept[n].assert.name, i.kept[n].errorMessage, i.kept[n].assert, !0) } }, addError: function (t, i, n, r, s) { this._insertErrorWrapper(t), t._ui.$errorsWrapper.addClass("filled").append(e(t.options.errorTemplate).addClass("parsley-" + i).html(n || this._getErrorMessage(t, r))), !0 !== s && this._errorClass(t) }, updateError: function (e, t, i, n, r) { e._ui.$errorsWrapper.addClass("filled").find(".parsley-" + t).html(i || this._getErrorMessage(e, n)), !0 !== r && this._errorClass(e) }, removeError: function (e, t, i) { e._ui.$errorsWrapper.removeClass("filled").find(".parsley-" + t).remove(), !0 !== i && this.manageStatusClass(e) }, focus: function (e) { if (e._focusedField = null, !0 === e.validationResult || "none" === e.options.focus) return null; for (var t = 0; t < e.fields.length; t++) { var i = e.fields[t]; if (!0 !== i.validationResult && i.validationResult.length > 0 && "undefined" == typeof i.options.noFocus && (e._focusedField = i.$element, "first" === e.options.focus)) break } return null === e._focusedField ? null : e._focusedField.focus() }, _getErrorMessage: function (e, t) { var i = t.name + "Message"; return "undefined" != typeof e.options[i] ? window.Parsley.formatMessage(e.options[i], t.requirements) : window.Parsley.getErrorMessage(t) }, _diff: function (e, t, i) { for (var n = [], r = [], s = 0; s < e.length; s++) { for (var a = !1, o = 0; o < t.length; o++) if (e[s].assert.name === t[o].assert.name) { a = !0; break } a ? r.push(e[s]) : n.push(e[s]) } return { kept: r, added: n, removed: i ? [] : this._diff(t, e, !0).added } }, setupForm: function (t) { t.$element.on("submit.Parsley", !1, e.proxy(t.onSubmitValidate, t)), t.$element.on("click.Parsley", 'input[type="submit"], button[type="submit"]', e.proxy(t.onSubmitButton, t)), !1 !== t.options.uiEnabled && t.$element.attr("novalidate", "") }, setupField: function (t) { var i = { active: !1 }; !1 !== t.options.uiEnabled && (i.active = !0, t.$element.attr(t.options.namespace + "id", t.__id__), i.$errorClassHandler = this._manageClassHandler(t), i.errorsWrapperId = "parsley-id-" + (t.options.multiple ? "multiple-" + t.options.multiple : t.__id__), i.$errorsWrapper = e(t.options.errorsWrapper).attr("id", i.errorsWrapperId), i.lastValidationResult = [], i.validatedOnce = !1, i.validationInformationVisible = !1, t._ui = i, this.actualizeTriggers(t)) }, _manageClassHandler: function (t) { if ("string" == typeof t.options.classHandler && e(t.options.classHandler).length) return e(t.options.classHandler); var i = t.options.classHandler(t); return "undefined" != typeof i && i.length ? i : !t.options.multiple || t.$element.is("select") ? t.$element : t.$element.parent() }, _insertErrorWrapper: function (t) { var i; if (0 !== t._ui.$errorsWrapper.parent().length) return t._ui.$errorsWrapper.parent(); if ("string" == typeof t.options.errorsContainer) { if (e(t.options.errorsContainer).length) return e(t.options.errorsContainer).append(t._ui.$errorsWrapper); a.warn("The errors container `" + t.options.errorsContainer + "` does not exist in DOM") } else "function" == typeof t.options.errorsContainer && (i = t.options.errorsContainer(t)); if ("undefined" != typeof i && i.length) return i.append(t._ui.$errorsWrapper); var n = t.$element; return t.options.multiple && (n = n.parent()), n.after(t._ui.$errorsWrapper) }, actualizeTriggers: function (t) { var i = t.$element; if (t.options.multiple && (i = e("[" + t.options.namespace + 'multiple="' + t.options.multiple + '"]')), i.off(".Parsley"), !1 !== t.options.trigger) { var n = t.options.trigger.replace(/^\s+/g, "").replace(/\s+$/g, ""); "" !== n && i.on(n.split(" ").join(".Parsley ") + ".Parsley", e.proxy("function" == typeof t.eventValidate ? t.eventValidate : this.eventValidate, t)) } }, eventValidate: function (e) { new RegExp("key").test(e.type) && !this._ui.validationInformationVisible && this.getValue().length <= this.options.validationThreshold || (this._ui.validatedOnce = !0, this.validate()) }, manageFailingFieldTrigger: function (t) { return t._ui.failedOnce = !0, t.options.multiple && e("[" + t.options.namespace + 'multiple="' + t.options.multiple + '"]').each(function () { return new RegExp("change", "i").test(e(this).parsley().options.trigger || "") ? void 0 : e(this).on("change.ParsleyFailedOnce", !1, e.proxy(t.validate, t)) }), t.$element.is("select") && !new RegExp("change", "i").test(t.options.trigger || "") ? t.$element.on("change.ParsleyFailedOnce", !1, e.proxy(t.validate, t)) : new RegExp("keyup", "i").test(t.options.trigger || "") ? void 0 : t.$element.on("keyup.ParsleyFailedOnce", !1, e.proxy(t.validate, t)) }, reset: function (e) { this.actualizeTriggers(e), e.$element.off(".ParsleyFailedOnce"), "undefined" != typeof e._ui && "ParsleyForm" !== e.__class__ && (e._ui.$errorsWrapper.removeClass("filled").children().remove(), this._resetClass(e), e._ui.validatedOnce = !1, e._ui.lastValidationResult = [], e._ui.validationInformationVisible = !1, e._ui.failedOnce = !1) }, destroy: function (e) { this.reset(e), "ParsleyForm" !== e.__class__ && ("undefined" != typeof e._ui && e._ui.$errorsWrapper.remove(), delete e._ui) }, _successClass: function (e) { e._ui.validationInformationVisible = !0, e._ui.$errorClassHandler.removeClass(e.options.errorClass).addClass(e.options.successClass) }, _errorClass: function (e) { e._ui.validationInformationVisible = !0, e._ui.$errorClassHandler.removeClass(e.options.successClass).addClass(e.options.errorClass) }, _resetClass: function (e) { e._ui.$errorClassHandler.removeClass(e.options.successClass).removeClass(e.options.errorClass) } }; var g = function (t, i, n) { this.__class__ = "ParsleyForm", this.__id__ = a.generateID(), this.$element = e(t), this.domOptions = i, this.options = n, this.parent = window.Parsley, this.fields = [], this.validationResult = null }, v = { pending: null, resolved: !0, rejected: !1 }; g.prototype = { onSubmitValidate: function (e) { var t = this; if (!0 !== e.parsley) return this._$submitSource = this._$submitSource || this.$element.find('input[type="submit"], button[type="submit"]').first(), this._$submitSource.is("[formnovalidate]") ? void (this._$submitSource = null) : (e.stopImmediatePropagation(), e.preventDefault(), this.whenValidate(void 0, void 0, e).done(function () { t._submit() }).always(function () { t._$submitSource = null }), this) }, onSubmitButton: function (t) { this._$submitSource = e(t.target) }, _submit: function () { !1 !== this._trigger("submit") && (this.$element.find(".parsley_synthetic_submit_button").remove(), this._$submitSource && e('<input class="parsley_synthetic_submit_button" type="hidden">').attr("name", this._$submitSource.attr("name")).attr("value", this._$submitSource.attr("value")).appendTo(this.$element), this.$element.trigger(e.extend(e.Event("submit"), { parsley: !0 }))) }, validate: function (e, t, i) { return v[this.whenValidate(e, t, i).state()] }, whenValidate: function (t, i, n) { var r = this; this.submitEvent = n, this.validationResult = !0, this._trigger("validate"), this._refreshFields(); var s = this._withoutReactualizingFormOptions(function () { return e.map(this.fields, function (e) { return !t || r._isFieldInGroup(e, t) ? e.whenValidate(i) : void 0 }) }), a = function () { var t = e.Deferred(); return !1 === r.validationResult && t.reject(), t.resolve().promise() }; return e.when.apply(e, s).done(function () { r._trigger("success") }).fail(function () { r.validationResult = !1, r._trigger("error") }).always(function () { r._trigger("validated") }).pipe(a, a) }, isValid: function (e, t) { return v[this.whenValid(e, t).state()] }, whenValid: function (t, i) { var n = this; this._refreshFields(); var r = this._withoutReactualizingFormOptions(function () { return e.map(this.fields, function (e) { return !t || n._isFieldInGroup(e, t) ? e.whenValid(i) : void 0 }) }); return e.when.apply(e, r) }, _isFieldInGroup: function (t, i) { return e.isArray(t.options.group) ? -1 !== e.inArray(i, t.options.group) : t.options.group === i }, _refreshFields: function () { return this.actualizeOptions()._bindFields() }, _bindFields: function () { var t = this, i = this.fields; return this.fields = [], this.fieldsMappedById = {}, this._withoutReactualizingFormOptions(function () { this.$element.find(this.options.inputs).not(this.options.excluded).each(function () { var e = new window.Parsley.Factory(this, {}, t); "ParsleyField" !== e.__class__ && "ParsleyFieldMultiple" !== e.__class__ || !0 === e.options.excluded || "undefined" == typeof t.fieldsMappedById[e.__class__ + "-" + e.__id__] && (t.fieldsMappedById[e.__class__ + "-" + e.__id__] = e, t.fields.push(e)) }), e(i).not(t.fields).each(function () { this._trigger("reset") }) }), this }, _withoutReactualizingFormOptions: function (e) { var t = this.actualizeOptions; this.actualizeOptions = function () { return this }; var i = e.call(this); return this.actualizeOptions = t, i }, _trigger: function (e) { return this.trigger("form:" + e) } }; var _ = function (t, i, n, r, s) { if (!new RegExp("ParsleyField").test(t.__class__)) throw new Error("ParsleyField or ParsleyFieldMultiple instance expected"); var a = window.Parsley._validatorRegistry.validators[i], o = new f(a); e.extend(this, { validator: o, name: i, requirements: n, priority: r || t.options[i + "Priority"] || o.priority, isDomConstraint: !0 === s }), this._parseRequirements(t.options) }, w = function (e) { var t = e[0].toUpperCase(); return t + e.slice(1) }; _.prototype = { validate: function (e, t) { var i = this.requirementList.slice(0); return i.unshift(e), i.push(t), this.validator.validate.apply(this.validator, i) }, _parseRequirements: function (e) { var t = this; this.requirementList = this.validator.parseRequirements(this.requirements, function (i) { return e[t.name + w(i)] }) } }; var F = function (t, i, n, r) { this.__class__ = "ParsleyField", this.__id__ = a.generateID(), this.$element = e(t), "undefined" != typeof r && (this.parent = r), this.options = n, this.domOptions = i, this.constraints = [], this.constraintsByName = {}, this.validationResult = [], this._bindConstraints() }, b = { pending: null, resolved: !0, rejected: !1 }; F.prototype = { validate: function (e) { var t = this.whenValidate(e); switch (t.state()) { case "pending": return null; case "resolved": return !0; case "rejected": return this.validationResult } }, whenValidate: function (e) { var t = this; return this.value = this.getValue(), this._trigger("validate"), this.whenValid(e, this.value).done(function () { t._trigger("success") }).fail(function () { t._trigger("error") }).always(function () { t._trigger("validated") }) }, hasConstraints: function () { return 0 !== this.constraints.length }, needsValidation: function (e) { return "undefined" == typeof e && (e = this.getValue()), e.length || this._isRequired() || "undefined" != typeof this.options.validateIfEmpty ? !0 : !1 }, isValid: function (e, t) { return b[this.whenValid(e, t).state()] }, whenValid: function (t, i) { if (this.refreshConstraints(), this.validationResult = !0, !this.hasConstraints()) return e.when(); if ("boolean" != typeof t && "undefined" == typeof i && (i = t, t = !1), ("undefined" == typeof i || null === i) && (i = this.getValue()), !this.needsValidation(i) && !0 !== t) return e.when(); var n = this._getGroupedConstraints(), r = [], s = this; return e.each(n, function (t, n) { var a = e.when.apply(e, e.map(n, e.proxy(s, "_validateConstraint", i))); return r.push(a), "rejected" === a.state() ? !1 : void 0 }), e.when.apply(e, r) }, _validateConstraint: function (t, i) { var n = this, r = i.validate(t, this); return !1 === r && (r = e.Deferred().reject()), e.when(r).fail(function (e) { !0 === n.validationResult && (n.validationResult = []), n.validationResult.push({ assert: i, errorMessage: "string" == typeof e && e }) }) }, getValue: function () { var e; return e = "function" == typeof this.options.value ? this.options.value(this) : "undefined" != typeof this.options.value ? this.options.value : this.$element.val(), "undefined" == typeof e || null === e ? "" : this._handleWhitespace(e) }, refreshConstraints: function () { return this.actualizeOptions()._bindConstraints() }, addConstraint: function (e, t, i, n) { if (window.Parsley._validatorRegistry.validators[e]) { var r = new _(this, e, t, i, n); "undefined" !== this.constraintsByName[r.name] && this.removeConstraint(r.name), this.constraints.push(r), this.constraintsByName[r.name] = r } return this }, removeConstraint: function (e) { for (var t = 0; t < this.constraints.length; t++) if (e === this.constraints[t].name) { this.constraints.splice(t, 1); break } return delete this.constraintsByName[e], this }, updateConstraint: function (e, t, i) { return this.removeConstraint(e).addConstraint(e, t, i) }, _bindConstraints: function () { for (var e = [], t = {}, i = 0; i < this.constraints.length; i++) !1 === this.constraints[i].isDomConstraint && (e.push(this.constraints[i]), t[this.constraints[i].name] = this.constraints[i]); this.constraints = e, this.constraintsByName = t; for (var n in this.options) this.addConstraint(n, this.options[n], void 0, !0); return this._bindHtml5Constraints() }, _bindHtml5Constraints: function () { (this.$element.hasClass("required") || this.$element.attr("required")) && this.addConstraint("required", !0, void 0, !0), "string" == typeof this.$element.attr("pattern") && this.addConstraint("pattern", this.$element.attr("pattern"), void 0, !0), "undefined" != typeof this.$element.attr("min") && "undefined" != typeof this.$element.attr("max") ? this.addConstraint("range", [this.$element.attr("min"), this.$element.attr("max")], void 0, !0) : "undefined" != typeof this.$element.attr("min") ? this.addConstraint("min", this.$element.attr("min"), void 0, !0) : "undefined" != typeof this.$element.attr("max") && this.addConstraint("max", this.$element.attr("max"), void 0, !0), "undefined" != typeof this.$element.attr("minlength") && "undefined" != typeof this.$element.attr("maxlength") ? this.addConstraint("length", [this.$element.attr("minlength"), this.$element.attr("maxlength")], void 0, !0) : "undefined" != typeof this.$element.attr("minlength") ? this.addConstraint("minlength", this.$element.attr("minlength"), void 0, !0) : "undefined" != typeof this.$element.attr("maxlength") && this.addConstraint("maxlength", this.$element.attr("maxlength"), void 0, !0); var e = this.$element.attr("type"); return "undefined" == typeof e ? this : "number" === e ? "undefined" == typeof this.$element.attr("step") || 0 === parseFloat(this.$element.attr("step")) % 1 ? this.addConstraint("type", "integer", void 0, !0) : this.addConstraint("type", "number", void 0, !0) : /^(email|url|range)$/i.test(e) ? this.addConstraint("type", e, void 0, !0) : this }, _isRequired: function () { return "undefined" == typeof this.constraintsByName.required ? !1 : !1 !== this.constraintsByName.required.requirements }, _trigger: function (e) { return this.trigger("field:" + e) }, _handleWhitespace: function (e) { return !0 === this.options.trimValue && a.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"'), "squish" === this.options.whitespace && (e = e.replace(/\s{2,}/g, " ")), ("trim" === this.options.whitespace || "squish" === this.options.whitespace || !0 === this.options.trimValue) && (e = a.trimString(e)), e }, _getGroupedConstraints: function () { if (!1 === this.options.priorityEnabled) return [this.constraints]; for (var e = [], t = {}, i = 0; i < this.constraints.length; i++) { var n = this.constraints[i].priority; t[n] || e.push(t[n] = []), t[n].push(this.constraints[i]) } return e.sort(function (e, t) { return t[0].priority - e[0].priority }), e } }; var $ = F, C = function () { this.__class__ = "ParsleyFieldMultiple" }; C.prototype = { addElement: function (e) { return this.$elements.push(e), this }, refreshConstraints: function () { var t; if (this.constraints = [], this.$element.is("select")) return this.actualizeOptions()._bindConstraints(), this; for (var i = 0; i < this.$elements.length; i++) if (e("html").has(this.$elements[i]).length) { t = this.$elements[i].data("ParsleyFieldMultiple").refreshConstraints().constraints; for (var n = 0; n < t.length; n++) this.addConstraint(t[n].name, t[n].requirements, t[n].priority, t[n].isDomConstraint) } else this.$elements.splice(i, 1); return this }, getValue: function () { if ("undefined" != typeof this.options.value) return this.options.value; if (this.$element.is("input[type=radio]")) return this._findRelatedMultiple().filter(":checked").val() || ""; if (this.$element.is("input[type=checkbox]")) { var t = []; return this._findRelatedMultiple().filter(":checked").each(function () { t.push(e(this).val()) }), t } return this.$element.is("select") && null === this.$element.val() ? [] : this.$element.val() }, _init: function () { return this.$elements = [this.$element], this } }; var x = function (t, i, n) { this.$element = e(t); var r = this.$element.data("Parsley"); if (r) return "undefined" != typeof n && r.parent === window.Parsley && (r.parent = n, r._resetOptions(r.options)), r; if (!this.$element.length) throw new Error("You must bind Parsley on an existing element."); if ("undefined" != typeof n && "ParsleyForm" !== n.__class__) throw new Error("Parent instance must be a ParsleyForm instance"); return this.parent = n || window.Parsley, this.init(i) }; x.prototype = { init: function (e) { return this.__class__ = "Parsley", this.__version__ = "@@version", this.__id__ = a.generateID(), this._resetOptions(e), this.$element.is("form") || a.checkAttr(this.$element, this.options.namespace, "validate") && !this.$element.is(this.options.inputs) ? this.bind("parsleyForm") : this.isMultiple() ? this.handleMultiple() : this.bind("parsleyField") }, isMultiple: function () { return this.$element.is("input[type=radio], input[type=checkbox]") || this.$element.is("select") && "undefined" != typeof this.$element.attr("multiple") }, handleMultiple: function () { var t, i, n = this; if (this.options.multiple || ("undefined" != typeof this.$element.attr("name") && this.$element.attr("name").length ? this.options.multiple = t = this.$element.attr("name") : "undefined" != typeof this.$element.attr("id") && this.$element.attr("id").length && (this.options.multiple = this.$element.attr("id"))), this.$element.is("select") && "undefined" != typeof this.$element.attr("multiple")) return this.options.multiple = this.options.multiple || this.__id__, this.bind("parsleyFieldMultiple"); if (!this.options.multiple) return a.warn("To be bound by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.", this.$element), this; this.options.multiple = this.options.multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g, ""), "undefined" != typeof t && e('input[name="' + t + '"]').each(function () { e(this).is("input[type=radio], input[type=checkbox]") && e(this).attr(n.options.namespace + "multiple", n.options.multiple) }); for (var r = this._findRelatedMultiple(), s = 0; s < r.length; s++) if (i = e(r.get(s)).data("Parsley"), "undefined" != typeof i) { this.$element.data("ParsleyFieldMultiple") || i.addElement(this.$element); break } return this.bind("parsleyField", !0), i || this.bind("parsleyFieldMultiple") }, bind: function (t, i) { var n; switch (t) { case "parsleyForm": n = e.extend(new g(this.$element, this.domOptions, this.options), window.ParsleyExtend)._bindFields(); break; case "parsleyField": n = e.extend(new $(this.$element, this.domOptions, this.options, this.parent), window.ParsleyExtend); break; case "parsleyFieldMultiple": n = e.extend(new $(this.$element, this.domOptions, this.options, this.parent), new C, window.ParsleyExtend)._init(); break; default: throw new Error(t + "is not a supported Parsley type") } return this.options.multiple && a.setAttr(this.$element, this.options.namespace, "multiple", this.options.multiple), "undefined" != typeof i ? (this.$element.data("ParsleyFieldMultiple", n), n) : (this.$element.data("Parsley", n), n._trigger("init"), n) } }; var P = e.fn.jquery.split("."); if (parseInt(P[0]) <= 1 && parseInt(P[1]) < 8) throw "The loaded version of jQuery is too old. Please upgrade to 1.8.x or better."; P.forEach || a.warn("Parsley requires ES5 to run properly. Please include https://github.com/es-shims/es5-shim"); var V = e.extend(new l, { $element: e(document), actualizeOptions: null, _resetOptions: null, Factory: x, version: "@@version" }); e.extend($.prototype, l.prototype), e.extend(g.prototype, l.prototype), e.extend(x.prototype, l.prototype), e.fn.parsley = e.fn.psly = function (t) { if (this.length > 1) { var i = []; return this.each(function () { i.push(e(this).parsley(t)) }), i } return e(this).length ? new x(this, t) : void a.warn("You must bind Parsley on an existing element.") }, "undefined" == typeof window.ParsleyExtend && (window.ParsleyExtend = {}), V.options = e.extend(a.objectCreate(o), window.ParsleyConfig), window.ParsleyConfig = V.options,
    window.Parsley = window.psly = V, window.ParsleyUtils = a; var E = window.Parsley._validatorRegistry = new c(window.ParsleyConfig.validators, window.ParsleyConfig.i18n); window.ParsleyValidator = {}, e.each("setLocale addCatalog addMessage addMessages getErrorMessage formatMessage addValidator updateValidator removeValidator".split(" "), function (t, i) { window.Parsley[i] = e.proxy(E, i), window.ParsleyValidator[i] = function () { return a.warnOnce("Accessing the method '" + i + "' through ParsleyValidator is deprecated. Simply call 'window.Parsley." + i + "(...)'"), window.Parsley[i].apply(window.Parsley, arguments) } }), window.ParsleyUI = "function" == typeof window.ParsleyConfig.ParsleyUI ? (new window.ParsleyConfig.ParsleyUI).listen() : (new y).listen(), !1 !== window.ParsleyConfig.autoBind && e(function () { e("[data-parsley-validate]").length && e("[data-parsley-validate]").parsley() }); var M = e({}), R = function () { a.warnOnce("Parsley's pubsub module is deprecated; use the 'on' and 'off' methods on parsley instances or window.Parsley") }, O = "parsley:"; e.listen = function (e, n) { var r; if (R(), "object" == typeof arguments[1] && "function" == typeof arguments[2] && (r = arguments[1], n = arguments[2]), "function" != typeof n) throw new Error("Wrong parameters"); window.Parsley.on(i(e), t(n, r)) }, e.listenTo = function (e, n, r) { if (R(), !(e instanceof $ || e instanceof g)) throw new Error("Must give Parsley instance"); if ("string" != typeof n || "function" != typeof r) throw new Error("Wrong parameters"); e.on(i(n), t(r)) }, e.unsubscribe = function (e, t) { if (R(), "string" != typeof e || "function" != typeof t) throw new Error("Wrong arguments"); window.Parsley.off(i(e), t.parsleyAdaptedCallback) }, e.unsubscribeTo = function (e, t) { if (R(), !(e instanceof $ || e instanceof g)) throw new Error("Must give Parsley instance"); e.off(i(t)) }, e.unsubscribeAll = function (t) { R(), window.Parsley.off(i(t)), e("form,input,textarea,select").each(function () { var n = e(this).data("Parsley"); n && n.off(i(t)) }) }, e.emit = function (e, t) { R(); var n = t instanceof $ || t instanceof g, r = Array.prototype.slice.call(arguments, n ? 2 : 1); r.unshift(i(e)), n || (t = window.Parsley), t.trigger.apply(t, r) }; e.extend(!0, V, { asyncValidators: { "default": { fn: function (e) { return e.status >= 200 && e.status < 300 }, url: !1 }, reverse: { fn: function (e) { return e.status < 200 || e.status >= 300 }, url: !1 } }, addAsyncValidator: function (e, t, i, n) { return V.asyncValidators[e] = { fn: t, url: i || !1, options: n || {} }, this }, eventValidate: function (e) { new RegExp("key").test(e.type) && !this._ui.validationInformationVisible && this.getValue().length <= this.options.validationThreshold || (this._ui.validatedOnce = !0, this.whenValidate()) } }), V.addValidator("remote", { requirementType: { "": "string", validator: "string", reverse: "boolean", options: "object" }, validateString: function (t, i, n, r) { var s, a, o = {}, l = n.validator || (!0 === n.reverse ? "reverse" : "default"); if ("undefined" == typeof V.asyncValidators[l]) throw new Error("Calling an undefined async validator: `" + l + "`"); i = V.asyncValidators[l].url || i, i.indexOf("{value}") > -1 ? i = i.replace("{value}", encodeURIComponent(t)) : o[r.$element.attr("name") || r.$element.attr("id")] = t; var u = e.extend(!0, n.options || {}, V.asyncValidators[l].options); s = e.extend(!0, {}, { url: i, data: o, type: "GET" }, u), r.trigger("field:ajaxoptions", r, s), a = e.param(s), "undefined" == typeof V._remoteCache && (V._remoteCache = {}); var d = V._remoteCache[a] = V._remoteCache[a] || e.ajax(s), h = function () { var t = V.asyncValidators[l].fn.call(r, d, i, n); return t || (t = e.Deferred().reject()), e.when(t) }; return d.then(h, h) }, priority: -1 }), V.on("form:submit", function () { V._remoteCache = {} }), window.ParsleyExtend.addAsyncValidator = function () { return ParsleyUtils.warnOnce("Accessing the method `addAsyncValidator` through an instance is deprecated. Simply call `Parsley.addAsyncValidator(...)`"), V.apply(V.addAsyncValidator, arguments) }, V.addMessages("en", { defaultMessage: "This value seems to be invalid.", type: { email: "This value should be a valid email.", url: "This value should be a valid url.", number: "This value should be a valid number.", integer: "This value should be a valid integer.", digits: "This value should be digits.", alphanum: "This value should be alphanumeric." }, notblank: "This value should not be blank.", required: "This value is required.", pattern: "This value seems to be invalid.", min: "This value should be greater than or equal to %s.", max: "This value should be lower than or equal to %s.", range: "This value should be between %s and %s.", minlength: "This value is too short. It should have %s characters or more.", maxlength: "This value is too long. It should have %s characters or fewer.", length: "This value length is invalid. It should be between %s and %s characters long.", mincheck: "You must select at least %s choices.", maxcheck: "You must select %s choices or fewer.", check: "You must select between %s and %s choices.", equalto: "This value should be the same." }), V.setLocale("en"); var q = V; return q
});
//# sourceMappingURL=parsley.min.js.map
;
/*
Copyright 2014 Igor Vaynberg

Version: 3.5.1 Timestamp: Tue Jul 22 18:58:56 EDT 2014

This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
General Public License version 2 (the "GPL License"). You may choose either license to govern your
use of this software only upon the condition that you accept all of the terms of either the Apache
License or the GPL License.

You may obtain a copy of the Apache License and the GPL License at:

http://www.apache.org/licenses/LICENSE-2.0
http://www.gnu.org/licenses/gpl-2.0.html

Unless required by applicable law or agreed to in writing, software distributed under the Apache License
or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the Apache License and the GPL License for the specific language governing
permissions and limitations under the Apache License and the GPL License.
*/
!function(a){"undefined"==typeof a.fn.each2&&a.extend(a.fn,{each2:function(b){for(var c=a([0]),d=-1,e=this.length;++d<e&&(c.context=c[0]=this[d])&&b.call(c[0],d,c)!==!1;);return this}})}(jQuery),function(a,b){"use strict";function n(b){var c=a(document.createTextNode(""));b.before(c),c.before(b),c.remove()}function o(a){function b(a){return m[a]||a}return a.replace(/[^\u0000-\u007E]/g,b)}function p(a,b){for(var c=0,d=b.length;d>c;c+=1)if(r(a,b[c]))return c;return-1}function q(){var b=a(l);b.appendTo("body");var c={width:b.width()-b[0].clientWidth,height:b.height()-b[0].clientHeight};return b.remove(),c}function r(a,c){return a===c?!0:a===b||c===b?!1:null===a||null===c?!1:a.constructor===String?a+""==c+"":c.constructor===String?c+""==a+"":!1}function s(b,c){var d,e,f;if(null===b||b.length<1)return[];for(d=b.split(c),e=0,f=d.length;f>e;e+=1)d[e]=a.trim(d[e]);return d}function t(a){return a.outerWidth(!1)-a.width()}function u(c){var d="keyup-change-value";c.on("keydown",function(){a.data(c,d)===b&&a.data(c,d,c.val())}),c.on("keyup",function(){var e=a.data(c,d);e!==b&&c.val()!==e&&(a.removeData(c,d),c.trigger("keyup-change"))})}function v(c){c.on("mousemove",function(c){var d=i;(d===b||d.x!==c.pageX||d.y!==c.pageY)&&a(c.target).trigger("mousemove-filtered",c)})}function w(a,c,d){d=d||b;var e;return function(){var b=arguments;window.clearTimeout(e),e=window.setTimeout(function(){c.apply(d,b)},a)}}function x(a,b){var c=w(a,function(a){b.trigger("scroll-debounced",a)});b.on("scroll",function(a){p(a.target,b.get())>=0&&c(a)})}function y(a){a[0]!==document.activeElement&&window.setTimeout(function(){var d,b=a[0],c=a.val().length;a.focus();var e=b.offsetWidth>0||b.offsetHeight>0;e&&b===document.activeElement&&(b.setSelectionRange?b.setSelectionRange(c,c):b.createTextRange&&(d=b.createTextRange(),d.collapse(!1),d.select()))},0)}function z(b){b=a(b)[0];var c=0,d=0;if("selectionStart"in b)c=b.selectionStart,d=b.selectionEnd-c;else if("selection"in document){b.focus();var e=document.selection.createRange();d=document.selection.createRange().text.length,e.moveStart("character",-b.value.length),c=e.text.length-d}return{offset:c,length:d}}function A(a){a.preventDefault(),a.stopPropagation()}function B(a){a.preventDefault(),a.stopImmediatePropagation()}function C(b){if(!h){var c=b[0].currentStyle||window.getComputedStyle(b[0],null);h=a(document.createElement("div")).css({position:"absolute",left:"-10000px",top:"-10000px",display:"none",fontSize:c.fontSize,fontFamily:c.fontFamily,fontStyle:c.fontStyle,fontWeight:c.fontWeight,letterSpacing:c.letterSpacing,textTransform:c.textTransform,whiteSpace:"nowrap"}),h.attr("class","select2-sizer"),a("body").append(h)}return h.text(b.val()),h.width()}function D(b,c,d){var e,g,f=[];e=a.trim(b.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each2(function(){0===this.indexOf("select2-")&&f.push(this)})),e=a.trim(c.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each2(function(){0!==this.indexOf("select2-")&&(g=d(this),g&&f.push(g))})),b.attr("class",f.join(" "))}function E(a,b,c,d){var e=o(a.toUpperCase()).indexOf(o(b.toUpperCase())),f=b.length;return 0>e?(c.push(d(a)),void 0):(c.push(d(a.substring(0,e))),c.push("<span class='select2-match'>"),c.push(d(a.substring(e,e+f))),c.push("</span>"),c.push(d(a.substring(e+f,a.length))),void 0)}function F(a){var b={"\\":"&#92;","&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#47;"};return String(a).replace(/[&<>"'\/\\]/g,function(a){return b[a]})}function G(c){var d,e=null,f=c.quietMillis||100,g=c.url,h=this;return function(i){window.clearTimeout(d),d=window.setTimeout(function(){var d=c.data,f=g,j=c.transport||a.fn.select2.ajaxDefaults.transport,k={type:c.type||"GET",cache:c.cache||!1,jsonpCallback:c.jsonpCallback||b,dataType:c.dataType||"json"},l=a.extend({},a.fn.select2.ajaxDefaults.params,k);d=d?d.call(h,i.term,i.page,i.context):null,f="function"==typeof f?f.call(h,i.term,i.page,i.context):f,e&&"function"==typeof e.abort&&e.abort(),c.params&&(a.isFunction(c.params)?a.extend(l,c.params.call(h)):a.extend(l,c.params)),a.extend(l,{url:f,dataType:c.dataType,data:d,success:function(a){var b=c.results(a,i.page,i);i.callback(b)},error:function(a,b,c){var d={hasError:!0,jqXHR:a,textStatus:b,errorThrown:c};i.callback(d)}}),e=j.call(h,l)},f)}}function H(b){var d,e,c=b,f=function(a){return""+a.text};a.isArray(c)&&(e=c,c={results:e}),a.isFunction(c)===!1&&(e=c,c=function(){return e});var g=c();return g.text&&(f=g.text,a.isFunction(f)||(d=g.text,f=function(a){return a[d]})),function(b){var g,d=b.term,e={results:[]};return""===d?(b.callback(c()),void 0):(g=function(c,e){var h,i;if(c=c[0],c.children){h={};for(i in c)c.hasOwnProperty(i)&&(h[i]=c[i]);h.children=[],a(c.children).each2(function(a,b){g(b,h.children)}),(h.children.length||b.matcher(d,f(h),c))&&e.push(h)}else b.matcher(d,f(c),c)&&e.push(c)},a(c().results).each2(function(a,b){g(b,e.results)}),b.callback(e),void 0)}}function I(c){var d=a.isFunction(c);return function(e){var f=e.term,g={results:[]},h=d?c(e):c;a.isArray(h)&&(a(h).each(function(){var a=this.text!==b,c=a?this.text:this;(""===f||e.matcher(f,c))&&g.results.push(a?this:{id:this,text:this})}),e.callback(g))}}function J(b,c){if(a.isFunction(b))return!0;if(!b)return!1;if("string"==typeof b)return!0;throw new Error(c+" must be a string, function, or falsy value")}function K(b,c){if(a.isFunction(b)){var d=Array.prototype.slice.call(arguments,2);return b.apply(c,d)}return b}function L(b){var c=0;return a.each(b,function(a,b){b.children?c+=L(b.children):c++}),c}function M(a,c,d,e){var h,i,j,k,l,f=a,g=!1;if(!e.createSearchChoice||!e.tokenSeparators||e.tokenSeparators.length<1)return b;for(;;){for(i=-1,j=0,k=e.tokenSeparators.length;k>j&&(l=e.tokenSeparators[j],i=a.indexOf(l),!(i>=0));j++);if(0>i)break;if(h=a.substring(0,i),a=a.substring(i+l.length),h.length>0&&(h=e.createSearchChoice.call(this,h,c),h!==b&&null!==h&&e.id(h)!==b&&null!==e.id(h))){for(g=!1,j=0,k=c.length;k>j;j++)if(r(e.id(h),e.id(c[j]))){g=!0;break}g||d(h)}}return f!==a?a:void 0}function N(){var b=this;a.each(arguments,function(a,c){b[c].remove(),b[c]=null})}function O(b,c){var d=function(){};return d.prototype=new b,d.prototype.constructor=d,d.prototype.parent=b.prototype,d.prototype=a.extend(d.prototype,c),d}if(window.Select2===b){var c,d,e,f,g,h,j,k,i={x:0,y:0},c={TAB:9,ENTER:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,SHIFT:16,CTRL:17,ALT:18,PAGE_UP:33,PAGE_DOWN:34,HOME:36,END:35,BACKSPACE:8,DELETE:46,isArrow:function(a){switch(a=a.which?a.which:a){case c.LEFT:case c.RIGHT:case c.UP:case c.DOWN:return!0}return!1},isControl:function(a){var b=a.which;switch(b){case c.SHIFT:case c.CTRL:case c.ALT:return!0}return a.metaKey?!0:!1},isFunctionKey:function(a){return a=a.which?a.which:a,a>=112&&123>=a}},l="<div class='select2-measure-scrollbar'></div>",m={"\u24b6":"A","\uff21":"A","\xc0":"A","\xc1":"A","\xc2":"A","\u1ea6":"A","\u1ea4":"A","\u1eaa":"A","\u1ea8":"A","\xc3":"A","\u0100":"A","\u0102":"A","\u1eb0":"A","\u1eae":"A","\u1eb4":"A","\u1eb2":"A","\u0226":"A","\u01e0":"A","\xc4":"A","\u01de":"A","\u1ea2":"A","\xc5":"A","\u01fa":"A","\u01cd":"A","\u0200":"A","\u0202":"A","\u1ea0":"A","\u1eac":"A","\u1eb6":"A","\u1e00":"A","\u0104":"A","\u023a":"A","\u2c6f":"A","\ua732":"AA","\xc6":"AE","\u01fc":"AE","\u01e2":"AE","\ua734":"AO","\ua736":"AU","\ua738":"AV","\ua73a":"AV","\ua73c":"AY","\u24b7":"B","\uff22":"B","\u1e02":"B","\u1e04":"B","\u1e06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24b8":"C","\uff23":"C","\u0106":"C","\u0108":"C","\u010a":"C","\u010c":"C","\xc7":"C","\u1e08":"C","\u0187":"C","\u023b":"C","\ua73e":"C","\u24b9":"D","\uff24":"D","\u1e0a":"D","\u010e":"D","\u1e0c":"D","\u1e10":"D","\u1e12":"D","\u1e0e":"D","\u0110":"D","\u018b":"D","\u018a":"D","\u0189":"D","\ua779":"D","\u01f1":"DZ","\u01c4":"DZ","\u01f2":"Dz","\u01c5":"Dz","\u24ba":"E","\uff25":"E","\xc8":"E","\xc9":"E","\xca":"E","\u1ec0":"E","\u1ebe":"E","\u1ec4":"E","\u1ec2":"E","\u1ebc":"E","\u0112":"E","\u1e14":"E","\u1e16":"E","\u0114":"E","\u0116":"E","\xcb":"E","\u1eba":"E","\u011a":"E","\u0204":"E","\u0206":"E","\u1eb8":"E","\u1ec6":"E","\u0228":"E","\u1e1c":"E","\u0118":"E","\u1e18":"E","\u1e1a":"E","\u0190":"E","\u018e":"E","\u24bb":"F","\uff26":"F","\u1e1e":"F","\u0191":"F","\ua77b":"F","\u24bc":"G","\uff27":"G","\u01f4":"G","\u011c":"G","\u1e20":"G","\u011e":"G","\u0120":"G","\u01e6":"G","\u0122":"G","\u01e4":"G","\u0193":"G","\ua7a0":"G","\ua77d":"G","\ua77e":"G","\u24bd":"H","\uff28":"H","\u0124":"H","\u1e22":"H","\u1e26":"H","\u021e":"H","\u1e24":"H","\u1e28":"H","\u1e2a":"H","\u0126":"H","\u2c67":"H","\u2c75":"H","\ua78d":"H","\u24be":"I","\uff29":"I","\xcc":"I","\xcd":"I","\xce":"I","\u0128":"I","\u012a":"I","\u012c":"I","\u0130":"I","\xcf":"I","\u1e2e":"I","\u1ec8":"I","\u01cf":"I","\u0208":"I","\u020a":"I","\u1eca":"I","\u012e":"I","\u1e2c":"I","\u0197":"I","\u24bf":"J","\uff2a":"J","\u0134":"J","\u0248":"J","\u24c0":"K","\uff2b":"K","\u1e30":"K","\u01e8":"K","\u1e32":"K","\u0136":"K","\u1e34":"K","\u0198":"K","\u2c69":"K","\ua740":"K","\ua742":"K","\ua744":"K","\ua7a2":"K","\u24c1":"L","\uff2c":"L","\u013f":"L","\u0139":"L","\u013d":"L","\u1e36":"L","\u1e38":"L","\u013b":"L","\u1e3c":"L","\u1e3a":"L","\u0141":"L","\u023d":"L","\u2c62":"L","\u2c60":"L","\ua748":"L","\ua746":"L","\ua780":"L","\u01c7":"LJ","\u01c8":"Lj","\u24c2":"M","\uff2d":"M","\u1e3e":"M","\u1e40":"M","\u1e42":"M","\u2c6e":"M","\u019c":"M","\u24c3":"N","\uff2e":"N","\u01f8":"N","\u0143":"N","\xd1":"N","\u1e44":"N","\u0147":"N","\u1e46":"N","\u0145":"N","\u1e4a":"N","\u1e48":"N","\u0220":"N","\u019d":"N","\ua790":"N","\ua7a4":"N","\u01ca":"NJ","\u01cb":"Nj","\u24c4":"O","\uff2f":"O","\xd2":"O","\xd3":"O","\xd4":"O","\u1ed2":"O","\u1ed0":"O","\u1ed6":"O","\u1ed4":"O","\xd5":"O","\u1e4c":"O","\u022c":"O","\u1e4e":"O","\u014c":"O","\u1e50":"O","\u1e52":"O","\u014e":"O","\u022e":"O","\u0230":"O","\xd6":"O","\u022a":"O","\u1ece":"O","\u0150":"O","\u01d1":"O","\u020c":"O","\u020e":"O","\u01a0":"O","\u1edc":"O","\u1eda":"O","\u1ee0":"O","\u1ede":"O","\u1ee2":"O","\u1ecc":"O","\u1ed8":"O","\u01ea":"O","\u01ec":"O","\xd8":"O","\u01fe":"O","\u0186":"O","\u019f":"O","\ua74a":"O","\ua74c":"O","\u01a2":"OI","\ua74e":"OO","\u0222":"OU","\u24c5":"P","\uff30":"P","\u1e54":"P","\u1e56":"P","\u01a4":"P","\u2c63":"P","\ua750":"P","\ua752":"P","\ua754":"P","\u24c6":"Q","\uff31":"Q","\ua756":"Q","\ua758":"Q","\u024a":"Q","\u24c7":"R","\uff32":"R","\u0154":"R","\u1e58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1e5a":"R","\u1e5c":"R","\u0156":"R","\u1e5e":"R","\u024c":"R","\u2c64":"R","\ua75a":"R","\ua7a6":"R","\ua782":"R","\u24c8":"S","\uff33":"S","\u1e9e":"S","\u015a":"S","\u1e64":"S","\u015c":"S","\u1e60":"S","\u0160":"S","\u1e66":"S","\u1e62":"S","\u1e68":"S","\u0218":"S","\u015e":"S","\u2c7e":"S","\ua7a8":"S","\ua784":"S","\u24c9":"T","\uff34":"T","\u1e6a":"T","\u0164":"T","\u1e6c":"T","\u021a":"T","\u0162":"T","\u1e70":"T","\u1e6e":"T","\u0166":"T","\u01ac":"T","\u01ae":"T","\u023e":"T","\ua786":"T","\ua728":"TZ","\u24ca":"U","\uff35":"U","\xd9":"U","\xda":"U","\xdb":"U","\u0168":"U","\u1e78":"U","\u016a":"U","\u1e7a":"U","\u016c":"U","\xdc":"U","\u01db":"U","\u01d7":"U","\u01d5":"U","\u01d9":"U","\u1ee6":"U","\u016e":"U","\u0170":"U","\u01d3":"U","\u0214":"U","\u0216":"U","\u01af":"U","\u1eea":"U","\u1ee8":"U","\u1eee":"U","\u1eec":"U","\u1ef0":"U","\u1ee4":"U","\u1e72":"U","\u0172":"U","\u1e76":"U","\u1e74":"U","\u0244":"U","\u24cb":"V","\uff36":"V","\u1e7c":"V","\u1e7e":"V","\u01b2":"V","\ua75e":"V","\u0245":"V","\ua760":"VY","\u24cc":"W","\uff37":"W","\u1e80":"W","\u1e82":"W","\u0174":"W","\u1e86":"W","\u1e84":"W","\u1e88":"W","\u2c72":"W","\u24cd":"X","\uff38":"X","\u1e8a":"X","\u1e8c":"X","\u24ce":"Y","\uff39":"Y","\u1ef2":"Y","\xdd":"Y","\u0176":"Y","\u1ef8":"Y","\u0232":"Y","\u1e8e":"Y","\u0178":"Y","\u1ef6":"Y","\u1ef4":"Y","\u01b3":"Y","\u024e":"Y","\u1efe":"Y","\u24cf":"Z","\uff3a":"Z","\u0179":"Z","\u1e90":"Z","\u017b":"Z","\u017d":"Z","\u1e92":"Z","\u1e94":"Z","\u01b5":"Z","\u0224":"Z","\u2c7f":"Z","\u2c6b":"Z","\ua762":"Z","\u24d0":"a","\uff41":"a","\u1e9a":"a","\xe0":"a","\xe1":"a","\xe2":"a","\u1ea7":"a","\u1ea5":"a","\u1eab":"a","\u1ea9":"a","\xe3":"a","\u0101":"a","\u0103":"a","\u1eb1":"a","\u1eaf":"a","\u1eb5":"a","\u1eb3":"a","\u0227":"a","\u01e1":"a","\xe4":"a","\u01df":"a","\u1ea3":"a","\xe5":"a","\u01fb":"a","\u01ce":"a","\u0201":"a","\u0203":"a","\u1ea1":"a","\u1ead":"a","\u1eb7":"a","\u1e01":"a","\u0105":"a","\u2c65":"a","\u0250":"a","\ua733":"aa","\xe6":"ae","\u01fd":"ae","\u01e3":"ae","\ua735":"ao","\ua737":"au","\ua739":"av","\ua73b":"av","\ua73d":"ay","\u24d1":"b","\uff42":"b","\u1e03":"b","\u1e05":"b","\u1e07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24d2":"c","\uff43":"c","\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\xe7":"c","\u1e09":"c","\u0188":"c","\u023c":"c","\ua73f":"c","\u2184":"c","\u24d3":"d","\uff44":"d","\u1e0b":"d","\u010f":"d","\u1e0d":"d","\u1e11":"d","\u1e13":"d","\u1e0f":"d","\u0111":"d","\u018c":"d","\u0256":"d","\u0257":"d","\ua77a":"d","\u01f3":"dz","\u01c6":"dz","\u24d4":"e","\uff45":"e","\xe8":"e","\xe9":"e","\xea":"e","\u1ec1":"e","\u1ebf":"e","\u1ec5":"e","\u1ec3":"e","\u1ebd":"e","\u0113":"e","\u1e15":"e","\u1e17":"e","\u0115":"e","\u0117":"e","\xeb":"e","\u1ebb":"e","\u011b":"e","\u0205":"e","\u0207":"e","\u1eb9":"e","\u1ec7":"e","\u0229":"e","\u1e1d":"e","\u0119":"e","\u1e19":"e","\u1e1b":"e","\u0247":"e","\u025b":"e","\u01dd":"e","\u24d5":"f","\uff46":"f","\u1e1f":"f","\u0192":"f","\ua77c":"f","\u24d6":"g","\uff47":"g","\u01f5":"g","\u011d":"g","\u1e21":"g","\u011f":"g","\u0121":"g","\u01e7":"g","\u0123":"g","\u01e5":"g","\u0260":"g","\ua7a1":"g","\u1d79":"g","\ua77f":"g","\u24d7":"h","\uff48":"h","\u0125":"h","\u1e23":"h","\u1e27":"h","\u021f":"h","\u1e25":"h","\u1e29":"h","\u1e2b":"h","\u1e96":"h","\u0127":"h","\u2c68":"h","\u2c76":"h","\u0265":"h","\u0195":"hv","\u24d8":"i","\uff49":"i","\xec":"i","\xed":"i","\xee":"i","\u0129":"i","\u012b":"i","\u012d":"i","\xef":"i","\u1e2f":"i","\u1ec9":"i","\u01d0":"i","\u0209":"i","\u020b":"i","\u1ecb":"i","\u012f":"i","\u1e2d":"i","\u0268":"i","\u0131":"i","\u24d9":"j","\uff4a":"j","\u0135":"j","\u01f0":"j","\u0249":"j","\u24da":"k","\uff4b":"k","\u1e31":"k","\u01e9":"k","\u1e33":"k","\u0137":"k","\u1e35":"k","\u0199":"k","\u2c6a":"k","\ua741":"k","\ua743":"k","\ua745":"k","\ua7a3":"k","\u24db":"l","\uff4c":"l","\u0140":"l","\u013a":"l","\u013e":"l","\u1e37":"l","\u1e39":"l","\u013c":"l","\u1e3d":"l","\u1e3b":"l","\u017f":"l","\u0142":"l","\u019a":"l","\u026b":"l","\u2c61":"l","\ua749":"l","\ua781":"l","\ua747":"l","\u01c9":"lj","\u24dc":"m","\uff4d":"m","\u1e3f":"m","\u1e41":"m","\u1e43":"m","\u0271":"m","\u026f":"m","\u24dd":"n","\uff4e":"n","\u01f9":"n","\u0144":"n","\xf1":"n","\u1e45":"n","\u0148":"n","\u1e47":"n","\u0146":"n","\u1e4b":"n","\u1e49":"n","\u019e":"n","\u0272":"n","\u0149":"n","\ua791":"n","\ua7a5":"n","\u01cc":"nj","\u24de":"o","\uff4f":"o","\xf2":"o","\xf3":"o","\xf4":"o","\u1ed3":"o","\u1ed1":"o","\u1ed7":"o","\u1ed5":"o","\xf5":"o","\u1e4d":"o","\u022d":"o","\u1e4f":"o","\u014d":"o","\u1e51":"o","\u1e53":"o","\u014f":"o","\u022f":"o","\u0231":"o","\xf6":"o","\u022b":"o","\u1ecf":"o","\u0151":"o","\u01d2":"o","\u020d":"o","\u020f":"o","\u01a1":"o","\u1edd":"o","\u1edb":"o","\u1ee1":"o","\u1edf":"o","\u1ee3":"o","\u1ecd":"o","\u1ed9":"o","\u01eb":"o","\u01ed":"o","\xf8":"o","\u01ff":"o","\u0254":"o","\ua74b":"o","\ua74d":"o","\u0275":"o","\u01a3":"oi","\u0223":"ou","\ua74f":"oo","\u24df":"p","\uff50":"p","\u1e55":"p","\u1e57":"p","\u01a5":"p","\u1d7d":"p","\ua751":"p","\ua753":"p","\ua755":"p","\u24e0":"q","\uff51":"q","\u024b":"q","\ua757":"q","\ua759":"q","\u24e1":"r","\uff52":"r","\u0155":"r","\u1e59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1e5b":"r","\u1e5d":"r","\u0157":"r","\u1e5f":"r","\u024d":"r","\u027d":"r","\ua75b":"r","\ua7a7":"r","\ua783":"r","\u24e2":"s","\uff53":"s","\xdf":"s","\u015b":"s","\u1e65":"s","\u015d":"s","\u1e61":"s","\u0161":"s","\u1e67":"s","\u1e63":"s","\u1e69":"s","\u0219":"s","\u015f":"s","\u023f":"s","\ua7a9":"s","\ua785":"s","\u1e9b":"s","\u24e3":"t","\uff54":"t","\u1e6b":"t","\u1e97":"t","\u0165":"t","\u1e6d":"t","\u021b":"t","\u0163":"t","\u1e71":"t","\u1e6f":"t","\u0167":"t","\u01ad":"t","\u0288":"t","\u2c66":"t","\ua787":"t","\ua729":"tz","\u24e4":"u","\uff55":"u","\xf9":"u","\xfa":"u","\xfb":"u","\u0169":"u","\u1e79":"u","\u016b":"u","\u1e7b":"u","\u016d":"u","\xfc":"u","\u01dc":"u","\u01d8":"u","\u01d6":"u","\u01da":"u","\u1ee7":"u","\u016f":"u","\u0171":"u","\u01d4":"u","\u0215":"u","\u0217":"u","\u01b0":"u","\u1eeb":"u","\u1ee9":"u","\u1eef":"u","\u1eed":"u","\u1ef1":"u","\u1ee5":"u","\u1e73":"u","\u0173":"u","\u1e77":"u","\u1e75":"u","\u0289":"u","\u24e5":"v","\uff56":"v","\u1e7d":"v","\u1e7f":"v","\u028b":"v","\ua75f":"v","\u028c":"v","\ua761":"vy","\u24e6":"w","\uff57":"w","\u1e81":"w","\u1e83":"w","\u0175":"w","\u1e87":"w","\u1e85":"w","\u1e98":"w","\u1e89":"w","\u2c73":"w","\u24e7":"x","\uff58":"x","\u1e8b":"x","\u1e8d":"x","\u24e8":"y","\uff59":"y","\u1ef3":"y","\xfd":"y","\u0177":"y","\u1ef9":"y","\u0233":"y","\u1e8f":"y","\xff":"y","\u1ef7":"y","\u1e99":"y","\u1ef5":"y","\u01b4":"y","\u024f":"y","\u1eff":"y","\u24e9":"z","\uff5a":"z","\u017a":"z","\u1e91":"z","\u017c":"z","\u017e":"z","\u1e93":"z","\u1e95":"z","\u01b6":"z","\u0225":"z","\u0240":"z","\u2c6c":"z","\ua763":"z","\u0386":"\u0391","\u0388":"\u0395","\u0389":"\u0397","\u038a":"\u0399","\u03aa":"\u0399","\u038c":"\u039f","\u038e":"\u03a5","\u03ab":"\u03a5","\u038f":"\u03a9","\u03ac":"\u03b1","\u03ad":"\u03b5","\u03ae":"\u03b7","\u03af":"\u03b9","\u03ca":"\u03b9","\u0390":"\u03b9","\u03cc":"\u03bf","\u03cd":"\u03c5","\u03cb":"\u03c5","\u03b0":"\u03c5","\u03c9":"\u03c9","\u03c2":"\u03c3"};j=a(document),g=function(){var a=1;return function(){return a++}}(),d=O(Object,{bind:function(a){var b=this;return function(){a.apply(b,arguments)}},init:function(c){var d,e,f=".select2-results";this.opts=c=this.prepareOpts(c),this.id=c.id,c.element.data("select2")!==b&&null!==c.element.data("select2")&&c.element.data("select2").destroy(),this.container=this.createContainer(),this.liveRegion=a("<span>",{role:"status","aria-live":"polite"}).addClass("select2-hidden-accessible").appendTo(document.body),this.containerId="s2id_"+(c.element.attr("id")||"autogen"+g()),this.containerEventName=this.containerId.replace(/([.])/g,"_").replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g,"\\$1"),this.container.attr("id",this.containerId),this.container.attr("title",c.element.attr("title")),this.body=a("body"),D(this.container,this.opts.element,this.opts.adaptContainerCssClass),this.container.attr("style",c.element.attr("style")),this.container.css(K(c.containerCss,this.opts.element)),this.container.addClass(K(c.containerCssClass,this.opts.element)),this.elementTabIndex=this.opts.element.attr("tabindex"),this.opts.element.data("select2",this).attr("tabindex","-1").before(this.container).on("click.select2",A),this.container.data("select2",this),this.dropdown=this.container.find(".select2-drop"),D(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass),this.dropdown.addClass(K(c.dropdownCssClass,this.opts.element)),this.dropdown.data("select2",this),this.dropdown.on("click",A),this.results=d=this.container.find(f),this.search=e=this.container.find("input.select2-input"),this.queryCount=0,this.resultsPage=0,this.context=null,this.initContainer(),this.container.on("click",A),v(this.results),this.dropdown.on("mousemove-filtered",f,this.bind(this.highlightUnderEvent)),this.dropdown.on("touchstart touchmove touchend",f,this.bind(function(a){this._touchEvent=!0,this.highlightUnderEvent(a)})),this.dropdown.on("touchmove",f,this.bind(this.touchMoved)),this.dropdown.on("touchstart touchend",f,this.bind(this.clearTouchMoved)),this.dropdown.on("click",this.bind(function(){this._touchEvent&&(this._touchEvent=!1,this.selectHighlighted())})),x(80,this.results),this.dropdown.on("scroll-debounced",f,this.bind(this.loadMoreIfNeeded)),a(this.container).on("change",".select2-input",function(a){a.stopPropagation()}),a(this.dropdown).on("change",".select2-input",function(a){a.stopPropagation()}),a.fn.mousewheel&&d.mousewheel(function(a,b,c,e){var f=d.scrollTop();e>0&&0>=f-e?(d.scrollTop(0),A(a)):0>e&&d.get(0).scrollHeight-d.scrollTop()+e<=d.height()&&(d.scrollTop(d.get(0).scrollHeight-d.height()),A(a))}),u(e),e.on("keyup-change input paste",this.bind(this.updateResults)),e.on("focus",function(){e.addClass("select2-focused")}),e.on("blur",function(){e.removeClass("select2-focused")}),this.dropdown.on("mouseup",f,this.bind(function(b){a(b.target).closest(".select2-result-selectable").length>0&&(this.highlightUnderEvent(b),this.selectHighlighted(b))})),this.dropdown.on("click mouseup mousedown touchstart touchend focusin",function(a){a.stopPropagation()}),this.nextSearchTerm=b,a.isFunction(this.opts.initSelection)&&(this.initSelection(),this.monitorSource()),null!==c.maximumInputLength&&this.search.attr("maxlength",c.maximumInputLength);var h=c.element.prop("disabled");h===b&&(h=!1),this.enable(!h);var i=c.element.prop("readonly");i===b&&(i=!1),this.readonly(i),k=k||q(),this.autofocus=c.element.prop("autofocus"),c.element.prop("autofocus",!1),this.autofocus&&this.focus(),this.search.attr("placeholder",c.searchInputPlaceholder)},destroy:function(){var a=this.opts.element,c=a.data("select2"),d=this;this.close(),a.length&&a[0].detachEvent&&a.each(function(){this.detachEvent("onpropertychange",d._sync)}),this.propertyObserver&&(this.propertyObserver.disconnect(),this.propertyObserver=null),this._sync=null,c!==b&&(c.container.remove(),c.liveRegion.remove(),c.dropdown.remove(),a.removeClass("select2-offscreen").removeData("select2").off(".select2").prop("autofocus",this.autofocus||!1),this.elementTabIndex?a.attr({tabindex:this.elementTabIndex}):a.removeAttr("tabindex"),a.show()),N.call(this,"container","liveRegion","dropdown","results","search")},optionToData:function(a){return a.is("option")?{id:a.prop("value"),text:a.text(),element:a.get(),css:a.attr("class"),disabled:a.prop("disabled"),locked:r(a.attr("locked"),"locked")||r(a.data("locked"),!0)}:a.is("optgroup")?{text:a.attr("label"),children:[],element:a.get(),css:a.attr("class")}:void 0},prepareOpts:function(c){var d,e,f,h,i=this;if(d=c.element,"select"===d.get(0).tagName.toLowerCase()&&(this.select=e=c.element),e&&a.each(["id","multiple","ajax","query","createSearchChoice","initSelection","data","tags"],function(){if(this in c)throw new Error("Option '"+this+"' is not allowed for Select2 when attached to a <select> element.")}),c=a.extend({},{populateResults:function(d,e,f){var h,j=this.opts.id,k=this.liveRegion;h=function(d,e,l){var m,n,o,p,q,r,s,t,u,v;d=c.sortResults(d,e,f);var w=[];for(m=0,n=d.length;n>m;m+=1)o=d[m],q=o.disabled===!0,p=!q&&j(o)!==b,r=o.children&&o.children.length>0,s=a("<li></li>"),s.addClass("select2-results-dept-"+l),s.addClass("select2-result"),s.addClass(p?"select2-result-selectable":"select2-result-unselectable"),q&&s.addClass("select2-disabled"),r&&s.addClass("select2-result-with-children"),s.addClass(i.opts.formatResultCssClass(o)),s.attr("role","presentation"),t=a(document.createElement("div")),t.addClass("select2-result-label"),t.attr("id","select2-result-label-"+g()),t.attr("role","option"),v=c.formatResult(o,t,f,i.opts.escapeMarkup),v!==b&&(t.html(v),s.append(t)),r&&(u=a("<ul></ul>"),u.addClass("select2-result-sub"),h(o.children,u,l+1),s.append(u)),s.data("select2-data",o),w.push(s[0]);e.append(w),k.text(c.formatMatches(d.length))},h(e,d,0)}},a.fn.select2.defaults,c),"function"!=typeof c.id&&(f=c.id,c.id=function(a){return a[f]}),a.isArray(c.element.data("select2Tags"))){if("tags"in c)throw"tags specified as both an attribute 'data-select2-tags' and in options of Select2 "+c.element.attr("id");c.tags=c.element.data("select2Tags")}if(e?(c.query=this.bind(function(a){var f,g,h,c={results:[],more:!1},e=a.term;h=function(b,c){var d;b.is("option")?a.matcher(e,b.text(),b)&&c.push(i.optionToData(b)):b.is("optgroup")&&(d=i.optionToData(b),b.children().each2(function(a,b){h(b,d.children)}),d.children.length>0&&c.push(d))},f=d.children(),this.getPlaceholder()!==b&&f.length>0&&(g=this.getPlaceholderOption(),g&&(f=f.not(g))),f.each2(function(a,b){h(b,c.results)}),a.callback(c)}),c.id=function(a){return a.id}):"query"in c||("ajax"in c?(h=c.element.data("ajax-url"),h&&h.length>0&&(c.ajax.url=h),c.query=G.call(c.element,c.ajax)):"data"in c?c.query=H(c.data):"tags"in c&&(c.query=I(c.tags),c.createSearchChoice===b&&(c.createSearchChoice=function(b){return{id:a.trim(b),text:a.trim(b)}}),c.initSelection===b&&(c.initSelection=function(b,d){var e=[];a(s(b.val(),c.separator)).each(function(){var b={id:this,text:this},d=c.tags;a.isFunction(d)&&(d=d()),a(d).each(function(){return r(this.id,b.id)?(b=this,!1):void 0}),e.push(b)}),d(e)}))),"function"!=typeof c.query)throw"query function not defined for Select2 "+c.element.attr("id");if("top"===c.createSearchChoicePosition)c.createSearchChoicePosition=function(a,b){a.unshift(b)};else if("bottom"===c.createSearchChoicePosition)c.createSearchChoicePosition=function(a,b){a.push(b)};else if("function"!=typeof c.createSearchChoicePosition)throw"invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function";return c},monitorSource:function(){var d,c=this.opts.element,e=this;c.on("change.select2",this.bind(function(){this.opts.element.data("select2-change-triggered")!==!0&&this.initSelection()})),this._sync=this.bind(function(){var a=c.prop("disabled");a===b&&(a=!1),this.enable(!a);var d=c.prop("readonly");d===b&&(d=!1),this.readonly(d),D(this.container,this.opts.element,this.opts.adaptContainerCssClass),this.container.addClass(K(this.opts.containerCssClass,this.opts.element)),D(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass),this.dropdown.addClass(K(this.opts.dropdownCssClass,this.opts.element))}),c.length&&c[0].attachEvent&&c.each(function(){this.attachEvent("onpropertychange",e._sync)}),d=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver,d!==b&&(this.propertyObserver&&(delete this.propertyObserver,this.propertyObserver=null),this.propertyObserver=new d(function(b){a.each(b,e._sync)}),this.propertyObserver.observe(c.get(0),{attributes:!0,subtree:!1}))},triggerSelect:function(b){var c=a.Event("select2-selecting",{val:this.id(b),object:b,choice:b});return this.opts.element.trigger(c),!c.isDefaultPrevented()},triggerChange:function(b){b=b||{},b=a.extend({},b,{type:"change",val:this.val()}),this.opts.element.data("select2-change-triggered",!0),this.opts.element.trigger(b),this.opts.element.data("select2-change-triggered",!1),this.opts.element.click(),this.opts.blurOnChange&&this.opts.element.blur()},isInterfaceEnabled:function(){return this.enabledInterface===!0},enableInterface:function(){var a=this._enabled&&!this._readonly,b=!a;return a===this.enabledInterface?!1:(this.container.toggleClass("select2-container-disabled",b),this.close(),this.enabledInterface=a,!0)},enable:function(a){a===b&&(a=!0),this._enabled!==a&&(this._enabled=a,this.opts.element.prop("disabled",!a),this.enableInterface())},disable:function(){this.enable(!1)},readonly:function(a){a===b&&(a=!1),this._readonly!==a&&(this._readonly=a,this.opts.element.prop("readonly",a),this.enableInterface())},opened:function(){return this.container?this.container.hasClass("select2-dropdown-open"):!1},positionDropdown:function(){var t,u,v,w,x,b=this.dropdown,c=this.container.offset(),d=this.container.outerHeight(!1),e=this.container.outerWidth(!1),f=b.outerHeight(!1),g=a(window),h=g.width(),i=g.height(),j=g.scrollLeft()+h,l=g.scrollTop()+i,m=c.top+d,n=c.left,o=l>=m+f,p=c.top-f>=g.scrollTop(),q=b.outerWidth(!1),r=j>=n+q,s=b.hasClass("select2-drop-above");s?(u=!0,!p&&o&&(v=!0,u=!1)):(u=!1,!o&&p&&(v=!0,u=!0)),v&&(b.hide(),c=this.container.offset(),d=this.container.outerHeight(!1),e=this.container.outerWidth(!1),f=b.outerHeight(!1),j=g.scrollLeft()+h,l=g.scrollTop()+i,m=c.top+d,n=c.left,q=b.outerWidth(!1),r=j>=n+q,b.show(),this.focusSearch()),this.opts.dropdownAutoWidth?(x=a(".select2-results",b)[0],b.addClass("select2-drop-auto-width"),b.css("width",""),q=b.outerWidth(!1)+(x.scrollHeight===x.clientHeight?0:k.width),q>e?e=q:q=e,f=b.outerHeight(!1),r=j>=n+q):this.container.removeClass("select2-drop-auto-width"),"static"!==this.body.css("position")&&(t=this.body.offset(),m-=t.top,n-=t.left),r||(n=c.left+this.container.outerWidth(!1)-q),w={left:n,width:e},u?(w.top=c.top-f,w.bottom="auto",this.container.addClass("select2-drop-above"),b.addClass("select2-drop-above")):(w.top=m,w.bottom="auto",this.container.removeClass("select2-drop-above"),b.removeClass("select2-drop-above")),w=a.extend(w,K(this.opts.dropdownCss,this.opts.element)),b.css(w)},shouldOpen:function(){var b;return this.opened()?!1:this._enabled===!1||this._readonly===!0?!1:(b=a.Event("select2-opening"),this.opts.element.trigger(b),!b.isDefaultPrevented())},clearDropdownAlignmentPreference:function(){this.container.removeClass("select2-drop-above"),this.dropdown.removeClass("select2-drop-above")},open:function(){return this.shouldOpen()?(this.opening(),j.on("mousemove.select2Event",function(a){i.x=a.pageX,i.y=a.pageY}),!0):!1},opening:function(){var f,b=this.containerEventName,c="scroll."+b,d="resize."+b,e="orientationchange."+b;this.container.addClass("select2-dropdown-open").addClass("select2-container-active"),this.clearDropdownAlignmentPreference(),this.dropdown[0]!==this.body.children().last()[0]&&this.dropdown.detach().appendTo(this.body),f=a("#select2-drop-mask"),0==f.length&&(f=a(document.createElement("div")),f.attr("id","select2-drop-mask").attr("class","select2-drop-mask"),f.hide(),f.appendTo(this.body),f.on("mousedown touchstart click",function(b){n(f);var d,c=a("#select2-drop");c.length>0&&(d=c.data("select2"),d.opts.selectOnBlur&&d.selectHighlighted({noFocus:!0}),d.close(),b.preventDefault(),b.stopPropagation())})),this.dropdown.prev()[0]!==f[0]&&this.dropdown.before(f),a("#select2-drop").removeAttr("id"),this.dropdown.attr("id","select2-drop"),f.show(),this.positionDropdown(),this.dropdown.show(),this.positionDropdown(),this.dropdown.addClass("select2-drop-active");var g=this;this.container.parents().add(window).each(function(){a(this).on(d+" "+c+" "+e,function(){g.opened()&&g.positionDropdown()})})},close:function(){if(this.opened()){var b=this.containerEventName,c="scroll."+b,d="resize."+b,e="orientationchange."+b;this.container.parents().add(window).each(function(){a(this).off(c).off(d).off(e)}),this.clearDropdownAlignmentPreference(),a("#select2-drop-mask").hide(),this.dropdown.removeAttr("id"),this.dropdown.hide(),this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active"),this.results.empty(),j.off("mousemove.select2Event"),this.clearSearch(),this.search.removeClass("select2-active"),this.opts.element.trigger(a.Event("select2-close"))}},externalSearch:function(a){this.open(),this.search.val(a),this.updateResults(!1)},clearSearch:function(){},getMaximumSelectionSize:function(){return K(this.opts.maximumSelectionSize,this.opts.element)},ensureHighlightVisible:function(){var c,d,e,f,g,h,i,j,b=this.results;if(d=this.highlight(),!(0>d)){if(0==d)return b.scrollTop(0),void 0;c=this.findHighlightableChoices().find(".select2-result-label"),e=a(c[d]),j=(e.offset()||{}).top||0,f=j+e.outerHeight(!0),d===c.length-1&&(i=b.find("li.select2-more-results"),i.length>0&&(f=i.offset().top+i.outerHeight(!0))),g=b.offset().top+b.outerHeight(!0),f>g&&b.scrollTop(b.scrollTop()+(f-g)),h=j-b.offset().top,0>h&&"none"!=e.css("display")&&b.scrollTop(b.scrollTop()+h)}},findHighlightableChoices:function(){return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)")},moveHighlight:function(b){for(var c=this.findHighlightableChoices(),d=this.highlight();d>-1&&d<c.length;){d+=b;var e=a(c[d]);if(e.hasClass("select2-result-selectable")&&!e.hasClass("select2-disabled")&&!e.hasClass("select2-selected")){this.highlight(d);
break}}},highlight:function(b){var d,e,c=this.findHighlightableChoices();return 0===arguments.length?p(c.filter(".select2-highlighted")[0],c.get()):(b>=c.length&&(b=c.length-1),0>b&&(b=0),this.removeHighlight(),d=a(c[b]),d.addClass("select2-highlighted"),this.search.attr("aria-activedescendant",d.find(".select2-result-label").attr("id")),this.ensureHighlightVisible(),this.liveRegion.text(d.text()),e=d.data("select2-data"),e&&this.opts.element.trigger({type:"select2-highlight",val:this.id(e),choice:e}),void 0)},removeHighlight:function(){this.results.find(".select2-highlighted").removeClass("select2-highlighted")},touchMoved:function(){this._touchMoved=!0},clearTouchMoved:function(){this._touchMoved=!1},countSelectableResults:function(){return this.findHighlightableChoices().length},highlightUnderEvent:function(b){var c=a(b.target).closest(".select2-result-selectable");if(c.length>0&&!c.is(".select2-highlighted")){var d=this.findHighlightableChoices();this.highlight(d.index(c))}else 0==c.length&&this.removeHighlight()},loadMoreIfNeeded:function(){var c,a=this.results,b=a.find("li.select2-more-results"),d=this.resultsPage+1,e=this,f=this.search.val(),g=this.context;0!==b.length&&(c=b.offset().top-a.offset().top-a.height(),c<=this.opts.loadMorePadding&&(b.addClass("select2-active"),this.opts.query({element:this.opts.element,term:f,page:d,context:g,matcher:this.opts.matcher,callback:this.bind(function(c){e.opened()&&(e.opts.populateResults.call(this,a,c.results,{term:f,page:d,context:g}),e.postprocessResults(c,!1,!1),c.more===!0?(b.detach().appendTo(a).text(K(e.opts.formatLoadMore,e.opts.element,d+1)),window.setTimeout(function(){e.loadMoreIfNeeded()},10)):b.remove(),e.positionDropdown(),e.resultsPage=d,e.context=c.context,this.opts.element.trigger({type:"select2-loaded",items:c}))})})))},tokenize:function(){},updateResults:function(c){function m(){d.removeClass("select2-active"),h.positionDropdown(),e.find(".select2-no-results,.select2-selection-limit,.select2-searching").length?h.liveRegion.text(e.text()):h.liveRegion.text(h.opts.formatMatches(e.find(".select2-result-selectable").length))}function n(a){e.html(a),m()}var g,i,l,d=this.search,e=this.results,f=this.opts,h=this,j=d.val(),k=a.data(this.container,"select2-last-term");if((c===!0||!k||!r(j,k))&&(a.data(this.container,"select2-last-term",j),c===!0||this.showSearchInput!==!1&&this.opened())){l=++this.queryCount;var o=this.getMaximumSelectionSize();if(o>=1&&(g=this.data(),a.isArray(g)&&g.length>=o&&J(f.formatSelectionTooBig,"formatSelectionTooBig")))return n("<li class='select2-selection-limit'>"+K(f.formatSelectionTooBig,f.element,o)+"</li>"),void 0;if(d.val().length<f.minimumInputLength)return J(f.formatInputTooShort,"formatInputTooShort")?n("<li class='select2-no-results'>"+K(f.formatInputTooShort,f.element,d.val(),f.minimumInputLength)+"</li>"):n(""),c&&this.showSearch&&this.showSearch(!0),void 0;if(f.maximumInputLength&&d.val().length>f.maximumInputLength)return J(f.formatInputTooLong,"formatInputTooLong")?n("<li class='select2-no-results'>"+K(f.formatInputTooLong,f.element,d.val(),f.maximumInputLength)+"</li>"):n(""),void 0;f.formatSearching&&0===this.findHighlightableChoices().length&&n("<li class='select2-searching'>"+K(f.formatSearching,f.element)+"</li>"),d.addClass("select2-active"),this.removeHighlight(),i=this.tokenize(),i!=b&&null!=i&&d.val(i),this.resultsPage=1,f.query({element:f.element,term:d.val(),page:this.resultsPage,context:null,matcher:f.matcher,callback:this.bind(function(g){var i;if(l==this.queryCount){if(!this.opened())return this.search.removeClass("select2-active"),void 0;if(g.hasError!==b&&J(f.formatAjaxError,"formatAjaxError"))return n("<li class='select2-ajax-error'>"+K(f.formatAjaxError,f.element,g.jqXHR,g.textStatus,g.errorThrown)+"</li>"),void 0;if(this.context=g.context===b?null:g.context,this.opts.createSearchChoice&&""!==d.val()&&(i=this.opts.createSearchChoice.call(h,d.val(),g.results),i!==b&&null!==i&&h.id(i)!==b&&null!==h.id(i)&&0===a(g.results).filter(function(){return r(h.id(this),h.id(i))}).length&&this.opts.createSearchChoicePosition(g.results,i)),0===g.results.length&&J(f.formatNoMatches,"formatNoMatches"))return n("<li class='select2-no-results'>"+K(f.formatNoMatches,f.element,d.val())+"</li>"),void 0;e.empty(),h.opts.populateResults.call(this,e,g.results,{term:d.val(),page:this.resultsPage,context:null}),g.more===!0&&J(f.formatLoadMore,"formatLoadMore")&&(e.append("<li class='select2-more-results'>"+f.escapeMarkup(K(f.formatLoadMore,f.element,this.resultsPage))+"</li>"),window.setTimeout(function(){h.loadMoreIfNeeded()},10)),this.postprocessResults(g,c),m(),this.opts.element.trigger({type:"select2-loaded",items:g})}})})}},cancel:function(){this.close()},blur:function(){this.opts.selectOnBlur&&this.selectHighlighted({noFocus:!0}),this.close(),this.container.removeClass("select2-container-active"),this.search[0]===document.activeElement&&this.search.blur(),this.clearSearch(),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus")},focusSearch:function(){y(this.search)},selectHighlighted:function(a){if(this._touchMoved)return this.clearTouchMoved(),void 0;var b=this.highlight(),c=this.results.find(".select2-highlighted"),d=c.closest(".select2-result").data("select2-data");d?(this.highlight(b),this.onSelect(d,a)):a&&a.noFocus&&this.close()},getPlaceholder:function(){var a;return this.opts.element.attr("placeholder")||this.opts.element.attr("data-placeholder")||this.opts.element.data("placeholder")||this.opts.placeholder||((a=this.getPlaceholderOption())!==b?a.text():b)},getPlaceholderOption:function(){if(this.select){var c=this.select.children("option").first();if(this.opts.placeholderOption!==b)return"first"===this.opts.placeholderOption&&c||"function"==typeof this.opts.placeholderOption&&this.opts.placeholderOption(this.select);if(""===a.trim(c.text())&&""===c.val())return c}},initContainerWidth:function(){function c(){var c,d,e,f,g,h;if("off"===this.opts.width)return null;if("element"===this.opts.width)return 0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px";if("copy"===this.opts.width||"resolve"===this.opts.width){if(c=this.opts.element.attr("style"),c!==b)for(d=c.split(";"),f=0,g=d.length;g>f;f+=1)if(h=d[f].replace(/\s/g,""),e=h.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i),null!==e&&e.length>=1)return e[1];return"resolve"===this.opts.width?(c=this.opts.element.css("width"),c.indexOf("%")>0?c:0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px"):null}return a.isFunction(this.opts.width)?this.opts.width():this.opts.width}var d=c.call(this);null!==d&&this.container.css("width",d)}}),e=O(d,{createContainer:function(){var b=a(document.createElement("div")).attr({"class":"select2-container"}).html(["<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>","   <span class='select2-chosen'>&#160;</span><abbr class='select2-search-choice-close'></abbr>","   <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>","</a>","<label for='' class='select2-offscreen'></label>","<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />","<div class='select2-drop select2-display-none'>","   <div class='select2-search'>","       <label for='' class='select2-offscreen'></label>","       <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'","       aria-autocomplete='list' />","   </div>","   <ul class='select2-results' role='listbox'>","   </ul>","</div>"].join(""));return b},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.focusser.prop("disabled",!this.isInterfaceEnabled())},opening:function(){var c,d,e;this.opts.minimumResultsForSearch>=0&&this.showSearch(!0),this.parent.opening.apply(this,arguments),this.showSearchInput!==!1&&this.search.val(this.focusser.val()),this.opts.shouldFocusInput(this)&&(this.search.focus(),c=this.search.get(0),c.createTextRange?(d=c.createTextRange(),d.collapse(!1),d.select()):c.setSelectionRange&&(e=this.search.val().length,c.setSelectionRange(e,e))),""===this.search.val()&&this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.search.select()),this.focusser.prop("disabled",!0).val(""),this.updateResults(!0),this.opts.element.trigger(a.Event("select2-open"))},close:function(){this.opened()&&(this.parent.close.apply(this,arguments),this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus())},focus:function(){this.opened()?this.close():(this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus())},isFocused:function(){return this.container.hasClass("select2-container-active")},cancel:function(){this.parent.cancel.apply(this,arguments),this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus()},destroy:function(){a("label[for='"+this.focusser.attr("id")+"']").attr("for",this.opts.element.attr("id")),this.parent.destroy.apply(this,arguments),N.call(this,"selection","focusser")},initContainer:function(){var b,h,d=this.container,e=this.dropdown,f=g();this.opts.minimumResultsForSearch<0?this.showSearch(!1):this.showSearch(!0),this.selection=b=d.find(".select2-choice"),this.focusser=d.find(".select2-focusser"),b.find(".select2-chosen").attr("id","select2-chosen-"+f),this.focusser.attr("aria-labelledby","select2-chosen-"+f),this.results.attr("id","select2-results-"+f),this.search.attr("aria-owns","select2-results-"+f),this.focusser.attr("id","s2id_autogen"+f),h=a("label[for='"+this.opts.element.attr("id")+"']"),this.focusser.prev().text(h.text()).attr("for",this.focusser.attr("id"));var i=this.opts.element.attr("title");this.opts.element.attr("title",i||h.text()),this.focusser.attr("tabindex",this.elementTabIndex),this.search.attr("id",this.focusser.attr("id")+"_search"),this.search.prev().text(a("label[for='"+this.focusser.attr("id")+"']").text()).attr("for",this.search.attr("id")),this.search.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()&&229!=a.keyCode){if(a.which===c.PAGE_UP||a.which===c.PAGE_DOWN)return A(a),void 0;switch(a.which){case c.UP:case c.DOWN:return this.moveHighlight(a.which===c.UP?-1:1),A(a),void 0;case c.ENTER:return this.selectHighlighted(),A(a),void 0;case c.TAB:return this.selectHighlighted({noFocus:!0}),void 0;case c.ESC:return this.cancel(a),A(a),void 0}}})),this.search.on("blur",this.bind(function(){document.activeElement===this.body.get(0)&&window.setTimeout(this.bind(function(){this.opened()&&this.search.focus()}),0)})),this.focusser.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()&&a.which!==c.TAB&&!c.isControl(a)&&!c.isFunctionKey(a)&&a.which!==c.ESC){if(this.opts.openOnEnter===!1&&a.which===c.ENTER)return A(a),void 0;if(a.which==c.DOWN||a.which==c.UP||a.which==c.ENTER&&this.opts.openOnEnter){if(a.altKey||a.ctrlKey||a.shiftKey||a.metaKey)return;return this.open(),A(a),void 0}return a.which==c.DELETE||a.which==c.BACKSPACE?(this.opts.allowClear&&this.clear(),A(a),void 0):void 0}})),u(this.focusser),this.focusser.on("keyup-change input",this.bind(function(a){if(this.opts.minimumResultsForSearch>=0){if(a.stopPropagation(),this.opened())return;this.open()}})),b.on("mousedown touchstart","abbr",this.bind(function(a){this.isInterfaceEnabled()&&(this.clear(),B(a),this.close(),this.selection.focus())})),b.on("mousedown touchstart",this.bind(function(c){n(b),this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.opened()?this.close():this.isInterfaceEnabled()&&this.open(),A(c)})),e.on("mousedown touchstart",this.bind(function(){this.opts.shouldFocusInput(this)&&this.search.focus()})),b.on("focus",this.bind(function(a){A(a)})),this.focusser.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active")})).on("blur",this.bind(function(){this.opened()||(this.container.removeClass("select2-container-active"),this.opts.element.trigger(a.Event("select2-blur")))})),this.search.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active")})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.setPlaceholder()},clear:function(b){var c=this.selection.data("select2-data");if(c){var d=a.Event("select2-clearing");if(this.opts.element.trigger(d),d.isDefaultPrevented())return;var e=this.getPlaceholderOption();this.opts.element.val(e?e.val():""),this.selection.find(".select2-chosen").empty(),this.selection.removeData("select2-data"),this.setPlaceholder(),b!==!1&&(this.opts.element.trigger({type:"select2-removed",val:this.id(c),choice:c}),this.triggerChange({removed:c}))}},initSelection:function(){if(this.isPlaceholderOptionSelected())this.updateSelection(null),this.close(),this.setPlaceholder();else{var c=this;this.opts.initSelection.call(null,this.opts.element,function(a){a!==b&&null!==a&&(c.updateSelection(a),c.close(),c.setPlaceholder(),c.nextSearchTerm=c.opts.nextSearchTerm(a,c.search.val()))})}},isPlaceholderOptionSelected:function(){var a;return this.getPlaceholder()===b?!1:(a=this.getPlaceholderOption())!==b&&a.prop("selected")||""===this.opts.element.val()||this.opts.element.val()===b||null===this.opts.element.val()},prepareOpts:function(){var b=this.parent.prepareOpts.apply(this,arguments),c=this;return"select"===b.element.get(0).tagName.toLowerCase()?b.initSelection=function(a,b){var d=a.find("option").filter(function(){return this.selected&&!this.disabled});b(c.optionToData(d))}:"data"in b&&(b.initSelection=b.initSelection||function(c,d){var e=c.val(),f=null;b.query({matcher:function(a,c,d){var g=r(e,b.id(d));return g&&(f=d),g},callback:a.isFunction(d)?function(){d(f)}:a.noop})}),b},getPlaceholder:function(){return this.select&&this.getPlaceholderOption()===b?b:this.parent.getPlaceholder.apply(this,arguments)},setPlaceholder:function(){var a=this.getPlaceholder();if(this.isPlaceholderOptionSelected()&&a!==b){if(this.select&&this.getPlaceholderOption()===b)return;this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(a)),this.selection.addClass("select2-default"),this.container.removeClass("select2-allowclear")}},postprocessResults:function(a,b,c){var d=0,e=this;if(this.findHighlightableChoices().each2(function(a,b){return r(e.id(b.data("select2-data")),e.opts.element.val())?(d=a,!1):void 0}),c!==!1&&(b===!0&&d>=0?this.highlight(d):this.highlight(0)),b===!0){var g=this.opts.minimumResultsForSearch;g>=0&&this.showSearch(L(a.results)>=g)}},showSearch:function(b){this.showSearchInput!==b&&(this.showSearchInput=b,this.dropdown.find(".select2-search").toggleClass("select2-search-hidden",!b),this.dropdown.find(".select2-search").toggleClass("select2-offscreen",!b),a(this.dropdown,this.container).toggleClass("select2-with-searchbox",b))},onSelect:function(a,b){if(this.triggerSelect(a)){var c=this.opts.element.val(),d=this.data();this.opts.element.val(this.id(a)),this.updateSelection(a),this.opts.element.trigger({type:"select2-selected",val:this.id(a),choice:a}),this.nextSearchTerm=this.opts.nextSearchTerm(a,this.search.val()),this.close(),b&&b.noFocus||!this.opts.shouldFocusInput(this)||this.focusser.focus(),r(c,this.id(a))||this.triggerChange({added:a,removed:d})}},updateSelection:function(a){var d,e,c=this.selection.find(".select2-chosen");this.selection.data("select2-data",a),c.empty(),null!==a&&(d=this.opts.formatSelection(a,c,this.opts.escapeMarkup)),d!==b&&c.append(d),e=this.opts.formatSelectionCssClass(a,c),e!==b&&c.addClass(e),this.selection.removeClass("select2-default"),this.opts.allowClear&&this.getPlaceholder()!==b&&this.container.addClass("select2-allowclear")},val:function(){var a,c=!1,d=null,e=this,f=this.data();if(0===arguments.length)return this.opts.element.val();if(a=arguments[0],arguments.length>1&&(c=arguments[1]),this.select)this.select.val(a).find("option").filter(function(){return this.selected}).each2(function(a,b){return d=e.optionToData(b),!1}),this.updateSelection(d),this.setPlaceholder(),c&&this.triggerChange({added:d,removed:f});else{if(!a&&0!==a)return this.clear(c),void 0;if(this.opts.initSelection===b)throw new Error("cannot call val() if initSelection() is not defined");this.opts.element.val(a),this.opts.initSelection(this.opts.element,function(a){e.opts.element.val(a?e.id(a):""),e.updateSelection(a),e.setPlaceholder(),c&&e.triggerChange({added:a,removed:f})})}},clearSearch:function(){this.search.val(""),this.focusser.val("")},data:function(a){var c,d=!1;return 0===arguments.length?(c=this.selection.data("select2-data"),c==b&&(c=null),c):(arguments.length>1&&(d=arguments[1]),a?(c=this.data(),this.opts.element.val(a?this.id(a):""),this.updateSelection(a),d&&this.triggerChange({added:a,removed:c})):this.clear(d),void 0)}}),f=O(d,{createContainer:function(){var b=a(document.createElement("div")).attr({"class":"select2-container select2-container-multi"}).html(["<ul class='select2-choices'>","  <li class='select2-search-field'>","    <label for='' class='select2-offscreen'></label>","    <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>","  </li>","</ul>","<div class='select2-drop select2-drop-multi select2-display-none'>","   <ul class='select2-results'>","   </ul>","</div>"].join(""));return b},prepareOpts:function(){var b=this.parent.prepareOpts.apply(this,arguments),c=this;return"select"===b.element.get(0).tagName.toLowerCase()?b.initSelection=function(a,b){var d=[];a.find("option").filter(function(){return this.selected&&!this.disabled}).each2(function(a,b){d.push(c.optionToData(b))}),b(d)}:"data"in b&&(b.initSelection=b.initSelection||function(c,d){var e=s(c.val(),b.separator),f=[];b.query({matcher:function(c,d,g){var h=a.grep(e,function(a){return r(a,b.id(g))}).length;return h&&f.push(g),h},callback:a.isFunction(d)?function(){for(var a=[],c=0;c<e.length;c++)for(var g=e[c],h=0;h<f.length;h++){var i=f[h];if(r(g,b.id(i))){a.push(i),f.splice(h,1);break}}d(a)}:a.noop})}),b},selectChoice:function(a){var b=this.container.find(".select2-search-choice-focus");b.length&&a&&a[0]==b[0]||(b.length&&this.opts.element.trigger("choice-deselected",b),b.removeClass("select2-search-choice-focus"),a&&a.length&&(this.close(),a.addClass("select2-search-choice-focus"),this.opts.element.trigger("choice-selected",a)))},destroy:function(){a("label[for='"+this.search.attr("id")+"']").attr("for",this.opts.element.attr("id")),this.parent.destroy.apply(this,arguments),N.call(this,"searchContainer","selection")},initContainer:function(){var d,b=".select2-choices";this.searchContainer=this.container.find(".select2-search-field"),this.selection=d=this.container.find(b);var e=this;this.selection.on("click",".select2-search-choice:not(.select2-locked)",function(){e.search[0].focus(),e.selectChoice(a(this))}),this.search.attr("id","s2id_autogen"+g()),this.search.prev().text(a("label[for='"+this.opts.element.attr("id")+"']").text()).attr("for",this.search.attr("id")),this.search.on("input paste",this.bind(function(){this.search.attr("placeholder")&&0==this.search.val().length||this.isInterfaceEnabled()&&(this.opened()||this.open())})),this.search.attr("tabindex",this.elementTabIndex),this.keydowns=0,this.search.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()){++this.keydowns;var b=d.find(".select2-search-choice-focus"),e=b.prev(".select2-search-choice:not(.select2-locked)"),f=b.next(".select2-search-choice:not(.select2-locked)"),g=z(this.search);if(b.length&&(a.which==c.LEFT||a.which==c.RIGHT||a.which==c.BACKSPACE||a.which==c.DELETE||a.which==c.ENTER)){var h=b;return a.which==c.LEFT&&e.length?h=e:a.which==c.RIGHT?h=f.length?f:null:a.which===c.BACKSPACE?this.unselect(b.first())&&(this.search.width(10),h=e.length?e:f):a.which==c.DELETE?this.unselect(b.first())&&(this.search.width(10),h=f.length?f:null):a.which==c.ENTER&&(h=null),this.selectChoice(h),A(a),h&&h.length||this.open(),void 0}if((a.which===c.BACKSPACE&&1==this.keydowns||a.which==c.LEFT)&&0==g.offset&&!g.length)return this.selectChoice(d.find(".select2-search-choice:not(.select2-locked)").last()),A(a),void 0;if(this.selectChoice(null),this.opened())switch(a.which){case c.UP:case c.DOWN:return this.moveHighlight(a.which===c.UP?-1:1),A(a),void 0;case c.ENTER:return this.selectHighlighted(),A(a),void 0;case c.TAB:return this.selectHighlighted({noFocus:!0}),this.close(),void 0;case c.ESC:return this.cancel(a),A(a),void 0}if(a.which!==c.TAB&&!c.isControl(a)&&!c.isFunctionKey(a)&&a.which!==c.BACKSPACE&&a.which!==c.ESC){if(a.which===c.ENTER){if(this.opts.openOnEnter===!1)return;if(a.altKey||a.ctrlKey||a.shiftKey||a.metaKey)return}this.open(),(a.which===c.PAGE_UP||a.which===c.PAGE_DOWN)&&A(a),a.which===c.ENTER&&A(a)}}})),this.search.on("keyup",this.bind(function(){this.keydowns=0,this.resizeSearch()})),this.search.on("blur",this.bind(function(b){this.container.removeClass("select2-container-active"),this.search.removeClass("select2-focused"),this.selectChoice(null),this.opened()||this.clearSearch(),b.stopImmediatePropagation(),this.opts.element.trigger(a.Event("select2-blur"))})),this.container.on("click",b,this.bind(function(b){this.isInterfaceEnabled()&&(a(b.target).closest(".select2-search-choice").length>0||(this.selectChoice(null),this.clearPlaceholder(),this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.open(),this.focusSearch(),b.preventDefault()))})),this.container.on("focus",b,this.bind(function(){this.isInterfaceEnabled()&&(this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"),this.clearPlaceholder())})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.clearSearch()},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.search.prop("disabled",!this.isInterfaceEnabled())},initSelection:function(){if(""===this.opts.element.val()&&""===this.opts.element.text()&&(this.updateSelection([]),this.close(),this.clearSearch()),this.select||""!==this.opts.element.val()){var c=this;this.opts.initSelection.call(null,this.opts.element,function(a){a!==b&&null!==a&&(c.updateSelection(a),c.close(),c.clearSearch())})}},clearSearch:function(){var a=this.getPlaceholder(),c=this.getMaxSearchWidth();a!==b&&0===this.getVal().length&&this.search.hasClass("select2-focused")===!1?(this.search.val(a).addClass("select2-default"),this.search.width(c>0?c:this.container.css("width"))):this.search.val("").width(10)},clearPlaceholder:function(){this.search.hasClass("select2-default")&&this.search.val("").removeClass("select2-default")},opening:function(){this.clearPlaceholder(),this.resizeSearch(),this.parent.opening.apply(this,arguments),this.focusSearch(),""===this.search.val()&&this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.search.select()),this.updateResults(!0),this.opts.shouldFocusInput(this)&&this.search.focus(),this.opts.element.trigger(a.Event("select2-open"))},close:function(){this.opened()&&this.parent.close.apply(this,arguments)},focus:function(){this.close(),this.search.focus()},isFocused:function(){return this.search.hasClass("select2-focused")},updateSelection:function(b){var c=[],d=[],e=this;a(b).each(function(){p(e.id(this),c)<0&&(c.push(e.id(this)),d.push(this))}),b=d,this.selection.find(".select2-search-choice").remove(),a(b).each(function(){e.addSelectedChoice(this)}),e.postprocessResults()},tokenize:function(){var a=this.search.val();a=this.opts.tokenizer.call(this,a,this.data(),this.bind(this.onSelect),this.opts),null!=a&&a!=b&&(this.search.val(a),a.length>0&&this.open())},onSelect:function(a,c){this.triggerSelect(a)&&""!==a.text&&(this.addSelectedChoice(a),this.opts.element.trigger({type:"selected",val:this.id(a),choice:a}),this.nextSearchTerm=this.opts.nextSearchTerm(a,this.search.val()),this.clearSearch(),this.updateResults(),(this.select||!this.opts.closeOnSelect)&&this.postprocessResults(a,!1,this.opts.closeOnSelect===!0),this.opts.closeOnSelect?(this.close(),this.search.width(10)):this.countSelectableResults()>0?(this.search.width(10),this.resizeSearch(),this.getMaximumSelectionSize()>0&&this.val().length>=this.getMaximumSelectionSize()?this.updateResults(!0):this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.updateResults(),this.search.select()),this.positionDropdown()):(this.close(),this.search.width(10)),this.triggerChange({added:a}),c&&c.noFocus||this.focusSearch())},cancel:function(){this.close(),this.focusSearch()},addSelectedChoice:function(c){var j,k,d=!c.locked,e=a("<li class='select2-search-choice'>    <div></div>    <a href='#' class='select2-search-choice-close' tabindex='-1'></a></li>"),f=a("<li class='select2-search-choice select2-locked'><div></div></li>"),g=d?e:f,h=this.id(c),i=this.getVal();j=this.opts.formatSelection(c,g.find("div"),this.opts.escapeMarkup),j!=b&&g.find("div").replaceWith("<div>"+j+"</div>"),k=this.opts.formatSelectionCssClass(c,g.find("div")),k!=b&&g.addClass(k),d&&g.find(".select2-search-choice-close").on("mousedown",A).on("click dblclick",this.bind(function(b){this.isInterfaceEnabled()&&(this.unselect(a(b.target)),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"),A(b),this.close(),this.focusSearch())})).on("focus",this.bind(function(){this.isInterfaceEnabled()&&(this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"))})),g.data("select2-data",c),g.insertBefore(this.searchContainer),i.push(h),this.setVal(i)},unselect:function(b){var d,e,c=this.getVal();if(b=b.closest(".select2-search-choice"),0===b.length)throw"Invalid argument: "+b+". Must be .select2-search-choice";if(d=b.data("select2-data")){var f=a.Event("select2-removing");if(f.val=this.id(d),f.choice=d,this.opts.element.trigger(f),f.isDefaultPrevented())return!1;for(;(e=p(this.id(d),c))>=0;)c.splice(e,1),this.setVal(c),this.select&&this.postprocessResults();return b.remove(),this.opts.element.trigger({type:"select2-removed",val:this.id(d),choice:d}),this.triggerChange({removed:d}),!0}},postprocessResults:function(a,b,c){var d=this.getVal(),e=this.results.find(".select2-result"),f=this.results.find(".select2-result-with-children"),g=this;e.each2(function(a,b){var c=g.id(b.data("select2-data"));p(c,d)>=0&&(b.addClass("select2-selected"),b.find(".select2-result-selectable").addClass("select2-selected"))}),f.each2(function(a,b){b.is(".select2-result-selectable")||0!==b.find(".select2-result-selectable:not(.select2-selected)").length||b.addClass("select2-selected")}),-1==this.highlight()&&c!==!1&&g.highlight(0),!this.opts.createSearchChoice&&!e.filter(".select2-result:not(.select2-selected)").length>0&&(!a||a&&!a.more&&0===this.results.find(".select2-no-results").length)&&J(g.opts.formatNoMatches,"formatNoMatches")&&this.results.append("<li class='select2-no-results'>"+K(g.opts.formatNoMatches,g.opts.element,g.search.val())+"</li>")},getMaxSearchWidth:function(){return this.selection.width()-t(this.search)},resizeSearch:function(){var a,b,c,d,e,f=t(this.search);a=C(this.search)+10,b=this.search.offset().left,c=this.selection.width(),d=this.selection.offset().left,e=c-(b-d)-f,a>e&&(e=c-f),40>e&&(e=c-f),0>=e&&(e=a),this.search.width(Math.floor(e))},getVal:function(){var a;return this.select?(a=this.select.val(),null===a?[]:a):(a=this.opts.element.val(),s(a,this.opts.separator))},setVal:function(b){var c;this.select?this.select.val(b):(c=[],a(b).each(function(){p(this,c)<0&&c.push(this)}),this.opts.element.val(0===c.length?"":c.join(this.opts.separator)))},buildChangeDetails:function(a,b){for(var b=b.slice(0),a=a.slice(0),c=0;c<b.length;c++)for(var d=0;d<a.length;d++)r(this.opts.id(b[c]),this.opts.id(a[d]))&&(b.splice(c,1),c>0&&c--,a.splice(d,1),d--);return{added:b,removed:a}},val:function(c,d){var e,f=this;if(0===arguments.length)return this.getVal();if(e=this.data(),e.length||(e=[]),!c&&0!==c)return this.opts.element.val(""),this.updateSelection([]),this.clearSearch(),d&&this.triggerChange({added:this.data(),removed:e}),void 0;if(this.setVal(c),this.select)this.opts.initSelection(this.select,this.bind(this.updateSelection)),d&&this.triggerChange(this.buildChangeDetails(e,this.data()));else{if(this.opts.initSelection===b)throw new Error("val() cannot be called if initSelection() is not defined");this.opts.initSelection(this.opts.element,function(b){var c=a.map(b,f.id);f.setVal(c),f.updateSelection(b),f.clearSearch(),d&&f.triggerChange(f.buildChangeDetails(e,f.data()))})}this.clearSearch()},onSortStart:function(){if(this.select)throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");this.search.width(0),this.searchContainer.hide()},onSortEnd:function(){var b=[],c=this;this.searchContainer.show(),this.searchContainer.appendTo(this.searchContainer.parent()),this.resizeSearch(),this.selection.find(".select2-search-choice").each(function(){b.push(c.opts.id(a(this).data("select2-data")))}),this.setVal(b),this.triggerChange()},data:function(b,c){var e,f,d=this;return 0===arguments.length?this.selection.children(".select2-search-choice").map(function(){return a(this).data("select2-data")}).get():(f=this.data(),b||(b=[]),e=a.map(b,function(a){return d.opts.id(a)}),this.setVal(e),this.updateSelection(b),this.clearSearch(),c&&this.triggerChange(this.buildChangeDetails(f,this.data())),void 0)}}),a.fn.select2=function(){var d,e,f,g,h,c=Array.prototype.slice.call(arguments,0),i=["val","destroy","opened","open","close","focus","isFocused","container","dropdown","onSortStart","onSortEnd","enable","disable","readonly","positionDropdown","data","search"],j=["opened","isFocused","container","dropdown"],k=["val","data"],l={search:"externalSearch"};return this.each(function(){if(0===c.length||"object"==typeof c[0])d=0===c.length?{}:a.extend({},c[0]),d.element=a(this),"select"===d.element.get(0).tagName.toLowerCase()?h=d.element.prop("multiple"):(h=d.multiple||!1,"tags"in d&&(d.multiple=h=!0)),e=h?new window.Select2["class"].multi:new window.Select2["class"].single,e.init(d);else{if("string"!=typeof c[0])throw"Invalid arguments to select2 plugin: "+c;if(p(c[0],i)<0)throw"Unknown method: "+c[0];if(g=b,e=a(this).data("select2"),e===b)return;if(f=c[0],"container"===f?g=e.container:"dropdown"===f?g=e.dropdown:(l[f]&&(f=l[f]),g=e[f].apply(e,c.slice(1))),p(c[0],j)>=0||p(c[0],k)>=0&&1==c.length)return!1}}),g===b?this:g},a.fn.select2.defaults={width:"copy",loadMorePadding:0,closeOnSelect:!0,openOnEnter:!0,containerCss:{},dropdownCss:{},containerCssClass:"",dropdownCssClass:"",formatResult:function(a,b,c,d){var e=[];return E(a.text,c.term,e,d),e.join("")},formatSelection:function(a,c,d){return a?d(a.text):b},sortResults:function(a){return a},formatResultCssClass:function(a){return a.css},formatSelectionCssClass:function(){return b},minimumResultsForSearch:0,minimumInputLength:0,maximumInputLength:null,maximumSelectionSize:0,id:function(a){return a==b?null:a.id},matcher:function(a,b){return o(""+b).toUpperCase().indexOf(o(""+a).toUpperCase())>=0},separator:",",tokenSeparators:[],tokenizer:M,escapeMarkup:F,blurOnChange:!1,selectOnBlur:!1,adaptContainerCssClass:function(a){return a},adaptDropdownCssClass:function(){return null},nextSearchTerm:function(){return b},searchInputPlaceholder:"",createSearchChoicePosition:"top",shouldFocusInput:function(a){var b="ontouchstart"in window||navigator.msMaxTouchPoints>0;return b?a.opts.minimumResultsForSearch<0?!1:!0:!0}},a.fn.select2.locales=[],a.fn.select2.locales.en={formatMatches:function(a){return 1===a?"One result is available, press enter to select it.":a+" results are available, use up and down arrow keys to navigate."
},formatNoMatches:function(){return"No matches found"},formatAjaxError:function(){return"Loading failed"},formatInputTooShort:function(a,b){var c=b-a.length;return"Please enter "+c+" or more character"+(1==c?"":"s")},formatInputTooLong:function(a,b){var c=a.length-b;return"Please delete "+c+" character"+(1==c?"":"s")},formatSelectionTooBig:function(a){return"You can only select "+a+" item"+(1==a?"":"s")},formatLoadMore:function(){return"Loading more results\u2026"},formatSearching:function(){return"Searching\u2026"}},a.extend(a.fn.select2.defaults,a.fn.select2.locales.en),a.fn.select2.ajaxDefaults={transport:a.ajax,params:{type:"GET",cache:!1,dataType:"json"}},window.Select2={query:{ajax:G,local:H,tags:I},util:{debounce:w,markMatch:E,escapeMarkup:F,stripDiacritics:o},"class":{"abstract":d,single:e,multi:f}}}}(jQuery);;
(function(G){var B,J,C,K,N,M,I,E,H,A,L;J=!!document.createElement("canvas").getContext;B=(function(){var P=document.createElement("div");P.innerHTML='<v:shape id="vml_flag1" adj="1" />';var O=P.firstChild;O.style.behavior="url(#default#VML)";return O?typeof O.adj=="object":true})();if(!(J||B)){G.fn.maphilight=function(){return this};return }if(J){E=function(O){return Math.max(0,Math.min(parseInt(O,16),255))};H=function(O,P){return"rgba("+E(O.substr(0,2))+","+E(O.substr(2,2))+","+E(O.substr(4,2))+","+P+")"};C=function(O){var P=G('<canvas style="width:'+O.width+"px;height:"+O.height+'px;"></canvas>').get(0);P.getContext("2d").clearRect(0,0,P.width,P.height);return P};var F=function(Q,O,R,P,S){P=P||0;S=S||0;Q.beginPath();if(O=="rect"){Q.rect(R[0]+P,R[1]+S,R[2]-R[0],R[3]-R[1])}else{if(O=="poly"){Q.moveTo(R[0]+P,R[1]+S);for(i=2;i<R.length;i+=2){Q.lineTo(R[i]+P,R[i+1]+S)}}else{if(O=="circ"){Q.arc(R[0]+P,R[1]+S,R[2],0,Math.PI*2,false)}}}Q.closePath()};K=function(Q,T,U,X,O){var S,P=Q.getContext("2d");if(X.shadow){P.save();if(X.shadowPosition=="inside"){F(P,T,U);P.clip()}var R=Q.width*100;var W=Q.height*100;F(P,T,U,R,W);P.shadowOffsetX=X.shadowX-R;P.shadowOffsetY=X.shadowY-W;P.shadowBlur=X.shadowRadius;P.shadowColor=H(X.shadowColor,X.shadowOpacity);var V=X.shadowFrom;if(!V){if(X.shadowPosition=="outside"){V="fill"}else{V="stroke"}}if(V=="stroke"){P.strokeStyle="rgba(0,0,0,1)";P.stroke()}else{if(V=="fill"){P.fillStyle="rgba(0,0,0,1)";P.fill()}}P.restore();if(X.shadowPosition=="outside"){P.save();F(P,T,U);P.globalCompositeOperation="destination-out";P.fillStyle="rgba(0,0,0,1);";P.fill();P.restore()}}P.save();F(P,T,U);if(X.fill){P.fillStyle=H(X.fillColor,X.fillOpacity);P.fill()}if(X.stroke){P.strokeStyle=H(X.strokeColor,X.strokeOpacity);P.lineWidth=X.strokeWidth;P.stroke()}P.restore();if(X.fade){G(Q).css("opacity",0).animate({opacity:1},100)}};N=function(O){O.getContext("2d").clearRect(0,0,O.width,O.height)}}else{C=function(O){return G('<var style="zoom:1;overflow:hidden;display:block;width:'+O.width+"px;height:"+O.height+'px;"></var>').get(0)};K=function(P,T,U,X,O){var V,W,R,S;for(var Q in U){U[Q]=parseInt(U[Q],10)}V='<v:fill color="#'+X.fillColor+'" opacity="'+(X.fill?X.fillOpacity:0)+'" />';W=(X.stroke?'strokeweight="'+X.strokeWidth+'" stroked="t" strokecolor="#'+X.strokeColor+'"':'stroked="f"');R='<v:stroke opacity="'+X.strokeOpacity+'"/>';if(T=="rect"){S=G('<v:rect name="'+O+'" filled="t" '+W+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+U[0]+"px;top:"+U[1]+"px;width:"+(U[2]-U[0])+"px;height:"+(U[3]-U[1])+'px;"></v:rect>')}else{if(T=="poly"){S=G('<v:shape name="'+O+'" filled="t" '+W+' coordorigin="0,0" coordsize="'+P.width+","+P.height+'" path="m '+U[0]+","+U[1]+" l "+U.join(",")+' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:'+P.width+"px;height:"+P.height+'px;"></v:shape>')}else{if(T=="circ"){S=G('<v:oval name="'+O+'" filled="t" '+W+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(U[0]-U[2])+"px;top:"+(U[1]-U[2])+"px;width:"+(U[2]*2)+"px;height:"+(U[2]*2)+'px;"></v:oval>')}}}S.get(0).innerHTML=V+R;G(P).append(S)};N=function(P){var O=G("<div>"+P.innerHTML+"</div>");O.children("[name=highlighted]").remove();P.innerHTML=O.html()}}M=function(P){var O,Q=P.getAttribute("coords").split(",");for(O=0;O<Q.length;O++){Q[O]=parseFloat(Q[O])}return[P.getAttribute("shape").toLowerCase().substr(0,4),Q]};L=function(Q,P){var O=G(Q);return G.extend({},P,G.metadata?O.metadata():false,O.data("maphilight"))};A=function(O){if(!O.complete){return false}if(typeof O.naturalWidth!="undefined"&&O.naturalWidth===0){return false}return true};I={position:"absolute",left:0,top:0,padding:0,border:0};var D=false;G.fn.maphilight=function(O){O=G.extend({},G.fn.maphilight.defaults,O);if(!J&&!D){G(window).ready(function(){document.namespaces.add("v","urn:schemas-microsoft-com:vml");var Q=document.createStyleSheet();var P=["shape","rect","oval","circ","fill","stroke","imagedata","group","textbox"];G.each(P,function(){Q.addRule("v\\:"+this,"behavior: url(#default#VML); antialias:true")})});D=true}return this.each(function(){var U,R,Y,Q,T,V,X,S,W;U=G(this);if(!A(this)){return window.setTimeout(function(){U.maphilight(O)},200)}Y=G.extend({},O,G.metadata?U.metadata():false,U.data("maphilight"));W=U.get(0).getAttribute("usemap");if(!W){return }Q=G('map[name="'+W.substr(1)+'"]');if(!(U.is('img,input[type="image"]')&&W&&Q.size()>0)){return }if(U.hasClass("maphilighted")){var P=U.parent();U.insertBefore(P);P.remove();G(Q).unbind(".maphilight").find("area[coords]").unbind(".maphilight")}R=G("<div></div>").css({display:"block",background:'url("'+this.src+'")',position:"relative",padding:0,width:this.width,height:this.height});if(Y.wrapClass){if(Y.wrapClass===true){R.addClass(G(this).attr("class"))}else{R.addClass(Y.wrapClass)}}U.before(R).css("opacity",0).css(I).remove();if(B){U.css("filter","Alpha(opacity=0)")}R.append(U);T=C(this);G(T).css(I);T.height=this.height;T.width=this.width;X=function(c){var a,b;b=L(this,Y);if(!b.neverOn&&!b.alwaysOn){a=M(this);K(T,a[0],a[1],b,"highlighted");if(b.groupBy){var Z;if(/^[a-zA-Z][\-a-zA-Z]+$/.test(b.groupBy)){Z=Q.find("area["+b.groupBy+'="'+G(this).attr(b.groupBy)+'"]')}else{Z=Q.find(b.groupBy)}var d=this;Z.each(function(){if(this!=d){var f=L(this,Y);if(!f.neverOn&&!f.alwaysOn){var e=M(this);K(T,e[0],e[1],f,"highlighted")}}})}if(!J){G(T).append("<v:rect></v:rect>")}}};G(Q).bind("alwaysOn.maphilight",function(){if(V){N(V)}if(!J){G(T).empty()}G(Q).find("area[coords]").each(function(){var Z,a;a=L(this,Y);if(a.alwaysOn){if(!V&&J){V=C(U[0]);G(V).css(I);V.width=U[0].width;V.height=U[0].height;U.before(V)}a.fade=a.alwaysOnFade;Z=M(this);if(J){K(V,Z[0],Z[1],a,"")}else{K(T,Z[0],Z[1],a,"")}}})});G(Q).trigger("alwaysOn.maphilight").find("area[coords]").bind("mouseover.maphilight",X).bind("mouseout.maphilight",function(Z){N(T)});U.before(T);U.addClass("maphilighted")})};G.fn.maphilight.defaults={fill:true,fillColor:"000000",fillOpacity:0.2,stroke:true,strokeColor:"ff0000",strokeOpacity:1,strokeWidth:1,fade:true,alwaysOn:false,neverOn:false,groupBy:false,wrapClass:true,shadow:false,shadowX:0,shadowY:0,shadowRadius:6,shadowColor:"000000",shadowOpacity:0.8,shadowPosition:"outside",shadowFrom:false}})(jQuery);;
/**
 * Bootstrap Multiselect v0.9.8 (https://github.com/davidstutz/bootstrap-multiselect)
 * 
 * Copyright 2012 - 2014 David Stutz
 * 
 * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0.
 */
!function ($) {

    "use strict";// jshint ;_;

    if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
        ko.bindingHandlers.multiselect = {

            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

                var listOfSelectedItems = allBindingsAccessor().selectedOptions;
                var config = ko.utils.unwrapObservable(valueAccessor());

                $(element).multiselect(config);

                if (isObservableArray(listOfSelectedItems)) {

                    // Set the initial selection state on the multiselect list.
                    $(element).multiselect('select', ko.utils.unwrapObservable(listOfSelectedItems));

                    // Subscribe to the selectedOptions: ko.observableArray
                    listOfSelectedItems.subscribe(function (changes) {
                        var addedArray = [], deletedArray = [];
                        forEach(changes, function (change) {
                            switch (change.status) {
                                case 'added':
                                    addedArray.push(change.value);
                                    break;
                                case 'deleted':
                                    deletedArray.push(change.value);
                                    break;
                            }
                        });

                        if (addedArray.length > 0) {
                            $(element).multiselect('select', addedArray);
                        }

                        if (deletedArray.length > 0) {
                            $(element).multiselect('deselect', deletedArray);
                        }
                    }, null, "arrayChange");
                }
            },

            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

                var listOfItems = allBindingsAccessor().options,
                    ms = $(element).data('multiselect'),
                    config = ko.utils.unwrapObservable(valueAccessor());

                if (isObservableArray(listOfItems)) {
                    // Subscribe to the options: ko.observableArray incase it changes later
                    listOfItems.subscribe(function (theArray) {
                        $(element).multiselect('rebuild');
                    });
                }

                if (!ms) {
                    $(element).multiselect(config);
                }
                else {
                    ms.updateOriginalOptions();
                }
            }
        };
    }

    function isObservableArray(obj) {
        return ko.isObservable(obj) && !(obj.destroyAll === undefined);
    }

    function forEach(array, callback) {
        for (var index = 0; index < array.length; ++index) {
            callback(array[index]);
        }
    }

    /**
     * Constructor to create a new multiselect using the given select.
     * 
     * @param {jQuery} select
     * @param {Object} options
     * @returns {Multiselect}
     */
    function Multiselect(select, options) {

        this.$select = $(select);
        this.options = this.mergeOptions($.extend({}, options, this.$select.data()));

        // Initialization.
        // We have to clone to create a new reference.
        this.originalOptions = this.$select.clone()[0].options;
        this.query = '';
        this.searchTimeout = null;

        this.options.multiple = this.$select.attr('multiple') === "multiple";
        this.options.onChange = $.proxy(this.options.onChange, this);
        this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
        this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
        this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this);
        this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this);

        // Build select all if enabled.
        this.buildContainer();
        this.buildButton();
        this.buildDropdown();
        this.buildSelectAll();
        this.buildDropdownOptions();
        this.buildFilter();

        this.updateButtonText();
        this.updateSelectAll();

        if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
            this.disable();
        }

        this.$select.hide().after(this.$container);
    };

    Multiselect.prototype = {

        defaults: {
            /**
             * Default text function will either print 'None selected' in case no
             * option is selected or a list of the selected options up to a length
             * of 3 selected options.
             * 
             * @param {jQuery} options
             * @param {jQuery} select
             * @returns {String}
             */
            buttonText: function (options, select) {
                if (options.length === 0) {
                    return this.nonSelectedText + ' <b class="caret"></b>';
                }
                else if (options.length == $('option', $(select)).length) {
                    return this.allSelectedText + ' <b class="caret"></b>';
                }
                else if (options.length > this.numberDisplayed) {
                    return options.length + ' ' + this.nSelectedText + ' <b class="caret"></b>';
                }
                else {
                    var selected = '';
                    options.each(function () {
                        var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html();

                        selected += label + ', ';
                    });

                    return selected.substr(0, selected.length - 2) + ' <b class="caret"></b>';
                }
            },
            /**
             * Updates the title of the button similar to the buttonText function.
             * 
             * @param {jQuery} options
             * @param {jQuery} select
             * @returns {@exp;selected@call;substr}
             */
            buttonTitle: function (options, select) {
                if (options.length === 0) {
                    return this.nonSelectedText;
                }
                else {
                    var selected = '';
                    options.each(function () {
                        selected += $(this).text() + ', ';
                    });
                    return selected.substr(0, selected.length - 2);
                }
            },
            /**
             * Create a label.
             * 
             * @param {jQuery} element
             * @returns {String}
             */
            label: function (element) {
                return $(element).attr('label') || $(element).html();
            },
            /**
             * Triggered on change of the multiselect.
             * 
             * Not triggered when selecting/deselecting options manually.
             * 
             * @param {jQuery} option
             * @param {Boolean} checked
             */
            onChange: function (option, checked) {

            },
            /**
             * Triggered when the dropdown is shown.
             * 
             * @param {jQuery} event
             */
            onDropdownShow: function (event) {

            },
            /**
             * Triggered when the dropdown is hidden.
             * 
             * @param {jQuery} event
             */
            onDropdownHide: function (event) {

            },
            /**
             * Triggered after the dropdown is shown.
             * 
             * @param {jQuery} event
             */
            onDropdownShown: function (event) {

            },
            /**
             * Triggered after the dropdown is hidden.
             * 
             * @param {jQuery} event
             */
            onDropdownHidden: function (event) {

            },
            buttonClass: 'btn btn-default',
            buttonWidth: 'auto',
            buttonContainer: '<div class="btn-group" />',
            dropRight: false,
            selectedClass: 'active',
            // Maximum height of the dropdown menu.
            // If maximum height is exceeded a scrollbar will be displayed.
            maxHeight: false,
            checkboxName: false,
            includeSelectAllOption: false,
            includeSelectAllIfMoreThan: 0,
            selectAllText: ' Select all',
            selectAllValue: 'multiselect-all',
            selectAllName: false,
            enableFiltering: false,
            enableCaseInsensitiveFiltering: false,
            enableClickableOptGroups: false,
            filterPlaceholder: 'Search',
            // possible options: 'text', 'value', 'both'
            filterBehavior: 'text',
            includeFilterClearBtn: true,
            preventInputChangeEvent: false,
            nonSelectedText: 'None selected',
            nSelectedText: 'selected',
            allSelectedText: 'All selected',
            numberDisplayed: 3,
            disableIfEmpty: false,
            templates: {
                button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
                ul: '<ul class="multiselect-container dropdown-menu"></ul>',
                filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
                filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default multiselect-clear-filter" type="button"><i class="glyphicon glyphicon-remove-circle"></i></button></span>',
                li: '<li><a href="javascript:void(0);"><label></label></a></li>',
                divider: '<li class="multiselect-item divider"></li>',
                liGroup: '<li class="multiselect-item multiselect-group"><label></label></li>'
            }
        },

        constructor: Multiselect,

        /**
         * Builds the container of the multiselect.
         */
        buildContainer: function () {
            this.$container = $(this.options.buttonContainer);
            this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
            this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
            this.$container.on('shown.bs.dropdown', this.options.onDropdownShown);
            this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden);
        },

        /**
         * Builds the button of the multiselect.
         */
        buildButton: function () {
            this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);

            // Adopt active state.
            if (this.$select.prop('disabled')) {
                this.disable();
            }
            else {
                this.enable();
            }

            // Manually add button width if set.
            if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
                this.$button.css({
                    'width': this.options.buttonWidth
                });
                this.$container.css({
                    'width': this.options.buttonWidth
                });
            }

            // Keep the tab index from the select.
            var tabindex = this.$select.attr('tabindex');
            if (tabindex) {
                this.$button.attr('tabindex', tabindex);
            }

            this.$container.prepend(this.$button);
        },

        /**
         * Builds the ul representing the dropdown menu.
         */
        buildDropdown: function () {

            // Build ul.
            this.$ul = $(this.options.templates.ul);

            if (this.options.dropRight) {
                this.$ul.addClass('pull-right');
            }

            // Set max height of dropdown menu to activate auto scrollbar.
            if (this.options.maxHeight) {
                // TODO: Add a class for this option to move the css declarations.
                this.$ul.css({
                    'max-height': this.options.maxHeight + 'px',
                    'overflow-y': 'auto',
                    'overflow-x': 'hidden'
                });
            }

            this.$container.append(this.$ul);
        },

        /**
         * Build the dropdown options and binds all nessecary events.
         * 
         * Uses createDivider and createOptionValue to create the necessary options.
         */
        buildDropdownOptions: function () {

            this.$select.children().each($.proxy(function (index, element) {

                var $element = $(element);
                // Support optgroups and options without a group simultaneously.
                var tag = $element.prop('tagName')
                    .toLowerCase();

                if ($element.prop('value') === this.options.selectAllValue) {
                    return;
                }

                if (tag === 'optgroup') {
                    this.createOptgroup(element);
                }
                else if (tag === 'option') {

                    if ($element.data('role') === 'divider') {
                        this.createDivider();
                    }
                    else {
                        this.createOptionValue(element);
                    }

                }

                // Other illegal tags will be ignored.
            }, this));

            // Bind the change event on the dropdown elements.
            $('li input', this.$ul).on('change', $.proxy(function (event) {
                var $target = $(event.target);

                var checked = $target.prop('checked') || false;
                var isSelectAllOption = $target.val() === this.options.selectAllValue;

                // Apply or unapply the configured selected class.
                if (this.options.selectedClass) {
                    if (checked) {
                        $target.closest('li')
                            .addClass(this.options.selectedClass);
                    }
                    else {
                        $target.closest('li')
                            .removeClass(this.options.selectedClass);
                    }
                }

                // Get the corresponding option.
                var value = $target.val();
                var $option = this.getOptionByValue(value);

                var $optionsNotThis = $('option', this.$select).not($option);
                var $checkboxesNotThis = $('input', this.$container).not($target);

                if (isSelectAllOption) {
                    if (checked) {
                        this.selectAll();
                    }
                    else {
                        this.deselectAll();
                    }
                }

                if (!isSelectAllOption) {
                    if (checked) {
                        $option.prop('selected', true);

                        if (this.options.multiple) {
                            // Simply select additional option.
                            $option.prop('selected', true);
                        }
                        else {
                            // Unselect all other options and corresponding checkboxes.
                            if (this.options.selectedClass) {
                                $($checkboxesNotThis).closest('li').removeClass(this.options.selectedClass);
                            }

                            $($checkboxesNotThis).prop('checked', false);
                            $optionsNotThis.prop('selected', false);

                            // It's a single selection, so close.
                            this.$button.click();
                        }

                        if (this.options.selectedClass === "active") {
                            $optionsNotThis.closest("a").css("outline", "");
                        }
                    }
                    else {
                        // Unselect option.
                        $option.prop('selected', false);
                    }
                }

                this.$select.change();

                this.updateButtonText();
                this.updateSelectAll();

                this.options.onChange($option, checked);

                if (this.options.preventInputChangeEvent) {
                    return false;
                }
            }, this));

            $('li a', this.$ul).on('touchstart click', function (event) {
                event.stopPropagation();

                var $target = $(event.target);

                if (document.getSelection().type === 'Range') {
                    var $input = $(this).find("input:first");

                    $input.prop("checked", !$input.prop("checked"))
                        .trigger("change");
                }

                if (event.shiftKey) {
                    var checked = $target.prop('checked') || false;

                    if (checked) {
                        var prev = $target.closest('li')
                            .siblings('li[class="active"]:first');

                        var currentIdx = $target.closest('li')
                            .index();
                        var prevIdx = prev.index();

                        if (currentIdx > prevIdx) {
                            $target.closest("li").prevUntil(prev).each(
                                function () {
                                    $(this).find("input:first").prop("checked", true)
                                        .trigger("change");
                                }
                            );
                        }
                        else {
                            $target.closest("li").nextUntil(prev).each(
                                function () {
                                    $(this).find("input:first").prop("checked", true)
                                        .trigger("change");
                                }
                            );
                        }
                    }
                }

                $target.blur();
            });

            // Keyboard support.
            this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function (event) {
                if ($('input[type="text"]', this.$container).is(':focus')) {
                    return;
                }

                if (event.keyCode === 9 && this.$container.hasClass('open')) {
                    this.$button.click();
                }
                else {
                    var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible");

                    if (!$items.length) {
                        return;
                    }

                    var index = $items.index($items.filter(':focus'));

                    // Navigation up.
                    if (event.keyCode === 38 && index > 0) {
                        index--;
                    }
                        // Navigate down.
                    else if (event.keyCode === 40 && index < $items.length - 1) {
                        index++;
                    }
                    else if (!~index) {
                        index = 0;
                    }

                    var $current = $items.eq(index);
                    $current.focus();

                    if (event.keyCode === 32 || event.keyCode === 13) {
                        var $checkbox = $current.find('input');

                        $checkbox.prop("checked", !$checkbox.prop("checked"));
                        $checkbox.change();
                    }

                    event.stopPropagation();
                    event.preventDefault();
                }
            }, this));

            if (this.options.enableClickableOptGroups && this.options.multiple) {
                $('li.multiselect-group', this.$ul).on('click', $.proxy(function (event) {
                    event.stopPropagation();

                    var group = $(event.target).parent();

                    // Search all option in optgroup
                    var $options = group.nextUntil('li.divider');

                    // check or uncheck items
                    var allChecked = true;
                    var optionInputs = $options.find('input');
                    optionInputs.each(function () {
                        allChecked = allChecked && $(this).prop('checked');
                    });

                    optionInputs.prop('checked', !allChecked).trigger('change');
                }, this));
            }
        },

        /**
         * Create an option using the given select option.
         * 
         * @param {jQuery} element
         */
        createOptionValue: function (element) {
            var $element = $(element);
            if ($element.is(':selected')) {
                $element.prop('selected', true);
            }

            // Support the label attribute on options.
            var label = this.options.label(element);
            var value = $element.val();
            var inputType = this.options.multiple ? "checkbox" : "radio";

            var $li = $(this.options.templates.li);
            var $label = $('label', $li);
            $label.addClass(inputType);

            var $checkbox = $('<input/>').attr('type', inputType);

            if (this.options.checkboxName) {
                $checkbox.attr('name', this.options.checkboxName);
            }
            $label.append($checkbox);

            var selected = $element.prop('selected') || false;
            $checkbox.val(value);

            if (value === this.options.selectAllValue) {
                $li.addClass("multiselect-item multiselect-all");
                $checkbox.parent().parent()
                    .addClass('multiselect-all');
            }

            $label.append(" " + label);
            $label.attr('title', $element.attr('title'));

            this.$ul.append($li);

            if ($element.is(':disabled')) {
                $checkbox.attr('disabled', 'disabled')
                    .prop('disabled', true)
                    .closest('a')
                    .attr("tabindex", "-1")
                    .closest('li')
                    .addClass('disabled');
            }

            $checkbox.prop('checked', selected);

            if (selected && this.options.selectedClass) {
                $checkbox.closest('li')
                    .addClass(this.options.selectedClass);
            }
        },

        /**
         * Creates a divider using the given select option.
         * 
         * @param {jQuery} element
         */
        createDivider: function (element) {
            var $divider = $(this.options.templates.divider);
            this.$ul.append($divider);
        },

        /**
         * Creates an optgroup.
         * 
         * @param {jQuery} group
         */
        createOptgroup: function (group) {
            var groupName = $(group).prop('label');

            // Add a header for the group.
            var $li = $(this.options.templates.liGroup);
            $('label', $li).text(groupName);

            if (this.options.enableClickableOptGroups) {
                $li.addClass('multiselect-group-clickable');
            }

            this.$ul.append($li);

            if ($(group).is(':disabled')) {
                $li.addClass('disabled');
            }

            // Add the options of the group.
            $('option', group).each($.proxy(function (index, element) {
                this.createOptionValue(element);
            }, this));
        },

        /**
         * Build the selct all.
         * 
         * Checks if a select all has already been created.
         */
        buildSelectAll: function () {
            if (typeof this.options.selectAllValue === 'number') {
                this.options.selectAllValue = this.options.selectAllValue.toString();
            }

            var alreadyHasSelectAll = this.hasSelectAll();

            if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
                    && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {

                // Check whether to add a divider after the select all.
                if (this.options.includeSelectAllDivider) {
                    this.$ul.prepend($(this.options.templates.divider));
                }

                var $li = $(this.options.templates.li);
                $('label', $li).addClass("checkbox");

                if (this.options.selectAllName) {
                    $('label', $li).append('<input type="checkbox" name="' + this.options.selectAllName + '" />');
                }
                else {
                    $('label', $li).append('<input type="checkbox" />');
                }

                var $checkbox = $('input', $li);
                $checkbox.val(this.options.selectAllValue);

                $li.addClass("multiselect-item multiselect-all");
                $checkbox.parent().parent()
                    .addClass('multiselect-all');

                $('label', $li).append(" " + this.options.selectAllText);

                this.$ul.prepend($li);

                $checkbox.prop('checked', false);
            }
        },

        /**
         * Builds the filter.
         */
        buildFilter: function () {

            // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
            if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
                var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);

                if (this.$select.find('option').length >= enableFilterLength) {

                    this.$filter = $(this.options.templates.filter);
                    $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);

                    // Adds optional filter clear button
                    if (this.options.includeFilterClearBtn) {
                        var clearBtn = $(this.options.templates.filterClearBtn);
                        clearBtn.on('click', $.proxy(function (event) {
                            clearTimeout(this.searchTimeout);
                            this.$filter.find('.multiselect-search').val('');
                            $('li', this.$ul).show().removeClass("filter-hidden");
                            this.updateSelectAll();
                        }, this));
                        this.$filter.find('.input-group').append(clearBtn);
                    }

                    this.$ul.prepend(this.$filter);

                    this.$filter.val(this.query).on('click', function (event) {
                        event.stopPropagation();
                    }).on('input keydown', $.proxy(function (event) {
                        // Cancel enter key default behaviour
                        if (event.which === 13) {
                            event.preventDefault();
                        }

                        // This is useful to catch "keydown" events after the browser has updated the control.
                        clearTimeout(this.searchTimeout);

                        this.searchTimeout = this.asyncFunction($.proxy(function () {

                            if (this.query !== event.target.value) {
                                this.query = event.target.value;

                                var currentGroup, currentGroupVisible;
                                $.each($('li', this.$ul), $.proxy(function (index, element) {
                                    var value = $('input', element).val();
                                    var text = $('label', element).text();

                                    var filterCandidate = '';
                                    if ((this.options.filterBehavior === 'text')) {
                                        filterCandidate = text;
                                    }
                                    else if ((this.options.filterBehavior === 'value')) {
                                        filterCandidate = value;
                                    }
                                    else if (this.options.filterBehavior === 'both') {
                                        filterCandidate = text + '\n' + value;
                                    }

                                    if (value !== this.options.selectAllValue && text) {
                                        // By default lets assume that element is not
                                        // interesting for this search.
                                        var showElement = false;

                                        if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) {
                                            showElement = true;
                                        }
                                        else if (filterCandidate.indexOf(this.query) > -1) {
                                            showElement = true;
                                        }

                                        // Toggle current element (group or group item) according to showElement boolean.
                                        $(element).toggle(showElement).toggleClass('filter-hidden', !showElement);

                                        // Differentiate groups and group items.
                                        if ($(element).hasClass('multiselect-group')) {
                                            // Remember group status.
                                            currentGroup = element;
                                            currentGroupVisible = showElement;
                                        }
                                        else {
                                            // Show group name when at least one of its items is visible.
                                            if (showElement) {
                                                $(currentGroup).show().removeClass('filter-hidden');
                                            }

                                            // Show all group items when group name satisfies filter.
                                            if (!showElement && currentGroupVisible) {
                                                $(element).show().removeClass('filter-hidden');
                                            }
                                        }
                                    }
                                }, this));
                            }

                            this.updateSelectAll();
                        }, this), 300, this);
                    }, this));
                }
            }
        },

        /**
         * Unbinds the whole plugin.
         */
        destroy: function () {
            this.$container.remove();
            this.$select.show();
            this.$select.data('multiselect', null);
        },

        /**
         * Refreshs the multiselect based on the selected options of the select.
         */
        refresh: function () {
            $('option', this.$select).each($.proxy(function (index, element) {
                var $input = $('li input', this.$ul).filter(function () {
                    return $(this).val() === $(element).val();
                });

                if ($(element).is(':selected')) {
                    $input.prop('checked', true);

                    if (this.options.selectedClass) {
                        $input.closest('li')
                            .addClass(this.options.selectedClass);
                    }
                }
                else {
                    $input.prop('checked', false);

                    if (this.options.selectedClass) {
                        $input.closest('li')
                            .removeClass(this.options.selectedClass);
                    }
                }

                if ($(element).is(":disabled")) {
                    $input.attr('disabled', 'disabled')
                        .prop('disabled', true)
                        .closest('li')
                        .addClass('disabled');
                }
                else {
                    $input.prop('disabled', false)
                        .closest('li')
                        .removeClass('disabled');
                }
            }, this));

            this.updateButtonText();
            this.updateSelectAll();
        },

        /**
         * Select all options of the given values.
         * 
         * If triggerOnChange is set to true, the on change event is triggered if
         * and only if one value is passed.
         * 
         * @param {Array} selectValues
         * @param {Boolean} triggerOnChange
         */
        select: function (selectValues, triggerOnChange) {
            if (!$.isArray(selectValues)) {
                selectValues = [selectValues];
            }

            for (var i = 0; i < selectValues.length; i++) {
                var value = selectValues[i];

                if (value === null || value === undefined) {
                    continue;
                }

                var $option = this.getOptionByValue(value);
                var $checkbox = this.getInputByValue(value);

                if ($option === undefined || $checkbox === undefined) {
                    continue;
                }

                if (!this.options.multiple) {
                    this.deselectAll(false);
                }

                if (this.options.selectedClass) {
                    $checkbox.closest('li')
                        .addClass(this.options.selectedClass);
                }

                $checkbox.prop('checked', true);
                $option.prop('selected', true);
            }

            this.updateButtonText();
            this.updateSelectAll();

            if (triggerOnChange && selectValues.length === 1) {
                this.options.onChange($option, true);
            }
        },

        /**
         * Clears all selected items.
         */
        clearSelection: function () {
            this.deselectAll(false);
            this.updateButtonText();
            this.updateSelectAll();
        },

        /**
         * Deselects all options of the given values.
         * 
         * If triggerOnChange is set to true, the on change event is triggered, if
         * and only if one value is passed.
         * 
         * @param {Array} deselectValues
         * @param {Boolean} triggerOnChange
         */
        deselect: function (deselectValues, triggerOnChange) {
            if (!$.isArray(deselectValues)) {
                deselectValues = [deselectValues];
            }

            for (var i = 0; i < deselectValues.length; i++) {
                var value = deselectValues[i];

                if (value === null || value === undefined) {
                    continue;
                }

                var $option = this.getOptionByValue(value);
                var $checkbox = this.getInputByValue(value);

                if ($option === undefined || $checkbox === undefined) {
                    continue;
                }

                if (this.options.selectedClass) {
                    $checkbox.closest('li')
                        .removeClass(this.options.selectedClass);
                }

                $checkbox.prop('checked', false);
                $option.prop('selected', false);
            }

            this.updateButtonText();
            this.updateSelectAll();

            if (triggerOnChange && deselectValues.length === 1) {
                this.options.onChange($option, false);
            }
        },

        /**
         * Selects all enabled & visible options.
         *
         * If justVisible is true or not specified, only visible options are selected.
         *
         * @param {Boolean} justVisible
         */
        selectAll: function (justVisible) {
            var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
            var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul);
            var visibleCheckboxes = allCheckboxes.filter(":visible");
            var allCheckboxesCount = allCheckboxes.length;
            var visibleCheckboxesCount = visibleCheckboxes.length;

            if (justVisible) {
                visibleCheckboxes.prop('checked', true);
                $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").addClass(this.options.selectedClass);
            }
            else {
                allCheckboxes.prop('checked', true);
                $("li:not(.divider):not(.disabled)", this.$ul).addClass(this.options.selectedClass);
            }

            if (allCheckboxesCount === visibleCheckboxesCount || justVisible === false) {
                $("option:enabled", this.$select).prop('selected', true);
            }
            else {
                var values = visibleCheckboxes.map(function () {
                    return $(this).val();
                }).get();

                $("option:enabled", this.$select).filter(function (index) {
                    return $.inArray($(this).val(), values) !== -1;
                }).prop('selected', true);
            }
        },

        /**
         * Deselects all options.
         * 
         * If justVisible is true or not specified, only visible options are deselected.
         * 
         * @param {Boolean} justVisible
         */
        deselectAll: function (justVisible) {
            var justVisible = typeof justVisible === 'undefined' ? true : justVisible;

            if (justVisible) {
                var visibleCheckboxes = $("li input[type='checkbox']:enabled", this.$ul).filter(":visible");
                visibleCheckboxes.prop('checked', false);

                var values = visibleCheckboxes.map(function () {
                    return $(this).val();
                }).get();

                $("option:enabled", this.$select).filter(function (index) {
                    return $.inArray($(this).val(), values) !== -1;
                }).prop('selected', false);

                if (this.options.selectedClass) {
                    $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass);
                }
            }
            else {
                $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false);
                $("option:enabled", this.$select).prop('selected', false);

                if (this.options.selectedClass) {
                    $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass);
                }
            }
        },

        /**
         * Rebuild the plugin.
         * 
         * Rebuilds the dropdown, the filter and the select all option.
         */
        rebuild: function () {
            this.$ul.html('');

            // Important to distinguish between radios and checkboxes.
            this.options.multiple = this.$select.attr('multiple') === "multiple";

            this.buildSelectAll();
            this.buildDropdownOptions();
            this.buildFilter();

            this.updateButtonText();
            this.updateSelectAll();

            if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
                this.disable();
            }

            if (this.options.dropRight) {
                this.$ul.addClass('pull-right');
            }
        },

        /**
         * The provided data will be used to build the dropdown.
         */
        dataprovider: function (dataprovider) {
            var optionDOM = "";
            var groupCounter = 0;
            var tags = $(''); // create empty jQuery array

            $.each(dataprovider, function (index, option) {
                var tag;
                if ($.isArray(option.children)) { // create optiongroup tag
                    groupCounter++;
                    tag = $('<optgroup/>').attr({
                        label: option.label || 'Group ' + groupCounter
                    });
                    forEach(option.children, function (subOption) { // add children option tags
                        tag.append($('<option/>').attr({
                            value: subOption.value,
                            label: subOption.label || subOption.value,
                            title: subOption.title,
                            selected: !!subOption.selected
                        }));
                    });

                    optionDOM += '</optgroup>';
                }
                else { // create option tag
                    tag = $('<option/>').attr({
                        value: option.value,
                        label: option.label || option.value,
                        title: option.title,
                        selected: !!option.selected
                    });
                }

                tags = tags.add(tag);
            });

            this.$select.empty().append(tags);
            this.rebuild();
        },

        /**
         * Enable the multiselect.
         */
        enable: function () {
            this.$select.prop('disabled', false);
            this.$button.prop('disabled', false)
                .removeClass('disabled');
        },

        /**
         * Disable the multiselect.
         */
        disable: function () {
            this.$select.prop('disabled', true);
            this.$button.prop('disabled', true)
                .addClass('disabled');
        },

        /**
         * Set the options.
         * 
         * @param {Array} options
         */
        setOptions: function (options) {
            this.options = this.mergeOptions(options);
        },

        /**
         * Merges the given options with the default options.
         * 
         * @param {Array} options
         * @returns {Array}
         */
        mergeOptions: function (options) {
            return $.extend(true, {}, this.defaults, options);
        },

        /**
         * Checks whether a select all checkbox is present.
         * 
         * @returns {Boolean}
         */
        hasSelectAll: function () {
            return $('li.' + this.options.selectAllValue, this.$ul).length > 0;
        },

        /**
         * Updates the select all checkbox based on the currently displayed and selected checkboxes.
         */
        updateSelectAll: function () {
            if (this.hasSelectAll()) {
                var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul);
                var allBoxesLength = allBoxes.length;
                var checkedBoxesLength = allBoxes.filter(":checked").length;
                var selectAllLi = $("li." + this.options.selectAllValue, this.$ul);
                var selectAllInput = selectAllLi.find("input");

                if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
                    selectAllInput.prop("checked", true);
                    selectAllLi.addClass(this.options.selectedClass);
                }
                else {
                    selectAllInput.prop("checked", false);
                    selectAllLi.removeClass(this.options.selectedClass);
                }
            }
        },

        /**
         * Update the button text and its title based on the currently selected options.
         */
        updateButtonText: function () {
            var options = this.getSelected();

            // First update the displayed button text.
            $('.multiselect', this.$container).html(this.options.buttonText(options, this.$select));

            // Now update the title attribute of the button.
            $('.multiselect', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
        },

        /**
         * Get all selected options.
         * 
         * @returns {jQUery}
         */
        getSelected: function () {
            return $('option', this.$select).filter(":selected");
        },

        /**
         * Gets a select option by its value.
         * 
         * @param {String} value
         * @returns {jQuery}
         */
        getOptionByValue: function (value) {

            var options = $('option', this.$select);
            var valueToCompare = value.toString();

            for (var i = 0; i < options.length; i = i + 1) {
                var option = options[i];
                if (option.value === valueToCompare) {
                    return $(option);
                }
            }
        },

        /**
         * Get the input (radio/checkbox) by its value.
         * 
         * @param {String} value
         * @returns {jQuery}
         */
        getInputByValue: function (value) {

            var checkboxes = $('li input', this.$ul);
            var valueToCompare = value.toString();

            for (var i = 0; i < checkboxes.length; i = i + 1) {
                var checkbox = checkboxes[i];
                if (checkbox.value === valueToCompare) {
                    return $(checkbox);
                }
            }
        },

        /**
         * Used for knockout integration.
         */
        updateOriginalOptions: function () {
            this.originalOptions = this.$select.clone()[0].options;
        },

        asyncFunction: function (callback, timeout, self) {
            var args = Array.prototype.slice.call(arguments, 3);
            return setTimeout(function () {
                callback.apply(self || window, args);
            }, timeout);
        }
    };

    $.fn.multiselect = function (option, parameter, extraOptions) {
        return this.each(function () {
            var data = $(this).data('multiselect');
            var options = typeof option === 'object' && option;

            // Initialize the multiselect.
            if (!data) {
                data = new Multiselect(this, options);
                $(this).data('multiselect', data);
            }

            // Call multiselect method.
            if (typeof option === 'string') {
                data[option](parameter, extraOptions);

                if (option === 'destroy') {
                    $(this).data('multiselect', false);
                }
            }
        });
    };

    $.fn.multiselect.Constructor = Multiselect;

    $(function () {
        $("select[data-role=multiselect]").multiselect();
    });

}(window.jQuery);;
/*jslint browser: true, confusion: true, sloppy: true, vars: true, nomen: false, plusplus: false, indent: 2 */
/*global window,google */

/**
 * @name MarkerClustererPlus for Google Maps V3
 * @version 2.0.1 [July 27, 2011]
 * @author Gary Little
 * @fileoverview
 * The library creates and manages per-zoom-level clusters for large amounts of markers.
 * <p>
 * This is an enhanced V3 implementation of the
 * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
 * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the
 * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/"
 * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little.
 * <p>
 * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It
 *  adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>printable</code>,
 *  <code>batchSizeIE</code>, and <code>calculator</code> properties as well as support for
 *  four more events. It also allows greater control over the styling of the text that appears
 *  on the cluster marker. The documentation has been significantly improved and the overall
 *  code has been simplified and polished. Very large numbers of markers can now be managed
 *  without causing Javascript timeout errors on Internet Explorer. Note that the name of the
 *  <code>clusterclick</code> event has been deprecated. The new name is <code>click</code>,
 *  so please change your application code now.
 */

/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * @name ClusterIconStyle
 * @class This class represents the object for values in the <code>styles</code> array passed
 *  to the {@link MarkerClusterer} constructor. The element in this array that is used to
 *  style the cluster icon is determined by calling the <code>calculator</code> function.
 *
 * @property {string} url The URL of the cluster icon image file. Required.
 * @property {number} height The height (in pixels) of the cluster icon. Required.
 * @property {number} width The width (in pixels) of the cluster icon. Required.
 * @property {Array} [anchor] The anchor position (in pixels) of the label text to be shown on
 *  the cluster icon, relative to the top left corner of the icon.
 *  The format is <code>[yoffset, xoffset]</code>. The <code>yoffset</code> must be positive
 *  and less than <code>height</code> and the <code>xoffset</code> must be positive and less
 *  than <code>width</code>. The default is to anchor the label text so that it is centered
 *  on the icon.
 * @property {string} [textColor="black"] The color of the label text shown on the
 *  cluster icon.
 * @property {number} [textSize=11] The size (in pixels) of the label text shown on the
 *  cluster icon.
 * @property {number} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
 *  property for the label text shown on the cluster icon.
 * @property {number} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
 *  property for the label text shown on the cluster icon.
 * @property {number} [fontStyle="normal"] The value of the CSS <code>font-style</code>
 *  property for the label text shown on the cluster icon.
 * @property {number} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
 *  property for the label text shown on the cluster icon.
 * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
 *  within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
 *  (the same format as for the CSS <code>background-position</code> property). You must set
 *  this property appropriately when the image defined by <code>url</code> represents a sprite
 *  containing multiple images.
 */
/**
 * @name ClusterIconInfo
 * @class This class is an object containing general information about a cluster icon. This is
 *  the object that a <code>calculator</code> function returns.
 *
 * @property {string} text The text of the label to be shown on the cluster icon.
 * @property {number} index The index plus 1 of the element in the <code>styles</code>
 *  array to be used to style the cluster icon.
 */
/**
 * A cluster icon.
 *
 * @constructor
 * @extends google.maps.OverlayView
 * @param {Cluster} cluster The cluster with which the icon is to be associated.
 * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
 *  to use for various cluster sizes.
 * @private
 */
function ClusterIcon(cluster, styles) {
  cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);

  this.cluster_ = cluster;
  this.styles_ = styles;
  this.center_ = null;
  this.div_ = null;
  this.sums_ = null;
  this.visible_ = false;

  this.setMap(cluster.getMap()); // Note: this causes onAdd to be called
}


/**
 * Adds the icon to the DOM.
 */
ClusterIcon.prototype.onAdd = function () {
  var cClusterIcon = this;

  this.div_ = document.createElement("div");
  if (this.visible_) {
    this.show();
  }

  this.getPanes().overlayMouseTarget.appendChild(this.div_);

  google.maps.event.addDomListener(this.div_, "click", function () {
    var mc = cClusterIcon.cluster_.getMarkerClusterer();
    /**
     * This event is fired when a cluster marker is clicked.
     * @name MarkerClusterer#click
     * @param {Cluster} c The cluster that was clicked.
     * @event
     */
    google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
    google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name

    // The default click handler follows. Disable it by setting
    // the zoomOnClick property to false.
    var mz = mc.getMaxZoom();
    if (mc.getZoomOnClick()) {
      // Zoom into the cluster.
      mc.getMap().fitBounds(cClusterIcon.cluster_.getBounds());
      // Don't zoom beyond the max zoom level
      if (mz && (mc.getMap().getZoom() > mz)) {
        mc.getMap().setZoom(mz + 1);
      }
    }
  });

  google.maps.event.addDomListener(this.div_, "mouseover", function () {
    var mc = cClusterIcon.cluster_.getMarkerClusterer();
    /**
     * This event is fired when the mouse moves over a cluster marker.
     * @name MarkerClusterer#mouseover
     * @param {Cluster} c The cluster that the mouse moved over.
     * @event
     */
    google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_);
  });

  google.maps.event.addDomListener(this.div_, "mouseout", function () {
    var mc = cClusterIcon.cluster_.getMarkerClusterer();
    /**
     * This event is fired when the mouse moves out of a cluster marker.
     * @name MarkerClusterer#mouseout
     * @param {Cluster} c The cluster that the mouse moved out of.
     * @event
     */
    google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_);
  });
};


/**
 * Removes the icon from the DOM.
 */
ClusterIcon.prototype.onRemove = function () {
  if (this.div_ && this.div_.parentNode) {
    this.hide();
    google.maps.event.clearInstanceListeners(this.div_);
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};


/**
 * Draws the icon.
 */
ClusterIcon.prototype.draw = function () {
  if (this.visible_) {
    var pos = this.getPosFromLatLng_(this.center_);
    this.div_.style.top = pos.y + "px";
    this.div_.style.left = pos.x + "px";
  }
};


/**
 * Hides the icon.
 */
ClusterIcon.prototype.hide = function () {
  if (this.div_) {
    this.div_.style.display = "none";
  }
  this.visible_ = false;
};


/**
 * Positions and shows the icon.
 */
ClusterIcon.prototype.show = function () {
  if (this.div_) {
    var pos = this.getPosFromLatLng_(this.center_);
    this.div_.style.cssText = this.createCss(pos);
    if (this.cluster_.printable_) {
      // (Would like to use "width: inherit;" below, but doesn't work with MSIE)
      this.div_.innerHTML = "<img src='" + this.url_ + "'><div style='position: absolute; top: 0px; left: 0px; width: " + this.width_ + "px;'>" + this.sums_.text + "</div>";
    } else {
      this.div_.innerHTML = this.sums_.text;
    }
    this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
    this.div_.style.display = "";
  }
  this.visible_ = true;
};


/**
 * Sets the icon styles to the appropriate element in the styles array.
 *
 * @param {ClusterIconInfo} sums The icon label text and styles index.
 */
ClusterIcon.prototype.useStyle = function (sums) {
  this.sums_ = sums;
  var index = Math.max(0, sums.index - 1);
  index = Math.min(this.styles_.length - 1, index);
  var style = this.styles_[index];
  this.url_ = style.url;
  this.height_ = style.height;
  this.width_ = style.width;
  this.anchor_ = style.anchor;
  this.textColor_ = style.textColor || "black";
  this.textSize_ = style.textSize || 11;
  this.textDecoration_ = style.textDecoration || "none";
  this.fontWeight_ = style.fontWeight || "bold";
  this.fontStyle_ = style.fontStyle || "normal";
  this.fontFamily_ = style.fontFamily || "Arial,sans-serif";
  this.backgroundPosition_ = style.backgroundPosition || "0 0";
};


/**
 * Sets the position at which to center the icon.
 *
 * @param {google.maps.LatLng} center The latlng to set as the center.
 */
ClusterIcon.prototype.setCenter = function (center) {
  this.center_ = center;
};


/**
 * Creates the cssText style parameter based on the position of the icon.
 *
 * @param {google.maps.Point} pos The position of the icon.
 * @return {string} The CSS style text.
 */
ClusterIcon.prototype.createCss = function (pos) {
  var style = [];
  if (!this.cluster_.printable_) {
    style.push('background-image:url(' + this.url_ + ');');
    style.push('background-position:' + this.backgroundPosition_ + ';');
  }

  if (typeof this.anchor_ === 'object') {
    if (typeof this.anchor_[0] === 'number' && this.anchor_[0] > 0 &&
        this.anchor_[0] < this.height_) {
      style.push('height:' + (this.height_ - this.anchor_[0]) +
          'px; padding-top:' + this.anchor_[0] + 'px;');
    } else {
      style.push('height:' + this.height_ + 'px; line-height:' + this.height_ +
          'px;');
    }
    if (typeof this.anchor_[1] === 'number' && this.anchor_[1] > 0 &&
        this.anchor_[1] < this.width_) {
      style.push('width:' + (this.width_ - this.anchor_[1]) +
          'px; padding-left:' + this.anchor_[1] + 'px;');
    } else {
      style.push('width:' + this.width_ + 'px; text-align:center;');
    }
  } else {
    style.push('height:' + this.height_ + 'px; line-height:' +
        this.height_ + 'px; width:' + this.width_ + 'px; text-align:center;');
  }

  style.push('cursor:pointer; top:' + pos.y + 'px; left:' +
      pos.x + 'px; color:' + this.textColor_ + '; position:absolute; font-size:' +
      this.textSize_ + 'px; font-family:' + this.fontFamily_ + '; font-weight:' +
      this.fontWeight_ + '; font-style:' + this.fontStyle_ + '; text-decoration:' +
      this.textDecoration_ + ';');
  return style.join("");
};


/**
 * Returns the position at which to place the DIV depending on the latlng.
 *
 * @param {google.maps.LatLng} latlng The position in latlng.
 * @return {google.maps.Point} The position in pixels.
 */
ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {
  var pos = this.getProjection().fromLatLngToDivPixel(latlng);
  pos.x -= parseInt(this.width_ / 2, 10);
  pos.y -= parseInt(this.height_ / 2, 10);
  return pos;
};


/**
 * Creates a single cluster that manages a group of proximate markers.
 *  Used internally, do not call this constructor directly.
 * @constructor
 * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
 *  cluster is associated.
 */
function Cluster(mc) {
  this.markerClusterer_ = mc;
  this.map_ = mc.getMap();
  this.gridSize_ = mc.getGridSize();
  this.minClusterSize_ = mc.getMinimumClusterSize();
  this.averageCenter_ = mc.getAverageCenter();
  this.printable_ = mc.getPrintable();
  this.markers_ = [];
  this.center_ = null;
  this.bounds_ = null;
  this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());
}


/**
 * Returns the number of markers managed by the cluster. You can call this from
 * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
 * for the <code>MarkerClusterer</code> object.
 *
 * @return {number} The number of markers in the cluster.
 */
Cluster.prototype.getSize = function () {
  return this.markers_.length;
};


/**
 * Returns the array of markers managed by the cluster. You can call this from
 * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
 * for the <code>MarkerClusterer</code> object.
 *
 * @return {Array} The array of markers in the cluster.
 */
Cluster.prototype.getMarkers = function () {
  return this.markers_;
};


/**
 * Returns the center of the cluster. You can call this from
 * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
 * for the <code>MarkerClusterer</code> object.
 *
 * @return {google.maps.LatLng} The center of the cluster.
 */
Cluster.prototype.getCenter = function () {
  return this.center_;
};


/**
 * Returns the map with which the cluster is associated.
 *
 * @return {google.maps.Map} The map.
 * @ignore
 */
Cluster.prototype.getMap = function () {
  return this.map_;
};


/**
 * Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
 *
 * @return {MarkerClusterer} The associated marker clusterer.
 * @ignore
 */
Cluster.prototype.getMarkerClusterer = function () {
  return this.markerClusterer_;
};


/**
 * Returns the bounds of the cluster.
 *
 * @return {google.maps.LatLngBounds} the cluster bounds.
 * @ignore
 */
Cluster.prototype.getBounds = function () {
  var i;
  var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  var markers = this.getMarkers();
  for (i = 0; i < markers.length; i++) {
    bounds.extend(markers[i].getPosition());
  }
  return bounds;
};


/**
 * Removes the cluster from the map.
 *
 * @ignore
 */
Cluster.prototype.remove = function () {
  this.clusterIcon_.setMap(null);
  this.markers_ = [];
  delete this.markers_;
};


/**
 * Adds a marker to the cluster.
 *
 * @param {google.maps.Marker} marker The marker to be added.
 * @return {boolean} True if the marker was added.
 * @ignore
 */
Cluster.prototype.addMarker = function (marker) {
  var i;
  var mCount;

  if (this.isMarkerAlreadyAdded_(marker)) {
    return false;
  }

  if (!this.center_) {
    this.center_ = marker.getPosition();
    this.calculateBounds_();
  } else {
    if (this.averageCenter_) {
      var l = this.markers_.length + 1;
      var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
      var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
      this.center_ = new google.maps.LatLng(lat, lng);
      this.calculateBounds_();
    }
  }

  marker.isAdded = true;
  this.markers_.push(marker);

  mCount = this.markers_.length;
  if (this.map_.getZoom() > this.markerClusterer_.getMaxZoom()) {
    // Zoomed in past max zoom, so show the marker.
    if (marker.getMap() !== this.map_) {
      marker.setMap(this.map_);
    }
  } else if (mCount < this.minClusterSize_) {
    // Min cluster size not reached so show the marker.
    if (marker.getMap() !== this.map_) {
      marker.setMap(this.map_);
    }
  } else if (mCount === this.minClusterSize_) {
    // Hide the markers that were showing.
    for (i = 0; i < mCount; i++) {
      this.markers_[i].setMap(null);
    }
  } else {
    marker.setMap(null);
  }

  this.updateIcon_();
  return true;
};


/**
 * Determines if a marker lies within the cluster's bounds.
 *
 * @param {google.maps.Marker} marker The marker to check.
 * @return {boolean} True if the marker lies in the bounds.
 * @ignore
 */
Cluster.prototype.isMarkerInClusterBounds = function (marker) {
  return this.bounds_.contains(marker.getPosition());
};


/**
 * Calculates the extended bounds of the cluster with the grid.
 */
Cluster.prototype.calculateBounds_ = function () {
  var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};


/**
 * Updates the cluster icon.
 */
Cluster.prototype.updateIcon_ = function () {
  var mCount = this.markers_.length;

  if (this.map_.getZoom() > this.markerClusterer_.getMaxZoom()) {
    this.clusterIcon_.hide();
    return;
  }

  if (mCount < this.minClusterSize_) {
    // Min cluster size not yet reached.
    this.clusterIcon_.hide();
    return;
  }

  var numStyles = this.markerClusterer_.getStyles().length;
  var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
  this.clusterIcon_.setCenter(this.center_);
  this.clusterIcon_.useStyle(sums);
  this.clusterIcon_.show();
};


/**
 * Determines if a marker has already been added to the cluster.
 *
 * @param {google.maps.Marker} marker The marker to check.
 * @return {boolean} True if the marker has already been added.
 */
Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
  var i;
  if (this.markers_.indexOf) {
    return this.markers_.indexOf(marker) !== -1;
  } else {
    for (i = 0; i < this.markers_.length; i++) {
      if (marker === this.markers_[i]) {
        return true;
      }
    }
  }
  return false;
};


/**
 * @name MarkerClustererOptions
 * @class This class represents the optional parameter passed to
 *  the {@link MarkerClusterer} constructor.
 * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
 * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
 *  <code>null</code> if clustering is to be enabled at all zoom levels.
 * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
 *  clicked. You may want to set this to <code>false</code> if you have installed a handler
 *  for the <code>click</code> event and it deals with zooming on its own.
 * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
 *  the average position of all markers in the cluster. If set to <code>false</code>, the
 *  cluster marker is positioned at the location of the first marker added to the cluster.
 * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
 *  before the markers are hidden and a cluster marker appears.
 * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
 *  may want to set this to <code>true</code> to ensure that hidden markers are not included
 *  in the marker count that appears on a cluster marker (this count is the value of the
 *  <code>text</code> property of the result returned by the default <code>calculator</code>).
 *  If set to <code>true</code> and you change the visibility of a marker being clustered, be
 *  sure to also call <code>MarkerClusterer.repaint()</code>.
 * @property {boolean} [printable=false] Whether to make the cluster icons printable. Do not
 *  set to <code>true</code> if the <code>url</code> fields in the <code>styles</code> array
 *  refer to image sprite files.
 * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
 *  marker.
 * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
 *  the text to be displayed on a cluster marker and the index indicating which style to use
 *  for the cluster marker. The input parameters for the function are (1) the array of markers
 *  represented by a cluster marker and (2) the number of cluster icon styles. It returns a
 *  {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
 *  <code>text</code> property which is the number of markers in the cluster and an
 *  <code>index</code> property which is one higher than the lowest integer such that
 *  <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
 *  array, whichever is less. The <code>styles</code> array element used has an index of
 *  <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
 *  <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
 *  for a cluster icon representing 125 markers so the element used in the <code>styles</code>
 *  array is <code>2</code>.
 * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
 *  of the cluster markers to be used. The element to be used to style a given cluster marker
 *  is determined by the function defined by the <code>calculator</code> property.
 *  The default is an array of {@link ClusterIconStyle} elements whose properties are derived
 *  from the values for <code>imagePath</code>, <code>imageExtension</code>, and
 *  <code>imageSizes</code>.
 * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
 *  being used, markers are processed in several batches with a small delay inserted between
 *  each batch in an attempt to avoid Javascript timeout errors. Set this property to the
 *  number of markers to be processed in a single batch; select as high a number as you can
 *  without causing a timeout error in the browser. This number might need to be as low as 100
 *  if 15,000 markers are being managed, for example.
 * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
 *  The full URL of the root name of the group of image files to use for cluster icons.
 *  The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
 *  where n is the image file number (1, 2, etc.).
 * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
 *  The extension name for the cluster icon image files (e.g., <code>"png"</code> or
 *  <code>"jpg"</code>).
 * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
 *  An array of numbers containing the widths of the group of
 *  <code>imagePath</code>n.<code>imageExtension</code> image files.
 *  (The images are assumed to be square.)
 */
/**
 * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
 * @constructor
 * @extends google.maps.OverlayView
 * @param {google.maps.Map} map The Google map to attach to.
 * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
 * @param {MarkerClustererOptions} [opt_options] The optional parameters.
 */
function MarkerClusterer(map, opt_markers, opt_options) {
  // MarkerClusterer implements google.maps.OverlayView interface. We use the
  // extend function to extend MarkerClusterer with google.maps.OverlayView
  // because it might not always be available when the code is defined so we
  // look for it at the last possible moment. If it doesn't exist now then
  // there is no point going ahead :)
  this.extend(MarkerClusterer, google.maps.OverlayView);

  opt_markers = opt_markers || [];
  opt_options = opt_options || {};

  this.markers_ = [];
  this.clusters_ = [];
  this.listeners_ = [];
  this.activeMap_ = null;
  this.ready_ = false;

  this.gridSize_ = opt_options.gridSize || 60;
  this.minClusterSize_ = opt_options.minimumClusterSize || 2;
  this.maxZoom_ = opt_options.maxZoom || null;
  this.styles_ = opt_options.styles || [];
  this.title_ = opt_options.title || "";
  this.zoomOnClick_ = true;
  if (opt_options.zoomOnClick !== undefined) {
    this.zoomOnClick_ = opt_options.zoomOnClick;
  }
  this.averageCenter_ = false;
  if (opt_options.averageCenter !== undefined) {
    this.averageCenter_ = opt_options.averageCenter;
  }
  this.ignoreHidden_ = false;
  if (opt_options.ignoreHidden !== undefined) {
    this.ignoreHidden_ = opt_options.ignoreHidden;
  }
  this.printable_ = false;
  if (opt_options.printable !== undefined) {
    this.printable_ = opt_options.printable;
  }
  this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;
  this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;
  this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;
  this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;
  this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;

  if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
    // Try to avoid IE timeout when processing a huge number of markers:
    this.batchSize_ = this.batchSizeIE_;
  } else {
    this.batchSize_ = MarkerClusterer.BATCH_SIZE;
  }

  this.setupStyles_();

  this.addMarkers(opt_markers, true);
  this.setMap(map); // Note: this causes onAdd to be called
}


/**
 * Implementation of the onAdd interface method.
 * @ignore
 */
MarkerClusterer.prototype.onAdd = function () {
  var cMarkerClusterer = this;

  this.activeMap_ = this.getMap();
  this.ready_ = true;

  this.repaint();

  // Add the map event listeners
  this.listeners_ = [
    google.maps.event.addListener(this.getMap(), "zoom_changed", function () {
      cMarkerClusterer.resetViewport_(false);
    }),
    google.maps.event.addListener(this.getMap(), "idle", function () {
      cMarkerClusterer.redraw_();
    })
  ];
};


/**
 * Implementation of the onRemove interface method.
 * Removes map event listeners and all cluster icons from the DOM.
 * All managed markers are also put back on the map.
 * @ignore
 */
MarkerClusterer.prototype.onRemove = function () {
  var i;

  // Put all the managed markers back on the map:
  for (i = 0; i < this.markers_.length; i++) {
    this.markers_[i].setMap(this.activeMap_);
  }

  // Remove all clusters:
  for (i = 0; i < this.clusters_.length; i++) {
    this.clusters_[i].remove();
  }
  this.clusters_ = [];

  // Remove map event listeners:
  for (i = 0; i < this.listeners_.length; i++) {
    google.maps.event.removeListener(this.listeners_[i]);
  }
  this.listeners_ = [];

  this.activeMap_ = null;
  this.ready_ = false;
};


/**
 * Implementation of the draw interface method.
 * @ignore
 */
MarkerClusterer.prototype.draw = function () {};


/**
 * Sets up the styles object.
 */
MarkerClusterer.prototype.setupStyles_ = function () {
  var i, size;
  if (this.styles_.length > 0) {
    return;
  }

  for (i = 0; i < this.imageSizes_.length; i++) {
    size = this.imageSizes_[i];
    this.styles_.push({
      url: this.imagePath_ + (i + 1) + "." + this.imageExtension_,
      height: size,
      width: size
    });
  }
};


/**
 *  Fits the map to the bounds of the markers managed by the clusterer.
 */
MarkerClusterer.prototype.fitMapToMarkers = function () {
  var i;
  var markers = this.getMarkers();
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < markers.length; i++) {
    bounds.extend(markers[i].getPosition());
  }

  this.getMap().fitBounds(bounds);
};


/**
 * Returns the value of the <code>gridSize</code> property.
 *
 * @return {number} The grid size.
 */
MarkerClusterer.prototype.getGridSize = function () {
  return this.gridSize_;
};


/**
 * Sets the value of the <code>gridSize</code> property.
 *
 * @param {number} gridSize The grid size.
 */
MarkerClusterer.prototype.setGridSize = function (gridSize) {
  this.gridSize_ = gridSize;
};


/**
 * Returns the value of the <code>minimumClusterSize</code> property.
 *
 * @return {number} The minimum cluster size.
 */
MarkerClusterer.prototype.getMinimumClusterSize = function () {
  return this.minClusterSize_;
};

/**
 * Sets the value of the <code>minimumClusterSize</code> property.
 *
 * @param {number} minimumClusterSize The minimum cluster size.
 */
MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {
  this.minClusterSize_ = minimumClusterSize;
};


/**
 *  Returns the value of the <code>maxZoom</code> property.
 *
 *  @return {number} The maximum zoom level.
 */
MarkerClusterer.prototype.getMaxZoom = function () {
  return this.maxZoom_ || this.getMap().mapTypes[this.getMap().getMapTypeId()].maxZoom;
};


/**
 *  Sets the value of the <code>maxZoom</code> property.
 *
 *  @param {number} maxZoom The maximum zoom level.
 */
MarkerClusterer.prototype.setMaxZoom = function (maxZoom) {
  this.maxZoom_ = maxZoom;
};


/**
 *  Returns the value of the <code>styles</code> property.
 *
 *  @return {Array} The array of styles defining the cluster markers to be used.
 */
MarkerClusterer.prototype.getStyles = function () {
  return this.styles_;
};


/**
 *  Sets the value of the <code>styles</code> property.
 *
 *  @param {Array.<ClusterIconStyle>} styles The array of styles to use.
 */
MarkerClusterer.prototype.setStyles = function (styles) {
  this.styles_ = styles;
};


/**
 * Returns the value of the <code>title</code> property.
 *
 * @return {string} The content of the title text.
 */
MarkerClusterer.prototype.getTitle = function () {
  return this.title_;
};


/**
 *  Sets the value of the <code>title</code> property.
 *
 *  @param {string} title The value of the title property.
 */
MarkerClusterer.prototype.setTitle = function (title) {
  this.title_ = title;
};


/**
 * Returns the value of the <code>zoomOnClick</code> property.
 *
 * @return {boolean} True if zoomOnClick property is set.
 */
MarkerClusterer.prototype.getZoomOnClick = function () {
  return this.zoomOnClick_;
};


/**
 *  Sets the value of the <code>zoomOnClick</code> property.
 *
 *  @param {boolean} zoomOnClick The value of the zoomOnClick property.
 */
MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {
  this.zoomOnClick_ = zoomOnClick;
};


/**
 * Returns the value of the <code>averageCenter</code> property.
 *
 * @return {boolean} True if averageCenter property is set.
 */
MarkerClusterer.prototype.getAverageCenter = function () {
  return this.averageCenter_;
};


/**
 *  Sets the value of the <code>averageCenter</code> property.
 *
 *  @param {boolean} averageCenter The value of the averageCenter property.
 */
MarkerClusterer.prototype.setAverageCenter = function (averageCenter) {
  this.averageCenter_ = averageCenter;
};


/**
 * Returns the value of the <code>ignoreHidden</code> property.
 *
 * @return {boolean} True if ignoreHidden property is set.
 */
MarkerClusterer.prototype.getIgnoreHidden = function () {
  return this.ignoreHidden_;
};


/**
 *  Sets the value of the <code>ignoreHidden</code> property.
 *
 *  @param {boolean} ignoreHidden The value of the ignoreHidden property.
 */
MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {
  this.ignoreHidden_ = ignoreHidden;
};


/**
 * Returns the value of the <code>imageExtension</code> property.
 *
 * @return {string} The value of the imageExtension property.
 */
MarkerClusterer.prototype.getImageExtension = function () {
  return this.imageExtension_;
};


/**
 *  Sets the value of the <code>imageExtension</code> property.
 *
 *  @param {string} imageExtension The value of the imageExtension property.
 */
MarkerClusterer.prototype.setImageExtension = function (imageExtension) {
  this.imageExtension_ = imageExtension;
};


/**
 * Returns the value of the <code>imagePath</code> property.
 *
 * @return {string} The value of the imagePath property.
 */
MarkerClusterer.prototype.getImagePath = function () {
  return this.imagePath_;
};


/**
 *  Sets the value of the <code>imagePath</code> property.
 *
 *  @param {string} imagePath The value of the imagePath property.
 */
MarkerClusterer.prototype.setImagePath = function (imagePath) {
  this.imagePath_ = imagePath;
};


/**
 * Returns the value of the <code>imageSizes</code> property.
 *
 * @return {Array} The value of the imageSizes property.
 */
MarkerClusterer.prototype.getImageSizes = function () {
  return this.imageSizes_;
};


/**
 *  Sets the value of the <code>imageSizes</code> property.
 *
 *  @param {Array} imageSizes The value of the imageSizes property.
 */
MarkerClusterer.prototype.setImageSizes = function (imageSizes) {
  this.imageSizes_ = imageSizes;
};


/**
 * Returns the value of the <code>calculator</code> property.
 *
 * @return {function} the value of the calculator property.
 */
MarkerClusterer.prototype.getCalculator = function () {
  return this.calculator_;
};


/**
 * Sets the value of the <code>calculator</code> property.
 *
 * @param {function(Array.<google.maps.Marker>, number)} calculator The value
 *  of the calculator property.
 */
MarkerClusterer.prototype.setCalculator = function (calculator) {
  this.calculator_ = calculator;
};


/**
 * Returns the value of the <code>printable</code> property.
 *
 * @return {boolean} the value of the printable property.
 */
MarkerClusterer.prototype.getPrintable = function () {
  return this.printable_;
};


/**
 * Sets the value of the <code>printable</code> property.
 *
 *  @param {boolean} printable The value of the printable property.
 */
MarkerClusterer.prototype.setPrintable = function (printable) {
  this.printable_ = printable;
};


/**
 * Returns the value of the <code>batchSizeIE</code> property.
 *
 * @return {number} the value of the batchSizeIE property.
 */
MarkerClusterer.prototype.getBatchSizeIE = function () {
  return this.batchSizeIE_;
};


/**
 * Sets the value of the <code>batchSizeIE</code> property.
 *
 *  @param {number} batchSizeIE The value of the batchSizeIE property.
 */
MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {
  this.batchSizeIE_ = batchSizeIE;
};


/**
 *  Returns the array of markers managed by the clusterer.
 *
 *  @return {Array} The array of markers managed by the clusterer.
 */
MarkerClusterer.prototype.getMarkers = function () {
  return this.markers_;
};


/**
 *  Returns the number of markers managed by the clusterer.
 *
 *  @return {number} The number of markers.
 */
MarkerClusterer.prototype.getTotalMarkers = function () {
  return this.markers_.length;
};


/**
 * Returns the number of clusters formed by the clusterer.
 *
 * @return {number} The number of clusters formed by the clusterer.
 */
MarkerClusterer.prototype.getTotalClusters = function () {
  return this.clusters_.length;
};


/**
 * Adds a marker to the clusterer. The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>.
 *
 * @param {google.maps.Marker} marker The marker to add.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 */
MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {
  this.pushMarkerTo_(marker);
  if (!opt_nodraw) {
    this.redraw_();
  }
};


/**
 * Adds an array of markers to the clusterer. The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>.
 *
 * @param {Array.<google.maps.Marker>} markers The markers to add.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 */
MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {
  var i;
  for (i = 0; i < markers.length; i++) {
    this.pushMarkerTo_(markers[i]);
  }
  if (!opt_nodraw) {
    this.redraw_();
  }
};


/**
 * Pushes a marker to the clusterer.
 *
 * @param {google.maps.Marker} marker The marker to add.
 */
MarkerClusterer.prototype.pushMarkerTo_ = function (marker) {
  // If the marker is draggable add a listener so we can update the clusters on the dragend:
  if (marker.getDraggable()) {
    var cMarkerClusterer = this;
    google.maps.event.addListener(marker, "dragend", function () {
      if (cMarkerClusterer.ready_) {
        this.isAdded = false;
        cMarkerClusterer.repaint();
      }
    });
  }
  marker.isAdded = false;
  this.markers_.push(marker);
};


/**
 * Removes a marker from the cluster.  The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
 *  marker was removed from the clusterer.
 *
 * @param {google.maps.Marker} marker The marker to remove.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 * @return {boolean} True if the marker was removed from the clusterer.
 */
MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {
  var removed = this.removeMarker_(marker);

  if (!opt_nodraw && removed) {
    this.repaint();
  }

  return removed;
};


/**
 * Removes an array of markers from the cluster. The clusters are redrawn unless
 *  <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
 *  were removed from the clusterer.
 *
 * @param {Array.<google.maps.Marker>} markers The markers to remove.
 * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
 * @return {boolean} True if markers were removed from the clusterer.
 */
MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {
  var i, r;
  var removed = false;

  for (i = 0; i < markers.length; i++) {
    r = this.removeMarker_(markers[i]);
    removed = removed || r;
  }

  if (!opt_nodraw && removed) {
    this.repaint();
  }

  return removed;
};


/**
 * Removes a marker and returns true if removed, false if not.
 *
 * @param {google.maps.Marker} marker The marker to remove
 * @return {boolean} Whether the marker was removed or not
 */
MarkerClusterer.prototype.removeMarker_ = function (marker) {
  var i;
  var index = -1;
  if (this.markers_.indexOf) {
    index = this.markers_.indexOf(marker);
  } else {
    for (i = 0; i < this.markers_.length; i++) {
      if (marker === this.markers_[i]) {
        index = i;
        break;
      }
    }
  }

  if (index === -1) {
    // Marker is not in our list of markers, so do nothing:
    return false;
  }

  marker.setMap(null);
  this.markers_.splice(index, 1); // Remove the marker from the list of managed markers
  return true;
};


/**
 * Removes all clusters and markers from the map and also removes all markers
 *  managed by the clusterer.
 */
MarkerClusterer.prototype.clearMarkers = function () {
  this.resetViewport_(true);
  this.markers_ = [];
};


/**
 * Recalculates and redraws all the marker clusters from scratch.
 *  Call this after changing any properties.
 */
MarkerClusterer.prototype.repaint = function () {
  var oldClusters = this.clusters_.slice();
  this.clusters_ = [];
  this.resetViewport_(false);
  this.redraw_();

  // Remove the old clusters.
  // Do it in a timeout to prevent blinking effect.
  setTimeout(function () {
    var i;
    for (i = 0; i < oldClusters.length; i++) {
      oldClusters[i].remove();
    }
  }, 0);
};


/**
 * Returns the current bounds extended by the grid size.
 *
 * @param {google.maps.LatLngBounds} bounds The bounds to extend.
 * @return {google.maps.LatLngBounds} The extended bounds.
 * @ignore
 */
MarkerClusterer.prototype.getExtendedBounds = function (bounds) {
  var projection = this.getProjection();

  // Turn the bounds into latlng.
  var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
      bounds.getNorthEast().lng());
  var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
      bounds.getSouthWest().lng());

  // Convert the points to pixels and the extend out by the grid size.
  var trPix = projection.fromLatLngToDivPixel(tr);
  trPix.x += this.gridSize_;
  trPix.y -= this.gridSize_;

  var blPix = projection.fromLatLngToDivPixel(bl);
  blPix.x -= this.gridSize_;
  blPix.y += this.gridSize_;

  // Convert the pixel points back to LatLng
  var ne = projection.fromDivPixelToLatLng(trPix);
  var sw = projection.fromDivPixelToLatLng(blPix);

  // Extend the bounds to contain the new bounds.
  bounds.extend(ne);
  bounds.extend(sw);

  return bounds;
};


/**
 * Redraws all the clusters.
 */
MarkerClusterer.prototype.redraw_ = function () {
  this.createClusters_(0);
};


/**
 * Removes all clusters from the map. The markers are also removed from the map
 *  if <code>opt_hide</code> is set to <code>true</code>.
 *
 * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
 *  from the map.
 */
MarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
  var i, marker;
  // Remove all the clusters
  for (i = 0; i < this.clusters_.length; i++) {
    this.clusters_[i].remove();
  }
  this.clusters_ = [];

  // Reset the markers to not be added and to be removed from the map.
  for (i = 0; i < this.markers_.length; i++) {
    marker = this.markers_[i];
    marker.isAdded = false;
    if (opt_hide) {
      marker.setMap(null);
    }
  }
};


/**
 * Calculates the distance between two latlng locations in km.
 *
 * @param {google.maps.LatLng} p1 The first lat lng point.
 * @param {google.maps.LatLng} p2 The second lat lng point.
 * @return {number} The distance between the two points in km.
 * @see http://www.movable-type.co.uk/scripts/latlong.html
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {
  var R = 6371; // Radius of the Earth in km
  var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
  var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d;
};


/**
 * Determines if a marker is contained in a bounds.
 *
 * @param {google.maps.Marker} marker The marker to check.
 * @param {google.maps.LatLngBounds} bounds The bounds to check against.
 * @return {boolean} True if the marker is in the bounds.
 */
MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {
  return bounds.contains(marker.getPosition());
};


/**
 * Adds a marker to a cluster, or creates a new cluster.
 *
 * @param {google.maps.Marker} marker The marker to add.
 */
MarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
  var i, d, cluster, center;
  var distance = 40000; // Some large number
  var clusterToAddTo = null;
  for (i = 0; i < this.clusters_.length; i++) {
    cluster = this.clusters_[i];
    center = cluster.getCenter();
    if (center) {
      d = this.distanceBetweenPoints_(center, marker.getPosition());
      if (d < distance) {
        distance = d;
        clusterToAddTo = cluster;
      }
    }
  }

  if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
    clusterToAddTo.addMarker(marker);
  } else {
    cluster = new Cluster(this);
    cluster.addMarker(marker);
    this.clusters_.push(cluster);
  }
};


/**
 * Creates the clusters. This is done in batches to avoid timeout errors
 *  in some browsers when there is a huge number of markers.
 *
 * @param {number} iFirst The index of the first marker in the batch of
 *  markers to be added to clusters.
 */
MarkerClusterer.prototype.createClusters_ = function (iFirst) {
  var i, marker;
  var cMarkerClusterer = this;
  if (!this.ready_) {
    return;
  }

  // Cancel previous batch processing if we're working on the first batch:
  if (iFirst === 0) {
    /**
     * This event is fired when the <code>MarkerClusterer</code> begins
     *  clustering markers.
     * @name MarkerClusterer#clusteringbegin
     * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
     * @event
     */
    google.maps.event.trigger(this, "clusteringbegin", this);

    if (typeof this.timerRefStatic !== "undefined") {
      clearTimeout(this.timerRefStatic);
      delete this.timerRefStatic;
    }
  }

  // Get our current map view bounds.
  // Create a new bounds object so we don't affect the map.
  var mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
      this.getMap().getBounds().getNorthEast());
  var bounds = this.getExtendedBounds(mapBounds);

  var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);

  for (i = iFirst; i < iLast; i++) {
    marker = this.markers_[i];
    if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
      if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
        this.addToClosestCluster_(marker);
      }
    }
  }

  if (iLast < this.markers_.length) {
    this.timerRefStatic = setTimeout(function () {
      cMarkerClusterer.createClusters_(iLast);
    }, 0);
  } else {
    delete this.timerRefStatic;

    /**
     * This event is fired when the <code>MarkerClusterer</code> stops
     *  clustering markers.
     * @name MarkerClusterer#clusteringend
     * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
     * @event
     */
    google.maps.event.trigger(this, "clusteringend", this);
  }
};


/**
 * Extends an object's prototype by another's.
 *
 * @param {Object} obj1 The object to be extended.
 * @param {Object} obj2 The object to extend with.
 * @return {Object} The new extended object.
 * @ignore
 */
MarkerClusterer.prototype.extend = function (obj1, obj2) {
  return (function (object) {
    var property;
    for (property in object.prototype) {
      this.prototype[property] = object.prototype[property];
    }
    return this;
  }).apply(obj1, [obj2]);
};


/**
 * The default function for determining the label text and style
 * for a cluster icon.
 *
 * @param {Array.<google.maps.Marker>} markers The array of represented by the cluster.
 * @param {number} numStyles The number of marker styles available.
 * @return {ClusterIconInfo} The information resource for the cluster.
 * @constant
 * @ignore
 */
MarkerClusterer.CALCULATOR = function (markers, numStyles) {
  var index = 0;
  var count = markers.length.toString();

  var dv = count;
  while (dv !== 0) {
    dv = parseInt(dv / 10, 10);
    index++;
  }

  index = Math.min(index, numStyles);
  return {
    text: count,
    index: index
  };
};


/**
 * The number of markers to process in one batch.
 *
 * @type {number}
 * @constant
 */
MarkerClusterer.BATCH_SIZE = 2000;


/**
 * The number of markers to process in one batch (IE only).
 *
 * @type {number}
 * @constant
 */
MarkerClusterer.BATCH_SIZE_IE = 500;


/**
 * The default root name for the marker cluster images.
 *
 * @type {string}
 * @constant
 */
MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m";


/**
 * The default extension name for the marker cluster images.
 *
 * @type {string}
 * @constant
 */
MarkerClusterer.IMAGE_EXTENSION = "png";


/**
 * The default array of sizes for the marker cluster images.
 *
 * @type {Array.<number>}
 * @constant
 */
MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];
;
/*!
 * mustache.js - Logic-less {{mustache}} templates with JavaScript
 * http://github.com/janl/mustache.js
 */

/*global define: false*/

(function (global, factory) {
  if (typeof exports === "object" && exports) {
    factory(exports); // CommonJS
  } else if (typeof define === "function" && define.amd) {
    define(['exports'], factory); // AMD
  } else {
    factory(global.Mustache = {}); // <script>
  }
}(this, function (mustache) {

  var Object_toString = Object.prototype.toString;
  var isArray = Array.isArray || function (object) {
    return Object_toString.call(object) === '[object Array]';
  };

  function isFunction(object) {
    return typeof object === 'function';
  }

  function escapeRegExp(string) {
    return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
  }

  // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
  // See https://github.com/janl/mustache.js/issues/189
  var RegExp_test = RegExp.prototype.test;
  function testRegExp(re, string) {
    return RegExp_test.call(re, string);
  }

  var nonSpaceRe = /\S/;
  function isWhitespace(string) {
    return !testRegExp(nonSpaceRe, string);
  }

  var entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  var whiteRe = /\s*/;
  var spaceRe = /\s+/;
  var equalsRe = /\s*=/;
  var curlyRe = /\s*\}/;
  var tagRe = /#|\^|\/|>|\{|&|=|!/;

  /**
   * Breaks up the given `template` string into a tree of tokens. If the `tags`
   * argument is given here it must be an array with two string values: the
   * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
   * course, the default is to use mustaches (i.e. mustache.tags).
   *
   * A token is an array with at least 4 elements. The first element is the
   * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
   * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
   * all text that appears outside a symbol this element is "text".
   *
   * The second element of a token is its "value". For mustache tags this is
   * whatever else was inside the tag besides the opening symbol. For text tokens
   * this is the text itself.
   *
   * The third and fourth elements of the token are the start and end indices,
   * respectively, of the token in the original template.
   *
   * Tokens that are the root node of a subtree contain two more elements: 1) an
   * array of tokens in the subtree and 2) the index in the original template at
   * which the closing tag for that section begins.
   */
  function parseTemplate(template, tags) {
    if (!template)
      return [];

    var sections = [];     // Stack to hold section tokens
    var tokens = [];       // Buffer to hold the tokens
    var spaces = [];       // Indices of whitespace tokens on the current line
    var hasTag = false;    // Is there a {{tag}} on the current line?
    var nonSpace = false;  // Is there a non-space char on the current line?

    // Strips all whitespace tokens array for the current line
    // if there was a {{#tag}} on it and otherwise only space.
    function stripSpace() {
      if (hasTag && !nonSpace) {
        while (spaces.length)
          delete tokens[spaces.pop()];
      } else {
        spaces = [];
      }

      hasTag = false;
      nonSpace = false;
    }

    var openingTagRe, closingTagRe, closingCurlyRe;
    function compileTags(tags) {
      if (typeof tags === 'string')
        tags = tags.split(spaceRe, 2);

      if (!isArray(tags) || tags.length !== 2)
        throw new Error('Invalid tags: ' + tags);

      openingTagRe = new RegExp(escapeRegExp(tags[0]) + '\\s*');
      closingTagRe = new RegExp('\\s*' + escapeRegExp(tags[1]));
      closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tags[1]));
    }

    compileTags(tags || mustache.tags);

    var scanner = new Scanner(template);

    var start, type, value, chr, token, openSection;
    while (!scanner.eos()) {
      start = scanner.pos;

      // Match any text between tags.
      value = scanner.scanUntil(openingTagRe);

      if (value) {
        for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
          chr = value.charAt(i);

          if (isWhitespace(chr)) {
            spaces.push(tokens.length);
          } else {
            nonSpace = true;
          }

          tokens.push([ 'text', chr, start, start + 1 ]);
          start += 1;

          // Check for whitespace on the current line.
          if (chr === '\n')
            stripSpace();
        }
      }

      // Match the opening tag.
      if (!scanner.scan(openingTagRe))
        break;

      hasTag = true;

      // Get the tag type.
      type = scanner.scan(tagRe) || 'name';
      scanner.scan(whiteRe);

      // Get the tag value.
      if (type === '=') {
        value = scanner.scanUntil(equalsRe);
        scanner.scan(equalsRe);
        scanner.scanUntil(closingTagRe);
      } else if (type === '{') {
        value = scanner.scanUntil(closingCurlyRe);
        scanner.scan(curlyRe);
        scanner.scanUntil(closingTagRe);
        type = '&';
      } else {
        value = scanner.scanUntil(closingTagRe);
      }

      // Match the closing tag.
      if (!scanner.scan(closingTagRe))
        throw new Error('Unclosed tag at ' + scanner.pos);

      token = [ type, value, start, scanner.pos ];
      tokens.push(token);

      if (type === '#' || type === '^') {
        sections.push(token);
      } else if (type === '/') {
        // Check section nesting.
        openSection = sections.pop();

        if (!openSection)
          throw new Error('Unopened section "' + value + '" at ' + start);

        if (openSection[1] !== value)
          throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
      } else if (type === 'name' || type === '{' || type === '&') {
        nonSpace = true;
      } else if (type === '=') {
        // Set the tags for the next time around.
        compileTags(value);
      }
    }

    // Make sure there are no open sections when we're done.
    openSection = sections.pop();

    if (openSection)
      throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);

    return nestTokens(squashTokens(tokens));
  }

  /**
   * Combines the values of consecutive text tokens in the given `tokens` array
   * to a single token.
   */
  function squashTokens(tokens) {
    var squashedTokens = [];

    var token, lastToken;
    for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
      token = tokens[i];

      if (token) {
        if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
          lastToken[1] += token[1];
          lastToken[3] = token[3];
        } else {
          squashedTokens.push(token);
          lastToken = token;
        }
      }
    }

    return squashedTokens;
  }

  /**
   * Forms the given array of `tokens` into a nested tree structure where
   * tokens that represent a section have two additional items: 1) an array of
   * all tokens that appear in that section and 2) the index in the original
   * template that represents the end of that section.
   */
  function nestTokens(tokens) {
    var nestedTokens = [];
    var collector = nestedTokens;
    var sections = [];

    var token, section;
    for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
      token = tokens[i];

      switch (token[0]) {
      case '#':
      case '^':
        collector.push(token);
        sections.push(token);
        collector = token[4] = [];
        break;
      case '/':
        section = sections.pop();
        section[5] = token[2];
        collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
        break;
      default:
        collector.push(token);
      }
    }

    return nestedTokens;
  }

  /**
   * A simple string scanner that is used by the template parser to find
   * tokens in template strings.
   */
  function Scanner(string) {
    this.string = string;
    this.tail = string;
    this.pos = 0;
  }

  /**
   * Returns `true` if the tail is empty (end of string).
   */
  Scanner.prototype.eos = function () {
    return this.tail === "";
  };

  /**
   * Tries to match the given regular expression at the current position.
   * Returns the matched text if it can match, the empty string otherwise.
   */
  Scanner.prototype.scan = function (re) {
    var match = this.tail.match(re);

    if (!match || match.index !== 0)
      return '';

    var string = match[0];

    this.tail = this.tail.substring(string.length);
    this.pos += string.length;

    return string;
  };

  /**
   * Skips all text until the given regular expression can be matched. Returns
   * the skipped string, which is the entire tail if no match can be made.
   */
  Scanner.prototype.scanUntil = function (re) {
    var index = this.tail.search(re), match;

    switch (index) {
    case -1:
      match = this.tail;
      this.tail = "";
      break;
    case 0:
      match = "";
      break;
    default:
      match = this.tail.substring(0, index);
      this.tail = this.tail.substring(index);
    }

    this.pos += match.length;

    return match;
  };

  /**
   * Represents a rendering context by wrapping a view object and
   * maintaining a reference to the parent context.
   */
  function Context(view, parentContext) {
    this.view = view == null ? {} : view;
    this.cache = { '.': this.view };
    this.parent = parentContext;
  }

  /**
   * Creates a new context using the given view with this context
   * as the parent.
   */
  Context.prototype.push = function (view) {
    return new Context(view, this);
  };

  /**
   * Returns the value of the given name in this context, traversing
   * up the context hierarchy if the value is absent in this context's view.
   */
  Context.prototype.lookup = function (name) {
    var cache = this.cache;

    var value;
    if (name in cache) {
      value = cache[name];
    } else {
      var context = this, names, index;

      while (context) {
        if (name.indexOf('.') > 0) {
          value = context.view;
          names = name.split('.');
          index = 0;

          while (value != null && index < names.length)
            value = value[names[index++]];
        } else {
          value = context.view[name];
        }

        if (value != null)
          break;

        context = context.parent;
      }

      cache[name] = value;
    }

    if (isFunction(value))
      value = value.call(this.view);

    return value;
  };

  /**
   * A Writer knows how to take a stream of tokens and render them to a
   * string, given a context. It also maintains a cache of templates to
   * avoid the need to parse the same template twice.
   */
  function Writer() {
    this.cache = {};
  }

  /**
   * Clears all cached templates in this writer.
   */
  Writer.prototype.clearCache = function () {
    this.cache = {};
  };

  /**
   * Parses and caches the given `template` and returns the array of tokens
   * that is generated from the parse.
   */
  Writer.prototype.parse = function (template, tags) {
    var cache = this.cache;
    var tokens = cache[template];

    if (tokens == null)
      tokens = cache[template] = parseTemplate(template, tags);

    return tokens;
  };

  /**
   * High-level method that is used to render the given `template` with
   * the given `view`.
   *
   * The optional `partials` argument may be an object that contains the
   * names and templates of partials that are used in the template. It may
   * also be a function that is used to load partial templates on the fly
   * that takes a single argument: the name of the partial.
   */
  Writer.prototype.render = function (template, view, partials) {
    var tokens = this.parse(template);
    var context = (view instanceof Context) ? view : new Context(view);
    return this.renderTokens(tokens, context, partials, template);
  };

  /**
   * Low-level method that renders the given array of `tokens` using
   * the given `context` and `partials`.
   *
   * Note: The `originalTemplate` is only ever used to extract the portion
   * of the original template that was contained in a higher-order section.
   * If the template doesn't use higher-order sections, this argument may
   * be omitted.
   */
  Writer.prototype.renderTokens = function (tokens, context, partials, originalTemplate) {
    var buffer = '';

    // This function is used to render an arbitrary template
    // in the current context by higher-order sections.
    var self = this;
    function subRender(template) {
      return self.render(template, context, partials);
    }

    var token, value;
    for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
      token = tokens[i];

      switch (token[0]) {
      case '#':
        value = context.lookup(token[1]);

        if (!value)
          continue;

        if (isArray(value)) {
          for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
            buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
          }
        } else if (typeof value === 'object' || typeof value === 'string') {
          buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
        } else if (isFunction(value)) {
          if (typeof originalTemplate !== 'string')
            throw new Error('Cannot use higher-order sections without the original template');

          // Extract the portion of the original template that the section contains.
          value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);

          if (value != null)
            buffer += value;
        } else {
          buffer += this.renderTokens(token[4], context, partials, originalTemplate);
        }

        break;
      case '^':
        value = context.lookup(token[1]);

        // Use JavaScript's definition of falsy. Include empty arrays.
        // See https://github.com/janl/mustache.js/issues/186
        if (!value || (isArray(value) && value.length === 0))
          buffer += this.renderTokens(token[4], context, partials, originalTemplate);

        break;
      case '>':
        if (!partials)
          continue;

        value = isFunction(partials) ? partials(token[1]) : partials[token[1]];

        if (value != null)
          buffer += this.renderTokens(this.parse(value), context, partials, value);

        break;
      case '&':
        value = context.lookup(token[1]);

        if (value != null)
          buffer += value;

        break;
      case 'name':
        value = context.lookup(token[1]);

        if (value != null)
          buffer += mustache.escape(value);

        break;
      case 'text':
        buffer += token[1];
        break;
      }
    }

    return buffer;
  };

  mustache.name = "mustache.js";
  mustache.version = "0.8.1";
  mustache.tags = [ "{{", "}}" ];

  // All high-level mustache.* functions use this writer.
  var defaultWriter = new Writer();

  /**
   * Clears all cached templates in the default writer.
   */
  mustache.clearCache = function () {
    return defaultWriter.clearCache();
  };

  /**
   * Parses and caches the given template in the default writer and returns the
   * array of tokens it contains. Doing this ahead of time avoids the need to
   * parse templates on the fly as they are rendered.
   */
  mustache.parse = function (template, tags) {
    return defaultWriter.parse(template, tags);
  };

  /**
   * Renders the `template` with the given `view` and `partials` using the
   * default writer.
   */
  mustache.render = function (template, view, partials) {
    return defaultWriter.render(template, view, partials);
  };

  // This is here for backwards compatibility with 0.4.x.
  mustache.to_html = function (template, view, partials, send) {
    var result = mustache.render(template, view, partials);

    if (isFunction(send)) {
      send(result);
    } else {
      return result;
    }
  };

  // Export the escaping function so that the user may override it.
  // See https://github.com/janl/mustache.js/issues/244
  mustache.escape = escapeHtml;

  // Export these mainly for testing, but also for advanced usage.
  mustache.Scanner = Scanner;
  mustache.Context = Context;
  mustache.Writer = Writer;

}));
;
/*! VelocityJS.org (1.2.3). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */
/*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */
!function (a) { function b(a) { var b = a.length, d = c.type(a); return "function" === d || c.isWindow(a) ? !1 : 1 === a.nodeType && b ? !0 : "array" === d || 0 === b || "number" == typeof b && b > 0 && b - 1 in a } if (!a.jQuery) { var c = function (a, b) { return new c.fn.init(a, b) }; c.isWindow = function (a) { return null != a && a == a.window }, c.type = function (a) { return null == a ? a + "" : "object" == typeof a || "function" == typeof a ? e[g.call(a)] || "object" : typeof a }, c.isArray = Array.isArray || function (a) { return "array" === c.type(a) }, c.isPlainObject = function (a) { var b; if (!a || "object" !== c.type(a) || a.nodeType || c.isWindow(a)) return !1; try { if (a.constructor && !f.call(a, "constructor") && !f.call(a.constructor.prototype, "isPrototypeOf")) return !1 } catch (d) { return !1 } for (b in a); return void 0 === b || f.call(a, b) }, c.each = function (a, c, d) { var e, f = 0, g = a.length, h = b(a); if (d) { if (h) for (; g > f && (e = c.apply(a[f], d), e !== !1) ; f++); else for (f in a) if (e = c.apply(a[f], d), e === !1) break } else if (h) for (; g > f && (e = c.call(a[f], f, a[f]), e !== !1) ; f++); else for (f in a) if (e = c.call(a[f], f, a[f]), e === !1) break; return a }, c.data = function (a, b, e) { if (void 0 === e) { var f = a[c.expando], g = f && d[f]; if (void 0 === b) return g; if (g && b in g) return g[b] } else if (void 0 !== b) { var f = a[c.expando] || (a[c.expando] = ++c.uuid); return d[f] = d[f] || {}, d[f][b] = e, e } }, c.removeData = function (a, b) { var e = a[c.expando], f = e && d[e]; f && c.each(b, function (a, b) { delete f[b] }) }, c.extend = function () { var a, b, d, e, f, g, h = arguments[0] || {}, i = 1, j = arguments.length, k = !1; for ("boolean" == typeof h && (k = h, h = arguments[i] || {}, i++), "object" != typeof h && "function" !== c.type(h) && (h = {}), i === j && (h = this, i--) ; j > i; i++) if (null != (f = arguments[i])) for (e in f) a = h[e], d = f[e], h !== d && (k && d && (c.isPlainObject(d) || (b = c.isArray(d))) ? (b ? (b = !1, g = a && c.isArray(a) ? a : []) : g = a && c.isPlainObject(a) ? a : {}, h[e] = c.extend(k, g, d)) : void 0 !== d && (h[e] = d)); return h }, c.queue = function (a, d, e) { function f(a, c) { var d = c || []; return null != a && (b(Object(a)) ? !function (a, b) { for (var c = +b.length, d = 0, e = a.length; c > d;) a[e++] = b[d++]; if (c !== c) for (; void 0 !== b[d];) a[e++] = b[d++]; return a.length = e, a }(d, "string" == typeof a ? [a] : a) : [].push.call(d, a)), d } if (a) { d = (d || "fx") + "queue"; var g = c.data(a, d); return e ? (!g || c.isArray(e) ? g = c.data(a, d, f(e)) : g.push(e), g) : g || [] } }, c.dequeue = function (a, b) { c.each(a.nodeType ? [a] : a, function (a, d) { b = b || "fx"; var e = c.queue(d, b), f = e.shift(); "inprogress" === f && (f = e.shift()), f && ("fx" === b && e.unshift("inprogress"), f.call(d, function () { c.dequeue(d, b) })) }) }, c.fn = c.prototype = { init: function (a) { if (a.nodeType) return this[0] = a, this; throw new Error("Not a DOM node.") }, offset: function () { var b = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : { top: 0, left: 0 }; return { top: b.top + (a.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0), left: b.left + (a.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0) } }, position: function () { function a() { for (var a = this.offsetParent || document; a && "html" === !a.nodeType.toLowerCase && "static" === a.style.position;) a = a.offsetParent; return a || document } var b = this[0], a = a.apply(b), d = this.offset(), e = /^(?:body|html)$/i.test(a.nodeName) ? { top: 0, left: 0 } : c(a).offset(); return d.top -= parseFloat(b.style.marginTop) || 0, d.left -= parseFloat(b.style.marginLeft) || 0, a.style && (e.top += parseFloat(a.style.borderTopWidth) || 0, e.left += parseFloat(a.style.borderLeftWidth) || 0), { top: d.top - e.top, left: d.left - e.left } } }; var d = {}; c.expando = "velocity" + (new Date).getTime(), c.uuid = 0; for (var e = {}, f = e.hasOwnProperty, g = e.toString, h = "Boolean Number String Function Array Date RegExp Object Error".split(" "), i = 0; i < h.length; i++) e["[object " + h[i] + "]"] = h[i].toLowerCase(); c.fn.init.prototype = c.fn, a.Velocity = { Utilities: c } } }(window), function (a) { "object" == typeof module && "object" == typeof module.exports ? module.exports = a() : "function" == typeof define && define.amd ? define(a) : a() }(function () {
    return function (a, b, c, d) {
        function e(a) { for (var b = -1, c = a ? a.length : 0, d = []; ++b < c;) { var e = a[b]; e && d.push(e) } return d } function f(a) { return p.isWrapped(a) ? a = [].slice.call(a) : p.isNode(a) && (a = [a]), a } function g(a) { var b = m.data(a, "velocity"); return null === b ? d : b } function h(a) { return function (b) { return Math.round(b * a) * (1 / a) } } function i(a, c, d, e) { function f(a, b) { return 1 - 3 * b + 3 * a } function g(a, b) { return 3 * b - 6 * a } function h(a) { return 3 * a } function i(a, b, c) { return ((f(b, c) * a + g(b, c)) * a + h(b)) * a } function j(a, b, c) { return 3 * f(b, c) * a * a + 2 * g(b, c) * a + h(b) } function k(b, c) { for (var e = 0; p > e; ++e) { var f = j(c, a, d); if (0 === f) return c; var g = i(c, a, d) - b; c -= g / f } return c } function l() { for (var b = 0; t > b; ++b) x[b] = i(b * u, a, d) } function m(b, c, e) { var f, g, h = 0; do g = c + (e - c) / 2, f = i(g, a, d) - b, f > 0 ? e = g : c = g; while (Math.abs(f) > r && ++h < s); return g } function n(b) { for (var c = 0, e = 1, f = t - 1; e != f && x[e] <= b; ++e) c += u; --e; var g = (b - x[e]) / (x[e + 1] - x[e]), h = c + g * u, i = j(h, a, d); return i >= q ? k(b, h) : 0 == i ? h : m(b, c, c + u) } function o() { y = !0, (a != c || d != e) && l() } var p = 4, q = .001, r = 1e-7, s = 10, t = 11, u = 1 / (t - 1), v = "Float32Array" in b; if (4 !== arguments.length) return !1; for (var w = 0; 4 > w; ++w) if ("number" != typeof arguments[w] || isNaN(arguments[w]) || !isFinite(arguments[w])) return !1; a = Math.min(a, 1), d = Math.min(d, 1), a = Math.max(a, 0), d = Math.max(d, 0); var x = v ? new Float32Array(t) : new Array(t), y = !1, z = function (b) { return y || o(), a === c && d === e ? b : 0 === b ? 0 : 1 === b ? 1 : i(n(b), c, e) }; z.getControlPoints = function () { return [{ x: a, y: c }, { x: d, y: e }] }; var A = "generateBezier(" + [a, c, d, e] + ")"; return z.toString = function () { return A }, z } function j(a, b) { var c = a; return p.isString(a) ? t.Easings[a] || (c = !1) : c = p.isArray(a) && 1 === a.length ? h.apply(null, a) : p.isArray(a) && 2 === a.length ? u.apply(null, a.concat([b])) : p.isArray(a) && 4 === a.length ? i.apply(null, a) : !1, c === !1 && (c = t.Easings[t.defaults.easing] ? t.defaults.easing : s), c } function k(a) { if (a) { var b = (new Date).getTime(), c = t.State.calls.length; c > 1e4 && (t.State.calls = e(t.State.calls)); for (var f = 0; c > f; f++) if (t.State.calls[f]) { var h = t.State.calls[f], i = h[0], j = h[2], n = h[3], o = !!n, q = null; n || (n = t.State.calls[f][3] = b - 16); for (var r = Math.min((b - n) / j.duration, 1), s = 0, u = i.length; u > s; s++) { var w = i[s], y = w.element; if (g(y)) { var z = !1; if (j.display !== d && null !== j.display && "none" !== j.display) { if ("flex" === j.display) { var A = ["-webkit-box", "-moz-box", "-ms-flexbox", "-webkit-flex"]; m.each(A, function (a, b) { v.setPropertyValue(y, "display", b) }) } v.setPropertyValue(y, "display", j.display) } j.visibility !== d && "hidden" !== j.visibility && v.setPropertyValue(y, "visibility", j.visibility); for (var B in w) if ("element" !== B) { var C, D = w[B], E = p.isString(D.easing) ? t.Easings[D.easing] : D.easing; if (1 === r) C = D.endValue; else { var F = D.endValue - D.startValue; if (C = D.startValue + F * E(r, j, F), !o && C === D.currentValue) continue } if (D.currentValue = C, "tween" === B) q = C; else { if (v.Hooks.registered[B]) { var G = v.Hooks.getRoot(B), H = g(y).rootPropertyValueCache[G]; H && (D.rootPropertyValue = H) } var I = v.setPropertyValue(y, B, D.currentValue + (0 === parseFloat(C) ? "" : D.unitType), D.rootPropertyValue, D.scrollData); v.Hooks.registered[B] && (g(y).rootPropertyValueCache[G] = v.Normalizations.registered[G] ? v.Normalizations.registered[G]("extract", null, I[1]) : I[1]), "transform" === I[0] && (z = !0) } } j.mobileHA && g(y).transformCache.translate3d === d && (g(y).transformCache.translate3d = "(0px, 0px, 0px)", z = !0), z && v.flushTransformCache(y) } } j.display !== d && "none" !== j.display && (t.State.calls[f][2].display = !1), j.visibility !== d && "hidden" !== j.visibility && (t.State.calls[f][2].visibility = !1), j.progress && j.progress.call(h[1], h[1], r, Math.max(0, n + j.duration - b), n, q), 1 === r && l(f) } } t.State.isTicking && x(k) } function l(a, b) { if (!t.State.calls[a]) return !1; for (var c = t.State.calls[a][0], e = t.State.calls[a][1], f = t.State.calls[a][2], h = t.State.calls[a][4], i = !1, j = 0, k = c.length; k > j; j++) { var l = c[j].element; if (b || f.loop || ("none" === f.display && v.setPropertyValue(l, "display", f.display), "hidden" === f.visibility && v.setPropertyValue(l, "visibility", f.visibility)), f.loop !== !0 && (m.queue(l)[1] === d || !/\.velocityQueueEntryFlag/i.test(m.queue(l)[1])) && g(l)) { g(l).isAnimating = !1, g(l).rootPropertyValueCache = {}; var n = !1; m.each(v.Lists.transforms3D, function (a, b) { var c = /^scale/.test(b) ? 1 : 0, e = g(l).transformCache[b]; g(l).transformCache[b] !== d && new RegExp("^\\(" + c + "[^.]").test(e) && (n = !0, delete g(l).transformCache[b]) }), f.mobileHA && (n = !0, delete g(l).transformCache.translate3d), n && v.flushTransformCache(l), v.Values.removeClass(l, "velocity-animating") } if (!b && f.complete && !f.loop && j === k - 1) try { f.complete.call(e, e) } catch (o) { setTimeout(function () { throw o }, 1) } h && f.loop !== !0 && h(e), g(l) && f.loop === !0 && !b && (m.each(g(l).tweensContainer, function (a, b) { /^rotate/.test(a) && 360 === parseFloat(b.endValue) && (b.endValue = 0, b.startValue = 360), /^backgroundPosition/.test(a) && 100 === parseFloat(b.endValue) && "%" === b.unitType && (b.endValue = 0, b.startValue = 100) }), t(l, "reverse", { loop: !0, delay: f.delay })), f.queue !== !1 && m.dequeue(l, f.queue) } t.State.calls[a] = !1; for (var p = 0, q = t.State.calls.length; q > p; p++) if (t.State.calls[p] !== !1) { i = !0; break } i === !1 && (t.State.isTicking = !1, delete t.State.calls, t.State.calls = []) } var m, n = function () { if (c.documentMode) return c.documentMode; for (var a = 7; a > 4; a--) { var b = c.createElement("div"); if (b.innerHTML = "<!--[if IE " + a + "]><span></span><![endif]-->", b.getElementsByTagName("span").length) return b = null, a } return d }(), o = function () { var a = 0; return b.webkitRequestAnimationFrame || b.mozRequestAnimationFrame || function (b) { var c, d = (new Date).getTime(); return c = Math.max(0, 16 - (d - a)), a = d + c, setTimeout(function () { b(d + c) }, c) } }(), p = { isString: function (a) { return "string" == typeof a }, isArray: Array.isArray || function (a) { return "[object Array]" === Object.prototype.toString.call(a) }, isFunction: function (a) { return "[object Function]" === Object.prototype.toString.call(a) }, isNode: function (a) { return a && a.nodeType }, isNodeList: function (a) { return "object" == typeof a && /^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(a)) && a.length !== d && (0 === a.length || "object" == typeof a[0] && a[0].nodeType > 0) }, isWrapped: function (a) { return a && (a.jquery || b.Zepto && b.Zepto.zepto.isZ(a)) }, isSVG: function (a) { return b.SVGElement && a instanceof b.SVGElement }, isEmptyObject: function (a) { for (var b in a) return !1; return !0 } }, q = !1; if (a.fn && a.fn.jquery ? (m = a, q = !0) : m = b.Velocity.Utilities, 8 >= n && !q) throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity."); if (7 >= n) return void (jQuery.fn.velocity = jQuery.fn.animate); var r = 400, s = "swing", t = { State: { isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent), isAndroid: /Android/i.test(navigator.userAgent), isGingerbread: /Android 2\.3\.[3-7]/i.test(navigator.userAgent), isChrome: b.chrome, isFirefox: /Firefox/i.test(navigator.userAgent), prefixElement: c.createElement("div"), prefixMatches: {}, scrollAnchor: null, scrollPropertyLeft: null, scrollPropertyTop: null, isTicking: !1, calls: [] }, CSS: {}, Utilities: m, Redirects: {}, Easings: {}, Promise: b.Promise, defaults: { queue: "", duration: r, easing: s, begin: d, complete: d, progress: d, display: d, visibility: d, loop: !1, delay: !1, mobileHA: !0, _cacheValues: !0 }, init: function (a) { m.data(a, "velocity", { isSVG: p.isSVG(a), isAnimating: !1, computedStyle: null, tweensContainer: null, rootPropertyValueCache: {}, transformCache: {} }) }, hook: null, mock: !1, version: { major: 1, minor: 2, patch: 2 }, debug: !1 }; b.pageYOffset !== d ? (t.State.scrollAnchor = b, t.State.scrollPropertyLeft = "pageXOffset", t.State.scrollPropertyTop = "pageYOffset") : (t.State.scrollAnchor = c.documentElement || c.body.parentNode || c.body, t.State.scrollPropertyLeft = "scrollLeft", t.State.scrollPropertyTop = "scrollTop"); var u = function () { function a(a) { return -a.tension * a.x - a.friction * a.v } function b(b, c, d) { var e = { x: b.x + d.dx * c, v: b.v + d.dv * c, tension: b.tension, friction: b.friction }; return { dx: e.v, dv: a(e) } } function c(c, d) { var e = { dx: c.v, dv: a(c) }, f = b(c, .5 * d, e), g = b(c, .5 * d, f), h = b(c, d, g), i = 1 / 6 * (e.dx + 2 * (f.dx + g.dx) + h.dx), j = 1 / 6 * (e.dv + 2 * (f.dv + g.dv) + h.dv); return c.x = c.x + i * d, c.v = c.v + j * d, c } return function d(a, b, e) { var f, g, h, i = { x: -1, v: 0, tension: null, friction: null }, j = [0], k = 0, l = 1e-4, m = .016; for (a = parseFloat(a) || 500, b = parseFloat(b) || 20, e = e || null, i.tension = a, i.friction = b, f = null !== e, f ? (k = d(a, b), g = k / e * m) : g = m; ;) if (h = c(h || i, g), j.push(1 + h.x), k += 16, !(Math.abs(h.x) > l && Math.abs(h.v) > l)) break; return f ? function (a) { return j[a * (j.length - 1) | 0] } : k } }(); t.Easings = { linear: function (a) { return a }, swing: function (a) { return .5 - Math.cos(a * Math.PI) / 2 }, spring: function (a) { return 1 - Math.cos(4.5 * a * Math.PI) * Math.exp(6 * -a) } }, m.each([["ease", [.25, .1, .25, 1]], ["ease-in", [.42, 0, 1, 1]], ["ease-out", [0, 0, .58, 1]], ["ease-in-out", [.42, 0, .58, 1]], ["easeInSine", [.47, 0, .745, .715]], ["easeOutSine", [.39, .575, .565, 1]], ["easeInOutSine", [.445, .05, .55, .95]], ["easeInQuad", [.55, .085, .68, .53]], ["easeOutQuad", [.25, .46, .45, .94]], ["easeInOutQuad", [.455, .03, .515, .955]], ["easeInCubic", [.55, .055, .675, .19]], ["easeOutCubic", [.215, .61, .355, 1]], ["easeInOutCubic", [.645, .045, .355, 1]], ["easeInQuart", [.895, .03, .685, .22]], ["easeOutQuart", [.165, .84, .44, 1]], ["easeInOutQuart", [.77, 0, .175, 1]], ["easeInQuint", [.755, .05, .855, .06]], ["easeOutQuint", [.23, 1, .32, 1]], ["easeInOutQuint", [.86, 0, .07, 1]], ["easeInExpo", [.95, .05, .795, .035]], ["easeOutExpo", [.19, 1, .22, 1]], ["easeInOutExpo", [1, 0, 0, 1]], ["easeInCirc", [.6, .04, .98, .335]], ["easeOutCirc", [.075, .82, .165, 1]], ["easeInOutCirc", [.785, .135, .15, .86]]], function (a, b) { t.Easings[b[0]] = i.apply(null, b[1]) }); var v = t.CSS = { RegEx: { isHex: /^#([A-f\d]{3}){1,2}$/i, valueUnwrap: /^[A-z]+\((.*)\)$/i, wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/, valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi }, Lists: { colors: ["fill", "stroke", "stopColor", "color", "backgroundColor", "borderColor", "borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor", "outlineColor"], transformsBase: ["translateX", "translateY", "scale", "scaleX", "scaleY", "skewX", "skewY", "rotateZ"], transforms3D: ["transformPerspective", "translateZ", "scaleZ", "rotateX", "rotateY"] }, Hooks: { templates: { textShadow: ["Color X Y Blur", "black 0px 0px 0px"], boxShadow: ["Color X Y Blur Spread", "black 0px 0px 0px 0px"], clip: ["Top Right Bottom Left", "0px 0px 0px 0px"], backgroundPosition: ["X Y", "0% 0%"], transformOrigin: ["X Y Z", "50% 50% 0px"], perspectiveOrigin: ["X Y", "50% 50%"] }, registered: {}, register: function () { for (var a = 0; a < v.Lists.colors.length; a++) { var b = "color" === v.Lists.colors[a] ? "0 0 0 1" : "255 255 255 1"; v.Hooks.templates[v.Lists.colors[a]] = ["Red Green Blue Alpha", b] } var c, d, e; if (n) for (c in v.Hooks.templates) { d = v.Hooks.templates[c], e = d[0].split(" "); var f = d[1].match(v.RegEx.valueSplit); "Color" === e[0] && (e.push(e.shift()), f.push(f.shift()), v.Hooks.templates[c] = [e.join(" "), f.join(" ")]) } for (c in v.Hooks.templates) { d = v.Hooks.templates[c], e = d[0].split(" "); for (var a in e) { var g = c + e[a], h = a; v.Hooks.registered[g] = [c, h] } } }, getRoot: function (a) { var b = v.Hooks.registered[a]; return b ? b[0] : a }, cleanRootPropertyValue: function (a, b) { return v.RegEx.valueUnwrap.test(b) && (b = b.match(v.RegEx.valueUnwrap)[1]), v.Values.isCSSNullValue(b) && (b = v.Hooks.templates[a][1]), b }, extractValue: function (a, b) { var c = v.Hooks.registered[a]; if (c) { var d = c[0], e = c[1]; return b = v.Hooks.cleanRootPropertyValue(d, b), b.toString().match(v.RegEx.valueSplit)[e] } return b }, injectValue: function (a, b, c) { var d = v.Hooks.registered[a]; if (d) { var e, f, g = d[0], h = d[1]; return c = v.Hooks.cleanRootPropertyValue(g, c), e = c.toString().match(v.RegEx.valueSplit), e[h] = b, f = e.join(" ") } return c } }, Normalizations: { registered: { clip: function (a, b, c) { switch (a) { case "name": return "clip"; case "extract": var d; return v.RegEx.wrappedValueAlreadyExtracted.test(c) ? d = c : (d = c.toString().match(v.RegEx.valueUnwrap), d = d ? d[1].replace(/,(\s+)?/g, " ") : c), d; case "inject": return "rect(" + c + ")" } }, blur: function (a, b, c) { switch (a) { case "name": return t.State.isFirefox ? "filter" : "-webkit-filter"; case "extract": var d = parseFloat(c); if (!d && 0 !== d) { var e = c.toString().match(/blur\(([0-9]+[A-z]+)\)/i); d = e ? e[1] : 0 } return d; case "inject": return parseFloat(c) ? "blur(" + c + ")" : "none" } }, opacity: function (a, b, c) { if (8 >= n) switch (a) { case "name": return "filter"; case "extract": var d = c.toString().match(/alpha\(opacity=(.*)\)/i); return c = d ? d[1] / 100 : 1; case "inject": return b.style.zoom = 1, parseFloat(c) >= 1 ? "" : "alpha(opacity=" + parseInt(100 * parseFloat(c), 10) + ")" } else switch (a) { case "name": return "opacity"; case "extract": return c; case "inject": return c } } }, register: function () { 9 >= n || t.State.isGingerbread || (v.Lists.transformsBase = v.Lists.transformsBase.concat(v.Lists.transforms3D)); for (var a = 0; a < v.Lists.transformsBase.length; a++) !function () { var b = v.Lists.transformsBase[a]; v.Normalizations.registered[b] = function (a, c, e) { switch (a) { case "name": return "transform"; case "extract": return g(c) === d || g(c).transformCache[b] === d ? /^scale/i.test(b) ? 1 : 0 : g(c).transformCache[b].replace(/[()]/g, ""); case "inject": var f = !1; switch (b.substr(0, b.length - 1)) { case "translate": f = !/(%|px|em|rem|vw|vh|\d)$/i.test(e); break; case "scal": case "scale": t.State.isAndroid && g(c).transformCache[b] === d && 1 > e && (e = 1), f = !/(\d)$/i.test(e); break; case "skew": f = !/(deg|\d)$/i.test(e); break; case "rotate": f = !/(deg|\d)$/i.test(e) } return f || (g(c).transformCache[b] = "(" + e + ")"), g(c).transformCache[b] } } }(); for (var a = 0; a < v.Lists.colors.length; a++) !function () { var b = v.Lists.colors[a]; v.Normalizations.registered[b] = function (a, c, e) { switch (a) { case "name": return b; case "extract": var f; if (v.RegEx.wrappedValueAlreadyExtracted.test(e)) f = e; else { var g, h = { black: "rgb(0, 0, 0)", blue: "rgb(0, 0, 255)", gray: "rgb(128, 128, 128)", green: "rgb(0, 128, 0)", red: "rgb(255, 0, 0)", white: "rgb(255, 255, 255)" }; /^[A-z]+$/i.test(e) ? g = h[e] !== d ? h[e] : h.black : v.RegEx.isHex.test(e) ? g = "rgb(" + v.Values.hexToRgb(e).join(" ") + ")" : /^rgba?\(/i.test(e) || (g = h.black), f = (g || e).toString().match(v.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g, " ") } return 8 >= n || 3 !== f.split(" ").length || (f += " 1"), f; case "inject": return 8 >= n ? 4 === e.split(" ").length && (e = e.split(/\s+/).slice(0, 3).join(" ")) : 3 === e.split(" ").length && (e += " 1"), (8 >= n ? "rgb" : "rgba") + "(" + e.replace(/\s+/g, ",").replace(/\.(\d)+(?=,)/g, "") + ")" } } }() } }, Names: { camelCase: function (a) { return a.replace(/-(\w)/g, function (a, b) { return b.toUpperCase() }) }, SVGAttribute: function (a) { var b = "width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2"; return (n || t.State.isAndroid && !t.State.isChrome) && (b += "|transform"), new RegExp("^(" + b + ")$", "i").test(a) }, prefixCheck: function (a) { if (t.State.prefixMatches[a]) return [t.State.prefixMatches[a], !0]; for (var b = ["", "Webkit", "Moz", "ms", "O"], c = 0, d = b.length; d > c; c++) { var e; if (e = 0 === c ? a : b[c] + a.replace(/^\w/, function (a) { return a.toUpperCase() }), p.isString(t.State.prefixElement.style[e])) return t.State.prefixMatches[a] = e, [e, !0] } return [a, !1] } }, Values: { hexToRgb: function (a) { var b, c = /^#?([a-f\d])([a-f\d])([a-f\d])$/i, d = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i; return a = a.replace(c, function (a, b, c, d) { return b + b + c + c + d + d }), b = d.exec(a), b ? [parseInt(b[1], 16), parseInt(b[2], 16), parseInt(b[3], 16)] : [0, 0, 0] }, isCSSNullValue: function (a) { return 0 == a || /^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(a) }, getUnitType: function (a) { return /^(rotate|skew)/i.test(a) ? "deg" : /(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(a) ? "" : "px" }, getDisplayType: function (a) { var b = a && a.tagName.toString().toLowerCase(); return /^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(b) ? "inline" : /^(li)$/i.test(b) ? "list-item" : /^(tr)$/i.test(b) ? "table-row" : /^(table)$/i.test(b) ? "table" : /^(tbody)$/i.test(b) ? "table-row-group" : "block" }, addClass: function (a, b) { a.classList ? a.classList.add(b) : a.className += (a.className.length ? " " : "") + b }, removeClass: function (a, b) { a.classList ? a.classList.remove(b) : a.className = a.className.toString().replace(new RegExp("(^|\\s)" + b.split(" ").join("|") + "(\\s|$)", "gi"), " ") } }, getPropertyValue: function (a, c, e, f) { function h(a, c) { function e() { j && v.setPropertyValue(a, "display", "none") } var i = 0; if (8 >= n) i = m.css(a, c); else { var j = !1; if (/^(width|height)$/.test(c) && 0 === v.getPropertyValue(a, "display") && (j = !0, v.setPropertyValue(a, "display", v.Values.getDisplayType(a))), !f) { if ("height" === c && "border-box" !== v.getPropertyValue(a, "boxSizing").toString().toLowerCase()) { var k = a.offsetHeight - (parseFloat(v.getPropertyValue(a, "borderTopWidth")) || 0) - (parseFloat(v.getPropertyValue(a, "borderBottomWidth")) || 0) - (parseFloat(v.getPropertyValue(a, "paddingTop")) || 0) - (parseFloat(v.getPropertyValue(a, "paddingBottom")) || 0); return e(), k } if ("width" === c && "border-box" !== v.getPropertyValue(a, "boxSizing").toString().toLowerCase()) { var l = a.offsetWidth - (parseFloat(v.getPropertyValue(a, "borderLeftWidth")) || 0) - (parseFloat(v.getPropertyValue(a, "borderRightWidth")) || 0) - (parseFloat(v.getPropertyValue(a, "paddingLeft")) || 0) - (parseFloat(v.getPropertyValue(a, "paddingRight")) || 0); return e(), l } } var o; o = g(a) === d ? b.getComputedStyle(a, null) : g(a).computedStyle ? g(a).computedStyle : g(a).computedStyle = b.getComputedStyle(a, null), "borderColor" === c && (c = "borderTopColor"), i = 9 === n && "filter" === c ? o.getPropertyValue(c) : o[c], ("" === i || null === i) && (i = a.style[c]), e() } if ("auto" === i && /^(top|right|bottom|left)$/i.test(c)) { var p = h(a, "position"); ("fixed" === p || "absolute" === p && /top|left/i.test(c)) && (i = m(a).position()[c] + "px") } return i } var i; if (v.Hooks.registered[c]) { var j = c, k = v.Hooks.getRoot(j); e === d && (e = v.getPropertyValue(a, v.Names.prefixCheck(k)[0])), v.Normalizations.registered[k] && (e = v.Normalizations.registered[k]("extract", a, e)), i = v.Hooks.extractValue(j, e) } else if (v.Normalizations.registered[c]) { var l, o; l = v.Normalizations.registered[c]("name", a), "transform" !== l && (o = h(a, v.Names.prefixCheck(l)[0]), v.Values.isCSSNullValue(o) && v.Hooks.templates[c] && (o = v.Hooks.templates[c][1])), i = v.Normalizations.registered[c]("extract", a, o) } if (!/^[\d-]/.test(i)) if (g(a) && g(a).isSVG && v.Names.SVGAttribute(c)) if (/^(height|width)$/i.test(c)) try { i = a.getBBox()[c] } catch (p) { i = 0 } else i = a.getAttribute(c); else i = h(a, v.Names.prefixCheck(c)[0]); return v.Values.isCSSNullValue(i) && (i = 0), t.debug >= 2 && console.log("Get " + c + ": " + i), i }, setPropertyValue: function (a, c, d, e, f) { var h = c; if ("scroll" === c) f.container ? f.container["scroll" + f.direction] = d : "Left" === f.direction ? b.scrollTo(d, f.alternateValue) : b.scrollTo(f.alternateValue, d); else if (v.Normalizations.registered[c] && "transform" === v.Normalizations.registered[c]("name", a)) v.Normalizations.registered[c]("inject", a, d), h = "transform", d = g(a).transformCache[c]; else { if (v.Hooks.registered[c]) { var i = c, j = v.Hooks.getRoot(c); e = e || v.getPropertyValue(a, j), d = v.Hooks.injectValue(i, d, e), c = j } if (v.Normalizations.registered[c] && (d = v.Normalizations.registered[c]("inject", a, d), c = v.Normalizations.registered[c]("name", a)), h = v.Names.prefixCheck(c)[0], 8 >= n) try { a.style[h] = d } catch (k) { t.debug && console.log("Browser does not support [" + d + "] for [" + h + "]") } else g(a) && g(a).isSVG && v.Names.SVGAttribute(c) ? a.setAttribute(c, d) : a.style[h] = d; t.debug >= 2 && console.log("Set " + c + " (" + h + "): " + d) } return [h, d] }, flushTransformCache: function (a) { function b(b) { return parseFloat(v.getPropertyValue(a, b)) } var c = ""; if ((n || t.State.isAndroid && !t.State.isChrome) && g(a).isSVG) { var d = { translate: [b("translateX"), b("translateY")], skewX: [b("skewX")], skewY: [b("skewY")], scale: 1 !== b("scale") ? [b("scale"), b("scale")] : [b("scaleX"), b("scaleY")], rotate: [b("rotateZ"), 0, 0] }; m.each(g(a).transformCache, function (a) { /^translate/i.test(a) ? a = "translate" : /^scale/i.test(a) ? a = "scale" : /^rotate/i.test(a) && (a = "rotate"), d[a] && (c += a + "(" + d[a].join(" ") + ") ", delete d[a]) }) } else { var e, f; m.each(g(a).transformCache, function (b) { return e = g(a).transformCache[b], "transformPerspective" === b ? (f = e, !0) : (9 === n && "rotateZ" === b && (b = "rotate"), void (c += b + e + " ")) }), f && (c = "perspective" + f + " " + c) } v.setPropertyValue(a, "transform", c) } }; v.Hooks.register(), v.Normalizations.register(), t.hook = function (a, b, c) { var e = d; return a = f(a), m.each(a, function (a, f) { if (g(f) === d && t.init(f), c === d) e === d && (e = t.CSS.getPropertyValue(f, b)); else { var h = t.CSS.setPropertyValue(f, b, c); "transform" === h[0] && t.CSS.flushTransformCache(f), e = h } }), e }; var w = function () {
            function a() { return h ? B.promise || null : i } function e() { function a() { function a(a, b) { var c = d, e = d, g = d; return p.isArray(a) ? (c = a[0], !p.isArray(a[1]) && /^[\d-]/.test(a[1]) || p.isFunction(a[1]) || v.RegEx.isHex.test(a[1]) ? g = a[1] : (p.isString(a[1]) && !v.RegEx.isHex.test(a[1]) || p.isArray(a[1])) && (e = b ? a[1] : j(a[1], h.duration), a[2] !== d && (g = a[2]))) : c = a, b || (e = e || h.easing), p.isFunction(c) && (c = c.call(f, y, x)), p.isFunction(g) && (g = g.call(f, y, x)), [c || 0, e, g] } function l(a, b) { var c, d; return d = (b || "0").toString().toLowerCase().replace(/[%A-z]+$/, function (a) { return c = a, "" }), c || (c = v.Values.getUnitType(a)), [d, c] } function n() { var a = { myParent: f.parentNode || c.body, position: v.getPropertyValue(f, "position"), fontSize: v.getPropertyValue(f, "fontSize") }, d = a.position === I.lastPosition && a.myParent === I.lastParent, e = a.fontSize === I.lastFontSize; I.lastParent = a.myParent, I.lastPosition = a.position, I.lastFontSize = a.fontSize; var h = 100, i = {}; if (e && d) i.emToPx = I.lastEmToPx, i.percentToPxWidth = I.lastPercentToPxWidth, i.percentToPxHeight = I.lastPercentToPxHeight; else { var j = g(f).isSVG ? c.createElementNS("http://www.w3.org/2000/svg", "rect") : c.createElement("div"); t.init(j), a.myParent.appendChild(j), m.each(["overflow", "overflowX", "overflowY"], function (a, b) { t.CSS.setPropertyValue(j, b, "hidden") }), t.CSS.setPropertyValue(j, "position", a.position), t.CSS.setPropertyValue(j, "fontSize", a.fontSize), t.CSS.setPropertyValue(j, "boxSizing", "content-box"), m.each(["minWidth", "maxWidth", "width", "minHeight", "maxHeight", "height"], function (a, b) { t.CSS.setPropertyValue(j, b, h + "%") }), t.CSS.setPropertyValue(j, "paddingLeft", h + "em"), i.percentToPxWidth = I.lastPercentToPxWidth = (parseFloat(v.getPropertyValue(j, "width", null, !0)) || 1) / h, i.percentToPxHeight = I.lastPercentToPxHeight = (parseFloat(v.getPropertyValue(j, "height", null, !0)) || 1) / h, i.emToPx = I.lastEmToPx = (parseFloat(v.getPropertyValue(j, "paddingLeft")) || 1) / h, a.myParent.removeChild(j) } return null === I.remToPx && (I.remToPx = parseFloat(v.getPropertyValue(c.body, "fontSize")) || 16), null === I.vwToPx && (I.vwToPx = parseFloat(b.innerWidth) / 100, I.vhToPx = parseFloat(b.innerHeight) / 100), i.remToPx = I.remToPx, i.vwToPx = I.vwToPx, i.vhToPx = I.vhToPx, t.debug >= 1 && console.log("Unit ratios: " + JSON.stringify(i), f), i } if (h.begin && 0 === y) try { h.begin.call(o, o) } catch (r) { setTimeout(function () { throw r }, 1) } if ("scroll" === C) { var u, w, z, A = /^x$/i.test(h.axis) ? "Left" : "Top", D = parseFloat(h.offset) || 0; h.container ? p.isWrapped(h.container) || p.isNode(h.container) ? (h.container = h.container[0] || h.container, u = h.container["scroll" + A], z = u + m(f).position()[A.toLowerCase()] + D) : h.container = null : (u = t.State.scrollAnchor[t.State["scrollProperty" + A]], w = t.State.scrollAnchor[t.State["scrollProperty" + ("Left" === A ? "Top" : "Left")]], z = m(f).offset()[A.toLowerCase()] + D), i = { scroll: { rootPropertyValue: !1, startValue: u, currentValue: u, endValue: z, unitType: "", easing: h.easing, scrollData: { container: h.container, direction: A, alternateValue: w } }, element: f }, t.debug && console.log("tweensContainer (scroll): ", i.scroll, f) } else if ("reverse" === C) { if (!g(f).tweensContainer) return void m.dequeue(f, h.queue); "none" === g(f).opts.display && (g(f).opts.display = "auto"), "hidden" === g(f).opts.visibility && (g(f).opts.visibility = "visible"), g(f).opts.loop = !1, g(f).opts.begin = null, g(f).opts.complete = null, s.easing || delete h.easing, s.duration || delete h.duration, h = m.extend({}, g(f).opts, h); var E = m.extend(!0, {}, g(f).tweensContainer); for (var F in E) if ("element" !== F) { var G = E[F].startValue; E[F].startValue = E[F].currentValue = E[F].endValue, E[F].endValue = G, p.isEmptyObject(s) || (E[F].easing = h.easing), t.debug && console.log("reverse tweensContainer (" + F + "): " + JSON.stringify(E[F]), f) } i = E } else if ("start" === C) { var E; g(f).tweensContainer && g(f).isAnimating === !0 && (E = g(f).tweensContainer), m.each(q, function (b, c) { if (RegExp("^" + v.Lists.colors.join("$|^") + "$").test(b)) { var e = a(c, !0), f = e[0], g = e[1], h = e[2]; if (v.RegEx.isHex.test(f)) { for (var i = ["Red", "Green", "Blue"], j = v.Values.hexToRgb(f), k = h ? v.Values.hexToRgb(h) : d, l = 0; l < i.length; l++) { var m = [j[l]]; g && m.push(g), k !== d && m.push(k[l]), q[b + i[l]] = m } delete q[b] } } }); for (var H in q) { var K = a(q[H]), L = K[0], M = K[1], N = K[2]; H = v.Names.camelCase(H); var O = v.Hooks.getRoot(H), P = !1; if (g(f).isSVG || "tween" === O || v.Names.prefixCheck(O)[1] !== !1 || v.Normalizations.registered[O] !== d) { (h.display !== d && null !== h.display && "none" !== h.display || h.visibility !== d && "hidden" !== h.visibility) && /opacity|filter/.test(H) && !N && 0 !== L && (N = 0), h._cacheValues && E && E[H] ? (N === d && (N = E[H].endValue + E[H].unitType), P = g(f).rootPropertyValueCache[O]) : v.Hooks.registered[H] ? N === d ? (P = v.getPropertyValue(f, O), N = v.getPropertyValue(f, H, P)) : P = v.Hooks.templates[O][1] : N === d && (N = v.getPropertyValue(f, H)); var Q, R, S, T = !1; if (Q = l(H, N), N = Q[0], S = Q[1], Q = l(H, L), L = Q[0].replace(/^([+-\/*])=/, function (a, b) { return T = b, "" }), R = Q[1], N = parseFloat(N) || 0, L = parseFloat(L) || 0, "%" === R && (/^(fontSize|lineHeight)$/.test(H) ? (L /= 100, R = "em") : /^scale/.test(H) ? (L /= 100, R = "") : /(Red|Green|Blue)$/i.test(H) && (L = L / 100 * 255, R = "")), /[\/*]/.test(T)) R = S; else if (S !== R && 0 !== N) if (0 === L) R = S; else { e = e || n(); var U = /margin|padding|left|right|width|text|word|letter/i.test(H) || /X$/.test(H) || "x" === H ? "x" : "y"; switch (S) { case "%": N *= "x" === U ? e.percentToPxWidth : e.percentToPxHeight; break; case "px": break; default: N *= e[S + "ToPx"] } switch (R) { case "%": N *= 1 / ("x" === U ? e.percentToPxWidth : e.percentToPxHeight); break; case "px": break; default: N *= 1 / e[R + "ToPx"] } } switch (T) { case "+": L = N + L; break; case "-": L = N - L; break; case "*": L = N * L; break; case "/": L = N / L } i[H] = { rootPropertyValue: P, startValue: N, currentValue: N, endValue: L, unitType: R, easing: M }, t.debug && console.log("tweensContainer (" + H + "): " + JSON.stringify(i[H]), f) } else t.debug && console.log("Skipping [" + O + "] due to a lack of browser support.") } i.element = f } i.element && (v.Values.addClass(f, "velocity-animating"), J.push(i), "" === h.queue && (g(f).tweensContainer = i, g(f).opts = h), g(f).isAnimating = !0, y === x - 1 ? (t.State.calls.push([J, o, h, null, B.resolver]), t.State.isTicking === !1 && (t.State.isTicking = !0, k())) : y++) } var e, f = this, h = m.extend({}, t.defaults, s), i = {}; switch (g(f) === d && t.init(f), parseFloat(h.delay) && h.queue !== !1 && m.queue(f, h.queue, function (a) { t.velocityQueueEntryFlag = !0, g(f).delayTimer = { setTimeout: setTimeout(a, parseFloat(h.delay)), next: a } }), h.duration.toString().toLowerCase()) { case "fast": h.duration = 200; break; case "normal": h.duration = r; break; case "slow": h.duration = 600; break; default: h.duration = parseFloat(h.duration) || 1 } t.mock !== !1 && (t.mock === !0 ? h.duration = h.delay = 1 : (h.duration *= parseFloat(t.mock) || 1, h.delay *= parseFloat(t.mock) || 1)), h.easing = j(h.easing, h.duration), h.begin && !p.isFunction(h.begin) && (h.begin = null), h.progress && !p.isFunction(h.progress) && (h.progress = null), h.complete && !p.isFunction(h.complete) && (h.complete = null), h.display !== d && null !== h.display && (h.display = h.display.toString().toLowerCase(), "auto" === h.display && (h.display = t.CSS.Values.getDisplayType(f))), h.visibility !== d && null !== h.visibility && (h.visibility = h.visibility.toString().toLowerCase()), h.mobileHA = h.mobileHA && t.State.isMobile && !t.State.isGingerbread, h.queue === !1 ? h.delay ? setTimeout(a, h.delay) : a() : m.queue(f, h.queue, function (b, c) { return c === !0 ? (B.promise && B.resolver(o), !0) : (t.velocityQueueEntryFlag = !0, void a(b)) }), "" !== h.queue && "fx" !== h.queue || "inprogress" === m.queue(f)[0] || m.dequeue(f) } var h, i, n, o, q, s, u = arguments[0] && (arguments[0].p || m.isPlainObject(arguments[0].properties) && !arguments[0].properties.names || p.isString(arguments[0].properties)); if (p.isWrapped(this) ? (h = !1, n = 0, o = this, i = this) : (h = !0, n = 1, o = u ? arguments[0].elements || arguments[0].e : arguments[0]), o = f(o)) {
                u ? (q = arguments[0].properties || arguments[0].p, s = arguments[0].options || arguments[0].o) : (q = arguments[n], s = arguments[n + 1]); var x = o.length, y = 0; if (!/^(stop|finish|finishAll)$/i.test(q) && !m.isPlainObject(s)) { var z = n + 1; s = {}; for (var A = z; A < arguments.length; A++) p.isArray(arguments[A]) || !/^(fast|normal|slow)$/i.test(arguments[A]) && !/^\d/.test(arguments[A]) ? p.isString(arguments[A]) || p.isArray(arguments[A]) ? s.easing = arguments[A] : p.isFunction(arguments[A]) && (s.complete = arguments[A]) : s.duration = arguments[A] } var B = { promise: null, resolver: null, rejecter: null }; h && t.Promise && (B.promise = new t.Promise(function (a, b) { B.resolver = a, B.rejecter = b })); var C; switch (q) {
                    case "scroll": C = "scroll"; break; case "reverse": C = "reverse"; break; case "finish": case "finishAll": case "stop": m.each(o, function (a, b) { g(b) && g(b).delayTimer && (clearTimeout(g(b).delayTimer.setTimeout), g(b).delayTimer.next && g(b).delayTimer.next(), delete g(b).delayTimer), "finishAll" !== q || s !== !0 && !p.isString(s) || (m.each(m.queue(b, p.isString(s) ? s : ""), function (a, b) { p.isFunction(b) && b() }), m.queue(b, p.isString(s) ? s : "", [])) }); var D = []; return m.each(t.State.calls, function (a, b) {
                        b && m.each(b[1], function (c, e) {
                            var f = s === d ? "" : s; return f === !0 || b[2].queue === f || s === d && b[2].queue === !1 ? void m.each(o, function (c, d) {
                                d === e && ((s === !0 || p.isString(s)) && (m.each(m.queue(d, p.isString(s) ? s : ""), function (a, b) {
                                    p.isFunction(b) && b(null, !0)
                                }), m.queue(d, p.isString(s) ? s : "", [])), "stop" === q ? (g(d) && g(d).tweensContainer && f !== !1 && m.each(g(d).tweensContainer, function (a, b) { b.endValue = b.currentValue }), D.push(a)) : ("finish" === q || "finishAll" === q) && (b[2].duration = 1))
                            }) : !0
                        })
                    }), "stop" === q && (m.each(D, function (a, b) { l(b, !0) }), B.promise && B.resolver(o)), a(); default: if (!m.isPlainObject(q) || p.isEmptyObject(q)) { if (p.isString(q) && t.Redirects[q]) { var E = m.extend({}, s), F = E.duration, G = E.delay || 0; return E.backwards === !0 && (o = m.extend(!0, [], o).reverse()), m.each(o, function (a, b) { parseFloat(E.stagger) ? E.delay = G + parseFloat(E.stagger) * a : p.isFunction(E.stagger) && (E.delay = G + E.stagger.call(b, a, x)), E.drag && (E.duration = parseFloat(F) || (/^(callout|transition)/.test(q) ? 1e3 : r), E.duration = Math.max(E.duration * (E.backwards ? 1 - a / x : (a + 1) / x), .75 * E.duration, 200)), t.Redirects[q].call(b, b, E || {}, a, x, o, B.promise ? B : d) }), a() } var H = "Velocity: First argument (" + q + ") was not a property map, a known action, or a registered redirect. Aborting."; return B.promise ? B.rejecter(new Error(H)) : console.log(H), a() } C = "start"
                } var I = { lastParent: null, lastPosition: null, lastFontSize: null, lastPercentToPxWidth: null, lastPercentToPxHeight: null, lastEmToPx: null, remToPx: null, vwToPx: null, vhToPx: null }, J = []; m.each(o, function (a, b) { p.isNode(b) && e.call(b) }); var K, E = m.extend({}, t.defaults, s); if (E.loop = parseInt(E.loop), K = 2 * E.loop - 1, E.loop) for (var L = 0; K > L; L++) { var M = { delay: E.delay, progress: E.progress }; L === K - 1 && (M.display = E.display, M.visibility = E.visibility, M.complete = E.complete), w(o, "reverse", M) } return a()
            }
        }; t = m.extend(w, t), t.animate = w; var x = b.requestAnimationFrame || o; return t.State.isMobile || c.hidden === d || c.addEventListener("visibilitychange", function () { c.hidden ? (x = function (a) { return setTimeout(function () { a(!0) }, 16) }, k()) : x = b.requestAnimationFrame || o }), a.Velocity = t, a !== b && (a.fn.velocity = w, a.fn.velocity.defaults = t.defaults), m.each(["Down", "Up"], function (a, b) { t.Redirects["slide" + b] = function (a, c, e, f, g, h) { var i = m.extend({}, c), j = i.begin, k = i.complete, l = { height: "", marginTop: "", marginBottom: "", paddingTop: "", paddingBottom: "" }, n = {}; i.display === d && (i.display = "Down" === b ? "inline" === t.CSS.Values.getDisplayType(a) ? "inline-block" : "block" : "none"), i.begin = function () { j && j.call(g, g); for (var c in l) { n[c] = a.style[c]; var d = t.CSS.getPropertyValue(a, c); l[c] = "Down" === b ? [d, 0] : [0, d] } n.overflow = a.style.overflow, a.style.overflow = "hidden" }, i.complete = function () { for (var b in n) a.style[b] = n[b]; k && k.call(g, g), h && h.resolver(g) }, t(a, l, i) } }), m.each(["In", "Out"], function (a, b) { t.Redirects["fade" + b] = function (a, c, e, f, g, h) { var i = m.extend({}, c), j = { opacity: "In" === b ? 1 : 0 }, k = i.complete; i.complete = e !== f - 1 ? i.begin = null : function () { k && k.call(g, g), h && h.resolver(g) }, i.display === d && (i.display = "In" === b ? "auto" : "none"), t(this, j, i) } }), t
    }(window.jQuery || window.Zepto || window, window, document)
});;
/*
Mustache helper
*/

var MustacheHelper = {
    getTemplate: function (url) {
        var template = '';
        jQuery.ajax({
            url: url,
            success: function (html) {
                template = html;
            },
            async: false
        });

        return template;
    },
    render: function (template, view) {
        view.defaultOfferCtaText = window.defaultOfferCtaText
        return Mustache.render(template, view);
    }
};

function getCommonQsSplitter()
{
    return ';';
}

function doCommonWorkShopRedirect(linkClicked)
{
    var name = linkClicked.getAttribute('attr-data-name');
    dataLayer.push({
        'event': 'Popup kontakt',
        'shop': name,
        'leadType': 'prisförslag'
    });

    var servicesSelect = document.getElementById('service-selector');
    var querys = new String('');
    if (servicesSelect.selectedIndex >= 0) {
        for (var i = 0; i < servicesSelect.length; i++) {
            if (servicesSelect.options[i].selected)
                querys += (querys.length > 0 ? getCommonQsSplitter() : '&service=') + servicesSelect.options[i].value;
        }

        location.href = linkClicked.href + querys;
        return false;
    }

    checkCommonTarget(linkClicked);

    var offerApp = document.getElementById('app-offer-v3');

    if (offerApp) {
        window.workshopId = linkClicked.getAttribute('data-id');
        if ($('#find-garage-map').data('serviceid')) {
            window.serviceIds = $('#find-garage-map').data('serviceid').toString();
        }

        offerApp.querySelector('a').click();
        return false;
    }

    return true;
}

function doCommonPhoneView(linkClicked) {
   
    var attr = linkClicked.getAttribute('attr-data');
    var name = linkClicked.getAttribute('attr-data-name');
    linkClicked.nextElementSibling.className = '';
    linkClicked.nextElementSibling.innerText = attr;
    linkClicked.nextElementSibling.setAttribute('href', 'tel:' + attr);
    linkClicked.className = 'hidden';

    dataLayer.push({
        'event': 'Popup kontakt',
        'shop': name, 
        'leadType': 'phone'
    });

    return false;
}

function doCommonEmailView(linkClicked) {

    var attr = linkClicked.getAttribute('attr-data').replace(';', '@');
    var name = linkClicked.getAttribute('attr-data-name');
    linkClicked.nextElementSibling.className = '';
    linkClicked.nextElementSibling.innerText = attr;
    linkClicked.nextElementSibling.setAttribute('href', 'mailto:' + attr);
    linkClicked.className = 'hidden';

    dataLayer.push({
        'event': 'Popup kontakt',
        'shop': name,
        'leadType': 'email' 
    });

    return false;
}

function doCommonAddressViewForList(linkClicked) {
    var address = linkClicked.getAttribute('attr-data-address');
    var zipCity = linkClicked.getAttribute('attr-data-zipcity');
    var name = linkClicked.getAttribute('attr-data-name');
    linkClicked.style.display = 'none';
    linkClicked.parentElement.innerHTML = linkClicked.parentElement.innerHTML + '<br/>' + address + '<br/>' + zipCity;

    dataLayer.push({
        'event': 'Popup kontakt',
        'shop': name,
        'leadType': 'address'
    });

    return false;
}

function doCommonAddressView(linkClicked) {
    var address = linkClicked.getAttribute('attr-data-address');
    var zipCity = linkClicked.getAttribute('attr-data-zipcity');
    var name = linkClicked.getAttribute('attr-data-name');
    linkClicked.parentElement.innerHTML = address + '<br/>' + zipCity;

    dataLayer.push({
        'event': 'Popup kontakt',
        'shop': name,
        'leadType': 'address'
    });

    return false;
}

function doCommonLeadAction(idIn, typeIn) {
    $.ajax({
        type: "post",
        url: "/DoLeadAction/",
        data: { id: idIn, type: typeIn},
    }).fail(function (jqXHR, textStatus) {
        console.log("Request failed: " + textStatus);
    });
}

function doCommonShopRedirect(linkClicked) {

    var useExternalShopRedirect = $('.find-garage-holder').attr('data-attr-useexternalshoplink') == 'true';
    if (useExternalShopRedirect) {
        const sId = linkClicked.getAttribute('data-id');
        $.ajax({
            url: '/api/store/getexternalurl/'+ sId,
        }).done(function (url) {
            $('#external-link').attr('href', url);
            $('#external-link-counter').text('3');
            $('#external-link-modal').modal('show');
        });
        return false;
    }
    checkCommonTarget(linkClicked);
    return true;    
}

function doCommonWorkShopClick(linkClicked) {
    checkCommonTarget(linkClicked);
    return true;
}

function checkCommonTarget(linkClicked) {
    if (window.DISPLAYFRAMED) {
        linkClicked.target = '_blank';
    }
}


function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function checkCookie(cname) {
  var name = cname + "=";
  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);
    }
    if (c.indexOf(name) == 0) {
        return false;
    }
  }
  return true;
};
if (typeof console === "undefined" || typeof console.log === "undefined") {
    console = {};
    console.log = function () { };
}


(function ($) {

    var bodyTimeout;
    var eventHandlers = {
      dataToggle: function(e) {
        var target = $(this).data('toggle');
        $(target).toggle();

        toggleIcon($(this));
      },

      dataToggleCloseOutside: function(e) {
        var _this = $(this);
        if(_this.hasClass('only-touch-toggle')) {
          e.preventDefault();
          if(!Modernizr.touch) return;
        }

        if(!Modernizr.touch) {
          e.stopPropagation();
        }
        $('body').off('click', closeOnBodyClick);

        var target = _this.data('toggle-close-outside');
        $(target).toggle();

        toggleIcon(_this);

        var closeOnBodyClick = function() {
          $(target).toggle();
          toggleIcon(_this);
        }

        $('body').one('click', closeOnBodyClick);
      },

      dataSlideToggle: function(e) {
        var target = $(this).data('slide-toggle');
        $(target).slideToggle();

        toggleIcon($(this));
      },

      dataMobileToggle: function(e) {
        e.preventDefault();
        if($(window).width() > 768) return;
        var target = $(this).data('mobile-toggle');
        $(target).toggle();
        toggleIcon($(this));
      },

      dataMobileToggleSibling: function(e) {
        e.preventDefault();
        if($(window).width() > 768) return;

        var targetElem = $(this).data('mobile-toggle-sibling');
        var target;

        if(!$(this).siblings(targetElem).length) {
          target = $(this).siblings().find(targetElem);

        } else {
          target = $(this).siblings(targetElem);
        }

        target.toggle();

        toggleIcon($(this));
      }

    };

    var toggleIcon = function(elem) {
      if(elem.hasClass('fa-caret-down')) {
        elem.addClass('fa-caret-up').removeClass('fa-caret-down');
      } else if(elem.hasClass('fa-caret-up')) {
        elem.removeClass('fa-caret-up').addClass('fa-caret-down');
      }

      if(elem.find('.fa-caret-down').length) {
        elem.find('.fa-caret-down').addClass('fa-caret-up').removeClass('fa-caret-down');
      } else if(elem.find('.fa-caret-up').length) {
        elem.find('.fa-caret-up').addClass('fa-caret-down').removeClass('fa-caret-up');
      }
    };

    /*
    * TOGGLE A SINGLE ELEMENT ON CLICK
    */
    $('[data-toggle]').on('click', eventHandlers.dataToggle);

    /*
    * TOGGLE A SINGLE ELEMENT ON CLICK AND THEN CLOSE ON CLICK ANYWHERE
    */
    $('[data-toggle-close-outside]').on('click', eventHandlers.dataToggleCloseOutside);

    /*
    * TOGGLE A SINGLE ELEMENT ON CLICK WITH SLIDE
    */
    $('[data-slide-toggle]').on('click', eventHandlers.dataSlideToggle);

    /*
    * TOGGLE A SINGLE ELEMENT ON CLICK ONLY ON MOBILE
    */
    $('[data-mobile-toggle]').on('click', eventHandlers.dataMobileToggle);

    /*
    * TOGGLE ALL SIBLINGS OF AN ELEMTN
    */
    $('[data-mobile-toggle-sibling]').on('click', eventHandlers.dataMobileToggleSibling);


})(jQuery);


(function($) {
  $(document).ready(function(){
    $('a[data-scroll]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top - 50
        }, 900, 'swing', function () {
            //window.location.hash = target;
        });
    });
  });
})(jQuery);



/*
* jquery.sameheight.js v1.1
* http://github.com/justinforce/jquery-sameheight
*
* Copyright 2011, Justin Force
* Licensed under the MIT license
*
* Set selected elements to the same height as the tallest element in the
* selection. Automatically adjust on $(window).resize()
*/

/*jslint browser: true, white: true */
/*global jQuery */

(function($) {

'use strict';

// add Array.indexOf if it isn't defined
if (!Array.indexOf) {
  Array.prototype.indexOf = function(obj) {
    var i, len = this.length; // for loop vars

    for (i = 0; i < len; i += 1) {
      if (obj === this[i]) {
        return i;
      }
    }
    return -1;
  };
}


// Set all selected elements to the same height
$.fn.sameHeight = function() {

  var these = this; // for use in nested function

  // Set the resize listener, then trigger resize to set height immediately.
  // First set all heights to auto or they will grow when the window resizes.
  // Find the max height by comparing all of the elements, then set the height
  // of the selection
  $(window).resize(function() {
    var max = 0;
    these.height('auto').each(function() {
      max = Math.max(max, $(this).height());
    }).css('min-height', max);
  }).resize();

  return this;
};


// Set everything with class="sameheight sh_something" to the same height
$.sameHeight = function() {

  $('.sameheight').each(function() {
    var selectors = [], // array of the "sh_X" class names
    match;              // all elements with className sh_[something]

    match = $(this).attr('class').match(/(sh_\S+)/);
    if (match && match[1] && selectors.indexOf(match[1]) < 0) {
      selectors.push(match[1]);
    }

    $.each(selectors, function() {
      $('.' + this).sameHeight();
    });
  });
};

}(jQuery));


var Regions = (function(root, undefined) {
  "use strict";
  // Private
  var _this;
  var toArray = Array.prototype.slice;
  var defaults = {
    version: '0.1'
  };
  var listener = window.addEventListener || window.attachEvent;

  function init(opts) {

    // Return if on IE
    if('attachEvent' in window || is_old_IE) {
      return false;
    }

    _this = this;
    _this.elems = {
      containers: [],
      movers: []
    };
    var options = helpers.extend(defaults, opts);

    addListeners();
  };

  function addListeners() {
    // Listen
    listener('DOMContentLoaded', setElems);
    listener('resize', resizeHandler);
  }

  function setElems() {
    var nodeList = toArray.call( document.querySelectorAll('[region-flow-from], [region-flow-into]') ) || [];
    for(var i in nodeList) {

      var node = nodeList[i];
      var attrs = [];
      // Loop through attributes of node and store in key-value
      toArray.call(node.attributes).forEach(function(attr) {
        attrs[attr.name] = attr.value;
      });

      if ( typeof attrs['region-flow-into'] === 'undefined' ) {
        _this.elems['containers'][ attrs['region-flow-from'] ] = node;
      } else {
        _this.elems['movers'].push({
          node:             node,
          breakPoint:       attrs['region-breakpoint'],
          flowInto:         attrs['region-flow-into'],
          isMoved:          false,
          origPrevSibling:  node.previousElementSibling,
          origParent:       node.parentNode,
          priority:         i
        });
      }
    }
    // Set init positions
    resizeHandler();
  };

  function resizeHandler() {
    var elems = _this.elems['movers'];
    var width = window.innerWidth;
    var containers = _this.elems['containers']

    for(var i in elems) {
      var elem = elems[i];
      var breakPoint = parseInt( elem.breakPoint, 10);

      if( !elem.isMoved && width <= breakPoint ) {
        elem.isMoved = true;
        if (containers[elem.flowInto])
            helpers.appendChild(containers[elem.flowInto], elem.node);

      } else if( elem.isMoved && width > breakPoint ) {
        elem.isMoved = false;
        if(elem.origPrevSibling) {
          helpers.insertAfter(elem.origPrevSibling, elem.node);
        } else {
          helpers.prependChild(elem.origParent, elem.node);
        }
      }
    }
  }

  // Helpers
  var helpers = {
    /*
    * Extends orig obj with ext obj - shallow copy
    */
    extend: function(orig, ext) {
      if(typeof orig !== 'object' || typeof ext !== 'object')
        throw new Error('Can only extend objects');

      for(var key in ext) {
        orig[key] = ext[key];
      }
      return orig;
    },
    /*
    * Append newNode into referenceNode
    */
    appendChild: function(referenceNode, newNode) {
      referenceNode.appendChild(newNode);
    },

    /*
    * Perpend newNode into referenceNode
    */
    prependChild: function(referenceNode, newNode) {
        referenceNode.insertBefore( newNode, referenceNode.firstChild);
    },

    /*
    * Insert newNode after referenceNode
    */
    insertAfter: function(referenceNode, newNode) {
        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    },
    /*
    * Checks whether a given node still exists in the DOM
    */
    stillExistsInDom: function(node) {
        return document.documentElement.contains(node);
    }
  };

  // Public
  return {
    init: init
  }

})(window);



/*
* COUNTUP JS
*/
function countUp(a, b, c, d, e, f) { this.options = f || { useEasing: !0, useGrouping: !0, separator: ",", decimal: "." }; for (var g = 0, h = ["webkit", "moz", "ms"], i = 0; i < h.length && !window.requestAnimationFrame; ++i) window.requestAnimationFrame = window[h[i] + "RequestAnimationFrame"], window.cancelAnimationFrame = window[h[i] + "CancelAnimationFrame"] || window[h[i] + "CancelRequestAnimationFrame"]; window.requestAnimationFrame || (window.requestAnimationFrame = function (a) { var c = (new Date).getTime(), d = Math.max(0, 16 - (c - g)), e = window.setTimeout(function () { a(c + d) }, d); return g = c + d, e }), window.cancelAnimationFrame || (window.cancelAnimationFrame = function (a) { clearTimeout(a) }); var j = this; this.d = "string" == typeof a ? document.getElementById(a) : a, this.startVal = Number(b), this.endVal = Number(c), this.countDown = this.startVal > this.endVal ? !0 : !1, this.startTime = null, this.timestamp = null, this.remaining = null, this.frameVal = this.startVal, this.rAF = null, this.decimals = Math.max(0, d || 0), this.dec = Math.pow(10, this.decimals), this.duration = 1e3 * e || 2e3, this.easeOutExpo = function (a, b, c, d) { return 1024 * c * (-Math.pow(2, -10 * a / d) + 1) / 1023 + b }, this.count = function (a) { null === j.startTime && (j.startTime = a), j.timestamp = a; var b = a - j.startTime; if (j.remaining = j.duration - b, j.options.useEasing) if (j.countDown) { var c = j.easeOutExpo(b, 0, j.startVal - j.endVal, j.duration); j.frameVal = j.startVal - c } else j.frameVal = j.easeOutExpo(b, j.startVal, j.endVal - j.startVal, j.duration); else if (j.countDown) { var c = (j.startVal - j.endVal) * (b / j.duration); j.frameVal = j.startVal - c } else j.frameVal = j.startVal + (j.endVal - j.startVal) * (b / j.duration); j.frameVal = Math.round(j.frameVal * j.dec) / j.dec, j.frameVal = j.countDown ? j.frameVal < j.endVal ? j.endVal : j.frameVal : j.frameVal > j.endVal ? j.endVal : j.frameVal, j.d.innerHTML = j.formatNumber(j.frameVal.toFixed(j.decimals)), b < j.duration ? j.rAF = requestAnimationFrame(j.count) : null != j.callback && j.callback() }, this.start = function (a) { return j.callback = a, isNaN(j.endVal) || isNaN(j.startVal) ? (console.log("countUp error: startVal or endVal is not a number"), j.d.innerHTML = "--") : j.rAF = requestAnimationFrame(j.count), !1 }, this.stop = function () { cancelAnimationFrame(j.rAF) }, this.reset = function () { j.startTime = null, cancelAnimationFrame(j.rAF), j.d.innerHTML = j.formatNumber(j.startVal.toFixed(j.decimals)) }, this.resume = function () { j.startTime = null, j.duration = j.remaining, j.startVal = j.frameVal, requestAnimationFrame(j.count) }, this.formatNumber = function (a) { a += ""; var b, c, d, e; if (b = a.split("."), c = b[0], d = b.length > 1 ? j.options.decimal + b[1] : "", e = /(\d+)(\d{3})/, j.options.useGrouping) for (; e.test(c) ;) c = c.replace(e, "$1" + j.options.separator + "$2"); return c + d }, j.d.innerHTML = j.formatNumber(j.startVal.toFixed(j.decimals)) }



// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {

    Array.prototype.map = function (callback, thisArg) {

        var T, A, k;

        if (this == null) {
            throw new TypeError(' this is null or not defined');
        }

        // 1. Let O be the result of calling ToObject passing the |this| 
        //    value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal 
        //    method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0;

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if (typeof callback !== 'function') {
            throw new TypeError(callback + ' is not a function');
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (arguments.length > 1) {
            T = thisArg;
        }

        // 6. Let A be a new array created as if by the expression new Array(len) 
        //    where Array is the standard built-in constructor with that name and 
        //    len is the value of len.
        A = new Array(len);

        // 7. Let k be 0
        k = 0;

        // 8. Repeat, while k < len
        while (k < len) {

            var kValue, mappedValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal 
            //    method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (k in O) {

                // i. Let kValue be the result of calling the Get internal 
                //    method of O with argument Pk.
                kValue = O[k];

                // ii. Let mappedValue be the result of calling the Call internal 
                //     method of callback with T as the this value and argument 
                //     list containing kValue, k, and O.
                mappedValue = callback.call(T, kValue, k, O);

                // iii. Call the DefineOwnProperty internal method of A with arguments
                // Pk, Property Descriptor
                // { Value: mappedValue,
                //   Writable: true,
                //   Enumerable: true,
                //   Configurable: true },
                // and false.

                // In browsers that support Object.defineProperty, use the following:
                // Object.defineProperty(A, k, {
                //   value: mappedValue,
                //   writable: true,
                //   enumerable: true,
                //   configurable: true
                // });

                // For best browser support, use the following:
                A[k] = mappedValue;
            }
            // d. Increase k by 1.
            k++;
        }

        // 9. return A
        return A;
    };
}


/**
 * Swiper 5.3.7
 * Most modern mobile touch slider and framework with hardware accelerated transitions
 * http://swiperjs.com
 *
 * Copyright 2014-2020 Vladimir Kharlampidi
 *
 * Released under the MIT License
 *
 * Released on: April 10, 2020
 */

!function (e, t) { "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : (e = e || self).Swiper = t() }(this, (function () { "use strict"; var e = "undefined" == typeof document ? { body: {}, addEventListener: function () { }, removeEventListener: function () { }, activeElement: { blur: function () { }, nodeName: "" }, querySelector: function () { return null }, querySelectorAll: function () { return [] }, getElementById: function () { return null }, createEvent: function () { return { initEvent: function () { } } }, createElement: function () { return { children: [], childNodes: [], style: {}, setAttribute: function () { }, getElementsByTagName: function () { return [] } } }, location: { hash: "" } } : document, t = "undefined" == typeof window ? { document: e, navigator: { userAgent: "" }, location: {}, history: {}, CustomEvent: function () { return this }, addEventListener: function () { }, removeEventListener: function () { }, getComputedStyle: function () { return { getPropertyValue: function () { return "" } } }, Image: function () { }, Date: function () { }, screen: {}, setTimeout: function () { }, clearTimeout: function () { } } : window, i = function (e) { for (var t = 0; t < e.length; t += 1)this[t] = e[t]; return this.length = e.length, this }; function s(s, a) { var r = [], n = 0; if (s && !a && s instanceof i) return s; if (s) if ("string" == typeof s) { var o, l, d = s.trim(); if (d.indexOf("<") >= 0 && d.indexOf(">") >= 0) { var h = "div"; for (0 === d.indexOf("<li") && (h = "ul"), 0 === d.indexOf("<tr") && (h = "tbody"), 0 !== d.indexOf("<td") && 0 !== d.indexOf("<th") || (h = "tr"), 0 === d.indexOf("<tbody") && (h = "table"), 0 === d.indexOf("<option") && (h = "select"), (l = e.createElement(h)).innerHTML = d, n = 0; n < l.childNodes.length; n += 1)r.push(l.childNodes[n]) } else for (o = a || "#" !== s[0] || s.match(/[ .<>:~]/) ? (a || e).querySelectorAll(s.trim()) : [e.getElementById(s.trim().split("#")[1])], n = 0; n < o.length; n += 1)o[n] && r.push(o[n]) } else if (s.nodeType || s === t || s === e) r.push(s); else if (s.length > 0 && s[0].nodeType) for (n = 0; n < s.length; n += 1)r.push(s[n]); return new i(r) } function a(e) { for (var t = [], i = 0; i < e.length; i += 1)-1 === t.indexOf(e[i]) && t.push(e[i]); return t } s.fn = i.prototype, s.Class = i, s.Dom7 = i; var r = { addClass: function (e) { if (void 0 === e) return this; for (var t = e.split(" "), i = 0; i < t.length; i += 1)for (var s = 0; s < this.length; s += 1)void 0 !== this[s] && void 0 !== this[s].classList && this[s].classList.add(t[i]); return this }, removeClass: function (e) { for (var t = e.split(" "), i = 0; i < t.length; i += 1)for (var s = 0; s < this.length; s += 1)void 0 !== this[s] && void 0 !== this[s].classList && this[s].classList.remove(t[i]); return this }, hasClass: function (e) { return !!this[0] && this[0].classList.contains(e) }, toggleClass: function (e) { for (var t = e.split(" "), i = 0; i < t.length; i += 1)for (var s = 0; s < this.length; s += 1)void 0 !== this[s] && void 0 !== this[s].classList && this[s].classList.toggle(t[i]); return this }, attr: function (e, t) { var i = arguments; if (1 === arguments.length && "string" == typeof e) return this[0] ? this[0].getAttribute(e) : void 0; for (var s = 0; s < this.length; s += 1)if (2 === i.length) this[s].setAttribute(e, t); else for (var a in e) this[s][a] = e[a], this[s].setAttribute(a, e[a]); return this }, removeAttr: function (e) { for (var t = 0; t < this.length; t += 1)this[t].removeAttribute(e); return this }, data: function (e, t) { var i; if (void 0 !== t) { for (var s = 0; s < this.length; s += 1)(i = this[s]).dom7ElementDataStorage || (i.dom7ElementDataStorage = {}), i.dom7ElementDataStorage[e] = t; return this } if (i = this[0]) { if (i.dom7ElementDataStorage && e in i.dom7ElementDataStorage) return i.dom7ElementDataStorage[e]; var a = i.getAttribute("data-" + e); return a || void 0 } }, transform: function (e) { for (var t = 0; t < this.length; t += 1) { var i = this[t].style; i.webkitTransform = e, i.transform = e } return this }, transition: function (e) { "string" != typeof e && (e += "ms"); for (var t = 0; t < this.length; t += 1) { var i = this[t].style; i.webkitTransitionDuration = e, i.transitionDuration = e } return this }, on: function () { for (var e, t = [], i = arguments.length; i--;)t[i] = arguments[i]; var a = t[0], r = t[1], n = t[2], o = t[3]; function l(e) { var t = e.target; if (t) { var i = e.target.dom7EventData || []; if (i.indexOf(e) < 0 && i.unshift(e), s(t).is(r)) n.apply(t, i); else for (var a = s(t).parents(), o = 0; o < a.length; o += 1)s(a[o]).is(r) && n.apply(a[o], i) } } function d(e) { var t = e && e.target && e.target.dom7EventData || []; t.indexOf(e) < 0 && t.unshift(e), n.apply(this, t) } "function" == typeof t[1] && (a = (e = t)[0], n = e[1], o = e[2], r = void 0), o || (o = !1); for (var h, p = a.split(" "), c = 0; c < this.length; c += 1) { var u = this[c]; if (r) for (h = 0; h < p.length; h += 1) { var v = p[h]; u.dom7LiveListeners || (u.dom7LiveListeners = {}), u.dom7LiveListeners[v] || (u.dom7LiveListeners[v] = []), u.dom7LiveListeners[v].push({ listener: n, proxyListener: l }), u.addEventListener(v, l, o) } else for (h = 0; h < p.length; h += 1) { var f = p[h]; u.dom7Listeners || (u.dom7Listeners = {}), u.dom7Listeners[f] || (u.dom7Listeners[f] = []), u.dom7Listeners[f].push({ listener: n, proxyListener: d }), u.addEventListener(f, d, o) } } return this }, off: function () { for (var e, t = [], i = arguments.length; i--;)t[i] = arguments[i]; var s = t[0], a = t[1], r = t[2], n = t[3]; "function" == typeof t[1] && (s = (e = t)[0], r = e[1], n = e[2], a = void 0), n || (n = !1); for (var o = s.split(" "), l = 0; l < o.length; l += 1)for (var d = o[l], h = 0; h < this.length; h += 1) { var p = this[h], c = void 0; if (!a && p.dom7Listeners ? c = p.dom7Listeners[d] : a && p.dom7LiveListeners && (c = p.dom7LiveListeners[d]), c && c.length) for (var u = c.length - 1; u >= 0; u -= 1) { var v = c[u]; r && v.listener === r || r && v.listener && v.listener.dom7proxy && v.listener.dom7proxy === r ? (p.removeEventListener(d, v.proxyListener, n), c.splice(u, 1)) : r || (p.removeEventListener(d, v.proxyListener, n), c.splice(u, 1)) } } return this }, trigger: function () { for (var i = [], s = arguments.length; s--;)i[s] = arguments[s]; for (var a = i[0].split(" "), r = i[1], n = 0; n < a.length; n += 1)for (var o = a[n], l = 0; l < this.length; l += 1) { var d = this[l], h = void 0; try { h = new t.CustomEvent(o, { detail: r, bubbles: !0, cancelable: !0 }) } catch (t) { (h = e.createEvent("Event")).initEvent(o, !0, !0), h.detail = r } d.dom7EventData = i.filter((function (e, t) { return t > 0 })), d.dispatchEvent(h), d.dom7EventData = [], delete d.dom7EventData } return this }, transitionEnd: function (e) { var t, i = ["webkitTransitionEnd", "transitionend"], s = this; function a(r) { if (r.target === this) for (e.call(this, r), t = 0; t < i.length; t += 1)s.off(i[t], a) } if (e) for (t = 0; t < i.length; t += 1)s.on(i[t], a); return this }, outerWidth: function (e) { if (this.length > 0) { if (e) { var t = this.styles(); return this[0].offsetWidth + parseFloat(t.getPropertyValue("margin-right")) + parseFloat(t.getPropertyValue("margin-left")) } return this[0].offsetWidth } return null }, outerHeight: function (e) { if (this.length > 0) { if (e) { var t = this.styles(); return this[0].offsetHeight + parseFloat(t.getPropertyValue("margin-top")) + parseFloat(t.getPropertyValue("margin-bottom")) } return this[0].offsetHeight } return null }, offset: function () { if (this.length > 0) { var i = this[0], s = i.getBoundingClientRect(), a = e.body, r = i.clientTop || a.clientTop || 0, n = i.clientLeft || a.clientLeft || 0, o = i === t ? t.scrollY : i.scrollTop, l = i === t ? t.scrollX : i.scrollLeft; return { top: s.top + o - r, left: s.left + l - n } } return null }, css: function (e, i) { var s; if (1 === arguments.length) { if ("string" != typeof e) { for (s = 0; s < this.length; s += 1)for (var a in e) this[s].style[a] = e[a]; return this } if (this[0]) return t.getComputedStyle(this[0], null).getPropertyValue(e) } if (2 === arguments.length && "string" == typeof e) { for (s = 0; s < this.length; s += 1)this[s].style[e] = i; return this } return this }, each: function (e) { if (!e) return this; for (var t = 0; t < this.length; t += 1)if (!1 === e.call(this[t], t, this[t])) return this; return this }, html: function (e) { if (void 0 === e) return this[0] ? this[0].innerHTML : void 0; for (var t = 0; t < this.length; t += 1)this[t].innerHTML = e; return this }, text: function (e) { if (void 0 === e) return this[0] ? this[0].textContent.trim() : null; for (var t = 0; t < this.length; t += 1)this[t].textContent = e; return this }, is: function (a) { var r, n, o = this[0]; if (!o || void 0 === a) return !1; if ("string" == typeof a) { if (o.matches) return o.matches(a); if (o.webkitMatchesSelector) return o.webkitMatchesSelector(a); if (o.msMatchesSelector) return o.msMatchesSelector(a); for (r = s(a), n = 0; n < r.length; n += 1)if (r[n] === o) return !0; return !1 } if (a === e) return o === e; if (a === t) return o === t; if (a.nodeType || a instanceof i) { for (r = a.nodeType ? [a] : a, n = 0; n < r.length; n += 1)if (r[n] === o) return !0; return !1 } return !1 }, index: function () { var e, t = this[0]; if (t) { for (e = 0; null !== (t = t.previousSibling);)1 === t.nodeType && (e += 1); return e } }, eq: function (e) { if (void 0 === e) return this; var t, s = this.length; return new i(e > s - 1 ? [] : e < 0 ? (t = s + e) < 0 ? [] : [this[t]] : [this[e]]) }, append: function () { for (var t, s = [], a = arguments.length; a--;)s[a] = arguments[a]; for (var r = 0; r < s.length; r += 1) { t = s[r]; for (var n = 0; n < this.length; n += 1)if ("string" == typeof t) { var o = e.createElement("div"); for (o.innerHTML = t; o.firstChild;)this[n].appendChild(o.firstChild) } else if (t instanceof i) for (var l = 0; l < t.length; l += 1)this[n].appendChild(t[l]); else this[n].appendChild(t) } return this }, prepend: function (t) { var s, a; for (s = 0; s < this.length; s += 1)if ("string" == typeof t) { var r = e.createElement("div"); for (r.innerHTML = t, a = r.childNodes.length - 1; a >= 0; a -= 1)this[s].insertBefore(r.childNodes[a], this[s].childNodes[0]) } else if (t instanceof i) for (a = 0; a < t.length; a += 1)this[s].insertBefore(t[a], this[s].childNodes[0]); else this[s].insertBefore(t, this[s].childNodes[0]); return this }, next: function (e) { return this.length > 0 ? e ? this[0].nextElementSibling && s(this[0].nextElementSibling).is(e) ? new i([this[0].nextElementSibling]) : new i([]) : this[0].nextElementSibling ? new i([this[0].nextElementSibling]) : new i([]) : new i([]) }, nextAll: function (e) { var t = [], a = this[0]; if (!a) return new i([]); for (; a.nextElementSibling;) { var r = a.nextElementSibling; e ? s(r).is(e) && t.push(r) : t.push(r), a = r } return new i(t) }, prev: function (e) { if (this.length > 0) { var t = this[0]; return e ? t.previousElementSibling && s(t.previousElementSibling).is(e) ? new i([t.previousElementSibling]) : new i([]) : t.previousElementSibling ? new i([t.previousElementSibling]) : new i([]) } return new i([]) }, prevAll: function (e) { var t = [], a = this[0]; if (!a) return new i([]); for (; a.previousElementSibling;) { var r = a.previousElementSibling; e ? s(r).is(e) && t.push(r) : t.push(r), a = r } return new i(t) }, parent: function (e) { for (var t = [], i = 0; i < this.length; i += 1)null !== this[i].parentNode && (e ? s(this[i].parentNode).is(e) && t.push(this[i].parentNode) : t.push(this[i].parentNode)); return s(a(t)) }, parents: function (e) { for (var t = [], i = 0; i < this.length; i += 1)for (var r = this[i].parentNode; r;)e ? s(r).is(e) && t.push(r) : t.push(r), r = r.parentNode; return s(a(t)) }, closest: function (e) { var t = this; return void 0 === e ? new i([]) : (t.is(e) || (t = t.parents(e).eq(0)), t) }, find: function (e) { for (var t = [], s = 0; s < this.length; s += 1)for (var a = this[s].querySelectorAll(e), r = 0; r < a.length; r += 1)t.push(a[r]); return new i(t) }, children: function (e) { for (var t = [], r = 0; r < this.length; r += 1)for (var n = this[r].childNodes, o = 0; o < n.length; o += 1)e ? 1 === n[o].nodeType && s(n[o]).is(e) && t.push(n[o]) : 1 === n[o].nodeType && t.push(n[o]); return new i(a(t)) }, filter: function (e) { for (var t = [], s = 0; s < this.length; s += 1)e.call(this[s], s, this[s]) && t.push(this[s]); return new i(t) }, remove: function () { for (var e = 0; e < this.length; e += 1)this[e].parentNode && this[e].parentNode.removeChild(this[e]); return this }, add: function () { for (var e = [], t = arguments.length; t--;)e[t] = arguments[t]; var i, a, r = this; for (i = 0; i < e.length; i += 1) { var n = s(e[i]); for (a = 0; a < n.length; a += 1)r[r.length] = n[a], r.length += 1 } return r }, styles: function () { return this[0] ? t.getComputedStyle(this[0], null) : {} } }; Object.keys(r).forEach((function (e) { s.fn[e] = s.fn[e] || r[e] })); var n = { deleteProps: function (e) { var t = e; Object.keys(t).forEach((function (e) { try { t[e] = null } catch (e) { } try { delete t[e] } catch (e) { } })) }, nextTick: function (e, t) { return void 0 === t && (t = 0), setTimeout(e, t) }, now: function () { return Date.now() }, getTranslate: function (e, i) { var s, a, r; void 0 === i && (i = "x"); var n = t.getComputedStyle(e, null); return t.WebKitCSSMatrix ? ((a = n.transform || n.webkitTransform).split(",").length > 6 && (a = a.split(", ").map((function (e) { return e.replace(",", ".") })).join(", ")), r = new t.WebKitCSSMatrix("none" === a ? "" : a)) : s = (r = n.MozTransform || n.OTransform || n.MsTransform || n.msTransform || n.transform || n.getPropertyValue("transform").replace("translate(", "matrix(1, 0, 0, 1,")).toString().split(","), "x" === i && (a = t.WebKitCSSMatrix ? r.m41 : 16 === s.length ? parseFloat(s[12]) : parseFloat(s[4])), "y" === i && (a = t.WebKitCSSMatrix ? r.m42 : 16 === s.length ? parseFloat(s[13]) : parseFloat(s[5])), a || 0 }, parseUrlQuery: function (e) { var i, s, a, r, n = {}, o = e || t.location.href; if ("string" == typeof o && o.length) for (r = (s = (o = o.indexOf("?") > -1 ? o.replace(/\S*\?/, "") : "").split("&").filter((function (e) { return "" !== e }))).length, i = 0; i < r; i += 1)a = s[i].replace(/#\S+/g, "").split("="), n[decodeURIComponent(a[0])] = void 0 === a[1] ? void 0 : decodeURIComponent(a[1]) || ""; return n }, isObject: function (e) { return "object" == typeof e && null !== e && e.constructor && e.constructor === Object }, extend: function () { for (var e = [], t = arguments.length; t--;)e[t] = arguments[t]; for (var i = Object(e[0]), s = 1; s < e.length; s += 1) { var a = e[s]; if (null != a) for (var r = Object.keys(Object(a)), o = 0, l = r.length; o < l; o += 1) { var d = r[o], h = Object.getOwnPropertyDescriptor(a, d); void 0 !== h && h.enumerable && (n.isObject(i[d]) && n.isObject(a[d]) ? n.extend(i[d], a[d]) : !n.isObject(i[d]) && n.isObject(a[d]) ? (i[d] = {}, n.extend(i[d], a[d])) : i[d] = a[d]) } } return i } }, o = { touch: t.Modernizr && !0 === t.Modernizr.touch || !!(t.navigator.maxTouchPoints > 0 || "ontouchstart" in t || t.DocumentTouch && e instanceof t.DocumentTouch), pointerEvents: !!t.PointerEvent && "maxTouchPoints" in t.navigator && t.navigator.maxTouchPoints > 0, observer: "MutationObserver" in t || "WebkitMutationObserver" in t, passiveListener: function () { var e = !1; try { var i = Object.defineProperty({}, "passive", { get: function () { e = !0 } }); t.addEventListener("testPassiveListener", null, i) } catch (e) { } return e }(), gestures: "ongesturestart" in t }, l = function (e) { void 0 === e && (e = {}); var t = this; t.params = e, t.eventsListeners = {}, t.params && t.params.on && Object.keys(t.params.on).forEach((function (e) { t.on(e, t.params.on[e]) })) }, d = { components: { configurable: !0 } }; l.prototype.on = function (e, t, i) { var s = this; if ("function" != typeof t) return s; var a = i ? "unshift" : "push"; return e.split(" ").forEach((function (e) { s.eventsListeners[e] || (s.eventsListeners[e] = []), s.eventsListeners[e][a](t) })), s }, l.prototype.once = function (e, t, i) { var s = this; if ("function" != typeof t) return s; function a() { for (var i = [], r = arguments.length; r--;)i[r] = arguments[r]; s.off(e, a), a.f7proxy && delete a.f7proxy, t.apply(s, i) } return a.f7proxy = t, s.on(e, a, i) }, l.prototype.off = function (e, t) { var i = this; return i.eventsListeners ? (e.split(" ").forEach((function (e) { void 0 === t ? i.eventsListeners[e] = [] : i.eventsListeners[e] && i.eventsListeners[e].length && i.eventsListeners[e].forEach((function (s, a) { (s === t || s.f7proxy && s.f7proxy === t) && i.eventsListeners[e].splice(a, 1) })) })), i) : i }, l.prototype.emit = function () { for (var e = [], t = arguments.length; t--;)e[t] = arguments[t]; var i, s, a, r = this; if (!r.eventsListeners) return r; "string" == typeof e[0] || Array.isArray(e[0]) ? (i = e[0], s = e.slice(1, e.length), a = r) : (i = e[0].events, s = e[0].data, a = e[0].context || r); var n = Array.isArray(i) ? i : i.split(" "); return n.forEach((function (e) { if (r.eventsListeners && r.eventsListeners[e]) { var t = []; r.eventsListeners[e].forEach((function (e) { t.push(e) })), t.forEach((function (e) { e.apply(a, s) })) } })), r }, l.prototype.useModulesParams = function (e) { var t = this; t.modules && Object.keys(t.modules).forEach((function (i) { var s = t.modules[i]; s.params && n.extend(e, s.params) })) }, l.prototype.useModules = function (e) { void 0 === e && (e = {}); var t = this; t.modules && Object.keys(t.modules).forEach((function (i) { var s = t.modules[i], a = e[i] || {}; s.instance && Object.keys(s.instance).forEach((function (e) { var i = s.instance[e]; t[e] = "function" == typeof i ? i.bind(t) : i })), s.on && t.on && Object.keys(s.on).forEach((function (e) { t.on(e, s.on[e]) })), s.create && s.create.bind(t)(a) })) }, d.components.set = function (e) { this.use && this.use(e) }, l.installModule = function (e) { for (var t = [], i = arguments.length - 1; i-- > 0;)t[i] = arguments[i + 1]; var s = this; s.prototype.modules || (s.prototype.modules = {}); var a = e.name || Object.keys(s.prototype.modules).length + "_" + n.now(); return s.prototype.modules[a] = e, e.proto && Object.keys(e.proto).forEach((function (t) { s.prototype[t] = e.proto[t] })), e.static && Object.keys(e.static).forEach((function (t) { s[t] = e.static[t] })), e.install && e.install.apply(s, t), s }, l.use = function (e) { for (var t = [], i = arguments.length - 1; i-- > 0;)t[i] = arguments[i + 1]; var s = this; return Array.isArray(e) ? (e.forEach((function (e) { return s.installModule(e) })), s) : s.installModule.apply(s, [e].concat(t)) }, Object.defineProperties(l, d); var h = { updateSize: function () { var e, t, i = this.$el; e = void 0 !== this.params.width ? this.params.width : i[0].clientWidth, t = void 0 !== this.params.height ? this.params.height : i[0].clientHeight, 0 === e && this.isHorizontal() || 0 === t && this.isVertical() || (e = e - parseInt(i.css("padding-left"), 10) - parseInt(i.css("padding-right"), 10), t = t - parseInt(i.css("padding-top"), 10) - parseInt(i.css("padding-bottom"), 10), n.extend(this, { width: e, height: t, size: this.isHorizontal() ? e : t })) }, updateSlides: function () { var e = this.params, i = this.$wrapperEl, s = this.size, a = this.rtlTranslate, r = this.wrongRTL, o = this.virtual && e.virtual.enabled, l = o ? this.virtual.slides.length : this.slides.length, d = i.children("." + this.params.slideClass), h = o ? this.virtual.slides.length : d.length, p = [], c = [], u = []; function v(t) { return !e.cssMode || t !== d.length - 1 } var f = e.slidesOffsetBefore; "function" == typeof f && (f = e.slidesOffsetBefore.call(this)); var m = e.slidesOffsetAfter; "function" == typeof m && (m = e.slidesOffsetAfter.call(this)); var g = this.snapGrid.length, b = this.snapGrid.length, w = e.spaceBetween, y = -f, x = 0, T = 0; if (void 0 !== s) { var E, S; "string" == typeof w && w.indexOf("%") >= 0 && (w = parseFloat(w.replace("%", "")) / 100 * s), this.virtualSize = -w, a ? d.css({ marginLeft: "", marginTop: "" }) : d.css({ marginRight: "", marginBottom: "" }), e.slidesPerColumn > 1 && (E = Math.floor(h / e.slidesPerColumn) === h / this.params.slidesPerColumn ? h : Math.ceil(h / e.slidesPerColumn) * e.slidesPerColumn, "auto" !== e.slidesPerView && "row" === e.slidesPerColumnFill && (E = Math.max(E, e.slidesPerView * e.slidesPerColumn))); for (var C, M = e.slidesPerColumn, P = E / M, z = Math.floor(h / e.slidesPerColumn), k = 0; k < h; k += 1) { S = 0; var $ = d.eq(k); if (e.slidesPerColumn > 1) { var L = void 0, I = void 0, D = void 0; if ("row" === e.slidesPerColumnFill && e.slidesPerGroup > 1) { var O = Math.floor(k / (e.slidesPerGroup * e.slidesPerColumn)), A = k - e.slidesPerColumn * e.slidesPerGroup * O, G = 0 === O ? e.slidesPerGroup : Math.min(Math.ceil((h - O * M * e.slidesPerGroup) / M), e.slidesPerGroup); L = (I = A - (D = Math.floor(A / G)) * G + O * e.slidesPerGroup) + D * E / M, $.css({ "-webkit-box-ordinal-group": L, "-moz-box-ordinal-group": L, "-ms-flex-order": L, "-webkit-order": L, order: L }) } else "column" === e.slidesPerColumnFill ? (D = k - (I = Math.floor(k / M)) * M, (I > z || I === z && D === M - 1) && (D += 1) >= M && (D = 0, I += 1)) : I = k - (D = Math.floor(k / P)) * P; $.css("margin-" + (this.isHorizontal() ? "top" : "left"), 0 !== D && e.spaceBetween && e.spaceBetween + "px") } if ("none" !== $.css("display")) { if ("auto" === e.slidesPerView) { var H = t.getComputedStyle($[0], null), B = $[0].style.transform, N = $[0].style.webkitTransform; if (B && ($[0].style.transform = "none"), N && ($[0].style.webkitTransform = "none"), e.roundLengths) S = this.isHorizontal() ? $.outerWidth(!0) : $.outerHeight(!0); else if (this.isHorizontal()) { var X = parseFloat(H.getPropertyValue("width")), V = parseFloat(H.getPropertyValue("padding-left")), Y = parseFloat(H.getPropertyValue("padding-right")), F = parseFloat(H.getPropertyValue("margin-left")), W = parseFloat(H.getPropertyValue("margin-right")), R = H.getPropertyValue("box-sizing"); S = R && "border-box" === R ? X + F + W : X + V + Y + F + W } else { var q = parseFloat(H.getPropertyValue("height")), j = parseFloat(H.getPropertyValue("padding-top")), K = parseFloat(H.getPropertyValue("padding-bottom")), U = parseFloat(H.getPropertyValue("margin-top")), _ = parseFloat(H.getPropertyValue("margin-bottom")), Z = H.getPropertyValue("box-sizing"); S = Z && "border-box" === Z ? q + U + _ : q + j + K + U + _ } B && ($[0].style.transform = B), N && ($[0].style.webkitTransform = N), e.roundLengths && (S = Math.floor(S)) } else S = (s - (e.slidesPerView - 1) * w) / e.slidesPerView, e.roundLengths && (S = Math.floor(S)), d[k] && (this.isHorizontal() ? d[k].style.width = S + "px" : d[k].style.height = S + "px"); d[k] && (d[k].swiperSlideSize = S), u.push(S), e.centeredSlides ? (y = y + S / 2 + x / 2 + w, 0 === x && 0 !== k && (y = y - s / 2 - w), 0 === k && (y = y - s / 2 - w), Math.abs(y) < .001 && (y = 0), e.roundLengths && (y = Math.floor(y)), T % e.slidesPerGroup == 0 && p.push(y), c.push(y)) : (e.roundLengths && (y = Math.floor(y)), (T - Math.min(this.params.slidesPerGroupSkip, T)) % this.params.slidesPerGroup == 0 && p.push(y), c.push(y), y = y + S + w), this.virtualSize += S + w, x = S, T += 1 } } if (this.virtualSize = Math.max(this.virtualSize, s) + m, a && r && ("slide" === e.effect || "coverflow" === e.effect) && i.css({ width: this.virtualSize + e.spaceBetween + "px" }), e.setWrapperSize && (this.isHorizontal() ? i.css({ width: this.virtualSize + e.spaceBetween + "px" }) : i.css({ height: this.virtualSize + e.spaceBetween + "px" })), e.slidesPerColumn > 1 && (this.virtualSize = (S + e.spaceBetween) * E, this.virtualSize = Math.ceil(this.virtualSize / e.slidesPerColumn) - e.spaceBetween, this.isHorizontal() ? i.css({ width: this.virtualSize + e.spaceBetween + "px" }) : i.css({ height: this.virtualSize + e.spaceBetween + "px" }), e.centeredSlides)) { C = []; for (var Q = 0; Q < p.length; Q += 1) { var J = p[Q]; e.roundLengths && (J = Math.floor(J)), p[Q] < this.virtualSize + p[0] && C.push(J) } p = C } if (!e.centeredSlides) { C = []; for (var ee = 0; ee < p.length; ee += 1) { var te = p[ee]; e.roundLengths && (te = Math.floor(te)), p[ee] <= this.virtualSize - s && C.push(te) } p = C, Math.floor(this.virtualSize - s) - Math.floor(p[p.length - 1]) > 1 && p.push(this.virtualSize - s) } if (0 === p.length && (p = [0]), 0 !== e.spaceBetween && (this.isHorizontal() ? a ? d.filter(v).css({ marginLeft: w + "px" }) : d.filter(v).css({ marginRight: w + "px" }) : d.filter(v).css({ marginBottom: w + "px" })), e.centeredSlides && e.centeredSlidesBounds) { var ie = 0; u.forEach((function (t) { ie += t + (e.spaceBetween ? e.spaceBetween : 0) })); var se = (ie -= e.spaceBetween) - s; p = p.map((function (e) { return e < 0 ? -f : e > se ? se + m : e })) } if (e.centerInsufficientSlides) { var ae = 0; if (u.forEach((function (t) { ae += t + (e.spaceBetween ? e.spaceBetween : 0) })), (ae -= e.spaceBetween) < s) { var re = (s - ae) / 2; p.forEach((function (e, t) { p[t] = e - re })), c.forEach((function (e, t) { c[t] = e + re })) } } n.extend(this, { slides: d, snapGrid: p, slidesGrid: c, slidesSizesGrid: u }), h !== l && this.emit("slidesLengthChange"), p.length !== g && (this.params.watchOverflow && this.checkOverflow(), this.emit("snapGridLengthChange")), c.length !== b && this.emit("slidesGridLengthChange"), (e.watchSlidesProgress || e.watchSlidesVisibility) && this.updateSlidesOffset() } }, updateAutoHeight: function (e) { var t, i = [], s = 0; if ("number" == typeof e ? this.setTransition(e) : !0 === e && this.setTransition(this.params.speed), "auto" !== this.params.slidesPerView && this.params.slidesPerView > 1) if (this.params.centeredSlides) this.visibleSlides.each((function (e, t) { i.push(t) })); else for (t = 0; t < Math.ceil(this.params.slidesPerView); t += 1) { var a = this.activeIndex + t; if (a > this.slides.length) break; i.push(this.slides.eq(a)[0]) } else i.push(this.slides.eq(this.activeIndex)[0]); for (t = 0; t < i.length; t += 1)if (void 0 !== i[t]) { var r = i[t].offsetHeight; s = r > s ? r : s } s && this.$wrapperEl.css("height", s + "px") }, updateSlidesOffset: function () { for (var e = this.slides, t = 0; t < e.length; t += 1)e[t].swiperSlideOffset = this.isHorizontal() ? e[t].offsetLeft : e[t].offsetTop }, updateSlidesProgress: function (e) { void 0 === e && (e = this && this.translate || 0); var t = this.params, i = this.slides, a = this.rtlTranslate; if (0 !== i.length) { void 0 === i[0].swiperSlideOffset && this.updateSlidesOffset(); var r = -e; a && (r = e), i.removeClass(t.slideVisibleClass), this.visibleSlidesIndexes = [], this.visibleSlides = []; for (var n = 0; n < i.length; n += 1) { var o = i[n], l = (r + (t.centeredSlides ? this.minTranslate() : 0) - o.swiperSlideOffset) / (o.swiperSlideSize + t.spaceBetween); if (t.watchSlidesVisibility || t.centeredSlides && t.autoHeight) { var d = -(r - o.swiperSlideOffset), h = d + this.slidesSizesGrid[n]; (d >= 0 && d < this.size - 1 || h > 1 && h <= this.size || d <= 0 && h >= this.size) && (this.visibleSlides.push(o), this.visibleSlidesIndexes.push(n), i.eq(n).addClass(t.slideVisibleClass)) } o.progress = a ? -l : l } this.visibleSlides = s(this.visibleSlides) } }, updateProgress: function (e) { if (void 0 === e) { var t = this.rtlTranslate ? -1 : 1; e = this && this.translate && this.translate * t || 0 } var i = this.params, s = this.maxTranslate() - this.minTranslate(), a = this.progress, r = this.isBeginning, o = this.isEnd, l = r, d = o; 0 === s ? (a = 0, r = !0, o = !0) : (r = (a = (e - this.minTranslate()) / s) <= 0, o = a >= 1), n.extend(this, { progress: a, isBeginning: r, isEnd: o }), (i.watchSlidesProgress || i.watchSlidesVisibility || i.centeredSlides && i.autoHeight) && this.updateSlidesProgress(e), r && !l && this.emit("reachBeginning toEdge"), o && !d && this.emit("reachEnd toEdge"), (l && !r || d && !o) && this.emit("fromEdge"), this.emit("progress", a) }, updateSlidesClasses: function () { var e, t = this.slides, i = this.params, s = this.$wrapperEl, a = this.activeIndex, r = this.realIndex, n = this.virtual && i.virtual.enabled; t.removeClass(i.slideActiveClass + " " + i.slideNextClass + " " + i.slidePrevClass + " " + i.slideDuplicateActiveClass + " " + i.slideDuplicateNextClass + " " + i.slideDuplicatePrevClass), (e = n ? this.$wrapperEl.find("." + i.slideClass + '[data-swiper-slide-index="' + a + '"]') : t.eq(a)).addClass(i.slideActiveClass), i.loop && (e.hasClass(i.slideDuplicateClass) ? s.children("." + i.slideClass + ":not(." + i.slideDuplicateClass + ')[data-swiper-slide-index="' + r + '"]').addClass(i.slideDuplicateActiveClass) : s.children("." + i.slideClass + "." + i.slideDuplicateClass + '[data-swiper-slide-index="' + r + '"]').addClass(i.slideDuplicateActiveClass)); var o = e.nextAll("." + i.slideClass).eq(0).addClass(i.slideNextClass); i.loop && 0 === o.length && (o = t.eq(0)).addClass(i.slideNextClass); var l = e.prevAll("." + i.slideClass).eq(0).addClass(i.slidePrevClass); i.loop && 0 === l.length && (l = t.eq(-1)).addClass(i.slidePrevClass), i.loop && (o.hasClass(i.slideDuplicateClass) ? s.children("." + i.slideClass + ":not(." + i.slideDuplicateClass + ')[data-swiper-slide-index="' + o.attr("data-swiper-slide-index") + '"]').addClass(i.slideDuplicateNextClass) : s.children("." + i.slideClass + "." + i.slideDuplicateClass + '[data-swiper-slide-index="' + o.attr("data-swiper-slide-index") + '"]').addClass(i.slideDuplicateNextClass), l.hasClass(i.slideDuplicateClass) ? s.children("." + i.slideClass + ":not(." + i.slideDuplicateClass + ')[data-swiper-slide-index="' + l.attr("data-swiper-slide-index") + '"]').addClass(i.slideDuplicatePrevClass) : s.children("." + i.slideClass + "." + i.slideDuplicateClass + '[data-swiper-slide-index="' + l.attr("data-swiper-slide-index") + '"]').addClass(i.slideDuplicatePrevClass)) }, updateActiveIndex: function (e) { var t, i = this.rtlTranslate ? this.translate : -this.translate, s = this.slidesGrid, a = this.snapGrid, r = this.params, o = this.activeIndex, l = this.realIndex, d = this.snapIndex, h = e; if (void 0 === h) { for (var p = 0; p < s.length; p += 1)void 0 !== s[p + 1] ? i >= s[p] && i < s[p + 1] - (s[p + 1] - s[p]) / 2 ? h = p : i >= s[p] && i < s[p + 1] && (h = p + 1) : i >= s[p] && (h = p); r.normalizeSlideIndex && (h < 0 || void 0 === h) && (h = 0) } if (a.indexOf(i) >= 0) t = a.indexOf(i); else { var c = Math.min(r.slidesPerGroupSkip, h); t = c + Math.floor((h - c) / r.slidesPerGroup) } if (t >= a.length && (t = a.length - 1), h !== o) { var u = parseInt(this.slides.eq(h).attr("data-swiper-slide-index") || h, 10); n.extend(this, { snapIndex: t, realIndex: u, previousIndex: o, activeIndex: h }), this.emit("activeIndexChange"), this.emit("snapIndexChange"), l !== u && this.emit("realIndexChange"), (this.initialized || this.params.runCallbacksOnInit) && this.emit("slideChange") } else t !== d && (this.snapIndex = t, this.emit("snapIndexChange")) }, updateClickedSlide: function (e) { var t = this.params, i = s(e.target).closest("." + t.slideClass)[0], a = !1; if (i) for (var r = 0; r < this.slides.length; r += 1)this.slides[r] === i && (a = !0); if (!i || !a) return this.clickedSlide = void 0, void (this.clickedIndex = void 0); this.clickedSlide = i, this.virtual && this.params.virtual.enabled ? this.clickedIndex = parseInt(s(i).attr("data-swiper-slide-index"), 10) : this.clickedIndex = s(i).index(), t.slideToClickedSlide && void 0 !== this.clickedIndex && this.clickedIndex !== this.activeIndex && this.slideToClickedSlide() } }; var p = { getTranslate: function (e) { void 0 === e && (e = this.isHorizontal() ? "x" : "y"); var t = this.params, i = this.rtlTranslate, s = this.translate, a = this.$wrapperEl; if (t.virtualTranslate) return i ? -s : s; if (t.cssMode) return s; var r = n.getTranslate(a[0], e); return i && (r = -r), r || 0 }, setTranslate: function (e, t) { var i = this.rtlTranslate, s = this.params, a = this.$wrapperEl, r = this.wrapperEl, n = this.progress, o = 0, l = 0; this.isHorizontal() ? o = i ? -e : e : l = e, s.roundLengths && (o = Math.floor(o), l = Math.floor(l)), s.cssMode ? r[this.isHorizontal() ? "scrollLeft" : "scrollTop"] = this.isHorizontal() ? -o : -l : s.virtualTranslate || a.transform("translate3d(" + o + "px, " + l + "px, 0px)"), this.previousTranslate = this.translate, this.translate = this.isHorizontal() ? o : l; var d = this.maxTranslate() - this.minTranslate(); (0 === d ? 0 : (e - this.minTranslate()) / d) !== n && this.updateProgress(e), this.emit("setTranslate", this.translate, t) }, minTranslate: function () { return -this.snapGrid[0] }, maxTranslate: function () { return -this.snapGrid[this.snapGrid.length - 1] }, translateTo: function (e, t, i, s, a) { var r; void 0 === e && (e = 0), void 0 === t && (t = this.params.speed), void 0 === i && (i = !0), void 0 === s && (s = !0); var n = this, o = n.params, l = n.wrapperEl; if (n.animating && o.preventInteractionOnTransition) return !1; var d, h = n.minTranslate(), p = n.maxTranslate(); if (d = s && e > h ? h : s && e < p ? p : e, n.updateProgress(d), o.cssMode) { var c = n.isHorizontal(); return 0 === t ? l[c ? "scrollLeft" : "scrollTop"] = -d : l.scrollTo ? l.scrollTo(((r = {})[c ? "left" : "top"] = -d, r.behavior = "smooth", r)) : l[c ? "scrollLeft" : "scrollTop"] = -d, !0 } return 0 === t ? (n.setTransition(0), n.setTranslate(d), i && (n.emit("beforeTransitionStart", t, a), n.emit("transitionEnd"))) : (n.setTransition(t), n.setTranslate(d), i && (n.emit("beforeTransitionStart", t, a), n.emit("transitionStart")), n.animating || (n.animating = !0, n.onTranslateToWrapperTransitionEnd || (n.onTranslateToWrapperTransitionEnd = function (e) { n && !n.destroyed && e.target === this && (n.$wrapperEl[0].removeEventListener("transitionend", n.onTranslateToWrapperTransitionEnd), n.$wrapperEl[0].removeEventListener("webkitTransitionEnd", n.onTranslateToWrapperTransitionEnd), n.onTranslateToWrapperTransitionEnd = null, delete n.onTranslateToWrapperTransitionEnd, i && n.emit("transitionEnd")) }), n.$wrapperEl[0].addEventListener("transitionend", n.onTranslateToWrapperTransitionEnd), n.$wrapperEl[0].addEventListener("webkitTransitionEnd", n.onTranslateToWrapperTransitionEnd))), !0 } }; var c = { setTransition: function (e, t) { this.params.cssMode || this.$wrapperEl.transition(e), this.emit("setTransition", e, t) }, transitionStart: function (e, t) { void 0 === e && (e = !0); var i = this.activeIndex, s = this.params, a = this.previousIndex; if (!s.cssMode) { s.autoHeight && this.updateAutoHeight(); var r = t; if (r || (r = i > a ? "next" : i < a ? "prev" : "reset"), this.emit("transitionStart"), e && i !== a) { if ("reset" === r) return void this.emit("slideResetTransitionStart"); this.emit("slideChangeTransitionStart"), "next" === r ? this.emit("slideNextTransitionStart") : this.emit("slidePrevTransitionStart") } } }, transitionEnd: function (e, t) { void 0 === e && (e = !0); var i = this.activeIndex, s = this.previousIndex, a = this.params; if (this.animating = !1, !a.cssMode) { this.setTransition(0); var r = t; if (r || (r = i > s ? "next" : i < s ? "prev" : "reset"), this.emit("transitionEnd"), e && i !== s) { if ("reset" === r) return void this.emit("slideResetTransitionEnd"); this.emit("slideChangeTransitionEnd"), "next" === r ? this.emit("slideNextTransitionEnd") : this.emit("slidePrevTransitionEnd") } } } }; var u = { slideTo: function (e, t, i, s) { var a; void 0 === e && (e = 0), void 0 === t && (t = this.params.speed), void 0 === i && (i = !0); var r = this, n = e; n < 0 && (n = 0); var o = r.params, l = r.snapGrid, d = r.slidesGrid, h = r.previousIndex, p = r.activeIndex, c = r.rtlTranslate, u = r.wrapperEl; if (r.animating && o.preventInteractionOnTransition) return !1; var v = Math.min(r.params.slidesPerGroupSkip, n), f = v + Math.floor((n - v) / r.params.slidesPerGroup); f >= l.length && (f = l.length - 1), (p || o.initialSlide || 0) === (h || 0) && i && r.emit("beforeSlideChangeStart"); var m, g = -l[f]; if (r.updateProgress(g), o.normalizeSlideIndex) for (var b = 0; b < d.length; b += 1)-Math.floor(100 * g) >= Math.floor(100 * d[b]) && (n = b); if (r.initialized && n !== p) { if (!r.allowSlideNext && g < r.translate && g < r.minTranslate()) return !1; if (!r.allowSlidePrev && g > r.translate && g > r.maxTranslate() && (p || 0) !== n) return !1 } if (m = n > p ? "next" : n < p ? "prev" : "reset", c && -g === r.translate || !c && g === r.translate) return r.updateActiveIndex(n), o.autoHeight && r.updateAutoHeight(), r.updateSlidesClasses(), "slide" !== o.effect && r.setTranslate(g), "reset" !== m && (r.transitionStart(i, m), r.transitionEnd(i, m)), !1; if (o.cssMode) { var w = r.isHorizontal(), y = -g; return c && (y = u.scrollWidth - u.offsetWidth - y), 0 === t ? u[w ? "scrollLeft" : "scrollTop"] = y : u.scrollTo ? u.scrollTo(((a = {})[w ? "left" : "top"] = y, a.behavior = "smooth", a)) : u[w ? "scrollLeft" : "scrollTop"] = y, !0 } return 0 === t ? (r.setTransition(0), r.setTranslate(g), r.updateActiveIndex(n), r.updateSlidesClasses(), r.emit("beforeTransitionStart", t, s), r.transitionStart(i, m), r.transitionEnd(i, m)) : (r.setTransition(t), r.setTranslate(g), r.updateActiveIndex(n), r.updateSlidesClasses(), r.emit("beforeTransitionStart", t, s), r.transitionStart(i, m), r.animating || (r.animating = !0, r.onSlideToWrapperTransitionEnd || (r.onSlideToWrapperTransitionEnd = function (e) { r && !r.destroyed && e.target === this && (r.$wrapperEl[0].removeEventListener("transitionend", r.onSlideToWrapperTransitionEnd), r.$wrapperEl[0].removeEventListener("webkitTransitionEnd", r.onSlideToWrapperTransitionEnd), r.onSlideToWrapperTransitionEnd = null, delete r.onSlideToWrapperTransitionEnd, r.transitionEnd(i, m)) }), r.$wrapperEl[0].addEventListener("transitionend", r.onSlideToWrapperTransitionEnd), r.$wrapperEl[0].addEventListener("webkitTransitionEnd", r.onSlideToWrapperTransitionEnd))), !0 }, slideToLoop: function (e, t, i, s) { void 0 === e && (e = 0), void 0 === t && (t = this.params.speed), void 0 === i && (i = !0); var a = e; return this.params.loop && (a += this.loopedSlides), this.slideTo(a, t, i, s) }, slideNext: function (e, t, i) { void 0 === e && (e = this.params.speed), void 0 === t && (t = !0); var s = this.params, a = this.animating, r = this.activeIndex < s.slidesPerGroupSkip ? 1 : s.slidesPerGroup; if (s.loop) { if (a) return !1; this.loopFix(), this._clientLeft = this.$wrapperEl[0].clientLeft } return this.slideTo(this.activeIndex + r, e, t, i) }, slidePrev: function (e, t, i) { void 0 === e && (e = this.params.speed), void 0 === t && (t = !0); var s = this.params, a = this.animating, r = this.snapGrid, n = this.slidesGrid, o = this.rtlTranslate; if (s.loop) { if (a) return !1; this.loopFix(), this._clientLeft = this.$wrapperEl[0].clientLeft } function l(e) { return e < 0 ? -Math.floor(Math.abs(e)) : Math.floor(e) } var d, h = l(o ? this.translate : -this.translate), p = r.map((function (e) { return l(e) })), c = (n.map((function (e) { return l(e) })), r[p.indexOf(h)], r[p.indexOf(h) - 1]); return void 0 === c && s.cssMode && r.forEach((function (e) { !c && h >= e && (c = e) })), void 0 !== c && (d = n.indexOf(c)) < 0 && (d = this.activeIndex - 1), this.slideTo(d, e, t, i) }, slideReset: function (e, t, i) { return void 0 === e && (e = this.params.speed), void 0 === t && (t = !0), this.slideTo(this.activeIndex, e, t, i) }, slideToClosest: function (e, t, i, s) { void 0 === e && (e = this.params.speed), void 0 === t && (t = !0), void 0 === s && (s = .5); var a = this.activeIndex, r = Math.min(this.params.slidesPerGroupSkip, a), n = r + Math.floor((a - r) / this.params.slidesPerGroup), o = this.rtlTranslate ? this.translate : -this.translate; if (o >= this.snapGrid[n]) { var l = this.snapGrid[n]; o - l > (this.snapGrid[n + 1] - l) * s && (a += this.params.slidesPerGroup) } else { var d = this.snapGrid[n - 1]; o - d <= (this.snapGrid[n] - d) * s && (a -= this.params.slidesPerGroup) } return a = Math.max(a, 0), a = Math.min(a, this.slidesGrid.length - 1), this.slideTo(a, e, t, i) }, slideToClickedSlide: function () { var e, t = this, i = t.params, a = t.$wrapperEl, r = "auto" === i.slidesPerView ? t.slidesPerViewDynamic() : i.slidesPerView, o = t.clickedIndex; if (i.loop) { if (t.animating) return; e = parseInt(s(t.clickedSlide).attr("data-swiper-slide-index"), 10), i.centeredSlides ? o < t.loopedSlides - r / 2 || o > t.slides.length - t.loopedSlides + r / 2 ? (t.loopFix(), o = a.children("." + i.slideClass + '[data-swiper-slide-index="' + e + '"]:not(.' + i.slideDuplicateClass + ")").eq(0).index(), n.nextTick((function () { t.slideTo(o) }))) : t.slideTo(o) : o > t.slides.length - r ? (t.loopFix(), o = a.children("." + i.slideClass + '[data-swiper-slide-index="' + e + '"]:not(.' + i.slideDuplicateClass + ")").eq(0).index(), n.nextTick((function () { t.slideTo(o) }))) : t.slideTo(o) } else t.slideTo(o) } }; var v = { loopCreate: function () { var t = this, i = t.params, a = t.$wrapperEl; a.children("." + i.slideClass + "." + i.slideDuplicateClass).remove(); var r = a.children("." + i.slideClass); if (i.loopFillGroupWithBlank) { var n = i.slidesPerGroup - r.length % i.slidesPerGroup; if (n !== i.slidesPerGroup) { for (var o = 0; o < n; o += 1) { var l = s(e.createElement("div")).addClass(i.slideClass + " " + i.slideBlankClass); a.append(l) } r = a.children("." + i.slideClass) } } "auto" !== i.slidesPerView || i.loopedSlides || (i.loopedSlides = r.length), t.loopedSlides = Math.ceil(parseFloat(i.loopedSlides || i.slidesPerView, 10)), t.loopedSlides += i.loopAdditionalSlides, t.loopedSlides > r.length && (t.loopedSlides = r.length); var d = [], h = []; r.each((function (e, i) { var a = s(i); e < t.loopedSlides && h.push(i), e < r.length && e >= r.length - t.loopedSlides && d.push(i), a.attr("data-swiper-slide-index", e) })); for (var p = 0; p < h.length; p += 1)a.append(s(h[p].cloneNode(!0)).addClass(i.slideDuplicateClass)); for (var c = d.length - 1; c >= 0; c -= 1)a.prepend(s(d[c].cloneNode(!0)).addClass(i.slideDuplicateClass)) }, loopFix: function () { this.emit("beforeLoopFix"); var e, t = this.activeIndex, i = this.slides, s = this.loopedSlides, a = this.allowSlidePrev, r = this.allowSlideNext, n = this.snapGrid, o = this.rtlTranslate; this.allowSlidePrev = !0, this.allowSlideNext = !0; var l = -n[t] - this.getTranslate(); if (t < s) e = i.length - 3 * s + t, e += s, this.slideTo(e, 0, !1, !0) && 0 !== l && this.setTranslate((o ? -this.translate : this.translate) - l); else if (t >= i.length - s) { e = -i.length + t + s, e += s, this.slideTo(e, 0, !1, !0) && 0 !== l && this.setTranslate((o ? -this.translate : this.translate) - l) } this.allowSlidePrev = a, this.allowSlideNext = r, this.emit("loopFix") }, loopDestroy: function () { var e = this.$wrapperEl, t = this.params, i = this.slides; e.children("." + t.slideClass + "." + t.slideDuplicateClass + ",." + t.slideClass + "." + t.slideBlankClass).remove(), i.removeAttr("data-swiper-slide-index") } }; var f = { setGrabCursor: function (e) { if (!(o.touch || !this.params.simulateTouch || this.params.watchOverflow && this.isLocked || this.params.cssMode)) { var t = this.el; t.style.cursor = "move", t.style.cursor = e ? "-webkit-grabbing" : "-webkit-grab", t.style.cursor = e ? "-moz-grabbin" : "-moz-grab", t.style.cursor = e ? "grabbing" : "grab" } }, unsetGrabCursor: function () { o.touch || this.params.watchOverflow && this.isLocked || this.params.cssMode || (this.el.style.cursor = "") } }; var m, g, b, w, y, x, T, E, S, C, M, P, z, k, $, L = { appendSlide: function (e) { var t = this.$wrapperEl, i = this.params; if (i.loop && this.loopDestroy(), "object" == typeof e && "length" in e) for (var s = 0; s < e.length; s += 1)e[s] && t.append(e[s]); else t.append(e); i.loop && this.loopCreate(), i.observer && o.observer || this.update() }, prependSlide: function (e) { var t = this.params, i = this.$wrapperEl, s = this.activeIndex; t.loop && this.loopDestroy(); var a = s + 1; if ("object" == typeof e && "length" in e) { for (var r = 0; r < e.length; r += 1)e[r] && i.prepend(e[r]); a = s + e.length } else i.prepend(e); t.loop && this.loopCreate(), t.observer && o.observer || this.update(), this.slideTo(a, 0, !1) }, addSlide: function (e, t) { var i = this.$wrapperEl, s = this.params, a = this.activeIndex; s.loop && (a -= this.loopedSlides, this.loopDestroy(), this.slides = i.children("." + s.slideClass)); var r = this.slides.length; if (e <= 0) this.prependSlide(t); else if (e >= r) this.appendSlide(t); else { for (var n = a > e ? a + 1 : a, l = [], d = r - 1; d >= e; d -= 1) { var h = this.slides.eq(d); h.remove(), l.unshift(h) } if ("object" == typeof t && "length" in t) { for (var p = 0; p < t.length; p += 1)t[p] && i.append(t[p]); n = a > e ? a + t.length : a } else i.append(t); for (var c = 0; c < l.length; c += 1)i.append(l[c]); s.loop && this.loopCreate(), s.observer && o.observer || this.update(), s.loop ? this.slideTo(n + this.loopedSlides, 0, !1) : this.slideTo(n, 0, !1) } }, removeSlide: function (e) { var t = this.params, i = this.$wrapperEl, s = this.activeIndex; t.loop && (s -= this.loopedSlides, this.loopDestroy(), this.slides = i.children("." + t.slideClass)); var a, r = s; if ("object" == typeof e && "length" in e) { for (var n = 0; n < e.length; n += 1)a = e[n], this.slides[a] && this.slides.eq(a).remove(), a < r && (r -= 1); r = Math.max(r, 0) } else a = e, this.slides[a] && this.slides.eq(a).remove(), a < r && (r -= 1), r = Math.max(r, 0); t.loop && this.loopCreate(), t.observer && o.observer || this.update(), t.loop ? this.slideTo(r + this.loopedSlides, 0, !1) : this.slideTo(r, 0, !1) }, removeAllSlides: function () { for (var e = [], t = 0; t < this.slides.length; t += 1)e.push(t); this.removeSlide(e) } }, I = (m = t.navigator.platform, g = t.navigator.userAgent, b = { ios: !1, android: !1, androidChrome: !1, desktop: !1, iphone: !1, ipod: !1, ipad: !1, edge: !1, ie: !1, firefox: !1, macos: !1, windows: !1, cordova: !(!t.cordova && !t.phonegap), phonegap: !(!t.cordova && !t.phonegap), electron: !1 }, w = t.screen.width, y = t.screen.height, x = g.match(/(Android);?[\s\/]+([\d.]+)?/), T = g.match(/(iPad).*OS\s([\d_]+)/), E = g.match(/(iPod)(.*OS\s([\d_]+))?/), S = !T && g.match(/(iPhone\sOS|iOS)\s([\d_]+)/), C = g.indexOf("MSIE ") >= 0 || g.indexOf("Trident/") >= 0, M = g.indexOf("Edge/") >= 0, P = g.indexOf("Gecko/") >= 0 && g.indexOf("Firefox/") >= 0, z = "Win32" === m, k = g.toLowerCase().indexOf("electron") >= 0, $ = "MacIntel" === m, !T && $ && o.touch && (1024 === w && 1366 === y || 834 === w && 1194 === y || 834 === w && 1112 === y || 768 === w && 1024 === y) && (T = g.match(/(Version)\/([\d.]+)/), $ = !1), b.ie = C, b.edge = M, b.firefox = P, x && !z && (b.os = "android", b.osVersion = x[2], b.android = !0, b.androidChrome = g.toLowerCase().indexOf("chrome") >= 0), (T || S || E) && (b.os = "ios", b.ios = !0), S && !E && (b.osVersion = S[2].replace(/_/g, "."), b.iphone = !0), T && (b.osVersion = T[2].replace(/_/g, "."), b.ipad = !0), E && (b.osVersion = E[3] ? E[3].replace(/_/g, ".") : null, b.ipod = !0), b.ios && b.osVersion && g.indexOf("Version/") >= 0 && "10" === b.osVersion.split(".")[0] && (b.osVersion = g.toLowerCase().split("version/")[1].split(" ")[0]), b.webView = !(!(S || T || E) || !g.match(/.*AppleWebKit(?!.*Safari)/i) && !t.navigator.standalone) || t.matchMedia && t.matchMedia("(display-mode: standalone)").matches, b.webview = b.webView, b.standalone = b.webView, b.desktop = !(b.ios || b.android) || k, b.desktop && (b.electron = k, b.macos = $, b.windows = z, b.macos && (b.os = "macos"), b.windows && (b.os = "windows")), b.pixelRatio = t.devicePixelRatio || 1, b); function D(i) { var a = this.touchEventsData, r = this.params, o = this.touches; if (!this.animating || !r.preventInteractionOnTransition) { var l = i; l.originalEvent && (l = l.originalEvent); var d = s(l.target); if (("wrapper" !== r.touchEventsTarget || d.closest(this.wrapperEl).length) && (a.isTouchEvent = "touchstart" === l.type, (a.isTouchEvent || !("which" in l) || 3 !== l.which) && !(!a.isTouchEvent && "button" in l && l.button > 0 || a.isTouched && a.isMoved))) if (r.noSwiping && d.closest(r.noSwipingSelector ? r.noSwipingSelector : "." + r.noSwipingClass)[0]) this.allowClick = !0; else if (!r.swipeHandler || d.closest(r.swipeHandler)[0]) { o.currentX = "touchstart" === l.type ? l.targetTouches[0].pageX : l.pageX, o.currentY = "touchstart" === l.type ? l.targetTouches[0].pageY : l.pageY; var h = o.currentX, p = o.currentY, c = r.edgeSwipeDetection || r.iOSEdgeSwipeDetection, u = r.edgeSwipeThreshold || r.iOSEdgeSwipeThreshold; if (!c || !(h <= u || h >= t.screen.width - u)) { if (n.extend(a, { isTouched: !0, isMoved: !1, allowTouchCallbacks: !0, isScrolling: void 0, startMoving: void 0 }), o.startX = h, o.startY = p, a.touchStartTime = n.now(), this.allowClick = !0, this.updateSize(), this.swipeDirection = void 0, r.threshold > 0 && (a.allowThresholdMove = !1), "touchstart" !== l.type) { var v = !0; d.is(a.formElements) && (v = !1), e.activeElement && s(e.activeElement).is(a.formElements) && e.activeElement !== d[0] && e.activeElement.blur(); var f = v && this.allowTouchMove && r.touchStartPreventDefault; (r.touchStartForcePreventDefault || f) && l.preventDefault() } this.emit("touchStart", l) } } } } function O(t) { var i = this.touchEventsData, a = this.params, r = this.touches, o = this.rtlTranslate, l = t; if (l.originalEvent && (l = l.originalEvent), i.isTouched) { if (!i.isTouchEvent || "mousemove" !== l.type) { var d = "touchmove" === l.type && l.targetTouches && (l.targetTouches[0] || l.changedTouches[0]), h = "touchmove" === l.type ? d.pageX : l.pageX, p = "touchmove" === l.type ? d.pageY : l.pageY; if (l.preventedByNestedSwiper) return r.startX = h, void (r.startY = p); if (!this.allowTouchMove) return this.allowClick = !1, void (i.isTouched && (n.extend(r, { startX: h, startY: p, currentX: h, currentY: p }), i.touchStartTime = n.now())); if (i.isTouchEvent && a.touchReleaseOnEdges && !a.loop) if (this.isVertical()) { if (p < r.startY && this.translate <= this.maxTranslate() || p > r.startY && this.translate >= this.minTranslate()) return i.isTouched = !1, void (i.isMoved = !1) } else if (h < r.startX && this.translate <= this.maxTranslate() || h > r.startX && this.translate >= this.minTranslate()) return; if (i.isTouchEvent && e.activeElement && l.target === e.activeElement && s(l.target).is(i.formElements)) return i.isMoved = !0, void (this.allowClick = !1); if (i.allowTouchCallbacks && this.emit("touchMove", l), !(l.targetTouches && l.targetTouches.length > 1)) { r.currentX = h, r.currentY = p; var c = r.currentX - r.startX, u = r.currentY - r.startY; if (!(this.params.threshold && Math.sqrt(Math.pow(c, 2) + Math.pow(u, 2)) < this.params.threshold)) { var v; if (void 0 === i.isScrolling) this.isHorizontal() && r.currentY === r.startY || this.isVertical() && r.currentX === r.startX ? i.isScrolling = !1 : c * c + u * u >= 25 && (v = 180 * Math.atan2(Math.abs(u), Math.abs(c)) / Math.PI, i.isScrolling = this.isHorizontal() ? v > a.touchAngle : 90 - v > a.touchAngle); if (i.isScrolling && this.emit("touchMoveOpposite", l), void 0 === i.startMoving && (r.currentX === r.startX && r.currentY === r.startY || (i.startMoving = !0)), i.isScrolling) i.isTouched = !1; else if (i.startMoving) { this.allowClick = !1, a.cssMode || l.preventDefault(), a.touchMoveStopPropagation && !a.nested && l.stopPropagation(), i.isMoved || (a.loop && this.loopFix(), i.startTranslate = this.getTranslate(), this.setTransition(0), this.animating && this.$wrapperEl.trigger("webkitTransitionEnd transitionend"), i.allowMomentumBounce = !1, !a.grabCursor || !0 !== this.allowSlideNext && !0 !== this.allowSlidePrev || this.setGrabCursor(!0), this.emit("sliderFirstMove", l)), this.emit("sliderMove", l), i.isMoved = !0; var f = this.isHorizontal() ? c : u; r.diff = f, f *= a.touchRatio, o && (f = -f), this.swipeDirection = f > 0 ? "prev" : "next", i.currentTranslate = f + i.startTranslate; var m = !0, g = a.resistanceRatio; if (a.touchReleaseOnEdges && (g = 0), f > 0 && i.currentTranslate > this.minTranslate() ? (m = !1, a.resistance && (i.currentTranslate = this.minTranslate() - 1 + Math.pow(-this.minTranslate() + i.startTranslate + f, g))) : f < 0 && i.currentTranslate < this.maxTranslate() && (m = !1, a.resistance && (i.currentTranslate = this.maxTranslate() + 1 - Math.pow(this.maxTranslate() - i.startTranslate - f, g))), m && (l.preventedByNestedSwiper = !0), !this.allowSlideNext && "next" === this.swipeDirection && i.currentTranslate < i.startTranslate && (i.currentTranslate = i.startTranslate), !this.allowSlidePrev && "prev" === this.swipeDirection && i.currentTranslate > i.startTranslate && (i.currentTranslate = i.startTranslate), a.threshold > 0) { if (!(Math.abs(f) > a.threshold || i.allowThresholdMove)) return void (i.currentTranslate = i.startTranslate); if (!i.allowThresholdMove) return i.allowThresholdMove = !0, r.startX = r.currentX, r.startY = r.currentY, i.currentTranslate = i.startTranslate, void (r.diff = this.isHorizontal() ? r.currentX - r.startX : r.currentY - r.startY) } a.followFinger && !a.cssMode && ((a.freeMode || a.watchSlidesProgress || a.watchSlidesVisibility) && (this.updateActiveIndex(), this.updateSlidesClasses()), a.freeMode && (0 === i.velocities.length && i.velocities.push({ position: r[this.isHorizontal() ? "startX" : "startY"], time: i.touchStartTime }), i.velocities.push({ position: r[this.isHorizontal() ? "currentX" : "currentY"], time: n.now() })), this.updateProgress(i.currentTranslate), this.setTranslate(i.currentTranslate)) } } } } } else i.startMoving && i.isScrolling && this.emit("touchMoveOpposite", l) } function A(e) { var t = this, i = t.touchEventsData, s = t.params, a = t.touches, r = t.rtlTranslate, o = t.$wrapperEl, l = t.slidesGrid, d = t.snapGrid, h = e; if (h.originalEvent && (h = h.originalEvent), i.allowTouchCallbacks && t.emit("touchEnd", h), i.allowTouchCallbacks = !1, !i.isTouched) return i.isMoved && s.grabCursor && t.setGrabCursor(!1), i.isMoved = !1, void (i.startMoving = !1); s.grabCursor && i.isMoved && i.isTouched && (!0 === t.allowSlideNext || !0 === t.allowSlidePrev) && t.setGrabCursor(!1); var p, c = n.now(), u = c - i.touchStartTime; if (t.allowClick && (t.updateClickedSlide(h), t.emit("tap click", h), u < 300 && c - i.lastClickTime < 300 && t.emit("doubleTap doubleClick", h)), i.lastClickTime = n.now(), n.nextTick((function () { t.destroyed || (t.allowClick = !0) })), !i.isTouched || !i.isMoved || !t.swipeDirection || 0 === a.diff || i.currentTranslate === i.startTranslate) return i.isTouched = !1, i.isMoved = !1, void (i.startMoving = !1); if (i.isTouched = !1, i.isMoved = !1, i.startMoving = !1, p = s.followFinger ? r ? t.translate : -t.translate : -i.currentTranslate, !s.cssMode) if (s.freeMode) { if (p < -t.minTranslate()) return void t.slideTo(t.activeIndex); if (p > -t.maxTranslate()) return void (t.slides.length < d.length ? t.slideTo(d.length - 1) : t.slideTo(t.slides.length - 1)); if (s.freeModeMomentum) { if (i.velocities.length > 1) { var v = i.velocities.pop(), f = i.velocities.pop(), m = v.position - f.position, g = v.time - f.time; t.velocity = m / g, t.velocity /= 2, Math.abs(t.velocity) < s.freeModeMinimumVelocity && (t.velocity = 0), (g > 150 || n.now() - v.time > 300) && (t.velocity = 0) } else t.velocity = 0; t.velocity *= s.freeModeMomentumVelocityRatio, i.velocities.length = 0; var b = 1e3 * s.freeModeMomentumRatio, w = t.velocity * b, y = t.translate + w; r && (y = -y); var x, T, E = !1, S = 20 * Math.abs(t.velocity) * s.freeModeMomentumBounceRatio; if (y < t.maxTranslate()) s.freeModeMomentumBounce ? (y + t.maxTranslate() < -S && (y = t.maxTranslate() - S), x = t.maxTranslate(), E = !0, i.allowMomentumBounce = !0) : y = t.maxTranslate(), s.loop && s.centeredSlides && (T = !0); else if (y > t.minTranslate()) s.freeModeMomentumBounce ? (y - t.minTranslate() > S && (y = t.minTranslate() + S), x = t.minTranslate(), E = !0, i.allowMomentumBounce = !0) : y = t.minTranslate(), s.loop && s.centeredSlides && (T = !0); else if (s.freeModeSticky) { for (var C, M = 0; M < d.length; M += 1)if (d[M] > -y) { C = M; break } y = -(y = Math.abs(d[C] - y) < Math.abs(d[C - 1] - y) || "next" === t.swipeDirection ? d[C] : d[C - 1]) } if (T && t.once("transitionEnd", (function () { t.loopFix() })), 0 !== t.velocity) { if (b = r ? Math.abs((-y - t.translate) / t.velocity) : Math.abs((y - t.translate) / t.velocity), s.freeModeSticky) { var P = Math.abs((r ? -y : y) - t.translate), z = t.slidesSizesGrid[t.activeIndex]; b = P < z ? s.speed : P < 2 * z ? 1.5 * s.speed : 2.5 * s.speed } } else if (s.freeModeSticky) return void t.slideToClosest(); s.freeModeMomentumBounce && E ? (t.updateProgress(x), t.setTransition(b), t.setTranslate(y), t.transitionStart(!0, t.swipeDirection), t.animating = !0, o.transitionEnd((function () { t && !t.destroyed && i.allowMomentumBounce && (t.emit("momentumBounce"), t.setTransition(s.speed), t.setTranslate(x), o.transitionEnd((function () { t && !t.destroyed && t.transitionEnd() }))) }))) : t.velocity ? (t.updateProgress(y), t.setTransition(b), t.setTranslate(y), t.transitionStart(!0, t.swipeDirection), t.animating || (t.animating = !0, o.transitionEnd((function () { t && !t.destroyed && t.transitionEnd() })))) : t.updateProgress(y), t.updateActiveIndex(), t.updateSlidesClasses() } else if (s.freeModeSticky) return void t.slideToClosest(); (!s.freeModeMomentum || u >= s.longSwipesMs) && (t.updateProgress(), t.updateActiveIndex(), t.updateSlidesClasses()) } else { for (var k = 0, $ = t.slidesSizesGrid[0], L = 0; L < l.length; L += L < s.slidesPerGroupSkip ? 1 : s.slidesPerGroup) { var I = L < s.slidesPerGroupSkip - 1 ? 1 : s.slidesPerGroup; void 0 !== l[L + I] ? p >= l[L] && p < l[L + I] && (k = L, $ = l[L + I] - l[L]) : p >= l[L] && (k = L, $ = l[l.length - 1] - l[l.length - 2]) } var D = (p - l[k]) / $, O = k < s.slidesPerGroupSkip - 1 ? 1 : s.slidesPerGroup; if (u > s.longSwipesMs) { if (!s.longSwipes) return void t.slideTo(t.activeIndex); "next" === t.swipeDirection && (D >= s.longSwipesRatio ? t.slideTo(k + O) : t.slideTo(k)), "prev" === t.swipeDirection && (D > 1 - s.longSwipesRatio ? t.slideTo(k + O) : t.slideTo(k)) } else { if (!s.shortSwipes) return void t.slideTo(t.activeIndex); t.navigation && (h.target === t.navigation.nextEl || h.target === t.navigation.prevEl) ? h.target === t.navigation.nextEl ? t.slideTo(k + O) : t.slideTo(k) : ("next" === t.swipeDirection && t.slideTo(k + O), "prev" === t.swipeDirection && t.slideTo(k)) } } } function G() { var e = this.params, t = this.el; if (!t || 0 !== t.offsetWidth) { e.breakpoints && this.setBreakpoint(); var i = this.allowSlideNext, s = this.allowSlidePrev, a = this.snapGrid; this.allowSlideNext = !0, this.allowSlidePrev = !0, this.updateSize(), this.updateSlides(), this.updateSlidesClasses(), ("auto" === e.slidesPerView || e.slidesPerView > 1) && this.isEnd && !this.params.centeredSlides ? this.slideTo(this.slides.length - 1, 0, !1, !0) : this.slideTo(this.activeIndex, 0, !1, !0), this.autoplay && this.autoplay.running && this.autoplay.paused && this.autoplay.run(), this.allowSlidePrev = s, this.allowSlideNext = i, this.params.watchOverflow && a !== this.snapGrid && this.checkOverflow() } } function H(e) { this.allowClick || (this.params.preventClicks && e.preventDefault(), this.params.preventClicksPropagation && this.animating && (e.stopPropagation(), e.stopImmediatePropagation())) } function B() { var e = this.wrapperEl, t = this.rtlTranslate; this.previousTranslate = this.translate, this.isHorizontal() ? this.translate = t ? e.scrollWidth - e.offsetWidth - e.scrollLeft : -e.scrollLeft : this.translate = -e.scrollTop, -0 === this.translate && (this.translate = 0), this.updateActiveIndex(), this.updateSlidesClasses(); var i = this.maxTranslate() - this.minTranslate(); (0 === i ? 0 : (this.translate - this.minTranslate()) / i) !== this.progress && this.updateProgress(t ? -this.translate : this.translate), this.emit("setTranslate", this.translate, !1) } var N = !1; function X() { } var V = { init: !0, direction: "horizontal", touchEventsTarget: "container", initialSlide: 0, speed: 300, cssMode: !1, updateOnWindowResize: !0, preventInteractionOnTransition: !1, edgeSwipeDetection: !1, edgeSwipeThreshold: 20, freeMode: !1, freeModeMomentum: !0, freeModeMomentumRatio: 1, freeModeMomentumBounce: !0, freeModeMomentumBounceRatio: 1, freeModeMomentumVelocityRatio: 1, freeModeSticky: !1, freeModeMinimumVelocity: .02, autoHeight: !1, setWrapperSize: !1, virtualTranslate: !1, effect: "slide", breakpoints: void 0, spaceBetween: 0, slidesPerView: 1, slidesPerColumn: 1, slidesPerColumnFill: "column", slidesPerGroup: 1, slidesPerGroupSkip: 0, centeredSlides: !1, centeredSlidesBounds: !1, slidesOffsetBefore: 0, slidesOffsetAfter: 0, normalizeSlideIndex: !0, centerInsufficientSlides: !1, watchOverflow: !1, roundLengths: !1, touchRatio: 1, touchAngle: 45, simulateTouch: !0, shortSwipes: !0, longSwipes: !0, longSwipesRatio: .5, longSwipesMs: 300, followFinger: !0, allowTouchMove: !0, threshold: 0, touchMoveStopPropagation: !1, touchStartPreventDefault: !0, touchStartForcePreventDefault: !1, touchReleaseOnEdges: !1, uniqueNavElements: !0, resistance: !0, resistanceRatio: .85, watchSlidesProgress: !1, watchSlidesVisibility: !1, grabCursor: !1, preventClicks: !0, preventClicksPropagation: !0, slideToClickedSlide: !1, preloadImages: !0, updateOnImagesReady: !0, loop: !1, loopAdditionalSlides: 0, loopedSlides: null, loopFillGroupWithBlank: !1, allowSlidePrev: !0, allowSlideNext: !0, swipeHandler: null, noSwiping: !0, noSwipingClass: "swiper-no-swiping", noSwipingSelector: null, passiveListeners: !0, containerModifierClass: "swiper-container-", slideClass: "swiper-slide", slideBlankClass: "swiper-slide-invisible-blank", slideActiveClass: "swiper-slide-active", slideDuplicateActiveClass: "swiper-slide-duplicate-active", slideVisibleClass: "swiper-slide-visible", slideDuplicateClass: "swiper-slide-duplicate", slideNextClass: "swiper-slide-next", slideDuplicateNextClass: "swiper-slide-duplicate-next", slidePrevClass: "swiper-slide-prev", slideDuplicatePrevClass: "swiper-slide-duplicate-prev", wrapperClass: "swiper-wrapper", runCallbacksOnInit: !0 }, Y = { update: h, translate: p, transition: c, slide: u, loop: v, grabCursor: f, manipulation: L, events: { attachEvents: function () { var t = this.params, i = this.touchEvents, s = this.el, a = this.wrapperEl; this.onTouchStart = D.bind(this), this.onTouchMove = O.bind(this), this.onTouchEnd = A.bind(this), t.cssMode && (this.onScroll = B.bind(this)), this.onClick = H.bind(this); var r = !!t.nested; if (!o.touch && o.pointerEvents) s.addEventListener(i.start, this.onTouchStart, !1), e.addEventListener(i.move, this.onTouchMove, r), e.addEventListener(i.end, this.onTouchEnd, !1); else { if (o.touch) { var n = !("touchstart" !== i.start || !o.passiveListener || !t.passiveListeners) && { passive: !0, capture: !1 }; s.addEventListener(i.start, this.onTouchStart, n), s.addEventListener(i.move, this.onTouchMove, o.passiveListener ? { passive: !1, capture: r } : r), s.addEventListener(i.end, this.onTouchEnd, n), i.cancel && s.addEventListener(i.cancel, this.onTouchEnd, n), N || (e.addEventListener("touchstart", X), N = !0) } (t.simulateTouch && !I.ios && !I.android || t.simulateTouch && !o.touch && I.ios) && (s.addEventListener("mousedown", this.onTouchStart, !1), e.addEventListener("mousemove", this.onTouchMove, r), e.addEventListener("mouseup", this.onTouchEnd, !1)) } (t.preventClicks || t.preventClicksPropagation) && s.addEventListener("click", this.onClick, !0), t.cssMode && a.addEventListener("scroll", this.onScroll), t.updateOnWindowResize ? this.on(I.ios || I.android ? "resize orientationchange observerUpdate" : "resize observerUpdate", G, !0) : this.on("observerUpdate", G, !0) }, detachEvents: function () { var t = this.params, i = this.touchEvents, s = this.el, a = this.wrapperEl, r = !!t.nested; if (!o.touch && o.pointerEvents) s.removeEventListener(i.start, this.onTouchStart, !1), e.removeEventListener(i.move, this.onTouchMove, r), e.removeEventListener(i.end, this.onTouchEnd, !1); else { if (o.touch) { var n = !("onTouchStart" !== i.start || !o.passiveListener || !t.passiveListeners) && { passive: !0, capture: !1 }; s.removeEventListener(i.start, this.onTouchStart, n), s.removeEventListener(i.move, this.onTouchMove, r), s.removeEventListener(i.end, this.onTouchEnd, n), i.cancel && s.removeEventListener(i.cancel, this.onTouchEnd, n) } (t.simulateTouch && !I.ios && !I.android || t.simulateTouch && !o.touch && I.ios) && (s.removeEventListener("mousedown", this.onTouchStart, !1), e.removeEventListener("mousemove", this.onTouchMove, r), e.removeEventListener("mouseup", this.onTouchEnd, !1)) } (t.preventClicks || t.preventClicksPropagation) && s.removeEventListener("click", this.onClick, !0), t.cssMode && a.removeEventListener("scroll", this.onScroll), this.off(I.ios || I.android ? "resize orientationchange observerUpdate" : "resize observerUpdate", G) } }, breakpoints: { setBreakpoint: function () { var e = this.activeIndex, t = this.initialized, i = this.loopedSlides; void 0 === i && (i = 0); var s = this.params, a = this.$el, r = s.breakpoints; if (r && (!r || 0 !== Object.keys(r).length)) { var o = this.getBreakpoint(r); if (o && this.currentBreakpoint !== o) { var l = o in r ? r[o] : void 0; l && ["slidesPerView", "spaceBetween", "slidesPerGroup", "slidesPerGroupSkip", "slidesPerColumn"].forEach((function (e) { var t = l[e]; void 0 !== t && (l[e] = "slidesPerView" !== e || "AUTO" !== t && "auto" !== t ? "slidesPerView" === e ? parseFloat(t) : parseInt(t, 10) : "auto") })); var d = l || this.originalParams, h = s.slidesPerColumn > 1, p = d.slidesPerColumn > 1; h && !p ? a.removeClass(s.containerModifierClass + "multirow " + s.containerModifierClass + "multirow-column") : !h && p && (a.addClass(s.containerModifierClass + "multirow"), "column" === d.slidesPerColumnFill && a.addClass(s.containerModifierClass + "multirow-column")); var c = d.direction && d.direction !== s.direction, u = s.loop && (d.slidesPerView !== s.slidesPerView || c); c && t && this.changeDirection(), n.extend(this.params, d), n.extend(this, { allowTouchMove: this.params.allowTouchMove, allowSlideNext: this.params.allowSlideNext, allowSlidePrev: this.params.allowSlidePrev }), this.currentBreakpoint = o, u && t && (this.loopDestroy(), this.loopCreate(), this.updateSlides(), this.slideTo(e - i + this.loopedSlides, 0, !1)), this.emit("breakpoint", d) } } }, getBreakpoint: function (e) { if (e) { var i = !1, s = Object.keys(e).map((function (e) { if ("string" == typeof e && 0 === e.indexOf("@")) { var i = parseFloat(e.substr(1)); return { value: t.innerHeight * i, point: e } } return { value: e, point: e } })); s.sort((function (e, t) { return parseInt(e.value, 10) - parseInt(t.value, 10) })); for (var a = 0; a < s.length; a += 1) { var r = s[a], n = r.point; r.value <= t.innerWidth && (i = n) } return i || "max" } } }, checkOverflow: { checkOverflow: function () { var e = this.params, t = this.isLocked, i = this.slides.length > 0 && e.slidesOffsetBefore + e.spaceBetween * (this.slides.length - 1) + this.slides[0].offsetWidth * this.slides.length; e.slidesOffsetBefore && e.slidesOffsetAfter && i ? this.isLocked = i <= this.size : this.isLocked = 1 === this.snapGrid.length, this.allowSlideNext = !this.isLocked, this.allowSlidePrev = !this.isLocked, t !== this.isLocked && this.emit(this.isLocked ? "lock" : "unlock"), t && t !== this.isLocked && (this.isEnd = !1, this.navigation.update()) } }, classes: { addClasses: function () { var e = this.classNames, t = this.params, i = this.rtl, s = this.$el, a = []; a.push("initialized"), a.push(t.direction), t.freeMode && a.push("free-mode"), t.autoHeight && a.push("autoheight"), i && a.push("rtl"), t.slidesPerColumn > 1 && (a.push("multirow"), "column" === t.slidesPerColumnFill && a.push("multirow-column")), I.android && a.push("android"), I.ios && a.push("ios"), t.cssMode && a.push("css-mode"), a.forEach((function (i) { e.push(t.containerModifierClass + i) })), s.addClass(e.join(" ")) }, removeClasses: function () { var e = this.$el, t = this.classNames; e.removeClass(t.join(" ")) } }, images: { loadImage: function (e, i, s, a, r, n) { var o; function l() { n && n() } e.complete && r ? l() : i ? ((o = new t.Image).onload = l, o.onerror = l, a && (o.sizes = a), s && (o.srcset = s), i && (o.src = i)) : l() }, preloadImages: function () { var e = this; function t() { null != e && e && !e.destroyed && (void 0 !== e.imagesLoaded && (e.imagesLoaded += 1), e.imagesLoaded === e.imagesToLoad.length && (e.params.updateOnImagesReady && e.update(), e.emit("imagesReady"))) } e.imagesToLoad = e.$el.find("img"); for (var i = 0; i < e.imagesToLoad.length; i += 1) { var s = e.imagesToLoad[i]; e.loadImage(s, s.currentSrc || s.getAttribute("src"), s.srcset || s.getAttribute("srcset"), s.sizes || s.getAttribute("sizes"), !0, t) } } } }, F = {}, W = function (e) { function t() { for (var i, a, r, l = [], d = arguments.length; d--;)l[d] = arguments[d]; 1 === l.length && l[0].constructor && l[0].constructor === Object ? r = l[0] : (a = (i = l)[0], r = i[1]), r || (r = {}), r = n.extend({}, r), a && !r.el && (r.el = a), e.call(this, r), Object.keys(Y).forEach((function (e) { Object.keys(Y[e]).forEach((function (i) { t.prototype[i] || (t.prototype[i] = Y[e][i]) })) })); var h = this; void 0 === h.modules && (h.modules = {}), Object.keys(h.modules).forEach((function (e) { var t = h.modules[e]; if (t.params) { var i = Object.keys(t.params)[0], s = t.params[i]; if ("object" != typeof s || null === s) return; if (!(i in r) || !("enabled" in s)) return; !0 === r[i] && (r[i] = { enabled: !0 }), "object" != typeof r[i] || "enabled" in r[i] || (r[i].enabled = !0), r[i] || (r[i] = { enabled: !1 }) } })); var p = n.extend({}, V); h.useModulesParams(p), h.params = n.extend({}, p, F, r), h.originalParams = n.extend({}, h.params), h.passedParams = n.extend({}, r), h.$ = s; var c = s(h.params.el); if (a = c[0]) { if (c.length > 1) { var u = []; return c.each((function (e, i) { var s = n.extend({}, r, { el: i }); u.push(new t(s)) })), u } var v, f, m; return a.swiper = h, c.data("swiper", h), a && a.shadowRoot && a.shadowRoot.querySelector ? (v = s(a.shadowRoot.querySelector("." + h.params.wrapperClass))).children = function (e) { return c.children(e) } : v = c.children("." + h.params.wrapperClass), n.extend(h, { $el: c, el: a, $wrapperEl: v, wrapperEl: v[0], classNames: [], slides: s(), slidesGrid: [], snapGrid: [], slidesSizesGrid: [], isHorizontal: function () { return "horizontal" === h.params.direction }, isVertical: function () { return "vertical" === h.params.direction }, rtl: "rtl" === a.dir.toLowerCase() || "rtl" === c.css("direction"), rtlTranslate: "horizontal" === h.params.direction && ("rtl" === a.dir.toLowerCase() || "rtl" === c.css("direction")), wrongRTL: "-webkit-box" === v.css("display"), activeIndex: 0, realIndex: 0, isBeginning: !0, isEnd: !1, translate: 0, previousTranslate: 0, progress: 0, velocity: 0, animating: !1, allowSlideNext: h.params.allowSlideNext, allowSlidePrev: h.params.allowSlidePrev, touchEvents: (f = ["touchstart", "touchmove", "touchend", "touchcancel"], m = ["mousedown", "mousemove", "mouseup"], o.pointerEvents && (m = ["pointerdown", "pointermove", "pointerup"]), h.touchEventsTouch = { start: f[0], move: f[1], end: f[2], cancel: f[3] }, h.touchEventsDesktop = { start: m[0], move: m[1], end: m[2] }, o.touch || !h.params.simulateTouch ? h.touchEventsTouch : h.touchEventsDesktop), touchEventsData: { isTouched: void 0, isMoved: void 0, allowTouchCallbacks: void 0, touchStartTime: void 0, isScrolling: void 0, currentTranslate: void 0, startTranslate: void 0, allowThresholdMove: void 0, formElements: "input, select, option, textarea, button, video, label", lastClickTime: n.now(), clickTimeout: void 0, velocities: [], allowMomentumBounce: void 0, isTouchEvent: void 0, startMoving: void 0 }, allowClick: !0, allowTouchMove: h.params.allowTouchMove, touches: { startX: 0, startY: 0, currentX: 0, currentY: 0, diff: 0 }, imagesToLoad: [], imagesLoaded: 0 }), h.useModules(), h.params.init && h.init(), h } } e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t; var i = { extendedDefaults: { configurable: !0 }, defaults: { configurable: !0 }, Class: { configurable: !0 }, $: { configurable: !0 } }; return t.prototype.slidesPerViewDynamic = function () { var e = this.params, t = this.slides, i = this.slidesGrid, s = this.size, a = this.activeIndex, r = 1; if (e.centeredSlides) { for (var n, o = t[a].swiperSlideSize, l = a + 1; l < t.length; l += 1)t[l] && !n && (r += 1, (o += t[l].swiperSlideSize) > s && (n = !0)); for (var d = a - 1; d >= 0; d -= 1)t[d] && !n && (r += 1, (o += t[d].swiperSlideSize) > s && (n = !0)) } else for (var h = a + 1; h < t.length; h += 1)i[h] - i[a] < s && (r += 1); return r }, t.prototype.update = function () { var e = this; if (e && !e.destroyed) { var t = e.snapGrid, i = e.params; i.breakpoints && e.setBreakpoint(), e.updateSize(), e.updateSlides(), e.updateProgress(), e.updateSlidesClasses(), e.params.freeMode ? (s(), e.params.autoHeight && e.updateAutoHeight()) : (("auto" === e.params.slidesPerView || e.params.slidesPerView > 1) && e.isEnd && !e.params.centeredSlides ? e.slideTo(e.slides.length - 1, 0, !1, !0) : e.slideTo(e.activeIndex, 0, !1, !0)) || s(), i.watchOverflow && t !== e.snapGrid && e.checkOverflow(), e.emit("update") } function s() { var t = e.rtlTranslate ? -1 * e.translate : e.translate, i = Math.min(Math.max(t, e.maxTranslate()), e.minTranslate()); e.setTranslate(i), e.updateActiveIndex(), e.updateSlidesClasses() } }, t.prototype.changeDirection = function (e, t) { void 0 === t && (t = !0); var i = this.params.direction; return e || (e = "horizontal" === i ? "vertical" : "horizontal"), e === i || "horizontal" !== e && "vertical" !== e || (this.$el.removeClass("" + this.params.containerModifierClass + i).addClass("" + this.params.containerModifierClass + e), this.params.direction = e, this.slides.each((function (t, i) { "vertical" === e ? i.style.width = "" : i.style.height = "" })), this.emit("changeDirection"), t && this.update()), this }, t.prototype.init = function () { this.initialized || (this.emit("beforeInit"), this.params.breakpoints && this.setBreakpoint(), this.addClasses(), this.params.loop && this.loopCreate(), this.updateSize(), this.updateSlides(), this.params.watchOverflow && this.checkOverflow(), this.params.grabCursor && this.setGrabCursor(), this.params.preloadImages && this.preloadImages(), this.params.loop ? this.slideTo(this.params.initialSlide + this.loopedSlides, 0, this.params.runCallbacksOnInit) : this.slideTo(this.params.initialSlide, 0, this.params.runCallbacksOnInit), this.attachEvents(), this.initialized = !0, this.emit("init")) }, t.prototype.destroy = function (e, t) { void 0 === e && (e = !0), void 0 === t && (t = !0); var i = this, s = i.params, a = i.$el, r = i.$wrapperEl, o = i.slides; return void 0 === i.params || i.destroyed || (i.emit("beforeDestroy"), i.initialized = !1, i.detachEvents(), s.loop && i.loopDestroy(), t && (i.removeClasses(), a.removeAttr("style"), r.removeAttr("style"), o && o.length && o.removeClass([s.slideVisibleClass, s.slideActiveClass, s.slideNextClass, s.slidePrevClass].join(" ")).removeAttr("style").removeAttr("data-swiper-slide-index")), i.emit("destroy"), Object.keys(i.eventsListeners).forEach((function (e) { i.off(e) })), !1 !== e && (i.$el[0].swiper = null, i.$el.data("swiper", null), n.deleteProps(i)), i.destroyed = !0), null }, t.extendDefaults = function (e) { n.extend(F, e) }, i.extendedDefaults.get = function () { return F }, i.defaults.get = function () { return V }, i.Class.get = function () { return e }, i.$.get = function () { return s }, Object.defineProperties(t, i), t }(l), R = { name: "device", proto: { device: I }, static: { device: I } }, q = { name: "support", proto: { support: o }, static: { support: o } }, j = { isEdge: !!t.navigator.userAgent.match(/Edge/g), isSafari: function () { var e = t.navigator.userAgent.toLowerCase(); return e.indexOf("safari") >= 0 && e.indexOf("chrome") < 0 && e.indexOf("android") < 0 }(), isUiWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(t.navigator.userAgent) }, K = { name: "browser", proto: { browser: j }, static: { browser: j } }, U = { name: "resize", create: function () { var e = this; n.extend(e, { resize: { resizeHandler: function () { e && !e.destroyed && e.initialized && (e.emit("beforeResize"), e.emit("resize")) }, orientationChangeHandler: function () { e && !e.destroyed && e.initialized && e.emit("orientationchange") } } }) }, on: { init: function () { t.addEventListener("resize", this.resize.resizeHandler), t.addEventListener("orientationchange", this.resize.orientationChangeHandler) }, destroy: function () { t.removeEventListener("resize", this.resize.resizeHandler), t.removeEventListener("orientationchange", this.resize.orientationChangeHandler) } } }, _ = { func: t.MutationObserver || t.WebkitMutationObserver, attach: function (e, i) { void 0 === i && (i = {}); var s = this, a = new (0, _.func)((function (e) { if (1 !== e.length) { var i = function () { s.emit("observerUpdate", e[0]) }; t.requestAnimationFrame ? t.requestAnimationFrame(i) : t.setTimeout(i, 0) } else s.emit("observerUpdate", e[0]) })); a.observe(e, { attributes: void 0 === i.attributes || i.attributes, childList: void 0 === i.childList || i.childList, characterData: void 0 === i.characterData || i.characterData }), s.observer.observers.push(a) }, init: function () { if (o.observer && this.params.observer) { if (this.params.observeParents) for (var e = this.$el.parents(), t = 0; t < e.length; t += 1)this.observer.attach(e[t]); this.observer.attach(this.$el[0], { childList: this.params.observeSlideChildren }), this.observer.attach(this.$wrapperEl[0], { attributes: !1 }) } }, destroy: function () { this.observer.observers.forEach((function (e) { e.disconnect() })), this.observer.observers = [] } }, Z = { name: "observer", params: { observer: !1, observeParents: !1, observeSlideChildren: !1 }, create: function () { n.extend(this, { observer: { init: _.init.bind(this), attach: _.attach.bind(this), destroy: _.destroy.bind(this), observers: [] } }) }, on: { init: function () { this.observer.init() }, destroy: function () { this.observer.destroy() } } }, Q = { update: function (e) { var t = this, i = t.params, s = i.slidesPerView, a = i.slidesPerGroup, r = i.centeredSlides, o = t.params.virtual, l = o.addSlidesBefore, d = o.addSlidesAfter, h = t.virtual, p = h.from, c = h.to, u = h.slides, v = h.slidesGrid, f = h.renderSlide, m = h.offset; t.updateActiveIndex(); var g, b, w, y = t.activeIndex || 0; g = t.rtlTranslate ? "right" : t.isHorizontal() ? "left" : "top", r ? (b = Math.floor(s / 2) + a + l, w = Math.floor(s / 2) + a + d) : (b = s + (a - 1) + l, w = a + d); var x = Math.max((y || 0) - w, 0), T = Math.min((y || 0) + b, u.length - 1), E = (t.slidesGrid[x] || 0) - (t.slidesGrid[0] || 0); function S() { t.updateSlides(), t.updateProgress(), t.updateSlidesClasses(), t.lazy && t.params.lazy.enabled && t.lazy.load() } if (n.extend(t.virtual, { from: x, to: T, offset: E, slidesGrid: t.slidesGrid }), p === x && c === T && !e) return t.slidesGrid !== v && E !== m && t.slides.css(g, E + "px"), void t.updateProgress(); if (t.params.virtual.renderExternal) return t.params.virtual.renderExternal.call(t, { offset: E, from: x, to: T, slides: function () { for (var e = [], t = x; t <= T; t += 1)e.push(u[t]); return e }() }), void S(); var C = [], M = []; if (e) t.$wrapperEl.find("." + t.params.slideClass).remove(); else for (var P = p; P <= c; P += 1)(P < x || P > T) && t.$wrapperEl.find("." + t.params.slideClass + '[data-swiper-slide-index="' + P + '"]').remove(); for (var z = 0; z < u.length; z += 1)z >= x && z <= T && (void 0 === c || e ? M.push(z) : (z > c && M.push(z), z < p && C.push(z))); M.forEach((function (e) { t.$wrapperEl.append(f(u[e], e)) })), C.sort((function (e, t) { return t - e })).forEach((function (e) { t.$wrapperEl.prepend(f(u[e], e)) })), t.$wrapperEl.children(".swiper-slide").css(g, E + "px"), S() }, renderSlide: function (e, t) { var i = this.params.virtual; if (i.cache && this.virtual.cache[t]) return this.virtual.cache[t]; var a = i.renderSlide ? s(i.renderSlide.call(this, e, t)) : s('<div class="' + this.params.slideClass + '" data-swiper-slide-index="' + t + '">' + e + "</div>"); return a.attr("data-swiper-slide-index") || a.attr("data-swiper-slide-index", t), i.cache && (this.virtual.cache[t] = a), a }, appendSlide: function (e) { if ("object" == typeof e && "length" in e) for (var t = 0; t < e.length; t += 1)e[t] && this.virtual.slides.push(e[t]); else this.virtual.slides.push(e); this.virtual.update(!0) }, prependSlide: function (e) { var t = this.activeIndex, i = t + 1, s = 1; if (Array.isArray(e)) { for (var a = 0; a < e.length; a += 1)e[a] && this.virtual.slides.unshift(e[a]); i = t + e.length, s = e.length } else this.virtual.slides.unshift(e); if (this.params.virtual.cache) { var r = this.virtual.cache, n = {}; Object.keys(r).forEach((function (e) { var t = r[e], i = t.attr("data-swiper-slide-index"); i && t.attr("data-swiper-slide-index", parseInt(i, 10) + 1), n[parseInt(e, 10) + s] = t })), this.virtual.cache = n } this.virtual.update(!0), this.slideTo(i, 0) }, removeSlide: function (e) { if (null != e) { var t = this.activeIndex; if (Array.isArray(e)) for (var i = e.length - 1; i >= 0; i -= 1)this.virtual.slides.splice(e[i], 1), this.params.virtual.cache && delete this.virtual.cache[e[i]], e[i] < t && (t -= 1), t = Math.max(t, 0); else this.virtual.slides.splice(e, 1), this.params.virtual.cache && delete this.virtual.cache[e], e < t && (t -= 1), t = Math.max(t, 0); this.virtual.update(!0), this.slideTo(t, 0) } }, removeAllSlides: function () { this.virtual.slides = [], this.params.virtual.cache && (this.virtual.cache = {}), this.virtual.update(!0), this.slideTo(0, 0) } }, J = { name: "virtual", params: { virtual: { enabled: !1, slides: [], cache: !0, renderSlide: null, renderExternal: null, addSlidesBefore: 0, addSlidesAfter: 0 } }, create: function () { n.extend(this, { virtual: { update: Q.update.bind(this), appendSlide: Q.appendSlide.bind(this), prependSlide: Q.prependSlide.bind(this), removeSlide: Q.removeSlide.bind(this), removeAllSlides: Q.removeAllSlides.bind(this), renderSlide: Q.renderSlide.bind(this), slides: this.params.virtual.slides, cache: {} } }) }, on: { beforeInit: function () { if (this.params.virtual.enabled) { this.classNames.push(this.params.containerModifierClass + "virtual"); var e = { watchSlidesProgress: !0 }; n.extend(this.params, e), n.extend(this.originalParams, e), this.params.initialSlide || this.virtual.update() } }, setTranslate: function () { this.params.virtual.enabled && this.virtual.update() } } }, ee = { handle: function (i) { var s = this.rtlTranslate, a = i; a.originalEvent && (a = a.originalEvent); var r = a.keyCode || a.charCode; if (!this.allowSlideNext && (this.isHorizontal() && 39 === r || this.isVertical() && 40 === r || 34 === r)) return !1; if (!this.allowSlidePrev && (this.isHorizontal() && 37 === r || this.isVertical() && 38 === r || 33 === r)) return !1; if (!(a.shiftKey || a.altKey || a.ctrlKey || a.metaKey || e.activeElement && e.activeElement.nodeName && ("input" === e.activeElement.nodeName.toLowerCase() || "textarea" === e.activeElement.nodeName.toLowerCase()))) { if (this.params.keyboard.onlyInViewport && (33 === r || 34 === r || 37 === r || 39 === r || 38 === r || 40 === r)) { var n = !1; if (this.$el.parents("." + this.params.slideClass).length > 0 && 0 === this.$el.parents("." + this.params.slideActiveClass).length) return; var o = t.innerWidth, l = t.innerHeight, d = this.$el.offset(); s && (d.left -= this.$el[0].scrollLeft); for (var h = [[d.left, d.top], [d.left + this.width, d.top], [d.left, d.top + this.height], [d.left + this.width, d.top + this.height]], p = 0; p < h.length; p += 1) { var c = h[p]; c[0] >= 0 && c[0] <= o && c[1] >= 0 && c[1] <= l && (n = !0) } if (!n) return } this.isHorizontal() ? (33 !== r && 34 !== r && 37 !== r && 39 !== r || (a.preventDefault ? a.preventDefault() : a.returnValue = !1), (34 !== r && 39 !== r || s) && (33 !== r && 37 !== r || !s) || this.slideNext(), (33 !== r && 37 !== r || s) && (34 !== r && 39 !== r || !s) || this.slidePrev()) : (33 !== r && 34 !== r && 38 !== r && 40 !== r || (a.preventDefault ? a.preventDefault() : a.returnValue = !1), 34 !== r && 40 !== r || this.slideNext(), 33 !== r && 38 !== r || this.slidePrev()), this.emit("keyPress", r) } }, enable: function () { this.keyboard.enabled || (s(e).on("keydown", this.keyboard.handle), this.keyboard.enabled = !0) }, disable: function () { this.keyboard.enabled && (s(e).off("keydown", this.keyboard.handle), this.keyboard.enabled = !1) } }, te = { name: "keyboard", params: { keyboard: { enabled: !1, onlyInViewport: !0 } }, create: function () { n.extend(this, { keyboard: { enabled: !1, enable: ee.enable.bind(this), disable: ee.disable.bind(this), handle: ee.handle.bind(this) } }) }, on: { init: function () { this.params.keyboard.enabled && this.keyboard.enable() }, destroy: function () { this.keyboard.enabled && this.keyboard.disable() } } }; var ie = { lastScrollTime: n.now(), lastEventBeforeSnap: void 0, recentWheelEvents: [], event: function () { return t.navigator.userAgent.indexOf("firefox") > -1 ? "DOMMouseScroll" : function () { var t = "onwheel" in e; if (!t) { var i = e.createElement("div"); i.setAttribute("onwheel", "return;"), t = "function" == typeof i.onwheel } return !t && e.implementation && e.implementation.hasFeature && !0 !== e.implementation.hasFeature("", "") && (t = e.implementation.hasFeature("Events.wheel", "3.0")), t }() ? "wheel" : "mousewheel" }, normalize: function (e) { var t = 0, i = 0, s = 0, a = 0; return "detail" in e && (i = e.detail), "wheelDelta" in e && (i = -e.wheelDelta / 120), "wheelDeltaY" in e && (i = -e.wheelDeltaY / 120), "wheelDeltaX" in e && (t = -e.wheelDeltaX / 120), "axis" in e && e.axis === e.HORIZONTAL_AXIS && (t = i, i = 0), s = 10 * t, a = 10 * i, "deltaY" in e && (a = e.deltaY), "deltaX" in e && (s = e.deltaX), e.shiftKey && !s && (s = a, a = 0), (s || a) && e.deltaMode && (1 === e.deltaMode ? (s *= 40, a *= 40) : (s *= 800, a *= 800)), s && !t && (t = s < 1 ? -1 : 1), a && !i && (i = a < 1 ? -1 : 1), { spinX: t, spinY: i, pixelX: s, pixelY: a } }, handleMouseEnter: function () { this.mouseEntered = !0 }, handleMouseLeave: function () { this.mouseEntered = !1 }, handle: function (e) { var t = e, i = this, a = i.params.mousewheel; i.params.cssMode && t.preventDefault(); var r = i.$el; if ("container" !== i.params.mousewheel.eventsTarged && (r = s(i.params.mousewheel.eventsTarged)), !i.mouseEntered && !r[0].contains(t.target) && !a.releaseOnEdges) return !0; t.originalEvent && (t = t.originalEvent); var o = 0, l = i.rtlTranslate ? -1 : 1, d = ie.normalize(t); if (a.forceToAxis) if (i.isHorizontal()) { if (!(Math.abs(d.pixelX) > Math.abs(d.pixelY))) return !0; o = d.pixelX * l } else { if (!(Math.abs(d.pixelY) > Math.abs(d.pixelX))) return !0; o = d.pixelY } else o = Math.abs(d.pixelX) > Math.abs(d.pixelY) ? -d.pixelX * l : -d.pixelY; if (0 === o) return !0; if (a.invert && (o = -o), i.params.freeMode) { var h = { time: n.now(), delta: Math.abs(o), direction: Math.sign(o) }, p = i.mousewheel.lastEventBeforeSnap, c = p && h.time < p.time + 500 && h.delta <= p.delta && h.direction === p.direction; if (!c) { i.mousewheel.lastEventBeforeSnap = void 0, i.params.loop && i.loopFix(); var u = i.getTranslate() + o * a.sensitivity, v = i.isBeginning, f = i.isEnd; if (u >= i.minTranslate() && (u = i.minTranslate()), u <= i.maxTranslate() && (u = i.maxTranslate()), i.setTransition(0), i.setTranslate(u), i.updateProgress(), i.updateActiveIndex(), i.updateSlidesClasses(), (!v && i.isBeginning || !f && i.isEnd) && i.updateSlidesClasses(), i.params.freeModeSticky) { clearTimeout(i.mousewheel.timeout), i.mousewheel.timeout = void 0; var m = i.mousewheel.recentWheelEvents; m.length >= 15 && m.shift(); var g = m.length ? m[m.length - 1] : void 0, b = m[0]; if (m.push(h), g && (h.delta > g.delta || h.direction !== g.direction)) m.splice(0); else if (m.length >= 15 && h.time - b.time < 500 && b.delta - h.delta >= 1 && h.delta <= 6) { var w = o > 0 ? .8 : .2; i.mousewheel.lastEventBeforeSnap = h, m.splice(0), i.mousewheel.timeout = n.nextTick((function () { i.slideToClosest(i.params.speed, !0, void 0, w) }), 0) } i.mousewheel.timeout || (i.mousewheel.timeout = n.nextTick((function () { i.mousewheel.lastEventBeforeSnap = h, m.splice(0), i.slideToClosest(i.params.speed, !0, void 0, .5) }), 500)) } if (c || i.emit("scroll", t), i.params.autoplay && i.params.autoplayDisableOnInteraction && i.autoplay.stop(), u === i.minTranslate() || u === i.maxTranslate()) return !0 } } else { var y = { time: n.now(), delta: Math.abs(o), direction: Math.sign(o), raw: e }, x = i.mousewheel.recentWheelEvents; x.length >= 2 && x.shift(); var T = x.length ? x[x.length - 1] : void 0; if (x.push(y), T ? (y.direction !== T.direction || y.delta > T.delta) && i.mousewheel.animateSlider(y) : i.mousewheel.animateSlider(y), i.mousewheel.releaseScroll(y)) return !0 } return t.preventDefault ? t.preventDefault() : t.returnValue = !1, !1 }, animateSlider: function (e) { return e.delta >= 6 && n.now() - this.mousewheel.lastScrollTime < 60 || (e.direction < 0 ? this.isEnd && !this.params.loop || this.animating || (this.slideNext(), this.emit("scroll", e.raw)) : this.isBeginning && !this.params.loop || this.animating || (this.slidePrev(), this.emit("scroll", e.raw)), this.mousewheel.lastScrollTime = (new t.Date).getTime(), !1) }, releaseScroll: function (e) { var t = this.params.mousewheel; if (e.direction < 0) { if (this.isEnd && !this.params.loop && t.releaseOnEdges) return !0 } else if (this.isBeginning && !this.params.loop && t.releaseOnEdges) return !0; return !1 }, enable: function () { var e = ie.event(); if (this.params.cssMode) return this.wrapperEl.removeEventListener(e, this.mousewheel.handle), !0; if (!e) return !1; if (this.mousewheel.enabled) return !1; var t = this.$el; return "container" !== this.params.mousewheel.eventsTarged && (t = s(this.params.mousewheel.eventsTarged)), t.on("mouseenter", this.mousewheel.handleMouseEnter), t.on("mouseleave", this.mousewheel.handleMouseLeave), t.on(e, this.mousewheel.handle), this.mousewheel.enabled = !0, !0 }, disable: function () { var e = ie.event(); if (this.params.cssMode) return this.wrapperEl.addEventListener(e, this.mousewheel.handle), !0; if (!e) return !1; if (!this.mousewheel.enabled) return !1; var t = this.$el; return "container" !== this.params.mousewheel.eventsTarged && (t = s(this.params.mousewheel.eventsTarged)), t.off(e, this.mousewheel.handle), this.mousewheel.enabled = !1, !0 } }, se = { update: function () { var e = this.params.navigation; if (!this.params.loop) { var t = this.navigation, i = t.$nextEl, s = t.$prevEl; s && s.length > 0 && (this.isBeginning ? s.addClass(e.disabledClass) : s.removeClass(e.disabledClass), s[this.params.watchOverflow && this.isLocked ? "addClass" : "removeClass"](e.lockClass)), i && i.length > 0 && (this.isEnd ? i.addClass(e.disabledClass) : i.removeClass(e.disabledClass), i[this.params.watchOverflow && this.isLocked ? "addClass" : "removeClass"](e.lockClass)) } }, onPrevClick: function (e) { e.preventDefault(), this.isBeginning && !this.params.loop || this.slidePrev() }, onNextClick: function (e) { e.preventDefault(), this.isEnd && !this.params.loop || this.slideNext() }, init: function () { var e, t, i = this.params.navigation; (i.nextEl || i.prevEl) && (i.nextEl && (e = s(i.nextEl), this.params.uniqueNavElements && "string" == typeof i.nextEl && e.length > 1 && 1 === this.$el.find(i.nextEl).length && (e = this.$el.find(i.nextEl))), i.prevEl && (t = s(i.prevEl), this.params.uniqueNavElements && "string" == typeof i.prevEl && t.length > 1 && 1 === this.$el.find(i.prevEl).length && (t = this.$el.find(i.prevEl))), e && e.length > 0 && e.on("click", this.navigation.onNextClick), t && t.length > 0 && t.on("click", this.navigation.onPrevClick), n.extend(this.navigation, { $nextEl: e, nextEl: e && e[0], $prevEl: t, prevEl: t && t[0] })) }, destroy: function () { var e = this.navigation, t = e.$nextEl, i = e.$prevEl; t && t.length && (t.off("click", this.navigation.onNextClick), t.removeClass(this.params.navigation.disabledClass)), i && i.length && (i.off("click", this.navigation.onPrevClick), i.removeClass(this.params.navigation.disabledClass)) } }, ae = { update: function () { var e = this.rtl, t = this.params.pagination; if (t.el && this.pagination.el && this.pagination.$el && 0 !== this.pagination.$el.length) { var i, a = this.virtual && this.params.virtual.enabled ? this.virtual.slides.length : this.slides.length, r = this.pagination.$el, n = this.params.loop ? Math.ceil((a - 2 * this.loopedSlides) / this.params.slidesPerGroup) : this.snapGrid.length; if (this.params.loop ? ((i = Math.ceil((this.activeIndex - this.loopedSlides) / this.params.slidesPerGroup)) > a - 1 - 2 * this.loopedSlides && (i -= a - 2 * this.loopedSlides), i > n - 1 && (i -= n), i < 0 && "bullets" !== this.params.paginationType && (i = n + i)) : i = void 0 !== this.snapIndex ? this.snapIndex : this.activeIndex || 0, "bullets" === t.type && this.pagination.bullets && this.pagination.bullets.length > 0) { var o, l, d, h = this.pagination.bullets; if (t.dynamicBullets && (this.pagination.bulletSize = h.eq(0)[this.isHorizontal() ? "outerWidth" : "outerHeight"](!0), r.css(this.isHorizontal() ? "width" : "height", this.pagination.bulletSize * (t.dynamicMainBullets + 4) + "px"), t.dynamicMainBullets > 1 && void 0 !== this.previousIndex && (this.pagination.dynamicBulletIndex += i - this.previousIndex, this.pagination.dynamicBulletIndex > t.dynamicMainBullets - 1 ? this.pagination.dynamicBulletIndex = t.dynamicMainBullets - 1 : this.pagination.dynamicBulletIndex < 0 && (this.pagination.dynamicBulletIndex = 0)), o = i - this.pagination.dynamicBulletIndex, d = ((l = o + (Math.min(h.length, t.dynamicMainBullets) - 1)) + o) / 2), h.removeClass(t.bulletActiveClass + " " + t.bulletActiveClass + "-next " + t.bulletActiveClass + "-next-next " + t.bulletActiveClass + "-prev " + t.bulletActiveClass + "-prev-prev " + t.bulletActiveClass + "-main"), r.length > 1) h.each((function (e, a) { var r = s(a), n = r.index(); n === i && r.addClass(t.bulletActiveClass), t.dynamicBullets && (n >= o && n <= l && r.addClass(t.bulletActiveClass + "-main"), n === o && r.prev().addClass(t.bulletActiveClass + "-prev").prev().addClass(t.bulletActiveClass + "-prev-prev"), n === l && r.next().addClass(t.bulletActiveClass + "-next").next().addClass(t.bulletActiveClass + "-next-next")) })); else { var p = h.eq(i), c = p.index(); if (p.addClass(t.bulletActiveClass), t.dynamicBullets) { for (var u = h.eq(o), v = h.eq(l), f = o; f <= l; f += 1)h.eq(f).addClass(t.bulletActiveClass + "-main"); if (this.params.loop) if (c >= h.length - t.dynamicMainBullets) { for (var m = t.dynamicMainBullets; m >= 0; m -= 1)h.eq(h.length - m).addClass(t.bulletActiveClass + "-main"); h.eq(h.length - t.dynamicMainBullets - 1).addClass(t.bulletActiveClass + "-prev") } else u.prev().addClass(t.bulletActiveClass + "-prev").prev().addClass(t.bulletActiveClass + "-prev-prev"), v.next().addClass(t.bulletActiveClass + "-next").next().addClass(t.bulletActiveClass + "-next-next"); else u.prev().addClass(t.bulletActiveClass + "-prev").prev().addClass(t.bulletActiveClass + "-prev-prev"), v.next().addClass(t.bulletActiveClass + "-next").next().addClass(t.bulletActiveClass + "-next-next") } } if (t.dynamicBullets) { var g = Math.min(h.length, t.dynamicMainBullets + 4), b = (this.pagination.bulletSize * g - this.pagination.bulletSize) / 2 - d * this.pagination.bulletSize, w = e ? "right" : "left"; h.css(this.isHorizontal() ? w : "top", b + "px") } } if ("fraction" === t.type && (r.find("." + t.currentClass).text(t.formatFractionCurrent(i + 1)), r.find("." + t.totalClass).text(t.formatFractionTotal(n))), "progressbar" === t.type) { var y; y = t.progressbarOpposite ? this.isHorizontal() ? "vertical" : "horizontal" : this.isHorizontal() ? "horizontal" : "vertical"; var x = (i + 1) / n, T = 1, E = 1; "horizontal" === y ? T = x : E = x, r.find("." + t.progressbarFillClass).transform("translate3d(0,0,0) scaleX(" + T + ") scaleY(" + E + ")").transition(this.params.speed) } "custom" === t.type && t.renderCustom ? (r.html(t.renderCustom(this, i + 1, n)), this.emit("paginationRender", this, r[0])) : this.emit("paginationUpdate", this, r[0]), r[this.params.watchOverflow && this.isLocked ? "addClass" : "removeClass"](t.lockClass) } }, render: function () { var e = this.params.pagination; if (e.el && this.pagination.el && this.pagination.$el && 0 !== this.pagination.$el.length) { var t = this.virtual && this.params.virtual.enabled ? this.virtual.slides.length : this.slides.length, i = this.pagination.$el, s = ""; if ("bullets" === e.type) { for (var a = this.params.loop ? Math.ceil((t - 2 * this.loopedSlides) / this.params.slidesPerGroup) : this.snapGrid.length, r = 0; r < a; r += 1)e.renderBullet ? s += e.renderBullet.call(this, r, e.bulletClass) : s += "<" + e.bulletElement + ' class="' + e.bulletClass + '"></' + e.bulletElement + ">"; i.html(s), this.pagination.bullets = i.find("." + e.bulletClass) } "fraction" === e.type && (s = e.renderFraction ? e.renderFraction.call(this, e.currentClass, e.totalClass) : '<span class="' + e.currentClass + '"></span> / <span class="' + e.totalClass + '"></span>', i.html(s)), "progressbar" === e.type && (s = e.renderProgressbar ? e.renderProgressbar.call(this, e.progressbarFillClass) : '<span class="' + e.progressbarFillClass + '"></span>', i.html(s)), "custom" !== e.type && this.emit("paginationRender", this.pagination.$el[0]) } }, init: function () { var e = this, t = e.params.pagination; if (t.el) { var i = s(t.el); 0 !== i.length && (e.params.uniqueNavElements && "string" == typeof t.el && i.length > 1 && 1 === e.$el.find(t.el).length && (i = e.$el.find(t.el)), "bullets" === t.type && t.clickable && i.addClass(t.clickableClass), i.addClass(t.modifierClass + t.type), "bullets" === t.type && t.dynamicBullets && (i.addClass("" + t.modifierClass + t.type + "-dynamic"), e.pagination.dynamicBulletIndex = 0, t.dynamicMainBullets < 1 && (t.dynamicMainBullets = 1)), "progressbar" === t.type && t.progressbarOpposite && i.addClass(t.progressbarOppositeClass), t.clickable && i.on("click", "." + t.bulletClass, (function (t) { t.preventDefault(); var i = s(this).index() * e.params.slidesPerGroup; e.params.loop && (i += e.loopedSlides), e.slideTo(i) })), n.extend(e.pagination, { $el: i, el: i[0] })) } }, destroy: function () { var e = this.params.pagination; if (e.el && this.pagination.el && this.pagination.$el && 0 !== this.pagination.$el.length) { var t = this.pagination.$el; t.removeClass(e.hiddenClass), t.removeClass(e.modifierClass + e.type), this.pagination.bullets && this.pagination.bullets.removeClass(e.bulletActiveClass), e.clickable && t.off("click", "." + e.bulletClass) } } }, re = { setTranslate: function () { if (this.params.scrollbar.el && this.scrollbar.el) { var e = this.scrollbar, t = this.rtlTranslate, i = this.progress, s = e.dragSize, a = e.trackSize, r = e.$dragEl, n = e.$el, o = this.params.scrollbar, l = s, d = (a - s) * i; t ? (d = -d) > 0 ? (l = s - d, d = 0) : -d + s > a && (l = a + d) : d < 0 ? (l = s + d, d = 0) : d + s > a && (l = a - d), this.isHorizontal() ? (r.transform("translate3d(" + d + "px, 0, 0)"), r[0].style.width = l + "px") : (r.transform("translate3d(0px, " + d + "px, 0)"), r[0].style.height = l + "px"), o.hide && (clearTimeout(this.scrollbar.timeout), n[0].style.opacity = 1, this.scrollbar.timeout = setTimeout((function () { n[0].style.opacity = 0, n.transition(400) }), 1e3)) } }, setTransition: function (e) { this.params.scrollbar.el && this.scrollbar.el && this.scrollbar.$dragEl.transition(e) }, updateSize: function () { if (this.params.scrollbar.el && this.scrollbar.el) { var e = this.scrollbar, t = e.$dragEl, i = e.$el; t[0].style.width = "", t[0].style.height = ""; var s, a = this.isHorizontal() ? i[0].offsetWidth : i[0].offsetHeight, r = this.size / this.virtualSize, o = r * (a / this.size); s = "auto" === this.params.scrollbar.dragSize ? a * r : parseInt(this.params.scrollbar.dragSize, 10), this.isHorizontal() ? t[0].style.width = s + "px" : t[0].style.height = s + "px", i[0].style.display = r >= 1 ? "none" : "", this.params.scrollbar.hide && (i[0].style.opacity = 0), n.extend(e, { trackSize: a, divider: r, moveDivider: o, dragSize: s }), e.$el[this.params.watchOverflow && this.isLocked ? "addClass" : "removeClass"](this.params.scrollbar.lockClass) } }, getPointerPosition: function (e) { return this.isHorizontal() ? "touchstart" === e.type || "touchmove" === e.type ? e.targetTouches[0].clientX : e.clientX : "touchstart" === e.type || "touchmove" === e.type ? e.targetTouches[0].clientY : e.clientY }, setDragPosition: function (e) { var t, i = this.scrollbar, s = this.rtlTranslate, a = i.$el, r = i.dragSize, n = i.trackSize, o = i.dragStartPos; t = (i.getPointerPosition(e) - a.offset()[this.isHorizontal() ? "left" : "top"] - (null !== o ? o : r / 2)) / (n - r), t = Math.max(Math.min(t, 1), 0), s && (t = 1 - t); var l = this.minTranslate() + (this.maxTranslate() - this.minTranslate()) * t; this.updateProgress(l), this.setTranslate(l), this.updateActiveIndex(), this.updateSlidesClasses() }, onDragStart: function (e) { var t = this.params.scrollbar, i = this.scrollbar, s = this.$wrapperEl, a = i.$el, r = i.$dragEl; this.scrollbar.isTouched = !0, this.scrollbar.dragStartPos = e.target === r[0] || e.target === r ? i.getPointerPosition(e) - e.target.getBoundingClientRect()[this.isHorizontal() ? "left" : "top"] : null, e.preventDefault(), e.stopPropagation(), s.transition(100), r.transition(100), i.setDragPosition(e), clearTimeout(this.scrollbar.dragTimeout), a.transition(0), t.hide && a.css("opacity", 1), this.params.cssMode && this.$wrapperEl.css("scroll-snap-type", "none"), this.emit("scrollbarDragStart", e) }, onDragMove: function (e) { var t = this.scrollbar, i = this.$wrapperEl, s = t.$el, a = t.$dragEl; this.scrollbar.isTouched && (e.preventDefault ? e.preventDefault() : e.returnValue = !1, t.setDragPosition(e), i.transition(0), s.transition(0), a.transition(0), this.emit("scrollbarDragMove", e)) }, onDragEnd: function (e) { var t = this.params.scrollbar, i = this.scrollbar, s = this.$wrapperEl, a = i.$el; this.scrollbar.isTouched && (this.scrollbar.isTouched = !1, this.params.cssMode && (this.$wrapperEl.css("scroll-snap-type", ""), s.transition("")), t.hide && (clearTimeout(this.scrollbar.dragTimeout), this.scrollbar.dragTimeout = n.nextTick((function () { a.css("opacity", 0), a.transition(400) }), 1e3)), this.emit("scrollbarDragEnd", e), t.snapOnRelease && this.slideToClosest()) }, enableDraggable: function () { if (this.params.scrollbar.el) { var t = this.scrollbar, i = this.touchEventsTouch, s = this.touchEventsDesktop, a = this.params, r = t.$el[0], n = !(!o.passiveListener || !a.passiveListeners) && { passive: !1, capture: !1 }, l = !(!o.passiveListener || !a.passiveListeners) && { passive: !0, capture: !1 }; o.touch ? (r.addEventListener(i.start, this.scrollbar.onDragStart, n), r.addEventListener(i.move, this.scrollbar.onDragMove, n), r.addEventListener(i.end, this.scrollbar.onDragEnd, l)) : (r.addEventListener(s.start, this.scrollbar.onDragStart, n), e.addEventListener(s.move, this.scrollbar.onDragMove, n), e.addEventListener(s.end, this.scrollbar.onDragEnd, l)) } }, disableDraggable: function () { if (this.params.scrollbar.el) { var t = this.scrollbar, i = this.touchEventsTouch, s = this.touchEventsDesktop, a = this.params, r = t.$el[0], n = !(!o.passiveListener || !a.passiveListeners) && { passive: !1, capture: !1 }, l = !(!o.passiveListener || !a.passiveListeners) && { passive: !0, capture: !1 }; o.touch ? (r.removeEventListener(i.start, this.scrollbar.onDragStart, n), r.removeEventListener(i.move, this.scrollbar.onDragMove, n), r.removeEventListener(i.end, this.scrollbar.onDragEnd, l)) : (r.removeEventListener(s.start, this.scrollbar.onDragStart, n), e.removeEventListener(s.move, this.scrollbar.onDragMove, n), e.removeEventListener(s.end, this.scrollbar.onDragEnd, l)) } }, init: function () { if (this.params.scrollbar.el) { var e = this.scrollbar, t = this.$el, i = this.params.scrollbar, a = s(i.el); this.params.uniqueNavElements && "string" == typeof i.el && a.length > 1 && 1 === t.find(i.el).length && (a = t.find(i.el)); var r = a.find("." + this.params.scrollbar.dragClass); 0 === r.length && (r = s('<div class="' + this.params.scrollbar.dragClass + '"></div>'), a.append(r)), n.extend(e, { $el: a, el: a[0], $dragEl: r, dragEl: r[0] }), i.draggable && e.enableDraggable() } }, destroy: function () { this.scrollbar.disableDraggable() } }, ne = { setTransform: function (e, t) { var i = this.rtl, a = s(e), r = i ? -1 : 1, n = a.attr("data-swiper-parallax") || "0", o = a.attr("data-swiper-parallax-x"), l = a.attr("data-swiper-parallax-y"), d = a.attr("data-swiper-parallax-scale"), h = a.attr("data-swiper-parallax-opacity"); if (o || l ? (o = o || "0", l = l || "0") : this.isHorizontal() ? (o = n, l = "0") : (l = n, o = "0"), o = o.indexOf("%") >= 0 ? parseInt(o, 10) * t * r + "%" : o * t * r + "px", l = l.indexOf("%") >= 0 ? parseInt(l, 10) * t + "%" : l * t + "px", null != h) { var p = h - (h - 1) * (1 - Math.abs(t)); a[0].style.opacity = p } if (null == d) a.transform("translate3d(" + o + ", " + l + ", 0px)"); else { var c = d - (d - 1) * (1 - Math.abs(t)); a.transform("translate3d(" + o + ", " + l + ", 0px) scale(" + c + ")") } }, setTranslate: function () { var e = this, t = e.$el, i = e.slides, a = e.progress, r = e.snapGrid; t.children("[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]").each((function (t, i) { e.parallax.setTransform(i, a) })), i.each((function (t, i) { var n = i.progress; e.params.slidesPerGroup > 1 && "auto" !== e.params.slidesPerView && (n += Math.ceil(t / 2) - a * (r.length - 1)), n = Math.min(Math.max(n, -1), 1), s(i).find("[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]").each((function (t, i) { e.parallax.setTransform(i, n) })) })) }, setTransition: function (e) { void 0 === e && (e = this.params.speed); this.$el.find("[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]").each((function (t, i) { var a = s(i), r = parseInt(a.attr("data-swiper-parallax-duration"), 10) || e; 0 === e && (r = 0), a.transition(r) })) } }, oe = { getDistanceBetweenTouches: function (e) { if (e.targetTouches.length < 2) return 1; var t = e.targetTouches[0].pageX, i = e.targetTouches[0].pageY, s = e.targetTouches[1].pageX, a = e.targetTouches[1].pageY; return Math.sqrt(Math.pow(s - t, 2) + Math.pow(a - i, 2)) }, onGestureStart: function (e) { var t = this.params.zoom, i = this.zoom, a = i.gesture; if (i.fakeGestureTouched = !1, i.fakeGestureMoved = !1, !o.gestures) { if ("touchstart" !== e.type || "touchstart" === e.type && e.targetTouches.length < 2) return; i.fakeGestureTouched = !0, a.scaleStart = oe.getDistanceBetweenTouches(e) } a.$slideEl && a.$slideEl.length || (a.$slideEl = s(e.target).closest("." + this.params.slideClass), 0 === a.$slideEl.length && (a.$slideEl = this.slides.eq(this.activeIndex)), a.$imageEl = a.$slideEl.find("img, svg, canvas, picture, .swiper-zoom-target"), a.$imageWrapEl = a.$imageEl.parent("." + t.containerClass), a.maxRatio = a.$imageWrapEl.attr("data-swiper-zoom") || t.maxRatio, 0 !== a.$imageWrapEl.length) ? (a.$imageEl && a.$imageEl.transition(0), this.zoom.isScaling = !0) : a.$imageEl = void 0 }, onGestureChange: function (e) { var t = this.params.zoom, i = this.zoom, s = i.gesture; if (!o.gestures) { if ("touchmove" !== e.type || "touchmove" === e.type && e.targetTouches.length < 2) return; i.fakeGestureMoved = !0, s.scaleMove = oe.getDistanceBetweenTouches(e) } s.$imageEl && 0 !== s.$imageEl.length && (i.scale = o.gestures ? e.scale * i.currentScale : s.scaleMove / s.scaleStart * i.currentScale, i.scale > s.maxRatio && (i.scale = s.maxRatio - 1 + Math.pow(i.scale - s.maxRatio + 1, .5)), i.scale < t.minRatio && (i.scale = t.minRatio + 1 - Math.pow(t.minRatio - i.scale + 1, .5)), s.$imageEl.transform("translate3d(0,0,0) scale(" + i.scale + ")")) }, onGestureEnd: function (e) { var t = this.params.zoom, i = this.zoom, s = i.gesture; if (!o.gestures) { if (!i.fakeGestureTouched || !i.fakeGestureMoved) return; if ("touchend" !== e.type || "touchend" === e.type && e.changedTouches.length < 2 && !I.android) return; i.fakeGestureTouched = !1, i.fakeGestureMoved = !1 } s.$imageEl && 0 !== s.$imageEl.length && (i.scale = Math.max(Math.min(i.scale, s.maxRatio), t.minRatio), s.$imageEl.transition(this.params.speed).transform("translate3d(0,0,0) scale(" + i.scale + ")"), i.currentScale = i.scale, i.isScaling = !1, 1 === i.scale && (s.$slideEl = void 0)) }, onTouchStart: function (e) { var t = this.zoom, i = t.gesture, s = t.image; i.$imageEl && 0 !== i.$imageEl.length && (s.isTouched || (I.android && e.preventDefault(), s.isTouched = !0, s.touchesStart.x = "touchstart" === e.type ? e.targetTouches[0].pageX : e.pageX, s.touchesStart.y = "touchstart" === e.type ? e.targetTouches[0].pageY : e.pageY)) }, onTouchMove: function (e) { var t = this.zoom, i = t.gesture, s = t.image, a = t.velocity; if (i.$imageEl && 0 !== i.$imageEl.length && (this.allowClick = !1, s.isTouched && i.$slideEl)) { s.isMoved || (s.width = i.$imageEl[0].offsetWidth, s.height = i.$imageEl[0].offsetHeight, s.startX = n.getTranslate(i.$imageWrapEl[0], "x") || 0, s.startY = n.getTranslate(i.$imageWrapEl[0], "y") || 0, i.slideWidth = i.$slideEl[0].offsetWidth, i.slideHeight = i.$slideEl[0].offsetHeight, i.$imageWrapEl.transition(0), this.rtl && (s.startX = -s.startX, s.startY = -s.startY)); var r = s.width * t.scale, o = s.height * t.scale; if (!(r < i.slideWidth && o < i.slideHeight)) { if (s.minX = Math.min(i.slideWidth / 2 - r / 2, 0), s.maxX = -s.minX, s.minY = Math.min(i.slideHeight / 2 - o / 2, 0), s.maxY = -s.minY, s.touchesCurrent.x = "touchmove" === e.type ? e.targetTouches[0].pageX : e.pageX, s.touchesCurrent.y = "touchmove" === e.type ? e.targetTouches[0].pageY : e.pageY, !s.isMoved && !t.isScaling) { if (this.isHorizontal() && (Math.floor(s.minX) === Math.floor(s.startX) && s.touchesCurrent.x < s.touchesStart.x || Math.floor(s.maxX) === Math.floor(s.startX) && s.touchesCurrent.x > s.touchesStart.x)) return void (s.isTouched = !1); if (!this.isHorizontal() && (Math.floor(s.minY) === Math.floor(s.startY) && s.touchesCurrent.y < s.touchesStart.y || Math.floor(s.maxY) === Math.floor(s.startY) && s.touchesCurrent.y > s.touchesStart.y)) return void (s.isTouched = !1) } e.preventDefault(), e.stopPropagation(), s.isMoved = !0, s.currentX = s.touchesCurrent.x - s.touchesStart.x + s.startX, s.currentY = s.touchesCurrent.y - s.touchesStart.y + s.startY, s.currentX < s.minX && (s.currentX = s.minX + 1 - Math.pow(s.minX - s.currentX + 1, .8)), s.currentX > s.maxX && (s.currentX = s.maxX - 1 + Math.pow(s.currentX - s.maxX + 1, .8)), s.currentY < s.minY && (s.currentY = s.minY + 1 - Math.pow(s.minY - s.currentY + 1, .8)), s.currentY > s.maxY && (s.currentY = s.maxY - 1 + Math.pow(s.currentY - s.maxY + 1, .8)), a.prevPositionX || (a.prevPositionX = s.touchesCurrent.x), a.prevPositionY || (a.prevPositionY = s.touchesCurrent.y), a.prevTime || (a.prevTime = Date.now()), a.x = (s.touchesCurrent.x - a.prevPositionX) / (Date.now() - a.prevTime) / 2, a.y = (s.touchesCurrent.y - a.prevPositionY) / (Date.now() - a.prevTime) / 2, Math.abs(s.touchesCurrent.x - a.prevPositionX) < 2 && (a.x = 0), Math.abs(s.touchesCurrent.y - a.prevPositionY) < 2 && (a.y = 0), a.prevPositionX = s.touchesCurrent.x, a.prevPositionY = s.touchesCurrent.y, a.prevTime = Date.now(), i.$imageWrapEl.transform("translate3d(" + s.currentX + "px, " + s.currentY + "px,0)") } } }, onTouchEnd: function () { var e = this.zoom, t = e.gesture, i = e.image, s = e.velocity; if (t.$imageEl && 0 !== t.$imageEl.length) { if (!i.isTouched || !i.isMoved) return i.isTouched = !1, void (i.isMoved = !1); i.isTouched = !1, i.isMoved = !1; var a = 300, r = 300, n = s.x * a, o = i.currentX + n, l = s.y * r, d = i.currentY + l; 0 !== s.x && (a = Math.abs((o - i.currentX) / s.x)), 0 !== s.y && (r = Math.abs((d - i.currentY) / s.y)); var h = Math.max(a, r); i.currentX = o, i.currentY = d; var p = i.width * e.scale, c = i.height * e.scale; i.minX = Math.min(t.slideWidth / 2 - p / 2, 0), i.maxX = -i.minX, i.minY = Math.min(t.slideHeight / 2 - c / 2, 0), i.maxY = -i.minY, i.currentX = Math.max(Math.min(i.currentX, i.maxX), i.minX), i.currentY = Math.max(Math.min(i.currentY, i.maxY), i.minY), t.$imageWrapEl.transition(h).transform("translate3d(" + i.currentX + "px, " + i.currentY + "px,0)") } }, onTransitionEnd: function () { var e = this.zoom, t = e.gesture; t.$slideEl && this.previousIndex !== this.activeIndex && (t.$imageEl && t.$imageEl.transform("translate3d(0,0,0) scale(1)"), t.$imageWrapEl && t.$imageWrapEl.transform("translate3d(0,0,0)"), e.scale = 1, e.currentScale = 1, t.$slideEl = void 0, t.$imageEl = void 0, t.$imageWrapEl = void 0) }, toggle: function (e) { var t = this.zoom; t.scale && 1 !== t.scale ? t.out() : t.in(e) }, in: function (e) { var t, i, s, a, r, n, o, l, d, h, p, c, u, v, f, m, g = this.zoom, b = this.params.zoom, w = g.gesture, y = g.image; (w.$slideEl || (this.params.virtual && this.params.virtual.enabled && this.virtual ? w.$slideEl = this.$wrapperEl.children("." + this.params.slideActiveClass) : w.$slideEl = this.slides.eq(this.activeIndex), w.$imageEl = w.$slideEl.find("img, svg, canvas, picture, .swiper-zoom-target"), w.$imageWrapEl = w.$imageEl.parent("." + b.containerClass)), w.$imageEl && 0 !== w.$imageEl.length) && (w.$slideEl.addClass("" + b.zoomedSlideClass), void 0 === y.touchesStart.x && e ? (t = "touchend" === e.type ? e.changedTouches[0].pageX : e.pageX, i = "touchend" === e.type ? e.changedTouches[0].pageY : e.pageY) : (t = y.touchesStart.x, i = y.touchesStart.y), g.scale = w.$imageWrapEl.attr("data-swiper-zoom") || b.maxRatio, g.currentScale = w.$imageWrapEl.attr("data-swiper-zoom") || b.maxRatio, e ? (f = w.$slideEl[0].offsetWidth, m = w.$slideEl[0].offsetHeight, s = w.$slideEl.offset().left + f / 2 - t, a = w.$slideEl.offset().top + m / 2 - i, o = w.$imageEl[0].offsetWidth, l = w.$imageEl[0].offsetHeight, d = o * g.scale, h = l * g.scale, u = -(p = Math.min(f / 2 - d / 2, 0)), v = -(c = Math.min(m / 2 - h / 2, 0)), (r = s * g.scale) < p && (r = p), r > u && (r = u), (n = a * g.scale) < c && (n = c), n > v && (n = v)) : (r = 0, n = 0), w.$imageWrapEl.transition(300).transform("translate3d(" + r + "px, " + n + "px,0)"), w.$imageEl.transition(300).transform("translate3d(0,0,0) scale(" + g.scale + ")")) }, out: function () { var e = this.zoom, t = this.params.zoom, i = e.gesture; i.$slideEl || (this.params.virtual && this.params.virtual.enabled && this.virtual ? i.$slideEl = this.$wrapperEl.children("." + this.params.slideActiveClass) : i.$slideEl = this.slides.eq(this.activeIndex), i.$imageEl = i.$slideEl.find("img, svg, canvas, picture, .swiper-zoom-target"), i.$imageWrapEl = i.$imageEl.parent("." + t.containerClass)), i.$imageEl && 0 !== i.$imageEl.length && (e.scale = 1, e.currentScale = 1, i.$imageWrapEl.transition(300).transform("translate3d(0,0,0)"), i.$imageEl.transition(300).transform("translate3d(0,0,0) scale(1)"), i.$slideEl.removeClass("" + t.zoomedSlideClass), i.$slideEl = void 0) }, enable: function () { var e = this.zoom; if (!e.enabled) { e.enabled = !0; var t = !("touchstart" !== this.touchEvents.start || !o.passiveListener || !this.params.passiveListeners) && { passive: !0, capture: !1 }, i = !o.passiveListener || { passive: !1, capture: !0 }, s = "." + this.params.slideClass; o.gestures ? (this.$wrapperEl.on("gesturestart", s, e.onGestureStart, t), this.$wrapperEl.on("gesturechange", s, e.onGestureChange, t), this.$wrapperEl.on("gestureend", s, e.onGestureEnd, t)) : "touchstart" === this.touchEvents.start && (this.$wrapperEl.on(this.touchEvents.start, s, e.onGestureStart, t), this.$wrapperEl.on(this.touchEvents.move, s, e.onGestureChange, i), this.$wrapperEl.on(this.touchEvents.end, s, e.onGestureEnd, t), this.touchEvents.cancel && this.$wrapperEl.on(this.touchEvents.cancel, s, e.onGestureEnd, t)), this.$wrapperEl.on(this.touchEvents.move, "." + this.params.zoom.containerClass, e.onTouchMove, i) } }, disable: function () { var e = this.zoom; if (e.enabled) { this.zoom.enabled = !1; var t = !("touchstart" !== this.touchEvents.start || !o.passiveListener || !this.params.passiveListeners) && { passive: !0, capture: !1 }, i = !o.passiveListener || { passive: !1, capture: !0 }, s = "." + this.params.slideClass; o.gestures ? (this.$wrapperEl.off("gesturestart", s, e.onGestureStart, t), this.$wrapperEl.off("gesturechange", s, e.onGestureChange, t), this.$wrapperEl.off("gestureend", s, e.onGestureEnd, t)) : "touchstart" === this.touchEvents.start && (this.$wrapperEl.off(this.touchEvents.start, s, e.onGestureStart, t), this.$wrapperEl.off(this.touchEvents.move, s, e.onGestureChange, i), this.$wrapperEl.off(this.touchEvents.end, s, e.onGestureEnd, t), this.touchEvents.cancel && this.$wrapperEl.off(this.touchEvents.cancel, s, e.onGestureEnd, t)), this.$wrapperEl.off(this.touchEvents.move, "." + this.params.zoom.containerClass, e.onTouchMove, i) } } }, le = { loadInSlide: function (e, t) { void 0 === t && (t = !0); var i = this, a = i.params.lazy; if (void 0 !== e && 0 !== i.slides.length) { var r = i.virtual && i.params.virtual.enabled ? i.$wrapperEl.children("." + i.params.slideClass + '[data-swiper-slide-index="' + e + '"]') : i.slides.eq(e), n = r.find("." + a.elementClass + ":not(." + a.loadedClass + "):not(." + a.loadingClass + ")"); !r.hasClass(a.elementClass) || r.hasClass(a.loadedClass) || r.hasClass(a.loadingClass) || (n = n.add(r[0])), 0 !== n.length && n.each((function (e, n) { var o = s(n); o.addClass(a.loadingClass); var l = o.attr("data-background"), d = o.attr("data-src"), h = o.attr("data-srcset"), p = o.attr("data-sizes"); i.loadImage(o[0], d || l, h, p, !1, (function () { if (null != i && i && (!i || i.params) && !i.destroyed) { if (l ? (o.css("background-image", 'url("' + l + '")'), o.removeAttr("data-background")) : (h && (o.attr("srcset", h), o.removeAttr("data-srcset")), p && (o.attr("sizes", p), o.removeAttr("data-sizes")), d && (o.attr("src", d), o.removeAttr("data-src"))), o.addClass(a.loadedClass).removeClass(a.loadingClass), r.find("." + a.preloaderClass).remove(), i.params.loop && t) { var e = r.attr("data-swiper-slide-index"); if (r.hasClass(i.params.slideDuplicateClass)) { var s = i.$wrapperEl.children('[data-swiper-slide-index="' + e + '"]:not(.' + i.params.slideDuplicateClass + ")"); i.lazy.loadInSlide(s.index(), !1) } else { var n = i.$wrapperEl.children("." + i.params.slideDuplicateClass + '[data-swiper-slide-index="' + e + '"]'); i.lazy.loadInSlide(n.index(), !1) } } i.emit("lazyImageReady", r[0], o[0]), i.params.autoHeight && i.updateAutoHeight() } })), i.emit("lazyImageLoad", r[0], o[0]) })) } }, load: function () { var e = this, t = e.$wrapperEl, i = e.params, a = e.slides, r = e.activeIndex, n = e.virtual && i.virtual.enabled, o = i.lazy, l = i.slidesPerView; function d(e) { if (n) { if (t.children("." + i.slideClass + '[data-swiper-slide-index="' + e + '"]').length) return !0 } else if (a[e]) return !0; return !1 } function h(e) { return n ? s(e).attr("data-swiper-slide-index") : s(e).index() } if ("auto" === l && (l = 0), e.lazy.initialImageLoaded || (e.lazy.initialImageLoaded = !0), e.params.watchSlidesVisibility) t.children("." + i.slideVisibleClass).each((function (t, i) { var a = n ? s(i).attr("data-swiper-slide-index") : s(i).index(); e.lazy.loadInSlide(a) })); else if (l > 1) for (var p = r; p < r + l; p += 1)d(p) && e.lazy.loadInSlide(p); else e.lazy.loadInSlide(r); if (o.loadPrevNext) if (l > 1 || o.loadPrevNextAmount && o.loadPrevNextAmount > 1) { for (var c = o.loadPrevNextAmount, u = l, v = Math.min(r + u + Math.max(c, u), a.length), f = Math.max(r - Math.max(u, c), 0), m = r + l; m < v; m += 1)d(m) && e.lazy.loadInSlide(m); for (var g = f; g < r; g += 1)d(g) && e.lazy.loadInSlide(g) } else { var b = t.children("." + i.slideNextClass); b.length > 0 && e.lazy.loadInSlide(h(b)); var w = t.children("." + i.slidePrevClass); w.length > 0 && e.lazy.loadInSlide(h(w)) } } }, de = { LinearSpline: function (e, t) { var i, s, a, r, n, o = function (e, t) { for (s = -1, i = e.length; i - s > 1;)e[a = i + s >> 1] <= t ? s = a : i = a; return i }; return this.x = e, this.y = t, this.lastIndex = e.length - 1, this.interpolate = function (e) { return e ? (n = o(this.x, e), r = n - 1, (e - this.x[r]) * (this.y[n] - this.y[r]) / (this.x[n] - this.x[r]) + this.y[r]) : 0 }, this }, getInterpolateFunction: function (e) { this.controller.spline || (this.controller.spline = this.params.loop ? new de.LinearSpline(this.slidesGrid, e.slidesGrid) : new de.LinearSpline(this.snapGrid, e.snapGrid)) }, setTranslate: function (e, t) { var i, s, a = this, r = a.controller.control; function n(e) { var t = a.rtlTranslate ? -a.translate : a.translate; "slide" === a.params.controller.by && (a.controller.getInterpolateFunction(e), s = -a.controller.spline.interpolate(-t)), s && "container" !== a.params.controller.by || (i = (e.maxTranslate() - e.minTranslate()) / (a.maxTranslate() - a.minTranslate()), s = (t - a.minTranslate()) * i + e.minTranslate()), a.params.controller.inverse && (s = e.maxTranslate() - s), e.updateProgress(s), e.setTranslate(s, a), e.updateActiveIndex(), e.updateSlidesClasses() } if (Array.isArray(r)) for (var o = 0; o < r.length; o += 1)r[o] !== t && r[o] instanceof W && n(r[o]); else r instanceof W && t !== r && n(r) }, setTransition: function (e, t) { var i, s = this, a = s.controller.control; function r(t) { t.setTransition(e, s), 0 !== e && (t.transitionStart(), t.params.autoHeight && n.nextTick((function () { t.updateAutoHeight() })), t.$wrapperEl.transitionEnd((function () { a && (t.params.loop && "slide" === s.params.controller.by && t.loopFix(), t.transitionEnd()) }))) } if (Array.isArray(a)) for (i = 0; i < a.length; i += 1)a[i] !== t && a[i] instanceof W && r(a[i]); else a instanceof W && t !== a && r(a) } }, he = { makeElFocusable: function (e) { return e.attr("tabIndex", "0"), e }, addElRole: function (e, t) { return e.attr("role", t), e }, addElLabel: function (e, t) { return e.attr("aria-label", t), e }, disableEl: function (e) { return e.attr("aria-disabled", !0), e }, enableEl: function (e) { return e.attr("aria-disabled", !1), e }, onEnterKey: function (e) { var t = this.params.a11y; if (13 === e.keyCode) { var i = s(e.target); this.navigation && this.navigation.$nextEl && i.is(this.navigation.$nextEl) && (this.isEnd && !this.params.loop || this.slideNext(), this.isEnd ? this.a11y.notify(t.lastSlideMessage) : this.a11y.notify(t.nextSlideMessage)), this.navigation && this.navigation.$prevEl && i.is(this.navigation.$prevEl) && (this.isBeginning && !this.params.loop || this.slidePrev(), this.isBeginning ? this.a11y.notify(t.firstSlideMessage) : this.a11y.notify(t.prevSlideMessage)), this.pagination && i.is("." + this.params.pagination.bulletClass) && i[0].click() } }, notify: function (e) { var t = this.a11y.liveRegion; 0 !== t.length && (t.html(""), t.html(e)) }, updateNavigation: function () { if (!this.params.loop && this.navigation) { var e = this.navigation, t = e.$nextEl, i = e.$prevEl; i && i.length > 0 && (this.isBeginning ? this.a11y.disableEl(i) : this.a11y.enableEl(i)), t && t.length > 0 && (this.isEnd ? this.a11y.disableEl(t) : this.a11y.enableEl(t)) } }, updatePagination: function () { var e = this, t = e.params.a11y; e.pagination && e.params.pagination.clickable && e.pagination.bullets && e.pagination.bullets.length && e.pagination.bullets.each((function (i, a) { var r = s(a); e.a11y.makeElFocusable(r), e.a11y.addElRole(r, "button"), e.a11y.addElLabel(r, t.paginationBulletMessage.replace(/{{index}}/, r.index() + 1)) })) }, init: function () { this.$el.append(this.a11y.liveRegion); var e, t, i = this.params.a11y; this.navigation && this.navigation.$nextEl && (e = this.navigation.$nextEl), this.navigation && this.navigation.$prevEl && (t = this.navigation.$prevEl), e && (this.a11y.makeElFocusable(e), this.a11y.addElRole(e, "button"), this.a11y.addElLabel(e, i.nextSlideMessage), e.on("keydown", this.a11y.onEnterKey)), t && (this.a11y.makeElFocusable(t), this.a11y.addElRole(t, "button"), this.a11y.addElLabel(t, i.prevSlideMessage), t.on("keydown", this.a11y.onEnterKey)), this.pagination && this.params.pagination.clickable && this.pagination.bullets && this.pagination.bullets.length && this.pagination.$el.on("keydown", "." + this.params.pagination.bulletClass, this.a11y.onEnterKey) }, destroy: function () { var e, t; this.a11y.liveRegion && this.a11y.liveRegion.length > 0 && this.a11y.liveRegion.remove(), this.navigation && this.navigation.$nextEl && (e = this.navigation.$nextEl), this.navigation && this.navigation.$prevEl && (t = this.navigation.$prevEl), e && e.off("keydown", this.a11y.onEnterKey), t && t.off("keydown", this.a11y.onEnterKey), this.pagination && this.params.pagination.clickable && this.pagination.bullets && this.pagination.bullets.length && this.pagination.$el.off("keydown", "." + this.params.pagination.bulletClass, this.a11y.onEnterKey) } }, pe = { init: function () { if (this.params.history) { if (!t.history || !t.history.pushState) return this.params.history.enabled = !1, void (this.params.hashNavigation.enabled = !0); var e = this.history; e.initialized = !0, e.paths = pe.getPathValues(), (e.paths.key || e.paths.value) && (e.scrollToSlide(0, e.paths.value, this.params.runCallbacksOnInit), this.params.history.replaceState || t.addEventListener("popstate", this.history.setHistoryPopState)) } }, destroy: function () { this.params.history.replaceState || t.removeEventListener("popstate", this.history.setHistoryPopState) }, setHistoryPopState: function () { this.history.paths = pe.getPathValues(), this.history.scrollToSlide(this.params.speed, this.history.paths.value, !1) }, getPathValues: function () { var e = t.location.pathname.slice(1).split("/").filter((function (e) { return "" !== e })), i = e.length; return { key: e[i - 2], value: e[i - 1] } }, setHistory: function (e, i) { if (this.history.initialized && this.params.history.enabled) { var s = this.slides.eq(i), a = pe.slugify(s.attr("data-history")); t.location.pathname.includes(e) || (a = e + "/" + a); var r = t.history.state; r && r.value === a || (this.params.history.replaceState ? t.history.replaceState({ value: a }, null, a) : t.history.pushState({ value: a }, null, a)) } }, slugify: function (e) { return e.toString().replace(/\s+/g, "-").replace(/[^\w-]+/g, "").replace(/--+/g, "-").replace(/^-+/, "").replace(/-+$/, "") }, scrollToSlide: function (e, t, i) { if (t) for (var s = 0, a = this.slides.length; s < a; s += 1) { var r = this.slides.eq(s); if (pe.slugify(r.attr("data-history")) === t && !r.hasClass(this.params.slideDuplicateClass)) { var n = r.index(); this.slideTo(n, e, i) } } else this.slideTo(0, e, i) } }, ce = { onHashCange: function () { var t = e.location.hash.replace("#", ""); if (t !== this.slides.eq(this.activeIndex).attr("data-hash")) { var i = this.$wrapperEl.children("." + this.params.slideClass + '[data-hash="' + t + '"]').index(); if (void 0 === i) return; this.slideTo(i) } }, setHash: function () { if (this.hashNavigation.initialized && this.params.hashNavigation.enabled) if (this.params.hashNavigation.replaceState && t.history && t.history.replaceState) t.history.replaceState(null, null, "#" + this.slides.eq(this.activeIndex).attr("data-hash") || ""); else { var i = this.slides.eq(this.activeIndex), s = i.attr("data-hash") || i.attr("data-history"); e.location.hash = s || "" } }, init: function () { if (!(!this.params.hashNavigation.enabled || this.params.history && this.params.history.enabled)) { this.hashNavigation.initialized = !0; var i = e.location.hash.replace("#", ""); if (i) for (var a = 0, r = this.slides.length; a < r; a += 1) { var n = this.slides.eq(a); if ((n.attr("data-hash") || n.attr("data-history")) === i && !n.hasClass(this.params.slideDuplicateClass)) { var o = n.index(); this.slideTo(o, 0, this.params.runCallbacksOnInit, !0) } } this.params.hashNavigation.watchState && s(t).on("hashchange", this.hashNavigation.onHashCange) } }, destroy: function () { this.params.hashNavigation.watchState && s(t).off("hashchange", this.hashNavigation.onHashCange) } }, ue = { run: function () { var e = this, t = e.slides.eq(e.activeIndex), i = e.params.autoplay.delay; t.attr("data-swiper-autoplay") && (i = t.attr("data-swiper-autoplay") || e.params.autoplay.delay), clearTimeout(e.autoplay.timeout), e.autoplay.timeout = n.nextTick((function () { e.params.autoplay.reverseDirection ? e.params.loop ? (e.loopFix(), e.slidePrev(e.params.speed, !0, !0), e.emit("autoplay")) : e.isBeginning ? e.params.autoplay.stopOnLastSlide ? e.autoplay.stop() : (e.slideTo(e.slides.length - 1, e.params.speed, !0, !0), e.emit("autoplay")) : (e.slidePrev(e.params.speed, !0, !0), e.emit("autoplay")) : e.params.loop ? (e.loopFix(), e.slideNext(e.params.speed, !0, !0), e.emit("autoplay")) : e.isEnd ? e.params.autoplay.stopOnLastSlide ? e.autoplay.stop() : (e.slideTo(0, e.params.speed, !0, !0), e.emit("autoplay")) : (e.slideNext(e.params.speed, !0, !0), e.emit("autoplay")), e.params.cssMode && e.autoplay.running && e.autoplay.run() }), i) }, start: function () { return void 0 === this.autoplay.timeout && (!this.autoplay.running && (this.autoplay.running = !0, this.emit("autoplayStart"), this.autoplay.run(), !0)) }, stop: function () { return !!this.autoplay.running && (void 0 !== this.autoplay.timeout && (this.autoplay.timeout && (clearTimeout(this.autoplay.timeout), this.autoplay.timeout = void 0), this.autoplay.running = !1, this.emit("autoplayStop"), !0)) }, pause: function (e) { this.autoplay.running && (this.autoplay.paused || (this.autoplay.timeout && clearTimeout(this.autoplay.timeout), this.autoplay.paused = !0, 0 !== e && this.params.autoplay.waitForTransition ? (this.$wrapperEl[0].addEventListener("transitionend", this.autoplay.onTransitionEnd), this.$wrapperEl[0].addEventListener("webkitTransitionEnd", this.autoplay.onTransitionEnd)) : (this.autoplay.paused = !1, this.autoplay.run()))) } }, ve = { setTranslate: function () { for (var e = this.slides, t = 0; t < e.length; t += 1) { var i = this.slides.eq(t), s = -i[0].swiperSlideOffset; this.params.virtualTranslate || (s -= this.translate); var a = 0; this.isHorizontal() || (a = s, s = 0); var r = this.params.fadeEffect.crossFade ? Math.max(1 - Math.abs(i[0].progress), 0) : 1 + Math.min(Math.max(i[0].progress, -1), 0); i.css({ opacity: r }).transform("translate3d(" + s + "px, " + a + "px, 0px)") } }, setTransition: function (e) { var t = this, i = t.slides, s = t.$wrapperEl; if (i.transition(e), t.params.virtualTranslate && 0 !== e) { var a = !1; i.transitionEnd((function () { if (!a && t && !t.destroyed) { a = !0, t.animating = !1; for (var e = ["webkitTransitionEnd", "transitionend"], i = 0; i < e.length; i += 1)s.trigger(e[i]) } })) } } }, fe = { setTranslate: function () { var e, t = this.$el, i = this.$wrapperEl, a = this.slides, r = this.width, n = this.height, o = this.rtlTranslate, l = this.size, d = this.params.cubeEffect, h = this.isHorizontal(), p = this.virtual && this.params.virtual.enabled, c = 0; d.shadow && (h ? (0 === (e = i.find(".swiper-cube-shadow")).length && (e = s('<div class="swiper-cube-shadow"></div>'), i.append(e)), e.css({ height: r + "px" })) : 0 === (e = t.find(".swiper-cube-shadow")).length && (e = s('<div class="swiper-cube-shadow"></div>'), t.append(e))); for (var u = 0; u < a.length; u += 1) { var v = a.eq(u), f = u; p && (f = parseInt(v.attr("data-swiper-slide-index"), 10)); var m = 90 * f, g = Math.floor(m / 360); o && (m = -m, g = Math.floor(-m / 360)); var b = Math.max(Math.min(v[0].progress, 1), -1), w = 0, y = 0, x = 0; f % 4 == 0 ? (w = 4 * -g * l, x = 0) : (f - 1) % 4 == 0 ? (w = 0, x = 4 * -g * l) : (f - 2) % 4 == 0 ? (w = l + 4 * g * l, x = l) : (f - 3) % 4 == 0 && (w = -l, x = 3 * l + 4 * l * g), o && (w = -w), h || (y = w, w = 0); var T = "rotateX(" + (h ? 0 : -m) + "deg) rotateY(" + (h ? m : 0) + "deg) translate3d(" + w + "px, " + y + "px, " + x + "px)"; if (b <= 1 && b > -1 && (c = 90 * f + 90 * b, o && (c = 90 * -f - 90 * b)), v.transform(T), d.slideShadows) { var E = h ? v.find(".swiper-slide-shadow-left") : v.find(".swiper-slide-shadow-top"), S = h ? v.find(".swiper-slide-shadow-right") : v.find(".swiper-slide-shadow-bottom"); 0 === E.length && (E = s('<div class="swiper-slide-shadow-' + (h ? "left" : "top") + '"></div>'), v.append(E)), 0 === S.length && (S = s('<div class="swiper-slide-shadow-' + (h ? "right" : "bottom") + '"></div>'), v.append(S)), E.length && (E[0].style.opacity = Math.max(-b, 0)), S.length && (S[0].style.opacity = Math.max(b, 0)) } } if (i.css({ "-webkit-transform-origin": "50% 50% -" + l / 2 + "px", "-moz-transform-origin": "50% 50% -" + l / 2 + "px", "-ms-transform-origin": "50% 50% -" + l / 2 + "px", "transform-origin": "50% 50% -" + l / 2 + "px" }), d.shadow) if (h) e.transform("translate3d(0px, " + (r / 2 + d.shadowOffset) + "px, " + -r / 2 + "px) rotateX(90deg) rotateZ(0deg) scale(" + d.shadowScale + ")"); else { var C = Math.abs(c) - 90 * Math.floor(Math.abs(c) / 90), M = 1.5 - (Math.sin(2 * C * Math.PI / 360) / 2 + Math.cos(2 * C * Math.PI / 360) / 2), P = d.shadowScale, z = d.shadowScale / M, k = d.shadowOffset; e.transform("scale3d(" + P + ", 1, " + z + ") translate3d(0px, " + (n / 2 + k) + "px, " + -n / 2 / z + "px) rotateX(-90deg)") } var $ = j.isSafari || j.isUiWebView ? -l / 2 : 0; i.transform("translate3d(0px,0," + $ + "px) rotateX(" + (this.isHorizontal() ? 0 : c) + "deg) rotateY(" + (this.isHorizontal() ? -c : 0) + "deg)") }, setTransition: function (e) { var t = this.$el; this.slides.transition(e).find(".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left").transition(e), this.params.cubeEffect.shadow && !this.isHorizontal() && t.find(".swiper-cube-shadow").transition(e) } }, me = { setTranslate: function () { for (var e = this.slides, t = this.rtlTranslate, i = 0; i < e.length; i += 1) { var a = e.eq(i), r = a[0].progress; this.params.flipEffect.limitRotation && (r = Math.max(Math.min(a[0].progress, 1), -1)); var n = -180 * r, o = 0, l = -a[0].swiperSlideOffset, d = 0; if (this.isHorizontal() ? t && (n = -n) : (d = l, l = 0, o = -n, n = 0), a[0].style.zIndex = -Math.abs(Math.round(r)) + e.length, this.params.flipEffect.slideShadows) { var h = this.isHorizontal() ? a.find(".swiper-slide-shadow-left") : a.find(".swiper-slide-shadow-top"), p = this.isHorizontal() ? a.find(".swiper-slide-shadow-right") : a.find(".swiper-slide-shadow-bottom"); 0 === h.length && (h = s('<div class="swiper-slide-shadow-' + (this.isHorizontal() ? "left" : "top") + '"></div>'), a.append(h)), 0 === p.length && (p = s('<div class="swiper-slide-shadow-' + (this.isHorizontal() ? "right" : "bottom") + '"></div>'), a.append(p)), h.length && (h[0].style.opacity = Math.max(-r, 0)), p.length && (p[0].style.opacity = Math.max(r, 0)) } a.transform("translate3d(" + l + "px, " + d + "px, 0px) rotateX(" + o + "deg) rotateY(" + n + "deg)") } }, setTransition: function (e) { var t = this, i = t.slides, s = t.activeIndex, a = t.$wrapperEl; if (i.transition(e).find(".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left").transition(e), t.params.virtualTranslate && 0 !== e) { var r = !1; i.eq(s).transitionEnd((function () { if (!r && t && !t.destroyed) { r = !0, t.animating = !1; for (var e = ["webkitTransitionEnd", "transitionend"], i = 0; i < e.length; i += 1)a.trigger(e[i]) } })) } } }, ge = { setTranslate: function () { for (var e = this.width, t = this.height, i = this.slides, a = this.$wrapperEl, r = this.slidesSizesGrid, n = this.params.coverflowEffect, l = this.isHorizontal(), d = this.translate, h = l ? e / 2 - d : t / 2 - d, p = l ? n.rotate : -n.rotate, c = n.depth, u = 0, v = i.length; u < v; u += 1) { var f = i.eq(u), m = r[u], g = (h - f[0].swiperSlideOffset - m / 2) / m * n.modifier, b = l ? p * g : 0, w = l ? 0 : p * g, y = -c * Math.abs(g), x = n.stretch; "string" == typeof x && -1 !== x.indexOf("%") && (x = parseFloat(n.stretch) / 100 * m); var T = l ? 0 : x * g, E = l ? x * g : 0; Math.abs(E) < .001 && (E = 0), Math.abs(T) < .001 && (T = 0), Math.abs(y) < .001 && (y = 0), Math.abs(b) < .001 && (b = 0), Math.abs(w) < .001 && (w = 0); var S = "translate3d(" + E + "px," + T + "px," + y + "px)  rotateX(" + w + "deg) rotateY(" + b + "deg)"; if (f.transform(S), f[0].style.zIndex = 1 - Math.abs(Math.round(g)), n.slideShadows) { var C = l ? f.find(".swiper-slide-shadow-left") : f.find(".swiper-slide-shadow-top"), M = l ? f.find(".swiper-slide-shadow-right") : f.find(".swiper-slide-shadow-bottom"); 0 === C.length && (C = s('<div class="swiper-slide-shadow-' + (l ? "left" : "top") + '"></div>'), f.append(C)), 0 === M.length && (M = s('<div class="swiper-slide-shadow-' + (l ? "right" : "bottom") + '"></div>'), f.append(M)), C.length && (C[0].style.opacity = g > 0 ? g : 0), M.length && (M[0].style.opacity = -g > 0 ? -g : 0) } } (o.pointerEvents || o.prefixedPointerEvents) && (a[0].style.perspectiveOrigin = h + "px 50%") }, setTransition: function (e) { this.slides.transition(e).find(".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left").transition(e) } }, be = { init: function () { var e = this.params.thumbs, t = this.constructor; e.swiper instanceof t ? (this.thumbs.swiper = e.swiper, n.extend(this.thumbs.swiper.originalParams, { watchSlidesProgress: !0, slideToClickedSlide: !1 }), n.extend(this.thumbs.swiper.params, { watchSlidesProgress: !0, slideToClickedSlide: !1 })) : n.isObject(e.swiper) && (this.thumbs.swiper = new t(n.extend({}, e.swiper, { watchSlidesVisibility: !0, watchSlidesProgress: !0, slideToClickedSlide: !1 })), this.thumbs.swiperCreated = !0), this.thumbs.swiper.$el.addClass(this.params.thumbs.thumbsContainerClass), this.thumbs.swiper.on("tap", this.thumbs.onThumbClick) }, onThumbClick: function () { var e = this.thumbs.swiper; if (e) { var t = e.clickedIndex, i = e.clickedSlide; if (!(i && s(i).hasClass(this.params.thumbs.slideThumbActiveClass) || null == t)) { var a; if (a = e.params.loop ? parseInt(s(e.clickedSlide).attr("data-swiper-slide-index"), 10) : t, this.params.loop) { var r = this.activeIndex; this.slides.eq(r).hasClass(this.params.slideDuplicateClass) && (this.loopFix(), this._clientLeft = this.$wrapperEl[0].clientLeft, r = this.activeIndex); var n = this.slides.eq(r).prevAll('[data-swiper-slide-index="' + a + '"]').eq(0).index(), o = this.slides.eq(r).nextAll('[data-swiper-slide-index="' + a + '"]').eq(0).index(); a = void 0 === n ? o : void 0 === o ? n : o - r < r - n ? o : n } this.slideTo(a) } } }, update: function (e) { var t = this.thumbs.swiper; if (t) { var i = "auto" === t.params.slidesPerView ? t.slidesPerViewDynamic() : t.params.slidesPerView; if (this.realIndex !== t.realIndex) { var s, a = t.activeIndex; if (t.params.loop) { t.slides.eq(a).hasClass(t.params.slideDuplicateClass) && (t.loopFix(), t._clientLeft = t.$wrapperEl[0].clientLeft, a = t.activeIndex); var r = t.slides.eq(a).prevAll('[data-swiper-slide-index="' + this.realIndex + '"]').eq(0).index(), n = t.slides.eq(a).nextAll('[data-swiper-slide-index="' + this.realIndex + '"]').eq(0).index(); s = void 0 === r ? n : void 0 === n ? r : n - a == a - r ? a : n - a < a - r ? n : r } else s = this.realIndex; t.visibleSlidesIndexes && t.visibleSlidesIndexes.indexOf(s) < 0 && (t.params.centeredSlides ? s = s > a ? s - Math.floor(i / 2) + 1 : s + Math.floor(i / 2) - 1 : s > a && (s = s - i + 1), t.slideTo(s, e ? 0 : void 0)) } var o = 1, l = this.params.thumbs.slideThumbActiveClass; if (this.params.slidesPerView > 1 && !this.params.centeredSlides && (o = this.params.slidesPerView), this.params.thumbs.multipleActiveThumbs || (o = 1), o = Math.floor(o), t.slides.removeClass(l), t.params.loop || t.params.virtual && t.params.virtual.enabled) for (var d = 0; d < o; d += 1)t.$wrapperEl.children('[data-swiper-slide-index="' + (this.realIndex + d) + '"]').addClass(l); else for (var h = 0; h < o; h += 1)t.slides.eq(this.realIndex + h).addClass(l) } } }, we = [R, q, K, U, Z, J, te, { name: "mousewheel", params: { mousewheel: { enabled: !1, releaseOnEdges: !1, invert: !1, forceToAxis: !1, sensitivity: 1, eventsTarged: "container" } }, create: function () { n.extend(this, { mousewheel: { enabled: !1, enable: ie.enable.bind(this), disable: ie.disable.bind(this), handle: ie.handle.bind(this), handleMouseEnter: ie.handleMouseEnter.bind(this), handleMouseLeave: ie.handleMouseLeave.bind(this), animateSlider: ie.animateSlider.bind(this), releaseScroll: ie.releaseScroll.bind(this), lastScrollTime: n.now(), lastEventBeforeSnap: void 0, recentWheelEvents: [] } }) }, on: { init: function () { !this.params.mousewheel.enabled && this.params.cssMode && this.mousewheel.disable(), this.params.mousewheel.enabled && this.mousewheel.enable() }, destroy: function () { this.params.cssMode && this.mousewheel.enable(), this.mousewheel.enabled && this.mousewheel.disable() } } }, { name: "navigation", params: { navigation: { nextEl: null, prevEl: null, hideOnClick: !1, disabledClass: "swiper-button-disabled", hiddenClass: "swiper-button-hidden", lockClass: "swiper-button-lock" } }, create: function () { n.extend(this, { navigation: { init: se.init.bind(this), update: se.update.bind(this), destroy: se.destroy.bind(this), onNextClick: se.onNextClick.bind(this), onPrevClick: se.onPrevClick.bind(this) } }) }, on: { init: function () { this.navigation.init(), this.navigation.update() }, toEdge: function () { this.navigation.update() }, fromEdge: function () { this.navigation.update() }, destroy: function () { this.navigation.destroy() }, click: function (e) { var t, i = this.navigation, a = i.$nextEl, r = i.$prevEl; !this.params.navigation.hideOnClick || s(e.target).is(r) || s(e.target).is(a) || (a ? t = a.hasClass(this.params.navigation.hiddenClass) : r && (t = r.hasClass(this.params.navigation.hiddenClass)), !0 === t ? this.emit("navigationShow", this) : this.emit("navigationHide", this), a && a.toggleClass(this.params.navigation.hiddenClass), r && r.toggleClass(this.params.navigation.hiddenClass)) } } }, { name: "pagination", params: { pagination: { el: null, bulletElement: "span", clickable: !1, hideOnClick: !1, renderBullet: null, renderProgressbar: null, renderFraction: null, renderCustom: null, progressbarOpposite: !1, type: "bullets", dynamicBullets: !1, dynamicMainBullets: 1, formatFractionCurrent: function (e) { return e }, formatFractionTotal: function (e) { return e }, bulletClass: "swiper-pagination-bullet", bulletActiveClass: "swiper-pagination-bullet-active", modifierClass: "swiper-pagination-", currentClass: "swiper-pagination-current", totalClass: "swiper-pagination-total", hiddenClass: "swiper-pagination-hidden", progressbarFillClass: "swiper-pagination-progressbar-fill", progressbarOppositeClass: "swiper-pagination-progressbar-opposite", clickableClass: "swiper-pagination-clickable", lockClass: "swiper-pagination-lock" } }, create: function () { n.extend(this, { pagination: { init: ae.init.bind(this), render: ae.render.bind(this), update: ae.update.bind(this), destroy: ae.destroy.bind(this), dynamicBulletIndex: 0 } }) }, on: { init: function () { this.pagination.init(), this.pagination.render(), this.pagination.update() }, activeIndexChange: function () { (this.params.loop || void 0 === this.snapIndex) && this.pagination.update() }, snapIndexChange: function () { this.params.loop || this.pagination.update() }, slidesLengthChange: function () { this.params.loop && (this.pagination.render(), this.pagination.update()) }, snapGridLengthChange: function () { this.params.loop || (this.pagination.render(), this.pagination.update()) }, destroy: function () { this.pagination.destroy() }, click: function (e) { this.params.pagination.el && this.params.pagination.hideOnClick && this.pagination.$el.length > 0 && !s(e.target).hasClass(this.params.pagination.bulletClass) && (!0 === this.pagination.$el.hasClass(this.params.pagination.hiddenClass) ? this.emit("paginationShow", this) : this.emit("paginationHide", this), this.pagination.$el.toggleClass(this.params.pagination.hiddenClass)) } } }, { name: "scrollbar", params: { scrollbar: { el: null, dragSize: "auto", hide: !1, draggable: !1, snapOnRelease: !0, lockClass: "swiper-scrollbar-lock", dragClass: "swiper-scrollbar-drag" } }, create: function () { n.extend(this, { scrollbar: { init: re.init.bind(this), destroy: re.destroy.bind(this), updateSize: re.updateSize.bind(this), setTranslate: re.setTranslate.bind(this), setTransition: re.setTransition.bind(this), enableDraggable: re.enableDraggable.bind(this), disableDraggable: re.disableDraggable.bind(this), setDragPosition: re.setDragPosition.bind(this), getPointerPosition: re.getPointerPosition.bind(this), onDragStart: re.onDragStart.bind(this), onDragMove: re.onDragMove.bind(this), onDragEnd: re.onDragEnd.bind(this), isTouched: !1, timeout: null, dragTimeout: null } }) }, on: { init: function () { this.scrollbar.init(), this.scrollbar.updateSize(), this.scrollbar.setTranslate() }, update: function () { this.scrollbar.updateSize() }, resize: function () { this.scrollbar.updateSize() }, observerUpdate: function () { this.scrollbar.updateSize() }, setTranslate: function () { this.scrollbar.setTranslate() }, setTransition: function (e) { this.scrollbar.setTransition(e) }, destroy: function () { this.scrollbar.destroy() } } }, { name: "parallax", params: { parallax: { enabled: !1 } }, create: function () { n.extend(this, { parallax: { setTransform: ne.setTransform.bind(this), setTranslate: ne.setTranslate.bind(this), setTransition: ne.setTransition.bind(this) } }) }, on: { beforeInit: function () { this.params.parallax.enabled && (this.params.watchSlidesProgress = !0, this.originalParams.watchSlidesProgress = !0) }, init: function () { this.params.parallax.enabled && this.parallax.setTranslate() }, setTranslate: function () { this.params.parallax.enabled && this.parallax.setTranslate() }, setTransition: function (e) { this.params.parallax.enabled && this.parallax.setTransition(e) } } }, { name: "zoom", params: { zoom: { enabled: !1, maxRatio: 3, minRatio: 1, toggle: !0, containerClass: "swiper-zoom-container", zoomedSlideClass: "swiper-slide-zoomed" } }, create: function () { var e = this, t = { enabled: !1, scale: 1, currentScale: 1, isScaling: !1, gesture: { $slideEl: void 0, slideWidth: void 0, slideHeight: void 0, $imageEl: void 0, $imageWrapEl: void 0, maxRatio: 3 }, image: { isTouched: void 0, isMoved: void 0, currentX: void 0, currentY: void 0, minX: void 0, minY: void 0, maxX: void 0, maxY: void 0, width: void 0, height: void 0, startX: void 0, startY: void 0, touchesStart: {}, touchesCurrent: {} }, velocity: { x: void 0, y: void 0, prevPositionX: void 0, prevPositionY: void 0, prevTime: void 0 } }; "onGestureStart onGestureChange onGestureEnd onTouchStart onTouchMove onTouchEnd onTransitionEnd toggle enable disable in out".split(" ").forEach((function (i) { t[i] = oe[i].bind(e) })), n.extend(e, { zoom: t }); var i = 1; Object.defineProperty(e.zoom, "scale", { get: function () { return i }, set: function (t) { if (i !== t) { var s = e.zoom.gesture.$imageEl ? e.zoom.gesture.$imageEl[0] : void 0, a = e.zoom.gesture.$slideEl ? e.zoom.gesture.$slideEl[0] : void 0; e.emit("zoomChange", t, s, a) } i = t } }) }, on: { init: function () { this.params.zoom.enabled && this.zoom.enable() }, destroy: function () { this.zoom.disable() }, touchStart: function (e) { this.zoom.enabled && this.zoom.onTouchStart(e) }, touchEnd: function (e) { this.zoom.enabled && this.zoom.onTouchEnd(e) }, doubleTap: function (e) { this.params.zoom.enabled && this.zoom.enabled && this.params.zoom.toggle && this.zoom.toggle(e) }, transitionEnd: function () { this.zoom.enabled && this.params.zoom.enabled && this.zoom.onTransitionEnd() }, slideChange: function () { this.zoom.enabled && this.params.zoom.enabled && this.params.cssMode && this.zoom.onTransitionEnd() } } }, { name: "lazy", params: { lazy: { enabled: !1, loadPrevNext: !1, loadPrevNextAmount: 1, loadOnTransitionStart: !1, elementClass: "swiper-lazy", loadingClass: "swiper-lazy-loading", loadedClass: "swiper-lazy-loaded", preloaderClass: "swiper-lazy-preloader" } }, create: function () { n.extend(this, { lazy: { initialImageLoaded: !1, load: le.load.bind(this), loadInSlide: le.loadInSlide.bind(this) } }) }, on: { beforeInit: function () { this.params.lazy.enabled && this.params.preloadImages && (this.params.preloadImages = !1) }, init: function () { this.params.lazy.enabled && !this.params.loop && 0 === this.params.initialSlide && this.lazy.load() }, scroll: function () { this.params.freeMode && !this.params.freeModeSticky && this.lazy.load() }, resize: function () { this.params.lazy.enabled && this.lazy.load() }, scrollbarDragMove: function () { this.params.lazy.enabled && this.lazy.load() }, transitionStart: function () { this.params.lazy.enabled && (this.params.lazy.loadOnTransitionStart || !this.params.lazy.loadOnTransitionStart && !this.lazy.initialImageLoaded) && this.lazy.load() }, transitionEnd: function () { this.params.lazy.enabled && !this.params.lazy.loadOnTransitionStart && this.lazy.load() }, slideChange: function () { this.params.lazy.enabled && this.params.cssMode && this.lazy.load() } } }, { name: "controller", params: { controller: { control: void 0, inverse: !1, by: "slide" } }, create: function () { n.extend(this, { controller: { control: this.params.controller.control, getInterpolateFunction: de.getInterpolateFunction.bind(this), setTranslate: de.setTranslate.bind(this), setTransition: de.setTransition.bind(this) } }) }, on: { update: function () { this.controller.control && this.controller.spline && (this.controller.spline = void 0, delete this.controller.spline) }, resize: function () { this.controller.control && this.controller.spline && (this.controller.spline = void 0, delete this.controller.spline) }, observerUpdate: function () { this.controller.control && this.controller.spline && (this.controller.spline = void 0, delete this.controller.spline) }, setTranslate: function (e, t) { this.controller.control && this.controller.setTranslate(e, t) }, setTransition: function (e, t) { this.controller.control && this.controller.setTransition(e, t) } } }, { name: "a11y", params: { a11y: { enabled: !0, notificationClass: "swiper-notification", prevSlideMessage: "Previous slide", nextSlideMessage: "Next slide", firstSlideMessage: "This is the first slide", lastSlideMessage: "This is the last slide", paginationBulletMessage: "Go to slide {{index}}" } }, create: function () { var e = this; n.extend(e, { a11y: { liveRegion: s('<span class="' + e.params.a11y.notificationClass + '" aria-live="assertive" aria-atomic="true"></span>') } }), Object.keys(he).forEach((function (t) { e.a11y[t] = he[t].bind(e) })) }, on: { init: function () { this.params.a11y.enabled && (this.a11y.init(), this.a11y.updateNavigation()) }, toEdge: function () { this.params.a11y.enabled && this.a11y.updateNavigation() }, fromEdge: function () { this.params.a11y.enabled && this.a11y.updateNavigation() }, paginationUpdate: function () { this.params.a11y.enabled && this.a11y.updatePagination() }, destroy: function () { this.params.a11y.enabled && this.a11y.destroy() } } }, { name: "history", params: { history: { enabled: !1, replaceState: !1, key: "slides" } }, create: function () { n.extend(this, { history: { init: pe.init.bind(this), setHistory: pe.setHistory.bind(this), setHistoryPopState: pe.setHistoryPopState.bind(this), scrollToSlide: pe.scrollToSlide.bind(this), destroy: pe.destroy.bind(this) } }) }, on: { init: function () { this.params.history.enabled && this.history.init() }, destroy: function () { this.params.history.enabled && this.history.destroy() }, transitionEnd: function () { this.history.initialized && this.history.setHistory(this.params.history.key, this.activeIndex) }, slideChange: function () { this.history.initialized && this.params.cssMode && this.history.setHistory(this.params.history.key, this.activeIndex) } } }, { name: "hash-navigation", params: { hashNavigation: { enabled: !1, replaceState: !1, watchState: !1 } }, create: function () { n.extend(this, { hashNavigation: { initialized: !1, init: ce.init.bind(this), destroy: ce.destroy.bind(this), setHash: ce.setHash.bind(this), onHashCange: ce.onHashCange.bind(this) } }) }, on: { init: function () { this.params.hashNavigation.enabled && this.hashNavigation.init() }, destroy: function () { this.params.hashNavigation.enabled && this.hashNavigation.destroy() }, transitionEnd: function () { this.hashNavigation.initialized && this.hashNavigation.setHash() }, slideChange: function () { this.hashNavigation.initialized && this.params.cssMode && this.hashNavigation.setHash() } } }, { name: "autoplay", params: { autoplay: { enabled: !1, delay: 3e3, waitForTransition: !0, disableOnInteraction: !0, stopOnLastSlide: !1, reverseDirection: !1 } }, create: function () { var e = this; n.extend(e, { autoplay: { running: !1, paused: !1, run: ue.run.bind(e), start: ue.start.bind(e), stop: ue.stop.bind(e), pause: ue.pause.bind(e), onVisibilityChange: function () { "hidden" === document.visibilityState && e.autoplay.running && e.autoplay.pause(), "visible" === document.visibilityState && e.autoplay.paused && (e.autoplay.run(), e.autoplay.paused = !1) }, onTransitionEnd: function (t) { e && !e.destroyed && e.$wrapperEl && t.target === this && (e.$wrapperEl[0].removeEventListener("transitionend", e.autoplay.onTransitionEnd), e.$wrapperEl[0].removeEventListener("webkitTransitionEnd", e.autoplay.onTransitionEnd), e.autoplay.paused = !1, e.autoplay.running ? e.autoplay.run() : e.autoplay.stop()) } } }) }, on: { init: function () { this.params.autoplay.enabled && (this.autoplay.start(), document.addEventListener("visibilitychange", this.autoplay.onVisibilityChange)) }, beforeTransitionStart: function (e, t) { this.autoplay.running && (t || !this.params.autoplay.disableOnInteraction ? this.autoplay.pause(e) : this.autoplay.stop()) }, sliderFirstMove: function () { this.autoplay.running && (this.params.autoplay.disableOnInteraction ? this.autoplay.stop() : this.autoplay.pause()) }, touchEnd: function () { this.params.cssMode && this.autoplay.paused && !this.params.autoplay.disableOnInteraction && this.autoplay.run() }, destroy: function () { this.autoplay.running && this.autoplay.stop(), document.removeEventListener("visibilitychange", this.autoplay.onVisibilityChange) } } }, { name: "effect-fade", params: { fadeEffect: { crossFade: !1 } }, create: function () { n.extend(this, { fadeEffect: { setTranslate: ve.setTranslate.bind(this), setTransition: ve.setTransition.bind(this) } }) }, on: { beforeInit: function () { if ("fade" === this.params.effect) { this.classNames.push(this.params.containerModifierClass + "fade"); var e = { slidesPerView: 1, slidesPerColumn: 1, slidesPerGroup: 1, watchSlidesProgress: !0, spaceBetween: 0, virtualTranslate: !0 }; n.extend(this.params, e), n.extend(this.originalParams, e) } }, setTranslate: function () { "fade" === this.params.effect && this.fadeEffect.setTranslate() }, setTransition: function (e) { "fade" === this.params.effect && this.fadeEffect.setTransition(e) } } }, { name: "effect-cube", params: { cubeEffect: { slideShadows: !0, shadow: !0, shadowOffset: 20, shadowScale: .94 } }, create: function () { n.extend(this, { cubeEffect: { setTranslate: fe.setTranslate.bind(this), setTransition: fe.setTransition.bind(this) } }) }, on: { beforeInit: function () { if ("cube" === this.params.effect) { this.classNames.push(this.params.containerModifierClass + "cube"), this.classNames.push(this.params.containerModifierClass + "3d"); var e = { slidesPerView: 1, slidesPerColumn: 1, slidesPerGroup: 1, watchSlidesProgress: !0, resistanceRatio: 0, spaceBetween: 0, centeredSlides: !1, virtualTranslate: !0 }; n.extend(this.params, e), n.extend(this.originalParams, e) } }, setTranslate: function () { "cube" === this.params.effect && this.cubeEffect.setTranslate() }, setTransition: function (e) { "cube" === this.params.effect && this.cubeEffect.setTransition(e) } } }, { name: "effect-flip", params: { flipEffect: { slideShadows: !0, limitRotation: !0 } }, create: function () { n.extend(this, { flipEffect: { setTranslate: me.setTranslate.bind(this), setTransition: me.setTransition.bind(this) } }) }, on: { beforeInit: function () { if ("flip" === this.params.effect) { this.classNames.push(this.params.containerModifierClass + "flip"), this.classNames.push(this.params.containerModifierClass + "3d"); var e = { slidesPerView: 1, slidesPerColumn: 1, slidesPerGroup: 1, watchSlidesProgress: !0, spaceBetween: 0, virtualTranslate: !0 }; n.extend(this.params, e), n.extend(this.originalParams, e) } }, setTranslate: function () { "flip" === this.params.effect && this.flipEffect.setTranslate() }, setTransition: function (e) { "flip" === this.params.effect && this.flipEffect.setTransition(e) } } }, { name: "effect-coverflow", params: { coverflowEffect: { rotate: 50, stretch: 0, depth: 100, modifier: 1, slideShadows: !0 } }, create: function () { n.extend(this, { coverflowEffect: { setTranslate: ge.setTranslate.bind(this), setTransition: ge.setTransition.bind(this) } }) }, on: { beforeInit: function () { "coverflow" === this.params.effect && (this.classNames.push(this.params.containerModifierClass + "coverflow"), this.classNames.push(this.params.containerModifierClass + "3d"), this.params.watchSlidesProgress = !0, this.originalParams.watchSlidesProgress = !0) }, setTranslate: function () { "coverflow" === this.params.effect && this.coverflowEffect.setTranslate() }, setTransition: function (e) { "coverflow" === this.params.effect && this.coverflowEffect.setTransition(e) } } }, { name: "thumbs", params: { thumbs: { multipleActiveThumbs: !0, swiper: null, slideThumbActiveClass: "swiper-slide-thumb-active", thumbsContainerClass: "swiper-container-thumbs" } }, create: function () { n.extend(this, { thumbs: { swiper: null, init: be.init.bind(this), update: be.update.bind(this), onThumbClick: be.onThumbClick.bind(this) } }) }, on: { beforeInit: function () { var e = this.params.thumbs; e && e.swiper && (this.thumbs.init(), this.thumbs.update(!0)) }, slideChange: function () { this.thumbs.swiper && this.thumbs.update() }, update: function () { this.thumbs.swiper && this.thumbs.update() }, resize: function () { this.thumbs.swiper && this.thumbs.update() }, observerUpdate: function () { this.thumbs.swiper && this.thumbs.update() }, setTransition: function (e) { var t = this.thumbs.swiper; t && t.setTransition(e) }, beforeDestroy: function () { var e = this.thumbs.swiper; e && this.thumbs.swiperCreated && e && e.destroy() } } }]; return void 0 === W.use && (W.use = W.Class.use, W.installModule = W.Class.installModule), W.use(we), W }));;
(function($) {
    $('[data-copy-classes-to-parent="true"]').each(function (index, element) {
        var parent = $(element).parent();
        parent.addClass($(element).attr('class'));
    });

    $('[data-add-classes-to-parent]').each(function (index, element) {
        var parent = $(element).parent();
        parent.addClass($(element).attr('data-add-classes-to-parent'));
    });
})(jQuery);;
(function($) {

    // Vars
    var $xhr,
        $timer,
        $window,
        $menuHolder,
        $contentContainer,
        $stickyBg,
        isSticky = false,
        $inspirationMenu,
        $searchForm,
        $searchInput,
        $searchResults,
        $cartHolder,
        $mobileMenuHolder,
        $mobileToggle,
        $mobileCartHolder,
        $mobileCartToggle,
        $mobileMoreMenuToggle,
        currentItem = null
        clickInContainer = false;

    function initHeader() {
        setVars();
        modifyDom();
        addEvents();
    }

    function setVars() {
        $window =                   $(window);
        $menuHolder =               $('.main-menu-holder');
        $contentContainer =         $('.content-container');
        $stickyBg =                 $('.sticky-bg');
        $regNrHolder =              $('.select-car');
        $inspirationMenu =          $('.inspiration-menu');

        $shopMenu =                 $('#shop-menu');

        $searchToggle =             $('#ax-search-toggle');
        $searchForm =               $('#search');
        $searchInput =              $('#search input');
        $searchResults =            $('#ax-search-results');
        $cartHolder =               $('#cart-dropdown');

        //MOBILE
        $mobileMenuWrapper =        $('#ax-mobile-menu-wrapper');
        $mobileMenuHolder =         $('#ax-mobile-menu-holder');
        $mobileSearchWrapper =      $('#ax-mobile-search-wrapper');
        $mobileSearchHolder =       $('#ax-mobile-search-holder');
        $mobileSearchToggle =       $('#toggle-mobile-search');
        $mobileToggle =             $('#ax-mobile-closer');
        $mobileCartHolder =         $('#ax-mobile-cart-holder');
        $mobileCartToggle =         $('#ax-mobile-cart-closer');
        $mobileMoreMenuToggle = $('.ax-mobile-menu[data-menu-toggle-state]')
        clickInContainer = false;
    }

    function modifyDom() {

        // Fallback for non-transform support
        if (!Modernizr.csstransforms3d) {
            $mobileMenuHolder.addClass('ax-mobile-fallback');
            $mobileCartHolder.addClass('ax-mobile-fallback');
        }

        $('.ax-submenu-holder li').each(function() {
            if ($(this).find('> div').length) {
                $(this).addClass('has-children');
            }
        });
    }

    function addEvents() {
        if ($menuHolder.length) {
            
            $searchInput.on('keyup', eventHandlers.doSearch);
            $searchInput.on('focusin', eventHandlers.doSearch);
            $searchInput.on('focusout', function () {
                setTimeout(function () {
                    $searchResults.hide();
                }, 200);
                  
            });
            $searchResults.on('focusin', function () {
                $('#shop-menu').hide();
                jQuery('body').removeClass('modal-open');
                $searchResults.show();
            });
        }

        // Sticky menu
        if ($('#ax-header.blue-menu').length) {
            window.headerOffsetTop = $('#ax-header').offset().top;
            window.onscroll = function () { eventHandlers.onScroll(); };
            eventHandlers.onScroll();
        }

        // Mega menu nav
        $('#shop-menu .shop-menu-nav li.shop-nav-item a').on('click', eventHandlers.onShopMenuNavClick);
        $('#shop-menu').click(function (e) { // Click outside
            if (!jQuery(e.target).parents('#shop-menu > .container').length) {
                jQuery('.ax-search-holder').hide();
            }
        });

        // Toggle megamenu
        $('#shop-page-link').click(function (e) {
            e.preventDefault();
            clickInContainer = false;
            jQuery('#shop-menu').toggle();
            jQuery('body').toggleClass('modal-open');

            return false;
        });

        $('#shop-menu .container').click(function (e) {
            clickInContainer = true;
        });

        $('#shop-menu').click(function (e) {
            if (clickInContainer == false) { 
                $('#shop-menu').hide();
                $('body').toggleClass('modal-open');
            }
            clickInContainer = false;
        });

        $('.cart-quantity', $cartHolder).click(eventHandlers.toggleCartIn);
        

        //Meta-menu
        $('.toggle-meta-links').on('click', eventHandlers.toggleMetaMenu);

        // MOBILE MENU
        $('#toggle-mobile-menu, #ax-mobile-closer').on('click', eventHandlers.toggleMobileMenu);
        $('#toggle-mobile-search').on('click', eventHandlers.toggleMobileSearch);
        $('li.ax-has-mobile-submenu', $mobileMenuHolder).on('click', eventHandlers.toggleMobileSubMenu);
        $('#mobile-search input').on('keypress', function (e) {
            if (!('ontouchstart' in window)) return;

            if (e.which == 13) {
                $(this).parent().submit();
            }
        });
        $mobileMenuWrapper.on('click', function (e) {
            if ($mobileMenuHolder.hasClass('show-ax-mobile-menu')) {
                if (e.pageX > $mobileMenuHolder.width()) {
                    eventHandlers.toggleMobileMenu();
                }
            }
        });

        // MOBILE CART
        $('#toggle-mobile-cart, #mobile-cart-quantity, #ax-mobile-cart-closer').on('click', eventHandlers.toggleMobileCart);

        // Ipad normal cart toggle
        if (isTablet) {
            $('#toggle-cart').on('touchend click', function () {
                $(document).on('touchend click', function (e) {
                    if (!$.contains($('#cart-dropdown').get(0), e.target)) {
                        $('#cart-dropdown').removeClass('visible');
                    }
                });
            });
        }

        $('.toggle-right-menu-items').on('click', eventHandlers.toggleRightMenuItems);

        $mobileMoreMenuToggle.on('click', eventHandlers.onMobileMenuToggleClick);

    }
    var eventHandlers = {
        onMobileMenuToggleClick: function (e) {
            e.preventDefault();
            const currentState = $(e.currentTarget).attr('data-menu-toggle-state');
            $(e.currentTarget).attr('data-menu-toggle-state', currentState === 'closed' ? 'open' : 'closed');
        },

        toggleRightMenuItems: function (e) {
            const source = $(this).data('source');
            const searchHolder = $('.ax-search-holder');
            switch (source) {
                case 'cart-modal':
                    e.preventDefault();
                    searchHolder.hide();
                    $cartHolder.toggle();
                    break;
                case 'search-modal':
                    e.preventDefault();
                    $cartHolder.hide();
                    $shopMenu.hide();
                    searchHolder.toggle();
                    if (searchHolder.is(':visible'))
                        $searchInput.focus();
                    break;
                case 'login-modal':
                    searchHolder.hide();
                    $cartHolder.hide();
                    break;
            }
        },
        outsideMenuClick: function(e) {
            if (!$(e.target).closest('.category-menu').length) {
                $('.ax-submenu-holder').removeClass('selected');
                $('.category-menu > li').removeClass('selected');
                $('.category-menu > li > .ax-submenu-holder').removeClass('selected');
                $('.category-menu .ax-submenu-holder li > div').hide();
            }
            
        },
        onScroll: function () {
            var $header = $('#ax-header');
            if (window.pageYOffset > window.headerOffsetTop) {
                $header.addClass('sticky');
                $('body').addClass('has-stick-menu');
            } else {
                $header.removeClass('sticky');
                $('body').removeClass('has-stick-menu');
            }
        },
        onShopMenuNavClick: function (e) {
            e.preventDefault();

            $('.shop-nav-item').removeClass('active');
            $('.shop-menu-tab').removeClass('active');

            var $elem = $(this);
            $elem.parent().addClass('active');
            $($elem.data('controls')).addClass('active');

            return false;
        },
        onSubmenuClick: function (e) {
            var $elem = $(this);
            $elem.toggleClass('selected');
            if ($elem.parent().find('> div').length) {
                e.preventDefault();
                e.stopImmediatePropagation();
                $elem.parent().siblings('li').each(function() {
                    $(this).find('> a').removeClass('selected');
                    $(this).find('> div').hide();
                });
                $elem.parent().find('> div').toggle();
            }
        },
        onTopmenuClick: function (e) {
            var subMenuItem = $(this).find('.ax-submenu-holder');
            $(this).siblings('li').each(function() {
                $(this).removeClass('selected');
                $(this).find('.ax-submenu-holder').removeClass('selected');
            });
            $(this).toggleClass('selected');
            subMenuItem.toggleClass('selected');
            helpers.afterToggleMain();
        },
        toggleMetaMenu: function () {
            $(this).find('i').toggleClass('fa-chevron-up fa-chevron-down');
            $('.meta-links-right-holder').toggle();
        },

        toggleStickyMenu: function() {

            var offsetTop = $menuHolder.offset().top - $window.scrollTop();
            if(!isSticky && offsetTop <= 0) {
                $menuHolder.addClass('sticky');
                $menuHolder.css('width', $contentContainer.outerWidth() );
                $stickyBg.addClass('fade-in');
                $('html').addClass('sticky-header');
                if ($regNrHolder.length && $window.width() > 768) {
                    $regNrHolder.addClass('sticky');
                    $regNrHolder.css('width', $contentContainer.outerWidth());
                }
                isSticky = true;
            } else if(isSticky && $window.scrollTop() < 150) {
                $menuHolder.removeClass('sticky');
                $stickyBg.removeClass('fade-in');
                $('html').removeClass('sticky-header');
                if ($regNrHolder.length) {
                    $regNrHolder.removeClass('sticky');
                }
                isSticky = false;
            }
        },

        setCorrectMenuWidth: function() {
            $menuHolder.css('width', $contentContainer.outerWidth());
            if ($regNrHolder.length) {
                $regNrHolder.css('width', $contentContainer.outerWidth());
            }
        },

        // Set correct width on submenus
        onMenuTopLevelHover: function () {

            var _this = $(this);
            currentItem = _this;

            // Hide visible submenus
            $('.ax-submenu-level-2, .ax-submenu-level-3').hide();

            // $submenuHolder.css('top', $menuHolder.outerHeight()); TEMP HIDE
            var submenu = $('.ax-submenu-level-1', _this);
            submenu.css('width', $('.ax-submenu-header', submenu).first().outerWidth() + 1);
            helpers.afterToggleMain();
        },

        // Toggle submenus lvl1
        onMenuSubLevelHover: function () {
            helpers.doMenuSubLevelHover($(this));
        },

        onMenuHover: function () {
            var subMenuItem = $(this).find('.ax-submenu-holder');
            $('.ax-submenu-holder:visible').removeClass('selected');
            subMenuItem.addClass('selected')
            helpers.afterToggleMain();
        },


        onMenuBlockLeave: function () {
            setTimeout(function () { $('.ax-submenu-holder').removeClass('selected'); }, 200);
        },


        // lvl2
        onMenuSubLevel2Hover: function () { 

            var _this = $(this);
            currentItem = _this;

            _this.closest('ul').find('li').each(function () {
                $('.ax-submenu-level-3', $(this)).hide();
            });
            var submenu = _this.closest('li').find('.ax-submenu-level-3'); 
            submenu.show();
            helpers.afterToggleMain();
        },

        hideSubmenus: function () {
            $('.ax-submenu-level-2, .ax-submenu-level-3').hide();
            helpers.afterToggleMain();
        },


        // Toggle inspirationmenu
        showInspirationMenu: function() {
            $inspirationMenu.toggle();
        },

        // Toggles searchresult
        toggleSearchResults: function() {
            $searchResults.toggle();
        },

        // Toggles searchresult
        doSearch: function () {
            // cancel any previously-set timer
            if ($timer) {
                clearTimeout($timer);
            }

            var q = $searchInput.val().trim();
            if (q.length <= 2 || $searchInput.val() === $searchInput.attr('placeholder')) {
                $searchInput.css('border-bottom', '1px solid #BFBFBF');
                $searchResults.hide();
                $searchForm.removeClass('is-searching');
                return;
            }

            if ($xhr && $xhr.readyState != 4 && $xhr.readyState != 0) {
                $xhr.abort();
            }

            $timer = setTimeout(function () {
                $searchForm.addClass('is-searching');
                $xhr = $.getJSON("/api/search/?query=" + encodeURIComponent(q), function (html) {
                    $('.relative-search-container', $searchResults).html(html);
                    $('#ax-search-results .ax-button-primary').on('click', function() { $searchInput.closest("form").submit(); });
                    $searchInput.css('border-bottom', '1px solid #fff');
                    $searchForm.removeClass('is-searching');
                    $('#shop-menu').hide();
                    jQuery('body').removeClass('modal-open');
                    $searchResults.show();
                });
            }, 50);
        },

        toggleCartIn: function(e) {
            e.preventDefault();
            $cartHolder.addClass('visible');

            $cartHolder.one('mouseover', function(e) {
                $cartHolder.removeClass('visible');
            });
        },

        toggleMobileMenu: function (e) {
            if(e) helpers.preventDefaultStopPropagation(e);

            $mobileToggle.toggleClass('show-ax-mobile-menu');
            $mobileMenuHolder.toggleClass('show-ax-mobile-menu');
            $mobileMenuWrapper.toggleClass('show-ax-wrapper');
            $('#mobile-search input').blur();
            helpers.closeIfOpen('cart');
            helpers.closeIfOpen('search');
            helpers.afterToggle();            
        },

        toggleMobileSearch: function(e) {
            if(e) helpers.preventDefaultStopPropagation(e);

            $('#mobile-search input').focus();

            setTimeout(function() {
                $mobileSearchHolder.toggleClass('show-ax-mobile-search');
                $mobileSearchToggle.toggleClass('show-ax-mobile-search');
                helpers.closeIfOpen('cart');
                helpers.closeIfOpen('menu');
                helpers.afterToggle();

                $('#mobile-search input').focus();
            }, 50);

        },

        toggleMobileSubMenu: function(e) {
            if (!(e.target.nodeName === 'A' || e.target.nodeName === 'SPAN'))
                helpers.preventDefaultStopPropagation(e);
                

            var _this = $(e.target);

            if(!_this.hasClass('ax-has-mobile-submenu')) return;

            _this.toggleClass('ax-submenu-is-open');
            _this.children('.ax-mobile-submenu').toggle();
        },

        toggleMobileCart: function(e) {
            if(e) helpers.preventDefaultStopPropagation(e);
            $mobileCartToggle.toggleClass('show-ax-mobile-cart');
            $mobileCartHolder.toggleClass('show-ax-mobile-cart');
            helpers.closeIfOpen('menu');
            helpers.closeIfOpen('search');
            helpers.afterToggle();
        }
    };

    /*
    * Helpers
    */
    var helpers = {
        preventDefaultStopPropagation: function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
        },

        closeIfOpen: function (whichToClose) {
            if (whichToClose === 'menu') {
                if ($mobileMenuHolder.hasClass('show-ax-mobile-menu')) {
                    eventHandlers.toggleMobileMenu();
                }
            }
            else if (whichToClose === 'search') {
                if ($mobileSearchHolder.hasClass('show-ax-mobile-search')) {
                    eventHandlers.toggleMobileSearch();
                }
            }
            else {
                if ($mobileCartHolder.hasClass('show-ax-mobile-cart')) {
                    eventHandlers.toggleMobileCart();
                }
            }
        },

        afterToggle: function() {
            if( $mobileMenuHolder.hasClass('show-ax-mobile-menu') || $mobileCartHolder.hasClass('show-ax-mobile-cart') ) {
                $('.content-container').on('touchstart', helpers.preventDefaultStopPropagation);
                $('body').addClass('no-scroll');
            } else {
                $('body').removeClass('no-scroll');
                $('.content-container').off('touchstart', helpers.preventDefaultStopPropagation );
            }
        },

        doMenuSubLevelHover: function (itemIn) {
            var _this = itemIn
            currentItem = _this;

            _this.closest('ul').find('li').each(function () {
                $('.ax-submenu-level-2', $(this)).hide();
            });

            if (_this.hasClass('ax-submenu-category')) return;
            if (_this.hasClass('ax-submenu-header')) return;

            var submenu = _this.closest('li').find('.ax-submenu-level-2');
            submenu.show();
            helpers.afterToggleMain();
        },

		// calc width and length of the selected main menu item.
		// use scroll-class if window not enough
        afterToggleMain: function () {

            var maxHeight = 0;
            var widthTot = 0;

            $('.ax-submenu-level-3:visible').each(function () {
                maxHeight = $(this).height();
                widthTot += $(this).width();    
            });

            $('.ax-submenu-level-2:visible').each(function () {
                maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
                widthTot += $(this).width();  
            });

            $('.ax-submenu-level-1:visible').each(function () {

                $(this).css('height', 'auto');
                widthTot += $(this).width();
                maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;

                if ((maxHeight + 260) > window.innerHeight) {
                    $(this).parent().addClass('scroll-fix');
                    $(this).parent().height(window.innerHeight - 260);
                    $(this).parent().width(widthTot);
                    adjustAllHeight = true;
                    $(this).height(maxHeight);
                }
                else {
                    $(this).parent().removeClass('scroll-fix');
                    $(this).parent().css('height', 'auto');
                    $(this).parent().css('width', 'auto');
                }

            })

        }
    }

    $(document).ready(function() {
        initHeader();
    });
})(jQuery);;
(function ($) {
    function initCommon() {
        setVars();
        modifyDom();
        addEvents();
    };

    function setVars() {
        window.Autoexperten = {
            getParameterByName: function (name) {
                var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
                return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
            }
        };
    }

    function modifyDom() {

        if (isTablet) {
            $('#main-wrapper').css('overflow', 'hidden');
        }

        $('.same-height').sameHeight();
        $('.same-height-2').sameHeight();

        // Init responsive tabs
        fakewaffle.responsiveTabs(['xs']);

        // Init tooltip
        if ($('.has-tooltip').length)
            $('.has-tooltip').tooltip();

        if ($('div[class^=epi-]').length > 0) {
            $('.under-construction').removeClass('under-construction');
        }

        $('.standard-page-content table, .single-blog-content table, .single-project-holder .well table').addClass('table table-striped table-bordered table-responsive');

        // Tooltip
        $('.product-flag').tooltip();

        // Collage slider
        if ($(window).width() <= 768 && $('.shop-collage-block__ctas').length && $('.collage-shop-cta').length > 1) {

            $('.shop-collage-block__ctas').addClass('swiper-wrapper');
            $('.shop-collage-block__ctas .collage-shop-cta').each(function () {
                $('.shop-collage-block__ctas').append($(this).addClass('swiper-slide'));
            });
            $('.shop-collage-block__ctas > div:not(.swiper-slide)').remove();

            var swiper = new Swiper('.shop-collage-block', {
                autoplay: {
                    delay: 5000,
                    disableOnInteraction: true
                },
                loop: true,
                paginationClickable: true,
                pagination: {
                    el: '.slider-dots',
                }
            });
        }
    };

    function addEvents() {

        var showNotice = checkCookie("noticeDisplayed");
        if (showNotice) {
            $(".notice-block").show();

            $(".close-notice").click(function () {
                $(".notice-block").hide();
                setCookie("noticeDisplayed", 'yes', 1); // 1 day
            });
        }

        $('.pick-car-manually-button').on('click', function (e) {
            e.preventDefault();
            $('#choose-car-modal').data('destination', window.location.pathname);
            $('#change-car-modal').modal('hide');
            $('#choose-car-modal').modal('show');
        });

        $('.select-car h3').on('click', function () {
            if ($(window).width() < 768) {
                $(this).toggleClass('active');
                $(this).next().toggle();
            }
        });

        $('#toggle-filters').on('click', function (e) {
            if ($(window).width() < 768) {
                $(this).addClass('active');
                $('.mobile-filter-container').addClass('active');
                $('.close-mobile-overlay').fadeIn(300);
            }
        });
        $('.close-mobile-overlay').click(function (e) {
            $('#toggle-filters').removeClass('active');
            $('.mobile-filter-container').removeClass('active');
            $('.close-mobile-overlay').fadeOut(300);
        });

        $('#toggle-sort').on('click', function () {
            if ($(window).width() < 768) {
                $(this).toggleClass('active');
                $('.products-block-filter').toggle();
            }
        });

        $('.show-all-button').on('click', function (e) {
            $(this).parents('.filter-wrapper').find('.dropdown-menu').addClass('show-all');
            $(this).parent().hide();
        });

        $('.product-title a, .gtm-product-link').on('click', eventHandlers.productClick);

        $('.quantity-holder select').on('change', eventHandlers.toggleQuantityInput);
        $('#back-to-top').on('click', eventHandlers.scrollToTop);
        $('.filter-button').on('click', function () { $(this).toggleClass('selected') });

        $('.slider-holder').slidesjs({
            callback: {
                loaded: function () {
                    $(this).show();
                }
            }
        });

        $('.init-datepicker').datepicker({ format: 'yyyy-mm-dd' }).on('changeDate', function (e) { $(this).datepicker('hide') });

        // Footer mobile menu
        $('.footer-menus .header').on('click', function () {
            $(this).parent().toggleClass('active');
        })

        // MODALS
        $('#product-modal').on('shown.bs.modal', eventHandlers.setModalGoToProductHeight);
        $('#product-modal').on('show.bs.modal', eventHandlers.stopModalOnMobile);

        $('#usePromo').on('click', eventHandlers.shakeModal);

        // Social share
        $('.share-widget .share-link').on('click', eventHandlers.shareSocial);
        $('.share-widget-large .share-link').on('click', eventHandlers.shareSocial);

        // Product modal
        $('body').on('click', '.ax-single-product .preview-overlay', function (event) { eventHandlers.openProductModal(event, $(this).data('id')); });

        // Stock modal
        $('.open-stock-modal').on('click', function (event) { eventHandlers.openStockModal(event, $(this).data('id')); });

        // Store modal
        $('.open-store-modal').on('click', function (event) {
            var refreshPage = $(this).data('refreshPage');
            if (typeof refreshPage === 'undefined') {
                refreshPage = false;
            }
            eventHandlers.openStoreModal(event, refreshPage);
        });

        // Generic modal
        $('body').on('click', '.open-general-modal-link', eventHandlers.openGeneralModal);

        // Watch modal
        $('.watch, .watch-button').on('click', function (event) {
            $('#watch-form').show();
            $('.watch-holder #msg').hide();
            eventHandlers.openWatchModal(event, $(this).data('id'));
        });

        if ($('#browser-modal').length) {
            // browser modal
            $('#browser-modal .modal-close').click(function () {
                $('#browser-modal').removeClass('show');
            })

            $('#browser-modal-cancel').click(function () {
                $('#browser-modal').modal('hide');
            });

            $('#browser-modal').modal('show');
        }

        // Review modal
        $(document).on("click", ".review-button", function (event) {
            $('#review-form').show();
            $('.review-holder #msg').hide();
            $(".review-holder #thank-you-msg").hide();
            eventHandlers.openReviewModal(event, $(this).data('id'));
        });

        // Map
        $('.sweden-map').maphilight({ strokeColor: 'ffffff' });
        $('.map-counties a').on('hover', function () {
            var area = $('.map-holder map').find('area[href="' + $(this).attr('href') + '"]');
            area.hover();
        });
        $('.map-counties a').mouseover(function () {
            var area = $('.map-holder map').find('area[href="' + $(this).attr('href') + '"]');
            area.trigger('mouseover');
        });
        $('.map-counties a').mouseout(function () {
            $('.map-holder map area').trigger('mouseout');
        });

        $('.selected-categories .has-children').on('click', function (e) {
            if (e.target.nodeName === 'A') return;

            e.stopPropagation();
            var _this = $(this);
            if (_this.hasClass('is-expanded')) {
                _this.find('ul').first().hide();
                _this.removeClass('is-expanded');
            } else {
                _this.find('ul').first().show();
                _this.addClass('is-expanded');
            }
        });

        $('.ax-service-cost form').on('submit', function (e) {
            $('button div', $(this)).hide();
            $('button i', $(this)).removeClass('hidden');
        });

        // Search store from startpage
        $('.ax-find-shop form').on('submit', function () {
            $(this).find('button').text('').append($('<i class="fa fa-spinner fa-spin" />'));
        });

        $('body').on('click', '.open-price-calculation-modal', eventHandlers.openPriceCalculationModal);

        $('.ax-single-product .product-image, .ax-single-product .product-info-holder').on('click', function () {
            if ($(window).width() < 768) {
                var link = $(this).closest('.ax-single-product').find('.product-title a').attr('href');
                window.location.href = link;
            }
        });

        if ($('.dictionaryarticlepage-page').length > 0 || $('.standardpage-page').length > 0) {
            if ($('.ax-dictionary-block').length > 0 || ($('#app-offer-v3').length == 1 && $('.sidebar .col-md-12').length == 1)) {
                $(window).on('scroll', eventHandlers.toggleStickyBlocks);
            }
        }

        // Promotions
        if ('IntersectionObserver' in window) {
            var rootObserver = new IntersectionObserver(
                function (entries, observer) {
                    entries.forEach(function (entry) {
                        if (entry.isIntersecting && $(entry.target).height() > 0) {
                            dataLayer.push({
                                event: 'promotionImpression',
                                ecommerce: {
                                    promoView: {
                                        promotions: [
                                            {
                                                name: $(entry.target).data('promo-tracking-name'),
                                                position: $(entry.target).index() + 1
                                            }]
                                    }
                                }
                            });
                            observer.unobserve(entry.target);
                        }

                    });
                },
                { threshold: 1 });

            setTimeout(function () {
                $('[data-promo-tracking-name]').each(function () {
                    rootObserver.observe($(this)[0]);
                });
            }, 100);
        }
        
        $('[data-promo-tracking-name]').on('click', eventHandlers.onPromoCLick);

        window.addEventListener('CookiebotOnAccept', function () {
            if (Cookiebot.changed && window.location.search.length)
                $.get('/api/customer/cookiebotaccept' + window.location.search);
        })

        window.addEventListener('CookiebotOnDecline', function () {
            if (Cookiebot.changed)
                $.get('/api/customer/cookiebotdecline');
        })

    };

    var eventHandlers = {
        onPromoCLick: function (e) {
            var $elem = $(this);
            var pos = $('[data-promo-tracking-name]').index(this) + 1;

            dataLayer.push({
                'event': 'promotionClick',
                'ecommerce': {
                    'promoClick': {
                        'promotions': [
                            {
                                name: $elem.data('promo-tracking-name'),
                                position: pos
                            }]
                    }
                },
                'eventCallback': function () {
                    document.location = $elem.find('a').first().attr('href');
                }
            });
        },
        productClick: function (e) {
            // Hijack the click and send to GTM
            e.preventDefault();
            var productUrl = e.currentTarget.href;
            var productInfo = $(this).closest('.gtm-product-info').data();

            if (typeof productInfo === 'undefined' || productInfo == null) {
                document.location = productUrl;
                return;
            }
            dataLayer.push({
                'event': 'productClick',
                'ecommerce': {
                    'click': {
                        'actionField': { 'list': window.location.pathname + window.location.search },
                        'products': [{
                            'name': productInfo.name,
                            'id': productInfo.partNo,
                            'price': productInfo.price,
                            'brand': productInfo.brand,
                            'category': productInfo.category
                        }]
                    }
                },
                'eventCallback': function () {
                    document.location = productUrl;
                }
            });
        },

        scrollToTop: function () {
            $('html, body').animate({ scrollTop: 0 });
        },

        setModalGoToProductHeight: function () {
            var _this = $(this);

            $('.go-to-product', _this).css({
                height: $('.modal-content > div').outerHeight()
            });
        },

        stopModalOnMobile: function () {
            if ($(window).width() < 768) {
                return false;
            }
            return;
        },

        openGeneralModal: function (event) {
            console.log('openGeneralModal');
            event.preventDefault();
            var modal = $('#generic-modal');
            var link = $(this);

            var ajaxUrl = link.data('ajax-url');
            if (ajaxUrl) {
                $.getJSON(ajaxUrl, function (model) {
                    $('#generic-modal-header', modal).html(model.heading);
                    $('.sub-header', modal).html(model.subHeading);
                    $('.body', modal).html(model.content);
                    modal.modal('show');
                }).done(function () {
                    $('.ajax-loader', modal).hide();
                });
            } else {
                $('#generic-modal-header', modal).html(link.data('modal-header'));
                $('.sub-header', modal).html(link.data('modal-subheader'));
                $('.body', modal).html(link.data('modal-content'));
                modal.modal('show');
                $('.ajax-loader', modal).hide();
            }
        },

        shakeModal: function () {
            var modal = $(this).closest('.modal-dialog');
            modal.addClass('shake');
            modal.find('.modal-general-header').addClass('modal-red-header');
            setTimeout(function () {
                modal.removeClass('shake');
            }, 1000);
        },
        shareSocial: function (e) {
            var _this = $(this).children().first();

            if (_this.hasClass('prevent-default')) {
                e.preventDefault();
            }

            if (_this.hasClass('fa-facebook-square')) {
                helpers.social.facebook.share();
            }

            if (_this.hasClass('fa-twitter')) {
                helpers.social.twitter.share();
            }
        },

        openProductModal: function (event, pid) {
            event.preventDefault();
            var $productModal = $('#product-modal');

            $productModal.modal('show');
            $('.modal-content', $productModal).html('');
            $('.ajax-loader', $productModal).show();
            $.getJSON('/api/modals/product/' + pid, function (html) {

                $('.modal-content', $productModal).html(html);

                $('.quantity-holder select', $productModal).on('change', eventHandlers.toggleQuantityInput);
                $('.image-thumbnails img', $productModal).on('click', function () {
                    $('.large-image img', $productModal).attr('src', $(this).data('imageurl'));
                });
                $('.ajax-loader', $productModal).hide();
                $('.product-price-description .web-buy-button', $productModal).on('click', function () {
                    var btn = $(this);
                    var id = btn.data('id');
                    var row = btn.closest('.row');
                    var q = $('select.quantity-input', row).val();

                    if (q === 'more') {
                        q = $('input.quantity-input', row).val();
                    } else if (!q) {
                        $('.product-quantity', row).css('border', '2px solid red');
                        return;
                    }
                    $('.product-quantity', row).css('border', 'none');
                    $shoppingCart.eventHandlers.add(id, q);
                    $('.ax-nav-tabs a[href=#accessories]').tab('show');
                    btn.html('<span class="ax-sprite ax-cart buy-button"></span>TILLAGD I VARUKORGEN');

                });
            }).error(function () {
                $productModal.modal('hide');
                $('.ajax-loader', $productModal).hide();
            });

            // Push to GTM
            var productInfo = $(event.target).closest('.gtm-product-info').data();

            if (productInfo === null) {
                return;
            }

            dataLayer.push({
                'event': 'productInfoClick',
                'ecommerce': {
                    'detail': {
                        'actionField': { 'list': window.location.pathname + window.location.search },
                        'products': [{
                            'name': productInfo.name,
                            'id': productInfo.partNo,
                            'price': productInfo.price,
                            'brand': productInfo.brand,
                            'category': productInfo.category
                        }]
                    }
                }
            });

        },

        openStockModal: function (event, pid) {
            event.preventDefault();
            var $stockModal = $('#stock-modal');
            $stockModal.modal('show');
            $('.ajax-loader', $stockModal).show();
            $('.modal-content', $stockModal).html('');
            $('.ajax-loader', $stockModal).show();

            $.getJSON('/api/modals/stock/' + pid + '/1', function (html) {
                $('.modal-content', $stockModal).html(html);
                $('.ajax-loader', $stockModal).hide();
            }).error(function () {
                $('.ajax-loader', $stockModal).hide();
            });
        },

        openStoreModal: function (event, refreshPage) {
            event.preventDefault();
            var $storeModal = $('#store-modal');
            $storeModal.modal('show');
            $('.modal-content', $storeModal).html('');

            $.getJSON('/api/modals/store', function (html) {
                $('.modal-content', $storeModal).html(html);
                $('#store-modal').data('refreshPage', refreshPage);
                $('.ajax-loader', $storeModal).hide();
            }).error(function () {
                $('.ajax-loader', $storeModal).hide();
            });
        },

        openWatchModal: function (event, pid) {
            event.preventDefault();
            var $watchModal = $('#watch-modal');
            $('#watch-modal-pid', $watchModal).val(pid);
            $watchModal.modal('show');
        },

        openReviewModal: function (event, pid) {
            event.preventDefault();
            var $reviewModal = $('#review-modal');
            $('#review-modal-pid', $reviewModal).val(pid);
            $reviewModal.modal('show');
        },

        toggleQuantityInput: function () {
            var select = $(this);
            if (select.val() === 'more') {
                select
                    .hide()
                    .siblings('input')
                    .show()
                    .focus();
            }
        },

        toggleSlider: function () {
            if (sliderIsActive || !$sliderHolder.length) return;

            $('#slides-holder').slidesjs({
                pagination: {
                    active: true
                },
                navigation: {
                    active: false
                },
                callback: {
                    start: eventHandlers.loadImageForSlider
                }
            });
            sliderIsActive = true;
        },

        openPriceCalculationModal: function (e) {
            var type = $(this).data('type');
            var price = $(this).data('price');
            var header = $(this).data('header');
            e.preventDefault();
            var modal = $('#generic-modal');
            $('.modal-dialog', modal).hide();
            modal.addClass('part-payment-modal');
            $('.ajax-loader', modal).show();
            modal.modal('show');
            $.getJSON('/api/modals/product/pricecalculation/' + type + '/' + price, function (html) {
                $('#generic-modal-header', modal).html(header ? header : 'Delbetala med Autoexperten-kortet');
                $('.sub-header', modal).html('');
                $('.body', modal).html(html);
                $('#generic-modal table').addClass('table table-striped');
                $('.modal-dialog', modal).show();
            });
        },

        toggleStickyBlocks: function () {

            var sidebar = $('.sidebar');
            var mainContent = $('.main-content');
            if ($(window).width() <= 1200 || sidebar.height() > $(window).height())
                return;

            var myOffset = sidebar.parent().offset();
            var offsetTop = myOffset.top - $(window).scrollTop();

            var sidebarVirtualHeight = sidebar.position().top + sidebar.height();
            var mainContentVirtualHeight = mainContent.offset().top + mainContent.height() - $(window).scrollTop();

            if (sidebarVirtualHeight > mainContentVirtualHeight && ((offsetTop <= 0) || (sidebar.css('position') === 'absolute'))) {
                sidebar.addClass('sticky-interactable');
            }
            else if (offsetTop <= 0) {
                sidebar.css('position', '');
                sidebar.addClass('sticky-interactable');
                sidebar.removeClass('fixed');
            }
            else {
                sidebar.css('position', '');
                sidebar.css('top', '');
                sidebar.removeClass('sticky-interactable');
                sidebar.removeClass('fixed');
            }
        }
    };

    var helpers = {

        social: {
            facebook: {
                share: function () {
                    FB.ui({
                        method: 'share',
                        href: window.location.href
                    });
                }
            },

            twitter: {
                share: function () {
                    helpers.openShareWindow('https://twitter.com/intent/tweet?url=' + escape(window.location.href), 'Twitter');
                }
            },
        },

        openShareWindow: function (url, name) {
            var width = 575,
                height = 400,
                left = ($(window).width() - width) / 2,
                top = ($(window).height() - height) / 2,
                url = url,
                opts = 'status=1' +
                    ',width=' + width +
                    ',height=' + height +
                    ',top=' + top +
                    ',left=' + left;

            window.open(url, name, opts);
        }
    };

    $(document).ready(function () {
        initCommon();
    });

    // Init regions
    Regions.init({});

})(jQuery);
$(function () {
    if ($(document).width() < 850) {
        $('.thumb').remove();
    }
});;
var MultiSelect = function(container, onChangeCallback) {

    var self = this;
    self.container = container;
    self.onChange = onChangeCallback;
    self.nonSelectedTextDefault = 'Alla';
    self.init = function() {
        $('select', self.container).multiselect({
            nonSelectedText: self.nonSelectedTextDefault,
            numberDisplayed: 1,
            enableClickableOptGroups: true,
            nSelectedText: ' valda',
            allSelectedText: 'Alla valda',
            templates: {
                liGroup: '<li class="multiselect-item multiselect-group multiselect-group-clickable"><label class="checkbox"></label></li>'
            },
            buttonTitle: function (options, select) {
                var selected = '';
                options.each(function () {
                    selected += $(this).text() + ', ';
                });
                return selected.substr(0, selected.length - 2);
            },
            onChange: self.onChange
        });

        var addSubmenuClass = false;
        $('.multiselect-container li').each(function () {
            var $elem = $(this);
            var shouldAddIcon = false;

            if ($elem.hasClass('divider')) {
                addSubmenuClass = false;
            }

            if (addSubmenuClass) {
                $elem.addClass('is-sub');
                shouldAddIcon = false;

                $('a', $elem).on('click', function () {
                    setTimeout(function () {
                        if (!$elem.hasClass('active')) {
                            $elem.prevAll('li.multiselect-group').first().removeClass('active');
                        } else if (!$elem.prevUntil('li.multiselect-group').not('.active').length && !$elem.nextUntil('li.divider').not('.active').length) {
                            $elem.prevAll('li.multiselect-group').first().addClass('active');
                        }

                    }, 0);
                });
            }

            if ($elem.hasClass('multiselect-group')) {
                addSubmenuClass = true;
                shouldAddIcon = true;
                $('label', $elem).on('click', function () {
                    $elem.toggleClass('active');
                });

                if (!$elem.nextUntil('li.divider').not('.active').length) {
                    $elem.addClass('active');
                }
            }

            if (shouldAddIcon) {
                var icon = $('<i class="fa fa-chevron-down"></i>');
                $elem.append(icon);

                icon.on('click', function (e) {
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    $elem.nextUntil('.divider').toggle();
                    icon.toggleClass('fa-chevron-up');
                    icon.toggleClass('fa-chevron-down');
                });
            }
        });
    }
};;
(function ($) {

    var $sliderContainer,
        $topWidgetsContainer,
        $mobileQuicknav,
        $topSlider,
        sliderHeightIsSet;

    function initStart() {
        setVars();
        modifyDom();
        addEvents();
    }

    function setVars() {

    }

    function modifyDom() {
        if (detectIE()) {
            $('.offer-class').addClass('ie-detected');
            $('.shop-class').addClass('ie-detected');
        }
        var firstItemInBottomMidContentArea = $('.ax-newsletter-facebook-holder').first();
        if (firstItemInBottomMidContentArea.length) {
            firstItemInBottomMidContentArea.addClass('startsida-kampanjytor')
        }
    }

    function detectIE() {
        var ua = window.navigator.userAgent;

        var msie = ua.indexOf('MSIE ');
        if (msie > 0) {
            // IE 10 or older => return version number
            return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        }

        var trident = ua.indexOf('Trident/');
        if (trident > 0) {
            // IE 11 => return version number
            var rv = ua.indexOf('rv:');
            return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
        }

        var edge = ua.indexOf('Edge/');
        if (edge > 0) {
            // Edge (IE 12+) => return version number
            return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
        }

        // other browser
        return false;
    }

    function addEvents() {
        if ($('#ax-top-slides').length) {
            $(window).on('resize', eventHandlers.setSliderHeight);

            eventHandlers.setSliderHeight();

            $topSlider = $('.swiper-container').swiper({

                mode: 'horizontal',
                autoplay: 5000,
                autoplayDisableOnInteraction: false,
                loop: true,
                pagination: '.ax-slider-pagination',
                paginationClickable: true,
                onSwiperCreated: function () {
                    $('.swiper-container').css('opacity', 1);
                    $('.swiper-container .caption').show();
                    $('.ax-slider-prev').on('click', function () {
                        $topSlider.swipePrev();
                    });
                    $('.ax-slider-next').on('click', function () {
                        $topSlider.swipeNext();
                    });
                }
            });
        }

        if ($('.hero-slider').length && $('.hero-slide-block').length > 1) {
            
            $('.swiper-wrapper > div > div').each(function () {
                $('.swiper-wrapper').append($(this).addClass('swiper-slide'));
            });
            $('.swiper-wrapper > div:not(.swiper-slide)').remove();

            var paginationProps = ($(window).width() <= 768) ? { el: '.slider-dots' } : {el: '.swiper-pagination',type: 'fraction'};

            var swiper = new Swiper('.hero-slider', {
                autoplay: {
                    delay: 5000,
                    disableOnInteraction: true
                },
                loop: true,
                paginationClickable: true,
                pagination: paginationProps,
                navigation: {
                    nextEl: '.button-next',
                    prevEl: '.button-prev',
                },
            });
        }

    }

    var eventHandlers = {
        setSliderHeight: function () {
            if ($(window).width() > 990) {
                var height = $('.start-top-widget-holder').height() - 20;
                $('.swiper-slide, .swiper-container').css({ 'min-height': height, 'max-height': height });
            }
        }
    };

    $(document).ready(function () {
        initStart();
    });

})(jQuery);;
var StockOrder = function() {
    var currentOrder = null;

    var $quantity;
    var $totalPrice;
    var $fullName;
    var $emailAddress;
    var $phoneNumber;
    var $sendButton;
    var $productName;
    var $currentStore;
    var $form;
    var $spinner;
    var $spinnerText;
    var $topText;
    var $successView;
    var $failedView;
    var $formView;
    var $loadingView;
    var $closeButton;
    var $quantityHolders;
    var $productNameHolders;
    var $modal;
    var $selectQuantity;

    this.init = function (order) {
        currentOrder = order;

        setVars();
        removeEvents();
        modifyDom();
        addEvents();
    }

    this.postVisible = function()
    {
        $fullName.focus();
    }

    function setVars() {
        $modal = $('#stock-order-modal');
        $quantity = $('#stock-modal-quantity');
        $totalPrice = $('#stock-modal-total-price');
        $fullName = $('#stock-modal-full-name');
        $phoneNumber = $('#stock-modal-phone-number');
        $emailAddress = $('#stock-modal-email-address');
        $sendButton = $('#stock-modal-send-button');
        $productName = $('#stock-modal-product-name');
        $currentStore = $('.store-name');
        $form = $('#stock-modal-form');
        $spinner = $('#stock-modal-spinner');
        $spinnerText = $('#stock-modal-spinner-text');
        $topText = $('#stock-modal-top-text');
        $successView = $('#stock-modal-success-view');
        $failedView = $('#stock-modal-failed-view');
        $formView = $('#stock-modal-form-view');
        $loadingView = $('#stock-modal-loading-view');
        $closeButton = $('.close-button', $modal);
        $quantityHolders = $('.product-quantity', $modal);
        $productNameHolders = $('.product-name', $modal);
        $selectQuantity = $('#stock-modal-select-quantity');
    }

    function modifyDom() {
        $productName.html(currentOrder.productName);
        $productNameHolders.html(currentOrder.productName);
        $currentStore.html(currentOrder.storeName);
        $quantity.val(currentOrder.quantity.current);
        $quantityHolders.html(currentOrder.quantity.current);
        $totalPrice.html(currentOrder.price * currentOrder.quantity.current + ' kr');
        quantityHandler();

        defaultUiState();
    }

    function quantityHandler() {
        if (currentOrder.quantity.fixed) {
            // Use a select box instead of free input
            $('#stock-modal-select-quantity option').remove();

            for (var i = 1; i <= 10; i++) {
                var option = document.createElement('option');
                var result = i * currentOrder.quantity.multiplier;
                option.text = result;
                option.value = result;

                if (i === currentOrder.quantity.current) {
                    option.selected = 'selected';
                }

                $selectQuantity.append(option);
            }

            syncSelect();

            $selectQuantity.show();
            $quantity.hide();
        }
    }

    function defaultUiState() {
        $loadingView.hide();
        $successView.hide();
        $failedView.hide();
        $formView.show();
    }

    function syncSelect() {
        $quantity.val($selectQuantity.val());
        updateQuantity();
    }

    function updateQuantity() {
        currentOrder.quantity.current = parseInt($quantity.val());
        var total = currentOrder.price * currentOrder.quantity.current;

        if (!isNaN(total)) {
            $totalPrice.html(total + ' kr');
            $quantityHolders.html(currentOrder.quantity.current);
        } else {
            $totalPrice.html('0 kr');
        }
    }

    function addEvents() {
        $selectQuantity.on('change', syncSelect);

        $closeButton.on('click', function() {
            $('#stock-order-modal').modal('hide');
        });
        
        // Update the quantity and total price
        $quantity.on('keyup', updateQuantity);

        // Send the order
        $sendButton.on('click', function (e) {
            e.preventDefault();

            var valid = $form.parsley().validate();
            if (!valid) return;

            $formView.fadeOut(100, function() {
                $loadingView.fadeIn(300);
            });

            currentOrder.fullName = $fullName.val();
            currentOrder.phoneNumber = $phoneNumber.val();
            currentOrder.quantity = $quantity.val();
            currentOrder.email = $emailAddress.val();

            $.ajax({
                method: 'POST',
                url: '/api/order/send/',
                data: currentOrder,
                success: function (resp) {
                    if (resp === '') {
                        setTimeout(orderSuccess, 2000);
                    } else {
                        setTimeout(orderFailed, 2000);
                    }
                },
                error: function (xhr, textStatus, error) {
                    setTimeout(orderFailed, 2000);
                }
            });
        });
    }

    function orderSuccess() {
        $loadingView.fadeOut(100, function() {
            $successView.fadeIn(300);
            dataLayer.push({
                'event': 'reservationSuccess'
            });
        });
    }

    function orderFailed() {
        $loadingView.fadeOut(100, function () {
            $failedView.fadeIn(300);
        });
    }

    function removeEvents() {
        $selectQuantity.unbind();
        $quantity.unbind();
        $sendButton.unbind();
        $closeButton.unbind();
    }
};
(function ($) {
    var $checkoutProductsHolder;
    var $removeButtons;
    var $checkoutSummaryHolder;
    var $personCompanyNumberHolder;
    var $personCompanyNumberLabel;
    var $personCompanyNumberInput;
    var $personCompanyGetButton;
    var $buyerType1Radio;
    var $buyerType2Radio;
    var $checkoutSubmitButton;
    var $checkoutForm;
    var $checkoutName;
    var $checkoutSurname;
    var $checkoutCareOf;
    var $checkoutStreetAddress;
    var $checkoutCity;
    var $checkoutZipCode;
    var $checkoutPhone;
    var $checkoutEmail;
    var $checkoutNameLabel;
    var $checkoutCompanyNameHolder;
    var $checkoutCompanyName;
    var $checkoutSocIdErrorMessage;
    var $addPromoModalCodeText;
    var $addGiftCardNo;
    var $addGiftCardCvc;
    var $paymentMethodsHolder;
    var $shippingMethodsHolder;
    var $getAxCardHolder;
    var $useAxCardHolder;
    var $summaryHolder;
    var $summaryHolderSmall;
    var $paymentHolder;
    var $deliveryAddressHolder;

    // State for GTM
    var hasCompletedStep2 = false;
    var hasCompletedUserLead = false;
    var hasCompletedCartLead = false;
    var hasCheckedGTMOnStart = false;

    var submitted = false;

    function setVars() {
        $checkoutProductsHolder = $('#checkout-products');
        $removeButtons = $('.checkout-product-remove', $checkoutProductsHolder);
        $checkoutSummaryHolder = $('.checkout-table-summary-holder');
        $personCompanyNumberHolder = $('.soc-company-id');
        $personCompanyNumberLabel = $('#checkout-person-company-number-label');
        $personCompanyNumberInput = $('#checkoutSocId');
        $personCompanyGetButton = $('#checkout-person-company-get-button');
        $buyerType1Radio = $('#buyer-type-1');
        $buyerType2Radio = $('#buyer-type-2');
        $checkoutSubmitButton = $('#checkout-submit-button');
        $checkoutForm = $('#checkout-form');
        $checkoutName = $('#checkoutName');
        $checkoutSurname = $('#checkoutSurname');
        $checkoutCareOf = $('#checkoutCareOf');
        $checkoutStreetAddress = $('#checkoutStreetAddress');
        $checkoutCity = $('#checkoutCity');
        $checkoutZipCode = $('#checkoutZipCode');
        $checkoutPhone = $('#checkoutPhone');
        $checkoutEmail = $('#checkoutEmail');
        $checkoutNameLabel = $('#checkoutNameLabel');
        $checkoutCompanyNameHolder = $('#checkoutCompanyNameHolder');
        $checkoutCompanyName = $('#checkoutCompanyName');
        $checkoutSocIdErrorMessage = $('#checkoutSocIdErrorMessage');
        $addPromoModalCodeText = $('#add-promo-modal-code-text');
        $addGiftCardNo = $('#gift-card-no');
        $addGiftCardCvc = $('#gift-card-cvc');
        $paymentMethodsHolder = $('#payment-methods-holder');
        $shippingMethodsHolder = $('#checkout-shipping');
        $getAxCardHolder = $('#get-ax-card-holder');
        $useAxCardHolder = $('#use-ax-card-holder');
        $summaryHolder = $('.checkout-table-summary-holder');
        $summaryHolderSmall = $('#checkout-small-summary-holder');
        $paymentHolder = $('#checkout-payment');
        $deliveryAddressHolder = $('#checkout-delivery-address-holder');
    }

    function onStoreChanged()
    {
        var deliveryMethod = $('.open-store-modal.change-store-link').closest('.delivery-method');
        deliveryMethod.find('input').prop('checked', true).attr('checked', true);
        setPurchaseEnabled(false);
        pushStep3ToGTM(deliveryMethod.data().methodName);
        $('#checkout-pick-store-error').fadeOut();
        $.ajax({
            method: 'GET',
            url: '/api/checkout/updatedeliverymethod',
            data: "deliveryMethod=" + deliveryMethod.find('input').val(),
            success: function (data) {
                helpers.send({}, 'refresh');
            },
            error: function (xhr, textStatus, error) {
                setPurchaseEnabled(true);
            }
        });
    }
    function bindEvents() {
        // Disallow posting the form on enter keypress
        $('input,select', $checkoutForm).keypress(function(event) {
            return event.keyCode != 13;
        });

        $checkoutZipCode.on('keyup', function(e) {
            if ($(this).val().length === 5) {
                $.ajax({
                    method: 'GET',
                    url: '/api/checkout/updatezipcode/' + $(this).val(),
                    success: function (data) {
                        helpers.send({}, 'refresh');
                    },
                    error: function (xhr, textStatus, error) {

                    }
                });
            }
        });

        $('.delivery-method input').on('click', function (e) {
            setPurchaseEnabled(false);
            var deliveryMethod = $(this).closest('.delivery-method').data();

            if (deliveryMethod.pickupAtStore === 'True') {
                $('#checkout-pick-store-error').fadeOut();
            }
            $.ajax({
                method: 'GET',
                url: '/api/checkout/updatedeliverymethod',
                data: "deliveryMethod=" + $(this).val(),
                success: function (data) {
                    helpers.send({}, 'refresh');
                    pushStep3ToGTM(deliveryMethod.methodName);
                },
                error: function (xhr, textStatus, error) {
                    setPurchaseEnabled(true);
                }
            });
        });

        $('.payment-method input').on('click', function () {
            setPurchaseEnabled(false);
            var paymentMethod = $(this).closest('.payment-method').data();
            CheckCommonLead();
            // Invoice, should not be able to set a separate delivery address
            if ($(this).val() === '43') {
                $deliveryAddressHolder.hide();
            } else {
                $deliveryAddressHolder.show();
            }

            $('.checkout-table-summary-holder .well').addClass('is-loading');
            $.ajax({
                method: 'GET',
                url: '/api/checkout/updatepaymentmethod',
                data: "paymentMethod=" + $(this).val(),
                success: function (data) {
                    helpers.send({}, 'refresh');
                    pushStep4ToGTM(paymentMethod.methodName)        
                },
                error: function (xhr, textStatus, error) {
                    setPurchaseEnabled(true);
                }
            });
        });

        // TODO: This is a dupe, refactor (pub/sub)
        $('.open-store-modal').on('click', function (event) {

            event.stopImmediatePropagation();
            event.preventDefault();

            var refreshPage = $(this).data('refreshPage');
            if (typeof refreshPage === 'undefined') {
                refreshPage = false;
            }

            var $storeModal = $('#store-modal');
            $storeModal.modal('show');
            $('.modal-content', $storeModal).html('');

            $.getJSON('/api/modals/store', function (html) {
                $('.modal-content', $storeModal).html(html);
                $('#store-modal').data('refreshPage', refreshPage);
            });
        });

        $(document).on('store/changed', onStoreChanged);

        $addPromoModalCodeText.on('keydown', function(e) {
            if (e.which == 13) {
                e.preventDefault();
                $('#add-promo-modal-use-promo-button').trigger('click');
            }
        });

        $('#add-promo-modal-use-promo-button').on('click', function (e) {
            var _this = $(this);
            var modal = _this.closest('.modal-dialog');
            
            $('.checkout-table-summary-holder .well').addClass('is-loading');
            _this.text('').append($('<i class="fa fa-spinner fa-spin" />'));
            $.ajax({
                method: 'GET',
                url: '/api/checkout/applypromotion',
                data: "promotionCode=" + $addPromoModalCodeText.val(),
                success: function (data) {

                    if (data === 'discountApplied') {
                        $('#promo-code-modal').modal('hide');
                        helpers.send({}, 'refresh');
                    } else {

                        modal.addClass('shake');
                        modal.find('.modal-general-header').addClass('modal-red-header');
                        setTimeout(function () {
                            modal.removeClass('shake');
                            modal.find('.modal-general-header').removeClass('modal-red-header');
                        }, 1000);
                        _this.find('i').remove();
                        _this.text('Använd');
                    }
                    $('.checkout-table-summary-holder .well').removeClass('is-loading');
                },
                error: function (xhr, textStatus, error) {
                    $('.checkout-table-summary-holder .well').removeClass('is-loading');
                    modal.addClass('shake');
                    modal.find('.modal-general-header').addClass('modal-red-header');
                    setTimeout(function () {
                        modal.removeClass('shake');
                        modal.find('.modal-general-header').removeClass('modal-red-header');
                    }, 1000);
                    _this.find('i').remove();
                    _this.text('Använd');
                }
            });
        });

        $('#giftcard-button').on('click', function (e) {
            e.preventDefault();

            var cardNo = $addGiftCardNo.val();
            var cvc = $addGiftCardCvc.val();

            if (!cardNo || cardNo == '' || !cvc || cvc == '') {
                return false;
            }

            var _this = $(this);
            var modal = _this.closest('.modal-dialog');
            _this.text('').append($('<i class="fa fa-spinner fa-spin" />'));
            $('.checkout-table-summary-holder .well').addClass('is-loading');
            $.ajax({
                method: 'GET',
                url: '/api/checkout/applygiftcard',
                data: 'cardNo=' + cardNo + '&cvc=' + cvc,
                success: function (data) {
                    if (data === 'giftcardApplied') {
                        $('#promo-code-modal').modal('hide');
                        helpers.send({}, 'refresh');
                    } else {

                        modal.addClass('shake');
                        modal.find('.modal-general-header').addClass('modal-red-header');
                        setTimeout(function () {
                            modal.removeClass('shake');
                            modal.find('.modal-general-header').removeClass('modal-red-header');
                        }, 1000);
                    }
                    _this.find('i').remove();
                    _this.text('Använd');
                    $('.checkout-table-summary-holder .well').removeClass('is-loading');
                },
                error: function (xhr, textStatus, error) {
                    modal.addClass('shake');
                    modal.find('.modal-general-header').addClass('modal-red-header');
                    setTimeout(function () {
                        modal.removeClass('shake');
                        modal.find('.modal-general-header').removeClass('modal-red-header');
                    }, 1000);
                    _this.find('i').remove();
                    _this.text('Använd');
                    $('.checkout-table-summary-holder .well').removeClass('is-loading');
                }
            });
        });

        $('.remove-giftcard').on('click', function (e) {
            e.preventDefault();
            var paymentCode = $(this).data('id');
            
            $('.checkout-table-summary-holder .well').addClass('is-loading');
            $.ajax({
                method: 'GET',
                url: '/api/checkout/removegiftcard',
                data: 'paymentCode=' + paymentCode,
                success: function(data) {
                    if (data === 'giftcardRemoved') {
                        $('#promo-code-modal').modal('hide');
                        helpers.send({}, 'refresh');
                    } 
                    $('.checkout-table-summary-holder .well').removeClass('is-loading');
                },
                error: function(xhr, textStatus, error) {
                    $('.checkout-table-summary-holder .well').removeClass('is-loading');
                }
            });
        });

        $personCompanyGetButton.on('click', function (e) {
            e.preventDefault();

            $personCompanyGetButton.text('Hämtar ').append($('<i class="fa fa-spinner fa-spin" />'));
            function clearFields() {
                $checkoutName.val('');
                $checkoutSurname.val('');
                $checkoutCity.val('');
                $checkoutPhone.val('');
                $checkoutCareOf.val('');
                $checkoutStreetAddress.val('');
                $checkoutZipCode.val('');
                $checkoutCompanyName.val('');
            }

            $checkoutSocIdErrorMessage.addClass('hidden');
            var customerType = $buyerType1Radio.is(":checked") ? 'person' : 'company';

            $.ajax({
                method: 'GET',
                url: '/api/checkout/getaddress',
                data: "governmentId=" + $personCompanyNumberInput.val() + "&customerType=" + customerType,
                type: 'json',
                success: function (data) {
                    $personCompanyGetButton.text('Hämta mina uppgifter');
                    $personCompanyGetButton.find('i').remove();
                    if (data === null) {
                        $checkoutSocIdErrorMessage.removeClass('hidden');
                        return;
                    }

                    clearFields();

                    if (customerType === 'person') {
                        $checkoutName.val(data.firstName);
                        $checkoutSurname.val(data.lastName);
                    } else {
                        $checkoutCompanyName.val(data.fullName);
                    }

                    $checkoutCity.val(data.postalArea);
                    $checkoutZipCode.val(data.postalCode);
                    $checkoutStreetAddress.val(data.addressRow1);
                    $('.toggle-mobile-checkout').show();
                },
                error: function (xhr, textStatus, error) {
                    $personCompanyGetButton.text('Hämta mina uppgifter');
                    $personCompanyGetButton.find('i').remove();
                }
            });
        });

        $checkoutSubmitButton.on('click', function (e) {
            // Make sure a store is selected if that delivery 
            // method is chosen
            e.preventDefault();
           
            CheckCommonLead();
            if (submitted) {
                return false;
            }

            var selectedDeliveryMethod = $('.delivery-method input:checked').closest('.delivery-method').data();
            if (selectedDeliveryMethod !== null && selectedDeliveryMethod.pickupAtStore === 'True') {
                if (selectedDeliveryMethod.selectedStore === 'False') {

                    $('#checkout-pick-store-error').fadeIn(1000);
                    $('html, body').animate({
                        scrollTop: $("#checkout-pick-store-error").offset().top - 100
                    }, 500, function() {
                        
                    });

                    return;
                }
            }

            var valid = $checkoutForm.parsley().validate();
            if (!valid) {
                return;
            }

            if (getTotalPrice() === 0) {
                var $radio = $('input:radio', $paymentMethodsHolder).first();
                $radio.prop('checked', 'checked');
                $radio.prop('value', 18);
            }

            setPurchaseEnabled(false);
            $(this).parent().addClass('loading'); 
            $checkoutForm.submit();
            submitted = true;
        });

        $buyerType1Radio.on('click', function () {
            $personCompanyNumberInput.val('');
            setBuyer();
            filterDeliveryPaymentMethods();
            clearShippingPaymentSelections();
        });

        $buyerType2Radio.on('click', function () {
            $personCompanyNumberInput.val('');
            setBuyer();
            filterDeliveryPaymentMethods();
            clearShippingPaymentSelections();
        });

        $removeButtons.on('click', function (e) {
            var elem = $(this).closest('.checkout-single-product');
            var id = elem.data('id');
            $(this).find('i').removeClass('fa-times-circle').addClass('fa-spinner fa-spin');
            helpers.remove(id);
        });

        $('.quantity-holder select', $checkoutProductsHolder).on('change', function () {
            var select = $(this);

            if (!(select.val() === 'more')) {
                $(this).closest('.checkout-single-product').css('opacity', 0.3);
                var id = $(this).closest('.checkout-single-product').data('id');
                helpers.update(id, select.val());
            } else {
                helpers.toggleQuantityInput(select);
            }
        });

        $('.quantity-holder input', $checkoutProductsHolder).on('change', function () {
            var input = $(this);
            var id = $(this).closest('.checkout-single-product').data('id');
            helpers.update(id, input.val());
        });

        $('input', $checkoutForm).on('keypress input', function () {
            var inputName = $(this).attr('name');
            if (inputName == 'ShippingMethod' || inputName == 'PaymentMethod' ) {
                return;
            }
            pushStep2ToGTMIfNotSent();
        });

        if ($checkoutPhone.length) {
            $checkoutPhone.parsley().on('field:validate', function () {
                formatPhone(this.$element[0], this.value);

            });
        }

        $personCompanyNumberInput.on('change', function(e) {

            if (!this.value) {
                return;
            }

            this.value = this.value.replace(/[^0-9]/g, '');
        });

    }

    function unbindEvents() {
        $('input', $checkoutForm).unbind('keypress');
        $checkoutZipCode.unbind();
        $('.delivery-method input').unbind();
        $('.payment-method input').unbind();
        $('.open-store-modal').unbind();
        $('#add-promo-modal-use-promo-button').unbind();
        $personCompanyGetButton.unbind();
        $buyerType1Radio.unbind();
        $buyerType2Radio.unbind();
        $removeButtons.unbind();
        $('.quantity-holder select', $checkoutProductsHolder).unbind();
        $('.quantity-holder input', $checkoutProductsHolder).unbind();

        $personCompanyNumberInput.unbind('change');

        $('#giftcard-button').unbind();
        $('.remove-giftcard').unbind();
        $(document).off('store/changed', onStoreChanged);
    }

    function init() {
        setVars();
        modifyDom();
        filterDeliveryPaymentMethods();
        setBuyer();
        checkTotalPrice();
        unbindEvents();
        bindEvents();
        checkDefaultFormForGTM();
    }

    function setBuyer() {

        if (!$checkoutForm.length) {
            return;
        }

        var buyerType = $buyerType1Radio.prop('checked') ? 'person' : 'company';

        if (buyerType === 'person') {
            $checkoutForm.parsley().destroy();
            $checkoutCompanyName.removeAttr('required');
            $checkoutForm.parsley();
            $checkoutPhone.parsley().on('field:validate', function () {
                formatPhone(this.$element[0], this.value);

            });
            $personCompanyNumberLabel.html('Personnummer<br><span class="example">(ÅÅMMDDXXXX)</span>');
            $personCompanyGetButton.html('Hämta mina uppgifter');
            $checkoutCompanyNameHolder.addClass('hidden');
            $personCompanyNumberInput.attr("name", "SSN");
        }

        if (buyerType === 'company') {
            $checkoutForm.parsley().destroy();
            $checkoutCompanyName.prop('required', 'required');
            $checkoutForm.parsley();
            $checkoutPhone.parsley().on('field:validate', function () {
                formatPhone(this.$element[0], this.value);

            });
            $personCompanyNumberLabel.html('Org.nummer<br><span class="example">(ex. 5555540142)</span>');
            $personCompanyGetButton.html('Hämta uppgifter');
            $checkoutCompanyNameHolder.removeClass('hidden');
            $personCompanyNumberInput.attr("name", "CompanyOrgNo");
        }
    }

    function formatPhone(element, value) {
        try {
            

            var isValid = window.phoneUtils.isValidNumber(value, 'SE');

            if (!isValid) {
                return;
            }

            var regionCode = window.phoneUtils.getRegionCodeForNumber(value, 'SE');

            element.value = window.phoneUtils.formatNational(value, regionCode).replace(/[^0-9]/g, '');
        } catch (err) {

        }
    }

    function filterDeliveryPaymentMethods() {
        var buyerType = $buyerType1Radio.prop('checked') ? 'person' : 'company';

        var $deliveryMethods = $(".delivery-method", $shippingMethodsHolder).addClass('hidden');
        var $paymentMethods = $(".payment-method", $paymentMethodsHolder).addClass('hidden');

        $deliveryMethods.each(function (index, value) {
            if ($(value).data('is-for-person-only') === "True" && buyerType === 'person') {
                $(value).removeClass('hidden');
                return;
            }

            if ($(value).data('is-for-company-only') === "True" && buyerType === 'company') {
                $(value).removeClass('hidden');
                return;
            }

            if ($(value).data('is-for-company-only') === "False" && $(value).data('is-for-person-only') === "False") {
                $(value).removeClass('hidden');
                return;
            }

            $('input', value).prop("checked", "");
        });

        $paymentMethods.each(function (index, value) {
            if ($(value).data('is-for-person-only') === "True" && buyerType === 'person') {
                $(value).removeClass('hidden');
                return;
            }

            if ($(value).data('is-for-company-only') === "True" && buyerType === 'company') {
                $(value).removeClass('hidden');
                return;
            }

            if ($(value).data('is-for-company-only') === "False" && $(value).data('is-for-person-only') === "False") {
                $(value).removeClass('hidden');
                return;
            }

            $('input', value).prop("checked", "");
        });

        var firstHeight;
        $deliveryMethods.not('.hidden').each(function (index) {
            if (index % 2 == 0) {
                firstHeight = $(this).height();
            } else {
                var prev = $deliveryMethods.not('.hidden').eq(index - 1);
                if ($(this).height() < firstHeight) {
                    $(this).height(firstHeight + 15);
                    prev.height(firstHeight + 15);
                } else {
                    prev.height($(this).height() + 15);
                    $(this).height($(this).height() + 15);
                }     
            }
        });
        
    }

    function modifyDom() {
        addAffix();
    }

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        return !(charCode > 31 && (charCode < 48 || charCode > 57));
    }


    function addAffix() {
        $('.table-summary-widget').affix({
            offset: {
                top: 250,
                bottom: function() {
                    var bottom = $('.footer-text').outerHeight(true) + $('.footer-menus').outerHeight(true) + $('.footer-utils').outerHeight(true);
                    return (this.bottom = bottom + 230);
                }
            }
        });
    }
    
    function clearShippingPaymentSelections() {
        $getAxCardHolder.hide();
        $useAxCardHolder.hide();
        $('input', $paymentMethodsHolder).prop("checked", "");
        $('input', $shippingMethodsHolder).prop("checked", "");
    }

    function setPurchaseEnabled(enabled) {
        if (enabled === true) {
            $checkoutSubmitButton.prop("disabled", false);
        } else {
            $checkoutSubmitButton.prop("disabled", true);
        }
    }

    var helpers = {
        toggleQuantityInput: function(select) {
            if (select.val() === 'more') {
                select
                    .hide()
                    .siblings('input')
                    .show()
                    .focus();
            }
        },
        add: function (id, quantity) {
            var cartItem =
            {
                id: id,
                quantity: quantity ? quantity : 1
            };

            helpers.send(cartItem, 'add');
        },
        update: function (id, quantity) {
            var cartItem =
            {
                id: id,
                quantity: quantity
            };

            helpers.send(cartItem, 'update');
        },
        remove: function (id) {
            var cartItem =
            {
                id: id,
                quantity: 0
            };

            helpers.send(cartItem, 'remove');
        },
        send: function (cartItem, action) {
            
            // Disable the ability to make a purchase while updating
            setPurchaseEnabled(false);

            // Update the basket summary
            $('.checkout-table-summary-holder .well').addClass('is-loading');
            $.ajax({
                method: 'POST',
                url: '/api/shoppingcart/' + action,
                data: JSON.stringify({ item: cartItem, viewModel: 'CheckoutPage' }),
                type: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (html) {
                    $checkoutProductsHolder.replaceWith($(html));
                    CheckCommonLead();
                    // Update partials
                    $.ajax({
                        method: 'GET',
                        url: '/api/checkout/getpartials',
                        type: 'json',
                        success: function (data) {
                            $paymentMethodsHolder.replaceWith(data.Payment);
                            $shippingMethodsHolder.replaceWith(data.Shipment);
                            $summaryHolder.replaceWith(data.Summary);
                            $summaryHolderSmall.replaceWith(data.SmallSummary);
                            init();
                            setPurchaseEnabled(true);
                        },
                        error: function (xhr, textStatus, error) {
                            $('.checkout-table-summary-holder .well').removeClass('is-loading');
                            setPurchaseEnabled(true);
                        }
                    });

                },
                error: function (xhr, textStatus, error) {
                    
                }
            });



        }
    };

    function getTotalPrice() {
        return Math.round(parseFloat($('#checkout-total-price').data('total-price')));
    }

    function checkTotalPrice() {
        if (getTotalPrice() === 0) {
            $paymentHolder.hide();
        } else {
            $paymentHolder.show();
        }
    }

    function CheckCommonLead() {
        if (!hasCompletedUserLead) {
            $checkoutEmail.parsley().validate();
            if ($checkoutEmail.hasClass('parsley-success')) {
                doCommonLeadAction($checkoutEmail.val(), 'Login');
                hasCompletedUserLead = true;
            }
        }
        else if (!hasCompletedCartLead) {
            doCommonLeadAction(1, 'UpdateCart');
            hasCompletedCartLead = true;
        }
    }

    function checkDefaultFormForGTM() {
        if (!hasCheckedGTMOnStart) {

            if ($checkoutEmail.length && $checkoutEmail.val().length) {
                pushStep2ToGTMIfNotSent();
            }

            $('.delivery-checked').each(function () {
                var deliveryMethod = $(this).data();
                pushStep3ToGTM(deliveryMethod.methodName);
            });
            $('.payment-checked').each(function () {
                var paymentMethod = $(this).data();
                pushStep4ToGTM(paymentMethod.methodName);
            });
            hasCheckedGTMOnStart = true;
        }
    }

    function pushStep2ToGTMIfNotSent() {
        if (!hasCompletedStep2) {
            var option = $buyerType1Radio.prop('checked') ? 'personal' : 'business';
            dataLayer.push({
                'event': 'checkout',
                'ecommerce': {
                    'checkout': {
                        'actionField': { 'step': 2, 'option': option },
                        'products': gtmProducts
                    }
                }
            });
            console.log('pushStep2');
            hasCompletedStep2 = true;
        }
    }

    function pushStep3ToGTM(methodName) {
        dataLayer.push({
            'event': 'checkout',
            'ecommerce': {
                'checkout': {
                    'actionField': { 'step': 3, 'option': methodName },
                    'products': gtmProducts
                }
            }
        });
        console.log('pushStep3');
    }

    function pushStep4ToGTM(methodName) {
        dataLayer.push({
            'event': 'checkout',
            'ecommerce': {
                'checkout': {
                    'actionField': { 'step': 4, 'option': methodName },
                    'products': gtmProducts
                }
            }
        });
        console.log('pushStep4');
    }

    $(document).ready(function() {
        if ($('.ax-checkout-holder').length) {
            init();
        }
    });

})(jQuery);;
(function ($) {

    function setVars() {
 
    }

    function init() {
        setVars();
        modifyDom();

        $('.header-print').on('click', function (e) {
            window.print();
        });

        $('#checkout-share-button').on('click', function (e) {
            FB.ui({
                method: 'share',
                href: 'https://www.autoexperten.se'
            }, function (response) { });
        });
    }

    function modifyDom() {

    }

    $(document).ready(function() {
        if ($('.thanks-holder').length) {
            init();
        }
    });

})(jQuery);;
(function($) {

    function initRegnr() {
       setVars();
       modifyDom();
       addEvents();
    }

    function setVars() {

    }

    function modifyDom() {

    }

    function addEvents() {
        $('.toggle-category-menu').on('click', eventHandlers.toggleCategoryMenus);
    }

    var eventHandlers = {
        toggleCategoryMenus: function(e) {

            var holder = $(this).closest('.col-md-15');
            holder.find('.selected-categories').toggle();

            //var text = holder.find('p.toggle-category-menu')
            //if(text.html().indexOf('alla') !== -1) {
            //    text.html('Dölj');
            //} else {
            //    text.html('Se alla');
            //}

        }
    }

    $(document).ready(function () {
        initRegnr();
        var vehicle = new Vehicle(); 
        vehicle.init('change-car', window.location.href);
    });

})(jQuery);;
(function($) {

    var letterElements = [];
    var articleItems = [];

    function init() {
        letterElements = $('.dictionary-letter');
        articleItems = letterElements.find('ul li');

        $('#dict-search-field').on('keyup', filter);
    }

    function filter() {
        var text = $('#dict-search-field').val();

        articleItems.each(function() {
            if (this.textContent.toLowerCase().indexOf(text.toLowerCase()) > -1) {
                $(this).removeClass('hidden');
            } else {
                $(this).addClass('hidden');
            }

        });

        var hiddenCount = 0;

        letterElements.each(function (index) {
            if ($(this).find('li:not(.hidden)').size() === 0) {
                $(this).addClass('hidden');
                hiddenCount += 1;
            } else {
                $(this).removeClass('hidden');
            }

            if ((index === letterElements.size() - 1) &&
                hiddenCount === letterElements.size()) {
                $('#dict-all-hidden').removeClass('hidden');
            } else {
                $('#dict-all-hidden').addClass('hidden');
            }
        });
    }

    $(document).ready(function () {
        init();
    });
})(jQuery);;
(function ($) {
    function init() {
        if (!$('.ax-help-holder').length)
            return;

        modifyDom();
        addEvents();
        checkHash();
    }

    function checkHash() {
        var targetTab;
        var targetQuestion;
        var hash = window.location.hash;

        if (hash.substr(1, 1) === '/') {
            var hs = hash.substr(2).split('/');
            targetTab = hs[0];
            targetQuestion = hs[1];

            if (targetQuestion) {
                $('[href="#tab' + targetTab + '"][data-question-id="' + targetQuestion + '"]').click();
            } else {
                $('[href="#tab' + targetTab + '"]:not([data-remote-tab="true"])').click();
            }
        }
    }
    
    function modifyDom() {
        $('#questions-container').css('min-height', $('#tabs-container').height() + 12);
    }

    function addEvents() {
        $('[data-remote-tab="true"]').on('click', eventHandlers.triggerTab);
        $('[data-toggle="tab"]:not([data-remote-tab="true"])').on('click', eventHandlers.tabClick);
    }

    var eventHandlers = {
        tabClick: function(e) {
            window.location.hash = "/" + $(e.currentTarget).attr('href').substr(4);
        },

        triggerTab: function (e) {
            var targetHref = $(e.currentTarget).attr("href");

            $('.faq-categories ul li').each(function (index, element) {
                var sourceHref = $(element).find('a').attr("href");

                if (sourceHref === targetHref) {
                    $(element).addClass("active");
                } else {
                    $(element).removeClass("active");
                }
            });

            var questionId = $(e.currentTarget).attr("data-question-id");
            $('div[data-question-id]').removeClass('yellow-highlight');
            setTimeout(function () {
                var targetQuestion = targetHref + ' div[data-question-id="' + questionId + '"]';
                $(targetQuestion).addClass('yellow-highlight');
                
                $('html, body').animate({
                    scrollTop: $(targetQuestion).offset().top - 300
                }, 500);

                $('#questions-container').css('height', '');
                window.location.hash = "/" + targetHref.substr(4) + "/" + questionId;
            }, 1);
        }
    }

    $(document).ready(function () {
        init();
    });

})(jQuery);;
(function ($) {
    var $username,
        $password,
        $loginBtn,
        $forgotPasswordToggleBtn,

        $email,
        $forgotPasswordBtn,

        $ajaxLoader;

    function init() {
        setVars();
        modifyDom();
        addEvents();
    }

    var setVars = function () {
        $username = $('#login .username-holder input');
        $password = $('#login .password-holder input');
        $loginBtn = $('#login button.ax-button');
        $forgotPasswordToggleBtn = $('#login .forgot-password-btn');

        $email = $('#forgot-password .email-holder input');
        $forgotPasswordBtn = $('#forgot-password button.ax-button');

        $ajaxLoader = $('.login-form-holder .ajax-loader ');
    };

    function modifyDom() {
    }

    function addEvents() {
       
        $loginBtn.on('click', eventHandlers.login);
        $forgotPasswordToggleBtn.on('click', function (event) {
            event.preventDefault();
            $('#login').hide();
            $('#forgot-password').show();
            $('#message')
                .css('color', 'red')
                .html('');
        });

        $forgotPasswordBtn.on('click', eventHandlers.forgotPassword);
    }

    var eventHandlers = {
        login: function (e) {
            e.preventDefault();

            var username = $username.val().trim();
            var password = $password.val().trim();
            const token = document.getElementById('login').querySelector('input[name=__RequestVerificationToken]').getAttribute('value');

            if (username == "") {
                $username.css('border', '2px solid red');
            } else {
                $username.css('border', 'none');
            }
            
            if (password == "") {
                $password.css('border', '2px solid red');
            } else {
                $password.css('border', 'none');
            }
            
            if (username == "" || password == "")
                return;

            $('#login').hide();
            $ajaxLoader.show();
            $('#message').hide();
            $.ajax({
                method: 'POST',
                url: '/api/account/login',
                data: { username: username, password: password },
                type: 'json',
                headers: { "__RequestVerificationToken": token },
                success: function (resp) {
                    doCommonLeadAction(username, 'Login');
                    doCommonLeadAction(1, 'UpdateCart');
                    location.href = location.href.split('#')[0];
                },
                error: function (xhr, textStatus, error) {
                    $ajaxLoader.hide();
                    $('#login').show();
                    
                    $('#message')
                        .css('color', 'red')
                        .html(error).show();
                }
            });
        },
        forgotPassword: function (e) {
            e.preventDefault();
            var email = $email.val().trim();
           
            if (email == "") {
                $email.css('border', '2px solid red');
                return;
            } else {
                $email.css('border', 'none');
            }

            $ajaxLoader.show();

            $.ajax({
                method: 'POST',
                url: '/api/account/forgotpassword',
                data: '=' + email,
                type: 'json',
                success: function (message) {
                    $('#message')
                        .css('color', 'green')
                        .html(message);
                    $ajaxLoader.hide();
                    $email.parent().hide();
                    $email.hide();
                    $forgotPasswordBtn.hide();
                },
                error: function (xhr, textStatus, error) {
                    $('#message')
                        .css('color', 'red')
                        .html(error);
                    $ajaxLoader.hide();
                }
            });
        }
    }

    $(document).ready(function () {
        init();
    });

})(jQuery);;
var OnHand = function() {
    var self = this;
    var isLoaded = false;
    var temporaryLinkFn = function (e) {
        if (isLoaded) return;

        e.preventDefault();
        e.stopPropagation();
        var link = $(this).closest('.ax-single-product').find('.product-title a').attr('href');
        window.location.assign(link);
    }
    self.updateonhand = function() {
        var pids = [];
        $.each($('.warehouse-status:not(".is-loaded")'), function (i, w) {
            var product = $(this).closest('.ax-single-product');
            product.find('.product-button-holder .ax-button-group').on('click', temporaryLinkFn);
            pids.push($(w).data('id'));
        });
        if (pids.length > 0) {
            $.ajax({
                method: 'POST',
                url: '/api/productlist/onhand/',
                data: { "": pids },
                type: 'json',
                success: function (statuses) {
                    
                    $.each(statuses, function (i, s) {
                        var web = $('.warehouse-status[data-id=' + s.productId + '] i.web');
                        if (web.length > 0) {
                            web.removeClass('gray');
                            web.addClass(s.web ? 'green' : 'red');
                        }
                        var store = $('.warehouse-status[data-id=' + s.productId + '] i.store');
                        if (store.length > 0) {
                            store.removeClass('gray');
                            store.addClass(s.store ? 'green' : 'red');
                        }
                    });
                    $('.warehouse-status').addClass('is-loaded');
                    isLoaded = true;
                },
                error: function (xhr, textStatus, error) {
                }
            });
        }
    }
};;
(function ($) {
    var $currentPageIndex,
        $listHolder,
        $filters,
        $currentFilters = [],
        $moreBtn,
        $questionTextArea,
        $addCategoriesButton,
        $addProductsButton,
        $categoriesList,
        $productsList,
        $addHeading,
        $addName,
        $addEmail,
        $addSubmit,
        $gotoAskQuestionButton,
        $askQuestionHolder,
        $voteUpButton,
        $voteDownButton,
        sortOrder,
        $questionForm,
        $productsSelect;

    function initProject() {
        setVars();
        modifyDom();
        addEvents();
    }

    function setVars() {
        $currentPageIndex = 1;
        $listHolder = $('#ax-ask-expert-questions');
        $moreBtn = $('#askexpert-load-more-button');
        $filters = $('#expert-filter .filter-button');
        $addCategoriesButton = $('#ax-ask-expert-add-categories-button');
        $addProductsButton = $('#ax-ask-expert-add-products-button');
        $addHeading = $('#ax-ask-expert-add-heading');
        $questionTextArea = $('#ax-ask-expert-add-question');
        $addName = $('#ax-ask-expert-add-name');
        $addEmail = $('#ax-ask-expert-add-email');
        $categoriesList = $('#ax-ask-expert-categories-list');
        $productsList = $('#ax-ask-expert-products-list');
        $addSubmit = $('#ax-ask-expert-add-submit-button');
        $gotoAskQuestionButton = $('#ax-ask-expert-goto-ask-question');
        $askQuestionHolder = $('#ax-ask-expert-ask-question-holder');
        $voteUpButton = $('#ax-ask-expert-vote-up');
        $voteDownButton = $('#ax-ask-expert-vote-down');
        sortOrder = "publishDate";
        $questionForm = $('#ax-ask-expert-question-form');
        $productsSelect = $('#products-select');
    }

    function modifyDom() {
        // TODO: Localize
        $(".chosen-select").chosen({
            no_results_text: "Hittade inte: ",
            width: '100%',
            height: '100%',
            max_selected_options: 5
        });

        // TODO: Localize
        $productsSelect.select2({
            placeholder: "Sök efter produkt...",
            formatInputTooShort: "Skriv minst 3 tecken",
            formatInputTooLong: "För lång sökning",
            formatSelectionTooBig: "Du kan ej välja fler",
            formatAjaxError: "Tillfälligt fel",
            formatSearching: "Söker...",
            formatNoMatches: "Inga träffar",
            minimumInputLength: 3,
            width: "100%",
            multiple: true,
            maximumSelectionSize: 5,
            ajax: {
                url: "/api/products/products",
                dataType: 'json',
                quietMillis: 100,
                data: function (term) {
                    return {
                        q: term
                    };
                },
                results: function (data) {
                    data = $.map(data, function(val, i) {
                        return {
                            id: val.id,
                            text: val.value
                        };
                    });

                    return { results: data };
                }
            },
            dropdownCssClass: "bigdrop",
            escapeMarkup: function (m) { return m; }
        });        

        if (typeof axCaptchaFailed !== 'undefined') {
            $('#ax-ask-expert-recaptcha-holder').removeClass('hidden');
        }

        if (typeof productId !== 'undefined' && typeof productName !== 'undefined') {
            $productsSelect.select2('data', { id: productId, text: productName });
            eventHandlers.expandProductsArea();
        }

        $('.ax-submit-question-widget .box-highlight #ax-ask-expert-add-heading').focus();
    }

    function addEvents() {
        $moreBtn.on('click', eventHandlers.loadMore);
        $filters.on('click', eventHandlers.filter);
        $questionTextArea.on('focus', eventHandlers.expandTextArea);
        $addCategoriesButton.on('click', eventHandlers.expandCategoriesArea);
        $addProductsButton.on('click', eventHandlers.expandProductsArea);
        $addSubmit.on('click', eventHandlers.submit);
        $.listen('parsley:field:success', eventHandlers.fieldValidated);
        $gotoAskQuestionButton.on('click', eventHandlers.scrollToAskQuestion);
        $voteUpButton.on('click', { "direction": "up" }, eventHandlers.vote);
        $voteDownButton.on('click', { "direction": "down" }, eventHandlers.vote);

        $('.like').hover(function () {
            $('.vote-like').stop(true, true).show();
        }, function () {
            $('.vote-like').fadeOut(300);
        });

        $('#ax-ask-expert-new-questions-button').on('click', function () {
            $('#ax-ask-expert-answered-questions-button').removeClass('selected');
            $(this).addClass('selected');

            sortOrder = "publishDate";
            eventHandlers.reloadFilter();
        });

        $('#ax-ask-expert-answered-questions-button').on('click', function () {
            $('#ax-ask-expert-new-questions-button').removeClass('selected');
            $(this).addClass('selected');

            sortOrder = "lastCommentDate";
            eventHandlers.reloadFilter();
        });
    }

    var eventHandlers = {
        findProducts: function (e) {
            
        },
        vote: function (e) {
            $('.vote-like').addClass('animated fadeOutLeft');
            $('.vote-like').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                $('.vote-like').removeClass('animated fadeOutLeft');
                $('.vote-like').hide();
            });

            $.ajax({
                type: "POST",
                url: '/api/votes/' + e.data.direction,
                data: { contentId: axPageId },
                dataType: 'json',
            }).done(function (data) {
                $('#votes-count').html(data);
            });
        },
        scrollToAskQuestion: function(e) {
            $('html, body').animate({
                scrollTop: $askQuestionHolder.offset().top - 50
            }, 500);
        },
        fieldValidated: function(e) {
            $('#ax-ask-expert-recaptcha-holder').removeClass('hidden');
        },
        expandCategoriesArea: function(e) {
            $addCategoriesButton.css("height", "auto");
            $categoriesList.css("visibility", "visible");
        },
        expandProductsArea: function(e) {
            $addProductsButton.css("height", "auto");
            $productsList.css("visibility", "visible");
        },
        expandTextArea: function(e) {
            $questionTextArea.animate({
                height: '150px'
            });
        },
        loadMore: function (e) {
            var url = "/api/pagelist/" + $parentId + "/" + $pageSize + "/" + ($currentFilters.length > 0 ? $currentFilters.join(",") : "") + sortOrder + "/false/" + $currentPageIndex;
            helpers.reload(url);
        },
        filter: function (e) {
            var filterId = $(this).data('filter-id');
            helpers.updateArray($currentFilters, filterId);
            eventHandlers.reloadFilter();
        },
        reloadFilter: function(e) {
            $currentPageIndex = 0;

            var url = "/api/pagelist/" + $parentId + "/" + $pageSize + "/" + ($currentFilters.length > 0 ? $currentFilters.join(",") : "") + "/" + sortOrder + "/false/" + $currentPageIndex;
            helpers.reload(url, true);
        },
        submit: function(e) {
            var valid = $('#ax-ask-expert-question-form').parsley().validate();
            if (valid === false) return;

            var selectedCategories = [];
            $("#ax-ask-expert-categories-list select option:selected").each(function () {
                selectedCategories.push($(this).val());
            });

            var question = {
                heading: $addHeading.val(),
                question: $questionTextArea.val(),
                name: $addName.val(),
                email: $addEmail.val(),
                categories: selectedCategories,
                products: []
            };

            $('#ax-ask-expert-question-form').submit();
        }
    };

    var helpers = {
        buildItem: function (data) {

            if (data.mainBody.length > 100)
                data.mainBody = data.mainBody.substring(0, 100) + '...';

            var html = "";
            html += "    <div class=\"single-question row\">";
            html += "        <div class=\"col-xs-12 col-sm-2 col-lg-1\">";
            html += "            <div class=\"like-comment-box\">";
            html += "                <div class=\"like\">";
            html += "                    <p><i class=\"fa fa-thumbs-up\"><\/i> " + data.properties.votes + "<\/p>";
            html += "                <\/div>";
            html += "                <div class=\"comment\">";
            html += "                    <p><i class=\"fa fa-pencil\"><\/i> " + data.properties.comments + "<\/p>";
            html += "                <\/div>";
            html += "            <\/div>";
            html += "        <\/div>";
            html += "        <div class=\"col-xs-12 col-sm-7 col-lg-8\">";
            html += "            <p class=\"question-title\"><a href=\"" + data.url + "\">" + data.heading + "<\/a><\/p>";
            html += "            <p class=\"question-answer\">";
            html += "                " + data.mainBody;
            html += "                <a href=\"" + data.url + "\"><b>Svara & Kommentera<\/b><\/a>";
            html += "            <\/p>";
            html += "        <\/div>";
            html += "        <div class=\"col-xs-7 col-sm-3 col-lg-3 tags\">";

            if (data.categories) {
                for (var i = 0; i < data.categories.length; i++) {
                    html += "        <div class=\"ax-button ax-button-default ax-button-xs pull-right\">" + data.categories[i] + "<\/div>";
                }
            }

            html += "            <br \/>";
            html += "        <\/div>";

            if (data.properties.hasExpertAnswer) {
                html += "    <div class=\"is-answered\">";
                html += "       <p>Experten har svarat<\/p>";
                html += "    <\/div>";
            }

            html += "    <\/div>";

            return html;
        },
        updateArray: function (array, val) {
            var index = -1;
            $.each(array, function (i, obj) {
                if (obj === val) {
                    index = i;
                    return false;
                }
            });

            if (index > -1) {
                array.splice(index, 1);
            } else {
                array.push(val);
            }
        },
        reload: function (url, empty) {
            $.getJSON(url, function (data) {
                if (empty) {
                    $listHolder.html('');
                }

                if (data.list.length === 0) {
                    // TODO: Localize
                    $listHolder.html('Det finns inga frågor att visa.');
                }

                $.each(data.list, function (i, val) {
                    $listHolder.append(helpers.buildItem(val));
                });

                if (!data.hasMore) {
                    $moreBtn.hide();
                } else {
                    $moreBtn.show();
                }

                $currentPageIndex++;
            });
        }
    };

    $(document).ready(function () {
        initProject();
    });

})(jQuery);;
(function($) {
    var $currentPageIndex,
        $listHolder;

    function initBlog() {
       setVars();
       modifyDom();
       addEvents();
    }

    function setVars() {
        $currentPageIndex = 1;
        $listHolder = $('#category-products-holder');
    }

    function modifyDom() {

    }

    function addEvents() {
        $('.load-more-blogs').on('click', eventHandlers.loadMore);
    }

    var eventHandlers = {
        loadMore: function (e) {

            var url = "/api/pagelist/" + $parentId + "/" + $pageSize + "/" + ($category ? $category : "") + "/" + $currentPageIndex;

            $.getJSON(url, function (data) {
                $.each(data.list, function (i, val) {

                    var html =  "<div class='col-xs-6 col-mob-12 single-blog'>" +
                                    "<div class='blog-image-holder'>" +
                                        "<a href='" + val.url + "' title='" + val.heading + "'>" +
                                            "<img src='" + val.imageUrl + "?width=340' alt='" + val.heading + "'>" +
                                        "</a>" +
                                    "</div>" +
                                    "<div class='blog-text-holder'>" +
                                        "<p>" + val.heading + " <b>" + val.datePublish + "</b></p>" +
                                    "</div>" +
                                "</div>";

                    $('.latest-blog-holder').append(html);
                });
                $currentPageIndex++;
                if (!data.hasmore) {
                    $('.load-more-blogs').hide();
                }
            });
        }
    };

    $(document).ready(function() {
        initBlog();
    });

})(jQuery);;
var ProductList = function() {
    var self = this;

    var $onhand,
        $shoppingCart, $rating ;

    var $currentFilter = {};
    var $currentPage = 1;
    var isChangingFilter = false;

    var $contentId,
        $viewContainer,
        $sort,
        $filterHolder,
        $filterContent,
        $listHolder,
        $paginationContainer;

    self.init = function (contentId, shoppingcart, onhand, rating) {
        $contentId = contentId;
        $onhand = onhand;
        $shoppingCart = shoppingcart;
        $rating = rating;

        // Bind to StateChange Event
        History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
            helpers.refreshView();
        });

        loadState();
        setVars();
        modifyDom();
        addEvents();
        rebind(true);
    }

    function setVars() {
        $viewContainer = $('#view');
        $sort = $('#list-sort');
        $filterHolder = $('#filter-holder');
        $filterContent = $('#filter-content');
        $listHolder = $('#category-products-holder');
        $paginationContainer = $('.pager');
    }

    function modifyDom() {

        //banner-category-block.is-in-grid ax-single-product first hasclass matching non-matching
        // console.log('modifydom');
        $.each($('.banner-category-block.is-in-grid'), function (i, catBlock) {
            var firstProduct = $('.ax-single-product').first();
            if (firstProduct.hasClass('matching'))
                $(catBlock).addClass('matching');
            else if (firstProduct.hasClass('non-matching'))
                $(catBlock).addClass('non-matching');

            console.log($('.ax-single-product').attr('class'));
        });

        $.each($('.filter-slider-container .filter-slider'), function (i, sliderdiv) {
            var slider = $(sliderdiv);

            var min = parseInt(slider.data('min'));
            var max = parseInt(slider.data('max'));
            var startRange = [];

            var start = slider.data('start');
            if (start) {
                var startFrags = start.split('-');
                startRange.push(startFrags[0]);
                startRange.push(startFrags[1]);
            } else {
                startRange.push(min);
                startRange.push(max);
            }

            slider.noUiSlider({
                start: startRange,
                step: 1,
                range: {
                    'min': [min],
                    'max': [max]
                }
            });

        });

        var multiselect = new MultiSelect($filterHolder, function() {
            // Set delay so we dont wait for all inputs to be updated if twe toggle a full group
            isChangingFilter = true;
            setTimeout(function () {
                if (isChangingFilter) {
                    $currentPage = 1;
                    eventHandlers.updateFilter();
                    isChangingFilter = false;
                }
            }, 50);
        });
        multiselect.init();

        if (is_old_IE) {
            $filterHolder.append($('<div class="col-md-12"><div id="doFilter" class="ax-button ax-button-primary padding-top pull-right" style="width:150px;">Filtrera</div></div>'));
            $('#doFilter').on('click', function () {
                eventHandlers.updateFilter();
            });
        }
    }

    function addEvents() {
        $('.category-info a.more').on('click', eventHandlers.readMore);
        $('#mobileReadMoreContainer .more').on('click', eventHandlers.readMore);
        
        $('.flag-filter-button', $filterHolder).on('click', function () {
            $(this).toggleClass('selected');
            $currentPage = 1;
            eventHandlers.updateFilter();
        });

        $('.danger-filter-button', $filterHolder).on('click', function () {
            $(this).toggleClass('selected');
            $currentPage = 1;
            eventHandlers.updateFilter();
        });

        $('.filter-slider-container .filter-slider').on('set', function() {
            $currentPage = 1;
            eventHandlers.updateFilter();
        });
        $('.filter-slider-container .filter-slider').on('slide', eventHandlers.changeRangeLabels);

        $('.show-all-button').on('click', function (e) {
            $(this).parents('.filter-wrapper').find('.dropdown-menu').addClass('show-all');
            $(this).parent().hide();
        });

        $('#toggle-filters').on('click', function (e) {
            if ($(window).width() < 768) {
                $(this).addClass('active');
                $('.mobile-filter-container').addClass('active');
                $('.close-mobile-overlay').fadeIn(300);
            }
        });

        $('.clear-filters').on('click', function () {
            event.preventDefault();
            History.pushState(null, $('title').first().text(), location.href.split('?')[0]);
            url = '/api/productlist/filters/?contentid=' + $contentId;
            $.ajax({
                type: "GET",
                url: url,
                success: function (html) {
                    $filterContent.html(html);
                    setVars();
                    modifyDom();
                    addEvents();
                    rebind();
                }
            });
        });

    }

    function rebind(isInitialLoad) {

        // sm and xs hidden default to avoid "jumping screen" when changing layout - let make it visible
        $('.products-holder').removeClass('hidden-sm');
        $('.products-holder').removeClass('hidden-xs');

        $sort.on('change', function () {
            $currentPage = 1;
            eventHandlers.updateFilter();
        });

        $('a', $paginationContainer).on('click', function () {
            event.preventDefault();
            var href = $(this).attr('href');
            $currentPage = href.split('?page=')[1];

            $('html, body').animate({
                scrollTop: $("#category-products-holder").offset().top - 70
            }, 100);

            eventHandlers.updateFilter();
            return false;
        });

        $('.open-stock-modal').on('click', function (event) { eventHandlers.openStockModal(event, $(this).data('id')); });

        $('.web-buy').on('click', function () {
            $shoppingCart.eventHandlers.add($(this).data('id'));
        });

        eventHandlers.showMatchingHeaders();
        
        if (!isInitialLoad) {
            $onhand.updateonhand();
            $rating.updateRatings();
        }
    }

    function loadState() {
        if (location.hash && location.hash != '') {
            var frags = location.hash.split('&');

            $currentFilter = {
                contentId: $contentId,
                page: frags[0].split('=')[1],
                sort: frags[1].split('=')[1],
                categories: helpers.getArrayFromHash(frags[2]),
                manufacturers: helpers.getArrayFromHash(frags[3]),
                flags: helpers.getArrayFromHash(frags[4]),
                priceRange: helpers.getArrayFromHash(frags[5]),
            };

            $currentPage = $currentFilter.page;
            helpers.refreshView();
        }
    }

    var eventHandlers = {
        updateFilter: function() {

            if ($filterHolder.length) {

                var categories;
                var $categories = $('select[data-type="Category"]', $filterHolder).val();

                if (Array.isArray($categories)) {
                    categories = $.map($categories, function(id, i) { return parseInt(id); });
                } else if ($categories !== null) {
                    categories = [$categories];
                } else {
                    categories = [];
                }

                var manufacturers;
                var $manufacturers = $('select[data-type="Manufacturer"]', $filterHolder).val();
                
                if (Array.isArray($manufacturers)) {
                    manufacturers = $.map($manufacturers, function(id, i) { return parseInt(id); });
                } else if ($manufacturers !== null) {
                    manufacturers = [$manufacturers];
                } else {
                    manufacturers = [];
                }

                var flags = $.map($('.ax-button[data-type="Flag"].selected', $filterHolder), function(flag, i) {
                    return parseInt($(flag).data('flagid'));
                });

                var isDangergoodsFilter = $('.danger-filter-button').hasClass('selected');

                var pMin = parseInt($('.filter-slider-container[data-type="Price"] .filter-slider', $filterHolder).data('min'));
                var pMax = parseInt($('.filter-slider-container[data-type="Price"] .filter-slider', $filterHolder).data('max'));
                var price = $('.filter-slider-container[data-type="Price"] .filter-slider', $filterHolder).val() ?
                    $.map($('.filter-slider-container[data-type="Price"] .filter-slider', $filterHolder).val(), function(val, i) {
                        return parseInt(val);
                    }) : [];

                if (price[0] == pMin && price[1] == pMax)
                    price = [];

                var parametrics = [];
                $.each($('.ax-button[data-type="Parametric"].selected', $filterHolder), function (i, flag) {
                    if ($(flag).data('id'))
                        parametrics.push('pb_' + $(flag).data('id'));
                });

                $.each($('.filter-slider-container[data-type="Parametric"]', $filterHolder), function(i, slider) {
                    var min = parseInt($('.filter-slider', $(slider)).data('min'));
                    var max = parseInt($('.filter-slider', $(slider)).data('max'));

                    var parametricRange = $.map($('.filter-slider', $(slider)).val(), function(val, i) {
                        return parseInt(val);
                    });
                    if (parametricRange[0] != min || parametricRange[1] != max) {
                        parametrics.push('pr_' + $(slider).data('id') + '_' + parametricRange[0] + '-' + parametricRange[1]);
                    }
                });

                $.each($('select[data-type="Parametric"]', $filterHolder), function(i, select) {
                        
                    if ($(select).val() && $(select).data('id')) {
                        parametrics.push('pl_' + $(select).data('id') + '_' + $(select).val());
                    }
                });

                $.each($('select[data-type="ParametricMulti"]', $filterHolder), function(i, select) {
                    if ($(select).val() && $(select).data('id')) {
                        parametrics.push('pm_' + $(select).data('id') + '_' + $(select).val().join(';'));
                    }
                });
            }

            $currentFilter = {
                contentId: $contentId,
                page: $currentPage,
                sort: $sort ? $sort.val() : '',
                categories: categories ? categories : [],
                manufacturers: manufacturers ? manufacturers : [],
                flags: flags ? flags : [],
                priceRange: price ? price : [],
                parametrics: parametrics ? parametrics : []
            };
            var qs =
                'page=' + $currentFilter.page +
                ($currentFilter.sort && $currentFilter.sort !== "popular" ? '&sort=' + $currentFilter.sort : '') +
                ($currentFilter.categories.length > 0 ? '&categories=' + $currentFilter.categories.join() : '') +
                ($currentFilter.manufacturers.length > 0 ? '&manufacturers=' + $currentFilter.manufacturers.join() : '') +
                ($currentFilter.flags.length > 0 ? '&flags=' + $currentFilter.flags.join() : '') +
                ($currentFilter.priceRange.length > 0 ? '&priceRange=' + $currentFilter.priceRange.join() : '') +
                ($currentFilter.parametrics.length > 0 ? '&parametrics=' + $currentFilter.parametrics.join() : '') + 
                (isDangergoodsFilter ? '&dangergoods=1' : '');

            if (is_old_IE) {
                window.location.href = location.origin + '' + location.pathname + '?' + qs;
            } else {
                History.pushState(null, $('title').first().text(), location.href.split('?')[0] + '?' + qs);
            }

        },
        toggleQuantityInput: function() {
            var select = $(this);
            if (select.val() === 'more') {
                select
                    .hide()
                    .siblings('input')
                    .show()
                    .focus();
            }
        },
        toggleLargeImage: function() {
            $('.large-image img', $productModal).attr('src', $(this).data('imageurl'));
        },
        readMore: function(e) {
            $(this).siblings('div').toggleClass('text-fade');
            var txt = $(this).siblings('div').hasClass('text-fade') ? 'Läs mer' : 'Dölj';
            $(this).text(txt);
            
            if ($(this).siblings('div').hasClass('text-fade') && $(this).parent().attr('id') == 'mobileReadMoreContainer') {
                $(window).scrollTop(0);
            }

            return false;
        },
        changeRangeLabels: function(e) {
            var range = $(this).val();
            var heading = $(this).siblings('h3').eq(0);
            $('.filter-slider-from', heading).html(parseInt(range[0]));
            $('.filter-slider-to', heading).html(parseInt(range[1]));
        },
        openStockModal: function(event, pid) {
            event.preventDefault();
            var $stockModal = $('#stock-modal');
            $stockModal.modal('show');
            $('.modal-content', $stockModal).html('');

            $.getJSON('/api/modals/stock/' + pid + '/1', function(html) {
                $('.modal-content', $stockModal).html(html);
            });
        },
        showMatchingHeaders: function() {

            var dividers = $('.list-divider');
            if (!dividers.length)
                return;

            dividers.hide();
            
            if ($('.matching').length) {
                dividers.filter('.green').insertBefore($('.matching').first()).show();
            }
            if ($('.non-matching').length) {
                var nonMatching = $('.non-matching');
                if ($('.matching').length) {
                    var well = $('<div class="well well-light" />');
                    var wrapper = $('<div class="row products-holder products-non-matching-holder" />');
                    wrapper.append(nonMatching).insertAfter($('.products-holder').first());
                }

                dividers.filter('.black').insertBefore(nonMatching.first()).show();
            }
        }
    };

    var helpers = {
        refreshView: function () {
            helpers.ajaxLoader(true);

            var url = typeof $brandId !== "undefined" ?
                '/api/productlist/brandlist/?contentid=' + $contentId + '&manufacturers=' + $brandId + '&' + location.href.split('?')[1] :
                '/api/productlist/?contentid=' + $contentId + '&' + location.href.split('?')[1];

            $.ajax({
                method: 'GET',
                url: url,
                type: 'json',
                success: function (html) {
                    $('link[rel="prev"], link[rel="next"]').remove();
                    $viewContainer.html(html);
                    $('link[rel="prev"], link[rel="next"]').detach().each(function(i, e) {
                        $(this).attr('href', location.href.split('?')[0] + '?' + $(this).attr('href').split('?')[1]).appendTo("head");
                    });
                    $('.pager a').each(function(i, e) {
                        $(this).attr('href', location.pathname.split('?')[0] + '?' + $(this).attr('href').split('?')[1]);
                    });
                    helpers.ajaxLoader(false);
                    setVars();
                    rebind();

                    $('.product-image .lazyload').each(function () {
                        $(this).attr('src', $(this).data('src'));
                    });

                    // Update filters (disable for now)
                    //url = '/api/productlist/filters/?contentid=' + $contentId + '&' + location.href.split('?')[1];
                    //$.ajax({
                    //    type: "GET",
                    //    url: url,
                    //    success: function (html) {
                    //        $filterContent.html(html);
                    //        setVars();
                    //        modifyDom();
                    //        addEvents();
                    //        rebind();
                    //    }
                    //});
                },
                error: function (xhr, textStatus, error) {
                    helpers.ajaxLoader(false);
                }
            });
        },
        getArrayFromHash : function(keyValue) {
            var array = [];
            if (keyValue) {
                var value = keyValue.split('=')[1];
                if (value && value.length > 0) {
                    var valueArray = value.split(',');
                    for (var i = 0; i < valueArray.length; i++) {
                        if (valueArray[i] && valueArray[i].length > 0)
                        array.push(parseInt(valueArray[i]));
                    }
                }
            }
            return array;
        },
        ajaxLoader: function (show) {
            if (show) {
                $('.products-holder').addClass('loading');
                $('.ajax-loader').show();
            } else {
                $('.products-holder').removeClass('loading');
                $('.ajax-loader').hide();
            }
        }
    };
};

if (!window.location.origin) {
    window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
};
var ax = ax || {};

var AxWsMap = function () {
    ax.mapItems = ax.mapItems || [];

    var self = this;
    var mapCanvas;
    var zoomLevel;
    var map;
    var bounds;
    var geocoder;
    var markers = [];

    var $input;
    var $selectWorkshop;
    var $preselectedWorkshop;
    var $single = false;
    var $preselectedServices;
    var $workshopsOnly;
    var $coordinates;
    var $infowindow;
    var $listHeaderTimer;
    var $isOfferPage;

    var listItemTemplate = MustacheHelper.getTemplate('/static/js/templates/findworkshop/listItem.html');
    var markerInfoTemplate = MustacheHelper.getTemplate('/static/js/templates/findworkshop/markerInfo.html');
    var markerInfoSmallTemplate = MustacheHelper.getTemplate('/static/js/templates/findworkshop/markerInfoSmall.html');
    var showMapWhenIdle = true;
    var subServiceItems;

    function MarkerDistance(distance, store) {
        this.distance = distance;
        this.store = store;
    }

    self.light_init = function () {

        if ($('.find-garage-list .list-holder').length) {

            if (navigator.geolocation) {

                navigator.geolocation.getCurrentPosition(
                    function (position) {

                        var center = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                        var allStoresAsMarkers = $.map(ax.mapItems, function (x, i) {
                            return {
                                position: new google.maps.LatLng(x.lat, x.lng),
                                store: x
                            };
                        });

                        var nearbyStores = helpers.getStoresInBoundSortedByDistance(allStoresAsMarkers, center);

                        $('.find-garage-list .list-holder').html('');

                        if (nearbyStores.length > 0) {
                            $.each(nearbyStores.slice(0, 50), function (i, s) {
                                var listItem = MustacheHelper.render(listItemTemplate, s);
                                $('.find-garage-list .list-holder').append(listItem);
                            });
                        }
                        $('#find-garage-list').removeClass('startup-filer-shops');
                    },
                    function () {
                    }, 
                    { maximumAge: 60000, timeout: 10000 }
                );
            }
        }

    }

    self.initialize_map = function (elem, stores, zoom, searchholder, selectWorkshop, isSingle, preselectedWorkshop, preselectedServices, workshopsOnly, coordinates, listItemTemplatePath, isOfferPage) {
        $preselectedWorkshop = preselectedWorkshop;
        mapCanvas = document.getElementById(elem);
        bounds = new google.maps.LatLngBounds();
        zoomLevel = zoom;
        $selectWorkshop = selectWorkshop;
        $single = isSingle;
        $preselectedServices = preselectedServices;
        $workshopsOnly = workshopsOnly;
        $coordinates = coordinates;
        listItemTemplate = listItemTemplatePath ? MustacheHelper.getTemplate(listItemTemplatePath) : listItemTemplate;
        $isOfferPage = isOfferPage;

        $.ajax({
            method: 'GET',
            url: '/api/service/subservices',
            type: 'json',
            async: false,
            success: function (items) {
                subServiceItems = items;
            },
            error: function (xhr, textStatus, error) {
            }
        });

        if (searchholder) {
            $('.find-garage-filter-toggle-item.map-filter .filter-button').unbind('click');
            $('.find-garage-filter-toggle-item.map-filter .filter-button').on('click', function () {
                if (!$(this).hasClass('selected')) {

                    var element = $(this);
                    setTimeout(function () {
                        $.each($('.map-filter .filter-button'), function (i, item) {
                            $(item).removeClass('selected');
                        });
                        element.addClass('selected');
                        helpers.reloadMap();
                    }, 10);
                }
            });

            $('#find-garage-filter .filter-button').unbind('click');
            $('#find-garage-filter .filter-button').on('click', function () {
                $(this).toggleClass('selected');
                setTimeout(function () {
                    $.publish('/services-modified/');
                    helpers.reloadMap();
                }, 250);
            });

            $('#find-garage-list-link').unbind('click');
            $('#find-garage-list-link').on('click', function (e) {
                e.preventDefault();
                $('html,body').animate({
                    scrollTop: $('#find-garage-list').offset().top - 130
                }, 'slow');
            });

            var multiselect = new MultiSelect('.find-garage-service-filter', (function () {

                var timer;
                return function () {
                    $.publish('/services-modified/');
                    clearTimeout(timer);
                    timer = setTimeout(function () {
                        helpers.reloadMap();
                    }, 250);
                };

            })());

            multiselect.nonSelectedTextDefault = 'Alla verkstadstj&auml;nster';
            multiselect.init();

            $input = $(searchholder + ' input');
            $input.on('keypress', function (e) {
                if (e.which == 13) {
                    helpers.doMapSearch();
                }
            });

            $($(searchholder + ' .ax-button-primary')).on('click', function (e) {
                e.preventDefault();
                helpers.doMapSearch();
            });

            if (navigator.geolocation) {
                var navLink = $(searchholder + ' .search-location');
                if (!navLink.hasClass('allways-hide'))
                    navLink.show();

                navLink.on('click', function (e) {
                    e.preventDefault();
                    helpers.reloadMap(function() {
                        navigator.geolocation.getCurrentPosition(
                           function (position) {
                               helpers.setMapCenterGeoPosition(position);
                           },
                           function () {
                               map.fitBounds(bounds);
                           },
                           { maximumAge: 60000, timeout: 10000 });

                    });
                });
            }

            $.subscribe('/services-modified/', function () {
                helpers.updateListHeader();
            });

            helpers.updateListHeader();
        }

        if (stores) {
            helpers.loadMap(stores);
            map.setCenter(new google.maps.LatLng(stores[0].lat, stores[0].lng));
            map.setZoom(11);
        }
        else if ($coordinates) {
            helpers.reloadMap(function () {
                var listener = google.maps.event.addListenerOnce(map, "idle", function () {
                    if (stores || $coordinates) {
                        var lat;
                        var lng;
                        var zoomLvl = zoomLevel;

                        if (stores) {
                            lat = stores[0].lat;
                            lng = stores[0].lng;
                        } else {
                            lat = $coordinates.Latitude;
                            lng = $coordinates.Longitude;
                            zoomLvl = $coordinates.MapZoom;
                        }

                        map.setCenter(new google.maps.LatLng(lat, lng));
                        map.setZoom(zoomLvl);
                    }

                    else if (navigator.geolocation && !($input && $input.val()) && !$coordinates) {

                        var timeoutHandle = setTimeout(function () {
                            map.fitBounds(bounds);
                            $('.find-garage-map-holder').addClass('is-loaded');
                        }, 5000);

                        navigator.geolocation.getCurrentPosition(
                            function (position) {
                                clearTimeout(timeoutHandle);
                                helpers.setMapCenterGeoPosition(position);
                                helpers.findClosest(position);
                            },
                            function () {
                            },
                            { maximumAge: 60000, timeout: 10000 });

                    }

                    google.maps.event.removeListener(listener);
                });
            });

        }
        else if ($input && $input.val() && $input.val() != $input.attr('placeholder')) {
            helpers.reloadMap(helpers.doMapSearch);

        }
        else if (navigator.geolocation) {
            showMapWhenIdle = false;

            helpers.reloadMap(function () {
                
                var timeoutHandle = setTimeout(function () {
                    map.fitBounds(bounds);
                    $('.find-garage-map-holder').addClass('is-loaded');
                }, 5000);

                navigator.geolocation.getCurrentPosition(
                            function (position) {
                                clearTimeout(timeoutHandle);
                                helpers.setMapCenterGeoPosition(position);
                                $('.find-garage-map-holder').addClass('is-loaded');
                                helpers.findClosest(position);
                                
                            },
                            function () {
                            },
                            { maximumAge: 60000, timeout: 10000 });
            });
        }
        
        $.subscribe('/filter-services/', function (services) {
            helpers.reloadMap();
        });
    }
    self.centerMap = function (centerPos) {
        map.setCenter(centerPos);
    }
    self.triggerStoreMarker = function (storeId) {
        let storefilter = markers.filter(function (m) {
            return m.store.id == storeId;
        });
        var location = new google.maps.LatLng(storefilter[0].store.lat, storefilter[0].store.lng);
        map.setCenter(location);
        new google.maps.event.trigger(storefilter[0], 'click');
    }

    var helpers = {

        getServiceIdForSearch: function (serviceID) { // subservices return parent id, regual default pack to input
            if (subServiceItems) {
                for (var i = 0; i < subServiceItems.length; i++)
                {
                    if (serviceID == subServiceItems[i].serviceID)
                        return subServiceItems[i].parentServiceID;
                }
            }
            return serviceID;
        },

        reloadMap: function (callback) {

            var services = helpers.getServices();

            var types = [];

            if ($workshopsOnly) {
                types.push(2);
            } else {
                $.each($('.map-filter.find-garage-filter-toggle-item .selected'), function (i, item) {
                    if (!$(item).hasClass('filter-all')) {
                        types.push($(this).data('id'));
                    }
                });
            }
            
            if (services.length === 0 && (types.length === 0 || $isOfferPage) && ax.mapItems.length > 0) {
                helpers.loadMap(ax.mapItems);
                if ($.isFunction(callback)) {
                    callback();
                }
            } else {
                helpers.getStores([], services, types, $isOfferPage, function (stores) {
                    helpers.loadMap(stores);
                    if ($.isFunction(callback)) {
                        callback();
                    }
                });
            }
        },

        getServices: function () {
            var services;
            var $services = $('select[data-type="Service"]', '.find-garage-service-filter').val();

            if (Array.isArray($services)) {
                services = $.map($services, function (id, i) { return parseInt(id); });
            } else if ($services) {
                services = [$services];
            } else {
                services = [];
            }

            if (services.length === 0) {
                $.each($('#find-garage-filter .selected'), function (i, item) {

                    services.push($(this).data('id'));

                });
            }

            return services;
        },

        loadMap: function (stores) {
            var map_options = {
                disableDefaultUI: true,
                zoom: zoomLevel,
                zoomControl: true,
                scrollwheel: false,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL
                },
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                styles: styles
            }

            var currentCenter = map ? map.getCenter() : null;
            var currentZoom = map ? map.getZoom() : null;

            map = null;
            markers = [];
            bounds = new google.maps.LatLngBounds();

            map = new google.maps.Map(mapCanvas, map_options);
            geocoder = new google.maps.Geocoder();

            google.maps.event.addDomListener(window, 'resize', function () {
                var center = map.getCenter();
                google.maps.event.trigger(map, 'resize');
                map.setCenter(center);
            });

            if ($input) {
                google.maps.event.addListener(map, 'zoom_changed', (function () {
                    var timer;
                    return function () {
                        clearTimeout(timer);
                        timer = setTimeout(function () {
                            helpers.updatelist();
                        }, 200);
                    }
                }()));

                google.maps.event.addListener(map, 'dragend', (function () {
                    var timer;
                    return function () {
                        clearTimeout(timer);
                        timer = setTimeout(function () {
                            helpers.updatelist();
                        }, 200);
                    }
                }()));
            }

            var listener = google.maps.event.addListenerOnce(map, "idle", function () {

                if (showMapWhenIdle) {
                    $('.find-garage-map-holder').addClass('is-loaded');
                }

                google.maps.event.removeListener(listener);
            });

            helpers.addMarkers(stores);

            if (currentCenter && currentZoom) {
                map.setCenter(currentCenter);
                map.setZoom(currentZoom);
            }

            if ($preselectedWorkshop) {
                markers.forEach(function (marker) {
                    if (marker.store.id === parseInt($preselectedWorkshop)) {
                        map.setCenter(new google.maps.LatLng(marker.store.lat, marker.store.lng));
                    }
                });
            }
        },

        addMarkers: function (stores) {
            for (var i in stores) {
                if (stores.hasOwnProperty(i)) {

                    var store = stores[i];

                    if (stores[i].lat > 0 && stores[i].lng > 0) {
                        var location = new google.maps.LatLng(stores[i].lat, stores[i].lng);

                        var marker = new google.maps.Marker({
                            position: location,
                            map: map,
                            icon: helpers.getCorrectMarker(stores[i].type),
                            store: store,
                            optimized: true,
                            title: store.title
                    });

                        // Create closure
                        (function (map, marker, store) {
                            google.maps.event.addListener(marker, 'click', function () {
                                if ($infowindow)
                                    $infowindow.close();
                                $infowindow = new google.maps.InfoWindow({
                                    content: helpers.getMarkerInfoHtml(store)
                                });
                                $infowindow.open(map, marker);
                            });
                        })(map, marker, store);

                        bounds.extend(location);
                        markers.push(marker);
                    }
                }
            }

            var mcOptions = {
                gridSize: 30,
                maxZoom: 15,
                enableRetinaIcons: true,
                styles: [
                    {
                        height: 64,
                        width: 64,
                        url: "/static/img/png/cluster.png",
                        fontFamily: "AutoexpertenText, Arial, sans-serif",
                        textSize: 14,
                        textColor: "#FFF",
                        
                    }
                ]
            };

            var markerCluster = new MarkerClusterer(map, markers, mcOptions);

        },

        getCorrectMarker: function (type) {

            var marker_url = '/static/img/png/map-cart_x2.png';

            switch (type) {
                case 1:
                    marker_url = '/static/img/png/map-cart_x2.png';
                    break;

                case 2:
                    marker_url = '/static/img/png/map-garage_x2.png';
                    break;

                case 3:
                    marker_url = '/static/img/png/map-garage_x2.png';
                    break;
            }

            var icon = {
                url: marker_url, // url
                size: new google.maps.Size(64, 64), // size
                scaledSize: new google.maps.Size(32, 32), // scaled size
                origin: new google.maps.Point(0, 0), // origin
                anchor: new google.maps.Point(0, 0) // anchor
            };

            return icon;
        },

        setMapCenterGeoPosition: function (position) {

            map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
            map.setZoom(zoomLevel);
        },

        getMarkerInfoHtml: function (store) {
            var info = '';
            store.canSelect = $selectWorkshop;

            if ($(window).width() <= 767) {
                info = MustacheHelper.render(markerInfoSmallTemplate, store);
            } else {
                info = MustacheHelper.render(markerInfoTemplate, store);
            }

            return info;
        },

        getStores: function (ids, services, types, disableOffer, callback) {

            for (var i = 0; i < services.length; i++) {
                services[i] = this.getServiceIdForSearch(services[i]);
            }

            $.ajax({
                method: 'POST',
                url: '/api/workshop/search',
                data: { services: services, types: types, disableOffer: disableOffer },
                type: 'json',
                async: false,
                success: function (items) {
                    stores = items;
                    if ($.isFunction(callback)) {
                        callback(items);
                    }
                },
                error: function (xhr, textStatus, error) {
                }
            });
        },

        getMarkersInBound: function () {
            var b = map.getBounds();
            var markerhits = [];

            for (var i = 0; i < markers.length; i++) {
                if (b.contains(markers[i].getPosition())) {
                    markerhits.push(markers[i]);
                }
            }

            return markerhits;
        },

        getStoresInBound: function () {
            var markersInBound = this.getMarkersInBound();
            if (markers.length == markersInBound.length)
                return this.getStoresInBoundByDefault(markersInBound);
            else
                return this.getStoresInBoundSortedByDistance(markersInBound, map.getCenter());
        },

        getStoresInBoundByDefault: function (markersInBound) {
            var stores = [];
            for (var i = 0; i < markersInBound.length; i++) {
                stores.push(markersInBound[i].store);
            }
            return stores;
        },

        getStoresInBoundSortedByDistance: function (markersInBound, center) {
            var hits = [];
            for (var i = 0; i < markersInBound.length; i++) {
                distanceHit = google.maps.geometry.spherical.computeDistanceBetween(center, markersInBound[i].position);
                hits.push(new MarkerDistance(distanceHit, markersInBound[i].store));
            }

            hits.sort(function (a, b) {
                return a.distance - b.distance;
            });

            var stores = [];
            for (var i = 0; i < hits.length; i++) {
                stores.push(hits[i].store);
            }

            return stores;
        },
        getNearbyStores: function (city) {
            var b = map.getBounds();

            var stores = [];

            if (city) {
                for (var i = 0; i < markers.length; i++) {
                    if (!b.contains(markers[i].getPosition()) && markers[i].store.city && markers[i].store.city.toLowerCase() === city.toLowerCase()) {
                        stores.push(markers[i].store);
                    }
                }
            }

            return stores;
        },

        zoomOutToClosestMarker: function (position) {
            var store = helpers.findClosestMarker(position);
            var b = map.getBounds();
            var storePos = new google.maps.LatLng(store.lat, store.lng);
            b.extend(storePos);
            map.fitBounds(b);
        },

        doMapSearch: function () {
            $input.removeClass('has-error');
            $input.removeClass('error-highlight');
            var query = $input.val();
            if (!query)
                return;

            var items = markers.filter(function (marker) {
                return marker.store.title.toLowerCase().trim().replace('  ', ' ') === query.toLowerCase();
            });

            if (items.length) {

                var item = items[0];
                map.panTo(item.position);
                map.setZoom(15);
                helpers.updatelist();

            } else {

                geocoder.geocode({ 'address': query + ', sweden' }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        map.fitBounds(results[0].geometry.viewport);

                        var b = map.getBounds();
                        var city = results[0].address_components[0].long_name;
                        var nearbyStores = helpers.getNearbyStores(city);
                     
                        for (var i = 0; i < nearbyStores.length; i++) {
                            var nearbyStore = nearbyStores[i];
                            b.extend(new google.maps.LatLng(nearbyStore.lat, nearbyStore.lng));

                        }
                        map.fitBounds(b);
                        if (results[0].geometry.viewport) {
                            var marketsInBound = helpers.getMarkersInBound();
                            if (!marketsInBound.length) {
                                helpers.zoomOutToClosestMarker(helpers.getGeoCodePosition(results));
                            } else {
                                if (marketsInBound.length > 10 && helpers.isGeoCodeNotCountryOrCounty(results)) {
                                    helpers.zoomInToClosestMarker(helpers.getGeoCodePosition(results), marketsInBound.length);
                                }
                            }
                        }

                        helpers.updatelist();
                    } else {

                        var items = markers.filter(function (marker) {
                            return marker.store.title.toLowerCase().indexOf(query.toLowerCase()) !== -1;
                        });

                        if (items.length) {
                            var item = items[0];
                            map.panTo(item.position);
                            map.setZoom(15);
                            helpers.updatelist();
                        } else {
                            $input.addClass('has-error');
                            $input.addClass('error-highlight');
                        }
                    }
                });
            }
        },

        updatelist: function () {
            if ($('.find-garage-list .list-holder').length) {

                stores = helpers.getStoresInBound();

                $('.find-garage-list .list-holder').html('');

                if (stores.length > 0) {
                    $.each(stores, function (i, s) {
                        var listItem = MustacheHelper.render(listItemTemplate, s);
                        $('.find-garage-list .list-holder').append(listItem);
                    });
                }
                $('#find-garage-list').removeClass('startup-filer-shops');
            }
        },

        updateListHeader: function () {
            clearTimeout($listHeaderTimer);
            $listHeaderTimer = setTimeout(function () {
                var services = helpers.getServices();
                if (services.length > 0) {

                    $('.find-garage-list-filter').removeClass('hidden');
                    $('.garage-list-filter-button[data-id]').addClass('hidden');
                    $.each(services, function (i, s) {
                        $('.garage-list-filter-button[data-id="' + s + '"]').removeClass('hidden');
                    });

                } else {
                    $('.find-garage-list-filter').addClass('hidden');
                }
            }, 150);

        },

        findClosest: function (position) {

            var closestStore = helpers.findClosestMarker(position, true);
            if (closestStore) {
                $('.closest-store a').attr('href', closestStore.url);
                $('.closest-store p b').html(closestStore.title);
            } else {
                $('.closest-store').hide();
            }
            var closestWorkshop = helpers.findClosestMarker(position, false);
            if (closestWorkshop) {
                $('.closest-workshop a').attr('href', closestWorkshop.url);
                $('.closest-workshop p b').html(closestWorkshop.title);
            } else {
                $('.closest-workshop').hide();
            }
            if (closestStore || closestWorkshop)
                $('.closest-shop-holder').addClass('visible-xs');
        },
        zoomInToClosestMarker: function (pos, marketCount) {
            var nearestStore = helpers.findClosestMarker(pos);
            var storePos = new google.maps.LatLng(nearestStore.lat, nearestStore.lng);
            //map.panTo(storePos);
            //let zoomInLevel = 11;
            //if (marketCount > 15)
            //    zoomInLevel = $(window).width() < 750 ? 11 : 12;
            //map.setZoom(8);
       },
        getGeoCodePosition: function (results) {
            var pos = {
                coords: {
                    latitude: results[0].geometry.location.lat(),
                    longitude: results[0].geometry.location.lng()
                }
            }
            return pos;
        },
        isGeoCodeNotCountryOrCounty: function(results) {
            return results[0].types.length && results[0].types[0] != 'administrative_area_level_1' && results[0].types[0] != 'country';
        },
        findClosestMarker: function (position, onlyStores) {

            var rad = function (x) { return x * Math.PI / 180; };

            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            var R = 6371; // radius of earth in km
            var distances = [];
            var closest = -1;
            for (i = 0; i < markers.length; i++) {
                if ((onlyStores && markers[i].store.type == 1) || (!onlyStores && markers[i].store.type != 1)) {
                    var mlat = markers[i].position.lat();
                    var mlng = markers[i].position.lng();
                    var dLat = rad(mlat - lat);
                    var dLong = rad(mlng - lng);
                    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                        Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
                    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                    var d = R * c;
                    distances[i] = d;
                    if (closest == -1 || d < distances[closest]) {
                        closest = i;
                    }
                }
            }
            if (closest > 0)
                return markers[closest].store;
            else
                return null;
        }
    }

    function positionSuccess() {
        console.log('positionSuccess');
    }

    function positionError(error) {
        console.log('positionError');
    }


    var styles = [
        {
            "elementType": "labels.text",
            "stylers": [
                {
                    "visibility": "on",
                    "color": "#66687a",
                }
            ]
        },
        {
            "featureType": "landscape.natural",
            "elementType": "geometry.fill",
            "stylers": [
                {
                    "color": "#f5f5f2"
                },
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "administrative",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "transit",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi.attraction",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "landscape.man_made",
            "elementType": "geometry.fill",
            "stylers": [
                {
                    "color": "#ffffff"
                },
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi.business",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi.medical",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi.place_of_worship",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi.school",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi.sports_complex",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#ffffff"
                },
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "stylers": [
                {
                    "visibility": "on"
                },
                {
                    "color": "#ffffff"
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "color": "#ffffff"
                },
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "stylers": [
                {
                    "color": "#ffffff"
                }
            ]
        },
        {
            "featureType": "road.local",
            "stylers": [
                {
                    "color": "#ffffff"
                }
            ]
        },
        {
            "featureType": "poi.park",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "water",
            "stylers": [
                {
                    "color": "#71c8d4"
                }
            ]
        },
        {
            "featureType": "landscape",
            "stylers": [
                {
                    "color": "#e5e8e7"
                }
            ]
        },
        {
            "featureType": "poi.park",
            "stylers": [
                {
                    "color": "#8ba129"
                }
            ]
        },
        {
            "featureType": "road",
            "stylers": [
                {
                    "color": "#ffffff"
                }
            ]
        },
        {
            "featureType": "poi.sports_complex",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#c7c7c7"
                },
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "water",
            "stylers": [
                {
                    "color": "#abccff"
                }
            ]
        },
        {
            "featureType": "poi.park",
            "stylers": [
                {
                    "color": "#91b65d"
                }
            ]
        },
        {
            "featureType": "poi.park",
            "stylers": [
                {
                    "gamma": 1.51
                }
            ]
        },
        {
            "featureType": "road.local",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "poi.government",
            "elementType": "geometry",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "landscape",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "labels",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road.local",
            "stylers": [
                {
                    "visibility": "on"
                }
            ]
        },
        {
            "featureType": "road"
        },
        {
            "featureType": "road"
        },
        {},
        {
            "featureType": "road.highway"
        }
    ];

};;
const offer2020ListItem = document.querySelectorAll('.offer-2020 .qa ul li');

for (let offer of offer2020ListItem) {
    offer.addEventListener('click', onOffer2020Click);
}

function onOffer2020Click(event) {
    if (event.target.classList.contains('question')) {
        if (event.target.closest('li').classList.contains('active')) {
            event.target.closest('li').classList.remove('active');
        } else {
            event.target.closest('li').classList.add('active');
        }
    }
}

(function ($) {

    $(document).ready(function () {

        $('.service-preselector').click(function (e) {
            if (tryOpenApp($(this).attr('href'), true))
                return false;
            return true;
        });

        $('.service-opener').click(function (e) {
            if (tryOpenApp($(this).attr('href'), false))
                return false;
            return true;
        });

        function tryOpenApp(href, shouldSelectService) {

            const service = getServiceIdFromUrl(href);

            if (service > 0) {

                const offerOpenBtn = $('.services-overview').find('.services-steps__step--services');
                const selectServiceBtn = $('.modal-service').find('input[type=checkbox][value=' + service + ']').siblings('.ax-button');
                const tabHeader = selectServiceBtn.parentsUntil('.services-list').last().siblings('h2').text();
                const tabSliders = $('.services-swiper .services-swiper__slide');
                let tabElement = null;

                // trigger open offer "app"
                offerOpenBtn.click();

                tabSliders.each(function () {
                    if ($(this).text() == tabHeader.trim()) {
                        tabElement = $(this);
                        setTimeout(function () { tabElement.click() }, 500); // trigger "app" service header tab
                    }
                });

                if (shouldSelectService)
                    setTimeout(function () { selectServiceBtn.click() }, 500); // trigger "app" select service button

                return true;
            }

            return false;
        }

        function getServiceIdFromUrl(url) {
            let service = 0;
            if (url.indexOf('?') > -1) {
                const queryString = '?' + url.split('?')[1];
                const urlParams = new URLSearchParams(queryString);
                if (urlParams.has('service'))
                    service = urlParams.get('service');
            }
            return service
        }

    });

})(jQuery);



;
var Offer = function () {
    var summary = {
        workshop: {
            id: null,
            name: null
        },
        services: [],
        beginDate: null,
        endDate: null,
        regNo: null
    };

    var preselected = {
        workshopId: null,
        serviceIds: null,
        splitter: null,
    };

    var $workshopName = $('.offer-summary-workshop-name');
    var $serviceList = $('.offer-summary-service-list');
    var $selectServicesHeading = $('#offer-select-services-heading');
    var $regNumberInput = $('#offer-reg-number');
    var $vehicleSpecs = $('#offer-vehicle-specs');
    var $vehicleChassisNumber = $('.offer-vehicle-chassis-number');
    var $vehicleName = $('.offer-vehicle-name');
    var $vehicleRegistrationDate = $('.offer-vehicle-registration-date');
    var $noWorkshopSelectedMessage = $('#offer-no-workshop-selected');
    var $selectServicesRow = $('#offer-select-services-row');
    var $form = $('#offer-form');
    var $findGarageHolder = $('.find-garage-content-holder');
    var $workshopSelectedMessage = $('#offer-workshop-selected');
    var $selectWorkshopHeading = $('#offer-select-workshop-heading');
    var $submitButton = $('#offer-submit-button');
    var m_allWorkshopButtons = '.select-workshop-bytext .garage-button';
    var m_markers = [];

    function handlePreselections() {
        function getWorkshop() {
            $.ajax({
                method: 'GET',
                url: '/api/workshop/get/' + preselected.workshopId,
                type: 'json',
                success: function (data) {
                    summary.workshop = {
                        id: data.id,
                        name: data.title
                    };

                    $.publish('/select-workshop/', [data.id, data.title]);
                },
                error: function (xhr, textStatus, error) {

                }
            });
        }

        $('.offer-workshop-prespinner').hide();
        $findGarageHolder.show();

        if (preselected.workshopId !== null) // default workshop selected 
        {
            $noWorkshopSelectedMessage.hide(); 
            $selectServicesRow.show(); 
            $.publish('/services-modified/');
            getWorkshop();
            $workshopSelectedMessage.removeClass('hidden');
            $findGarageHolder.hide();
        }

        if (preselected.serviceIds !== null) // default service(s) found.
        {
            // Service
            var services = preselected.serviceIds.split(preselected.splitter);
            var firstService = "";
            var moreServices = "";
            
            for (var i = 0; i < services.length; i++) {
                var $serviceCheckbox = $('#service-checkbox-' + services[i]);
                if ($serviceCheckbox.length > 0)
                {
                    $serviceCheckbox.prop('checked', true);
                    $serviceCheckbox.addClass('selected');
                    if (firstService.length == 0)
                        firstService = $serviceCheckbox.data('name');
                    else
                        moreServices = " mm."
                }
            }

            if (firstService.length > 0)
            {
                $selectWorkshopHeading.html('Välj verkstad som utför <strong>' + firstService + moreServices + '</strong>');
                $noWorkshopSelectedMessage.show();
                $selectServicesRow.hide();
                $.publish('/services-modified/');
                $.publish('/filter-services/');
            }

            if (preselected.workshopId == null) // default workshop not selected 
            {
                $findGarageHolder.show();
            }
            else
            {
                $findGarageHolder.hide();
            }

        } 
    }

    function selectWorkshop(id, title) {
        summary.workshop = {
            id: id,
            name: title
        };

        $('button.select-workshop').hide();
        $('.select-workshop-success').fadeIn();

        $selectServicesHeading.html('Välj tjänster från');
    }

    function updateSummary() {
        $workshopName.html(summary.workshop.name);

        var servicesHtml = '';
        summary.services.forEach(function (item) {
            servicesHtml += '<li>' + item + '</li>';
        });
        $serviceList.html(servicesHtml);

    }

    function updateServices() {
        function filterDom(services) {
            $('.service-holder').show();

            // Hide and deselect each service not present in the
            // available services array
            $('.service-holder').each(function (e) {
                if ($.inArray(parseInt($(this).data('id')), services) === -1) {
                    $(this).hide();
                    $(this).removeClass('selected');
                    $(this).prop('checked', false);
                }
            });

            // Hide empty service blocks
            $('.single-service').each(function (e) {
                if ($('li[style!="display: none;"]', $(this)).length === 0) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });

            //if (preselected.serviceIds !== null) {
            //    var $preselected = $('#service-checkbox-' + preselected.serviceIds);
            //    $preselected.prop('checked', true);
            //    $preselected.addClass('selected');
            //}

        }

        $.ajax({
            method: 'GET',
            url: '/api/workshop/get/' + summary.workshop.id + '/services',
            type: 'json',
            success: function (data) {
                // Show only these services
                filterDom(data);
            },
            error: function (xhr, textStatus, error) {

            }
        });
    }

    function updateRegNumber(regNumber) {
        $.ajax({
            method: 'POST',
            url: '/api/vehicle/set',
            data: {
                RegNo: regNumber
            },
            type: 'json',
            success: function (data) {
                summary.regNo = regNumber;
                $regNumberInput.removeClass('has-error');
                $vehicleChassisNumber.html(data.chassisNumber);
                $vehicleRegistrationDate.html(data.registrationDate.replace('00:00:00', ''));
                $vehicleName.html(data.name);
                $vehicleSpecs.fadeIn(200);
            },
            error: function (xhr, textStatus, error) {
                summary.regNo = null;
                $regNumberInput.addClass('has-error');
                $vehicleSpecs.fadeOut(200);
            }
        });
    }

    function openServiceModal(event) {

        event.preventDefault();

        var modal = $('#service-modal');
        var link = $(this);
        
        $('#modal-service-header', modal).html(link.data('modal-header'));
        $('.sub-header', modal).html(link.data('modal-subheader'));
        $('.body', modal).html(link.data('modal-content'));
        modal.modal('show');
        
    }

    function addEvents() {

        setInterval(updateSummary, 5000);

        $regNumberInput.on('focusout', function (e) {
            var regNo = $(this).val().replace(' ', '');
            if (regNo.length === 6 && $(this).val() !== summary.regNo) {
                updateRegNumber(regNo);
            }
        });

        $submitButton.on('click', function (e) {

            e.preventDefault();

            $('input[name="WorkshopId"]').val(summary.workshop.id);

            var valid = $form.parsley().validate();
            if (!valid)
                return false;

            $submitButton.attr("disabled", "disabled");
            $form.submit();
        });

        $('body').on('click', '.open-service-modal-link', openServiceModal);

        $('.terms-checkbox label').click(function () {

            var checkboxTerms = $(this).siblings('.filter-button');

            if (checkboxTerms.is(':checked')) {
                checkboxTerms.removeClass('selected');
                checkboxTerms.prop('checked', false);
            } else {
                checkboxTerms.addClass('selected');
                checkboxTerms.prop('checked', true);
            }

        });
    }

    function initPubSub() {
        $.subscribe('/services-modified/', function () {
            // Collect all selected services
            summary.services = [];
            $('.filter-button:checked').each(function (index, item) {
                summary.services.push($(item).data('name'));
            });

            updateSummary();
        });

        $.subscribe('/select-workshop/', function (id, title) {
            selectWorkshop(id, title);
            updateSummary();
            updateServices();
            limitDatePickers(id);

            $noWorkshopSelectedMessage.hide();
            setTimeout(function () {
                $('html, body').animate({
                    scrollTop: $("#offer-select-services").offset().top - 100
                }, 500, function () {
                    $selectServicesRow.show();
                });
            }, 500);
        });

        $.subscribe('/select-workshop-only/', function (id, title) {
            console.log('select-workshop-only');
            selectWorkshop(id, title);
            updateSummary();
        });
    }

    function addAffix() {
        $('.table-summary-widget').affix({
            offset: {
                top: 250,
                bottom: function () {
                    var bottom = $('.footer-text').outerHeight(true) + $('.footer-menus').outerHeight(true) + $('.footer-utils').outerHeight(true);
                    return (this.bottom = bottom + 230);
                }
            }
        });
    }

    Date.prototype.addDays = function (days) {
        var dat = new Date(this.valueOf());
        dat.setDate(dat.getDate() + days);
        return dat;
    }

    function getDates(startDate, stopDate) {
        var dateArray = new Array();
        var currentDate = startDate;
        while (currentDate <= stopDate) {
            dateArray.push(new Date(currentDate).toDateString());
            currentDate = currentDate.addDays(1);
        }
        return dateArray;
    }

    function dayClosed(date, data) {
        var day = date.getDay();

        switch (day) {
            case 0:
                return data.sun.closed;
            case 1:
                return data.mon.closed;
            case 2:
                return data.tue.closed;
            case 3:
                return data.wed.closed;
            case 4:
                return data.thu.closed;
            case 5:
                return data.fri.closed;
            case 6:
                return data.sat.closed;
        }

        return false;
    }

    function isOlderDays(date) {
        var nowTemp = new Date();
        var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

        return date.valueOf() < now.valueOf();
    }

    function checkDates(date, disabledDates, data) {
        if (dayClosed(date, data)
            || isOlderDays(date)
            || $.inArray(date.toDateString(), disabledDates) > -1) {
            return 'disabled';
        }
    }

    function limitDatePickers(workshopId) {
        if (workshopId === null) {
            setupStandardDatepickers();
        } else {
            $.ajax({
                method: 'GET',
                url: '/api/workshop/get/' + workshopId + '/openinghours',
                type: 'json'
            }).success(function (data) {
                if (data) {
                    var disabledDates = [];

                    $.each(data.closedPeriods, function (index, period) {
                        var from = new Date(period.from);
                        var to = new Date(period.to);
                        disabledDates = disabledDates.concat(getDates(from, to));
                    });

                    var earlyDate = $('#offer-early-date').datepicker({
                        format: 'yyyy-mm-dd',
                        onRender: function (date) {
                            if (earlyDate && earlyDate.date && latestDate && latestDate.date) {
                               if (date.valueOf() >= earlyDate.date.valueOf() && date.valueOf() <= latestDate.date.valueOf()) {
                                   return 'in-range';
                               }
                            }

                            return checkDates(date, disabledDates, data);
                        }
                    }).on('changeDate', function (ev) {
                        if (ev.date.valueOf() > latestDate.date.valueOf()) {
                            var newDate = new Date(ev.date)
                            newDate.setDate(newDate.getDate() + 1);
                            latestDate.setValue(newDate);
                        }

                        latestDate.update();
                        earlyDate.hide();
                        $('#offer-latest-date')[0].focus();
                    }).data('datepicker');

                    var latestDate = $('#offer-latest-date').datepicker({
                        format: 'yyyy-mm-dd',
                        onRender: function (date) {
                            if (earlyDate && earlyDate.date && latestDate && latestDate.date) {
                                if (date.valueOf() >= earlyDate.date.valueOf() && date.valueOf() < latestDate.date.valueOf()) {
                                    return 'in-range';
                                }
                            }

                            if (date.valueOf() <= earlyDate.date.valueOf()) {
                                return 'disabled';
                            }

                            return checkDates(date, disabledDates, data);
                        }
                    }).on('changeDate', function (ev) {
                        latestDate.hide();
                        earlyDate.update();
                    }).data('datepicker');
                } else {
                    setupStandardDatepickers();
                }
            });
        }

    }

    function setupStandardDatepickers() {
        var earlyDate = $('#offer-early-date').datepicker({
            format: 'yyyy-mm-dd',
            onRender: function (date) {
               if (earlyDate && earlyDate.date && latestDate && latestDate.date) {
                    if (date.valueOf() >= earlyDate.date.valueOf() && date.valueOf() <= latestDate.date.valueOf()) {
                      return 'in-range';
                    }
                }

                if (isOlderDays(date)) {
                    return 'disabled';
                }
            }
        }).on('changeDate', function (ev) {
            if (ev.date.valueOf() > latestDate.date.valueOf()) {
                var newDate = new Date(ev.date)
                newDate.setDate(newDate.getDate() + 1);
                latestDate.setValue(newDate);
            }

            latestDate.update();
            earlyDate.hide();
            $('#offer-latest-date')[0].focus();
        }).data('datepicker');

        var latestDate = $('#offer-latest-date').datepicker({
            format: 'yyyy-mm-dd',
            onRender: function (date) {
                if (earlyDate && earlyDate.date && latestDate && latestDate.date) {
                    if (date.valueOf() >= earlyDate.date.valueOf() && date.valueOf() < latestDate.date.valueOf()) {
                        return 'in-range';
                    }
                }

                if (isOlderDays(date)) {
                    return 'disabled';
                }

                if (date.valueOf() <= earlyDate.date.valueOf()) {
                    return 'disabled';
                }
            }
        }).on('changeDate', function (ev) {
            latestDate.hide();
            earlyDate.update();
        }).data('datepicker');
    }

    function addFindWorkshopBySearchEvents()
    {
        addSearchClickEvent();
        addFindWorkshopBySearch();
    }

    function addSearchClickEvent()
    {
        var searchButton = $('.find-garage-search .ax-button-primary');
        $(searchButton).on('click', function (e) {
            e.preventDefault();
            findWorkshopByMaps();               
        });
    }

    function addFindWorkshopBySearch()
    {
        var allWorkshopButtons = '.select-workshop-bytext .garage-button';
        $(allWorkshopButtons).click(function () {

            $(allWorkshopButtons).removeClass('selected');
            $(this).addClass('selected');

            var wsName = $(this).attr('data-name');
            var wsId = $(this).attr('data-id');
            selectWorkshop(wsId, wsName);
            $.publish("/select-workshop/", [wsId, wsName]); 
            $('input[name="WorkshopId"]').val(summary.workshop.id);

            $('#offer-select-services-row label').unbind();
            $('#offer-select-services-row label').click(function () {  
                var timer;
                clearTimeout(timer);
                timer = setTimeout(function () {
                    $.publish('/services-modified/');
                }, 250);
            });

        });
    }

    function getSearchTerm()
    {
        var query = $('.find-garage-search input').val();
        var q = new String(query);
        return q.trim().toLocaleLowerCase();
    }

    function MarkerDistance(distance, marker) {
        this.distance = distance;
        this.marker = marker;
    }

    function findWorkshopByMaps() {
        clearPreviousHitsInfo();
        q = getSearchTerm();

        if (q.length == 0)
        {
            $('#no-workshops-hits').show();
            return;
        }

        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': q + ', sweden' }, function (results, status) {

            if (status == google.maps.GeocoderStatus.OK) {
                var hits = getMarkerDistancesNearestFirst(results);
                var listHolder = $('.find-garage-list .list-holder');
                for (var i = 0; i < 25; i++) {
                    var clonedItem = $('#ws-' + hits[i].marker.id).clone(true, true);
                    clonedItem.removeAttr('id');
                    clonedItem.addClass('map-hit');
                    clonedItem.attr('data-d', hits[i].distance);
                    listHolder.append(clonedItem);
                }
                $('.find-garage-list').show();
                $('.find-garage-list .list-holder .map-hit').show();
            }
            else
                $('#no-workshops-hits').show();
        }); 
    }

    function clearPreviousHitsInfo() {
        $('#no-workshops-hits').hide();
        $('.find-garage-list .list-holder .map-hit').remove();
    }

    function getMarkerDistancesNearestFirst(mapResult)
    {
        var hits = [];
        for (var i = 0; i < m_markers.length; i++) {
            var hit = google.maps.geometry.spherical.computeDistanceBetween(mapResult[0].geometry.location, m_markers[i].position);
            hits.push(new MarkerDistance(hit, m_markers[i]));
        }
        hits.sort(function (a, b) {
            return a.distance - b.distance;
        });
        return hits;
    }

    this.init = function (workshopId, serviceIds, registrationNumber, splitter, useMapToFindWorkshops) {
        preselected.workshopId = workshopId;
        preselected.serviceIds = serviceIds;
        preselected.splitter = splitter;

        if (registrationNumber) {
            $regNumberInput.val(registrationNumber);
        }

        limitDatePickers(workshopId);
        initPubSub();
        handlePreselections();

        if (useMapToFindWorkshops)
            addAffix();

        addEvents();

        if (useMapToFindWorkshops == false) {
            addFindWorkshopBySearchEvents();
            initMarkers();
        }
    }

    this.addWorkshopExternal = function (id, title) {
        selectWorkshop(id, title);
        updateSummary();
    }

    function initMarkers()
    {
        $(m_allWorkshopButtons).each(function () {
            var wsId = $(this).attr('data-id');
            var wsLat = parseFloat($(this).attr('data-lat'));
            var wsLgn = parseFloat($(this).attr('data-lng'));

            if (wsLat > 0 && wsLgn > 0) {
                var location = new google.maps.LatLng(wsLat, wsLgn);
                var marker = new google.maps.Marker({
                    position: location,
                    id: wsId
                });
                m_markers.push(marker);
            }
        });
    }
}
;
var Product = function () {
    var self = this;

    var $shoppingCart,
        $sliderHolder,
        $largeImage,
        sliderIsActive,
        $reviewPaginationContainer,
        $currentPage = 1,
        player,
        positionsAreChanged = false;
        thumbNailsCount = 0;

    self.init = function (shoppingCart) {
        $shoppingCart = shoppingCart;
        setVars();
        modifyDom();
        addEvents();
        eventHandlers.showHashTab();
    }

    function setVars() {
        $sliderHolder = $('#single-product-holder #mobile-product-slider');
        $largeImage = $('#single-product-holder .large-image img');
        $reviewPaginationContainer = $('.ax-reviews-holder .pager');
    }

    function modifyDom() {
        helpers.alignProductFlags();
        let mobilepreview = $('#mobilepreview');
        thumbNailsCount = $('.image-thumbnails img').length;
        if (thumbNailsCount > 0) {
            mobilepreview.remove();
            helpers.addMobileSlides();
            eventHandlers.toggleSlider();
        } else {
            mobilepreview.attr('src', $largeImage.attr('src'));
        }
        if (window.LOAD_LOWEST_PRICE_PART_NO != undefined) {
            $.ajax({
                method: 'GET',
                url: '/api/products/producthistorylowestprice/' + window.LOAD_LOWEST_PRICE_PART_NO,
                type: 'json',
                success: function (price) {
                    var el = document.getElementById('price-history-val');
                    el.innerText = price;
                    el.parentElement.setAttribute('style', '');                    
                }
            });
        }
    }

    function addEvents() {
        $('.product-info a.more').on('click', eventHandlers.readMore);
        $(window).on('resize', eventHandlers.toggleSlider);
        $('.image-thumbnails img').on('click', eventHandlers.toggleLargeImage);

        $('.product-extra-information .nav.nav-tabs li a').on('click', function (e) {
            e.preventDefault();
            window.location.hash = $(this).attr('href').replace('-tab', '');
        });

        window.onhashchange = function () {
            eventHandlers.showHashTab();
        };

        $('.carousel-control').on('click', function (e) {
            if (player) {
                player.stopVideo();
            }
        });
        $('.modal-close').on('click', function (e) {
            if (player) {
                player.stopVideo();
            }
        });

        $(document).on('click', 'a[data-target="#image-slider-modal"]', function (e) {
            var index = $(this).data('index');
            $('#image-slider-modal .carousel').carousel(index);
            $('#image-slider-modal .carousel').carousel('pause');
        });

        $(document).on('click', '.ax-reviews-holder .pager a', function () {

            event.preventDefault();
            var href = $(this).attr('href');
            $currentPage = href.split('?page=')[1];

            $('html, body').animate({
                scrollTop: $(".ax-reviews-holder").offset().top - 100
            }, 100);

            var productId = $("button.review-button").data("id");

            $.ajax({
                method: 'GET',
                url: '/api/review/list?productId=' + productId + '&pageSize=10&page=' + $currentPage,
                type: 'json',
                success: function (html) {
                    $(".ax-reviews-holder").html(html);

                },
                error: function (xhr, textStatus, error) {
                }
            });

            return false;
        });



        $('img[data-video-id]').on('click', function (e) {
            e.preventDefault();
            var videoId = $(this).data('video-id');
            $(this).parent().html("<div id='product-video-player'></div>");

            player = new YT.Player('product-video-player', {
                height: '390',
                width: '640',
                videoId: videoId,
                events: {
                    'onReady': onPlayerReady
                }
            });

            function onPlayerReady(event) {
                event.target.playVideo();
            }


        });

        $('.product-price-description .web-buy-button').on('click', function () {
            var btn = $(this);
            var id = btn.data('id');
            var row = btn.closest('.row');
            var q = $('select.quantity-input', row).val();

            if (q === 'more') {
                q = $('input.quantity-input', row).val();
            } else if (!q) {
                $('.product-quantity', row).css('border', '2px solid red');
                return;
            }

            var icon = btn.find('.buy-icon-holder i');
            $shoppingCart.eventHandlers.startIconAnimation(icon);
            $shoppingCart.eventHandlers.add(id, q).then(function () {
                $shoppingCart.eventHandlers.onItemSuccesfullyAdded(icon, btn);
            }, function (xhr, err) {
                $shoppingCart.eventHandlers.onItemErrorAdding(xhr, err, icon, btn);
            });

            //$('.product-quantity', row).css('border', 'none');

            //$('.ax-nav-tabs a[href=#accessories]').tab('show');
        });

        // Stock modal
        $('.store-buy-button').on('click', function () {
            var btn = $(this);
            var id = btn.data('id');
            var row = btn.closest('.row');
            var q = $('select.quantity-input', row).val();

            if (q === 'more') {
                q = $('input.quantity-input', row).val();
            } else if (!q) {
                $('.product-quantity', row).css('border', '2px solid red');
                return;
            }
            $('.product-quantity', row).css('border', 'none');
            eventHandlers.openStockModal(id, q);
        });

        $('.product-price-description .quantity-holder select').on('change', function () {
            helpers.toggleQuantityInput($(this));
        });

        $('#toggle-more-accessories').on('click', eventHandlers.toggleAccesories);

        $('.product-promotion-box').on('click', eventHandlers.scrollToPromotions);
    }

    var eventHandlers = {

        scrollToPromotions: function () {
            var promotions = $('.product-promotion').removeClass('animated pulse');
            $('html, body').animate({
                scrollTop: promotions.first().offset().top - 100
            }, 400, function () {
                setTimeout(function () {
                    promotions.addClass('animated pulse');
                }, 100);

            });
        },
        toggleLargeImage: function () {
            if ($(this).data('isModal')) {
                $largeImage.attr('src', $(this).data('imageurl'));
            }
        },
        toggleAccesories: function () {
            $(this).parent().find('.hidden').removeClass('hidden');
            $('.product-info .read-more').trigger('click');
            $(this).hide();
        },
        toggleSlider: function () {

            if (sliderIsActive || !$sliderHolder.length || thumbNailsCount < 2) return;

            $('#slides-holder').slidesjs({
                pagination: {
                    active: true
                },
                navigation: {
                    active: false
                },
                callback: {
                    loaded: eventHandlers.loadImageForSlider,
                    start: eventHandlers.loadImageForSlider
                },
                play: {
                    active: false,
                    auto: false
                }
            });
            sliderIsActive = false;
        },
        loadImageForSlider: function (slideNr) {
            if ($('.slider-image-holder').length === 1) {
                $('.slider-image-holder').css('left', 0);
                $('.slidesjs-pagination').hide();
                return;
            }
            var currentSlide = $('.slider-image-holder:nth-child(' + (slideNr + 1) + ')', $sliderHolder);
            if (!$('img', currentSlide).length) {
                var urlAttribute = currentSlide.data('imageurl');
                    if (urlAttribute != null) {
                        console.log(urlAttribute);
                        currentSlide.append($('<div class="slider-relative-holder"><img data-toggle="modal" data-target="#image-slider-modal" src="' + urlAttribute + '" width="195" height="177" /></div>'));
                    }       
            }

        },
        readMore: function (e) {
            $(this).siblings('.text-fade').removeClass('text-fade');
            $(this).parent().siblings('.text-fade').removeClass('text-fade');
            $(this).hide();
            return false;
        },
        openStockModal: function (pid, q) {
            event.preventDefault();
            var $stockModal = $('#stock-modal');
            $stockModal.modal('show');
            $('.modal-content', $stockModal).html('');

            $.getJSON('/api/modals/stock/' + pid + '/' + q, function (html) {
                $('.modal-content', $stockModal).html(html);
            });
        },
        showHashTab: function () {
            if (location.hash) {
                var tab = $('a[href=' + location.hash + '-tab' + ']');
                if (tab.length) {
                    tab.tab('show');
                    document.activeElement.blur();
                }
            }
        }
    }

    var helpers = {
        addMobileSlides: function () {
            $('.image-thumbnails img').each(function () {
                if ($(this).hasClass('play-button') == false) {
                    var fullsizeImageUrl = $(this).data('imageurl');
                    $('#slides-holder', $sliderHolder).append($('<div class="slider-image-holder" data-imageurl="' + fullsizeImageUrl + '"></div>'));
                }       
            });

            var firstImage = $('.slider-image-holder', $sliderHolder).first();
            firstImage.append($('<div class="slider-relative-holder"><img data-toggle="modal" data-target="#image-slider-modal" src="' + firstImage.data('imageurl') + '" width="195" height="177" /></div>'));
            $('#mobile-product-slider').parent().append($('single-product-holder .product-flag').clone().addClass('visible-xs'));

        },
        alignProductFlags: function () {
            var top = 10;
            $('single-product-image-holder .product-flag').each(function () {
                $(this).css('top', top);
                top += 40;
            });

        },
        toggleQuantityInput: function (select) {
            if (select.val() === 'more') {
                select
                    .hide()
                    .siblings('input')
                    .show()
                    .focus();
            }
        }
    }
};;
(function($) {
    var $currentPageIndex,
        $listHolder,
        $filters,
        $currentFilters = [],
        $moreBtn,
        $shoppingListWidget;

    function initProject() {
        setVars();
        modifyDom();
        addEvents();
    }

    function setVars() {
        $currentPageIndex = 1;
        $listHolder = $('.projects-posts-holder');
        $moreBtn = $('.load-more-projects');
        $filters = $('#projects-filter .filter-button');
        $shoppingListWidget = $('.shopping-list-widget');
    }

    function modifyDom() {

    }

    function addEvents() {
        $moreBtn.on('click', eventHandlers.loadMore);
        $filters.on('click', eventHandlers.filter);
        $('.shopping-list-widget a.ax-button').on('click', eventHandlers.addItemsToCart);
    }

    var eventHandlers = {
        loadMore: function(e) {
            var url = "/api/pagelist/" + $parentId + "/" + $pageSize + "/" + ($currentFilters.length > 0 ? $currentFilters.join(",") : "") + "/" + $currentPageIndex;
            helpers.reload(url);
        },
        filter: function(e) {
            var filterId = $(this).data('filter-id');
            helpers.updateArray($currentFilters, filterId);

            $currentPageIndex = 0;
           
            var url = "/api/pagelist/" + $parentId + "/" + $pageSize + "/" + ($currentFilters.length > 0 ? $currentFilters.join(",") : "") + "/" + $currentPageIndex;
            helpers.reload(url, true);
        },
        addItemsToCart: function (e) {
            var added = 0;
            $('.single-product.buyable', $shoppingListWidget).each(function (i, product) {
                
                if (!$(this).disabled) {
                    var cb = $('.custom-checkbox input:checkbox', product);
                    if (cb.is(':checked')) {
                        var q = $('select.quantity-input', product).val();

                        if (q === 'more') {
                            q = $('input.quantity-input', product).val();
                        }
                        $shoppingCart.eventHandlers.add($(product).data('id'), q);
                        added++;
                    }
                }
            });
            if (added > 0) {
                $(this).html('<span class="ax-sprite ax-cart buy-button"></span>TILLAGDA I VARUKORGEN');
            }
        }
    };

    var helpers = {
        buildItem: function(data) {

            if (data.mainBody.length > 80)
                data.mainBody = data.mainBody.substring(0, 80) + '...';

            var html =
                        "<div class='col-sm-4 col-xs-6  col-mob-12 single-project'>" +
                            "<a href='" + data.url + "' title='" + data.heading + "'>" +
                                "<div class='project-image-holder'>" +
                                    "<img src='" + data.imageUrl + "?mode=crop&width=230&height=118' alt='" + data.heading + "' />" +
                                    "<div class='text-holder'>" +
                                        (data.categories ? "<p class='pull-left'><b>" + data.categories[0] + "</b></p>" : "") +
                                     "</div>" +
                                 "</div>" +
                                 "<div class='project-text-holder'>" +
                                    "<p class='project-title'>" + data.heading + "</p>" +
                                    "<p>" + data.mainBody + "</p>" +
                                    "<a href='" + data.url + "' title='" + data.heading + "'>" + $btnText + "</a>" +
                                 "</div>" +
                             "</a>" +
                        "</div>";

            return html;
        },
        updateArray : function(array, val) {
            var index = -1;
            $.each(array, function (i, obj) {
                if (obj === val) {
                    index = i;
                    return false;
                }
            });

            if (index > -1) {
                array.splice(index, 1);
            } else {
                array.push(val);
            }
        },
        reload : function(url, empty) {
            $.getJSON(url, function (data) {
                if (empty) {
                    $listHolder.html('');
                }
                $.each(data.list, function (i, val) {
                    $listHolder.append(helpers.buildItem(val));
                });

                if (!data.hasMore) {
                    $moreBtn.hide();
                } else {
                    $moreBtn.show();
                }

                $currentPageIndex++;
            });
        }
    };

    $(document).ready(function() {
        initProject();
    });

})(jQuery);;
(function($) {

    var base_url = '/api/vehicle/manufacturers/';

    var init, modal, models, modeltypes, btn;

    var state = {
        brand: '',
        model: '',
        modeltype: ''
    };

    var values = {
        type: '',
        brand: '',
        model: ''
    }

    function setupChooseCarModal() {
        modal = $('#choose-car-modal');
        btn = $('#choose-car-modal #select-btn');
        var selects = $('select', modal);
        selects.first().chosen({ disable_search_threshold: 5 });
        

        selects.on('change', function() {
            selectChanged($(this));
        });

        btn.on('click', function() {
            setSelectedCar();
        });

        if (!init) {
            selectChanged($('#choose-vehicle-type'));
            init = true;
        }
    }

    function selectChanged(select) {
        var type = select.data('url-type');
        var url = '';

        var value = select.val();
        values[type] = value;

        if (type === 'modeltype') {
            state.modeltype = findWhere(modeltypes, 'tecDocNumber', select.val());
            return;
        }

        switch (type) {
            case 'type':
                url = base_url + value;
                break;

            case 'brand':
                state.brand = $('option:selected', select).text();
                url = base_url + values.type + '/' + value;
                break;

            case 'model':
                state.model = findWhere(models, 'id', parseInt(select.val(), 10));
                url = base_url + values.type + '/' + values.brand + '/' + value;
                break;
        }

        getSelectOptionData(select, url, type);
    }

    function getSelectOptionData(elem, ajax_url, type) {
        var _this = elem;
        $.ajax({
            method: 'GET',
            url: ajax_url,
            type: 'json',
            success: function(data) {
                if (!data) return;

                if (!Array.isArray(data)) {
                    try {
                        data = JSON.parse(data);
                    } catch (e) {
                        //console.log(e);
                    }
                }

                var next = _this.closest('div.col-md-12').next();
                populateChooseCarModalSelect(next, data, type);
            },
            error: function(xhr, textStatus, error) {
                var e = $('error');
                e.html(error, modal);
            }
        });
    }

    function populateChooseCarModalSelect(next, data, type) {
        var length = data.length;
        var select = next.find('select');
        select.empty();
        switch (type) {
            case 'type':
                select.append($('<option value=""></option>'));
                for (var i = 0; i < length; i++) {
                    var item = data[i];
                    select.append( $('<option value="' + item.id + '">' + item.name + '</option>'));
                }
                break;
            case 'brand':
                models = data;
                select.append($('<option value=""></option>'));
                for (var i = 0; i < length; i++) {
                    var item = data[i];
                    var name = item.name + (item.bodyName ? ', ' + item.bodyName : '' ) + ', ' + item.manufacturedFrom;
                    if (item.manufacturedUntil)
                        name += ' - ' + item.manufacturedUntil;

                    select.append($('<option value="' + item.id + '">' + name + '</option>'));
                }
                break;

            case 'model':
                modeltypes = data;
                select.append($('<option value=""></option>'));
                for (var i = 0; i < length; i++) {
                    var item = data[i];
                    select.append($('<option value="' + item.tecDocNumber + '">' + item.name + (item.bodyName ? ', ' + item.bodyName : '') + '</option>'));
                }
                break;
        }

        resetSelect(next.next());
        next.removeClass('inactive');
        select.prop('disabled', false);
        select.chosen();
        select.trigger("chosen:updated");
        //select.trigger('change');
    }

    function resetSelect(next) {
        if ($(next).hasClass('no-disable'))
            return;

        var select = next.find('select');
        select.prop('disabled', true);
        select.empty();
        select.chosen();
        select.trigger("chosen:updated");

        next.addClass('inactive');
        if (!$(next).is(':last-child'))
            resetSelect(next.next());
    }

    function setSelectedCar() {
        $.ajax({
            method: 'POST',
            url: '/api/vehicle/set',
            data: { tecDocType: state.modeltype.tecDocType, tecDocNo: state.modeltype.tecDocNumber },
            type: 'json',
            success: function (data) {
                var destination = $('#choose-car-modal').data('destination');
                location.href = destination;
            },
            error: function (xhr, textStatus, error) {
                var e = $('error');
                e.html(error, modal);
            }
        });
    }

    $(document).on('ready', function() {
        $('#choose-car-modal').on('show.bs.modal', setupChooseCarModal);

        if (document.location.href == document.referrer && jQuery('.new-vehicle-select-block .green-car-info').length) {
            $([document.documentElement, document.body]).animate({
                scrollTop: $('.new-vehicle-select-block').offset().top - 150
            }, 1000);
        }
    });

    function findWhere(collection, key, val) {
        var length = collection.length;
        for (var i = 0; i < length; i++) {
            if (collection[i][key] === val) {
                return collection[i];
            }
        }

        return false;
    }
})(jQuery);;
var Vehicle = function () {
    var self = this;

    var $block,
        $message,
        $input,
        $btn,
        $redirectUrl;

    self.init = function (id, redirectUrl) {
        $block = $('#' + id);
        $message = $('#' + id + ' .message');
        $input = $('#' + id + ' input');
        $btn = $('#' + id + ' button');
        $redirectUrl = redirectUrl;

        $('.table-summary-widget .set-regno').on('click', function (e) {
            e.preventDefault();
            eventHandlers.setRegno($(this).data('regno'));
        });

        $btn.on('click', function (e) {
            eventHandlers.setRegno($input.val().replace(/ /g, ''));
        });

        $('#clear-vehicle').on('click', eventHandlers.clearVehicle);
        $('.close-div').on('click', eventHandlers.clearVehicle);

        $input.keypress(function(e) {
            if (e.which == 13) {
                eventHandlers.setRegno($input.val().replace(/ /g, ''));
            }
        });

        $('.selected-car-info #clear-vehicle').on('click', eventHandlers.clearVehicle);
        $('.selected-car-info #change-vehicle').on('click', function() {
            $('.selected-car-info').hide();
            $('.select-car').show();
        });
        $('.selected-car-info #offer').on('click', function () {
            location.href = $(this).attr('href');
        });
    }

    var eventHandlers = {
        setRegno: function (regno) {
            $input.popover('destroy');
            $('button i', $block).toggleClass('hidden');
            $('button span', $block).toggleClass('hidden');
            $.ajax({
                method: 'POST',
                url: '/api/vehicle/set',
                data: { regNo: regno },
                type: 'json',
                success: function (vehicle) {
                    if (vehicle && (vehicle.tecDocNumber || vehicle.tecDocType === "TRAILER")) {
                        if ($redirectUrl) {
                            location.reload();
                        } else {
                            location.reload();
                        }
                    } else {
                        $('button i', $block).toggleClass('hidden');
                        $('button span', $block).toggleClass('hidden');
                        $('.choose-car-modal-holder #sub-header span').html('Vi kunde inte identifiera ditt fordon. Var god välj märke, modell och typ manuellt.');
                        //$('.choose-car-modal-holder #sub-header span').html('Vi har identifierat tillverkaren av ditt fordon. Var god välj modell och typ manuellt.');
                        $('.choose-car-modal-holder #sub-header').show();
                        $('#choose-car').click();
                    }
                },
                error: function (xhr, textStatus, error) {
                    $('button i', $block).toggleClass('hidden');
                    $('button span', $block).toggleClass('hidden');
                    $input.css('border', '2px solid red');
                    $input.data('content', error);
                    $input.popover();
                    $input.popover('show');
                }
            });
        },
        clearVehicle: function(e) {
            $.ajax({
                method: 'POST',
                url: '/api/vehicle/clear',
                data: '',
                type: 'json',
                success: function (resp) {
                    location.reload();
                },
                error: function (xhr, textStatus, error) {
                    
                }
            });
        }
    };
};;
var NewsLetter = function () {
    var self = this;

    var $successMessage,
        $subHeader,
        $input,
        $btn,
        $modal;

    self.init = function (id, succesMessage, subHeader) {
        $successMessage = succesMessage;
        $subHeader = subHeader;
        $input = $('#' + id + ' input');
        $btn = $('#' + id + ' button');
        $modal = $('#generic-modal');
        $btn.on('click', eventHandlers.subscribe);
        $input.keypress(function (e) {
            if (e.which == 13) {
                eventHandlers.subscribe();
            }
        });
    }

    var eventHandlers = {
        subscribe: function (e) {
            var email = $input.val().trim();
            if (email) {
                $('.sub-header', $modal).html('');
                $.ajax({
                    type: "POST",
                    url: "/api/customer/subscribe",
                    data:'=' + email,
                    success: function(resp) {
                        $input.val('');

                        $('#generic-modal-header', $modal).html('NYHETSBREV');
                        $('.sub-header', $modal).html($subHeader);
                        $('.body', $modal).html($successMessage);
                        $modal.modal('show');
                    },
                    error: function(xhr, textStatus, error) {
                        $('#generic-modal-header', $modal).html('NYHETSBREV');
                        $('.sub-header', $modal).html('Fel');
                        $('.body', $modal).html(error);
                        $modal.modal('show');
                    }
                });
            }
        }
    };
};;
var ShoppingCart = function () {
    var self = this;

    var $isMobile,
        $cartContainer,
        $cartHolder,
        animationDuration = 150,
        successButtonTimeout = 1000;

    self.init = function() {
        setVars();
        addEvents();
    }

    var setVars = function () {
        $cartHolder = $('#cart-dropdown');
        $cartContainer = $('.shopping-cart #cart-dropdown');
        var width = $(window).width();
        if (isTablet) {
            viewModel = width > 768 ? 'ShoppingCartBlock' : 'MobileShoppingCartBlock';
            $cartContainer = width > 768 ? $('.shopping-cart #cart-dropdown') : $('.mobile-cart-products-holder-2');
            $cartHolder = width > 768 ? $('#cart-dropdown') : $('#ax-mobile-cart-holder');
        } else {
            if (!$cartHolder.length) {
                $isMobile = true;
                $cartContainer = $('.mobile-cart-products-holder-2');
                $cartHolder = $('#ax-mobile-cart-holder');
            } else {
                $isMobile = false;
                $cartContainer = $('.shopping-cart #cart-dropdown');
            }
        }
        
    }

    var addEvents = function () {

        $('.ax-buy-button.web-buy').unbind("click");
        $('.ax-buy-button.web-buy').on('click', function () {

            var btn = $(this);
            var icon = btn.find('.buy-icon-holder i');
            self.eventHandlers.startIconAnimation(icon);
            self.eventHandlers.add(btn.data('id'), btn.data('quantity')).then(function () {
                self.eventHandlers.onItemSuccesfullyAdded(icon, btn);
            }, function (xhr, err) {
                self.eventHandlers.onItemErrorAdding(xhr, err, icon, btn);
            });
        });

        $('.quantity-holder select', $cartHolder).unbind("change");
        $('.quantity-holder select', $cartHolder).on('change', function() {
            var select = $(this);

            if (!(select.val() === 'more')) {
                var id = $(this).closest('.cart-single-product').data('id');
                self.eventHandlers.update(id, select.val());
            } else {
                helpers.toggleQuantityInput(select);
            }
        });

        $('.quantity-holder input', $cartHolder).unbind("change");
        $('.quantity-holder input', $cartHolder).on('change', function () {
            var input = $(this);
            var id = $(this).closest('.cart-single-product').data('id');
            self.eventHandlers.update(id, input.val());
        });

        $('.cart-product-remove').unbind("click");
        $('.cart-product-remove', $cartHolder).on('click', function () {
            var elem = $(this).closest('.cart-single-product');
            var id = elem.data('id');
            $(this).find('i').removeClass('fa-trash-alt').addClass('fa-spinner fa-spin');
            self.eventHandlers.remove(id, $(this).data('unique-name'), $(this).data('quantity'));
        });

        $.each($('.quantity-holder select'), function(i, select) {
            helpers.toggleQuantityInput($(select));
        });

        $('.share-shopping-cart-button').on('click', self.eventHandlers.toggleShareButton);

        if (isTablet) {
            // Listen for orientation changes
            window.addEventListener('orientationchange', self.eventHandlers.handleOrientiationChange);
        }
    }

    self.eventHandlers = {
        add: function (id, quantity) {
            var cartItem =
            {
                id: id,
                quantity: quantity ? quantity : 1
            };

            return helpers.send(cartItem, 'add');
        },
        update: function(id, quantity) {
            var cartItem =
            {
                id: id,
                quantity: quantity
            };

            helpers.send(cartItem, 'update');
        },
        remove: function(id, uniqueName, quantity) {
            var cartItem =
            {
                id: id,
                quantity: quantity,
                uniqueName: uniqueName
            };

            helpers.send(cartItem, 'remove');
        },
        toggleShareButton: function () {
            $('.share-shopping-cart-button').addClass('disabled');
            $('.share-shopping-cart-button i').removeClass('fa-share-square').addClass('fa-spinner fa-spin');
            $.ajax({
                method: 'POST',
                url: '/api/shoppingcart/url',
                type: 'json',
                success: function (url) {
                    $('.share-shopping-cart-button').hide();
                    $('.cart-share').addClass('shared');
                    var input = $('.share-shopping-cart-input');
                    input.val(url);
                    input.get(0).setSelectionRange(0, 9999);
                    input.show();
                    input.click(function () {
                        input.select();
                        document.execCommand('copy');
                        input.get(0).setSelectionRange(0, 9999);
                    });
                },
                error: function (xhr, textStatus, error) {
                    //console.log(error);
                }
            });
        },

        // The following methods handles the animation of icons
        startIconAnimation: function (icon) {
            icon.addClass('left');
            setTimeout(function () {
                icon.addClass('fa fa-spinner fa-spin').removeClass('icon-axcart left');
            }, animationDuration);
        },

        onItemSuccesfullyAdded: function (icon, btn) {
            btn = btn.find('.ax-button-right').length ? btn.find('.ax-button-right') : btn;
            icon.addClass('left');
            setTimeout(function () {
                icon.removeClass('fa fa-spinner fa-spin left').addClass('fa fa-check');
            }, animationDuration);
            btn.addClass('ax-button-green');
            var cart = $('#toggle-cart').addClass('green');
            setTimeout(function () {
                icon.addClass('left');
                setTimeout(function () {
                    icon.addClass('icon-axcart').removeClass('fa-check left');
                }, animationDuration);
                btn.removeClass('ax-button-green');
                cart.removeClass('green');
            }, successButtonTimeout);
        },

        onItemErrorAdding: function (xhr, error, icon, btn) {
            icon.addClass('left');
            setTimeout(function () {
                icon.removeClass('fa fa-spinner fa-spin left').addClass('fa fa-times-circle-o');
            }, animationDuration);
            btn.addClass('ax-button-red');
            setTimeout(function () {
                icon.addClass('left');
                setTimeout(function () {
                    icon.addClass('icon-axcart').removeClass('fa-times-circle-o left');
                }, animationDuration);
                btn.removeClass('ax-button-red');
            }, successButtonTimeout);
        },

        handleOrientiationChange: function () {
            var viewModel;
            var width = $(window).width();
            viewModel = width > 768 ? 'ShoppingCartBlock' : 'MobileShoppingCartBlock';
            $cartContainer = width > 768 ? $('.shopping-cart') : $cartContainer = $('.mobile-cart-products-holder');
            $cartHolder = width > 768 ? $('#cart-dropdown') : $('#ax-mobile-cart-holder');

            helpers.refresh(viewModel);

        }
    };

    var helpers = {
        send: function (cartItem, action) {
            var viewModel;
            var width = $(window).width();
            if (isTablet) {
                viewModel = width > 768 ? 'ShoppingCartBlock' : 'MobileShoppingCartBlock';
                $cartContainer = width > 768 ? $('.shopping-cart #cart-dropdown') : $('.mobile-cart-products-holder #cart-dropdown');
                $cartHolder = width > 768 ? $('#cart-dropdown') : $('#ax-mobile-cart-holder');
            } else {
                viewModel = $isMobile ? 'MobileShoppingCartBlock' : 'ShoppingCartBlock';
            }

            return $.ajax({
                method: 'POST',
                url: '/api/shoppingcart/' + action,
                data: JSON.stringify({ item: cartItem, viewModel: viewModel }),
                type: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (html) {

                    $cartContainer.html(html);
                    self.init();
                    helpers.updatecount();

                    if (($isMobile && !isTablet) || (isTablet && width <= 768)) {
                        $cartHolder.addClass('show-ax-mobile-cart');
                        $('#ax-mobile-cart-closer').addClass('show-ax-mobile-cart');
                        $('#ax-mobile-cart-holder').addClass('shopping-cart show-ax-mobile-cart');
                        $('body').addClass('no-scroll');
                    }
                    else {
                        $cartHolder.addClass('visible');

                        $cartHolder.one('mouseover', function (e) {
                            $cartHolder.removeClass('visible');
                        });

                        $('.cart-quantity', $cartHolder).click(function(e) {
                            
                            $cartHolder.addClass('visible');

                            $cartHolder.one('mouseover', function (e) {
                                $cartHolder.removeClass('visible');
                            });
                        });
                    }

                    if (isTablet && width > 768) {
                        $(document).one('touchend click', function (e) {
                            if (!$.contains($('#cart-dropdown').get(0), e.target)) {
                                $('#cart-dropdown').removeClass('visible');
                            }
                        });
                    }

                    // Push to GTM
                    var url;
                    if (action === 'add') {
                        url = 'product/' + cartItem.id;
                    } else if (action === 'remove') {
                        url = 'product/named/' + cartItem.uniqueName;
                    } else {
                        return;
                    }

                    doCommonLeadAction(cartItem.id, 'UpdateCart');

                    $.ajax({
                        method: 'GET',
                        url: '/api/products/' + url,
                        type: 'json',
                        success: function (data) {
                            if (typeof data.name === 'undefined')
                                return;

                            var product = {
                                name: data.name,
                                id: data.selectedVariant.partNo,
                                price: data.price.display,
                                category: data.category.id,
                                brand: data.manufacturer.name,
                                variant: '',
                                quantity: String(cartItem.quantity)
                            };

                            helpers.pushToGtm(product, action, data.category.name);
                        },
                        error: function (xhr, textStatus, error) {
                        
                        }
                    });
                },
                error: function (xhr, textStatus, error) {
                    var modal = $('#generic-modal');
                    $('#generic-modal-header', modal).html("VARUKORG");
                    $('.sub-header', modal).html('');
                    $('.body', modal).html(error);
                    modal.modal('show');
                    $('.ajax-loader', modal).hide();
                    if (action === 'add')
                        helpers.refresh(viewModel); // could be adjusted cart.
                }
            });
        },
        refresh: function (viewModel) {
            return $.ajax({
                method: 'POST',
                url: '/api/shoppingcart/refresh',
                data: JSON.stringify({viewModel: viewModel}),
                type: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (html) {
                    helpers.updatecount();
                    $cartContainer.replaceWith($(html));
                    self.init();
                }
            });
        },
        updatecount: function () {
            $.ajax({
                method: 'GET',
                url: '/api/shoppingcart/count',
                type: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (html) {
                    $('.cart-counter').html(html);
                    $('.cart-counter').show();
                },
                error: function (xhr, textStatus, error) {
                    //console.log(error);
                }
            });
        },
        toggleQuantityInput: function(select) {
            if (select.val() === 'more') {
                select
                    .hide()
                    .siblings('input')
                    .show()
                    .focus();
            }
        },
        pushToGtm: function (product, action, listName) {
            var eventName;
            if (action === 'add') {
                eventName = 'addToCart';
            } else if (action === 'remove') {
                eventName = 'removeFromCart';
            } else {
                eventName = 'unknown';
            }

            var ecommerce = {};
            ecommerce[action] = {
                'actionField': { 'list': window.location.pathname + window.location.search },
                'products': [product]
            };

            dataLayer.push({
                'event': eventName,
                'ecommerce': ecommerce
            });
        }
    };
};;
(function($) {

    var counters = [],
        $window,
        $setWorkshopLink,
        $clearWorkshopLink,
        $reviewPaginationContainer,
        $currentPage;


    function initGarage() {
       setVars();
       modifyDom();
       addEvents();
    }

    function setVars() {
        $window =   $(window);

        var options = {
            useEasing : true,
            useGrouping : false,
            separator : ',',
            decimal : '.'
        };
        if ($('#counter-text-1').length > 0) {
            counters.push(new countUp('counter-text-1', 0, $('#counter-text-1').data('count'), 0, 5, options));
        }
        if ($('#counter-text-2').length > 0) {
            counters.push(new countUp('counter-text-2', 0, $('#counter-text-2').data('count'), 0, 5, options));
        }
        if ($('#counter-text-3').length > 0) {
            counters.push(new countUp('counter-text-3', 0, $('#counter-text-3').data('count'), 0, 5, options));
        }
        $setWorkshopLink = $('.make-favorite-garage a.set-workshop');
        $clearWorkshopLink = $('.make-favorite-garage a.clear-workshop');
        $reviewPaginationContainer = $('.ax-reviews-holder .pager');
        $currentPage = 1;
    }

    function modifyDom() {

    }

    function addEvents() {
        if (counters.length > 0) {
            $(window).on('scroll', eventHandlers.checkForCounterStart);
        }
       
        $('.open-offer-modal').on('click', eventHandlers.openOfferModal);
        $setWorkshopLink.on('click', function (event) {
            event.preventDefault();
            eventHandlers.setWorkshop($(this).data('id'));
        });
        $clearWorkshopLink.on('click', function (event) {
            event.preventDefault();
            eventHandlers.clearWorkshop();
        });
    }

    var eventHandlers = {
        checkForCounterStart: function() {
            if( $(window).scrollTop() - 550 >= $('#counter-text-1').position().top ) {
                for(var i = 0; i < counters.length; i++) {
                    counters[i].start();
                }
            }
        },
        setWorkshop: function (workshopId) {
            $('.fa-spin', $setWorkshopLink).show();
            $.ajax({
                method: 'POST',
                url: '/api/workshop/set',
                data: '=' + workshopId,
                type: 'json',
                success: function (resp) {
                    $('.fa-spin', $setWorkshopLink).hide();
                    $setWorkshopLink.hide();
                    $clearWorkshopLink.show();
                },
                error: function (xhr, textStatus, error) {
                   
                }
            });
        },
        clearWorkshop: function () {
            $('.fa-spin', $clearWorkshopLink).show();
            $.ajax({
                method: 'POST',
                url: '/api/workshop/clear',
                type: 'json',
                success: function (resp) {
                    $('.fa-spin', $clearWorkshopLink).hide();
                    $setWorkshopLink.show();
                    $clearWorkshopLink.hide();
                    
                },
                error: function(xhr, textStatus, error) {

                }
            });
        }
    }

    $(document).ready(function() {

        if($('.garage-shop-holder').length)
            initGarage();
    });

})(jQuery);;
var Store = function () {
    var self = this;

    var $storeInput;
    var $stockInput;
    var $storeBtn;
    var $stockBtn;
    var $storeTable;
    var $stockTable;
    var geocoder;
    var stores;
    var storeMap;
    var storeMapId;

    self.setVars = function() {
        $storeInput = $('#ax-store-search-input');
        $stockInput = $('#ax-stock-search-input');
        $storeBtn = $('#ax-store-search');
        $stockBtn = $('#ax-stock-search');
        $storeTable = $('#ax-store-table');
        $stockTable = $('#ax-stock-table');
        $storePosBtn = $('#ax-store-position');
        $stockPosBtn = $('#ax-stock-position');
        stores = [];
        useMapInteractive = false;
        storeMapId = "stock-map";
    }

    self.init = function (storesObj, redirectUrl) {
        $redirectUrl = redirectUrl;
        geocoder = new google.maps.Geocoder();
        self.setVars();

        if (storesObj) {
            useMapInteractive = true
            stores = storesObj;
        }

        $storeBtn.on('click', function (e) {
            self.setVars();
            eventHandlers.search($storeInput.val().trim().toLowerCase(), $storeTable);
        });

        $stockBtn.on('click', function (e) {
            self.setVars();
            eventHandlers.search($stockInput.val().trim().toLowerCase(), $stockTable);
        });

        $storePosBtn.on('click', function (e) {
            self.setVars();
            $storeInput.val('');
            eventHandlers.position($storeTable);
        });

        $stockPosBtn.on('click', function (e) {
            self.setVars();
            $stockInput.val('');
            eventHandlers.position($stockTable);
        });

        $storeInput.keypress(function(e) {
            if (e.which == 13) {
                eventHandlers.search($storeInput.val().trim().toLowerCase(), $storeTable);
            }
        });

        $stockInput.keypress(function (e) {
            if (e.which == 13) {
                eventHandlers.search($stockInput.val().trim().toLowerCase(), $stockTable);
            }
        });

        $('.stock-store-table .set-store').on('click', function (e) {
            e.preventDefault();
            $('i', this).toggleClass('hidden');
            eventHandlers.set($(this).data('id'), $(this).data('name'));
        });

        $('#select-stock-btn').on('click', function (e) {
            e.preventDefault();
            eventHandlers.set($('[name="store-select"]:checked').data('id'), $('[name="store-select"]:checked').data('name'));
            return false;
        });

        $('input[name="store-select"]').on('change', function (e) {
            const id = new Number($(this).data('id'));
            storeMap.triggerStoreMarker(id);
        });

        // Stock map
        storeMap = new AxWsMap();

        if(useMapInteractive)
            eventHandlers.updateMap();

        $('.store-order').on('click', function (e) {
            // Compile the order
            var order = {
                storeId: $(this).data('id'),
                storeName: $(this).data('store-name'),
                productId: $(this).data('product-id'),
                productName: $(this).data('product-name'),
                quantity: {
                    current: parseInt($(this).data('quantity')),
                    fixed: $(this).data('quantity-fixed') === 'True',
                    multiplier: $(this).data('quantity-multiplier')
                },
                price: parseFloat($(this).data('product-price')),
                fullName: null,
                phoneNumber: null,
                email: null
            };

            var stockOrder = new StockOrder();
            stockOrder.init(order);

            // Proceed to step 2
            $('#stock-modal').modal('hide');
            $('#stock-order-modal').modal('show');

            stockOrder.postVisible();
        });

        // trigger selected marker
        if (useMapInteractive) {
            const selected = $('[name="store-select"]:checked');
            if (selected.length)
                storeMap.triggerStoreMarker(new Number(selected.data('id')));
        }

    }

    var eventHandlers = {
        set: function (id, name) {
            var refreshPage = $("#store-modal").data("refreshPage");
   
            $.ajax({
                method: 'POST',
                url: '/api/store/set',
                data: '=' + id,
                type: 'json',
                success: function (resp) {
                    if (refreshPage === false) {
                        $("#store-modal").modal("hide");
                        $(".store-name").html(name);
                        $(".change-store-link").html("Byt butik");
                        $(".change-store-link").closest('.delivery-method').data('selected-store', 'True');
                        $(document).trigger('store/changed');
                        return;
                    }

                    if ($redirectUrl) {
                        location.href = $redirectUrl;
                    } else {
                        location.reload();
                    }
                },
                error: function (xhr, textStatus, error) {
                }
            });
        },
        clear: function (e) {
            var refreshPage = $("#store-modal").data("refreshPage");

            $.ajax({
                method: 'POST',
                url: '/api/store/clear',
                data: '',
                type: 'json',
                success: function (resp) {
                    if (refreshPage === false) {
                        $("#store-modal").modal("hide");
                        $(".store-name").html("");
                        return;
                    }

                    if ($redirectUrl) {
                        location.href = $redirectUrl;
                    } else {
                        location.reload();
                    }
                },
                error: function (xhr, textStatus, error) {
                    
                }
            });
        },
        search : function(q, $target) {
            if (q == '') {
                $('tr', $target).show();
            } else {
                const app = this; 
                geocoder.geocode({ 'address': q + ', sweden' }, function (results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        const location = results[0].geometry.location;
                        if(useMapInteractive)
                            storeMap.centerMap(location);
                        app.updateTable(location, $target);
                    } else {
                        app.noStoresFound($target);
                    }
                    
                });
            }
        },
        position: function ($target) {
            const app = this;     
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    const location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                    app.updateTable(location, $target);
                });
            } else {
                app.noStoresFound($target);
            }
        },
        updateTable: function(location, $target) {
            let storesFound = false;
            $.each($('tbody tr', $target), function (index, row) {
                var storeLong = $(row).data('long');
                var storeLat = $(row).data('lat');
                var storeLocation = new google.maps.LatLng(storeLat, storeLong);
                var resultDistance = google.maps.geometry.spherical.computeDistanceBetween(location, storeLocation);

                if (resultDistance <= 45000) {
                    $(row).show();
                    $(row).attr('data-sort', Math.round(resultDistance));
                    storesFound = true;
                }
                else
                    $(row).hide();
            });

            if (!storesFound) {
                this.noStoresFound($target);
                return;
            }

            var sortedDistanceDesc = $('tbody tr:visible', $target).sort(function (a, b) {
                return new Number(new Number($(b).attr('data-sort') - $(a).attr('data-sort')));
            });

            for (let i = 0; i < sortedDistanceDesc.length; i++) {
                let first = $('tbody tr:first', $target);
                $(sortedDistanceDesc[i]).insertBefore(first);           
            }
            this.storesFound($target);

        },
        updateMap: function () {
            storeMap.initialize_map(storeMapId, stores, 10, null, false);
        },
        noStoresFound: function ($target) {
            $('#no-stores-found').removeClass('hidden');
            $('.ajax-loader').hide();
            $target.hide();
            $('.stock-modal #stock-map').hide();
        },
        storesFound: function ($target) {
            $('#no-stores-found').addClass('hidden');
            $target.show();
            $('.stock-modal #stock-map').show();
        },
    };
};;
var Watch = function() {
    var self = this;

    self.init = function() {
        $('#watch-modal-send-btn').on('click', function (event) {
            event.preventDefault();

            var valid = $('#watch-modal-form').parsley().validate();
            if (!valid) return;

            var pid = $('#watch-modal-pid').val();
            var name = $('#watch-modal-name').val();
            var email = $('#watch-modal-email').val();

            if (pid && name && email) {
                $.ajax({
                    method: 'POST',
                    url: '/api/watch/send',
                    data: { productId: pid, name: name, email: email },
                    type: 'json',
                    success: function(success) {
                        
                        $('#watch-modal-name').val('');
                        $('#watch-modal-email').val('');
                        $('#watch-form').hide();

                        $('.watch-holder #msg').html('<b>Bevakning skickad!</b><br>Du kommer att få ett mail när den finns åter i lager.');
                        $('.watch-holder #msg').show();
                    },
                    error: function (xhr, textStatus, error) {
                        $('.watch-holder #msg').html('<b>Ett fel inträffade.</b><br>Testa igen om en liten stund eller kontakta kundtjänst.');
                        $('.watch-holder #msg').show();
                    }
                });
            }
        });
    }
};;
var Review = function () {
    var self = this;
    var score = 3;

    function updateSelectedScore() {
        for (var index = 0; index < 5; index++) {

            if (index >= score)
                $("#review-modal .product-rating-holder").find(".fa").eq(index).addClass("fa-star-o").removeClass("fa-star");
            else {
                $("#review-modal .product-rating-holder").find(".fa").eq(index).addClass("fa-star").removeClass("fa-star-o");
            }
        }
    }

    self.init = function () {

        score = 3;

        $("#review-modal .product-rating-holder .fa").mouseenter(
            function () {
                $(this).prevAll().andSelf().addClass("fa-star").removeClass("fa-star-o");
                $(this).nextAll().removeClass("fa-star").addClass("fa-star-o");
            }
        );

        $("#review-modal .product-rating-holder").mouseleave(function () {
            updateSelectedScore();
        });

        $("#review-modal .product-rating-holder .fa").click(function() {
            score = $(this).prevAll().andSelf().length;
        });

        $("#review-modal-send-btn").on("click", function (event) {
            event.preventDefault();

            $("#review-modal-send-btn").html('<i class="fa fa-spinner fa-spin"></i>');
            var valid = $("#review-modal-form").parsley().validate();

            if (!valid) {
                $("#review-modal-send-btn").html('Lägg till omdöme');
                return;
            }
            
            var pid = $("#review-modal-pid").val();
            var name = $("#review-modal-name").val();
            var email = $("#review-modal-email").val();
            var text = $("#review-modal-review").val();
            var recaptchaResponse = $("#g-recaptcha-response").val();

            if (pid && name && text) {

                $.ajax({
                    method: "POST",
                    url: "/api/review/send",
                    data: { productId: pid, name: name, text: text, email: email, score: score, recaptchaResponse: recaptchaResponse },
                    type: "json",
                    success: function () {
                        $("#review-modal-send-btn").html('Lägg till omdöme');
                        $("#review-modal-name").val("");
                        $("#review-modal-review").val("");
                        $("#review-modal-email").val("");
                        $("#review-form").hide();
                        $(".review-holder #msg").hide();
                        $(".review-holder #thank-you-msg").show();

                        score = 3;
                        updateSelectedScore();
                        grecaptcha.reset();
                        
                    },
                    error: function (xhr, textStatus, error) {
                        $("#review-modal-send-btn").html('Lägg till omdöme');
                        $(".review-holder #msg").html(error).addClass('red-text');
                        $(".review-holder #msg").show();
                        grecaptcha.reset();
                    }
                });
            }
        });
    }
};;
var Rating = function() {
    var self = this;
    var isLoaded = false;

    self.updateRatings = function() {
        var pids = [];
        $.each($('.product-info-holder, .search-single-product'), function (i, w) {
            pids.push($(w).data('id'));
        });
        if (pids.length > 0) {
            $.ajax({
                method: 'POST',
                url: '/api/productlist/rating',
                data: { "": pids },
                type: 'json',
                success: function (ratings) {
                    
                    $.each(ratings, function (i, s) {
                        var ratingHolder = $('.product-info-holder[data-id=' + s.productId + '] .product-rating-holder, .search-single-product[data-id=' + s.productId + '] .product-rating-holder');
                        if (ratingHolder.length > 0) {

                            ratingHolder.find('.fa').each(function (index, el) {

                                $(el).removeClass("fa-star fa-star-o fa-star-half-o");

                                if (s.score >= index + 1 ) {
                                    $(el).addClass("fa-star");
                                }
                                else if ((index) < s.score && s.score < index + 1)
                                {
                                    $(el).addClass("fa-star-half-o");
                                }
                                else
                                {
                                    $(el).addClass("fa-star-o");
                                }
                            });

                            if (s.score > 0) {
                                ratingHolder.addClass('is-loaded');
                            }
                        }
                    });
                    
                    isLoaded = true;
                },
                error: function (xhr, textStatus, error) {
                }
            });
        }
    }
};;
var Search = function() {
    var self = this;
    var $currentFilter;
    var productPage;
    var loading;

    self.init = function () {

        History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
            loadState();
        });
        setVars();
        loadState();
        addEvents();
        productPage = 1;
        loading = false;
    }

    function setVars() {
        $currentFilter = {};
    }

    function addEvents() {
        $('#filteroptions a').on('click', eventHandlers.updateFilter);
        $('#js-more-products').on('click', eventHandlers.loadMoreProducts);
    }


    function loadState() {
        if (location.href && location.href != '') {

            var frags = location.href.split('&');

            $currentFilter = {
                type: frags.length > 1 ? decodeURIComponent(frags[1].split('=')[1]) : null
            };

            helpers.refreshView();
        }
    }

    var eventHandlers = {
        updateFilter: function(e) {
            e.preventDefault();
            var el = $(e.target);
            $('#filteroptions a').removeClass('active');
            el.addClass('active');
            var type = el.data('type');

            var qs = "query=" + helpers.getQuery();

            if (type)
                qs += '&type=' + type;

            if (is_old_IE) {
                window.location.href = location.origin + '' + location.pathname + '?' + qs;
            } else {
                History.pushState(null, $('title').first().text(), location.href.split('?')[0] + '?' + qs);
            }
        },
        loadMoreProducts: function (e) {
            e.preventDefault();

            if (!loading) {

                var el = $(e.target);
                helpers.startProductLoad(el);

                var productsBefore = helpers.getNoOfProductRows();
                productPage++;

                $.ajax({
                    method: 'GET',
                    url: 'productpage?query=' + helpers.getQuery() + '&page=' + productPage,
                    success: function (data) {
                        $('#js-product-list').append(data);
                        helpers.endProductLoad(el);
                        helpers.doProductOnHandAndLazyLoad();
                        helpers.syncPaging(el, productsBefore);
                    },
                    error: function () {
                        helpers.endProductLoad(el);
                    }
                });
            }

        }
    };

    var helpers = {
        refreshView: function () {

            if ($currentFilter.type) {
                $(".search-result-segment[data-type='" + $currentFilter.type + "']").show();
                $(".search-result-segment:not([data-type='" + $currentFilter.type + "'])").hide();
            } else {
                $(".search-result-segment").show();
            }
        },

        startProductLoad(loadLink) {
            loading = true;
            loadLink.find('i').removeClass('hidden');
        },

        endProductLoad(loadLink) {
            loadLink.find('i').addClass('hidden');
            loading = false;
        },

        getNoOfProductRows() {
            return $('#js-product-list .row').length;
        },

        getQuery() {
            return $('#search-query').text().replace(/"/g, "");
        },

        doProductOnHandAndLazyLoad() {
            var onhand = new OnHand();
            onhand.updateonhand();
            lazyload();
        },

        syncPaging(loadLink, productsBefore) {
            var productsAfter = helpers.getNoOfProductRows();
            $('#js-product-count').text(productsAfter);
            var added = productsAfter - productsBefore;
            if (added < 50) {
                loadLink.addClass('hidden');
            }
        }

    };
};;
(function ($) {
    var $mapInitialized;

    function init() {
        setVars();
        modifyDom();
        addEvents();
    }

    function setVars() {
    }

    function modifyDom() {

    }

    function addEvents() {
        $('.find-garage-filter-toggle-button').on('click', eventHandlers.toggleWorkshopFilterItems);
        $('#toggle-map-link').on('click', eventHandlers.toggleMapVisibility);
        $('.garages-framed .find-garage-search .ax-button-primary').on('click', eventHandlers.makeGarageListVisible);
        $('.garages-framed .find-garage-search input').on('click').on('keypress', function (e) {
            if (e.which == 13) {
                eventHandlers.makeGarageListVisible();
            }
        });
    }

    var eventHandlers = {
        toggleWorkshopFilterItems: function(e) {
            if ($(window).width() > 767) return;
            var filterItems = $('.find-garage-filter-toggle-item');
            var txt = filterItems.is(':visible') ? 'Visa filter' : 'Dölj filter';
            filterItems.slideToggle('100');
            $(this).text(txt);
        },
        toggleMapVisibility: function (e) {
            e.preventDefault();

            var mapContainer = $('.find-garage-map-holder')
            mapContainer.toggleClass('find-garage-map-holder-opened');
            $(e.currentTarget).toggleClass('find-garage-content-button-opened');
        },
        makeGarageListVisible: function (e) {
            setTimeout(function () { $('#find-garage-list').show(); }, 1000);      
        }
    }

    $(document).ready(function () {
        init();
    });

})(jQuery);

function disabledWorkshopClick(wsId)
{
    $('#manual-booking-modal .modal-content').hide();
    $('#manual-booking-modal').modal();
    $('#manual-booking-modal .ajax-loader').show();

    $.ajax({
        method: 'GET',
        url: '/api/workshop/get/' + wsId,
        type: 'json',
        success: function (data) {

            var address = data.address + ', ' + data.zip + ', ' + data.city;
            $('#modal-ws-title').text(data.title);
            $('#modal-ws-emaillink').text(data.email);
            $('#modal-ws-emaillink').attr('href', 'mailto:' + data.email);
            $('#modal-ws-phonelink').text(data.phone);
            $('#modal-ws-phonelink').attr('href', 'tel:' + data.phone);
            $('#modal-ws-address').text(address);
            $('#modal-ws-maplink').attr('href', 'https://maps.google.com?daddr=' + encodeURIComponent(address))

            $('#manual-booking-modal .ajax-loader').hide();
            $('#manual-booking-modal .modal-content').show();

            dataLayer.push({
                'event': 'Popup kontakt',
                'shop': data.title,
                'leadType': 'prisförslag'
            });

        },
        error: function (xhr, textStatus, error) {

        }
    });

    return false;
}

function enabledWorkshopClick(name) {
    dataLayer.push({
        'event': 'Popup kontakt',
        'shop': name,
        'leadType': 'prisförslag'
    });

    var offerApp = document.getElementById('app-offer-v3');
    if (offerApp) {
        offerApp.querySelector('a').click();
        return false;
    }

    return true;
};

window.Parsley
  .addValidator('mobilephone', {
      requirementType: 'string',
      validateString: function (value) {
          try {
              var isValid = window.phoneUtils.isValidNumber(value, 'SE');

              if (!isValid) {
                  return false;
              }

              var type = window.phoneUtils.getNumberType(value, 'SE');

              return type === 'MOBILE';

          } catch (err) {
              return false;
          }
          
      },
      messages: {
          sv: 'Ogiltigt mobilnummer'
      }
  });;
var AxWsServices = function () {
    var self = this;
    self.initializeServiceLists = function () {

        $('.bcl-services').each(function () {
            var axWsService = new AxWsService();
            axWsService.initializeServiceList($(this).parent());
        });

    }
    $('.map-link').on('click', function (e) {
        e.preventDefault();
        $(this).parent().children().toggleClass('hidden');
        g_initMap();
    });
}

var AxWsService = function () {
    var self = this;
    var $servicList;
    var $tabs;
    var $tabPreselected;
    var progressQ;
    var progressInicatorQ;
    var shoreMoreBtnQ;
    var tabsContainerQ;

    var customServiceSortIds = null;
    var pageing = 8;
    var currentpage = 1;
    var selectedClass = ''

    self.initializeServiceList = function (el) {
        const id = el.attr('id')
        $servicList = $(`#${id} .bcl-services .service-list`);
        $tabs = $(`#${id} .bcl-services--menu-tab`);
        $tabPreselected = $(`#${id} .bcl-services--menu-tab.preselected`);
        progressQ = `#${id} .bcl-services--progress`;
        progressInicatorQ = `#${id} .bcl-services--progress .progress-indicator`;
        shoreMoreBtnQ = `#${id} .bcl-services--progress a`;
        tabsContainerQ = `#${id} .bcl-services-container`;

        if (el.data('customsort').toString().length) {
            let sortlist = el.data('customsort').toString().split(',');
            sortlist.reverse();
            customServiceSortIds = sortlist.map(function (str) { return parseInt(str, 10); })
        }

        helpers.appendAllServicesToDOM();
        helpers.addEvents();
        helpers.showServicesForPreselectedOrFirstTab();

    }
    // service.IsStaticPriceAllowed || service.EnabledPriceApi
    var helpers = {

        appendAllServicesToDOM: function () {

            const serviceHTMLArray = helpers.getServicesFiltered().map(x => `
            <div class="col-md-3 col-sm-6 col-xs-6 category ${helpers.getCategoryClasses(x.Categories)} ${helpers.getPriceStatusClass(x)}">
                <div class="service-list--item">
                    <div class='icon-wrapper'>
                        ${helpers.tryGetDiscount(x)}
                        <div class="price-icon"><span>Pris direkt</span></div>
                        <img src="${x.Image}" alt="${x.Name}" title="${x.Name}"/>
                    </div>
                    <header>${x.Name}</header>
                    <div class="list-text hidden-xs">${x.ListDescription}</div>
                    <a href="#" onclick="return openOfferAppOnServicePage('${x.Id}');" class="ax-button list-booking-btn">Boka</a>
                    <a href="${x.Url}" class="list-booking-link">Läs mer om ${x.Name}</a>
                </div>
            </div>`);
            $servicList.append(serviceHTMLArray.join(''))
        },

        getServicesFiltered() {

            let filteredItems = [...window.serviceList];

            if (customServiceSortIds != null) {
                customServiceSortIds.forEach(id => {
                    for (var i = filteredItems.length-1; i >= 0; i--) {
                        if (filteredItems[i].Id === id) {
                            var removedElement = filteredItems.splice(i, 1)[0];
                            filteredItems.splice(0, 0, removedElement);
                            break; 
                        }
                    }
                });
            }

            return filteredItems;
        },

        addEvents: function () {
            $(shoreMoreBtnQ).on('click', eventHandlers.showMoreBtnClick)
            $tabs.on('click', eventHandlers.menuTabClick);
        },

        showServicesForPreselectedOrFirstTab() {
            let $tabItem = $tabPreselected.length ? $tabPreselected : $tabs.first();
            $tabItem.click();

            $servicList.removeClass('hidden');
            if ($tabs.length > 1)
                $(tabsContainerQ).removeClass('hidden');
        },

        getCategoryClasses: function (ids) {
            if (ids == null)
                return helpers.getCategoryClass(0);
            let idClasses = ids.map(x => helpers.getCategoryClass(x));
            idClasses.unshift(helpers.getCategoryClass(0));
            return idClasses.join(' ');
        },

        getCategoryClass: function (id) {
            return `cat-${id}`;
        },

        getPriceStatusClass: function (service) {
            return (service.IsStaticPriceAllowed || service.EnabledPriceApi) ? 'has-price' : '';
        },

        tryGetDiscount: function (service) {
            return (service.DiscountPercent != null) ? `<div class="discount-icon"><span>${service.DiscountCardText}</span></div>` : '';
        },

        updateList: function () {
            $servicList.find('.category').addClass('hidden');

            var itemsInCategory = $servicList.find(`.${selectedClass}`)
            itemsInCategory.slice(0, pageing * currentpage).removeClass('hidden');

            const itemsHiddenCount = $servicList.find(`.${selectedClass}.hidden`).length;
            $(progressQ).addClass('hidden');

            if (itemsHiddenCount > 0) {
                $(progressQ).removeClass('hidden');
                const itemsVisible = itemsInCategory.length - itemsHiddenCount;
                const percentProgress = Math.round((itemsVisible / itemsInCategory.length) * 100);
                $(progressInicatorQ).css('width', `${percentProgress}%`);
                $(progressQ).find('span').text(`Visar ${itemsVisible} av ${itemsInCategory.length} verkstadstjänster`)
            }
        }
    }

    var eventHandlers = {
        menuTabClick: function (e) {
            e.preventDefault();
            $tabs.removeClass('selected');
            $(this).addClass('selected');

            currentpage = 1;
            selectedClass = helpers.getCategoryClass($(this).data('id'));
            helpers.updateList();
        },
        showMoreBtnClick: function (e) {
            e.preventDefault();
            currentpage++;
            helpers.updateList();
        }
    }

};
