/* Minification failed. Returning unminified contents.
(23817,78-79): run-time error JS1100: Expected ',': =
(23817,81-82): run-time error JS1002: Syntax error: ,
(23817,94-95): run-time error JS1100: Expected ',': =
(23839,77-78): run-time error JS1100: Expected ',': =
 */
/*! jQuery UI - v1.10.4 - 2014-03-19
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.position.js, jquery.ui.datepicker.js, jquery.ui.effect.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */

(function(e,t){function i(t,i){var s,a,o,r=t.nodeName.toLowerCase();return"area"===r?(s=t.parentNode,a=s.name,t.href&&a&&"map"===s.nodeName.toLowerCase()?(o=e("img[usemap=#"+a+"]")[0],!!o&&n(o)):!1):(/input|select|textarea|button|object/.test(r)?!t.disabled:"a"===r?t.href||i:i)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var s=0,a=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,n){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),n&&n.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var n,s,a=e(this[0]);a.length&&a[0]!==document;){if(n=a.css("position"),("absolute"===n||"relative"===n||"fixed"===n)&&(s=parseInt(a.css("zIndex"),10),!isNaN(s)&&0!==s))return s;a=a.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++s)})},removeUniqueId:function(){return this.each(function(){a.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,n){return!!e.data(t,n[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),s=isNaN(n);return(s||n>=0)&&i(t,!s)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,n){function s(t,i,n,s){return e.each(a,function(){i-=parseFloat(e.css(t,"padding"+this))||0,n&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var a="Width"===n?["Left","Right"]:["Top","Bottom"],o=n.toLowerCase(),r={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(i){return i===t?r["inner"+n].call(this):this.each(function(){e(this).css(o,s(this,i)+"px")})},e.fn["outer"+n]=function(t,i){return"number"!=typeof t?r["outer"+n].call(this,t):this.each(function(){e(this).css(o,s(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,n){var s,a=e.ui[t].prototype;for(s in n)a.plugins[s]=a.plugins[s]||[],a.plugins[s].push([i,n[s]])},call:function(e,t,i){var n,s=e.plugins[t];if(s&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(n=0;s.length>n;n++)e.options[s[n][0]]&&s[n][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var n=i&&"left"===i?"scrollLeft":"scrollTop",s=!1;return t[n]>0?!0:(t[n]=1,s=t[n]>0,t[n]=0,s)}})})(jQuery);(function(t,e){function i(t,e,i){return[parseFloat(t[0])*(p.test(t[0])?e/100:1),parseFloat(t[1])*(p.test(t[1])?i/100:1)]}function s(e,i){return parseInt(t.css(e,i),10)||0}function n(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}t.ui=t.ui||{};var a,o=Math.max,r=Math.abs,l=Math.round,h=/left|center|right/,c=/top|center|bottom/,u=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,p=/%$/,f=t.fn.position;t.position={scrollbarWidth:function(){if(a!==e)return a;var i,s,n=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=n.children()[0];return t("body").append(n),i=o.offsetWidth,n.css("overflow","scroll"),s=o.offsetWidth,i===s&&(s=n[0].clientWidth),n.remove(),a=i-s},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,a="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:a?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s?i.width():i.outerWidth(),height:s?i.height():i.outerHeight()}}},t.fn.position=function(e){if(!e||!e.of)return f.apply(this,arguments);e=t.extend({},e);var a,p,g,m,v,_,b=t(e.of),y=t.position.getWithinInfo(e.within),k=t.position.getScrollInfo(y),w=(e.collision||"flip").split(" "),D={};return _=n(b),b[0].preventDefault&&(e.at="left top"),p=_.width,g=_.height,m=_.offset,v=t.extend({},m),t.each(["my","at"],function(){var t,i,s=(e[this]||"").split(" ");1===s.length&&(s=h.test(s[0])?s.concat(["center"]):c.test(s[0])?["center"].concat(s):["center","center"]),s[0]=h.test(s[0])?s[0]:"center",s[1]=c.test(s[1])?s[1]:"center",t=u.exec(s[0]),i=u.exec(s[1]),D[this]=[t?t[0]:0,i?i[0]:0],e[this]=[d.exec(s[0])[0],d.exec(s[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===e.at[0]?v.left+=p:"center"===e.at[0]&&(v.left+=p/2),"bottom"===e.at[1]?v.top+=g:"center"===e.at[1]&&(v.top+=g/2),a=i(D.at,p,g),v.left+=a[0],v.top+=a[1],this.each(function(){var n,h,c=t(this),u=c.outerWidth(),d=c.outerHeight(),f=s(this,"marginLeft"),_=s(this,"marginTop"),x=u+f+s(this,"marginRight")+k.width,C=d+_+s(this,"marginBottom")+k.height,M=t.extend({},v),T=i(D.my,c.outerWidth(),c.outerHeight());"right"===e.my[0]?M.left-=u:"center"===e.my[0]&&(M.left-=u/2),"bottom"===e.my[1]?M.top-=d:"center"===e.my[1]&&(M.top-=d/2),M.left+=T[0],M.top+=T[1],t.support.offsetFractions||(M.left=l(M.left),M.top=l(M.top)),n={marginLeft:f,marginTop:_},t.each(["left","top"],function(i,s){t.ui.position[w[i]]&&t.ui.position[w[i]][s](M,{targetWidth:p,targetHeight:g,elemWidth:u,elemHeight:d,collisionPosition:n,collisionWidth:x,collisionHeight:C,offset:[a[0]+T[0],a[1]+T[1]],my:e.my,at:e.at,within:y,elem:c})}),e.using&&(h=function(t){var i=m.left-M.left,s=i+p-u,n=m.top-M.top,a=n+g-d,l={target:{element:b,left:m.left,top:m.top,width:p,height:g},element:{element:c,left:M.left,top:M.top,width:u,height:d},horizontal:0>s?"left":i>0?"right":"center",vertical:0>a?"top":n>0?"bottom":"middle"};u>p&&p>r(i+s)&&(l.horizontal="center"),d>g&&g>r(n+a)&&(l.vertical="middle"),l.important=o(r(i),r(s))>o(r(n),r(a))?"horizontal":"vertical",e.using.call(this,t,l)}),c.offset(t.extend(M,{using:h}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,l=n-r,h=r+e.collisionWidth-a-n;e.collisionWidth>a?l>0&&0>=h?(i=t.left+l+e.collisionWidth-a-n,t.left+=l-i):t.left=h>0&&0>=l?n:l>h?n+a-e.collisionWidth:n:l>0?t.left+=l:h>0?t.left-=h:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,l=n-r,h=r+e.collisionHeight-a-n;e.collisionHeight>a?l>0&&0>=h?(i=t.top+l+e.collisionHeight-a-n,t.top+=l-i):t.top=h>0&&0>=l?n:l>h?n+a-e.collisionHeight:n:l>0?t.top+=l:h>0?t.top-=h:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,a=n.offset.left+n.scrollLeft,o=n.width,l=n.isWindow?n.scrollLeft:n.offset.left,h=t.left-e.collisionPosition.marginLeft,c=h-l,u=h+e.collisionWidth-o-l,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-o-a,(0>i||r(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-l,(s>0||u>r(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,a=n.offset.top+n.scrollTop,o=n.height,l=n.isWindow?n.scrollTop:n.offset.top,h=t.top-e.collisionPosition.marginTop,c=h-l,u=h+e.collisionHeight-o-l,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-o-a,t.top+p+f+g>c&&(0>s||r(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-l,t.top+p+f+g>u&&(i>0||u>r(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}},function(){var e,i,s,n,a,o=document.getElementsByTagName("body")[0],r=document.createElement("div");e=document.createElement(o?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&t.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(a in s)e.style[a]=s[a];e.appendChild(r),i=o||document.documentElement,i.insertBefore(e,i.firstChild),r.style.cssText="position: absolute; left: 10.7432222px;",n=t(r).offset().left,t.support.offsetFractions=n>10&&11>n,e.innerHTML="",i.removeChild(e)}()})(jQuery);(function(t,e){var i="ui-effects-";t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=h(),n=s._rgba=[];return i=i.toLowerCase(),f(l,function(t,a){var o,r=a.re.exec(i),l=r&&a.parse(r),h=a.space||"rgba";return l?(o=s[h](l),s[c[h].cache]=o[c[h].cache],n=s._rgba=o._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,a.transparent),s):a[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var a,o="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,l=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],h=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=h.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),h.fn=t.extend(h.prototype,{parse:function(n,o,r,l){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(o),o=e);var u=this,d=t.type(n),p=this._rgba=[];return o!==e&&(n=[n,o,r,l],d="array"),"string"===d?this.parse(s(n)||a._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof h?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var a=s.cache;f(s.props,function(t,e){if(!u[a]&&s.to){if("alpha"===t||null==n[t])return;u[a]=s.to(u._rgba)}u[a][e.idx]=i(n[t],e,!0)}),u[a]&&0>t.inArray(null,u[a].slice(0,3))&&(u[a][3]=1,s.from&&(u._rgba=s.from(u[a])))}),this):e},is:function(t){var i=h(t),s=!0,n=this;return f(c,function(t,a){var o,r=i[a.cache];return r&&(o=n[a.cache]||a.to&&a.to(n._rgba)||[],f(a.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===o[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=h(t),n=s._space(),a=c[n],o=0===this.alpha()?h("transparent"):this,r=o[a.cache]||a.to(o._rgba),l=r.slice();return s=s[a.cache],f(a.props,function(t,n){var a=n.idx,o=r[a],h=s[a],c=u[n.type]||{};null!==h&&(null===o?l[a]=h:(c.mod&&(h-o>c.mod/2?o+=c.mod:o-h>c.mod/2&&(o-=c.mod)),l[a]=i((h-o)*e+o,n)))}),this[n](l)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=h(e)._rgba;return h(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),h.fn.parse.prototype=h.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,a=t[2]/255,o=t[3],r=Math.max(s,n,a),l=Math.min(s,n,a),h=r-l,c=r+l,u=.5*c;return e=l===r?0:s===r?60*(n-a)/h+360:n===r?60*(a-s)/h+120:60*(s-n)/h+240,i=0===h?0:.5>=u?h/c:h/(2-c),[Math.round(e)%360,i,u,null==o?1:o]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],a=t[3],o=.5>=s?s*(1+i):s+i-s*i,r=2*s-o;return[Math.round(255*n(r,o,e+1/3)),Math.round(255*n(r,o,e)),Math.round(255*n(r,o,e-1/3)),a]},f(c,function(s,n){var a=n.props,o=n.cache,l=n.to,c=n.from;h.fn[s]=function(s){if(l&&!this[o]&&(this[o]=l(this._rgba)),s===e)return this[o].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[o].slice();return f(a,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=h(c(d)),n[o]=d,n):h(d)},f(a,function(e,i){h.fn[e]||(h.fn[e]=function(n){var a,o=t.type(n),l="alpha"===e?this._hsla?"hsla":"rgba":s,h=this[l](),c=h[i.idx];return"undefined"===o?c:("function"===o&&(n=n.call(this,c),o=t.type(n)),null==n&&i.empty?this:("string"===o&&(a=r.exec(n),a&&(n=c+parseFloat(a[2])*("+"===a[1]?1:-1))),h[i.idx]=n,this[l](h)))})})}),h.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var a,o,r="";if("transparent"!==n&&("string"!==t.type(n)||(a=s(n)))){if(n=h(a||n),!d.rgba&&1!==n._rgba[3]){for(o="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&o&&o.style;)try{r=t.css(o,"backgroundColor"),o=o.parentNode}catch(l){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(l){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=h(e.elem,i),e.end=h(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},h.hook(o),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},a=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,a={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(a[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(a[i]=n[i]);return a}function s(e,i){var s,n,o={};for(s in i)n=i[s],e[s]!==n&&(a[s]||(t.fx.step[s]||!isNaN(parseFloat(n)))&&(o[s]=n));return o}var n=["add","remove","toggle"],a={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(jQuery.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(e,a,o,r){var l=t.speed(a,o,r);return this.queue(function(){var a,o=t(this),r=o.attr("class")||"",h=l.children?o.find("*").addBack():o;h=h.map(function(){var e=t(this);return{el:e,start:i(this)}}),a=function(){t.each(n,function(t,i){e[i]&&o[i+"Class"](e[i])})},a(),h=h.map(function(){return this.end=i(this.el[0]),this.diff=s(this.start,this.end),this}),o.attr("class",r),h=h.map(function(){var e=this,i=t.Deferred(),s=t.extend({},l,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,h.get()).done(function(){a(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),l.complete.call(o[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,a){return s?t.effects.animateClass.call(this,{add:i},s,n,a):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,a){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,a):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(i){return function(s,n,a,o,r){return"boolean"==typeof n||n===e?a?t.effects.animateClass.call(this,n?{add:s}:{remove:s},a,o,r):i.apply(this,arguments):t.effects.animateClass.call(this,{toggle:s},n,a,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,a){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,a)}})}(),function(){function s(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function n(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}t.extend(t.effects,{version:"1.10.4",save:function(t,e){for(var s=0;e.length>s;s++)null!==e[s]&&t.data(i+e[s],t[0].style[e[s]])},restore:function(t,s){var n,a;for(a=0;s.length>a;a++)null!==s[a]&&(n=t.data(i+s[a]),n===e&&(n=""),t.css(s[a],n))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},a=document.activeElement;try{a.id}catch(o){a=document.body}return e.wrap(s),(e[0]===a||t.contains(e[0],a))&&t(a).focus(),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).focus()),e},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var a=e.cssUnit(i);a[0]>0&&(n[i]=a[0]*s+a[1])}),n}}),t.fn.extend({effect:function(){function e(e){function s(){t.isFunction(a)&&a.call(n[0]),t.isFunction(e)&&e()}var n=t(this),a=i.complete,r=i.mode;(n.is(":hidden")?"hide"===r:"show"===r)?(n[r](),s()):o.call(n[0],i,s)}var i=s.apply(this,arguments),n=i.mode,a=i.queue,o=t.effects.effect[i.effect];return t.fx.off||!o?n?this[n](i.duration,i.complete):this.each(function(){i.complete&&i.complete.call(this)}):a===!1?this.each(e):this.queue(a||"fx",e)},show:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="show",this.effect.call(this,i)}}(t.fn.show),hide:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="hide",this.effect.call(this,i)}}(t.fn.hide),toggle:function(t){return function(e){if(n(e)||"boolean"==typeof e)return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="toggle",this.effect.call(this,i)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s}})}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}()})(jQuery);;
/*! jQuery Validation Plugin - v1.10.0 - 9/7/2012
* https://github.com/jzaefferer/jquery-validation
* Copyright (c) 2012 Jörn Zaefferer; Licensed MIT */
(function(a){a.extend(a.fn,{validate:function(b){if(!this.length){b&&b.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return}var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.validateDelegate(":submit","click",function(b){c.settings.submitHandler&&(c.submitButton=b.target),a(b.target).hasClass("cancel")&&(c.cancelSubmit=!0)}),this.submit(function(b){function d(){var d;return c.settings.submitHandler?(c.submitButton&&(d=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(c.submitButton.value).appendTo(c.currentForm)),c.settings.submitHandler.call(c,c.currentForm,b),c.submitButton&&d.remove(),!1):!0}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){if(a(this[0]).is("form"))return this.validate().form();var b=!0,c=a(this[0].form).validate();return this.each(function(){b&=c.element(this)}),b},removeAttrs:function(b){var c={},d=this;return a.each(b.split(/\s/),function(a,b){c[b]=d.attr(b),d.removeAttr(b)}),c},rules:function(b,c){var d=this[0];if(b){var e=a.data(d.form,"validator").settings,f=e.rules,g=a.validator.staticRules(d);switch(b){case"add":a.extend(g,a.validator.normalizeRule(c)),f[d.name]=g,c.messages&&(e.messages[d.name]=a.extend(e.messages[d.name],c.messages));break;case"remove":if(!c)return delete f[d.name],g;var h={};return a.each(c.split(/\s/),function(a,b){h[b]=g[b],delete g[b]}),h}}var i=a.validator.normalizeRules(a.extend({},a.validator.metadataRules(d),a.validator.classRules(d),a.validator.attributeRules(d),a.validator.staticRules(d)),d);if(i.required){var j=i.required;delete i.required,i=a.extend({required:j},i)}return i}}),a.extend(a.expr[":"],{blank:function(b){return!a.trim(""+b.value)},filled:function(b){return!!a.trim(""+b.value)},unchecked:function(a){return!a.checked}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return arguments.length===1?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),c)}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a,b){this.lastActive=a,this.settings.focusCleanup&&!this.blockFocusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.addWrapper(this.errorsFor(a)).hide())},onfocusout:function(a,b){!this.checkable(a)&&(a.name in this.submitted||!this.optional(a))&&this.element(a)},onkeyup:function(a,b){if(b.which===9&&this.elementValue(a)==="")return;(a.name in this.submitted||a===this.lastActive)&&this.element(a)},onclick:function(a,b){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){b.type==="radio"?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){b.type==="radio"?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function d(b){var c=a.data(this[0].form,"validator"),d="on"+b.type.replace(/^validate/,"");c.settings[d]&&c.settings[d].call(c,this[0],b)}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var b=this.groups={};a.each(this.settings.groups,function(c,d){a.each(d.split(/\s/),function(a,d){b[d]=c})});var c=this.settings.rules;a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).validateDelegate(":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'] ","focusin focusout keyup",d).validateDelegate("[type='radio'], [type='checkbox'], select, option","click",d),this.settings.invalidHandler&&a(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){b=this.validationTargetFor(this.clean(b)),this.lastElement=b,this.prepareElement(b),this.currentElements=a(b);var c=this.check(b)!==!1;return c?delete this.invalid[b.name]:this.invalid[b.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),c},showErrors:function(b){if(b){a.extend(this.errorMap,b),this.errorList=[];for(var c in b)this.errorList.push({message:b[c],element:this.findByName(c)[0]});this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.submitted={},this.lastElement=null,this.prepareForm(),this.hideErrors(),this.elements().removeClass(this.settings.errorClass).removeData("previousValue")},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b=0;for(var c in a)b++;return b},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()===0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&a.grep(this.errorList,function(a){return a.element.name===b.name}).length===1&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){return!this.name&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in c||!b.objectLength(a(this).rules())?!1:(c[this.name]=!0,!0)})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.replace(" ",".");return a(this.settings.errorElement+"."+b,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([]),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c=a(b).attr("type"),d=a(b).val();return c==="radio"||c==="checkbox"?a('input[name="'+a(b).attr("name")+'"]:checked').val():typeof d=="string"?d.replace(/\r/g,""):d},check:function(b){b=this.validationTargetFor(this.clean(b));var c=a(b).rules(),d=!1,e=this.elementValue(b),f;for(var g in c){var h={method:g,parameters:c[g]};try{f=a.validator.methods[g].call(this,e,b,h.parameters);if(f==="dependency-mismatch"){d=!0;continue}d=!1;if(f==="pending"){this.toHide=this.toHide.not(this.errorsFor(b));return}if(!f)return this.formatAndAdd(b,h),!1}catch(i){throw this.settings.debug&&window.console&&console.log("exception occured when checking element "+b.id+", check the '"+h.method+"' method",i),i}}if(d)return;return this.objectLength(c)&&this.successList.push(b),!0},customMetaMessage:function(b,c){if(!a.metadata)return;var d=this.settings.meta?a(b).metadata()[this.settings.meta]:a(b).metadata();return d&&d.messages&&d.messages[c]},customDataMessage:function(b,c){return a(b).data("msg-"+c.toLowerCase())||b.attributes&&a(b).attr("data-msg-"+c.toLowerCase())},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==undefined)return arguments[a];return undefined},defaultMessage:function(b,c){return this.findDefined(this.customMessage(b.name,c),this.customDataMessage(b,c),this.customMetaMessage(b,c),!this.settings.ignoreTitle&&b.title||undefined,a.validator.messages[c],"<strong>Warning: No message defined for "+b.name+"</strong>")},formatAndAdd:function(b,c){var d=this.defaultMessage(b,c.method),e=/\$?\{(\d+)\}/g;typeof d=="function"?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),this.errorList.push({message:d,element:b}),this.errorMap[b.name]=d,this.submitted[b.name]=d},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b;for(a=0;this.errorList[a];a++){var c=this.errorList[a];this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message)}this.errorList.length&&(this.toShow=this.toShow.add(this.containers));if(this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d=this.errorsFor(b);d.length?(d.removeClass(this.settings.validClass).addClass(this.settings.errorClass),d.attr("generated")&&d.html(c)):(d=a("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(b),generated:!0}).addClass(this.settings.errorClass).html(c||""),this.settings.wrapper&&(d=d.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.append(d).length||(this.settings.errorPlacement?this.settings.errorPlacement(d,a(b)):d.insertAfter(b))),!c&&this.settings.success&&(d.text(""),typeof this.settings.success=="string"?d.addClass(this.settings.success):this.settings.success(d,b)),this.toShow=this.toShow.add(d)},errorsFor:function(b){var c=this.idOrName(b);return this.errors().filter(function(){return a(this).attr("for")===c})},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(a){return this.checkable(a)&&(a=this.findByName(a.name).not(this.settings.ignore)[0]),a},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find('[name="'+b+'"]')},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):!0},dependTypes:{"boolean":function(a,b){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(a){this.pending[a.name]||(this.pendingRequest++,this.pending[a.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],c&&this.pendingRequest===0&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.formSubmitted=!1):!c&&this.pendingRequest===0&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b){return a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,"remote")})}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},attributeRules:function(b){var c={},d=a(b);for(var e in a.validator.methods){var f;e==="required"?(f=d.get(0).getAttribute(e),f===""&&(f=!0),f=!!f):f=d.attr(e),f?c[e]=f:d[0].getAttribute("type")===e&&(c[e]=!0)}return c.maxlength&&/-1|2147483647|524288/.test(c.maxlength)&&delete c.maxlength,c},metadataRules:function(b){if(!a.metadata)return{};var c=a.data(b.form,"validator").settings.meta;return c?a(b).metadata()[c]:a(b).metadata()},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1){delete b[d];return}if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=e.param!==undefined?e.param:!0:delete b[d]}}),a.each(b,function(d,e){b[d]=a.isFunction(e)?e(c):e}),a.each(["minlength","maxlength","min","max"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){b[this]&&(b[this]=[Number(b[this][0]),Number(b[this][1])])}),a.validator.autoCreateRanges&&(b.min&&b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),b.minlength&&b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b.messages&&delete b.messages,b},normalizeRule:function(b){if(typeof b=="string"){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=d!==undefined?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if(c.nodeName.toLowerCase()==="select"){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:a.trim(b).length>0},remote:function(b,c,d){if(this.optional(c))return"dependency-mismatch";var e=this.previousValue(c);this.settings.messages[c.name]||(this.settings.messages[c.name]={}),e.originalMessage=this.settings.messages[c.name].remote,this.settings.messages[c.name].remote=e.message,d=typeof d=="string"&&{url:d}||d;if(this.pending[c.name])return"pending";if(e.old===b)return e.valid;e.old=b;var f=this;this.startRequest(c);var g={};return g[c.name]=b,a.ajax(a.extend(!0,{url:d,mode:"abort",port:"validate"+c.name,dataType:"json",data:g,success:function(d){f.settings.messages[c.name].remote=e.originalMessage;var g=d===!0||d==="true";if(g){var h=f.formSubmitted;f.prepareElement(c),f.formSubmitted=h,f.successList.push(c),delete f.invalid[c.name],f.showErrors()}else{var i={},j=d||f.defaultMessage(c,"remote");i[c.name]=e.message=a.isFunction(j)?j(b):j,f.invalid[c.name]=!0,f.showErrors(i)}e.valid=g,f.stopRequest(c,g)}},d)),"pending"},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(a.trim(b),c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(a.trim(b),c);return this.optional(c)||e<=d},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(a.trim(b),c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||a<=c},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},email:function(a,b){return this.optional(b)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a)},url:function(a,b){return this.optional(b)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)},date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a))},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9 \-]+/.test(a))return!1;var c=0,d=0,e=!1;a=a.replace(/\D/g,"");for(var f=a.length-1;f>=0;f--){var g=a.charAt(f);d=parseInt(g,10),e&&(d*=2)>9&&(d-=9),c+=d,e=!e}return c%10===0},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()}}}),a.format=a.validator.format})(jQuery),function(a){var b={};if(a.ajaxPrefilter)a.ajaxPrefilter(function(a,c,d){var e=a.port;a.mode==="abort"&&(b[e]&&b[e].abort(),b[e]=d)});else{var c=a.ajax;a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return e==="abort"?(b[f]&&b[f].abort(),b[f]=c.apply(this,arguments)):c.apply(this,arguments)}}}(jQuery),function(a){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&a.each({focus:"focusin",blur:"focusout"},function(b,c){function d(b){return b=a.event.fix(b),b.type=c,a.event.handle.call(this,b)}a.event.special[c]={setup:function(){this.addEventListener(b,d,!0)},teardown:function(){this.removeEventListener(b,d,!0)},handler:function(b){var d=arguments;return d[0]=a.event.fix(b),d[0].type=c,a.event.handle.apply(this,d)}}}),a.extend(a.fn,{validateDelegate:function(b,c,d){return this.bind(c,function(c){var e=a(c.target);if(e.is(b))return d.apply(e,arguments)})}})}(jQuery);
/*
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,d){var b=a(this).find("[data-valmsg-for='"+f(d[0].name)+"']"),e=a.parseJSON(b.attr("data-valmsg-replace"))!==false;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(e){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("<li />").html(this.message).appendTo(b)})}}function k(c){var b=c.data("unobtrusiveContainer"),d=a.parseJSON(b.attr("data-valmsg-replace"));if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");c.removeData("unobtrusiveContainer");d&&b.empty()}}function n(){var b=a(this);b.data("validator").resetForm();b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(c){var b=a(c),d=b.data(e),f=a.proxy(n,c);if(!d){d={options:{errorClass:"input-validation-error",errorElement:"span",errorPlacement:a.proxy(m,c),invalidHandler:a.proxy(l,c),messages:{},rules:{},success:a.proxy(k,c)},attachValidation:function(){b.unbind("reset."+e,f).bind("reset."+e,f).validate(this.options)},validate:function(){b.validate();return b.valid()}};b.data(e,d)}return d}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(b){var c=a(b).parents("form").andSelf().add(a(b).find("form")).filter("form");a(b).find(":input[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});c.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});b.addSingleVal("accept","exts").addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){return a(b.form).find(":input[name='"+f(c)+"']").val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery);;
/*!
 * jQuery smartresize plugin v2.1.0
 * http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/
 *
 * MIT License. by Paul Irish et al.
 */
(function ($, sr) {

    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced() {

            var obj = this, args = arguments;
            $(this).data('smartResizeEndSize') ? jQuery.fn[sr].startSize.width = $(this).data('smartResizeEndSize').width : jQuery.fn[sr].startSize.width = $(window).width();
            $(this).data('smartResizeEndSize') ? jQuery.fn[sr].startSize.height = $(this).data('smartResizeEndSize').height : jQuery.fn[sr].startSize.height = $(window).height();

            function delayed() {
                jQuery.fn[sr].endSize.width = $(window).width();
                jQuery.fn[sr].endSize.height = $(window).height();
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
                $(this).data('smartResizeStartSize', jQuery.fn[sr].startSize);
                $(this).data('smartResizeEndSize', jQuery.fn[sr].endSize);
            }

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 300);
        };
    };
    // smartresize
    jQuery.fn[sr] = function (fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };


    jQuery.fn[sr].startSize = function () {
        return { width: jQuery.fn[sr].startSize.width, height: jQuery.fn[sr].startSize.height };
    };
    jQuery.fn[sr].endSize = function () {
        return { width: jQuery.fn[sr].endSize.width, height: jQuery.fn[sr].endSize.height };
    };
    // smartscroll (dodge)
    jQuery.fn["smartscroll"] = function (fn) { return fn ? this.bind('scroll', debounce(fn)) : this.trigger("smartscroll"); };

})(jQuery, 'smartresize');;
/*! http://mths.be/placeholder v2.0.7 by @mathias */
; (function (f, h, $) { var a = 'placeholder' in h.createElement('input'), d = 'placeholder' in h.createElement('textarea'), i = $.fn, c = $.valHooks, k, j; if (a && d) { j = i.placeholder = function () { return this }; j.input = j.textarea = true } else { j = i.placeholder = function () { var l = this; l.filter((a ? 'textarea' : ':input') + '[placeholder]').not('.placeholder').bind({ 'focus.placeholder': b, 'blur.placeholder': e }).data('placeholder-enabled', true).trigger('blur.placeholder'); return l }; j.input = a; j.textarea = d; k = { get: function (m) { var l = $(m); return l.data('placeholder-enabled') && l.hasClass('placeholder') ? '' : m.value }, set: function (m, n) { var l = $(m); if (!l.data('placeholder-enabled')) { return m.value = n } if (n == '') { m.value = n; if (m != h.activeElement) { e.call(m) } } else { if (l.hasClass('placeholder')) { b.call(m, true, n) || (m.value = n) } else { m.value = n } } return l } }; a || (c.input = k); d || (c.textarea = k); $(function () { $(h).delegate('form', 'submit.placeholder', function () { var l = $('.placeholder', this).each(b); setTimeout(function () { l.each(e) }, 10) }) }); $(f).bind('beforeunload.placeholder', function () { $('.placeholder').each(function () { this.value = '' }) }) } function g(m) { var l = {}, n = /^jQuery\d+$/; $.each(m.attributes, function (p, o) { if (o.specified && !n.test(o.name)) { l[o.name] = o.value } }); return l } function b(m, n) { var l = this, o = $(l); if (l.value == o.attr('placeholder') && o.hasClass('placeholder')) { if (o.data('placeholder-password')) { o = o.hide().next().show().attr('id', o.removeAttr('id').data('placeholder-id')); if (m === true) { return o[0].value = n } o.focus() } else { l.value = ''; o.removeClass('placeholder'); l == h.activeElement && l.select() } } } function e() { var q, l = this, p = $(l), m = p, o = this.id; if (l.value == '') { if (l.type == 'password') { if (!p.data('placeholder-textinput')) { try { q = p.clone().attr({ type: 'text' }) } catch (n) { q = $('<input>').attr($.extend(g(this), { type: 'text' })) } q.removeAttr('name').data({ 'placeholder-password': true, 'placeholder-id': o }).bind('focus.placeholder', b); p.data({ 'placeholder-textinput': q, 'placeholder-id': o }).before(q) } p = p.removeAttr('id').hide().prev().attr('id', o).show() } p.addClass('placeholder'); p[0].value = p.attr('placeholder') } else { p.removeClass('placeholder') } } }(this, document, jQuery));;
/*!
 * jquery.backgroundcover.js
 * https://github.com/duncanmcdougall/jQuery-Background-Cover
 * Copyright 2013 Duncan McDougall and other contributors; Licensed MIT
 */
; (function ($) {

    'use strict';

    function coverImage() {

        if (!this._loaded) {
            return;
        }

        var img = this,
            $img = $(this).removeAttr("style").css({ 'position': 'absolute', 'max-width': 'none', 'display': 'block',top:0,left:0 }),
            settings = $img.data("settings") || {},
			isCover = settings.isCover !== false,
            imageContainer = $img.parent(),
            containerRatio = settings.containerRatio || (imageContainer.outerWidth() / imageContainer.outerHeight()),
            imgRatio = settings.imgRatio || (($img.attr("width") || img.width) / ($img.attr("height") || img.height)),
            ratio = containerRatio / imgRatio,
            offset,
            ratioLarge = ratio > 1,
            direction,
            tolerance = 0.05;

//        if( img.src.match(/desert/i) ) {
//            console.info( imageContainer.width() / imageContainer.height(),containerRatio,imgRatio,ratio );
//        }

        // set the z-index only if we aren't ignoring it
        if (!settings.ignoreIndex) {
            $img.css("z-index", -1);
        }

        imageContainer.css({
            // the position needs to be not static, so set to relative if it is otherwise leave as is
            'position': function (index, value) {
                if (value == "static") return "relative";
            },
                // going to set the z-index of the image to -1 (so it is behind everything). For this to work, the parent needs a z-index. Leave as if (if set) set to zero otherwise
            'z-index': function (index, value) { if (value == "auto" && !settings.ignoreIndex) return 0; },
            'overflow': 'hidden'
        });

        // check to see if the ratio is within the tolerance level
        if (Math.abs(1 - ratio) < tolerance) {
            $img.width("100%");
            $img.height("100%");
        } else {
            // ratio greater than 1 is where image is "thinner" than the container.
            // This implies shifting the top for a cover, or the left for a fit

            // (1 - r/r')/2
            // ratioLarge cover (move top) 
            // !ratioLarge fit (move top)
            if ((ratioLarge && isCover) || (!ratioLarge && !isCover)) {
                direction = "top";
                $img.width("100%");
                $img.height("auto");
            } else {
                // (1 - r'/r)/2
                // ratioLarge fit (move left)
                // !ratioLarge cover (move left)
                // switch the ratio
                direction = "left";
                ratio = 1 / ratio;
                $img.height("100%");
                $img.width("auto");
            }

            offset = (1 - ratio) * 50;

            $img.css(direction, offset + "%");
        }

    }

    var coverImages = $();
    var isInit = false;
    var cover = function () {
        coverImages.each(coverImage);
    };

    function imgLoaded(img) {
        img._loaded = true;
        coverImages = coverImages.add(img);
        coverImage.apply(img);
    }

    $.fn.backgroundCover = function (settings) {
        var settings = settings || { };

        this.each(function() {
            var img = this;
            
            if( $(img).data("backgroundcover") ) {
                coverImage.apply(img);
                return true;
            }

            // see if there are any settings on the elements in data-coversettings
            var coverSettings = $(img).data("coversettings");

            $(img).data("settings", $.extend({},settings, coverSettings));

            // this can be used for canvas as well
            if( img.getContext ) {
                imgLoaded(img);
                return true;
            }

            // borrowed from imagesloaded
            if (img.complete && img.naturalWidth !== undefined) {
                if (!img.naturalWidth) {
                    return true;
                }
                imgLoaded(img);
            } else {
                var proxyImage = new Image();
                $(proxyImage).load(function () {
                    imgLoaded(img);
                });
                proxyImage.src = img.src;
            }
        });

        if (!isInit) {
            if (!settings.ignoreResize) {
                $(window).bind("resize.backgroundCover", cover);
            }
            
            isInit = true;
        }

        return this;
    };

    $.backgroundCoverTrigger = cover;

})(jQuery);;
; (function ($) {
    'use strict';

    var imageResizePath = "{0}?{1}&mode=crop&quality=90";

    var defaultBounds = [100, 150, 200, 400, 600, 800, 1000, 1200];


    // rounds a width to an appropriate level based on an array of numbers
    function roundToAppropriateDimension(inWidth, bounds) {
        bounds = bounds || defaultBounds;
        for (var b = 0; b < bounds.length; b++) {
            if (inWidth < bounds[b] + 15) return bounds[b];
        }
        return 1400;
    }

    $.fn.responsiveBackgroundImage = function (options) {

        options = options || {};

        return this.each(function () {

            var imageContainer = $(this), iWidth, iHeight, pWidth, pHeight, oWidth, oHeight, iRatio, pRatio, src, parent = options.parent ? $(options.parent) : imageContainer.parent();
            if (!imageContainer.data("init") && parent.is(":visible")) {

                var image = new Image(),
                    srcOptions = "";

                oWidth = Number(imageContainer.data("outputwidth"));
                oHeight = Number(imageContainer.data("outputheight"));




                // do some checking for responsive layouts. These can be cropped with confidence

                // ignore the ratio stuff if a fixed width has been set
                if (oWidth || oHeight) {
                    if (oWidth) {
                        srcOptions += "&width=" + oWidth;
                    }

                    if (oHeight) {
                        srcOptions += "&height=" + oHeight;
                    }
                } else {

                    pWidth = parent.innerWidth();
                    pHeight = parent.innerHeight();
                    pRatio = pWidth / pHeight;

                    ////                    if (parent[0].className.match("responsive-ratio")) {
                    ////                        var round = roundToAppropriateDimension(pWidth);
                    ////                        src += "&width=" + round;
                    ////                        src += "&height=" + roundToAppropriateDimension(pHeight);
                    ////                    } else {


                    //                    iWidth = Number(imageContainer.data("width"));
                    //                    iHeight = Number(imageContainer.data("height"));
                    //                    iRatio = iWidth / iHeight;


                    //                    if (iRatio < pRatio) {
                    // use width as greatest
                    srcOptions += "&width=" + roundToAppropriateDimension(pWidth);
                    //                    } else {
                    // use height as greatest
                    srcOptions += "&height=" + roundToAppropriateDimension(pHeight);
                    //                    }

                    //                    }

                }

                src = imageResizePath.format(imageContainer.data("image"), srcOptions);

                image.onload = function () {
                    parent.addClass("ie-cover-image responsive-background");
                    parent.css({ backgroundImage: 'url("' + src + '")' }).data("image", src);
                };

                //                if( oHeight && oWidth ) {
                //                  src += "&crop=resize";
                //            } else {
                //              src += "&constrain=true";
                //        }

                image.src = src;

                imageContainer.remove();
            }
        });
    };
    $.fn.responsiveInlineBackgroundImage = function (options) {
        var resultantBackgroundImage = "{0}?&width={1}&height={2}&mode=crop&quality=90";
        options = options || {};

        return this.each(function () {
            var imageContainer = $(this), iWidth, iHeight, pWidth, pHeight, oWidth, oHeight, iRatio, pRatio, src, parent = options.parent ? $(options.parent) : imageContainer.parent();
            var state = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
            if (!imageContainer.data("init") && parent.is(":visible")) {

                //var image = new Image(),
                var srcOptions = "";
                var header_holder = $('#header_holder');
                var mobile_buttons = $('.mobile-buttons');
                var cookie_warning = $('.cookie-warning');
                var slick_slider = $('.slick-slider');
                var carousel = $('#myCarousel');
                if (isMobile) {
                    slick_slider.height($(window).height() - header_holder.height() - mobile_buttons.height());
                    carousel.height($(window).height() - header_holder.height() - mobile_buttons.height());
                }
                else {
                    slick_slider.height($(window).height() - header_holder.height());
                }

                oWidth = Number(imageContainer.data("outputwidth"));
                oHeight = Number(imageContainer.data("outputheight"));



                if (imageContainer.hasClass("split-slide")) {
                    srcOptions += "&width=" + imageContainer.outerWidth();
                    srcOptions += "&height=" + imageContainer.outerHeight();
                }
                else {
                    if (window.innerWidth < 992) {
                        oWidth = 992;
                        oHeight = 1024;
                        if (window.innerHeight > window.innerWidth) {
                            oHeight = 1024;
                        } else {
                            oHeight = 700;
                        }
                    }
                    else if ($(window).innerWidth() > 991 && $(window).innerWidth() <= 1366) {
                        oWidth = 1366;
                        oHeight = 700;

                    }

                    // do some checking for responsive layouts. These can be cropped with confidence

                    // ignore the ratio stuff if a fixed width has been set
                    if (oWidth || oHeight) {
                        if (oWidth) {
                            srcOptions += "&width=" + oWidth;
                        }

                        if (oHeight) {
                            srcOptions += "&height=" + oHeight;
                        }
                    } else {
                        if (imageContainer.hasClass("slick-slide")) {
                            pWidth = $(window).width() + 30;
                        }
                        else {
                            pWidth = parent.outerWidth();
                        }

                        pHeight = parent.outerHeight();
                        pRatio = pWidth / pHeight;

                        ////                    if (parent[0].className.match("responsive-ratio")) {
                        ////                        var round = roundToAppropriateDimension(pWidth);
                        ////                        src += "&width=" + round;
                        ////                        src += "&height=" + roundToAppropriateDimension(pHeight);
                        ////                    } else {


                        //                    iWidth = Number(imageContainer.data("width"));
                        //                    iHeight = Number(imageContainer.data("height"));
                        //                    iRatio = iWidth / iHeight;


                        //                    if (iRatio < pRatio) {
                        // use width as greatest
                        srcOptions += "&width=" + pWidth;
                        //                    } else {
                        // use height as greatest
                        srcOptions += "&height=" + pHeight;
                        //                    }

                        //                    }

                    }
                }

                src = imageResizePath.format(imageContainer.data('url').replace(/(?:^url\(["']?|["']?\)$)/g, "").split("?")[0], srcOptions);
                src = src.replace("quality=90", "quality=100");
                imageContainer.css({ backgroundImage: 'url("' + src + '")' });
                imageContainer.attr('title', imageContainer.data('title'));
                imageContainer.removeAttr("data-url");
                imageContainer.removeAttr("data-title");
                imageContainer.removeAttr("data-outputwidth");
                imageContainer.removeAttr("data-outputheight");
                /* image.onload = function() {
                     parent.addClass("ie-cover-image responsive-background");
                     parent.css({ backgroundImage: 'url("' + src + '")' }).data("image", src);
                 };*/

                //                if( oHeight && oWidth ) {
                //                  src += "&crop=resize";
                //            } else {
                //              src += "&constrain=true";
                //        }

                /*image.src = src;

                imageContainer.remove();*/

            }
        });
    };

})(jQuery);;
window.EQTR = (function (module, $) {
    "use strict";

    var helpers = {};

    helpers.jsPath = '/assets/js/';

    /*--- Check what view we are in - small, medium, large ---*/
    // Use a common element which changes between window sizes
    // e.g. main nav - hidden on small screens. try and avoid using device widths if possible
    helpers.getScreenView = function () {
        var small = 480,
			med = 768,
			large,
			screen;
        if ($(window).width() <= small) {
            screen = 'small';
        }
        else if ($(window).width() <= med) {
            screen = 'medium';
        }
        else {
            screen = 'large';
        }
        return screen;
    };

    /*--- Check the orientation of device ---*/
    helpers.getOrientation = function() {
        var deviceOrientation = window.orientation;
        if (typeof deviceOrientation === "undefined")
            deviceOrientation = 'orientation not supported';

        return deviceOrientation;
    };
    
    /* helper for getting the scrollwidth for the current browser */
    helpers.scrollbarWidth = function() {
        var scrollWidth
        // work out the scrollbar width (should be the same for the height)
        $('<div style="position:absolute;top:-10000px;width:100px;overflow:scroll;"><div style="width:200px;"></div>').appendTo("body").each(function() {
            scrollWidth = $(this).width() - this.clientWidth;
        }).remove();
        return scrollWidth;
    };

    /*--- Check if device supports touch event ---*/
    helpers.isTouchDevice = function () {
    	return !!('ontouchstart' in window) || !!window.navigator.msMaxTouchPoints;
    };
    
    /**
      * @desc pads out a number with zeros to a minimum length
      * @param int number - the number you want to convert
      * @param int size - minimum length of return string
      * @return string
    */
    helpers.pad = function (number, size) {
        var s = number + "";
        while (s.length < size) s = "0" + s;
        return s;
    };

    /* uuid creator */
    helpers.generateUuid = function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    };
    
    helpers.isEmail = function (email) {
        var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return regex.test(email);
    };

    // Gets a hash string parameter.
    // e.g. mysite.com/some-page/#foo=bar
    helpers.getHashParameter = function (url, paramName) {
        var searchString = url.split("#");

        if (searchString.length < 2) {
            return null;
        }

        var i, val, params = searchString[1].split("&");

        for (i = 0; i < params.length; i++) {
            val = params[i].split("=");
            if (val[0] == paramName) {
                return unescape(val[1]);
            }
        }
        return null;
    };
    
    // simple array shuffler
    helpers.shuffleArray = function(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    };

    module.helpers = helpers;

    // css module
    var css = { };
    /* css modifiers */

    css.defaultStyleSheetName = "dynamicClasses";
    css.stylesheet = null;

    css.init = function (stylesheetName,isNew) {
        stylesheetName = stylesheetName || css.defaultStyleSheetName;
        if (isNew) {
            css.stylesheet = css.createStylesheet(stylesheetName);
        } else {
            css.stylesheet = css.findStylesheetById("dynamicClasses");
        }
        
    };

    css.checkInit = function() {
        if (!css.stylesheet) {
            css.init(null, true);
        }
    };

    css.createStylesheet = function(name) {
        var head = document.head || document.getElementsByTagName('head')[0],
            style = document.createElement('style');

        style.type = 'text/css';
        style.id = name;
        //if (style.styleSheet) {
        //    style.styleSheet.cssText = css;
        //} else {
        //    style.appendChild(document.createTextNode(css));
        //}

        head.appendChild(style);

        return css.findStylesheetById(name);
    };

    css.findStylesheetById = function(id) {

        var styleSheet = document.getElementById(id);

        if (styleSheet) {

            if (styleSheet.sheet) {
                return styleSheet.sheet;
            } else {
                var ss = document.styleSheets;

                for (var s = 0, l = ss.length; s < l; s++) {
                    if (ss[s].id == id) return ss[s];
                }
            }

        }
        return css.createStylesheet(id);
    };

    css.findRule = function(selector,createIfNull) {
        // check to see if the stylesheet exists, if not create it
        css.checkInit();

        var rule = null, // Default to 'not found'
            theRules = css.stylesheet.cssRules || css.stylesheet.rules,
            findByIndex = typeof selector == "number";

        if (findByIndex) {
            return theRules[selector] || null;
        } else {

            selector = selector.toLowerCase();
            for (var i = 0; i < theRules.length; i++) {
                if (!theRules[i].selectorText) continue;
                if (theRules[i].selectorText.toLowerCase() == selector) {
                    rule = theRules[i];
                    break;
                } // endif theRules[i]
            } // end for i

            // if there is no rule then create the a blank rule
            if (!rule && createIfNull) {
                return css.addRule(selector);
            }
        }
        
        return rule;
    }; // end findCSSRule()

    css.changeRule = function(selector, property, setting) {
        // check to see if the stylesheet exists, if not create it
        css.checkInit();

        var rule = css.findRule(selector,true);

        if ((typeof property != "object") && setting) {
            // turn property and settings in an object
            var temp = property;
            property = { };
            property[temp] = setting;
        }
        
        for (var p in property) {
            rule.style[p] = property[p];
        }

        return rule;
    }; // end changeRule()

    css.addRule = function(selector, newRule) {
        // check to see if the stylesheet exists, if not create it
        css.checkInit();

        if (!newRule) {
            newRule = " ";
        }

        var ruleIndex;

        if (css.stylesheet.insertRule) {
            var ruleIndex = css.stylesheet.cssRules.length;
            ruleIndex = css.stylesheet.insertRule(selector + ' {' + newRule + '}', ruleIndex); // For Firefox, Chrome, etc.
        } else {
            ruleIndex = css.stylesheet.addRule(selector, newRule); // For Internet Explorer
            
            // some ie versions return -1. Assume it is just the ones that don't use insertRule return -1 as IE10 returns the index when using addRule but also has insertRule
            if (ruleIndex == -1) {
                ruleIndex = css.stylesheet.rules.length - 1;
            }
        } // endif css.stylesheet.addRule

        return css.findRule(ruleIndex);

    }; // end addCSSRule()

    css.removeRule = function(ruleIndex) {
        // check to see if the stylesheet exists, if not create it
        css.checkInit();

        if (css.stylesheet.removeRule) {
            css.stylesheet.removeRule(ruleIndex); // For Internet Explorer
        } else {
            css.stylesheet.deleteRule(ruleIndex); // For Firefox, Chrome, etc.
        } // endif css.stylesheet.removeRule
    }; // end removeCSSRule()

    css.addStylesheet = function(theHref) {
        if (document.createStyleSheet) {
            document.createStyleSheet(theHref);
        } else {
            var newSheet = document.createElement('link');
            newSheet.setAttribute('rel', 'stylesheet');
            newSheet.setAttribute('type', 'text/css');
            newSheet.setAttribute('href', theHref);
            document.getElementsByTagName('head')[0].appendChild(newSheet);
        }
    }; // end addStylesheet()

    module.css = css;

    return module;

})(window.EQTR|| {}, window.jQuery);

jQuery.fn.cleanWhitespace = function() {
    textNodes = this.contents().filter(
        function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); })
        .remove();
    return this;
}

/* .NET like string format/replace function. Simple method for replacing {} placeholders in a string */
String.prototype.format = function () {
    var str = this.toString();
    for (var x = 0; x < arguments.length; x++) {
        str = str.replace(new RegExp("\\{" + x + "\\}", "g"), arguments[x]);
    }
    return str;
};

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license

(function () {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']
                                   || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function (callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function () { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function (id) {
            clearTimeout(id);
        };
}());

// jquery element shuffle
(function ($) {

    $.fn.shuffle = function () {

        var allElems = this.get(),
            getRandom = function (max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function () {
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
            });

        this.each(function (i) {
            $(this).replaceWith($(shuffled[i]));
        });

        return $(shuffled);

    };

})(jQuery);

// indexof shim
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement, fromIndex) {
        var i,
            pivot = (fromIndex) ? fromIndex : 0,
            length;

        if (!this) {
            throw new TypeError();
        }

        length = this.length;

        if (length === 0 || pivot >= length) {
            return -1;
        }

        if (pivot < 0) {
            pivot = length - Math.abs(pivot);
        }

        for (i = pivot; i < length; i++) {
            if (this[i] === searchElement) {
                return i;
            }
        }
        return -1;
    };
}

// selector extension
jQuery.extend(jQuery.expr[':'], {
    cssVisible : function (el) {
        var $e = $(el);

        return !($e.css('visibility') == 'hidden' || $e.css('display') == 'none');
    }
});;
// tracking methods
window.EQTR = (function (module, $) {

    var pageTracker,
        pageViewDebounceTimer,
        _debounceTime = 500,
        // this only exists so neolane can piggy back on GA for the ecommerce stuff
        lastTrackedPage;

    // there is the ability to stop multiple trackers being sent from fast actions
    // e.g. used in the ajax page loading, so quick user actions in changing pages isn't skewing results
    // last action wins. This isn't set by default.
    function _trackPage(pageview, usePath, ignoreNeolane) {
        var pv = (usePath ? location.pathname : "") + (pageview || "");

        // if the location host is included and the protocol, strip it out
        if (pv) {
            var hostRegEx = new RegExp(location.protocol + "//" + location.host);
            pv = pv.replace(hostRegEx, "");
        }

// JM: not passing virtual pageviews through datalayer. Using native ga.
//        if (window.dataLayer) {
//            dataLayer.push({
//                'event': 'sendVirtualPageview',
//                'VirtualPageView': pv
//            });
//        } else
        if (window.ga) {
            ga('send', 'pageview', { page: pv });
        } else if (window._gaq) {
            _gaq.push(['_trackPageview', pv]);
        }

        if (window.dataLayer) {
            dataLayer.push({ event: "VirtualPageView" });
        }

        if (!ignoreNeolane) {
            // do the same for neolane
            submodule.createNeolaneTag(pv);
            lastTrackedPage = pv;
        }
    }

    var submodule = {
        trackPage: function (pageview, usePath, debounceTime) {
            if (debounceTime) {
                // rudimentary checker for setting the debounce time
                debounceTime = typeof debounceTime == "boolean" ? _debounceTime : (Number(debounceTime) || _debounceTime);

                clearTimeout(pageViewDebounceTimer);
                pageViewDebounceTimer = setTimeout(function () {
                    _trackPage(pageview, usePath);
                }, debounceTime);
            } else {
                _trackPage(pageview, usePath);
            }
        },
        trackEvent: function (category, action, label, value) {
            if (window.ga) {
                ga('send', 'event', category, action, label, value);
            } else if (window._gaq) {
                _gaq.push(['_trackEvent', category, action, label, value]);
            }
        },
        getLinkerUrl: function(url) {
            if (window.gaplugins && pageTracker) {
                var linker = new window.gaplugins.Linker(pageTracker);
                return linker.decorate(url);
            }

            return url;
        },
        getLinkerParam: function() {
            return pageTracker ? pageTracker.get('linkerParam') : "";
        },
        addTrans: function (id, affiliation, revenue, shipping, tax, currency) {
            if (window.ga) {
                /* ga('ecommerce:addTransaction', {
                     'id': '1234',                     // Transaction ID. Required.
                     'affiliation': 'Acme Clothing',   // Affiliation or store name.
                     'revenue': '11.99',               // Grand Total.
                     'shipping': '5',                  // Shipping.
                     'tax': '1.29',                    // Tax.
                     'currency' : 'EUR'
                 });*/
                ga('require', 'ecommerce', 'ecommerce.js');
                ga('ecommerce:addTransaction', { 'id': id, 'affiliation': affiliation, 'revenue': revenue, 'shipping': shipping, 'tax': tax, 'currency': currency });
            } else if (window._gaq) {
                /*  _gaq.push(['_addTrans',
                    '1234', // transaction ID - required
                    'Womens Apparel', // affiliation or store name
                    '28.28', // total - required; Shown as "Revenue" in the
                    // Transactions report. Does not include Tax and Shipping.
                    '1.29', // tax
                    '15.00', // shipping
                    'San Jose', // city
                    'California', // state or province
                    'USA'             // country
                ]);*/
                _gaq.push(['_addTrans', id, affiliation, revenue, tax, shipping, '', '']);
            }

        },
        addItem: function (id, name, sku, category, price, quantity, currency) {
            if (window.ga) {
                /*ga('ecommerce:addItem', {
                    'id': '1234',
                    'name': 'Fluffy Pink Bunnies',
                    'sku': 'DD23444',
                    'category': 'Party Toys',
                    'price': '11.99',
                    'quantity': '1',
                    'currency': 'GBP' // local currency code.
                });*/
                ga('ecommerce:addItem', { 'id': id, 'name': name, 'sku': sku, 'category': category, 'price': price, 'quantity': quantity, 'currency': currency });
            } else if (window._gaq) {
                /*_gaq.push(['_addItem',
                    '1234', // transaction ID - necessary to associate item with transaction
                    'DD44', // SKU/code - required
                    'T-Shirt', // product name - necessary to associate revenue with product
                    'Olive Medium', // category or variation
                    '11.99', // unit price - required
                    '1'             // quantity - required
                ]);*/
                _gaq.push(['_addItem', id, sku, name, category, price, quantity]);
            }
        },
        trackTrans: function () {
            if (window.ga) {
                ga('ecommerce:send');
            } else if (window._gaq) {
                _gaq.push(['_trackTrans']);
            }
        },
        getTracker: function () {
            return pageTracker;
        },
        setCustomVar: function (index, name, value, scope) {
            if (window.ga) {
            } else if (window._gaq) {
                //                _gaq.push(['_setCustomVar', 1, 'BookingDuration', '1', 3]);
                //                _gaq.push(['_setCustomVar', 2, 'BookingStayDate', '18/10/2013', 3]);
                //                _gaq.push(['_setCustomVar', 3, 'BookingPromoCode', 'NO CODE', 3]);
                _gaq.push(['_setCustomVar', index, name, value, scope]);
            }

        },
        createNeolaneTag: function (options) {
            /*
                options are:
                    path = (string) optional - unique identifier for the page. Default to current location path
                    // the next three are all optional, but should all be present if one is present.
                    amount = (int) optional - transaction amount
                    article = (int) optional - number of items in the transaction
                    id = (string) optional - transaction id 
            */


            var neoFolder = "nmsWebTracking",
                neoServers = ["//t.edev.roccofortehotels.com", "//t.e.roccofortehotels.com"],
                neoIsLive = /eqtr.com/i.test(location.host) ? 0 : 1,
                randomNumber = Math.random().toString(),
                neoTransationStr = '&amount={0}&article={1}&resConfNum={2}',
                neoTransaction = "",
                neoImgSrc = '{0}/r/{1}?tagid={2}|{3}|{4}{5}',
                neoType = "w",
                path;

            if (options) {
                if (typeof options == "string") {
                    path = options;
                } else {
                    path = options.path;

                    if (options.amount && options.article && options.id) {
                        neoTransaction = neoTransationStr.format(options.amount, options.article, options.id);
                        neoType = "t";
                    }
                }
            }

            // if there is no path use the location pathname
            if (!path) {
                path = location.pathname;
            }

            // push the path to lowercase (should be already)
            path = path.toLowerCase();


            // do some sanitisation on the path if necessary. The querystring needs to be less than 128 characters.
            // most urls should be, but am going to strip out some redundant namings
            if (!/^\/[a-z]{2}\//.test(path)) {
                path = "/en" + path;
            }

            // test for the home page
            if (/^\/[a-z]{2}\/$/.test(path)) {
                path += "home";
            }

            path = path.replace(/hotels\-and\-resorts\/(.)/, "$1").replace(/(^\/)|(\/$)/g, "");

            neoImgSrc = neoImgSrc.format(neoServers[neoIsLive], randomNumber, path, neoType, neoFolder, neoTransaction);
//            console.info(neoImgSrc);
            
            var neoImage = new Image();

            neoImage.src = neoImgSrc;

        }
    };

    module.Analytics = submodule;

    // get the tracker immediately because there are potentially race conditions formed between GTM and GA by pushing commands onto a stack.
    if (dataLayer) {
        dataLayer.push(function () {
            ga(function (tracker) {
                pageTracker = tracker;
            });
        });
    } else if (window.ga) {
        ga(function (tracker) {
            pageTracker = tracker;
        });
    }

    return module;
})(window.EQTR || {}, window.jQuery);;
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend(jQuery.easing,
{
    def: 'easeOutQuad',
    swing: function (x, t, b, c, d) {
        //alert(jQuery.easing.default);
        return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
    },
    easeInQuad: function (x, t, b, c, d) {
        return c * (t /= d) * t + b;
    },
    easeOutQuad: function (x, t, b, c, d) {
        return -c * (t /= d) * (t - 2) + b;
    },
    easeInOutQuad: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t + b;
        return -c / 2 * ((--t) * (t - 2) - 1) + b;
    },
    easeInCubic: function (x, t, b, c, d) {
        return c * (t /= d) * t * t + b;
    },
    easeOutCubic: function (x, t, b, c, d) {
        return c * ((t = t / d - 1) * t * t + 1) + b;
    },
    easeInOutCubic: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
        return c / 2 * ((t -= 2) * t * t + 2) + b;
    },
    easeInQuart: function (x, t, b, c, d) {
        return c * (t /= d) * t * t * t + b;
    },
    easeOutQuart: function (x, t, b, c, d) {
        return -c * ((t = t / d - 1) * t * t * t - 1) + b;
    },
    easeInOutQuart: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
        return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
    },
    easeInQuint: function (x, t, b, c, d) {
        return c * (t /= d) * t * t * t * t + b;
    },
    easeOutQuint: function (x, t, b, c, d) {
        return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
    },
    easeInOutQuint: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
        return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
    },
    easeInSine: function (x, t, b, c, d) {
        return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
    },
    easeOutSine: function (x, t, b, c, d) {
        return c * Math.sin(t / d * (Math.PI / 2)) + b;
    },
    easeInOutSine: function (x, t, b, c, d) {
        return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
    },
    easeInExpo: function (x, t, b, c, d) {
        return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
    },
    easeOutExpo: function (x, t, b, c, d) {
        return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
    },
    easeInOutExpo: function (x, t, b, c, d) {
        if (t == 0) return b;
        if (t == d) return b + c;
        if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
        return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
    },
    easeInCirc: function (x, t, b, c, d) {
        return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
    },
    easeOutCirc: function (x, t, b, c, d) {
        return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
    },
    easeInOutCirc: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
        return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
    },
    easeInElastic: function (x, t, b, c, d) {
        var s = 1.70158; var p = 0; var a = c;
        if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
        if (a < Math.abs(c)) { a = c; var s = p / 4; }
        else var s = p / (2 * Math.PI) * Math.asin(c / a);
        return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
    },
    easeOutElastic: function (x, t, b, c, d) {
        var s = 1.70158; var p = 0; var a = c;
        if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
        if (a < Math.abs(c)) { a = c; var s = p / 4; }
        else var s = p / (2 * Math.PI) * Math.asin(c / a);
        return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
    },
    easeInOutElastic: function (x, t, b, c, d) {
        var s = 1.70158; var p = 0; var a = c;
        if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5);
        if (a < Math.abs(c)) { a = c; var s = p / 4; }
        else var s = p / (2 * Math.PI) * Math.asin(c / a);
        if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
        return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
    },
    easeInBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c * (t /= d) * t * ((s + 1) * t - s) + b;
    },
    easeOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
    },
    easeInOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
        return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
    },
    easeInBounce: function (x, t, b, c, d) {
        return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b;
    },
    easeOutBounce: function (x, t, b, c, d) {
        if ((t /= d) < (1 / 2.75)) {
            return c * (7.5625 * t * t) + b;
        } else if (t < (2 / 2.75)) {
            return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
        } else if (t < (2.5 / 2.75)) {
            return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
        } else {
            return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
        }
    },
    easeInOutBounce: function (x, t, b, c, d) {
        if (t < d / 2) return jQuery.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b;
        return jQuery.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b;
    }
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */;
// outline.js
// based on http://www.paciellogroup.com/blog/2012/04/how-to-remove-css-outlines-in-an-accessible-manner/
(function (d) {

    var style_element = d.createElement('STYLE'),
	    dom_events = 'addEventListener' in d,
	    add_event_listener = function (type, callback) {
	        // Basic cross-browser event handling
	        if (dom_events) {
	            d.addEventListener(type, callback);
	        } else {
	            d.attachEvent('on' + type, callback);
	        }
	    },
	    set_css = function (css_text) {
	        // Handle setting of <style> element contents in IE8
	        !!style_element.styleSheet ? style_element.styleSheet.cssText = css_text : style_element.innerHTML = css_text;
	    }
    ;

    d.getElementsByTagName('HEAD')[0].appendChild(style_element);

    // Using mousedown instead of mouseover, so that previously focused elements don't lose focus ring on mouse move
    add_event_listener('mousedown', function () {
        set_css('a,button,select,textarea,input{outline:none}');
    });

    add_event_listener('keydown', function () {
        set_css('');
    });

})(document);;
(function ($) {

    /*  Vertically align elements inside their containers.
        Elements should probably be hidden via CSS until this function is complete.
        e.g 
        .element {
	        visibility:hidden;        
        }
        .valign {
	        visibility:visible;
        }
    */

    $.fn.valign = function (options) {
        var settings = $.extend({}, $.fn.valign.defaultOptions, options);

        return this.each(function () {
            var elem = $(this);
            elem.css(settings.style, "0");
            var container = elem.parent(),
                elemHeight = elem.outerHeight(),
                containerHeight = container.height(),
                topMargin = (containerHeight - elemHeight) / 2,
                spacingTop = settings.style;

            elem.css(spacingTop, Math.floor(topMargin)).addClass('valign');
        });

    };

    $.fn.valign.defaultOptions = {
        style: 'paddingTop'
    };

})(jQuery);;
/*!
 * hoverIntent v1.8.0 // 2014.06.29 // jQuery v1.9.1+
 * http://cherne.net/brian/resources/jquery.hoverIntent.html
 *
 * You may use hoverIntent under the terms of the MIT license. Basically that
 * means you are free to use hoverIntent as long as this header is left intact.
 * Copyright 2007, 2014 Brian Cherne
 */
(function ($) { $.fn.hoverIntent = function (handlerIn, handlerOut, selector) { var cfg = { interval: 100, sensitivity: 6, timeout: 0 }; if (typeof handlerIn === "object") { cfg = $.extend(cfg, handlerIn) } else { if ($.isFunction(handlerOut)) { cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector }) } else { cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut }) } } var cX, cY, pX, pY; var track = function (ev) { cX = ev.pageX; cY = ev.pageY }; var compare = function (ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); if (Math.sqrt((pX - cX) * (pX - cX) + (pY - cY) * (pY - cY)) < cfg.sensitivity) { $(ob).off("mousemove.hoverIntent", track); ob.hoverIntent_s = true; return cfg.over.apply(ob, [ev]) } else { pX = cX; pY = cY; ob.hoverIntent_t = setTimeout(function () { compare(ev, ob) }, cfg.interval) } }; var delay = function (ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = false; return cfg.out.apply(ob, [ev]) }; var handleHover = function (e) { var ev = $.extend({}, e); var ob = this; if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t) } if (e.type === "mouseenter") { pX = ev.pageX; pY = ev.pageY; $(ob).on("mousemove.hoverIntent", track); if (!ob.hoverIntent_s) { ob.hoverIntent_t = setTimeout(function () { compare(ev, ob) }, cfg.interval) } } else { $(ob).off("mousemove.hoverIntent", track); if (ob.hoverIntent_s) { ob.hoverIntent_t = setTimeout(function () { delay(ev, ob) }, cfg.timeout) } } }; return this.on({ "mouseenter.hoverIntent": handleHover, "mouseleave.hoverIntent": handleHover }, cfg.selector) } })(jQuery);;
/*! 
 * jquery.event.drag - v 2.2
 * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com
 * Open Source MIT License - http://threedubmedia.com/code/license
 */
// Created: 2008-06-04 
// Updated: 2012-05-21
// REQUIRES: jquery 1.7.x

;(function( $ ){

// add the jquery instance method
$.fn.drag = function( str, arg, opts ){
	// figure out the event type
	var type = typeof str == "string" ? str : "",
	// figure out the event handler...
	fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null;
	// fix the event type
	if ( type.indexOf("drag") !== 0 ) 
		type = "drag"+ type;
	// were options passed
	opts = ( str == fn ? arg : opts ) || {};
	// trigger or bind event handler
	return fn ? this.bind( type, opts, fn ) : this.trigger( type );
};

// local refs (increase compression)
var $event = $.event, 
$special = $event.special,
// configure the drag special event 
drag = $special.drag = {
	
	// these are the default settings
	defaults: {
		which: 1, // mouse button pressed to start drag sequence
		distance: 0, // distance dragged before dragstart
		not: ':input', // selector to suppress dragging on target elements
		handle: null, // selector to match handle target elements
		relative: false, // true to use "position", false to use "offset"
		drop: true, // false to suppress drop events, true or selector to allow
		click: false // false to suppress click events after dragend (no proxy)
	},
	
	// the key name for stored drag data
	datakey: "dragdata",
	
	// prevent bubbling for better performance
	noBubble: true,
	
	// count bound related events
	add: function( obj ){ 
		// read the interaction data
		var data = $.data( this, drag.datakey ),
		// read any passed options 
		opts = obj.data || {};
		// count another realted event
		data.related += 1;
		// extend data options bound with this event
		// don't iterate "opts" in case it is a node 
		$.each( drag.defaults, function( key, def ){
			if ( opts[ key ] !== undefined )
				data[ key ] = opts[ key ];
		});
	},
	
	// forget unbound related events
	remove: function(){
		$.data( this, drag.datakey ).related -= 1;
	},
	
	// configure interaction, capture settings
	setup: function(){
		// check for related events
		if ( $.data( this, drag.datakey ) ) 
			return;
		// initialize the drag data with copied defaults
		var data = $.extend({ related:0 }, drag.defaults );
		// store the interaction data
		$.data( this, drag.datakey, data );
		// bind the mousedown event, which starts drag interactions
		$event.add( this, "touchstart mousedown", drag.init, data );
		// prevent image dragging in IE...
		if ( this.attachEvent ) 
			this.attachEvent("ondragstart", drag.dontstart ); 
	},
	
	// destroy configured interaction
	teardown: function(){
		var data = $.data( this, drag.datakey ) || {};
		// check for related events
		if ( data.related ) 
			return;
		// remove the stored data
		$.removeData( this, drag.datakey );
		// remove the mousedown event
		$event.remove( this, "touchstart mousedown", drag.init );
		// enable text selection
		drag.textselect( true ); 
		// un-prevent image dragging in IE...
		if ( this.detachEvent ) 
			this.detachEvent("ondragstart", drag.dontstart ); 
	},
		
	// initialize the interaction
	init: function( event ){ 
		// sorry, only one touch at a time
		if ( drag.touched ) 
			return;
		// the drag/drop interaction data
		var dd = event.data, results;
		// check the which directive
		if ( event.which != 0 && dd.which > 0 && event.which != dd.which ) 
			return; 
		// check for suppressed selector
		if ( $( event.target ).is( dd.not ) ) 
			return;
		// check for handle selector
		if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length ) 
			return;

		drag.touched = event.type == 'touchstart' ? this : null;
		dd.propagates = 1;
		dd.mousedown = this;
		dd.interactions = [ drag.interaction( this, dd ) ];
		dd.target = event.target;
		dd.pageX = event.pageX;
		dd.pageY = event.pageY;
		dd.dragging = null;
		// handle draginit event... 
		results = drag.hijack( event, "draginit", dd );
		// early cancel
		if ( !dd.propagates )
			return;
		// flatten the result set
		results = drag.flatten( results );
		// insert new interaction elements
		if ( results && results.length ){
			dd.interactions = [];
			$.each( results, function(){
				dd.interactions.push( drag.interaction( this, dd ) );
			});
		}
		// remember how many interactions are propagating
		dd.propagates = dd.interactions.length;
		// locate and init the drop targets
		if ( dd.drop !== false && $special.drop ) 
			$special.drop.handler( event, dd );
		// disable text selection
		drag.textselect( false ); 
		// bind additional events...
		if ( drag.touched )
			$event.add( drag.touched, "touchmove touchend", drag.handler, dd );
		else 
			$event.add( document, "mousemove mouseup", drag.handler, dd );
	    // helps prevent text selection or scrolling
	    // JM: Removing this because it is stopping mousedown from propagating which is then breaking GTM auto tagging. 
        // JM: seems to be working and not selecting text or affecting scrolling
//		if ( !drag.touched || dd.live )
//			return false;
	},	
	
	// returns an interaction object
	interaction: function( elem, dd ){
		var offset = $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 };
		return {
			drag: elem, 
			callback: new drag.callback(), 
			droppable: [],
			offset: offset
		};
	},
	
	// handle drag-releatd DOM events
	handler: function( event ){ 
		// read the data before hijacking anything
		var dd = event.data;	
		// handle various events
		switch ( event.type ){
			// mousemove, check distance, start dragging
			case !dd.dragging && 'touchmove': 
				event.preventDefault();
			case !dd.dragging && 'mousemove':
				//  drag tolerance, x� + y� = distance�
				if ( Math.pow(  event.pageX-dd.pageX, 2 ) + Math.pow(  event.pageY-dd.pageY, 2 ) < Math.pow( dd.distance, 2 ) ) 
					break; // distance tolerance not reached
				event.target = dd.target; // force target from "mousedown" event (fix distance issue)
				drag.hijack( event, "dragstart", dd ); // trigger "dragstart"
				if ( dd.propagates ) // "dragstart" not rejected
					dd.dragging = true; // activate interaction
			// mousemove, dragging
			case 'touchmove':
				event.preventDefault();
			case 'mousemove':
				if ( dd.dragging ){
					// trigger "drag"		
					drag.hijack( event, "drag", dd );
					if ( dd.propagates ){
						// manage drop events
						if ( dd.drop !== false && $special.drop )
							$special.drop.handler( event, dd ); // "dropstart", "dropend"							
						break; // "drag" not rejected, stop		
					}
					event.type = "mouseup"; // helps "drop" handler behave
				}
			// mouseup, stop dragging
			case 'touchend': 
			case 'mouseup': 
			default:
				if ( drag.touched )
					$event.remove( drag.touched, "touchmove touchend", drag.handler ); // remove touch events
				else 
					$event.remove( document, "mousemove mouseup", drag.handler ); // remove page events	
				if ( dd.dragging ){
					if ( dd.drop !== false && $special.drop )
						$special.drop.handler( event, dd ); // "drop"
					drag.hijack( event, "dragend", dd ); // trigger "dragend"	
				}
				drag.textselect( true ); // enable text selection
				// if suppressing click events...
				if ( dd.click === false && dd.dragging )
					$.data( dd.mousedown, "suppress.click", new Date().getTime() + 5 );
				dd.dragging = drag.touched = false; // deactivate element	
				break;
		}
	},
		
	// re-use event object for custom events
	hijack: function( event, type, dd, x, elem ){
		// not configured
		if ( !dd ) 
			return;
		// remember the original event and type
		var orig = { event:event.originalEvent, type:event.type },
		// is the event drag related or drog related?
		mode = type.indexOf("drop") ? "drag" : "drop",
		// iteration vars
		result, i = x || 0, ia, $elems, callback,
		len = !isNaN( x ) ? x : dd.interactions.length;
		// modify the event type
		event.type = type;
		// remove the original event
		event.originalEvent = null;
		// initialize the results
		dd.results = [];
		// handle each interacted element
		do if ( ia = dd.interactions[ i ] ){
			// validate the interaction
			if ( type !== "dragend" && ia.cancelled )
				continue;
			// set the dragdrop properties on the event object
			callback = drag.properties( event, dd, ia );
			// prepare for more results
			ia.results = [];
			// handle each element
			$( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){
				// identify drag or drop targets individually
				callback.target = subject;
				// force propagtion of the custom event
				event.isPropagationStopped = function(){ return false; };
				// handle the event	
				result = subject ? $event.dispatch.call( subject, event, callback ) : null;
				// stop the drag interaction for this element
				if ( result === false ){
					if ( mode == "drag" ){
						ia.cancelled = true;
						dd.propagates -= 1;
					}
					if ( type == "drop" ){
						ia[ mode ][p] = null;
					}
				}
				// assign any dropinit elements
				else if ( type == "dropinit" )
					ia.droppable.push( drag.element( result ) || subject );
				// accept a returned proxy element 
				if ( type == "dragstart" )
					ia.proxy = $( drag.element( result ) || ia.drag )[0];
				// remember this result	
				ia.results.push( result );
				// forget the event result, for recycling
				delete event.result;
				// break on cancelled handler
				if ( type !== "dropinit" )
					return result;
			});	
			// flatten the results	
			dd.results[ i ] = drag.flatten( ia.results );	
			// accept a set of valid drop targets
			if ( type == "dropinit" )
				ia.droppable = drag.flatten( ia.droppable );
			// locate drop targets
			if ( type == "dragstart" && !ia.cancelled )
				callback.update(); 
		}
		while ( ++i < len )
		// restore the original event & type
		event.type = orig.type;
		event.originalEvent = orig.event;
		// return all handler results
		return drag.flatten( dd.results );
	},
		
	// extend the callback object with drag/drop properties...
	properties: function( event, dd, ia ){		
		var obj = ia.callback;
		// elements
		obj.drag = ia.drag;
		obj.proxy = ia.proxy || ia.drag;
		// starting mouse position
		obj.startX = dd.pageX;
		obj.startY = dd.pageY;
		// current distance dragged
		obj.deltaX = event.pageX - dd.pageX;
		obj.deltaY = event.pageY - dd.pageY;
		// original element position
		obj.originalX = ia.offset.left;
		obj.originalY = ia.offset.top;
		// adjusted element position
		obj.offsetX = obj.originalX + obj.deltaX; 
		obj.offsetY = obj.originalY + obj.deltaY;
		// assign the drop targets information
		obj.drop = drag.flatten( ( ia.drop || [] ).slice() );
		obj.available = drag.flatten( ( ia.droppable || [] ).slice() );
		return obj;	
	},
	
	// determine is the argument is an element or jquery instance
	element: function( arg ){
		if ( arg && ( arg.jquery || arg.nodeType == 1 ) )
			return arg;
	},
	
	// flatten nested jquery objects and arrays into a single dimension array
	flatten: function( arr ){
		return $.map( arr, function( member ){
			return member && member.jquery ? $.makeArray( member ) : 
				member && member.length ? drag.flatten( member ) : member;
		});
	},
	
	// toggles text selection attributes ON (true) or OFF (false)
	textselect: function( bool ){ 
		$( document )[ bool ? "unbind" : "bind" ]("selectstart", drag.dontstart )
			.css("MozUserSelect", bool ? "" : "none" );
		// .attr("unselectable", bool ? "off" : "on" )
		document.unselectable = bool ? "off" : "on"; 
	},
	
	// suppress "selectstart" and "ondragstart" events
	dontstart: function(){ 
		return false; 
	},
	
	// a callback instance contructor
	callback: function(){}
	
};

// callback methods
drag.callback.prototype = {
	update: function(){
		if ( $special.drop && this.available.length )
			$.each( this.available, function( i ){
				$special.drop.locate( this, i );
			});
	}
};

// patch $.event.$dispatch to allow suppressing clicks
var $dispatch = $event.dispatch;
$event.dispatch = function( event ){
	if ( $.data( this, "suppress."+ event.type ) - new Date().getTime() > 0 ){
		$.removeData( this, "suppress."+ event.type );
		return;
	}
	return $dispatch.apply( this, arguments );
};

// event fix hooks for touch events...
var touchHooks = 
$event.fixHooks.touchstart = 
$event.fixHooks.touchmove = 
$event.fixHooks.touchend =
$event.fixHooks.touchcancel = {
	props: "clientX clientY pageX pageY screenX screenY".split( " " ),
	filter: function( event, orig ) {
		if ( orig ){
			var touched = ( orig.touches && orig.touches[0] )
				|| ( orig.changedTouches && orig.changedTouches[0] )
				|| null; 
			// iOS webkit: touchstart, touchmove, touchend
			if ( touched ) 
				$.each( touchHooks.props, function( i, prop ){
					event[ prop ] = touched[ prop ];
				});
		}
		return event;
	}
};

// share the same special event configuration with related events...
$special.draginit = $special.dragstart = $special.dragend = drag;

})( jQuery );;
(function( $ ) {
	/**
	 * @attribute destroyed
	 * @parent specialevents
	 * @download  http://jmvcsite.heroku.com/pluginify?plugins[]=jquery/dom/destroyed/destroyed.js
	 * @test jquery/event/destroyed/qunit.html
	 * Provides a destroyed event on an element.
	 * <p>
	 * The destroyed event is called when the element
	 * is removed as a result of jQuery DOM manipulators like remove, html,
	 * replaceWith, etc. Destroyed events do not bubble, so make sure you don't use live or delegate with destroyed
	 * events.
	 * </p>
	 * <h2>Quick Example</h2>
	 * @codestart
	 * $(".foo").bind("destroyed", function(){
	 *    //clean up code
	 * })
	 * @codeend
	 * <h2>Quick Demo</h2>
	 * @demo jquery/event/destroyed/destroyed.html 
	 * <h2>More Involved Demo</h2>
	 * @demo jquery/event/destroyed/destroyed_menu.html 
	 */

	var oldClean = jQuery.cleanData;

	$.cleanData = function( elems ) {
		for ( var i = 0, elem;
		(elem = elems[i]) !== undefined; i++ ) {
			$(elem).triggerHandler("destroyed");
			//$.event.remove( elem, 'destroyed' );
		}
		oldClean(elems);
	};

})(jQuery);
/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version: 3.1.6
 *
 * Requires: jQuery 1.2.2+
 */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ('onwheel' in document || document.documentMode >= 9) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ($.event.fixHooks) {
        for (var i = toFix.length; i;) {
            $.event.fixHooks[toFix[--i]] = $.event.mouseHooks;
        }
    }

    $.event.special.mousewheel = {
        version: '3.1.6',

        setup: function () {
            if (this.addEventListener) {
                for (var i = toBind.length; i;) {
                    this.addEventListener(toBind[--i], handler, false);
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function () {
            if (this.removeEventListener) {
                for (var i = toBind.length; i;) {
                    this.removeEventListener(toBind[--i], handler, false);
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function (fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function (fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent = event || window.event,
            args = slice.call(arguments, 1),
            delta = 0,
            deltaX = 0,
            deltaY = 0,
            absDelta = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ('detail' in orgEvent) { deltaY = orgEvent.detail * -1; }
        if ('wheelDelta' in orgEvent) { deltaY = orgEvent.wheelDelta; }
        if ('wheelDeltaY' in orgEvent) { deltaY = orgEvent.wheelDeltaY; }
        if ('wheelDeltaX' in orgEvent) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ('axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ('deltaY' in orgEvent) {
            deltaY = orgEvent.deltaY * -1;
            delta = deltaY;
        }
        if ('deltaX' in orgEvent) {
            deltaX = orgEvent.deltaX;
            if (deltaY === 0) { delta = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if (deltaY === 0 && deltaX === 0) { return; }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max(Math.abs(deltaY), Math.abs(deltaX));
        if (!lowestDelta || absDelta < lowestDelta) {
            lowestDelta = absDelta;
        }

        // Get a whole, normalized value for the deltas
        delta = Math[delta >= 1 ? 'floor' : 'ceil'](delta / lowestDelta);
        deltaX = Math[deltaX >= 1 ? 'floor' : 'ceil'](deltaX / lowestDelta);
        deltaY = Math[deltaY >= 1 ? 'floor' : 'ceil'](deltaY / lowestDelta);

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

}));;
/* jquery.nicescroll
-- version 3.5.4
-- copyright 2013-11-13 InuYaksa*2013
-- licensed under the MIT
--
-- http://areaaperta.com/nicescroll
-- https://github.com/inuyaksa/jquery.nicescroll
--
*/

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals.
        factory(jQuery);
    }
}(function (jQuery) {

    // globals
    var domfocus = false;
    var mousefocus = false;
    var zoomactive = false;
    var tabindexcounter = 5000;
    var ascrailcounter = 2000;
    var globalmaxzindex = 0;

    var $ = jQuery;  // sandbox

    // http://stackoverflow.com/questions/2161159/get-script-path
    function getScriptPath() {
        var scripts = document.getElementsByTagName('script');
        var path = scripts[scripts.length - 1].src.split('?')[0];
        return (path.split('/').length > 0) ? path.split('/').slice(0, -1).join('/') + '/' : '';
    }
    //  var scriptpath = getScriptPath();

    var vendors = ['ms', 'moz', 'webkit', 'o'];

    var setAnimationFrame = window.requestAnimationFrame || false;
    var clearAnimationFrame = window.cancelAnimationFrame || false;

    if (!setAnimationFrame) {
        for (var vx in vendors) {
            var v = vendors[vx];
            if (!setAnimationFrame) setAnimationFrame = window[v + 'RequestAnimationFrame'];
            if (!clearAnimationFrame) clearAnimationFrame = window[v + 'CancelAnimationFrame'] || window[v + 'CancelRequestAnimationFrame'];
        }
    }

    var clsMutationObserver = window.MutationObserver || window.WebKitMutationObserver || false;

    var _globaloptions = {
        zindex: "auto",
        cursoropacitymin: 0,
        cursoropacitymax: 1,
        cursorcolor: "#424242",
        cursorwidth: "5px",
        cursorborder: "1px solid #fff",
        cursorborderradius: "5px",
        scrollspeed: 60,
        mousescrollstep: 8 * 3,
        touchbehavior: false,
        hwacceleration: true,
        usetransition: true,
        boxzoom: false,
        dblclickzoom: true,
        gesturezoom: true,
        grabcursorenabled: true,
        autohidemode: true,
        background: "",
        iframeautoresize: true,
        cursorminheight: 32,
        preservenativescrolling: true,
        railoffset: false,
        bouncescroll: true,
        spacebarenabled: true,
        railpadding: { top: 0, right: 0, left: 0, bottom: 0 },
        disableoutline: true,
        horizrailenabled: true,
        railalign: "right",
        railvalign: "bottom",
        enabletranslate3d: true,
        enablemousewheel: true,
        enablekeyboard: true,
        smoothscroll: true,
        sensitiverail: true,
        enablemouselockapi: true,
        //      cursormaxheight:false,
        cursorfixedheight: false,
        directionlockdeadzone: 6,
        hidecursordelay: 400,
        nativeparentscrolling: true,
        enablescrollonselection: true,
        overflowx: true,
        overflowy: true,
        cursordragspeed: 0.3,
        rtlmode: "auto",
        cursordragontouch: false,
        oneaxismousemode: "auto",
        scriptpath: getScriptPath()
    };

    var browserdetected = false;

    var getBrowserDetection = function () {

        if (browserdetected) return browserdetected;

        var domtest = document.createElement('DIV');

        var d = {};

        d.haspointerlock = "pointerLockElement" in document || "mozPointerLockElement" in document || "webkitPointerLockElement" in document;

        d.isopera = ("opera" in window);
        d.isopera12 = (d.isopera && ("getUserMedia" in navigator));
        d.isoperamini = (Object.prototype.toString.call(window.operamini) === "[object OperaMini]");

        d.isie = (("all" in document) && ("attachEvent" in domtest) && !d.isopera);
        d.isieold = (d.isie && !("msInterpolationMode" in domtest.style));  // IE6 and older
        d.isie7 = d.isie && !d.isieold && (!("documentMode" in document) || (document.documentMode == 7));
        d.isie8 = d.isie && ("documentMode" in document) && (document.documentMode == 8);
        d.isie9 = d.isie && ("performance" in window) && (document.documentMode >= 9);
        d.isie10 = d.isie && ("performance" in window) && (document.documentMode >= 10);

        d.isie9mobile = /iemobile.9/i.test(navigator.userAgent);  //wp 7.1 mango
        if (d.isie9mobile) d.isie9 = false;
        d.isie7mobile = (!d.isie9mobile && d.isie7) && /iemobile/i.test(navigator.userAgent);  //wp 7.0

        d.ismozilla = ("MozAppearance" in domtest.style);

        d.iswebkit = ("WebkitAppearance" in domtest.style);

        d.ischrome = ("chrome" in window);
        d.ischrome22 = (d.ischrome && d.haspointerlock);
        d.ischrome26 = (d.ischrome && ("transition" in domtest.style));  // issue with transform detection (maintain prefix)

        d.cantouch = ("ontouchstart" in document.documentElement) || ("ontouchstart" in window);  // detection for Chrome Touch Emulation
        d.hasmstouch = (window.navigator.msPointerEnabled || false);  // IE10+ pointer events

        d.ismac = /^mac$/i.test(navigator.platform);

        d.isios = (d.cantouch && /iphone|ipad|ipod/i.test(navigator.platform));
        d.isios4 = ((d.isios) && !("seal" in Object));

        d.isandroid = (/android/i.test(navigator.userAgent));

        d.trstyle = false;
        d.hastransform = false;
        d.hastranslate3d = false;
        d.transitionstyle = false;
        d.hastransition = false;
        d.transitionend = false;

        var check = ['transform', 'msTransform', 'webkitTransform', 'MozTransform', 'OTransform'];
        for (var a = 0; a < check.length; a++) {
            if (typeof domtest.style[check[a]] != "undefined") {
                d.trstyle = check[a];
                break;
            }
        }
        d.hastransform = (d.trstyle != false);
        if (d.hastransform) {
            domtest.style[d.trstyle] = "translate3d(1px,2px,3px)";
            d.hastranslate3d = /translate3d/.test(domtest.style[d.trstyle]);
        }

        d.transitionstyle = false;
        d.prefixstyle = '';
        d.transitionend = false;
        var check = ['transition', 'webkitTransition', 'MozTransition', 'OTransition', 'OTransition', 'msTransition', 'KhtmlTransition'];
        var prefix = ['', '-webkit-', '-moz-', '-o-', '-o', '-ms-', '-khtml-'];
        var evs = ['transitionend', 'webkitTransitionEnd', 'transitionend', 'otransitionend', 'oTransitionEnd', 'msTransitionEnd', 'KhtmlTransitionEnd'];
        for (var a = 0; a < check.length; a++) {
            if (check[a] in domtest.style) {
                d.transitionstyle = check[a];
                d.prefixstyle = prefix[a];
                d.transitionend = evs[a];
                break;
            }
        }
        if (d.ischrome26) {  // use always prefix
            d.prefixstyle = prefix[1];
        }

        d.hastransition = (d.transitionstyle);

        function detectCursorGrab() {
            var lst = ['-moz-grab', '-webkit-grab', 'grab'];
            if ((d.ischrome && !d.ischrome22) || d.isie) lst = [];  // force setting for IE returns false positive and chrome cursor bug
            for (var a = 0; a < lst.length; a++) {
                var p = lst[a];
                domtest.style['cursor'] = p;
                if (domtest.style['cursor'] == p) return p;
            }
            return 'url(http://www.google.com/intl/en_ALL/mapfiles/openhand.cur),n-resize';  // thank you google for custom cursor!
        }
        d.cursorgrabvalue = detectCursorGrab();

        d.hasmousecapture = ("setCapture" in domtest);

        d.hasMutationObserver = (clsMutationObserver !== false);

        domtest = null;  //memory released

        browserdetected = d;

        return d;
    };

    var NiceScrollClass = function (myopt, me) {

        var self = this;

        this.version = '3.5.4';
        this.name = 'nicescroll';

        this.me = me;

        this.opt = {
            doc: $("body"),
            win: false
        };

        $.extend(this.opt, _globaloptions);

        // Options for internal use
        this.opt.snapbackspeed = 80;

        if (myopt || false) {
            for (var a in self.opt) {
                if (typeof myopt[a] != "undefined") self.opt[a] = myopt[a];
            }
        }

        this.doc = self.opt.doc;
        this.iddoc = (this.doc && this.doc[0]) ? this.doc[0].id || '' : '';
        this.ispage = /^BODY|HTML/.test((self.opt.win) ? self.opt.win[0].nodeName : this.doc[0].nodeName);
        this.haswrapper = (self.opt.win !== false);
        this.win = self.opt.win || (this.ispage ? $(window) : this.doc);
        this.docscroll = (this.ispage && !this.haswrapper) ? $(window) : this.win;
        this.body = $("body");
        this.viewport = false;

        this.isfixed = false;

        this.iframe = false;
        this.isiframe = ((this.doc[0].nodeName == 'IFRAME') && (this.win[0].nodeName == 'IFRAME'));

        this.istextarea = (this.win[0].nodeName == 'TEXTAREA');

        this.forcescreen = false; //force to use screen position on events

        this.canshowonmouseevent = (self.opt.autohidemode != "scroll");

        // Events jump table    
        this.onmousedown = false;
        this.onmouseup = false;
        this.onmousemove = false;
        this.onmousewheel = false;
        this.onkeypress = false;
        this.ongesturezoom = false;
        this.onclick = false;

        // Nicescroll custom events
        this.onscrollstart = false;
        this.onscrollend = false;
        this.onscrollcancel = false;

        this.onzoomin = false;
        this.onzoomout = false;

        // Let's start!  
        this.view = false;
        this.page = false;

        this.scroll = { x: 0, y: 0 };
        this.scrollratio = { x: 0, y: 0 };
        this.cursorheight = 20;
        this.scrollvaluemax = 0;

        this.isrtlmode = false; //(this.opt.rtlmode=="auto") ? (this.win.css("direction")=="rtl") : (this.opt.rtlmode===true);
        //    this.checkrtlmode = false;

        this.scrollrunning = false;

        this.scrollmom = false;

        this.observer = false;
        this.observerremover = false;  // observer on parent for remove detection

        do {
            this.id = "ascrail" + (ascrailcounter++);
        } while (document.getElementById(this.id));

        this.rail = false;
        this.cursor = false;
        this.cursorfreezed = false;
        this.selectiondrag = false;

        this.zoom = false;
        this.zoomactive = false;

        this.hasfocus = false;
        this.hasmousefocus = false;

        this.visibility = true;
        this.locked = false;
        this.hidden = false; // rails always hidden
        this.cursoractive = true; // user can interact with cursors

        this.wheelprevented = false;  //prevent mousewheel event

        this.overflowx = self.opt.overflowx;
        this.overflowy = self.opt.overflowy;

        this.nativescrollingarea = false;
        this.checkarea = 0;

        this.events = [];  // event list for unbind

        this.saved = {};

        this.delaylist = {};
        this.synclist = {};

        this.lastdeltax = 0;
        this.lastdeltay = 0;

        this.detected = getBrowserDetection();

        var cap = $.extend({}, this.detected);

        this.canhwscroll = (cap.hastransform && self.opt.hwacceleration);
        this.ishwscroll = (this.canhwscroll && self.haswrapper);

        this.istouchcapable = false;  // desktop devices with touch screen support

        //## Check Chrome desktop with touch support
        if (cap.cantouch && cap.ischrome && !cap.isios && !cap.isandroid) {
            this.istouchcapable = true;
            cap.cantouch = false;  // parse normal desktop events
        }

        //## Firefox 18 nightly build (desktop) false positive (or desktop with touch support)
        if (cap.cantouch && cap.ismozilla && !cap.isios && !cap.isandroid) {
            this.istouchcapable = true;
            cap.cantouch = false;  // parse normal desktop events
        }

        //## disable MouseLock API on user request

        if (!self.opt.enablemouselockapi) {
            cap.hasmousecapture = false;
            cap.haspointerlock = false;
        }

        this.delayed = function (name, fn, tm, lazy) {
            var dd = self.delaylist[name];
            var nw = (new Date()).getTime();
            if (!lazy && dd && dd.tt) return false;
            if (dd && dd.tt) clearTimeout(dd.tt);
            if (dd && dd.last + tm > nw && !dd.tt) {
                self.delaylist[name] = {
                    last: nw + tm,
                    tt: setTimeout(function () { if (self || false) { self.delaylist[name].tt = 0; fn.call() } }, tm)
                }
            }
            else if (!dd || !dd.tt) {
                self.delaylist[name] = {
                    last: nw,
                    tt: 0
                };
                setTimeout(function () { fn.call(); }, 0);
            }
        };

        this.debounced = function (name, fn, tm) {
            var dd = self.delaylist[name];
            var nw = (new Date()).getTime();
            self.delaylist[name] = fn;
            if (!dd) {
                setTimeout(function () { var fn = self.delaylist[name]; self.delaylist[name] = false; fn.call(); }, tm);
            }
        };

        var _onsync = false;

        this.synched = function (name, fn) {

            function requestSync() {
                if (_onsync) return;
                setAnimationFrame(function () {
                    _onsync = false;
                    for (name in self.synclist) {
                        var fn = self.synclist[name];
                        if (fn) fn.call(self);
                        self.synclist[name] = false;
                    }
                });
                _onsync = true;
            };

            self.synclist[name] = fn;
            requestSync();
            return name;
        };

        this.unsynched = function (name) {
            if (self.synclist[name]) self.synclist[name] = false;
        };

        this.css = function (el, pars) {  // save & set
            for (var n in pars) {
                self.saved.css.push([el, n, el.css(n)]);
                el.css(n, pars[n]);
            }
        };

        this.scrollTop = function (val) {
            return (typeof val == "undefined") ? self.getScrollTop() : self.setScrollTop(val);
        };

        this.scrollLeft = function (val) {
            return (typeof val == "undefined") ? self.getScrollLeft() : self.setScrollLeft(val);
        };

        // derived by by Dan Pupius www.pupius.net
        BezierClass = function (st, ed, spd, p1, p2, p3, p4) {
            this.st = st;
            this.ed = ed;
            this.spd = spd;

            this.p1 = p1 || 0;
            this.p2 = p2 || 1;
            this.p3 = p3 || 0;
            this.p4 = p4 || 1;

            this.ts = (new Date()).getTime();
            this.df = this.ed - this.st;
        };
        BezierClass.prototype = {
            B2: function (t) { return 3 * t * t * (1 - t) },
            B3: function (t) { return 3 * t * (1 - t) * (1 - t) },
            B4: function (t) { return (1 - t) * (1 - t) * (1 - t) },
            getNow: function () {
                var nw = (new Date()).getTime();
                var pc = 1 - ((nw - this.ts) / this.spd);
                var bz = this.B2(pc) + this.B3(pc) + this.B4(pc);
                return (pc < 0) ? this.ed : this.st + Math.round(this.df * bz);
            },
            update: function (ed, spd) {
                this.st = this.getNow();
                this.ed = ed;
                this.spd = spd;
                this.ts = (new Date()).getTime();
                this.df = this.ed - this.st;
                return this;
            }
        };

        if (this.ishwscroll) {
            // hw accelerated scroll
            this.doc.translate = { x: 0, y: 0, tx: "0px", ty: "0px" };

            //this one can help to enable hw accel on ios6 http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/
            if (cap.hastranslate3d && cap.isios) this.doc.css("-webkit-backface-visibility", "hidden");  // prevent flickering http://stackoverflow.com/questions/3461441/      

            //derived from http://stackoverflow.com/questions/11236090/
            function getMatrixValues() {
                var tr = self.doc.css(cap.trstyle);
                if (tr && (tr.substr(0, 6) == "matrix")) {
                    return tr.replace(/^.*\((.*)\)$/g, "$1").replace(/px/g, '').split(/, +/);
                }
                return false;
            }

            this.getScrollTop = function (last) {
                if (!last) {
                    var mtx = getMatrixValues();
                    if (mtx) return (mtx.length == 16) ? -mtx[13] : -mtx[5];  //matrix3d 16 on IE10
                    if (self.timerscroll && self.timerscroll.bz) return self.timerscroll.bz.getNow();
                }
                return self.doc.translate.y;
            };

            this.getScrollLeft = function (last) {
                if (!last) {
                    var mtx = getMatrixValues();
                    if (mtx) return (mtx.length == 16) ? -mtx[12] : -mtx[4];  //matrix3d 16 on IE10
                    if (self.timerscroll && self.timerscroll.bh) return self.timerscroll.bh.getNow();
                }
                return self.doc.translate.x;
            };

            if (document.createEvent) {
                this.notifyScrollEvent = function (el) {
                    var e = document.createEvent("UIEvents");
                    e.initUIEvent("scroll", false, true, window, 1);
                    el.dispatchEvent(e);
                };
            }
            else if (document.fireEvent) {
                this.notifyScrollEvent = function (el) {
                    var e = document.createEventObject();
                    el.fireEvent("onscroll");
                    e.cancelBubble = true;
                };
            }
            else {
                this.notifyScrollEvent = function (el, add) { }; //NOPE
            }

            var cxscrollleft = -1; //(this.isrtlmode) ? 1 : -1;

            if (cap.hastranslate3d && self.opt.enabletranslate3d) {
                this.setScrollTop = function (val, silent) {
                    self.doc.translate.y = val;
                    self.doc.translate.ty = (val * -1) + "px";
                    self.doc.css(cap.trstyle, "translate3d(" + self.doc.translate.tx + "," + self.doc.translate.ty + ",0px)");
                    if (!silent) self.notifyScrollEvent(self.win[0]);
                };
                this.setScrollLeft = function (val, silent) {
                    self.doc.translate.x = val;
                    self.doc.translate.tx = (val * cxscrollleft) + "px";
                    self.doc.css(cap.trstyle, "translate3d(" + self.doc.translate.tx + "," + self.doc.translate.ty + ",0px)");
                    if (!silent) self.notifyScrollEvent(self.win[0]);
                };
            } else {
                this.setScrollTop = function (val, silent) {
                    self.doc.translate.y = val;
                    self.doc.translate.ty = (val * -1) + "px";
                    self.doc.css(cap.trstyle, "translate(" + self.doc.translate.tx + "," + self.doc.translate.ty + ")");
                    if (!silent) self.notifyScrollEvent(self.win[0]);
                };
                this.setScrollLeft = function (val, silent) {
                    self.doc.translate.x = val;
                    self.doc.translate.tx = (val * cxscrollleft) + "px";
                    self.doc.css(cap.trstyle, "translate(" + self.doc.translate.tx + "," + self.doc.translate.ty + ")");
                    if (!silent) self.notifyScrollEvent(self.win[0]);
                };
            }
        } else {
            // native scroll
            this.getScrollTop = function () {
                return self.docscroll.scrollTop();
            };
            this.setScrollTop = function (val) {
                return self.docscroll.scrollTop(val);
            };
            this.getScrollLeft = function () {
                return self.docscroll.scrollLeft();
            };
            this.setScrollLeft = function (val) {
                return self.docscroll.scrollLeft(val);
            };
        }

        this.getTarget = function (e) {
            if (!e) return false;
            if (e.target) return e.target;
            if (e.srcElement) return e.srcElement;
            return false;
        };

        this.hasParent = function (e, id) {
            if (!e) return false;
            var el = e.target || e.srcElement || e || false;
            while (el && el.id != id) {
                el = el.parentNode || false;
            }
            return (el !== false);
        };

        function getZIndex() {
            var dom = self.win;
            if ("zIndex" in dom) return dom.zIndex();  // use jQuery UI method when available
            while (dom.length > 0) {
                if (dom[0].nodeType == 9) return false;
                var zi = dom.css('zIndex');
                if (!isNaN(zi) && zi != 0) return parseInt(zi);
                dom = dom.parent();
            }
            return false;
        };

        //inspired by http://forum.jquery.com/topic/width-includes-border-width-when-set-to-thin-medium-thick-in-ie
        var _convertBorderWidth = { "thin": 1, "medium": 3, "thick": 5 };
        function getWidthToPixel(dom, prop, chkheight) {
            var wd = dom.css(prop);
            var px = parseFloat(wd);
            if (isNaN(px)) {
                px = _convertBorderWidth[wd] || 0;
                var brd = (px == 3) ? ((chkheight) ? (self.win.outerHeight() - self.win.innerHeight()) : (self.win.outerWidth() - self.win.innerWidth())) : 1; //DON'T TRUST CSS
                if (self.isie8 && px) px += 1;
                return (brd) ? px : 0;
            }
            return px;
        };

        this.getOffset = function () {
            if (self.isfixed) return { top: parseFloat(self.win.css('top')), left: parseFloat(self.win.css('left')) };
            if (!self.viewport) return self.win.offset();
            var ww = self.win.offset();
            var vp = self.viewport.offset();
            return { top: ww.top - vp.top + self.viewport.scrollTop(), left: ww.left - vp.left + self.viewport.scrollLeft() };
        };

        this.updateScrollBar = function (len) {
            if (self.ishwscroll) {
                self.rail.css({ height: self.win.innerHeight() });
                if (self.railh) self.railh.css({ width: self.win.innerWidth() });
            } else {
                var wpos = self.getOffset();
                var pos = { top: wpos.top, left: wpos.left };
                pos.top += getWidthToPixel(self.win, 'border-top-width', true);
                var brd = (self.win.outerWidth() - self.win.innerWidth()) / 2;
                pos.left += (self.rail.align) ? self.win.outerWidth() - getWidthToPixel(self.win, 'border-right-width') - self.rail.width : getWidthToPixel(self.win, 'border-left-width');

                var off = self.opt.railoffset;
                if (off) {
                    if (off.top) pos.top += off.top;
                    if (self.rail.align && off.left) pos.left += off.left;
                }

                if (!self.locked) self.rail.css({ top: pos.top, left: pos.left, height: (len) ? len.h : self.win.innerHeight() });

                if (self.zoom) {
                    self.zoom.css({ top: pos.top + 1, left: (self.rail.align == 1) ? pos.left - 20 : pos.left + self.rail.width + 4 });
                }

                if (self.railh && !self.locked) {
                    var pos = { top: wpos.top, left: wpos.left };
                    var y = (self.railh.align) ? pos.top + getWidthToPixel(self.win, 'border-top-width', true) + self.win.innerHeight() - self.railh.height : pos.top + getWidthToPixel(self.win, 'border-top-width', true);
                    var x = pos.left + getWidthToPixel(self.win, 'border-left-width');
                    self.railh.css({ top: y, left: x, width: self.railh.width });
                }


            }
        };

        this.doRailClick = function (e, dbl, hr) {

            var fn, pg, cur, pos;

            //      if (self.rail.drag&&self.rail.drag.pt!=1) return;
            if (self.locked) return;
            //      if (self.rail.drag) return;

            //      self.cancelScroll();       

            self.cancelEvent(e);

            if (dbl) {
                fn = (hr) ? self.doScrollLeft : self.doScrollTop;
                cur = (hr) ? ((e.pageX - self.railh.offset().left - (self.cursorwidth / 2)) * self.scrollratio.x) : ((e.pageY - self.rail.offset().top - (self.cursorheight / 2)) * self.scrollratio.y);
                fn(cur);
            } else {
                fn = (hr) ? self.doScrollLeftBy : self.doScrollBy;
                cur = (hr) ? self.scroll.x : self.scroll.y;
                pos = (hr) ? e.pageX - self.railh.offset().left : e.pageY - self.rail.offset().top;
                pg = (hr) ? self.view.w : self.view.h;
                (cur >= pos) ? fn(pg) : fn(-pg);
            }

        };

        self.hasanimationframe = (setAnimationFrame);
        self.hascancelanimationframe = (clearAnimationFrame);

        if (!self.hasanimationframe) {
            setAnimationFrame = function (fn) { return setTimeout(fn, 15 - Math.floor((+new Date) / 1000) % 16) }; // 1000/60)};
            clearAnimationFrame = clearInterval;
        }
        else if (!self.hascancelanimationframe) clearAnimationFrame = function () { self.cancelAnimationFrame = true };

        this.init = function () {

            self.saved.css = [];

            if (cap.isie7mobile) return true; // SORRY, DO NOT WORK!
            if (cap.isoperamini) return true; // SORRY, DO NOT WORK!

            if (cap.hasmstouch) self.css((self.ispage) ? $("html") : self.win, { '-ms-touch-action': 'none' });

            self.zindex = "auto";
            if (!self.ispage && self.opt.zindex == "auto") {
                self.zindex = getZIndex() || "auto";
            } else {
                self.zindex = self.opt.zindex;
            }

            if (!self.ispage && self.zindex != "auto") {
                if (self.zindex > globalmaxzindex) globalmaxzindex = self.zindex;
            }

            if (self.isie && self.zindex == 0 && self.opt.zindex == "auto") {  // fix IE auto == 0
                self.zindex = "auto";
            }

            /*      
                  self.ispage = true;
                  self.haswrapper = true;
            //      self.win = $(window);
                  self.docscroll = $("body");
            //      self.doc = $("body");
            */

            if (!self.ispage || (!cap.cantouch && !cap.isieold && !cap.isie9mobile)) {

                var cont = self.docscroll;
                if (self.ispage) cont = (self.haswrapper) ? self.win : self.doc;

                if (!cap.isie9mobile) self.css(cont, { 'overflow-y': 'hidden' });

                if (self.ispage && cap.isie7) {
                    if (self.doc[0].nodeName == 'BODY') self.css($("html"), { 'overflow-y': 'hidden' });  //IE7 double scrollbar issue
                    else if (self.doc[0].nodeName == 'HTML') self.css($("body"), { 'overflow-y': 'hidden' });  //IE7 double scrollbar issue
                }

                //if (cap.isios && !self.ispage && !self.haswrapper) self.css($("body"), { "-webkit-overflow-scrolling": "touch" });  //force hw acceleration

                var cursor = $(document.createElement('div'));
                cursor.css({
                    position: "relative", top: 0, "float": "right", width: self.opt.cursorwidth, height: "0px",
                    'background-color': self.opt.cursorcolor,
                    border: self.opt.cursorborder,
                    'background-clip': 'padding-box',
                    '-webkit-border-radius': self.opt.cursorborderradius,
                    '-moz-border-radius': self.opt.cursorborderradius,
                    'border-radius': self.opt.cursorborderradius
                });

                cursor.hborder = parseFloat(cursor.outerHeight() - cursor.innerHeight());
                self.cursor = cursor;

                var rail = $(document.createElement('div'));
                rail.attr('id', self.id);
                rail.addClass('nicescroll-rails');

                var v, a, kp = ["left", "right"];  //"top","bottom"
                for (var n in kp) {
                    a = kp[n];
                    v = self.opt.railpadding[a];
                    (v) ? rail.css("padding-" + a, v + "px") : self.opt.railpadding[a] = 0;
                }

                rail.append(cursor);

                rail.width = Math.max(parseFloat(self.opt.cursorwidth), cursor.outerWidth()) + self.opt.railpadding['left'] + self.opt.railpadding['right'];
                rail.css({ width: rail.width + "px", 'zIndex': self.zindex, "background": self.opt.background, cursor: "default" });

                rail.visibility = true;
                rail.scrollable = true;

                rail.align = (self.opt.railalign == "left") ? 0 : 1;

                self.rail = rail;

                self.rail.drag = false;

                var zoom = false;
                if (self.opt.boxzoom && !self.ispage && !cap.isieold) {
                    zoom = document.createElement('div');
                    self.bind(zoom, "click", self.doZoom);
                    self.zoom = $(zoom);
                    self.zoom.css({ "cursor": "pointer", 'z-index': self.zindex, 'backgroundImage': 'url(' + self.opt.scriptpath + 'zoomico.png)', 'height': 18, 'width': 18, 'backgroundPosition': '0px 0px' });
                    if (self.opt.dblclickzoom) self.bind(self.win, "dblclick", self.doZoom);
                    if (cap.cantouch && self.opt.gesturezoom) {
                        self.ongesturezoom = function (e) {
                            if (e.scale > 1.5) self.doZoomIn(e);
                            if (e.scale < 0.8) self.doZoomOut(e);
                            return self.cancelEvent(e);
                        };
                        self.bind(self.win, "gestureend", self.ongesturezoom);
                    }
                }

                // init HORIZ

                self.railh = false;

                if (self.opt.horizrailenabled) {

                    self.css(cont, { 'overflow-x': 'hidden' });

                    var cursor = $(document.createElement('div'));
                    cursor.css({
                        position: "relative", top: 0, height: self.opt.cursorwidth, width: "0px",
                        'background-color': self.opt.cursorcolor,
                        border: self.opt.cursorborder,
                        'background-clip': 'padding-box',
                        '-webkit-border-radius': self.opt.cursorborderradius,
                        '-moz-border-radius': self.opt.cursorborderradius,
                        'border-radius': self.opt.cursorborderradius
                    });

                    cursor.wborder = parseFloat(cursor.outerWidth() - cursor.innerWidth());
                    self.cursorh = cursor;

                    var railh = $(document.createElement('div'));
                    railh.attr('id', self.id + '-hr');
                    railh.addClass('nicescroll-rails');
                    railh.height = Math.max(parseFloat(self.opt.cursorwidth), cursor.outerHeight());
                    railh.css({ height: railh.height + "px", 'zIndex': self.zindex, "background": self.opt.background });

                    railh.append(cursor);

                    railh.visibility = true;
                    railh.scrollable = true;

                    railh.align = (self.opt.railvalign == "top") ? 0 : 1;

                    self.railh = railh;

                    self.railh.drag = false;

                }

                //        

                if (self.ispage) {
                    rail.css({ position: "fixed", top: "0px", height: "100%" });
                    (rail.align) ? rail.css({ right: "0px" }) : rail.css({ left: "0px" });
                    self.body.append(rail);
                    if (self.railh) {
                        railh.css({ position: "fixed", left: "0px", width: "100%" });
                        (railh.align) ? railh.css({ bottom: "0px" }) : railh.css({ top: "0px" });
                        self.body.append(railh);
                    }
                } else {
                    if (self.ishwscroll) {
                        if (self.win.css('position') == 'static') self.css(self.win, { 'position': 'relative' });
                        var bd = (self.win[0].nodeName == 'HTML') ? self.body : self.win;
                        if (self.zoom) {
                            self.zoom.css({ position: "absolute", top: 1, right: 0, "margin-right": rail.width + 4 });
                            bd.append(self.zoom);
                        }
                        rail.css({ position: "absolute", top: 0 });
                        (rail.align) ? rail.css({ right: 0 }) : rail.css({ left: 0 });
                        bd.append(rail);
                        if (railh) {
                            railh.css({ position: "absolute", left: 0, bottom: 0 });
                            (railh.align) ? railh.css({ bottom: 0 }) : railh.css({ top: 0 });
                            bd.append(railh);
                        }
                    } else {
                        self.isfixed = (self.win.css("position") == "fixed");
                        var rlpos = (self.isfixed) ? "fixed" : "absolute";

                        if (!self.isfixed) self.viewport = self.getViewport(self.win[0]);
                        if (self.viewport) {
                            self.body = self.viewport;
                            if ((/fixed|relative|absolute/.test(self.viewport.css("position"))) == false) self.css(self.viewport, { "position": "relative" });
                        }

                        rail.css({ position: rlpos });
                        if (self.zoom) self.zoom.css({ position: rlpos });
                        self.updateScrollBar();
                        self.body.append(rail);
                        if (self.zoom) self.body.append(self.zoom);
                        if (self.railh) {
                            railh.css({ position: rlpos });
                            self.body.append(railh);
                        }
                    }

                    if (cap.isios) self.css(self.win, { '-webkit-tap-highlight-color': 'rgba(0,0,0,0)', '-webkit-touch-callout': 'none' });  // prevent grey layer on click

                    if (cap.isie && self.opt.disableoutline) self.win.attr("hideFocus", "true");  // IE, prevent dotted rectangle on focused div
                    if (cap.iswebkit && self.opt.disableoutline) self.win.css({ "outline": "none" });
                    //          if (cap.isopera&&self.opt.disableoutline) self.win.css({"outline":"0"});  // Opera to test [TODO]

                }

                if (self.opt.autohidemode === false) {
                    self.autohidedom = false;
                    self.rail.css({ opacity: self.opt.cursoropacitymax });
                    if (self.railh) self.railh.css({ opacity: self.opt.cursoropacitymax });
                }
                else if ((self.opt.autohidemode === true) || (self.opt.autohidemode === "leave")) {
                    self.autohidedom = $().add(self.rail);
                    if (cap.isie8) self.autohidedom = self.autohidedom.add(self.cursor);
                    if (self.railh) self.autohidedom = self.autohidedom.add(self.railh);
                    if (self.railh && cap.isie8) self.autohidedom = self.autohidedom.add(self.cursorh);
                }
                else if (self.opt.autohidemode == "scroll") {
                    self.autohidedom = $().add(self.rail);
                    if (self.railh) self.autohidedom = self.autohidedom.add(self.railh);
                }
                else if (self.opt.autohidemode == "cursor") {
                    self.autohidedom = $().add(self.cursor);
                    if (self.railh) self.autohidedom = self.autohidedom.add(self.cursorh);
                }
                else if (self.opt.autohidemode == "hidden") {
                    self.autohidedom = false;
                    self.hide();
                    self.locked = false;
                }

                if (cap.isie9mobile) {

                    self.scrollmom = new ScrollMomentumClass2D(self);

                    /*
                    var trace = function(msg) {
                      var db = $("#debug");
                      if (isNaN(msg)&&(typeof msg != "string")) {
                        var x = [];
                        for(var a in msg) {
                          x.push(a+":"+msg[a]);
                        }
                        msg ="{"+x.join(",")+"}";
                      }
                      if (db.children().length>0) {
                        db.children().eq(0).before("<div>"+msg+"</div>");
                      } else {
                        db.append("<div>"+msg+"</div>");
                      }
                    }
                    window.onerror = function(msg,url,ln) {
                      trace("ERR: "+msg+" at "+ln);
                    }
          */

                    self.onmangotouch = function (e) {
                        var py = self.getScrollTop();
                        var px = self.getScrollLeft();

                        if ((py == self.scrollmom.lastscrolly) && (px == self.scrollmom.lastscrollx)) return true;
                        //            $("#debug").html('DRAG:'+py);

                        var dfy = py - self.mangotouch.sy;
                        var dfx = px - self.mangotouch.sx;
                        var df = Math.round(Math.sqrt(Math.pow(dfx, 2) + Math.pow(dfy, 2)));
                        if (df == 0) return;

                        var dry = (dfy < 0) ? -1 : 1;
                        var drx = (dfx < 0) ? -1 : 1;

                        var tm = +new Date();
                        if (self.mangotouch.lazy) clearTimeout(self.mangotouch.lazy);

                        if (((tm - self.mangotouch.tm) > 80) || (self.mangotouch.dry != dry) || (self.mangotouch.drx != drx)) {
                            //              trace('RESET+'+(tm-self.mangotouch.tm));
                            self.scrollmom.stop();
                            self.scrollmom.reset(px, py);
                            self.mangotouch.sy = py;
                            self.mangotouch.ly = py;
                            self.mangotouch.sx = px;
                            self.mangotouch.lx = px;
                            self.mangotouch.dry = dry;
                            self.mangotouch.drx = drx;
                            self.mangotouch.tm = tm;
                        } else {

                            self.scrollmom.stop();
                            self.scrollmom.update(self.mangotouch.sx - dfx, self.mangotouch.sy - dfy);
                            var gap = tm - self.mangotouch.tm;
                            self.mangotouch.tm = tm;

                            //              trace('MOVE:'+df+" - "+gap);

                            var ds = Math.max(Math.abs(self.mangotouch.ly - py), Math.abs(self.mangotouch.lx - px));
                            self.mangotouch.ly = py;
                            self.mangotouch.lx = px;

                            if (ds > 2) {
                                self.mangotouch.lazy = setTimeout(function () {
                                    //                  trace('END:'+ds+'+'+gap);                  
                                    self.mangotouch.lazy = false;
                                    self.mangotouch.dry = 0;
                                    self.mangotouch.drx = 0;
                                    self.mangotouch.tm = 0;
                                    self.scrollmom.doMomentum(30);
                                }, 100);
                            }
                        }
                    };

                    var top = self.getScrollTop();
                    var lef = self.getScrollLeft();
                    self.mangotouch = { sy: top, ly: top, dry: 0, sx: lef, lx: lef, drx: 0, lazy: false, tm: 0 };

                    self.bind(self.docscroll, "scroll", self.onmangotouch);

                } else {

                    if (cap.cantouch || self.istouchcapable || self.opt.touchbehavior || cap.hasmstouch) {

                        self.scrollmom = new ScrollMomentumClass2D(self);

                        self.ontouchstart = function (e) {
                            if (e.pointerType && e.pointerType != 2) return false;

                            self.hasmoving = false;

                            if (!self.locked) {

                                if (cap.hasmstouch) {
                                    var tg = (e.target) ? e.target : false;
                                    while (tg) {
                                        var nc = $(tg).getNiceScroll();
                                        if ((nc.length > 0) && (nc[0].me == self.me)) break;
                                        if (nc.length > 0) return false;
                                        if ((tg.nodeName == 'DIV') && (tg.id == self.id)) break;
                                        tg = (tg.parentNode) ? tg.parentNode : false;
                                    }
                                }

                                self.cancelScroll();

                                var tg = self.getTarget(e);

                                if (tg) {
                                    var skp = (/INPUT/i.test(tg.nodeName)) && (/range/i.test(tg.type));
                                    if (skp) return self.stopPropagation(e);
                                }

                                if (!("clientX" in e) && ("changedTouches" in e)) {
                                    e.clientX = e.changedTouches[0].clientX;
                                    e.clientY = e.changedTouches[0].clientY;
                                }

                                if (self.forcescreen) {
                                    var le = e;
                                    var e = { "original": (e.original) ? e.original : e };
                                    e.clientX = le.screenX;
                                    e.clientY = le.screenY;
                                }

                                self.rail.drag = { x: e.clientX, y: e.clientY, sx: self.scroll.x, sy: self.scroll.y, st: self.getScrollTop(), sl: self.getScrollLeft(), pt: 2, dl: false };

                                if (self.ispage || !self.opt.directionlockdeadzone) {
                                    self.rail.drag.dl = "f";
                                } else {

                                    var view = {
                                        w: $(window).width(),
                                        h: $(window).height()
                                    };

                                    var page = {
                                        w: Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
                                        h: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
                                    };

                                    var maxh = Math.max(0, page.h - view.h);
                                    var maxw = Math.max(0, page.w - view.w);

                                    if (!self.rail.scrollable && self.railh.scrollable) self.rail.drag.ck = (maxh > 0) ? "v" : false;
                                    else if (self.rail.scrollable && !self.railh.scrollable) self.rail.drag.ck = (maxw > 0) ? "h" : false;
                                    else self.rail.drag.ck = false;
                                    if (!self.rail.drag.ck) self.rail.drag.dl = "f";
                                }

                                if (self.opt.touchbehavior && self.isiframe && cap.isie) {
                                    var wp = self.win.position();
                                    self.rail.drag.x += wp.left;
                                    self.rail.drag.y += wp.top;
                                }

                                self.hasmoving = false;
                                self.lastmouseup = false;
                                self.scrollmom.reset(e.clientX, e.clientY);
                                if (!cap.cantouch && !this.istouchcapable && !cap.hasmstouch) {

                                    var ip = (tg) ? /INPUT|SELECT|TEXTAREA/i.test(tg.nodeName) : false;
                                    if (!ip) {
                                        if (!self.ispage && cap.hasmousecapture) tg.setCapture();

                                        if (self.opt.touchbehavior) {
                                            if (tg.onclick && !(tg._onclick || false)) {  // intercept DOM0 onclick event
                                                tg._onclick = tg.onclick;
                                                tg.onclick = function (e) {
                                                    if (self.hasmoving) return false;
                                                    tg._onclick.call(this, e);
                                                }
                                            }
                                            return self.cancelEvent(e);
                                        }

                                        return self.stopPropagation(e);
                                    }

                                    if (/SUBMIT|CANCEL|BUTTON/i.test($(tg).attr('type'))) {
                                        pc = { "tg": tg, "click": false };
                                        self.preventclick = pc;
                                    }

                                }
                            }

                        };

                        self.ontouchend = function (e) {
                            if (e.pointerType && e.pointerType != 2) return false;
                            if (self.rail.drag && (self.rail.drag.pt == 2)) {
                                self.scrollmom.doMomentum();
                                self.rail.drag = false;
                                if (self.hasmoving) {
                                    self.lastmouseup = true;
                                    self.hideCursor();
                                    if (cap.hasmousecapture) document.releaseCapture();
                                    if (!cap.cantouch) return self.cancelEvent(e);
                                }
                            }

                        };

                        var moveneedoffset = (self.opt.touchbehavior && self.isiframe && !cap.hasmousecapture);

                        self.ontouchmove = function (e, byiframe) {

                            if (e.pointerType && e.pointerType != 2) return false;

                            if (self.rail.drag && (self.rail.drag.pt == 2)) {
                                if (cap.cantouch && (typeof e.original == "undefined")) return true;  // prevent ios "ghost" events by clickable elements

                                self.hasmoving = true;

                                if (self.preventclick && !self.preventclick.click) {
                                    self.preventclick.click = self.preventclick.tg.onclick || false;
                                    self.preventclick.tg.onclick = self.onpreventclick;
                                }

                                var ev = $.extend({ "original": e }, e);
                                e = ev;

                                if (("changedTouches" in e)) {
                                    e.clientX = e.changedTouches[0].clientX;
                                    e.clientY = e.changedTouches[0].clientY;
                                }

                                if (self.forcescreen) {
                                    var le = e;
                                    var e = { "original": (e.original) ? e.original : e };
                                    e.clientX = le.screenX;
                                    e.clientY = le.screenY;
                                }

                                var ofx = ofy = 0;

                                if (moveneedoffset && !byiframe) {
                                    var wp = self.win.position();
                                    ofx = -wp.left;
                                    ofy = -wp.top;
                                }

                                var fy = e.clientY + ofy;
                                var my = (fy - self.rail.drag.y);
                                var fx = e.clientX + ofx;
                                var mx = (fx - self.rail.drag.x);

                                var ny = self.rail.drag.st - my;

                                if (self.ishwscroll && self.opt.bouncescroll) {
                                    if (ny < 0) {
                                        ny = Math.round(ny / 2);
                                        //                    fy = 0;
                                    }
                                    else if (ny > self.page.maxh) {
                                        ny = self.page.maxh + Math.round((ny - self.page.maxh) / 2);
                                        //                    fy = 0;
                                    }
                                } else {
                                    if (ny < 0) { ny = 0; fy = 0 }
                                    if (ny > self.page.maxh) { ny = self.page.maxh; fy = 0 }
                                }

                                if (self.railh && self.railh.scrollable) {
                                    var nx = self.rail.drag.sl - mx;; //(self.isrtlmode) ? mx-self.rail.drag.sl : self.rail.drag.sl-mx;

                                    if (self.ishwscroll && self.opt.bouncescroll) {
                                        if (nx < 0) {
                                            nx = Math.round(nx / 2);
                                            //                      fx = 0;
                                        }
                                        else if (nx > self.page.maxw) {
                                            nx = self.page.maxw + Math.round((nx - self.page.maxw) / 2);
                                            //                      fx = 0;
                                        }
                                    } else {
                                        if (nx < 0) { nx = 0; fx = 0 }
                                        if (nx > self.page.maxw) { nx = self.page.maxw; fx = 0 }
                                    }

                                }

                                var grabbed = false;
                                if (self.rail.drag.dl) {
                                    grabbed = true;
                                    if (self.rail.drag.dl == "v") nx = self.rail.drag.sl;
                                    else if (self.rail.drag.dl == "h") ny = self.rail.drag.st;
                                } else {
                                    var ay = Math.abs(my);
                                    var ax = Math.abs(mx);
                                    var dz = self.opt.directionlockdeadzone;
                                    if (self.rail.drag.ck == "v") {
                                        if (ay > dz && (ax <= (ay * 0.3))) {
                                            self.rail.drag = false;
                                            return true;
                                        }
                                        else if (ax > dz) {
                                            self.rail.drag.dl = "f";
                                            $("body").scrollTop($("body").scrollTop());  // stop iOS native scrolling (when active javascript has blocked)
                                        }
                                    }
                                    else if (self.rail.drag.ck == "h") {
                                        if (ax > dz && (ay <= (ax * 0.3))) {
                                            self.rail.drag = false;
                                            return true;
                                        }
                                        else if (ay > dz) {
                                            self.rail.drag.dl = "f";
                                            $("body").scrollLeft($("body").scrollLeft());  // stop iOS native scrolling (when active javascript has blocked)
                                        }
                                    }
                                }

                                self.synched("touchmove", function () {
                                    if (self.rail.drag && (self.rail.drag.pt == 2)) {
                                        if (self.prepareTransition) self.prepareTransition(0);
                                        if (self.rail.scrollable) self.setScrollTop(ny);
                                        self.scrollmom.update(fx, fy);
                                        if (self.railh && self.railh.scrollable) {
                                            self.setScrollLeft(nx);
                                            self.showCursor(ny, nx);
                                        } else {
                                            self.showCursor(ny);
                                        }
                                        if (cap.isie10) document.selection.clear();
                                    }
                                });

                                if (cap.ischrome && self.istouchcapable) grabbed = false;  //chrome touch emulation doesn't like!
                                if (grabbed) return self.cancelEvent(e);
                            }

                        };

                    }

                    self.onmousedown = function (e, hronly) {
                        if (self.rail.drag && self.rail.drag.pt != 1) return;
                        if (self.locked) return self.cancelEvent(e);
                        self.cancelScroll();
                        self.rail.drag = { x: e.clientX, y: e.clientY, sx: self.scroll.x, sy: self.scroll.y, pt: 1, hr: (!!hronly) };
                        var tg = self.getTarget(e);
                        if (!self.ispage && cap.hasmousecapture) tg.setCapture();
                        if (self.isiframe && !cap.hasmousecapture) {
                            self.saved["csspointerevents"] = self.doc.css("pointer-events");
                            self.css(self.doc, { "pointer-events": "none" });
                        }
                        self.hasmoving = false;
                        return self.cancelEvent(e);
                    };

                    self.onmouseup = function (e) {
                        if (self.rail.drag) {
                            if (cap.hasmousecapture) document.releaseCapture();
                            if (self.isiframe && !cap.hasmousecapture) self.doc.css("pointer-events", self.saved["csspointerevents"]);
                            if (self.rail.drag.pt != 1) return;
                            self.rail.drag = false;
                            //if (!self.rail.active) self.hideCursor();
                            if (self.hasmoving) self.triggerScrollEnd();  // TODO - check &&!self.scrollrunning
                            return self.cancelEvent(e);
                        }
                    };

                    self.onmousemove = function (e) {
                        if (self.rail.drag) {
                            if (self.rail.drag.pt != 1) return;

                            if (cap.ischrome && e.which == 0) return self.onmouseup(e);

                            self.cursorfreezed = true;
                            self.hasmoving = true;

                            if (self.rail.drag.hr) {
                                self.scroll.x = self.rail.drag.sx + (e.clientX - self.rail.drag.x);
                                if (self.scroll.x < 0) self.scroll.x = 0;
                                var mw = self.scrollvaluemaxw;
                                if (self.scroll.x > mw) self.scroll.x = mw;
                            } else {
                                self.scroll.y = self.rail.drag.sy + (e.clientY - self.rail.drag.y);
                                if (self.scroll.y < 0) self.scroll.y = 0;
                                var my = self.scrollvaluemax;
                                if (self.scroll.y > my) self.scroll.y = my;
                            }

                            self.synched('mousemove', function () {
                                if (self.rail.drag && (self.rail.drag.pt == 1)) {
                                    self.showCursor();
                                    if (self.rail.drag.hr) self.doScrollLeft(Math.round(self.scroll.x * self.scrollratio.x), self.opt.cursordragspeed);
                                    else self.doScrollTop(Math.round(self.scroll.y * self.scrollratio.y), self.opt.cursordragspeed);
                                }
                            });

                            return self.cancelEvent(e);
                        }
                        /*              
                                    else {
                                      self.checkarea = true;
                                    }
                        */
                    };

                    if (cap.cantouch || self.opt.touchbehavior) {

                        self.onpreventclick = function (e) {
                            if (self.preventclick) {
                                self.preventclick.tg.onclick = self.preventclick.click;
                                self.preventclick = false;
                                return self.cancelEvent(e);
                            }
                        }

                        //            self.onmousedown = self.ontouchstart;            
                        //            self.onmouseup = self.ontouchend;
                        //            self.onmousemove = self.ontouchmove;

                        self.bind(self.win, "mousedown", self.ontouchstart);  // control content dragging

                        self.onclick = (cap.isios) ? false : function (e) {
                            if (self.lastmouseup) {
                                self.lastmouseup = false;
                                return self.cancelEvent(e);
                            } else {
                                return true;
                            }
                        };

                        if (self.opt.grabcursorenabled && cap.cursorgrabvalue) {
                            self.css((self.ispage) ? self.doc : self.win, { 'cursor': cap.cursorgrabvalue });
                            self.css(self.rail, { 'cursor': cap.cursorgrabvalue });
                        }

                    } else {

                        function checkSelectionScroll(e) {
                            if (!self.selectiondrag) return;

                            if (e) {
                                var ww = self.win.outerHeight();
                                var df = (e.pageY - self.selectiondrag.top);
                                if (df > 0 && df < ww) df = 0;
                                if (df >= ww) df -= ww;
                                self.selectiondrag.df = df;
                            }
                            if (self.selectiondrag.df == 0) return;

                            var rt = -Math.floor(self.selectiondrag.df / 6) * 2;
                            //              self.doScrollTop(self.getScrollTop(true)+rt);
                            self.doScrollBy(rt);

                            self.debounced("doselectionscroll", function () { checkSelectionScroll() }, 50);
                        };

                        if ("getSelection" in document) {  // A grade - Major browsers
                            self.hasTextSelected = function () {
                                return (document.getSelection().rangeCount > 0);
                            };
                        }
                        else if ("selection" in document) {  //IE9-
                            self.hasTextSelected = function () {
                                return (document.selection.type != "None");
                            };
                        }
                        else {
                            self.hasTextSelected = function () {  // no support
                                return false;
                            };
                        }

                        self.onselectionstart = function (e) {
                            if (self.ispage) return;
                            self.selectiondrag = self.win.offset();
                        };
                        self.onselectionend = function (e) {
                            self.selectiondrag = false;
                        };
                        self.onselectiondrag = function (e) {
                            if (!self.selectiondrag) return;
                            if (self.hasTextSelected()) self.debounced("selectionscroll", function () { checkSelectionScroll(e) }, 250);
                        };


                    }

                    if (cap.hasmstouch) {
                        self.css(self.rail, { '-ms-touch-action': 'none' });
                        self.css(self.cursor, { '-ms-touch-action': 'none' });

                        self.bind(self.win, "MSPointerDown", self.ontouchstart);
                        self.bind(document, "MSPointerUp", self.ontouchend);
                        self.bind(document, "MSPointerMove", self.ontouchmove);
                        self.bind(self.cursor, "MSGestureHold", function (e) { e.preventDefault() });
                        self.bind(self.cursor, "contextmenu", function (e) { e.preventDefault() });
                    }

                    if (this.istouchcapable) {  //desktop with screen touch enabled
                        self.bind(self.win, "touchstart", self.ontouchstart);
                        self.bind(document, "touchend", self.ontouchend);
                        self.bind(document, "touchcancel", self.ontouchend);
                        self.bind(document, "touchmove", self.ontouchmove);
                    }

                    self.bind(self.cursor, "mousedown", self.onmousedown);
                    self.bind(self.cursor, "mouseup", self.onmouseup);

                    if (self.railh) {
                        self.bind(self.cursorh, "mousedown", function (e) { self.onmousedown(e, true) });

                        self.bind(self.cursorh, "mouseup", self.onmouseup);


                        /*						
                                    self.bind(self.cursorh,"mouseup",function(e){
                                      if (self.rail.drag&&self.rail.drag.pt==2) return;
                                      self.rail.drag = false;
                                      self.hasmoving = false;
                                      self.hideCursor();
                                      if (cap.hasmousecapture) document.releaseCapture();
                                      return self.cancelEvent(e);
                                    });
                        */

                    }

                    if (self.opt.cursordragontouch || !cap.cantouch && !self.opt.touchbehavior) {

                        self.rail.css({ "cursor": "default" });
                        self.railh && self.railh.css({ "cursor": "default" });

                        self.jqbind(self.rail, "mouseenter", function () {
                            if (!self.win.is(":visible")) return false;
                            if (self.canshowonmouseevent) self.showCursor();
                            self.rail.active = true;
                        });
                        self.jqbind(self.rail, "mouseleave", function () {
                            self.rail.active = false;
                            if (!self.rail.drag) self.hideCursor();
                        });

                        if (self.opt.sensitiverail) {
                            self.bind(self.rail, "click", function (e) { self.doRailClick(e, false, false) });
                            self.bind(self.rail, "dblclick", function (e) { self.doRailClick(e, true, false) });
                            self.bind(self.cursor, "click", function (e) { self.cancelEvent(e) });
                            self.bind(self.cursor, "dblclick", function (e) { self.cancelEvent(e) });
                        }

                        if (self.railh) {
                            self.jqbind(self.railh, "mouseenter", function () {
                                if (!self.win.is(":visible")) return false;
                                if (self.canshowonmouseevent) self.showCursor();
                                self.rail.active = true;
                            });
                            self.jqbind(self.railh, "mouseleave", function () {
                                self.rail.active = false;
                                if (!self.rail.drag) self.hideCursor();
                            });

                            if (self.opt.sensitiverail) {
                                self.bind(self.railh, "click", function (e) { self.doRailClick(e, false, true) });
                                self.bind(self.railh, "dblclick", function (e) { self.doRailClick(e, true, true) });
                                self.bind(self.cursorh, "click", function (e) { self.cancelEvent(e) });
                                self.bind(self.cursorh, "dblclick", function (e) { self.cancelEvent(e) });
                            }

                        }

                    }

                    if (!cap.cantouch && !self.opt.touchbehavior) {

                        self.bind((cap.hasmousecapture) ? self.win : document, "mouseup", self.onmouseup);
                        self.bind(document, "mousemove", self.onmousemove);
                        if (self.onclick) self.bind(document, "click", self.onclick);

                        if (!self.ispage && self.opt.enablescrollonselection) {
                            self.bind(self.win[0], "mousedown", self.onselectionstart);
                            self.bind(document, "mouseup", self.onselectionend);
                            self.bind(self.cursor, "mouseup", self.onselectionend);
                            if (self.cursorh) self.bind(self.cursorh, "mouseup", self.onselectionend);
                            self.bind(document, "mousemove", self.onselectiondrag);
                        }

                        if (self.zoom) {
                            self.jqbind(self.zoom, "mouseenter", function () {
                                if (self.canshowonmouseevent) self.showCursor();
                                self.rail.active = true;
                            });
                            self.jqbind(self.zoom, "mouseleave", function () {
                                self.rail.active = false;
                                if (!self.rail.drag) self.hideCursor();
                            });
                        }

                    } else {

                        self.bind((cap.hasmousecapture) ? self.win : document, "mouseup", self.ontouchend);
                        self.bind(document, "mousemove", self.ontouchmove);
                        if (self.onclick) self.bind(document, "click", self.onclick);

                        if (self.opt.cursordragontouch) {
                            self.bind(self.cursor, "mousedown", self.onmousedown);
                            self.bind(self.cursor, "mousemove", self.onmousemove);
                            self.cursorh && self.bind(self.cursorh, "mousedown", function (e) { self.onmousedown(e, true) });
                            self.cursorh && self.bind(self.cursorh, "mousemove", self.onmousemove);
                        }

                    }

                    if (self.opt.enablemousewheel) {
                        if (!self.isiframe) self.bind((cap.isie && self.ispage) ? document : self.win /*self.docscroll*/, "mousewheel", self.onmousewheel);
                        self.bind(self.rail, "mousewheel", self.onmousewheel);
                        if (self.railh) self.bind(self.railh, "mousewheel", self.onmousewheelhr);
                    }

                    if (!self.ispage && !cap.cantouch && !(/HTML|^BODY/.test(self.win[0].nodeName))) {
                        if (!self.win.attr("tabindex")) self.win.attr({ "tabindex": tabindexcounter++ });

                        self.jqbind(self.win, "focus", function (e) {
                            domfocus = (self.getTarget(e)).id || true;
                            self.hasfocus = true;
                            if (self.canshowonmouseevent) self.noticeCursor();
                        });
                        self.jqbind(self.win, "blur", function (e) {
                            domfocus = false;
                            self.hasfocus = false;
                        });

                        self.jqbind(self.win, "mouseenter", function (e) {
                            mousefocus = (self.getTarget(e)).id || true;
                            self.hasmousefocus = true;
                            if (self.canshowonmouseevent) self.noticeCursor();
                        });
                        self.jqbind(self.win, "mouseleave", function () {
                            mousefocus = false;
                            self.hasmousefocus = false;
                            if (!self.rail.drag) self.hideCursor();
                        });

                    };

                }  // !ie9mobile

                //Thanks to http://www.quirksmode.org !!
                self.onkeypress = function (e) {
                    if (self.locked && self.page.maxh == 0) return true;

                    e = (e) ? e : window.e;
                    var tg = self.getTarget(e);
                    if (tg && /INPUT|TEXTAREA|SELECT|OPTION/.test(tg.nodeName)) {
                        var tp = tg.getAttribute('type') || tg.type || false;
                        if ((!tp) || !(/submit|button|cancel/i.tp)) return true;
                    }

                    if ($(tg).attr('contenteditable')) return true;

                    if (self.hasfocus || (self.hasmousefocus && !domfocus) || (self.ispage && !domfocus && !mousefocus)) {
                        var key = e.keyCode;

                        if (self.locked && key != 27) return self.cancelEvent(e);

                        var ctrl = e.ctrlKey || false;
                        var shift = e.shiftKey || false;

                        var ret = false;
                        switch (key) {
                            case 38:
                            case 63233: //safari
                                self.doScrollBy(24 * 3);
                                ret = true;
                                break;
                            case 40:
                            case 63235: //safari
                                self.doScrollBy(-24 * 3);
                                ret = true;
                                break;
                            case 37:
                            case 63232: //safari
                                if (self.railh) {
                                    (ctrl) ? self.doScrollLeft(0) : self.doScrollLeftBy(24 * 3);
                                    ret = true;
                                }
                                break;
                            case 39:
                            case 63234: //safari
                                if (self.railh) {
                                    (ctrl) ? self.doScrollLeft(self.page.maxw) : self.doScrollLeftBy(-24 * 3);
                                    ret = true;
                                }
                                break;
                            case 33:
                            case 63276: // safari
                                self.doScrollBy(self.view.h);
                                ret = true;
                                break;
                            case 34:
                            case 63277: // safari
                                self.doScrollBy(-self.view.h);
                                ret = true;
                                break;
                            case 36:
                            case 63273: // safari                
                                (self.railh && ctrl) ? self.doScrollPos(0, 0) : self.doScrollTo(0);
                                ret = true;
                                break;
                            case 35:
                            case 63275: // safari
                                (self.railh && ctrl) ? self.doScrollPos(self.page.maxw, self.page.maxh) : self.doScrollTo(self.page.maxh);
                                ret = true;
                                break;
                            case 32:
                                if (self.opt.spacebarenabled) {
                                    (shift) ? self.doScrollBy(self.view.h) : self.doScrollBy(-self.view.h);
                                    ret = true;
                                }
                                break;
                            case 27: // ESC
                                if (self.zoomactive) {
                                    self.doZoom();
                                    ret = true;
                                }
                                break;
                        }
                        if (ret) return self.cancelEvent(e);
                    }
                };

                if (self.opt.enablekeyboard) self.bind(document, (cap.isopera && !cap.isopera12) ? "keypress" : "keydown", self.onkeypress);

                self.bind(document, "keydown", function (e) {
                    var ctrl = e.ctrlKey || false;
                    if (ctrl) self.wheelprevented = true;
                });
                self.bind(document, "keyup", function (e) {
                    var ctrl = e.ctrlKey || false;
                    if (!ctrl) self.wheelprevented = false;
                });

                self.bind(window, 'resize', self.lazyResize);
                self.bind(window, 'orientationchange', self.lazyResize);

                self.bind(window, "load", self.lazyResize);

                if (cap.ischrome && !self.ispage && !self.haswrapper) { //chrome void scrollbar bug - it persists in version 26
                    var tmp = self.win.attr("style");
                    var ww = parseFloat(self.win.css("width")) + 1;
                    self.win.css('width', ww);
                    self.synched("chromefix", function () { self.win.attr("style", tmp) });
                }


                // Trying a cross-browser implementation - good luck!

                self.onAttributeChange = function (e) {
                    self.lazyResize(250);
                };

                if (!self.ispage && !self.haswrapper) {
                    // redesigned MutationObserver for Chrome18+/Firefox14+/iOS6+ with support for: remove div, add/remove content
                    if (clsMutationObserver !== false) {
                        self.observer = new clsMutationObserver(function (mutations) {
                            mutations.forEach(self.onAttributeChange);
                        });
                        self.observer.observe(self.win[0], { childList: true, characterData: false, attributes: true, subtree: false });

                        self.observerremover = new clsMutationObserver(function (mutations) {
                            mutations.forEach(function (mo) {
                                if (mo.removedNodes.length > 0) {
                                    for (var dd in mo.removedNodes) {
                                        if (mo.removedNodes[dd] == self.win[0]) return self.remove();
                                    }
                                }
                            });
                        });
                        self.observerremover.observe(self.win[0].parentNode, { childList: true, characterData: false, attributes: false, subtree: false });

                    } else {
                        self.bind(self.win, (cap.isie && !cap.isie9) ? "propertychange" : "DOMAttrModified", self.onAttributeChange);
                        if (cap.isie9) self.win[0].attachEvent("onpropertychange", self.onAttributeChange); //IE9 DOMAttrModified bug
                        self.bind(self.win, "DOMNodeRemoved", function (e) {
                            if (e.target == self.win[0]) self.remove();
                        });
                    }
                }

                //

                if (!self.ispage && self.opt.boxzoom) self.bind(window, "resize", self.resizeZoom);
                if (self.istextarea) self.bind(self.win, "mouseup", self.lazyResize);

                //        self.checkrtlmode = true;
                self.lazyResize(30);

            }

            if (this.doc[0].nodeName == 'IFRAME') {
                function oniframeload(e) {
                    self.iframexd = false;
                    try {
                        var doc = 'contentDocument' in this ? this.contentDocument : this.contentWindow.document;
                        var a = doc.domain;
                    } catch (e) { self.iframexd = true; doc = false };

                    if (self.iframexd) {
                        if ("console" in window) console.log('NiceScroll error: policy restriced iframe');
                        return true;  //cross-domain - I can't manage this        
                    }

                    self.forcescreen = true;

                    if (self.isiframe) {
                        self.iframe = {
                            "doc": $(doc),
                            "html": self.doc.contents().find('html')[0],
                            "body": self.doc.contents().find('body')[0]
                        };
                        self.getContentSize = function () {
                            return {
                                w: Math.max(self.iframe.html.scrollWidth, self.iframe.body.scrollWidth),
                                h: Math.max(self.iframe.html.scrollHeight, self.iframe.body.scrollHeight)
                            };
                        };
                        self.docscroll = $(self.iframe.body);//$(this.contentWindow);
                    }

                    if (!cap.isios && self.opt.iframeautoresize && !self.isiframe) {
                        self.win.scrollTop(0); // reset position
                        self.doc.height("");  //reset height to fix browser bug
                        var hh = Math.max(doc.getElementsByTagName('html')[0].scrollHeight, doc.body.scrollHeight);
                        self.doc.height(hh);
                    }
                    self.lazyResize(30);

                    if (cap.isie7) self.css($(self.iframe.html), { 'overflow-y': 'hidden' });
                    //self.css($(doc.body),{'overflow-y':'hidden'});
                    self.css($(self.iframe.body), { 'overflow-y': 'hidden' });

                    if (cap.isios && self.haswrapper) {
                        self.css($(doc.body), { '-webkit-transform': 'translate3d(0,0,0)' });  // avoid iFrame content clipping - thanks to http://blog.derraab.com/2012/04/02/avoid-iframe-content-clipping-with-css-transform-on-ios/
                    }

                    if ('contentWindow' in this) {
                        self.bind(this.contentWindow, "scroll", self.onscroll);  //IE8 & minor
                    } else {
                        self.bind(doc, "scroll", self.onscroll);
                    }

                    if (self.opt.enablemousewheel) {
                        self.bind(doc, "mousewheel", self.onmousewheel);
                    }

                    if (self.opt.enablekeyboard) self.bind(doc, (cap.isopera) ? "keypress" : "keydown", self.onkeypress);

                    if (cap.cantouch || self.opt.touchbehavior) {
                        self.bind(doc, "mousedown", self.ontouchstart);
                        self.bind(doc, "mousemove", function (e) { self.ontouchmove(e, true) });
                        if (self.opt.grabcursorenabled && cap.cursorgrabvalue) self.css($(doc.body), { 'cursor': cap.cursorgrabvalue });
                    }

                    self.bind(doc, "mouseup", self.ontouchend);

                    if (self.zoom) {
                        if (self.opt.dblclickzoom) self.bind(doc, 'dblclick', self.doZoom);
                        if (self.ongesturezoom) self.bind(doc, "gestureend", self.ongesturezoom);
                    }
                };

                if (this.doc[0].readyState && this.doc[0].readyState == "complete") {
                    setTimeout(function () { oniframeload.call(self.doc[0], false) }, 500);
                }
                self.bind(this.doc, "load", oniframeload);

            }

        };

        this.showCursor = function (py, px) {
            if (self.cursortimeout) {
                clearTimeout(self.cursortimeout);
                self.cursortimeout = 0;
            }
            if (!self.rail) return;
            if (self.autohidedom) {
                self.autohidedom.stop().css({ opacity: self.opt.cursoropacitymax });
                self.cursoractive = true;
            }

            if (!self.rail.drag || self.rail.drag.pt != 1) {
                if ((typeof py != "undefined") && (py !== false)) {
                    self.scroll.y = Math.round(py * 1 / self.scrollratio.y);
                }
                if (typeof px != "undefined") {
                    self.scroll.x = Math.round(px * 1 / self.scrollratio.x);  //-cxscrollleft * Math.round(px * 1/self.scrollratio.x);
                }
            }

            self.cursor.css({ height: self.cursorheight, top: self.scroll.y });
            if (self.cursorh) {
                (!self.rail.align && self.rail.visibility) ? self.cursorh.css({ width: self.cursorwidth, left: self.scroll.x + self.rail.width }) : self.cursorh.css({ width: self.cursorwidth, left: self.scroll.x });
                self.cursoractive = true;
            }

            if (self.zoom) self.zoom.stop().css({ opacity: self.opt.cursoropacitymax });
        };

        this.hideCursor = function (tm) {
            if (self.cursortimeout) return;
            if (!self.rail) return;
            if (!self.autohidedom) return;
            if (self.hasmousefocus && self.opt.autohidemode == "leave") return;
            self.cursortimeout = setTimeout(function () {
                if (!self.rail.active || !self.showonmouseevent) {
                    self.autohidedom.stop().animate({ opacity: self.opt.cursoropacitymin });
                    if (self.zoom) self.zoom.stop().animate({ opacity: self.opt.cursoropacitymin });
                    self.cursoractive = false;
                }
                self.cursortimeout = 0;
            }, tm || self.opt.hidecursordelay);
        };

        this.noticeCursor = function (tm, py, px) {
            self.showCursor(py, px);
            if (!self.rail.active) self.hideCursor(tm);
        };

        this.getContentSize =
          (self.ispage) ?
            function () {
                return {
                    w: Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
                    h: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
                }
            }
          : (self.haswrapper) ?
            function () {
                return {
                    w: self.doc.outerWidth() + parseInt(self.win.css('paddingLeft')) + parseInt(self.win.css('paddingRight')),
                    h: self.doc.outerHeight() + parseInt(self.win.css('paddingTop')) + parseInt(self.win.css('paddingBottom'))
                }
            }
          : function () {
              return {
                  w: self.docscroll[0].scrollWidth,
                  h: self.docscroll[0].scrollHeight
              }
          };

        this.onResize = function (e, page) {

            if (!self || !self.win) return false;

            if (!self.haswrapper && !self.ispage) {
                if (self.win.css('display') == 'none') {
                    if (self.visibility) self.hideRail().hideRailHr();
                    return false;
                } else {
                    if (!self.hidden && !self.visibility) self.showRail().showRailHr();
                }
            }

            var premaxh = self.page.maxh;
            var premaxw = self.page.maxw;

            var preview = { h: self.view.h, w: self.view.w };

            self.view = {
                w: (self.ispage) ? self.win.width() : parseInt(self.win[0].clientWidth),
                h: (self.ispage) ? self.win.height() : parseInt(self.win[0].clientHeight)
            };

            self.page = (page) ? page : self.getContentSize();

            self.page.maxh = Math.max(0, self.page.h - self.view.h);
            self.page.maxw = Math.max(0, self.page.w - self.view.w);

            if ((self.page.maxh == premaxh) && (self.page.maxw == premaxw) && (self.view.w == preview.w)) {
                // test position        
                if (!self.ispage) {
                    var pos = self.win.offset();
                    if (self.lastposition) {
                        var lst = self.lastposition;
                        if ((lst.top == pos.top) && (lst.left == pos.left)) return self; //nothing to do            
                    }
                    self.lastposition = pos;
                } else {
                    return self; //nothing to do
                }
            }

            if (self.page.maxh == 0) {
                self.hideRail();
                self.scrollvaluemax = 0;
                self.scroll.y = 0;
                self.scrollratio.y = 0;
                self.cursorheight = 0;
                self.setScrollTop(0);
                self.rail.scrollable = false;
            } else {
                self.rail.scrollable = true;
            }

            if (self.page.maxw == 0) {
                self.hideRailHr();
                self.scrollvaluemaxw = 0;
                self.scroll.x = 0;
                self.scrollratio.x = 0;
                self.cursorwidth = 0;
                self.setScrollLeft(0);
                self.railh.scrollable = false;
            } else {
                self.railh.scrollable = true;
            }

            self.locked = (self.page.maxh == 0) && (self.page.maxw == 0);
            if (self.locked) {
                if (!self.ispage) self.updateScrollBar(self.view);
                return false;
            }

            if (!self.hidden && !self.visibility) {
                self.showRail().showRailHr();
            }
            else if (!self.hidden && !self.railh.visibility) self.showRailHr();

            if (self.istextarea && self.win.css('resize') && self.win.css('resize') != 'none') self.view.h -= 20;

            self.cursorheight = Math.min(self.view.h, Math.round(self.view.h * (self.view.h / self.page.h)));
            self.cursorheight = (self.opt.cursorfixedheight) ? self.opt.cursorfixedheight : Math.max(self.opt.cursorminheight, self.cursorheight);

            self.cursorwidth = Math.min(self.view.w, Math.round(self.view.w * (self.view.w / self.page.w)));
            self.cursorwidth = (self.opt.cursorfixedheight) ? self.opt.cursorfixedheight : Math.max(self.opt.cursorminheight, self.cursorwidth);

            self.scrollvaluemax = self.view.h - self.cursorheight - self.cursor.hborder;

            if (self.railh) {
                self.railh.width = (self.page.maxh > 0) ? (self.view.w - self.rail.width) : self.view.w;
                self.scrollvaluemaxw = self.railh.width - self.cursorwidth - self.cursorh.wborder;
            }

            /*			
                  if (self.checkrtlmode&&self.railh) {
                    self.checkrtlmode = false;
                    if (self.opt.rtlmode&&self.scroll.x==0) self.setScrollLeft(self.page.maxw);
                  }
            */

            if (!self.ispage) self.updateScrollBar(self.view);

            self.scrollratio = {
                x: (self.page.maxw / self.scrollvaluemaxw),
                y: (self.page.maxh / self.scrollvaluemax)
            };

            var sy = self.getScrollTop();
            if (sy > self.page.maxh) {
                self.doScrollTop(self.page.maxh);
            } else {
                self.scroll.y = Math.round(self.getScrollTop() * (1 / self.scrollratio.y));
                self.scroll.x = Math.round(self.getScrollLeft() * (1 / self.scrollratio.x));
                if (self.cursoractive) self.noticeCursor();
            }

            if (self.scroll.y && (self.getScrollTop() == 0)) self.doScrollTo(Math.floor(self.scroll.y * self.scrollratio.y));

            return self;
        };

        this.resize = self.onResize;

        this.lazyResize = function (tm) {   // event debounce
            tm = (isNaN(tm)) ? 30 : tm;
            self.delayed('resize', self.resize, tm);
            return self;
        };

        // modified by MDN https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/wheel
        function _modernWheelEvent(dom, name, fn, bubble) {
            self._bind(dom, name, function (e) {
                var e = (e) ? e : window.event;
                var event = {
                    original: e,
                    target: e.target || e.srcElement,
                    type: "wheel",
                    deltaMode: e.type == "MozMousePixelScroll" ? 0 : 1,
                    deltaX: 0,
                    deltaZ: 0,
                    preventDefault: function () {
                        e.preventDefault ? e.preventDefault() : e.returnValue = false;
                        return false;
                    },
                    stopImmediatePropagation: function () {
                        (e.stopImmediatePropagation) ? e.stopImmediatePropagation() : e.cancelBubble = true;
                    }
                };

                if (name == "mousewheel") {
                    event.deltaY = -1 / 40 * e.wheelDelta;
                    e.wheelDeltaX && (event.deltaX = -1 / 40 * e.wheelDeltaX);
                } else {
                    event.deltaY = e.detail;
                }

                return fn.call(dom, event);
            }, bubble);
        };

        this._bind = function (el, name, fn, bubble) {  // primitive bind
            self.events.push({ e: el, n: name, f: fn, b: bubble, q: false });
            if (el.addEventListener) {
                el.addEventListener(name, fn, bubble || false);
            }
            else if (el.attachEvent) {
                el.attachEvent("on" + name, fn);
            }
            else {
                el["on" + name] = fn;
            }
        };

        this.jqbind = function (dom, name, fn) {  // use jquery bind for non-native events (mouseenter/mouseleave)
            self.events.push({ e: dom, n: name, f: fn, q: true });
            $(dom).bind(name, fn);
        };

        this.bind = function (dom, name, fn, bubble) {  // touch-oriented & fixing jquery bind
            var el = ("jquery" in dom) ? dom[0] : dom;

            if (name == 'mousewheel') {
                if ("onwheel" in self.win) {
                    self._bind(el, "wheel", fn, bubble || false);
                } else {
                    var wname = (typeof document.onmousewheel != "undefined") ? "mousewheel" : "DOMMouseScroll";  // older IE/Firefox
                    _modernWheelEvent(el, wname, fn, bubble || false);
                    if (wname == "DOMMouseScroll") _modernWheelEvent(el, "MozMousePixelScroll", fn, bubble || false);  // Firefox legacy
                }
            }
            else if (el.addEventListener) {
                if (cap.cantouch && /mouseup|mousedown|mousemove/.test(name)) {  // touch device support
                    var tt = (name == 'mousedown') ? 'touchstart' : (name == 'mouseup') ? 'touchend' : 'touchmove';
                    self._bind(el, tt, function (e) {
                        if (e.touches) {
                            if (e.touches.length < 2) { var ev = (e.touches.length) ? e.touches[0] : e; ev.original = e; fn.call(this, ev); }
                        }
                        else if (e.changedTouches) { var ev = e.changedTouches[0]; ev.original = e; fn.call(this, ev); }  //blackberry
                    }, bubble || false);
                }
                self._bind(el, name, fn, bubble || false);
                if (cap.cantouch && name == "mouseup") self._bind(el, "touchcancel", fn, bubble || false);
            }
            else {
                self._bind(el, name, function (e) {
                    e = e || window.event || false;
                    if (e) {
                        if (e.srcElement) e.target = e.srcElement;
                    }
                    if (!("pageY" in e)) {
                        e.pageX = e.clientX + document.documentElement.scrollLeft;
                        e.pageY = e.clientY + document.documentElement.scrollTop;
                    }
                    return ((fn.call(el, e) === false) || bubble === false) ? self.cancelEvent(e) : true;
                });
            }
        };

        this._unbind = function (el, name, fn, bub) {  // primitive unbind
            if (el.removeEventListener) {
                el.removeEventListener(name, fn, bub);
            }
            else if (el.detachEvent) {
                el.detachEvent('on' + name, fn);
            } else {
                el['on' + name] = false;
            }
        };

        this.unbindAll = function () {
            for (var a = 0; a < self.events.length; a++) {
                var r = self.events[a];
                (r.q) ? r.e.unbind(r.n, r.f) : self._unbind(r.e, r.n, r.f, r.b);
            }
        };

        // Thanks to http://www.switchonthecode.com !!
        this.cancelEvent = function (e) {
            var e = (e.original) ? e.original : (e) ? e : window.event || false;
            if (!e) return false;
            if (e.preventDefault) e.preventDefault();
            if (e.stopPropagation) e.stopPropagation();
            if (e.preventManipulation) e.preventManipulation();  //IE10
            e.cancelBubble = true;
            e.cancel = true;
            e.returnValue = false;
            return false;
        };

        this.stopPropagation = function (e) {
            var e = (e.original) ? e.original : (e) ? e : window.event || false;
            if (!e) return false;
            if (e.stopPropagation) return e.stopPropagation();
            if (e.cancelBubble) e.cancelBubble = true;
            return false;
        };

        this.showRail = function () {
            if ((self.page.maxh != 0) && (self.ispage || self.win.css('display') != 'none')) {
                self.visibility = true;
                self.rail.visibility = true;
                self.rail.css('display', 'block');
            }
            return self;
        };

        this.showRailHr = function () {
            if (!self.railh) return self;
            if ((self.page.maxw != 0) && (self.ispage || self.win.css('display') != 'none')) {
                self.railh.visibility = true;
                self.railh.css('display', 'block');
            }
            return self;
        };

        this.hideRail = function () {
            self.visibility = false;
            self.rail.visibility = false;
            self.rail.css('display', 'none');
            return self;
        };

        this.hideRailHr = function () {
            if (!self.railh) return self;
            self.railh.visibility = false;
            self.railh.css('display', 'none');
            return self;
        };

        this.show = function () {
            self.hidden = false;
            self.locked = false;
            return self.showRail().showRailHr();
        };

        this.hide = function () {
            self.hidden = true;
            self.locked = true;
            return self.hideRail().hideRailHr();
        };

        this.toggle = function () {
            return (self.hidden) ? self.show() : self.hide();
        };

        this.remove = function () {
            self.stop();
            if (self.cursortimeout) clearTimeout(self.cursortimeout);
            self.doZoomOut();
            self.unbindAll();

            if (cap.isie9) self.win[0].detachEvent("onpropertychange", self.onAttributeChange); //IE9 DOMAttrModified bug

            if (self.observer !== false) self.observer.disconnect();
            if (self.observerremover !== false) self.observerremover.disconnect();

            self.events = null;

            if (self.cursor) {
                self.cursor.remove();
            }
            if (self.cursorh) {
                self.cursorh.remove();
            }
            if (self.rail) {
                self.rail.remove();
            }
            if (self.railh) {
                self.railh.remove();
            }
            if (self.zoom) {
                self.zoom.remove();
            }
            for (var a = 0; a < self.saved.css.length; a++) {
                var d = self.saved.css[a];
                d[0].css(d[1], (typeof d[2] == "undefined") ? '' : d[2]);
            }
            self.saved = false;
            self.me.data('__nicescroll', ''); //erase all traces

            // memory leak fixed by GianlucaGuarini - thanks a lot!
            // remove the current nicescroll from the $.nicescroll array & normalize array
            var lst = $.nicescroll;
            lst.each(function (i) {
                if (!this) return;
                if (this.id === self.id) {
                    delete lst[i];
                    for (var b = ++i; b < lst.length; b++, i++) lst[i] = lst[b];
                    lst.length--;
                    if (lst.length) delete lst[lst.length];
                }
            });

            for (var i in self) {
                self[i] = null;
                delete self[i];
            }

            self = null;

        };

        this.scrollstart = function (fn) {
            this.onscrollstart = fn;
            return self;
        };
        this.scrollend = function (fn) {
            this.onscrollend = fn;
            return self;
        };
        this.scrollcancel = function (fn) {
            this.onscrollcancel = fn;
            return self;
        };

        this.zoomin = function (fn) {
            this.onzoomin = fn;
            return self;
        };
        this.zoomout = function (fn) {
            this.onzoomout = fn;
            return self;
        };

        this.isScrollable = function (e) {
            var dom = (e.target) ? e.target : e;
            if (dom.nodeName == 'OPTION') return true;
            while (dom && (dom.nodeType == 1) && !(/^BODY|HTML/.test(dom.nodeName))) {
                var dd = $(dom);
                var ov = dd.css('overflowY') || dd.css('overflowX') || dd.css('overflow') || '';
                if (/scroll|auto/.test(ov)) return (dom.clientHeight != dom.scrollHeight);
                dom = (dom.parentNode) ? dom.parentNode : false;
            }
            return false;
        };

        this.getViewport = function (me) {
            var dom = (me && me.parentNode) ? me.parentNode : false;
            while (dom && (dom.nodeType == 1) && !(/^BODY|HTML/.test(dom.nodeName))) {
                var dd = $(dom);
                if (/fixed|absolute/.test(dd.css("position"))) return dd;
                var ov = dd.css('overflowY') || dd.css('overflowX') || dd.css('overflow') || '';
                if ((/scroll|auto/.test(ov)) && (dom.clientHeight != dom.scrollHeight)) return dd;
                if (dd.getNiceScroll().length > 0) return dd;
                dom = (dom.parentNode) ? dom.parentNode : false;
            }
            return (dom) ? $(dom) : false;
        };

        this.triggerScrollEnd = function () {
            if (!self.onscrollend) return;

            var px = self.getScrollLeft();
            var py = self.getScrollTop();

            var info = { "type": "scrollend", "current": { "x": px, "y": py }, "end": { "x": px, "y": py } };
            self.onscrollend.call(self, info);
        }

        function execScrollWheel(e, hr, chkscroll) {
            var px, py;
            var rt = 1;

            if (e.deltaMode == 0) {  // PIXEL
                px = -Math.floor(e.deltaX * (self.opt.mousescrollstep / (18 * 3)));
                py = -Math.floor(e.deltaY * (self.opt.mousescrollstep / (18 * 3)));
            }
            else if (e.deltaMode == 1) {  // LINE
                px = -Math.floor(e.deltaX * self.opt.mousescrollstep);
                py = -Math.floor(e.deltaY * self.opt.mousescrollstep);
            }

            if (hr && self.opt.oneaxismousemode && (px == 0) && py) {  // classic vertical-only mousewheel + browser with x/y support 
                px = py;
                py = 0;
            }

            if (px) {
                if (self.scrollmom) { self.scrollmom.stop() }
                self.lastdeltax += px;
                self.debounced("mousewheelx", function () { var dt = self.lastdeltax; self.lastdeltax = 0; if (!self.rail.drag) { self.doScrollLeftBy(dt) } }, 15);
            }
            if (py) {
                if (self.opt.nativeparentscrolling && chkscroll && !self.ispage && !self.zoomactive) {
                    if (py < 0) {
                        if (self.getScrollTop() >= self.page.maxh) return true;
                    } else {
                        if (self.getScrollTop() <= 0) return true;
                    }
                }
                if (self.scrollmom) { self.scrollmom.stop() }
                self.lastdeltay += py;
                self.debounced("mousewheely", function () { var dt = self.lastdeltay; self.lastdeltay = 0; if (!self.rail.drag) { self.doScrollBy(dt) } }, 15);
            }

            e.stopImmediatePropagation();
            return e.preventDefault();
            //      return self.cancelEvent(e);
        };

        this.onmousewheel = function (e) {
            if (self.wheelprevented) return;
            if (self.locked) {
                self.debounced("checkunlock", self.resize, 250);
                return true;
            }
            if (self.rail.drag) return self.cancelEvent(e);

            if (self.opt.oneaxismousemode == "auto" && e.deltaX != 0) self.opt.oneaxismousemode = false;  // check two-axis mouse support (not very elegant)

            if (self.opt.oneaxismousemode && e.deltaX == 0) {
                if (!self.rail.scrollable) {
                    if (self.railh && self.railh.scrollable) {
                        return self.onmousewheelhr(e);
                    } else {
                        return true;
                    }
                }
            }

            var nw = +(new Date());
            var chk = false;
            if (self.opt.preservenativescrolling && ((self.checkarea + 600) < nw)) {
                //        self.checkarea = false;
                self.nativescrollingarea = self.isScrollable(e);
                chk = true;
            }
            self.checkarea = nw;
            if (self.nativescrollingarea) return true; // this isn't my business
            //      if (self.locked) return self.cancelEvent(e);
            var ret = execScrollWheel(e, false, chk);
            if (ret) self.checkarea = 0;
            return ret;
        };

        this.onmousewheelhr = function (e) {
            if (self.wheelprevented) return;
            if (self.locked || !self.railh.scrollable) return true;
            if (self.rail.drag) return self.cancelEvent(e);

            var nw = +(new Date());
            var chk = false;
            if (self.opt.preservenativescrolling && ((self.checkarea + 600) < nw)) {
                //        self.checkarea = false;
                self.nativescrollingarea = self.isScrollable(e);
                chk = true;
            }
            self.checkarea = nw;
            if (self.nativescrollingarea) return true; // this isn't my business
            if (self.locked) return self.cancelEvent(e);

            return execScrollWheel(e, true, chk);
        };

        this.stop = function () {
            self.cancelScroll();
            if (self.scrollmon) self.scrollmon.stop();
            self.cursorfreezed = false;
            self.scroll.y = Math.round(self.getScrollTop() * (1 / self.scrollratio.y));
            self.noticeCursor();
            return self;
        };

        this.getTransitionSpeed = function (dif) {
            var sp = Math.round(self.opt.scrollspeed * 10);
            var ex = Math.min(sp, Math.round((dif / 20) * self.opt.scrollspeed));
            return (ex > 20) ? ex : 0;
        };

        if (!self.opt.smoothscroll) {
            this.doScrollLeft = function (x, spd) {  //direct
                var y = self.getScrollTop();
                self.doScrollPos(x, y, spd);
            };
            this.doScrollTop = function (y, spd) {   //direct
                var x = self.getScrollLeft();
                self.doScrollPos(x, y, spd);
            };
            this.doScrollPos = function (x, y, spd) {  //direct
                var nx = (x > self.page.maxw) ? self.page.maxw : x;
                if (nx < 0) nx = 0;
                var ny = (y > self.page.maxh) ? self.page.maxh : y;
                if (ny < 0) ny = 0;
                self.synched('scroll', function () {
                    self.setScrollTop(ny);
                    self.setScrollLeft(nx);
                });
            };
            this.cancelScroll = function () { }; // direct
        }
        else if (self.ishwscroll && cap.hastransition && self.opt.usetransition) {
            this.prepareTransition = function (dif, istime) {
                var ex = (istime) ? ((dif > 20) ? dif : 0) : self.getTransitionSpeed(dif);
                var trans = (ex) ? cap.prefixstyle + 'transform ' + ex + 'ms ease-out' : '';
                if (!self.lasttransitionstyle || self.lasttransitionstyle != trans) {
                    self.lasttransitionstyle = trans;
                    self.doc.css(cap.transitionstyle, trans);
                }
                return ex;
            };

            this.doScrollLeft = function (x, spd) {  //trans
                var y = (self.scrollrunning) ? self.newscrolly : self.getScrollTop();
                self.doScrollPos(x, y, spd);
            };

            this.doScrollTop = function (y, spd) {   //trans
                var x = (self.scrollrunning) ? self.newscrollx : self.getScrollLeft();
                self.doScrollPos(x, y, spd);
            };

            this.doScrollPos = function (x, y, spd) {  //trans

                var py = self.getScrollTop();
                var px = self.getScrollLeft();

                if (((self.newscrolly - py) * (y - py) < 0) || ((self.newscrollx - px) * (x - px) < 0)) self.cancelScroll();  //inverted movement detection      

                if (self.opt.bouncescroll == false) {
                    if (y < 0) y = 0;
                    else if (y > self.page.maxh) y = self.page.maxh;
                    if (x < 0) x = 0;
                    else if (x > self.page.maxw) x = self.page.maxw;
                }

                if (self.scrollrunning && x == self.newscrollx && y == self.newscrolly) return false;

                self.newscrolly = y;
                self.newscrollx = x;

                self.newscrollspeed = spd || false;

                if (self.timer) return false;

                self.timer = setTimeout(function () {

                    var top = self.getScrollTop();
                    var lft = self.getScrollLeft();

                    var dst = {};
                    dst.x = x - lft;
                    dst.y = y - top;
                    dst.px = lft;
                    dst.py = top;

                    var dd = Math.round(Math.sqrt(Math.pow(dst.x, 2) + Math.pow(dst.y, 2)));

                    //          var df = (self.newscrollspeed) ? self.newscrollspeed : dd;

                    var ms = (self.newscrollspeed && self.newscrollspeed > 1) ? self.newscrollspeed : self.getTransitionSpeed(dd);
                    if (self.newscrollspeed && self.newscrollspeed <= 1) ms *= self.newscrollspeed;

                    self.prepareTransition(ms, true);

                    if (self.timerscroll && self.timerscroll.tm) clearInterval(self.timerscroll.tm);

                    if (ms > 0) {

                        if (!self.scrollrunning && self.onscrollstart) {
                            var info = { "type": "scrollstart", "current": { "x": lft, "y": top }, "request": { "x": x, "y": y }, "end": { "x": self.newscrollx, "y": self.newscrolly }, "speed": ms };
                            self.onscrollstart.call(self, info);
                        }

                        if (cap.transitionend) {
                            if (!self.scrollendtrapped) {
                                self.scrollendtrapped = true;
                                self.bind(self.doc, cap.transitionend, self.onScrollTransitionEnd, false); //I have got to do something usefull!!
                            }
                        } else {
                            if (self.scrollendtrapped) clearTimeout(self.scrollendtrapped);
                            self.scrollendtrapped = setTimeout(self.onScrollTransitionEnd, ms);  // simulate transitionend event
                        }

                        var py = top;
                        var px = lft;
                        self.timerscroll = {
                            bz: new BezierClass(py, self.newscrolly, ms, 0, 0, 0.58, 1),
                            bh: new BezierClass(px, self.newscrollx, ms, 0, 0, 0.58, 1)
                        };
                        if (!self.cursorfreezed) self.timerscroll.tm = setInterval(function () { self.showCursor(self.getScrollTop(), self.getScrollLeft()) }, 60);

                    }

                    self.synched("doScroll-set", function () {
                        self.timer = 0;
                        if (self.scrollendtrapped) self.scrollrunning = true;
                        self.setScrollTop(self.newscrolly);
                        self.setScrollLeft(self.newscrollx);
                        if (!self.scrollendtrapped) self.onScrollTransitionEnd();
                    });


                }, 50);

            };

            this.cancelScroll = function () {
                if (!self.scrollendtrapped) return true;
                var py = self.getScrollTop();
                var px = self.getScrollLeft();
                self.scrollrunning = false;
                if (!cap.transitionend) clearTimeout(cap.transitionend);
                self.scrollendtrapped = false;
                self._unbind(self.doc, cap.transitionend, self.onScrollTransitionEnd);
                self.prepareTransition(0);
                self.setScrollTop(py); // fire event onscroll
                if (self.railh) self.setScrollLeft(px);
                if (self.timerscroll && self.timerscroll.tm) clearInterval(self.timerscroll.tm);
                self.timerscroll = false;

                self.cursorfreezed = false;

                //self.noticeCursor(false,py,px);
                self.showCursor(py, px);
                return self;
            };
            this.onScrollTransitionEnd = function () {
                if (self.scrollendtrapped) self._unbind(self.doc, cap.transitionend, self.onScrollTransitionEnd);
                self.scrollendtrapped = false;
                self.prepareTransition(0);
                if (self.timerscroll && self.timerscroll.tm) clearInterval(self.timerscroll.tm);
                self.timerscroll = false;
                var py = self.getScrollTop();
                var px = self.getScrollLeft();
                self.setScrollTop(py);  // fire event onscroll        
                if (self.railh) self.setScrollLeft(px);  // fire event onscroll left

                self.noticeCursor(false, py, px);

                self.cursorfreezed = false;

                if (py < 0) py = 0
                else if (py > self.page.maxh) py = self.page.maxh;
                if (px < 0) px = 0
                else if (px > self.page.maxw) px = self.page.maxw;
                if ((py != self.newscrolly) || (px != self.newscrollx)) return self.doScrollPos(px, py, self.opt.snapbackspeed);

                if (self.onscrollend && self.scrollrunning) {
                    //          var info = {"type":"scrollend","current":{"x":px,"y":py},"end":{"x":self.newscrollx,"y":self.newscrolly}};
                    //          self.onscrollend.call(self,info);
                    self.triggerScrollEnd();
                }
                self.scrollrunning = false;

            };

        } else {

            this.doScrollLeft = function (x, spd) {  //no-trans
                var y = (self.scrollrunning) ? self.newscrolly : self.getScrollTop();
                self.doScrollPos(x, y, spd);
            };

            this.doScrollTop = function (y, spd) {  //no-trans
                var x = (self.scrollrunning) ? self.newscrollx : self.getScrollLeft();
                self.doScrollPos(x, y, spd);
            };

            this.doScrollPos = function (x, y, spd) {  //no-trans
                var y = ((typeof y == "undefined") || (y === false)) ? self.getScrollTop(true) : y;

                if ((self.timer) && (self.newscrolly == y) && (self.newscrollx == x)) return true;

                if (self.timer) clearAnimationFrame(self.timer);
                self.timer = 0;

                var py = self.getScrollTop();
                var px = self.getScrollLeft();

                if (((self.newscrolly - py) * (y - py) < 0) || ((self.newscrollx - px) * (x - px) < 0)) self.cancelScroll();  //inverted movement detection

                self.newscrolly = y;
                self.newscrollx = x;

                if (!self.bouncescroll || !self.rail.visibility) {
                    if (self.newscrolly < 0) {
                        self.newscrolly = 0;
                    }
                    else if (self.newscrolly > self.page.maxh) {
                        self.newscrolly = self.page.maxh;
                    }
                }
                if (!self.bouncescroll || !self.railh.visibility) {
                    if (self.newscrollx < 0) {
                        self.newscrollx = 0;
                    }
                    else if (self.newscrollx > self.page.maxw) {
                        self.newscrollx = self.page.maxw;
                    }
                }

                self.dst = {};
                self.dst.x = x - px;
                self.dst.y = y - py;
                self.dst.px = px;
                self.dst.py = py;

                var dst = Math.round(Math.sqrt(Math.pow(self.dst.x, 2) + Math.pow(self.dst.y, 2)));

                self.dst.ax = self.dst.x / dst;
                self.dst.ay = self.dst.y / dst;

                var pa = 0;
                var pe = dst;

                if (self.dst.x == 0) {
                    pa = py;
                    pe = y;
                    self.dst.ay = 1;
                    self.dst.py = 0;
                } else if (self.dst.y == 0) {
                    pa = px;
                    pe = x;
                    self.dst.ax = 1;
                    self.dst.px = 0;
                }

                var ms = self.getTransitionSpeed(dst);
                if (spd && spd <= 1) ms *= spd;
                if (ms > 0) {
                    self.bzscroll = (self.bzscroll) ? self.bzscroll.update(pe, ms) : new BezierClass(pa, pe, ms, 0, 1, 0, 1);
                } else {
                    self.bzscroll = false;
                }

                if (self.timer) return;

                if ((py == self.page.maxh && y >= self.page.maxh) || (px == self.page.maxw && x >= self.page.maxw)) self.checkContentSize();

                var sync = 1;

                function scrolling() {
                    if (self.cancelAnimationFrame) return true;

                    self.scrollrunning = true;

                    sync = 1 - sync;
                    if (sync) return (self.timer = setAnimationFrame(scrolling) || 1);

                    var done = 0;

                    var sc = sy = self.getScrollTop();
                    if (self.dst.ay) {
                        sc = (self.bzscroll) ? self.dst.py + (self.bzscroll.getNow() * self.dst.ay) : self.newscrolly;
                        var dr = sc - sy;
                        if ((dr < 0 && sc < self.newscrolly) || (dr > 0 && sc > self.newscrolly)) sc = self.newscrolly;
                        self.setScrollTop(sc);
                        if (sc == self.newscrolly) done = 1;
                    } else {
                        done = 1;
                    }

                    var scx = sx = self.getScrollLeft();
                    if (self.dst.ax) {
                        scx = (self.bzscroll) ? self.dst.px + (self.bzscroll.getNow() * self.dst.ax) : self.newscrollx;
                        var dr = scx - sx;
                        if ((dr < 0 && scx < self.newscrollx) || (dr > 0 && scx > self.newscrollx)) scx = self.newscrollx;
                        self.setScrollLeft(scx);
                        if (scx == self.newscrollx) done += 1;
                    } else {
                        done += 1;
                    }

                    if (done == 2) {
                        self.timer = 0;
                        self.cursorfreezed = false;
                        self.bzscroll = false;
                        self.scrollrunning = false;
                        if (sc < 0) sc = 0;
                        else if (sc > self.page.maxh) sc = self.page.maxh;
                        if (scx < 0) scx = 0;
                        else if (scx > self.page.maxw) scx = self.page.maxw;
                        if ((scx != self.newscrollx) || (sc != self.newscrolly)) self.doScrollPos(scx, sc);
                        else {
                            if (self.onscrollend) {
                                /*							
                                                var info = {"type":"scrollend","current":{"x":sx,"y":sy},"end":{"x":self.newscrollx,"y":self.newscrolly}};
                                                self.onscrollend.call(self,info);
                                */
                                self.triggerScrollEnd();
                            }
                        }
                    } else {
                        self.timer = setAnimationFrame(scrolling) || 1;
                    }
                };
                self.cancelAnimationFrame = false;
                self.timer = 1;

                if (self.onscrollstart && !self.scrollrunning) {
                    var info = { "type": "scrollstart", "current": { "x": px, "y": py }, "request": { "x": x, "y": y }, "end": { "x": self.newscrollx, "y": self.newscrolly }, "speed": ms };
                    self.onscrollstart.call(self, info);
                }

                scrolling();

                if ((py == self.page.maxh && y >= py) || (px == self.page.maxw && x >= px)) self.checkContentSize();

                self.noticeCursor();
            };

            this.cancelScroll = function () {
                if (self.timer) clearAnimationFrame(self.timer);
                self.timer = 0;
                self.bzscroll = false;
                self.scrollrunning = false;
                return self;
            };

        }

        this.doScrollBy = function (stp, relative) {
            var ny = 0;
            if (relative) {
                ny = Math.floor((self.scroll.y - stp) * self.scrollratio.y)
            } else {
                var sy = (self.timer) ? self.newscrolly : self.getScrollTop(true);
                ny = sy - stp;
            }
            if (self.bouncescroll) {
                var haf = Math.round(self.view.h / 2);
                if (ny < -haf) ny = -haf
                else if (ny > (self.page.maxh + haf)) ny = (self.page.maxh + haf);
            }
            self.cursorfreezed = false;

            py = self.getScrollTop(true);
            if (ny < 0 && py <= 0) return self.noticeCursor();
            else if (ny > self.page.maxh && py >= self.page.maxh) {
                self.checkContentSize();
                return self.noticeCursor();
            }

            self.doScrollTop(ny);
        };

        this.doScrollLeftBy = function (stp, relative) {
            var nx = 0;
            if (relative) {
                nx = Math.floor((self.scroll.x - stp) * self.scrollratio.x)
            } else {
                var sx = (self.timer) ? self.newscrollx : self.getScrollLeft(true);
                nx = sx - stp;
            }
            if (self.bouncescroll) {
                var haf = Math.round(self.view.w / 2);
                if (nx < -haf) nx = -haf;
                else if (nx > (self.page.maxw + haf)) nx = (self.page.maxw + haf);
            }
            self.cursorfreezed = false;

            px = self.getScrollLeft(true);
            if (nx < 0 && px <= 0) return self.noticeCursor();
            else if (nx > self.page.maxw && px >= self.page.maxw) return self.noticeCursor();

            self.doScrollLeft(nx);
        };

        this.doScrollTo = function (pos, relative) {
            var ny = (relative) ? Math.round(pos * self.scrollratio.y) : pos;
            if (ny < 0) ny = 0;
            else if (ny > self.page.maxh) ny = self.page.maxh;
            self.cursorfreezed = false;
            self.doScrollTop(pos);
        };

        this.checkContentSize = function () {
            var pg = self.getContentSize();
            if ((pg.h != self.page.h) || (pg.w != self.page.w)) self.resize(false, pg);
        };

        self.onscroll = function (e) {
            if (self.rail.drag) return;
            if (!self.cursorfreezed) {
                self.synched('scroll', function () {
                    self.scroll.y = Math.round(self.getScrollTop() * (1 / self.scrollratio.y));
                    if (self.railh) self.scroll.x = Math.round(self.getScrollLeft() * (1 / self.scrollratio.x));
                    self.noticeCursor();
                });
            }
        };
        self.bind(self.docscroll, "scroll", self.onscroll);

        this.doZoomIn = function (e) {
            if (self.zoomactive) return;
            self.zoomactive = true;

            self.zoomrestore = {
                style: {}
            };
            var lst = ['position', 'top', 'left', 'zIndex', 'backgroundColor', 'marginTop', 'marginBottom', 'marginLeft', 'marginRight'];
            var win = self.win[0].style;
            for (var a in lst) {
                var pp = lst[a];
                self.zoomrestore.style[pp] = (typeof win[pp] != "undefined") ? win[pp] : '';
            }

            self.zoomrestore.style.width = self.win.css('width');
            self.zoomrestore.style.height = self.win.css('height');

            self.zoomrestore.padding = {
                w: self.win.outerWidth() - self.win.width(),
                h: self.win.outerHeight() - self.win.height()
            };

            if (cap.isios4) {
                self.zoomrestore.scrollTop = $(window).scrollTop();
                $(window).scrollTop(0);
            }

            self.win.css({
                "position": (cap.isios4) ? "absolute" : "fixed",
                "top": 0,
                "left": 0,
                "z-index": globalmaxzindex + 100,
                "margin": "0px"
            });
            var bkg = self.win.css("backgroundColor");
            if (bkg == "" || /transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(bkg)) self.win.css("backgroundColor", "#fff");
            self.rail.css({ "z-index": globalmaxzindex + 101 });
            self.zoom.css({ "z-index": globalmaxzindex + 102 });
            self.zoom.css('backgroundPosition', '0px -18px');
            self.resizeZoom();

            if (self.onzoomin) self.onzoomin.call(self);

            return self.cancelEvent(e);
        };

        this.doZoomOut = function (e) {
            if (!self.zoomactive) return;
            self.zoomactive = false;

            self.win.css("margin", "");
            self.win.css(self.zoomrestore.style);

            if (cap.isios4) {
                $(window).scrollTop(self.zoomrestore.scrollTop);
            }

            self.rail.css({ "z-index": self.zindex });
            self.zoom.css({ "z-index": self.zindex });
            self.zoomrestore = false;
            self.zoom.css('backgroundPosition', '0px 0px');
            self.onResize();

            if (self.onzoomout) self.onzoomout.call(self);

            return self.cancelEvent(e);
        };

        this.doZoom = function (e) {
            return (self.zoomactive) ? self.doZoomOut(e) : self.doZoomIn(e);
        };

        this.resizeZoom = function () {
            if (!self.zoomactive) return;

            var py = self.getScrollTop(); //preserve scrolling position
            self.win.css({
                width: $(window).width() - self.zoomrestore.padding.w + "px",
                height: $(window).height() - self.zoomrestore.padding.h + "px"
            });
            self.onResize();

            self.setScrollTop(Math.min(self.page.maxh, py));
        };

        this.init();

        $.nicescroll.push(this);

    };

    // Inspired by the work of Kin Blas
    // http://webpro.host.adobe.com/people/jblas/momentum/includes/jquery.momentum.0.7.js  


    var ScrollMomentumClass2D = function (nc) {
        var self = this;
        this.nc = nc;

        this.lastx = 0;
        this.lasty = 0;
        this.speedx = 0;
        this.speedy = 0;
        this.lasttime = 0;
        this.steptime = 0;
        this.snapx = false;
        this.snapy = false;
        this.demulx = 0;
        this.demuly = 0;

        this.lastscrollx = -1;
        this.lastscrolly = -1;

        this.chkx = 0;
        this.chky = 0;

        this.timer = 0;

        this.time = function () {
            return +new Date();//beautifull hack
        };

        this.reset = function (px, py) {
            self.stop();
            var now = self.time();
            self.steptime = 0;
            self.lasttime = now;
            self.speedx = 0;
            self.speedy = 0;
            self.lastx = px;
            self.lasty = py;
            self.lastscrollx = -1;
            self.lastscrolly = -1;
        };

        this.update = function (px, py) {
            var now = self.time();
            self.steptime = now - self.lasttime;
            self.lasttime = now;
            var dy = py - self.lasty;
            var dx = px - self.lastx;
            var sy = self.nc.getScrollTop();
            var sx = self.nc.getScrollLeft();
            var newy = sy + dy;
            var newx = sx + dx;
            self.snapx = (newx < 0) || (newx > self.nc.page.maxw);
            self.snapy = (newy < 0) || (newy > self.nc.page.maxh);
            self.speedx = dx;
            self.speedy = dy;
            self.lastx = px;
            self.lasty = py;
        };

        this.stop = function () {
            self.nc.unsynched("domomentum2d");
            if (self.timer) clearTimeout(self.timer);
            self.timer = 0;
            self.lastscrollx = -1;
            self.lastscrolly = -1;
        };

        this.doSnapy = function (nx, ny) {
            var snap = false;

            if (ny < 0) {
                ny = 0;
                snap = true;
            }
            else if (ny > self.nc.page.maxh) {
                ny = self.nc.page.maxh;
                snap = true;
            }

            if (nx < 0) {
                nx = 0;
                snap = true;
            }
            else if (nx > self.nc.page.maxw) {
                nx = self.nc.page.maxw;
                snap = true;
            }

            (snap) ? self.nc.doScrollPos(nx, ny, self.nc.opt.snapbackspeed) : self.nc.triggerScrollEnd();
        };

        this.doMomentum = function (gp) {
            var t = self.time();
            var l = (gp) ? t + gp : self.lasttime;

            var sl = self.nc.getScrollLeft();
            var st = self.nc.getScrollTop();

            var pageh = self.nc.page.maxh;
            var pagew = self.nc.page.maxw;

            self.speedx = (pagew > 0) ? Math.min(60, self.speedx) : 0;
            self.speedy = (pageh > 0) ? Math.min(60, self.speedy) : 0;

            var chk = l && (t - l) <= 60;

            if ((st < 0) || (st > pageh) || (sl < 0) || (sl > pagew)) chk = false;

            var sy = (self.speedy && chk) ? self.speedy : false;
            var sx = (self.speedx && chk) ? self.speedx : false;

            if (sy || sx) {
                var tm = Math.max(16, self.steptime); //timeout granularity

                if (tm > 50) {  // do smooth
                    var xm = tm / 50;
                    self.speedx *= xm;
                    self.speedy *= xm;
                    tm = 50;
                }

                self.demulxy = 0;

                self.lastscrollx = self.nc.getScrollLeft();
                self.chkx = self.lastscrollx;
                self.lastscrolly = self.nc.getScrollTop();
                self.chky = self.lastscrolly;

                var nx = self.lastscrollx;
                var ny = self.lastscrolly;

                var onscroll = function () {
                    var df = ((self.time() - t) > 600) ? 0.04 : 0.02;

                    if (self.speedx) {
                        nx = Math.floor(self.lastscrollx - (self.speedx * (1 - self.demulxy)));
                        self.lastscrollx = nx;
                        if ((nx < 0) || (nx > pagew)) df = 0.10;
                    }

                    if (self.speedy) {
                        ny = Math.floor(self.lastscrolly - (self.speedy * (1 - self.demulxy)));
                        self.lastscrolly = ny;
                        if ((ny < 0) || (ny > pageh)) df = 0.10;
                    }

                    self.demulxy = Math.min(1, self.demulxy + df);

                    self.nc.synched("domomentum2d", function () {

                        if (self.speedx) {
                            var scx = self.nc.getScrollLeft();
                            if (scx != self.chkx) self.stop();
                            self.chkx = nx;
                            self.nc.setScrollLeft(nx);
                        }

                        if (self.speedy) {
                            var scy = self.nc.getScrollTop();
                            if (scy != self.chky) self.stop();
                            self.chky = ny;
                            self.nc.setScrollTop(ny);
                        }

                        if (!self.timer) {
                            self.nc.hideCursor();
                            self.doSnapy(nx, ny);
                        }

                    });

                    if (self.demulxy < 1) {
                        self.timer = setTimeout(onscroll, tm);
                    } else {
                        self.stop();
                        self.nc.hideCursor();
                        self.doSnapy(nx, ny);
                    }
                };

                onscroll();

            } else {
                self.doSnapy(self.nc.getScrollLeft(), self.nc.getScrollTop());
            }

        }

    };


    // override jQuery scrollTop

    var _scrollTop = jQuery.fn.scrollTop; // preserve original function

    jQuery.cssHooks["pageYOffset"] = {
        get: function (elem, computed, extra) {
            var nice = $.data(elem, '__nicescroll') || false;
            return (nice && nice.ishwscroll) ? nice.getScrollTop() : _scrollTop.call(elem);
        },
        set: function (elem, value) {
            var nice = $.data(elem, '__nicescroll') || false;
            (nice && nice.ishwscroll) ? nice.setScrollTop(parseInt(value)) : _scrollTop.call(elem, value);
            return this;
        }
    };

    /*  
      $.fx.step["scrollTop"] = function(fx){    
        $.cssHooks["scrollTop"].set( fx.elem, fx.now + fx.unit );
      };
    */

    jQuery.fn.scrollTop = function (value) {
        if (typeof value == "undefined") {
            var nice = (this[0]) ? $.data(this[0], '__nicescroll') || false : false;
            return (nice && nice.ishwscroll) ? nice.getScrollTop() : _scrollTop.call(this);
        } else {
            return this.each(function () {
                var nice = $.data(this, '__nicescroll') || false;
                (nice && nice.ishwscroll) ? nice.setScrollTop(parseInt(value)) : _scrollTop.call($(this), value);
            });
        }
    };

    // override jQuery scrollLeft

    var _scrollLeft = jQuery.fn.scrollLeft; // preserve original function

    $.cssHooks.pageXOffset = {
        get: function (elem, computed, extra) {
            var nice = $.data(elem, '__nicescroll') || false;
            return (nice && nice.ishwscroll) ? nice.getScrollLeft() : _scrollLeft.call(elem);
        },
        set: function (elem, value) {
            var nice = $.data(elem, '__nicescroll') || false;
            (nice && nice.ishwscroll) ? nice.setScrollLeft(parseInt(value)) : _scrollLeft.call(elem, value);
            return this;
        }
    };

    /*  
      $.fx.step["scrollLeft"] = function(fx){
        $.cssHooks["scrollLeft"].set( fx.elem, fx.now + fx.unit );
      };  
    */

    jQuery.fn.scrollLeft = function (value) {
        if (typeof value == "undefined") {
            var nice = (this[0]) ? $.data(this[0], '__nicescroll') || false : false;
            return (nice && nice.ishwscroll) ? nice.getScrollLeft() : _scrollLeft.call(this);
        } else {
            return this.each(function () {
                var nice = $.data(this, '__nicescroll') || false;
                (nice && nice.ishwscroll) ? nice.setScrollLeft(parseInt(value)) : _scrollLeft.call($(this), value);
            });
        }
    };

    var NiceScrollArray = function (doms) {
        var self = this;
        this.length = 0;
        this.name = "nicescrollarray";

        this.each = function (fn) {
            for (var a = 0, i = 0; a < self.length; a++) fn.call(self[a], i++);
            return self;
        };

        this.push = function (nice) {
            self[self.length] = nice;
            self.length++;
        };

        this.eq = function (idx) {
            return self[idx];
        };

        if (doms) {
            for (var a = 0; a < doms.length; a++) {
                var nice = $.data(doms[a], '__nicescroll') || false;
                if (nice) {
                    this[this.length] = nice;
                    this.length++;
                }
            };
        }

        return this;
    };

    function mplex(el, lst, fn) {
        for (var a = 0; a < lst.length; a++) fn(el, lst[a]);
    };
    mplex(
      NiceScrollArray.prototype,
      ['show', 'hide', 'toggle', 'onResize', 'resize', 'remove', 'stop', 'doScrollPos'],
      function (e, n) {
          e[n] = function () {
              var args = arguments;
              return this.each(function () {
                  this[n].apply(this, args);
              });
          };
      }
    );

    jQuery.fn.getNiceScroll = function (index) {
        if (typeof index == "undefined") {
            return new NiceScrollArray(this);
        } else {
            var nice = this[index] && $.data(this[index], '__nicescroll') || false;
            return nice;
        }
    };

    jQuery.extend(jQuery.expr[':'], {
        nicescroll: function (a) {
            return ($.data(a, '__nicescroll')) ? true : false;
        }
    });

    $.fn.niceScroll = function (wrapper, opt) {
        if (typeof opt == "undefined") {
            if ((typeof wrapper == "object") && !("jquery" in wrapper)) {
                opt = wrapper;
                wrapper = false;
            }
        }
        var ret = new NiceScrollArray();
        if (typeof opt == "undefined") opt = {};

        if (wrapper || false) {
            opt.doc = $(wrapper);
            opt.win = $(this);
        }
        var docundef = !("doc" in opt);
        if (!docundef && !("win" in opt)) opt.win = $(this);

        this.each(function () {
            var nice = $(this).data('__nicescroll') || false;
            if (!nice) {
                opt.doc = (docundef) ? $(this) : opt.doc;
                nice = new NiceScrollClass(opt, $(this));
                $(this).data('__nicescroll', nice);
            }
            ret.push(nice);
        });
        return (ret.length == 1) ? ret[0] : ret;
    };

    window.NiceScroll = {
        getjQuery: function () { return jQuery }
    };

    if (!$.nicescroll) {
        $.nicescroll = new NiceScrollArray();
        $.nicescroll.options = _globaloptions;
    }

}));
;
/**
 * History.js Native Adapter
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

// Closure
(function(window,undefined){
	"use strict";

	// Localise Globals
	var History = window.History = window.History||{};

	// Check Existence
	if ( typeof History.Adapter !== 'undefined' ) {
		throw new Error('History.js Adapter has already been loaded...');
	}

	// Add the Adapter
	History.Adapter = {
		/**
		 * History.Adapter.handlers[uid][eventName] = Array
		 */
		handlers: {},

		/**
		 * History.Adapter._uid
		 * The current element unique identifier
		 */
		_uid: 1,

		/**
		 * History.Adapter.uid(element)
		 * @param {Element} element
		 * @return {String} uid
		 */
		uid: function(element){
			return element._uid || (element._uid = History.Adapter._uid++);
		},

		/**
		 * History.Adapter.bind(el,event,callback)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Function} callback
		 * @return
		 */
		bind: function(element,eventName,callback){
			// Prepare
			var uid = History.Adapter.uid(element);

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
			History.Adapter.handlers[uid][eventName].push(callback);

			// Bind Global Listener
			element['on'+eventName] = (function(element,eventName){
				return function(event){
					History.Adapter.trigger(element,eventName,event);
				};
			})(element,eventName);
		},

		/**
		 * History.Adapter.trigger(el,event)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Object} event - a object of event data
		 * @return
		 */
		trigger: function(element,eventName,event){
			// Prepare
			event = event || {};
			var uid = History.Adapter.uid(element),
				i,n;

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];

			// Fire Listeners
			for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i<n; ++i ) {
				History.Adapter.handlers[uid][eventName][i].apply(this,[event]);
			}
		},

		/**
		 * History.Adapter.extractEventData(key,event,extra)
		 * @param {String} key - key for the event data to extract
		 * @param {String} event - custom and standard events
		 * @return {mixed}
		 */
		extractEventData: function(key,event){
			var result = (event && event[key]) || undefined;
			return result;
		},

		/**
		 * History.Adapter.onDomLoad(callback)
		 * @param {Function} callback
		 * @return
		 */
		onDomLoad: function(callback) {
			var timeout = window.setTimeout(function(){
				callback();
			},2000);
			window.onload = function(){
				clearTimeout(timeout);
				callback();
			};
		}
	};

	// Try to Initialise History
	if ( typeof History.init !== 'undefined' ) {
		History.init();
	}

})(window);
/**
 * History.js Core
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

(function(window,undefined){
	"use strict";

	// ========================================================================
	// Initialise

	// Localise Globals
	var
		console = window.console||undefined, // Prevent a JSLint complain
		document = window.document, // Make sure we are using the correct document
		navigator = window.navigator, // Make sure we are using the correct navigator
		sessionStorage = window.sessionStorage||false, // sessionStorage
		setTimeout = window.setTimeout,
		clearTimeout = window.clearTimeout,
		setInterval = window.setInterval,
		clearInterval = window.clearInterval,
		JSON = window.JSON,
		alert = window.alert,
		History = window.History = window.History||{}, // Public History Object
		history = window.history; // Old History Object

	try {
		sessionStorage.setItem('TEST', '1');
		sessionStorage.removeItem('TEST');
	} catch(e) {
		sessionStorage = false;
	}

	// MooTools Compatibility
	JSON.stringify = JSON.stringify||JSON.encode;
	JSON.parse = JSON.parse||JSON.decode;

	// Check Existence
	if ( typeof History.init !== 'undefined' ) {
		throw new Error('History.js Core has already been loaded...');
	}

	// Initialise History
	History.init = function(options){
		// Check Load Status of Adapter
		if ( typeof History.Adapter === 'undefined' ) {
			return false;
		}

		// Check Load Status of Core
		if ( typeof History.initCore !== 'undefined' ) {
			History.initCore();
		}

		// Check Load Status of HTML4 Support
		if ( typeof History.initHtml4 !== 'undefined' ) {
			History.initHtml4();
		}

		// Return true
		return true;
	};


	// ========================================================================
	// Initialise Core

	// Initialise Core
	History.initCore = function(options){
		// Initialise
		if ( typeof History.initCore.initialized !== 'undefined' ) {
			// Already Loaded
			return false;
		}
		else {
			History.initCore.initialized = true;
		}


		// ====================================================================
		// Options

		/**
		 * History.options
		 * Configurable options
		 */
		History.options = History.options||{};

		/**
		 * History.options.hashChangeInterval
		 * How long should the interval be before hashchange checks
		 */
		History.options.hashChangeInterval = History.options.hashChangeInterval || 100;

		/**
		 * History.options.safariPollInterval
		 * How long should the interval be before safari poll checks
		 */
		History.options.safariPollInterval = History.options.safariPollInterval || 500;

		/**
		 * History.options.doubleCheckInterval
		 * How long should the interval be before we perform a double check
		 */
		History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;

		/**
		 * History.options.disableSuid
		 * Force History not to append suid
		 */
		History.options.disableSuid = History.options.disableSuid || false;

		/**
		 * History.options.storeInterval
		 * How long should we wait between store calls
		 */
		History.options.storeInterval = History.options.storeInterval || 1000;

		/**
		 * History.options.busyDelay
		 * How long should we wait between busy events
		 */
		History.options.busyDelay = History.options.busyDelay || 250;

		/**
		 * History.options.debug
		 * If true will enable debug messages to be logged
		 */
		History.options.debug = History.options.debug || false;

		/**
		 * History.options.initialTitle
		 * What is the title of the initial state
		 */
		History.options.initialTitle = History.options.initialTitle || document.title;

		/**
		 * History.options.html4Mode
		 * If true, will force HTMl4 mode (hashtags)
		 */
		History.options.html4Mode = History.options.html4Mode || false;

		/**
		 * History.options.delayInit
		 * Want to override default options and call init manually.
		 */
		History.options.delayInit = History.options.delayInit || false;


		// ====================================================================
		// Interval record

		/**
		 * History.intervalList
		 * List of intervals set, to be cleared when document is unloaded.
		 */
		History.intervalList = [];

		/**
		 * History.clearAllIntervals
		 * Clears all setInterval instances.
		 */
		History.clearAllIntervals = function(){
			var i, il = History.intervalList;
			if (typeof il !== "undefined" && il !== null) {
				for (i = 0; i < il.length; i++) {
					clearInterval(il[i]);
				}
				History.intervalList = null;
			}
		};


		// ====================================================================
		// Debug

		/**
		 * History.debug(message,...)
		 * Logs the passed arguments if debug enabled
		 */
		History.debug = function(){
			if ( (History.options.debug||false) ) {
				History.log.apply(History,arguments);
			}
		};

		/**
		 * History.log(message,...)
		 * Logs the passed arguments
		 */
		History.log = function(){
			// Prepare
			var
				consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
				textarea = document.getElementById('log'),
				message,
				i,n,
				args,arg
				;

			// Write to Console
			if ( consoleExists ) {
				args = Array.prototype.slice.call(arguments);
				message = args.shift();
				if ( typeof console.debug !== 'undefined' ) {
					console.debug.apply(console,[message,args]);
				}
				else {
					console.log.apply(console,[message,args]);
				}
			}
			else {
				message = ("\n"+arguments[0]+"\n");
			}

			// Write to log
			for ( i=1,n=arguments.length; i<n; ++i ) {
				arg = arguments[i];
				if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) {
					try {
						arg = JSON.stringify(arg);
					}
					catch ( Exception ) {
						// Recursive Object
					}
				}
				message += "\n"+arg+"\n";
			}

			// Textarea
			if ( textarea ) {
				textarea.value += message+"\n-----\n";
				textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
			}
			// No Textarea, No Console
			else if ( !consoleExists ) {
				alert(message);
			}

			// Return true
			return true;
		};


		// ====================================================================
		// Emulated Status

		/**
		 * History.getInternetExplorerMajorVersion()
		 * Get's the major version of Internet Explorer
		 * @return {integer}
		 * @license Public Domain
		 * @author Benjamin Arthur Lupton <contact@balupton.com>
		 * @author James Padolsey <https://gist.github.com/527683>
		 */
		History.getInternetExplorerMajorVersion = function(){
			var result = History.getInternetExplorerMajorVersion.cached =
					(typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
				?	History.getInternetExplorerMajorVersion.cached
				:	(function(){
						var v = 3,
								div = document.createElement('div'),
								all = div.getElementsByTagName('i');
						while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
						return (v > 4) ? v : false;
					})()
				;
			return result;
		};

		/**
		 * History.isInternetExplorer()
		 * Are we using Internet Explorer?
		 * @return {boolean}
		 * @license Public Domain
		 * @author Benjamin Arthur Lupton <contact@balupton.com>
		 */
		History.isInternetExplorer = function(){
			var result =
				History.isInternetExplorer.cached =
				(typeof History.isInternetExplorer.cached !== 'undefined')
					?	History.isInternetExplorer.cached
					:	Boolean(History.getInternetExplorerMajorVersion())
				;
			return result;
		};

		/**
		 * History.emulated
		 * Which features require emulating?
		 */

		if (History.options.html4Mode) {
			History.emulated = {
				pushState : true,
				hashChange: true
			};
		}

		else {

			History.emulated = {
				pushState: !Boolean(
					window.history && window.history.pushState && window.history.replaceState
					&& !(
						(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
						|| (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
					)
				),
				hashChange: Boolean(
					!(('onhashchange' in window) || ('onhashchange' in document))
					||
					(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
				)
			};
		}

		/**
		 * History.enabled
		 * Is History enabled?
		 */
		History.enabled = !History.emulated.pushState;

		/**
		 * History.bugs
		 * Which bugs are present
		 */
		History.bugs = {
			/**
			 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
			 * https://bugs.webkit.org/show_bug.cgi?id=56249
			 */
			setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),

			/**
			 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
			 * https://bugs.webkit.org/show_bug.cgi?id=42940
			 */
			safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),

			/**
			 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
			 */
			ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),

			/**
			 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
			 */
			hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
		};

		/**
		 * History.isEmptyObject(obj)
		 * Checks to see if the Object is Empty
		 * @param {Object} obj
		 * @return {boolean}
		 */
		History.isEmptyObject = function(obj) {
			for ( var name in obj ) {
				if ( obj.hasOwnProperty(name) ) {
					return false;
				}
			}
			return true;
		};

		/**
		 * History.cloneObject(obj)
		 * Clones a object and eliminate all references to the original contexts
		 * @param {Object} obj
		 * @return {Object}
		 */
		History.cloneObject = function(obj) {
			var hash,newObj;
			if ( obj ) {
				hash = JSON.stringify(obj);
				newObj = JSON.parse(hash);
			}
			else {
				newObj = {};
			}
			return newObj;
		};


		// ====================================================================
		// URL Helpers

		/**
		 * History.getRootUrl()
		 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
		 * @return {String} rootUrl
		 */
		History.getRootUrl = function(){
			// Create
			var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
			if ( document.location.port||false ) {
				rootUrl += ':'+document.location.port;
			}
			rootUrl += '/';

			// Return
			return rootUrl;
		};

		/**
		 * History.getBaseHref()
		 * Fetches the `href` attribute of the `<base href="...">` element if it exists
		 * @return {String} baseHref
		 */
		History.getBaseHref = function(){
			// Create
			var
				baseElements = document.getElementsByTagName('base'),
				baseElement = null,
				baseHref = '';

			// Test for Base Element
			if ( baseElements.length === 1 ) {
				// Prepare for Base Element
				baseElement = baseElements[0];
				baseHref = baseElement.href.replace(/[^\/]+$/,'');
			}

			// Adjust trailing slash
			baseHref = baseHref.replace(/\/+$/,'');
			if ( baseHref ) baseHref += '/';

			// Return
			return baseHref;
		};

		/**
		 * History.getBaseUrl()
		 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
		 * @return {String} baseUrl
		 */
		History.getBaseUrl = function(){
			// Create
			var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();

			// Return
			return baseUrl;
		};

		/**
		 * History.getPageUrl()
		 * Fetches the URL of the current page
		 * @return {String} pageUrl
		 */
		History.getPageUrl = function(){
			// Fetch
			var
				State = History.getState(false,false),
				stateUrl = (State||{}).url||History.getLocationHref(),
				pageUrl;

			// Create
			pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
				return (/\./).test(part) ? part : part+'/';
			});

			// Return
			return pageUrl;
		};

		/**
		 * History.getBasePageUrl()
		 * Fetches the Url of the directory of the current page
		 * @return {String} basePageUrl
		 */
		History.getBasePageUrl = function(){
			// Create
			var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
				return (/[^\/]$/).test(part) ? '' : part;
			}).replace(/\/+$/,'')+'/';

			// Return
			return basePageUrl;
		};

		/**
		 * History.getFullUrl(url)
		 * Ensures that we have an absolute URL and not a relative URL
		 * @param {string} url
		 * @param {Boolean} allowBaseHref
		 * @return {string} fullUrl
		 */
		History.getFullUrl = function(url,allowBaseHref){
			// Prepare
			var fullUrl = url, firstChar = url.substring(0,1);
			allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;

			// Check
			if ( /[a-z]+\:\/\//.test(url) ) {
				// Full URL
			}
			else if ( firstChar === '/' ) {
				// Root URL
				fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
			}
			else if ( firstChar === '#' ) {
				// Anchor URL
				fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
			}
			else if ( firstChar === '?' ) {
				// Query URL
				fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
			}
			else {
				// Relative URL
				if ( allowBaseHref ) {
					fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
				} else {
					fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
				}
				// We have an if condition above as we do not want hashes
				// which are relative to the baseHref in our URLs
				// as if the baseHref changes, then all our bookmarks
				// would now point to different locations
				// whereas the basePageUrl will always stay the same
			}

			// Return
			return fullUrl.replace(/\#$/,'');
		};

		/**
		 * History.getShortUrl(url)
		 * Ensures that we have a relative URL and not a absolute URL
		 * @param {string} url
		 * @return {string} url
		 */
		History.getShortUrl = function(url){
			// Prepare
			var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();

			// Trim baseUrl
			if ( History.emulated.pushState ) {
				// We are in a if statement as when pushState is not emulated
				// The actual url these short urls are relative to can change
				// So within the same session, we the url may end up somewhere different
				shortUrl = shortUrl.replace(baseUrl,'');
			}

			// Trim rootUrl
			shortUrl = shortUrl.replace(rootUrl,'/');

			// Ensure we can still detect it as a state
			if ( History.isTraditionalAnchor(shortUrl) ) {
				shortUrl = './'+shortUrl;
			}

			// Clean It
			shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');

			// Return
			return shortUrl;
		};

		/**
		 * History.getLocationHref(document)
		 * Returns a normalized version of document.location.href
		 * accounting for browser inconsistencies, etc.
		 *
		 * This URL will be URI-encoded and will include the hash
		 *
		 * @param {object} document
		 * @return {string} url
		 */
		History.getLocationHref = function(doc) {
			doc = doc || document;

			// most of the time, this will be true
			if (doc.URL === doc.location.href)
				return doc.location.href;

			// some versions of webkit URI-decode document.location.href
			// but they leave document.URL in an encoded state
			if (doc.location.href === decodeURIComponent(doc.URL))
				return doc.URL;

			// FF 3.6 only updates document.URL when a page is reloaded
			// document.location.href is updated correctly
			if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
				return doc.location.href;

			if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
				return doc.location.href;
			
			return doc.URL || doc.location.href;
		};


		// ====================================================================
		// State Storage

		/**
		 * History.store
		 * The store for all session specific data
		 */
		History.store = {};

		/**
		 * History.idToState
		 * 1-1: State ID to State Object
		 */
		History.idToState = History.idToState||{};

		/**
		 * History.stateToId
		 * 1-1: State String to State ID
		 */
		History.stateToId = History.stateToId||{};

		/**
		 * History.urlToId
		 * 1-1: State URL to State ID
		 */
		History.urlToId = History.urlToId||{};

		/**
		 * History.storedStates
		 * Store the states in an array
		 */
		History.storedStates = History.storedStates||[];

		/**
		 * History.savedStates
		 * Saved the states in an array
		 */
		History.savedStates = History.savedStates||[];

		/**
		 * History.noramlizeStore()
		 * Noramlize the store by adding necessary values
		 */
		History.normalizeStore = function(){
			History.store.idToState = History.store.idToState||{};
			History.store.urlToId = History.store.urlToId||{};
			History.store.stateToId = History.store.stateToId||{};
		};

		/**
		 * History.getState()
		 * Get an object containing the data, title and url of the current state
		 * @param {Boolean} friendly
		 * @param {Boolean} create
		 * @return {Object} State
		 */
		History.getState = function(friendly,create){
			// Prepare
			if ( typeof friendly === 'undefined' ) { friendly = true; }
			if ( typeof create === 'undefined' ) { create = true; }

			// Fetch
			var State = History.getLastSavedState();

			// Create
			if ( !State && create ) {
				State = History.createStateObject();
			}

			// Adjust
			if ( friendly ) {
				State = History.cloneObject(State);
				State.url = State.cleanUrl||State.url;
			}

			// Return
			return State;
		};

		/**
		 * History.getIdByState(State)
		 * Gets a ID for a State
		 * @param {State} newState
		 * @return {String} id
		 */
		History.getIdByState = function(newState){

			// Fetch ID
			var id = History.extractId(newState.url),
				str;

			if ( !id ) {
				// Find ID via State String
				str = History.getStateString(newState);
				if ( typeof History.stateToId[str] !== 'undefined' ) {
					id = History.stateToId[str];
				}
				else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
					id = History.store.stateToId[str];
				}
				else {
					// Generate a new ID
					while ( true ) {
						id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
						if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
							break;
						}
					}

					// Apply the new State to the ID
					History.stateToId[str] = id;
					History.idToState[id] = newState;
				}
			}

			// Return ID
			return id;
		};

		/**
		 * History.normalizeState(State)
		 * Expands a State Object
		 * @param {object} State
		 * @return {object}
		 */
		History.normalizeState = function(oldState){
			// Variables
			var newState, dataNotEmpty;

			// Prepare
			if ( !oldState || (typeof oldState !== 'object') ) {
				oldState = {};
			}

			// Check
			if ( typeof oldState.normalized !== 'undefined' ) {
				return oldState;
			}

			// Adjust
			if ( !oldState.data || (typeof oldState.data !== 'object') ) {
				oldState.data = {};
			}

			// ----------------------------------------------------------------

			// Create
			newState = {};
			newState.normalized = true;
			newState.title = oldState.title||'';
			newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
			newState.hash = History.getShortUrl(newState.url);
			newState.data = History.cloneObject(oldState.data);

			// Fetch ID
			newState.id = History.getIdByState(newState);

			// ----------------------------------------------------------------

			// Clean the URL
			newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
			newState.url = newState.cleanUrl;

			// Check to see if we have more than just a url
			dataNotEmpty = !History.isEmptyObject(newState.data);

			// Apply
			if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
				// Add ID to Hash
				newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
				if ( !/\?/.test(newState.hash) ) {
					newState.hash += '?';
				}
				newState.hash += '&_suid='+newState.id;
			}

			// Create the Hashed URL
			newState.hashedUrl = History.getFullUrl(newState.hash);

			// ----------------------------------------------------------------

			// Update the URL if we have a duplicate
			if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
				newState.url = newState.hashedUrl;
			}

			// ----------------------------------------------------------------

			// Return
			return newState;
		};

		/**
		 * History.createStateObject(data,title,url)
		 * Creates a object based on the data, title and url state params
		 * @param {object} data
		 * @param {string} title
		 * @param {string} url
		 * @return {object}
		 */
		History.createStateObject = function(data,title,url){
			// Hashify
			var State = {
				'data': data,
				'title': title,
				'url': url
			};

			// Expand the State
			State = History.normalizeState(State);

			// Return object
			return State;
		};

		/**
		 * History.getStateById(id)
		 * Get a state by it's UID
		 * @param {String} id
		 */
		History.getStateById = function(id){
			// Prepare
			id = String(id);

			// Retrieve
			var State = History.idToState[id] || History.store.idToState[id] || undefined;

			// Return State
			return State;
		};

		/**
		 * Get a State's String
		 * @param {State} passedState
		 */
		History.getStateString = function(passedState){
			// Prepare
			var State, cleanedState, str;

			// Fetch
			State = History.normalizeState(passedState);

			// Clean
			cleanedState = {
				data: State.data,
				title: passedState.title,
				url: passedState.url
			};

			// Fetch
			str = JSON.stringify(cleanedState);

			// Return
			return str;
		};

		/**
		 * Get a State's ID
		 * @param {State} passedState
		 * @return {String} id
		 */
		History.getStateId = function(passedState){
			// Prepare
			var State, id;

			// Fetch
			State = History.normalizeState(passedState);

			// Fetch
			id = State.id;

			// Return
			return id;
		};

		/**
		 * History.getHashByState(State)
		 * Creates a Hash for the State Object
		 * @param {State} passedState
		 * @return {String} hash
		 */
		History.getHashByState = function(passedState){
			// Prepare
			var State, hash;

			// Fetch
			State = History.normalizeState(passedState);

			// Hash
			hash = State.hash;

			// Return
			return hash;
		};

		/**
		 * History.extractId(url_or_hash)
		 * Get a State ID by it's URL or Hash
		 * @param {string} url_or_hash
		 * @return {string} id
		 */
		History.extractId = function ( url_or_hash ) {
			// Prepare
			var id,parts,url, tmp;

			// Extract
			
			// If the URL has a #, use the id from before the #
			if (url_or_hash.indexOf('#') != -1)
			{
				tmp = url_or_hash.split("#")[0];
			}
			else
			{
				tmp = url_or_hash;
			}
			
			parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
			url = parts ? (parts[1]||url_or_hash) : url_or_hash;
			id = parts ? String(parts[2]||'') : '';

			// Return
			return id||false;
		};

		/**
		 * History.isTraditionalAnchor
		 * Checks to see if the url is a traditional anchor or not
		 * @param {String} url_or_hash
		 * @return {Boolean}
		 */
		History.isTraditionalAnchor = function(url_or_hash){
			// Check
			var isTraditional = !(/[\/\?\.]/.test(url_or_hash));

			// Return
			return isTraditional;
		};

		/**
		 * History.extractState
		 * Get a State by it's URL or Hash
		 * @param {String} url_or_hash
		 * @return {State|null}
		 */
		History.extractState = function(url_or_hash,create){
			// Prepare
			var State = null, id, url;
			create = create||false;

			// Fetch SUID
			id = History.extractId(url_or_hash);
			if ( id ) {
				State = History.getStateById(id);
			}

			// Fetch SUID returned no State
			if ( !State ) {
				// Fetch URL
				url = History.getFullUrl(url_or_hash);

				// Check URL
				id = History.getIdByUrl(url)||false;
				if ( id ) {
					State = History.getStateById(id);
				}

				// Create State
				if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
					State = History.createStateObject(null,null,url);
				}
			}

			// Return
			return State;
		};

		/**
		 * History.getIdByUrl()
		 * Get a State ID by a State URL
		 */
		History.getIdByUrl = function(url){
			// Fetch
			var id = History.urlToId[url] || History.store.urlToId[url] || undefined;

			// Return
			return id;
		};

		/**
		 * History.getLastSavedState()
		 * Get an object containing the data, title and url of the current state
		 * @return {Object} State
		 */
		History.getLastSavedState = function(){
			return History.savedStates[History.savedStates.length-1]||undefined;
		};

		/**
		 * History.getLastStoredState()
		 * Get an object containing the data, title and url of the current state
		 * @return {Object} State
		 */
		History.getLastStoredState = function(){
			return History.storedStates[History.storedStates.length-1]||undefined;
		};

		/**
		 * History.hasUrlDuplicate
		 * Checks if a Url will have a url conflict
		 * @param {Object} newState
		 * @return {Boolean} hasDuplicate
		 */
		History.hasUrlDuplicate = function(newState) {
			// Prepare
			var hasDuplicate = false,
				oldState;

			// Fetch
			oldState = History.extractState(newState.url);

			// Check
			hasDuplicate = oldState && oldState.id !== newState.id;

			// Return
			return hasDuplicate;
		};

		/**
		 * History.storeState
		 * Store a State
		 * @param {Object} newState
		 * @return {Object} newState
		 */
		History.storeState = function(newState){
			// Store the State
			History.urlToId[newState.url] = newState.id;

			// Push the State
			History.storedStates.push(History.cloneObject(newState));

			// Return newState
			return newState;
		};

		/**
		 * History.isLastSavedState(newState)
		 * Tests to see if the state is the last state
		 * @param {Object} newState
		 * @return {boolean} isLast
		 */
		History.isLastSavedState = function(newState){
			// Prepare
			var isLast = false,
				newId, oldState, oldId;

			// Check
			if ( History.savedStates.length ) {
				newId = newState.id;
				oldState = History.getLastSavedState();
				oldId = oldState.id;

				// Check
				isLast = (newId === oldId);
			}

			// Return
			return isLast;
		};

		/**
		 * History.saveState
		 * Push a State
		 * @param {Object} newState
		 * @return {boolean} changed
		 */
		History.saveState = function(newState){
			// Check Hash
			if ( History.isLastSavedState(newState) ) {
				return false;
			}

			// Push the State
			History.savedStates.push(History.cloneObject(newState));

			// Return true
			return true;
		};

		/**
		 * History.getStateByIndex()
		 * Gets a state by the index
		 * @param {integer} index
		 * @return {Object}
		 */
		History.getStateByIndex = function(index){
			// Prepare
			var State = null;

			// Handle
			if ( typeof index === 'undefined' ) {
				// Get the last inserted
				State = History.savedStates[History.savedStates.length-1];
			}
			else if ( index < 0 ) {
				// Get from the end
				State = History.savedStates[History.savedStates.length+index];
			}
			else {
				// Get from the beginning
				State = History.savedStates[index];
			}

			// Return State
			return State;
		};
		
		/**
		 * History.getCurrentIndex()
		 * Gets the current index
		 * @return (integer)
		*/
		History.getCurrentIndex = function(){
			// Prepare
			var index = null;
			
			// No states saved
			if(History.savedStates.length < 1) {
				index = 0;
			}
			else {
				index = History.savedStates.length-1;
			}
			return index;
		};

		// ====================================================================
		// Hash Helpers

		/**
		 * History.getHash()
		 * @param {Location=} location
		 * Gets the current document hash
		 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
		 * @return {string}
		 */
		History.getHash = function(doc){
			var url = History.getLocationHref(doc),
				hash;
			hash = History.getHashByUrl(url);
			return hash;
		};

		/**
		 * History.unescapeHash()
		 * normalize and Unescape a Hash
		 * @param {String} hash
		 * @return {string}
		 */
		History.unescapeHash = function(hash){
			// Prepare
			var result = History.normalizeHash(hash);

			// Unescape hash
			result = decodeURIComponent(result);

			// Return result
			return result;
		};

		/**
		 * History.normalizeHash()
		 * normalize a hash across browsers
		 * @return {string}
		 */
		History.normalizeHash = function(hash){
			// Prepare
			var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');

			// Return result
			return result;
		};

		/**
		 * History.setHash(hash)
		 * Sets the document hash
		 * @param {string} hash
		 * @return {History}
		 */
		History.setHash = function(hash,queue){
			// Prepare
			var State, pageUrl;

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.setHash: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.setHash,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Log
			//History.debug('History.setHash: called',hash);

			// Make Busy + Continue
			History.busy(true);

			// Check if hash is a state
			State = History.extractState(hash,true);
			if ( State && !History.emulated.pushState ) {
				// Hash is a state so skip the setHash
				//History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);

				// PushState
				History.pushState(State.data,State.title,State.url,false);
			}
			else if ( History.getHash() !== hash ) {
				// Hash is a proper hash, so apply it

				// Handle browser bugs
				if ( History.bugs.setHash ) {
					// Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249

					// Fetch the base page
					pageUrl = History.getPageUrl();

					// Safari hash apply
					History.pushState(null,null,pageUrl+'#'+hash,false);
				}
				else {
					// Normal hash apply
					document.location.hash = hash;
				}
			}

			// Chain
			return History;
		};

		/**
		 * History.escape()
		 * normalize and Escape a Hash
		 * @return {string}
		 */
		History.escapeHash = function(hash){
			// Prepare
			var result = History.normalizeHash(hash);

			// Escape hash
			result = window.encodeURIComponent(result);

			// IE6 Escape Bug
			if ( !History.bugs.hashEscape ) {
				// Restore common parts
				result = result
					.replace(/\%21/g,'!')
					.replace(/\%26/g,'&')
					.replace(/\%3D/g,'=')
					.replace(/\%3F/g,'?');
			}

			// Return result
			return result;
		};

		/**
		 * History.getHashByUrl(url)
		 * Extracts the Hash from a URL
		 * @param {string} url
		 * @return {string} url
		 */
		History.getHashByUrl = function(url){
			// Extract the hash
			var hash = String(url)
				.replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
				;

			// Unescape hash
			hash = History.unescapeHash(hash);

			// Return hash
			return hash;
		};

		/**
		 * History.setTitle(title)
		 * Applies the title to the document
		 * @param {State} newState
		 * @return {Boolean}
		 */
		History.setTitle = function(newState){
			// Prepare
			var title = newState.title,
				firstState;

			// Initial
			if ( !title ) {
				firstState = History.getStateByIndex(0);
				if ( firstState && firstState.url === newState.url ) {
					title = firstState.title||History.options.initialTitle;
				}
			}

			// Apply
			try {
				document.getElementsByTagName('title')[0].innerHTML = title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
			}
			catch ( Exception ) { }
			document.title = title;

			// Chain
			return History;
		};


		// ====================================================================
		// Queueing

		/**
		 * History.queues
		 * The list of queues to use
		 * First In, First Out
		 */
		History.queues = [];

		/**
		 * History.busy(value)
		 * @param {boolean} value [optional]
		 * @return {boolean} busy
		 */
		History.busy = function(value){
			// Apply
			if ( typeof value !== 'undefined' ) {
				//History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
				History.busy.flag = value;
			}
			// Default
			else if ( typeof History.busy.flag === 'undefined' ) {
				History.busy.flag = false;
			}

			// Queue
			if ( !History.busy.flag ) {
				// Execute the next item in the queue
				clearTimeout(History.busy.timeout);
				var fireNext = function(){
					var i, queue, item;
					if ( History.busy.flag ) return;
					for ( i=History.queues.length-1; i >= 0; --i ) {
						queue = History.queues[i];
						if ( queue.length === 0 ) continue;
						item = queue.shift();
						History.fireQueueItem(item);
						History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
					}
				};
				History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
			}

			// Return
			return History.busy.flag;
		};

		/**
		 * History.busy.flag
		 */
		History.busy.flag = false;

		/**
		 * History.fireQueueItem(item)
		 * Fire a Queue Item
		 * @param {Object} item
		 * @return {Mixed} result
		 */
		History.fireQueueItem = function(item){
			return item.callback.apply(item.scope||History,item.args||[]);
		};

		/**
		 * History.pushQueue(callback,args)
		 * Add an item to the queue
		 * @param {Object} item [scope,callback,args,queue]
		 */
		History.pushQueue = function(item){
			// Prepare the queue
			History.queues[item.queue||0] = History.queues[item.queue||0]||[];

			// Add to the queue
			History.queues[item.queue||0].push(item);

			// Chain
			return History;
		};

		/**
		 * History.queue (item,queue), (func,queue), (func), (item)
		 * Either firs the item now if not busy, or adds it to the queue
		 */
		History.queue = function(item,queue){
			// Prepare
			if ( typeof item === 'function' ) {
				item = {
					callback: item
				};
			}
			if ( typeof queue !== 'undefined' ) {
				item.queue = queue;
			}

			// Handle
			if ( History.busy() ) {
				History.pushQueue(item);
			} else {
				History.fireQueueItem(item);
			}

			// Chain
			return History;
		};

		/**
		 * History.clearQueue()
		 * Clears the Queue
		 */
		History.clearQueue = function(){
			History.busy.flag = false;
			History.queues = [];
			return History;
		};


		// ====================================================================
		// IE Bug Fix

		/**
		 * History.stateChanged
		 * States whether or not the state has changed since the last double check was initialised
		 */
		History.stateChanged = false;

		/**
		 * History.doubleChecker
		 * Contains the timeout used for the double checks
		 */
		History.doubleChecker = false;

		/**
		 * History.doubleCheckComplete()
		 * Complete a double check
		 * @return {History}
		 */
		History.doubleCheckComplete = function(){
			// Update
			History.stateChanged = true;

			// Clear
			History.doubleCheckClear();

			// Chain
			return History;
		};

		/**
		 * History.doubleCheckClear()
		 * Clear a double check
		 * @return {History}
		 */
		History.doubleCheckClear = function(){
			// Clear
			if ( History.doubleChecker ) {
				clearTimeout(History.doubleChecker);
				History.doubleChecker = false;
			}

			// Chain
			return History;
		};

		/**
		 * History.doubleCheck()
		 * Create a double check
		 * @return {History}
		 */
		History.doubleCheck = function(tryAgain){
			// Reset
			History.stateChanged = false;
			History.doubleCheckClear();

			// Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
			// Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
			if ( History.bugs.ieDoubleCheck ) {
				// Apply Check
				History.doubleChecker = setTimeout(
					function(){
						History.doubleCheckClear();
						if ( !History.stateChanged ) {
							//History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
							// Re-Attempt
							tryAgain();
						}
						return true;
					},
					History.options.doubleCheckInterval
				);
			}

			// Chain
			return History;
		};


		// ====================================================================
		// Safari Bug Fix

		/**
		 * History.safariStatePoll()
		 * Poll the current state
		 * @return {History}
		 */
		History.safariStatePoll = function(){
			// Poll the URL

			// Get the Last State which has the new URL
			var
				urlState = History.extractState(History.getLocationHref()),
				newState;

			// Check for a difference
			if ( !History.isLastSavedState(urlState) ) {
				newState = urlState;
			}
			else {
				return;
			}

			// Check if we have a state with that url
			// If not create it
			if ( !newState ) {
				//History.debug('History.safariStatePoll: new');
				newState = History.createStateObject();
			}

			// Apply the New State
			//History.debug('History.safariStatePoll: trigger');
			History.Adapter.trigger(window,'popstate');

			// Chain
			return History;
		};


		// ====================================================================
		// State Aliases

		/**
		 * History.back(queue)
		 * Send the browser history back one item
		 * @param {Integer} queue [optional]
		 */
		History.back = function(queue){
			//History.debug('History.back: called', arguments);

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.back: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.back,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Make Busy + Continue
			History.busy(true);

			// Fix certain browser bugs that prevent the state from changing
			History.doubleCheck(function(){
				History.back(false);
			});

			// Go back
			history.go(-1);

			// End back closure
			return true;
		};

		/**
		 * History.forward(queue)
		 * Send the browser history forward one item
		 * @param {Integer} queue [optional]
		 */
		History.forward = function(queue){
			//History.debug('History.forward: called', arguments);

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.forward: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.forward,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Make Busy + Continue
			History.busy(true);

			// Fix certain browser bugs that prevent the state from changing
			History.doubleCheck(function(){
				History.forward(false);
			});

			// Go forward
			history.go(1);

			// End forward closure
			return true;
		};

		/**
		 * History.go(index,queue)
		 * Send the browser history back or forward index times
		 * @param {Integer} queue [optional]
		 */
		History.go = function(index,queue){
			//History.debug('History.go: called', arguments);

			// Prepare
			var i;

			// Handle
			if ( index > 0 ) {
				// Forward
				for ( i=1; i<=index; ++i ) {
					History.forward(queue);
				}
			}
			else if ( index < 0 ) {
				// Backward
				for ( i=-1; i>=index; --i ) {
					History.back(queue);
				}
			}
			else {
				throw new Error('History.go: History.go requires a positive or negative integer passed.');
			}

			// Chain
			return History;
		};


		// ====================================================================
		// HTML5 State Support

		// Non-Native pushState Implementation
		if ( History.emulated.pushState ) {
			/*
			 * Provide Skeleton for HTML4 Browsers
			 */

			// Prepare
			var emptyFunction = function(){};
			History.pushState = History.pushState||emptyFunction;
			History.replaceState = History.replaceState||emptyFunction;
		} // History.emulated.pushState

		// Native pushState Implementation
		else {
			/*
			 * Use native HTML5 History API Implementation
			 */

			/**
			 * History.onPopState(event,extra)
			 * Refresh the Current State
			 */
			History.onPopState = function(event,extra){
				// Prepare
				var stateId = false, newState = false, currentHash, currentState;

				// Reset the double check
				History.doubleCheckComplete();

				// Check for a Hash, and handle apporiatly
				currentHash = History.getHash();
				if ( currentHash ) {
					// Expand Hash
					currentState = History.extractState(currentHash||History.getLocationHref(),true);
					if ( currentState ) {
						// We were able to parse it, it must be a State!
						// Let's forward to replaceState
						//History.debug('History.onPopState: state anchor', currentHash, currentState);
						History.replaceState(currentState.data, currentState.title, currentState.url, false);
					}
					else {
						// Traditional Anchor
						//History.debug('History.onPopState: traditional anchor', currentHash);
						History.Adapter.trigger(window,'anchorchange');
						History.busy(false);
					}

					// We don't care for hashes
					History.expectedStateId = false;
					return false;
				}

				// Ensure
				stateId = History.Adapter.extractEventData('state',event,extra) || false;

				// Fetch State
				if ( stateId ) {
					// Vanilla: Back/forward button was used
					newState = History.getStateById(stateId);
				}
				else if ( History.expectedStateId ) {
					// Vanilla: A new state was pushed, and popstate was called manually
					newState = History.getStateById(History.expectedStateId);
				}
				else {
					// Initial State
					newState = History.extractState(History.getLocationHref());
				}

				// The State did not exist in our store
				if ( !newState ) {
					// Regenerate the State
					newState = History.createStateObject(null,null,History.getLocationHref());
				}

				// Clean
				History.expectedStateId = false;

				// Check if we are the same state
				if ( History.isLastSavedState(newState) ) {
					// There has been no change (just the page's hash has finally propagated)
					//History.debug('History.onPopState: no change', newState, History.savedStates);
					History.busy(false);
					return false;
				}

				// Store the State
				History.storeState(newState);
				History.saveState(newState);

				// Force update of the title
				History.setTitle(newState);

				// Fire Our Event
				History.Adapter.trigger(window,'statechange');
				History.busy(false);

				// Return true
				return true;
			};
			History.Adapter.bind(window,'popstate',History.onPopState);

			/**
			 * History.pushState(data,title,url)
			 * Add a new State to the history object, become it, and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.pushState = function(data,title,url,queue){
				//History.debug('History.pushState: called', arguments);

				// Check the State
				if ( History.getHashByUrl(url) && History.emulated.pushState ) {
					throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.pushState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.pushState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy + Continue
				History.busy(true);

				// Create the newState
				var newState = History.createStateObject(data,title,url);

				// Check it
				if ( History.isLastSavedState(newState) ) {
					// Won't be a change
					History.busy(false);
				}
				else {
					// Store the newState
					History.storeState(newState);
					History.expectedStateId = newState.id;

					// Push the newState
					history.pushState(newState.id,newState.title,newState.url);

					// Fire HTML5 Event
					History.Adapter.trigger(window,'popstate');
				}

				// End pushState closure
				return true;
			};

			/**
			 * History.replaceState(data,title,url)
			 * Replace the State and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.replaceState = function(data,title,url,queue){
				//History.debug('History.replaceState: called', arguments);

				// Check the State
				if ( History.getHashByUrl(url) && History.emulated.pushState ) {
					throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.replaceState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.replaceState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy + Continue
				History.busy(true);

				// Create the newState
				var newState = History.createStateObject(data,title,url);

				// Check it
				if ( History.isLastSavedState(newState) ) {
					// Won't be a change
					History.busy(false);
				}
				else {
					// Store the newState
					History.storeState(newState);
					History.expectedStateId = newState.id;

					// Push the newState
					history.replaceState(newState.id,newState.title,newState.url);

					// Fire HTML5 Event
					History.Adapter.trigger(window,'popstate');
				}

				// End replaceState closure
				return true;
			};

		} // !History.emulated.pushState


		// ====================================================================
		// Initialise

		/**
		 * Load the Store
		 */
		if ( sessionStorage ) {
			// Fetch
			try {
				History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
			}
			catch ( err ) {
				History.store = {};
			}

			// Normalize
			History.normalizeStore();
		}
		else {
			// Default Load
			History.store = {};
			History.normalizeStore();
		}

		/**
		 * Clear Intervals on exit to prevent memory leaks
		 */
		History.Adapter.bind(window,"unload",History.clearAllIntervals);

		/**
		 * Create the initial State
		 */
		History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));

		/**
		 * Bind for Saving Store
		 */
		if ( sessionStorage ) {
			// When the page is closed
			History.onUnload = function(){
				// Prepare
				var	currentStore, item, currentStoreString;

				// Fetch
				try {
					currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
				}
				catch ( err ) {
					currentStore = {};
				}

				// Ensure
				currentStore.idToState = currentStore.idToState || {};
				currentStore.urlToId = currentStore.urlToId || {};
				currentStore.stateToId = currentStore.stateToId || {};

				// Sync
				for ( item in History.idToState ) {
					if ( !History.idToState.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.idToState[item] = History.idToState[item];
				}
				for ( item in History.urlToId ) {
					if ( !History.urlToId.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.urlToId[item] = History.urlToId[item];
				}
				for ( item in History.stateToId ) {
					if ( !History.stateToId.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.stateToId[item] = History.stateToId[item];
				}

				// Update
				History.store = currentStore;
				History.normalizeStore();

				// In Safari, going into Private Browsing mode causes the
				// Session Storage object to still exist but if you try and use
				// or set any property/function of it it throws the exception
				// "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
				// add something to storage that exceeded the quota." infinitely
				// every second.
				currentStoreString = JSON.stringify(currentStore);
				try {
					// Store
					sessionStorage.setItem('History.store', currentStoreString);
				}
				catch (e) {
					if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
						if (sessionStorage.length) {
							// Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
							// removing/resetting the storage can work.
							sessionStorage.removeItem('History.store');
							sessionStorage.setItem('History.store', currentStoreString);
						} else {
							// Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
						}
					} else {
						throw e;
					}
				}
			};

			// For Internet Explorer
			History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));

			// For Other Browsers
			History.Adapter.bind(window,'beforeunload',History.onUnload);
			History.Adapter.bind(window,'unload',History.onUnload);

			// Both are enabled for consistency
		}

		// Non-Native pushState Implementation
		if ( !History.emulated.pushState ) {
			// Be aware, the following is only for native pushState implementations
			// If you are wanting to include something for all browsers
			// Then include it above this if block

			/**
			 * Setup Safari Fix
			 */
			if ( History.bugs.safariPoll ) {
				History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
			}

			/**
			 * Ensure Cross Browser Compatibility
			 */
			if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
				/**
				 * Fix Safari HashChange Issue
				 */

				// Setup Alias
				History.Adapter.bind(window,'hashchange',function(){
					History.Adapter.trigger(window,'popstate');
				});

				// Initialise Alias
				if ( History.getHash() ) {
					History.Adapter.onDomLoad(function(){
						History.Adapter.trigger(window,'hashchange');
					});
				}
			}

		} // !History.emulated.pushState


	}; // History.initCore

	// Try to Initialise History
	if (!History.options || !History.options.delayInit) {
		History.init();
	}

})(window);
;
//This plugin is still to be optimised and reduced in file size.
// at the moment it works fully, but it could be faster.

(function ($) {

	//"use strict"

	// plugin version.
	var version = '0.10.2';
	var versionDate = '25th September 2013';
	var author = 'Adrian Roworth';
	var namespace = 'selectify';


	//privateFunction.apply(this, ['hello', 'hello2']);
	function privateFunction(parameter, parameter) {
		var $this = $(this);

		var settings = $this.data("settings");
	}

	/************************************************************************/
	/** PRIVATE METHODS START                                              **/
	/************************************************************************/

	// closes the menu that is open if the user clicks elsewhere on the document. This 
	// assumes that only one menu is open at any one time.
	function _closeBlurredMenus() {

		$('select').not(this).each(function () {
			$(this)[namespace]('closeMenu');
		});
	}

	// returns the width of the widest '<li>' in the passed-in '<ul>'.
	function _widestLi(ul) {

		var widths = new Array;
		var maxWidth = 0;
		var elOuterWidth;

		ul.css({ 'left': '-999999px', 'display': 'inline-block' });

		ul.children().each(function (index, el) {

			elOuterWidth = $(el).outerWidth();
			widths.push(elOuterWidth);

		});

		ul.css({ 'left': '', 'display': '' });

		maxWidth = Math.max.apply(Math, widths);
		return maxWidth;

	}

	// updates the '.selectify-selectmenu-selected-option-value' span with the chosen value.
	function _updateSelectedValue(selectMenuContainer, el) {

		var $this = $(this);

		if ($this.data('settings').clearCloseAfterLoadTimeoutOnClick === true) {

			clearTimeout($this.data('onLoadTimeout'));
			selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').removeClass($this.data('settings').activeTimeOutClass);

		}

		if (!selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').hasClass($this.data('settings').activeTimeOutClass)) {

			var ulLis = selectMenuContainer.find('.' + namespace + '-selectmenu li');

			var index = ulLis.index(el);

			// only update the selectmenu picked option if the menu is already open, otherwise
			// it will updated it with the first one on the list because 'index' will be '-1'.
			// REDUNDANT COMMENT ABOVE.
			if (el.is('li')) {

				selectMenuContainer.delay($this.data('settings').closeDelay, 'updateChosenQueue').queue('updateChosenQueue', function () {

					$(this).find('.' + namespace + '-selectmenu-selected-option-value').html(el.html());

					// evaluates the actual '<select>' element and changes it's value.
					$this.val(el.attr('selectmenu-value'));

				}).dequeue("updateChosenQueue");

			}
		}

	}
	function _getElementAttributes(el) {

		var elAttributes = '';

		$.each(el.attributes, function (index, item) {

			var itemNodeName = item.nodeName;
			var itemNodeValue = item.nodeValue;

			if (itemNodeName == 'value') {

				itemNodeName = 'selectmenu-value';
				if (!itemNodeValue) itemNodeValue = "selectifyemptyvalue";

			}

			elAttributes += itemNodeName + '="' + itemNodeValue + '" ';
		});
		return elAttributes;

	}
	function _showError(name, message) {

		//try {
		var err = new Error();
		err.name = name;
		err.message = message;
		//throw (err);

		//} catch (err) {

		// deprecated.
		//if ($.browser.msie) {
		//	alert(err.name + ':\n' + err.message);
		//} else if ($.browser.webkit) {
		//	alert(err.name + ':\n' + err.message);
		//} else if ($.browser.mozilla && console) {
		//	console.debug(err);

		if (console) {

			console.error(err.name + ' ' + err.message);

		} else {

			alert(err.name + '\n' + err.message);

		}
		//}

	}

	/************************************************************************/
	/** PRIVATE METHODS END                                                **/
	/************************************************************************/

	/************************************************************************/
	/** PUBLIC METHODS START                                               **/
	/************************************************************************/

	// public methods.
	// init(options)
	// togglemenu
	// openMenu
	// closeMenu
	// addItem(position, value, text)
	// removeItem(position, text)
	// changeItem(position, value, text)
	// buildMenu
	// enable(delay, callback)
	// disable(delay, callback)
	// destroy
	// status
	// isInit
	// isEnabled
	// statusCode
	// statusDescription
	// age
	// setSettings(options)
	//
	// CUSTOM EVENTS
	// beforeLoad.selectify - before the selectify selectmenu has loaded.
	// onLoad.selectify - after the selectify selectmenu has fully loaded.
	var methods = {

		init: function (options) {

			//try {

			    if (!this.length) {

					//throw "Element not found. Cannot initialise jQuery." + namespace + ".";
				//}

				//if ($(this).data('isSelectified') == true) {
					//throw "jQuery." + namespace + " is already initialised on this element.";
				//}

			//} catch (error) {

				//_showError('', error);
				return this;

			}

			return this.each(function () {

				var $this = $(this);
				$this.data('isSelectified', true);

				var selectedLiSelector, thisWidth;

				// sets the options passed in to the plugin.
				$this[namespace]('setSettings', $.fn[namespace].defaults, options);

				// callback.
				$this.data('settings').beforeLoad && $this.data('settings').beforeLoad();

				if ($this.data('settings').keepAge) {

					$this.data('age', 0);

					function getOlder() {
						$this.data('age', parseInt($this.data('age'), 10) + 1);
						setTimeout(getOlder, 1000);
					}

					getOlder();

				}

				var ul = $this[namespace]('buildMenu');
				var selectMenuContainer;

				$this.trigger('beforeLoad.selectify');

				// gets widest '<li>'s width.
				thisWidth = _widestLi(ul);

				// if any additional width has been specified, it is added on.
				if (parseInt($this.data('settings').additionalWidth) > 0) {
					thisWidth = parseInt($this.width()) + parseInt($this.data('settings').additionalWidth);
				}

				// if an absolute width has been specified, the width is changed to this new value.
				if (parseInt($this.data('settings').width) > 0) {
					thisWidth = parseInt($this.data('settings').width);
				}

				// if 'ignorePreselected' is true then the plugin disregards the 'selected' attribute, otherwise 
				// it uses the first '<option>' with a 'selected' attribute.
				$this.data('settings').ignorePreselected === false ? selectedLiSelector = ul.find('li[selected="selected"]:eq(0)').length > 0 ? 'li[selected="selected"]:eq(0)' : 'li:eq(0)' : selectedLiSelector = 'li:eq(0)';

				// wraps the '<ul>' in a new div.
				// + methods.getElementAttributes($this) +
				ul.wrap('<div class="' + namespace + '-selectmenu-container"' + ' />');

				//var selectMenuContainer = ul.parents('.' + namespace + '-selectmenu-container').addClass($this.attr('class')).css({ 'z-index': '1000', 'position': 'absolute', 'top': 0, 'left': 0 });
				selectMenuContainer = ul.parents('.' + namespace + '-selectmenu-container').addClass($this.attr('class')).css({ 'z-index': '1000', 'position': 'relative'});

				//$this.css({ 'position': 'relative', 'z-index': '900', 'top': '4px' });
				$this.data('selectMenuContainer', selectMenuContainer);
				// making sure that the 'selectMenuContainer' var is referencing the jquery data.
				selectMenuContainer = $this.data('selectMenuContainer');

				// setting up the DOM.
				selectMenuContainer.prepend('<div class="' + namespace + '-selectmenu-selected-option-container"><a class="' + namespace + '-selectmenu-selected-option"><span class="' + namespace + '-selectmenu-selected-option-value">' + $(ul).find(selectedLiSelector).text() + '</span><span class="' + namespace + '-selectmenu-selected-option-icon"></span></a></div>').height($('.' + namespace + '-selectmenu-selected-option-container').outerHeight(true)).width(thisWidth);

				if($this.data('settings').hasCloseButton) {
				    selectMenuContainer.prepend('<span class="' + namespace + '-selectmenu-close">X</span>');
				}

			    // dependant on jQueryUI. removed and replaced with a CSS substitute to save Gigabytes of data transfer.
				//selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').disableSelection();
			    selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option-container').css({ 'width': '100%', 'position': 'absolute', 'top': '0px', 'left': '0px' });

				if ($this.data('settings').hasCloseButton) {
				    selectMenuContainer.find('.' + namespace + '-selectmenu-close').css({ 'display': 'none' });
				}

				// set the width of the '<ul>' element and other CSS.
				ul.css({ 'width': '100%', 'position': 'absolute', 'top': selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option-container').outerHeight(true), 'left': '0px' });

				// sets the height of the '<ul>' element if it exceded the maximum height specified by the options.
				if ($this.data('settings').maxHeight > 0 && ul.height() >= $this.data('settings').maxHeight) {

					ul.css({ 'height': $this.data('settings').maxHeight + 'px' });

				}

				// set the selected option container's width.
				selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option-container').css({ 'width': '100%' });
				// adds the 'chosen' class to the determined li. e.g. 'selected="selected"' or :eq(0).
				ul.find(selectedLiSelector).addClass($this.data('settings').menuItemChosenClass);

				// start yer engines.
				$this.prop('disabled') == true || $this.prop('readonly') == true ? $this[namespace]('disable') : $this[namespace]('enable');

				// close all selectmenus when you click on the page.
				/*$this.on('blur', function () {
					_closeBlurredMenus.apply($this);
				});*/

			    			    selectMenuContainer.prepend($this);


				// callback.
				$this.data('settings').afterLoad && $this.data('settings').afterLoad();

				$this.trigger('onLoad.selectify');

			});

		},
		toggleMenu: function () {

			var $this = $(this);
			var selectMenuContainer = $this.data('selectMenuContainer');

			selectMenuContainer.find('.' + namespace + '-selectmenu').hasClass($this.data('settings').hiddenMenuClass) ? $this[namespace]('openMenu', selectMenuContainer) : $this[namespace]('closeMenu', selectMenuContainer);

		},
		openMenu: function () {

		    var $this = $(this),
		        settings = $this.data("settings"),
		        selectMenuContainer = $this.data('selectMenuContainer');

			if ($this.data('isEnabled') == true) {

				// we have to explicity iterate through the collection to test for
				// the 'timeout active' class.
			    selectMenuContainer.each(function () {

			        var $thisSelectMenuContainer = $(this),
			            $selectMenu = $thisSelectMenuContainer.find('.' + namespace + '-selectmenu');

					if (!$thisSelectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').hasClass(settings.activeTimeOutClass)) {
					    $thisSelectMenuContainer.delay(settings.openDelay, 'openMenuQueue').queue('openMenuQueue', function() {

					        $selectMenu.removeClass(settings.hiddenMenuClass).addClass(settings.visibleMenuClass);
					        $thisSelectMenuContainer.addClass(settings.visibleMenuClass);
					        //$thisSelectMenuContainer.find('.selectify-selectmenu-selected-option-container').addClass($this.data('settings').activeTimeOutClass);
					        $thisSelectMenuContainer.css({ 'z-index': 1010 });

					        // positions the dropdown menu at the top or the bottom of
					        // the selected option, depending on how far down the page
					        // the selectmenu is sitting. Much like the way that native 
					        // dropdowns work.
					        // Because the dropdowns are children of the selectify element, we need to calculate positioning based on the scrollParent not the window.

					        var $scrollParent = $selectMenu.scrollParent(),
					            $scrollParent = $scrollParent[0] == document ? $(window) : $scrollParent, // should be the window not the document otherwise you get incorrect calculations
                                parentTop = $scrollParent[0] == window ? 0 : $scrollParent.offset().top,
                                windowHeight = $scrollParent.height(),
					            selectMenuHeight = $selectMenu[0].scrollHeight,
					            maxHeight = settings.maxHeight || Infinity,
					            $input = $thisSelectMenuContainer.find('.' + namespace + '-selectmenu-selected-option-container'),
					            inputHeight = $input.outerHeight(true),
					            inputTop = $input.offset().top - parentTop,
                                setAtBottom = settings.openDirection != 'up',

					            // find out where the max available space is
					            // compare to the desired height and try and fit at the preferred direction
					            // if it doesn't fit then see which is the biggest space and try and put it there
					            // set the height based on the available height
					            desiredHeight = Math.min(selectMenuHeight, maxHeight),
					            topSpace = inputTop - settings.edgeOffset, //selectMenuOffsetTop - windowScrollTop - inputHeight - settings.edgeOffset,
					            bottomSpace = windowHeight - (inputTop + inputHeight) - settings.edgeOffset,
					            availableSpace = setAtBottom ? bottomSpace : topSpace;

					        // some of this is slighly redundant as we are potentially resetting values as the same.
                            // but we don't know yet if it will fit where is has been asked for
					        if (availableSpace < desiredHeight) {
					            availableSpace = Math.max(topSpace, bottomSpace);
					            setAtBottom = availableSpace == bottomSpace;
					        }

                            // set the height and position of the menu based of the available space
					        selectMenuHeight = desiredHeight > availableSpace ? availableSpace : desiredHeight;

					        $selectMenu.css({
					            height: selectMenuHeight,
					            top: setAtBottom ? inputHeight : -selectMenuHeight
					        });

					        $thisSelectMenuContainer.find('.' + namespace + '-selectmenu-close').css({ 'display': 'block' });

					        $this.trigger('openmenu.selectify');

					    }).dequeue("openMenuQueue");

					}

			    });

			}

		},
		closeMenu: function () {

			var $this = $(this);

			var selectMenuContainer = $this.data('selectMenuContainer');

			if ($this.data('isEnabled') == true) {

				// we have to explicity iterate through the collection to test for
				// the 'timeout active' class.
				selectMenuContainer.each(function () {

					var $thisSelectMenuContainer = $(this);

					if (!$thisSelectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').hasClass($this.data('settings').activeTimeOutClass)) {

						// this method is called every time that there is a click event
						// on the page. so we need to check if the 'selectmenu' in 
						// question is actually open.
						if ($thisSelectMenuContainer.find('.' + namespace + '-selectmenu').hasClass($this.data('settings').visibleMenuClass)) {

							$thisSelectMenuContainer.delay($this.data('settings').closeDelay, 'CloseMenuQueue').queue('CloseMenuQueue', function () {

								$thisSelectMenuContainer.find('.' + namespace + '-selectmenu').addClass($this.data('settings').hiddenMenuClass);
								$thisSelectMenuContainer.removeClass($this.data('settings').visibleMenuClass).find('.' + namespace + '-selectmenu').removeClass($this.data('settings').visibleMenuClass);
								//$thisSelectMenuContainer.find('.selectify-selectmenu-selected-option-container').removeClass($this.data('settings').activeTimeOutClass);
								$thisSelectMenuContainer.css({ 'z-index': 1000 });

								// reset where the '<ul>' should be so that the correct open position
								// can be calculated. Because the assumed '<ul>' position is below the
								// selected option when the menu is hidden.
								$thisSelectMenuContainer.find('.' + namespace + '-selectmenu').css({ 'top': selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option-container').outerHeight(true) + 'px' });
								$thisSelectMenuContainer.find('.' + namespace + '-selectmenu-close').css({ 'display': 'none' });

								$this.trigger('closemenu.selectify');

							}).dequeue("CloseMenuQueue");

						}

					}

				});

			}

		},
		// add item by passing the 'value' attribute, '<option>' text, and the index.
		addItem: function (position, value, text, callback) {

			var $this = $(this);

			try {

				if (!position || !value || !text) {

					throw "jQuery." + namespace + ".addItem(): This method requires at least 3 parameters 'position', 'value', and 'text'";

				}

				if (!isFinite(position)) {

					throw "jQuery." + namespace + ".removeItem(): The position index is not a finite number.";

				} else if (isNaN(position)) {

					throw "jQuery." + namespace + ".removeItem(): The position index is not a number.";

				} else if (isFinite(position) && !isNaN(position)) {

					var newOption = $('<option value="' + value + '">' + text + '</option>');
					newOption.insertBefore($this.children('option:eq(' + position + ')'));
					$this[namespace]('buildMenu');

				}

				callback && callback();

			} catch (error) {

				_showError('', error);

			}

		},
		// remove item by matching the '<option>' index, or it's text.
		// 'text' still to be implemented.
		removeItem: function (position, text, callback) {

			var $this = $(this);

			// even if 'position' is an integer, it is put in to an array so that 
			// the below works for both integers and arrays. As a result, there is
			// no need to replicate the same logic for different data types.
			if (isFinite(position) && !isNaN(position)) {

				var temp = position;
				position = new Array();
				position[0] = temp;

			}

			try {

				$.each(position, function (index, value) {

					if (!isFinite(value)) {

						throw "jQuery." + namespace + ".removeItem(): The position index is not a finite number.";

					} else if (isNaN(value)) {

						throw "jQuery." + namespace + ".removeItem(): The position index is not a number.";

					} else if (isFinite(value) && !isNaN(value)) {

						// if 'position' is negative. start from the end of the matched set and 
						// work backwards to get the index wanted. For example, '-2' means 2nd from the end.
						if (value < 0) {

							value = parseInt($this.children().length, 10) + parseInt(value, 10);

							if (value < -1) {

								throw 'jQuery.' + namespace + '.removeItem(): Item at position \'' + value + '\' doesn\'t exist. removing item at position \'0\'.';
								value = 0;

							}

						}

						if ($this.children(':eq(' + value + ')').length > 0 && value > -1 && value <= $this.children().length) {

							$this.children(':eq(' + value + ')').remove();
							$this[namespace]('buildMenu');

						} else {

							throw 'jQuery.' + namespace + '.removeItem(): Unable to remove <option> of position \'' + value + '\' as it doesn\'t exist.';

						}

					}

				});

				callback && callback();

			} catch (error) {

				_showError('', error);

			}

			//$this.selectify('buildMenu');

		},
		changeItem: function (position, value, text, callback) {

			var $this = $(this);

			$this[namespace]('removeItem', position);
			$this[namespace]('addItem', position, value, text, callback);


		},
		buildMenu: function () {

			var $this = $(this);
			var ul = $this.siblings('.' + namespace + '-selectmenu');
			var newLis = [];
			var ulLis = '';

			if (ul.length > 0) {

				ul.html('');
				__buildLis();
				__prettifyLis();

				return $this;

				// this will only execute on first run.
			} else {

			    ul = $('<ul/>');
				ul.addClass($this.attr('class')).addClass('' + namespace + '-selectmenu ' + $this.data('settings').hiddenMenuClass);

				__buildLis();
				ul.insertAfter($this);
				__prettifyLis();

				return ul;

			}

			function __buildLis() {

				// iterate through the '<select>s' '<options>' and add their attributes to the corrisponding new '<li>'.
				$this.children().each(function (index, el) {

					var $thisOption = this;
					var optionAttributes = '';
					var li = '';

					var hiddenClassForFirstEl = (index == 0 && $this.data('settings').firstOptionVisibleInDropDown == false) ? 'style="display: none;"' : '';

					li = '<li ' + _getElementAttributes($thisOption) + ' ' + hiddenClassForFirstEl + '>' + $($thisOption).html() + '</li>';
					newLis.push(li);

				});

				ul.append(newLis);

			}

			function __prettifyLis() {

				ulLis = ul.find('li');

				// ':odd' and ':even' return zero-indexed results so they are shifted 1 index to
				// the wrong position. fix this by swapping the class name that is added.

				// remove any of the plugin-related classes, just in case they are already there.
				ulLis.removeClass('' + namespace + '-selectmenu-option-even ' + namespace + '-selectmenu-option-odd ' + namespace + '-selectmenu-option-first ' + namespace + '-selectmenu-option-last');

				ulLis.filter(':odd').addClass('' + namespace + '-selectmenu-option-even');
				ulLis.filter(':even').addClass('' + namespace + '-selectmenu-option-odd');

				ulLis.filter(':first').addClass('' + namespace + '-selectmenu-option-first');
				ulLis.filter(':last').addClass('' + namespace + '-selectmenu-option-last');

				// select the first option of the '<ul>'.
				_updateSelectedValue.apply($this, [$this.siblings('.' + namespace + '-selectmenu-container'), ul.find('li:eq(0)')]);

			}

		},
		// enable the selectmenu.
		enable: function (delay, callback) {

			var $this = $(this);

			if ($this.data('isEnabled') != true) {

				var selectMenuContainer = $this.data('selectMenuContainer');
				var ul = selectMenuContainer.find('.' + namespace + '-selectmenu');
				var ulLis = ul.children('li');

				if (isNaN(delay)) {
					delay = 0;
					if (typeof delay == 'function') {
						callback = delay;
						delay = 0;
					}
				}

				function enableSelectmenu() {

					$this.data('isEnabled', true);
					$this.prop('disabled', false);

					selectMenuContainer.addClass($this.data('settings').menuEnabledClass).removeClass($this.data('settings').menuDisabledClass);

					$(ul).on('click', 'li', function () {

						// don't update anything if the timeout is active.
						if (!selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').hasClass($this.data('settings').activeTimeOutClass)) {

							$this[namespace]('toggleMenu', selectMenuContainer);
							var index = ul.find('li').index($(this));
							var indexTextValue = $(this).attr('selectmenu-value');
							$this.val(indexTextValue).change();
						    $this.trigger("selected.selectify",indexTextValue);

						}

					}).on('mouseenter', 'li', function () {

						$(this).siblings().addBack().removeClass($this.data('settings').menuItemHoverClass);
						$(this).addClass($this.data('settings').menuItemHoverClass);
						$this.trigger('mouseenter.selectify', [this, $(this).attr('selectmenu-value')]);

					}).on('mouseleave', 'li', function () {

					    $(this).siblings().addBack().removeClass($this.data('settings').menuItemHoverClass);
					    $this.trigger('mouseleave.selectify', [this, $(this).attr('selectmenu-value')]);

					});

					$('.' + namespace + '-selectmenu-selected-option', selectMenuContainer).on('click', function (e) {

						if (!$(this).hasClass($this.data('settings').activeTimeOutClass)) {

							$this[namespace]('toggleMenu', selectMenuContainer);
							_closeBlurredMenus.apply($this);

						}

					});

					$this.on('change', function (e) {

						var li = $('li[selectmenu-value="' + (this.value || 'selectifyemptyvalue') + '"]', ul);
						_updateSelectedValue.apply($this, [selectMenuContainer, li]);
						$('li', ul).removeClass($this.data('settings').menuItemChosenClass);
						li.addClass($this.data('settings').menuItemChosenClass);

					});

					// opens the selectmenu on load if 'openOnLoad' is set to true.
					if ($this.data('settings').openOnLoad === true) {

						selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').trigger('click');

						if ($this.data('settings').closeAfterLoadTimeout > 0) {

							selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').addClass($this.data('settings').activeTimeOutClass);

							var timeoutFunction = function () {

								selectMenuContainer.find('.' + namespace + '-selectmenu-selected-option').removeClass($this.data('settings').activeTimeOutClass);
								$this[namespace]('closeMenu', selectMenuContainer);

							};

							$this.data('onLoadTimeout', setTimeout(timeoutFunction, $this.data('settings').closeAfterLoadTimeout));

							var onLoadTimeout = $this.data('onLoadTimeout');

						}

					}

					callback && callback();
				}

				delay != 0 ? setTimeout(enableSelectmenu, delay) : enableSelectmenu();

			}

		},
		// disable the selectmenu.
		disable: function (delay, callback) {

			var $this = $(this);

			if ($this.data('isEnabled') != false) {

				var selectMenuContainer = $this.data('selectMenuContainer');
				var ul = selectMenuContainer.find('.' + namespace + '-selectmenu');

				// signature checking.
				if (isNaN(delay)) {
					delay = 0;
					if (typeof delay == 'function') {
						callback = delay;
						delay = 0;
					}
				}

				function disableSelectmenu() {

					$this.data('isEnabled', false);

					$this.prop('disabled', true);
					selectMenuContainer.removeClass($this.data('settings').menuEnabledClass).addClass($this.data('settings').menuDisabledClass);
					$(ul).off('click', 'li').off('mouseenter', 'li').off('mouseleave', 'li');
					$('.' + namespace + '-selectmenu-selected-option', selectMenuContainer).off('click');

					callback && callback();

				}

				delay != null ? setTimeout(disableSelectmenu, delay) : disableSelectmenu();

			}

		},
		// remove the selectmenu completely.
		destroy: function () {

			var $this = $(this);
			var selectmenuContainer = $this.data('selectMenuContainer');

			selectmenuContainer.remove();

		},
		status: function (item) {

			var $this = $(this);

			var childrenObject = {};
			$this.data('selectMenuContainer').find('.selectify-selectmenu').children().each(function () {
				//console.log($(this));
				var child = {
					'index': $(this).prevAll().length,
					'classes': $(this).attr('class'),
					'id': $(this).attr('id'),
					'innerHTML': $(this).html(),
					'outerHTML': $(this)[0].outerHTML,
					'DOM element': $(this)[0]
				};

				childrenObject[child.index] = child;
			});

			// defaulted to the 'Not initialised' response.
			var response = {
				'code': 0,
				'initialised': false,
				'enabled': false,
				'description': 'Not initialised',
				'version': $.fn.selectify.version,
				'version date': $.fn.selectify.versionDate,
				'children': childrenObject
			};

			response['initialised'] = $this.data('isSelectified') == true ? true : false;
			response['enabled'] = $this.data('isEnabled') == true ? true : false;
			response.initialised == true ?
			// response.initialised = true.
				(response.enabled == true ?
			// response.enabled = true.
					(response['code'] = 1, response['description'] = 'Initialised & enabled') :
			// response.enabled = false.
					(response['code'] = 2, response['description'] = 'Initialised & disabled')
				) :
			// response.initialised = false.
			(response['code'] = 0, response['description'] = 'Not initialised');

			response['age'] = $this.data('age');

			response['version'] = $.fn.selectify.version;
			response['version date'] = $.fn.selectify.versionDate;

			return response[item] || response;

		},
		isInitd: function () {
			return $(this).data('isSelectified') == true ? true : false;
		},
		isEnabled: function () {
			return $(this).data('isEnabled') == true ? true : false;
		},
		statusCode: function () {
			return $(this)[namespace]('status', 'code');
		},
		statusDescription: function () {
			return $(this)[namespace]('status', 'description');
		},
		age: function () {
			return (parseInt($(this).data('age'), 10) * 1000);
		},
		// stores plugin settings using the data method.
		setSettings: function () {
		    // default are overriden by option which are overridden by settings on the element itself

		    var args = [{}].concat( Array.prototype.slice.call(arguments, 0) ).concat(this.data("settings"));
		    this.data("settings", $.extend.apply(null,args));
		}

	};

	/************************************************************************/
	/** PUBLIC METHODS END                                                 **/
	/************************************************************************/

	$.fn[namespace] = function (method) {

		if (methods[method]) {

			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));

		} else if (typeof method === 'object' || !method) {

			return methods.init.apply(this, arguments);

		} else {

			$.error('Method ' + method + ' does not exist on jQuery.' + namespace);

		}

	};

	// returns plugin version.
	// $.fn.selectify.version;
	$.fn[namespace].version = (function () {

		return version;

	})();

	// returns plugin version date.
	// $.fn.selectify.versionDate;
	$.fn[namespace].versionDate = (function () {

		return versionDate;

	})();

	// returns plugin author.
	// $.fn.selectify.author;
	$.fn[namespace].author = (function () {

		return author;

	})();

	// default plugin options
	$.fn[namespace].defaults = {
		'additionalWidth': '0', // adds extra width on to the selectmenu. can be negative or positive.
		'width': '0', // makes the selectmenu a specific width. must be positive value.
		'ignorePreselected': false, // ignores any 'selected="selected"' attributes on the <option> elements.
		'openOnLoad': false, // opens the selectmenu on page load.
		'closeAfterLoadTimeout': 0, // number of milliseconds the selectmenu will close after page load. dependant on 'openOnLoad'.
		'clearCloseAfterLoadTimeoutOnClick': true, // clear the 'closeAfterLoadTimeout' on click. dependant on 'openOnLoad' & 'closeAfterLoadTimeout'.
		'openDelay': 0, // number of milliseconds the selectmenu will open after click.
		'closeDelay': 0, // number of milliseconds the selectmenu will close after click.
		'menuItemChosenClass': namespace + '-selectmenu-item-chosen', // class given to the chosen selectmenu item.
		'menuItemHoverClass': namespace + '-selectmenu-item-hover', // class given to the item being hovered over.
		'activeTimeOutClass': namespace + '-selectmenu-timeout-active', // class given to the selectmenu when 'closeAfterLoadTimeout' is more than '0'. this class will be on the selectmenu for the duration of the timeout.
		'hiddenMenuClass': namespace + '-selectmenu-hidden', // class given to a selectmenu options that are not active.
		'visibleMenuClass': namespace + '-selectmenu-open', // class given to a selectmenu options that are active.
		'menuEnabledClass': namespace + '-selectmenu-enabled', // class given to a selectmenu that is enabled.
		'menuDisabledClass': namespace + '-selectmenu-disabled', // class given to a selectmenu that is disabled.
		'maxHeight': 230, // maximum height of the menu options. 0 means no maximum height.
		'openDirection': 'auto', // can be 'auto', 'up', or 'down'. Determines where the select options will appear in relation to the selectmenu. Setting it to 'auto' will make the direction depend on how much space is available for the dropdown menu.
        'edgeOffset' : 45, // this is margin between the top or bottom of the screen and the menu top or bottom.
		'beforeLoad': null, // function to be executed before the selectmenu loads.
		'afterLoad': null, // function to be executed when the selectmenu has fully loaded loads.
		'keepAge': false, // if set to 'true', then the plugins age in seconds will be accessible.
		'firstOptionVisibleInDropDown': true, // boolean value to indicate whether the first '<option>' will be visible on the dropdown when it is opened.
        'hasCloseButton' : false // boolean value to indicate if the selectmenu will have a button to close the menu as well.
	};

})(jQuery);;
(function ($) {

	"use strict"

	// plugin version.
	var version = '0.1.0';
	var versionDate = '14th October 2013';
	var namespace = 'checkboxify';

	/************************************************************************/
	/** PRIVATE METHODS START                                              **/
	/************************************************************************/

	function _showError(name, message) {

		var err = new Error();
		err.name = name;
		err.message = message;

		if (console) {

			console.error(err.name + ' ' + err.message);

		} else {

			alert(err.name + '\n' + err.message);

		}

	}

	/************************************************************************/
	/** PRIVATE METHODS END                                                **/
	/************************************************************************/

	/************************************************************************/
	/** PUBLIC METHODS START                                               **/
	/************************************************************************/

	var methods = {

		init: function (options) {

			//try {
			    if (!this.length) {
					/*throw "Element not found. Cannot initialise jQuery." + namespace + ".";
				}
				if ($(this).data('isSelectified') == true) {
					throw "jQuery." + namespace + " is already initialised on this element.";
				}
			} catch (error) {
				_showError('', error);*/
				return this;
			}

			return this.each(function () {
			    var $this = $(this);
			    
			    if (!$this.data('isCheckboxified')) {

			        $this.data('isCheckboxified', true);
			        $this.data('settings', $.extend({}, $.fn[namespace].defaults, options));
                    
			        if ($this.parents('.compact').length) {
			            $this.next('label[for="' + $this.attr('id') + '"]').addBack().wrapAll('<div class="input-container" />');
                        // 0-based index.
			            //var evenInputContainers = $this.parents('.compact').find('.input-container:odd')
			            //evenInputContainers.addClass('last');

			            //evenInputContainers.each(function () {
			                //console.log($(this).add($(this).prev('.input-container')));
			                //$(this).add($(this).prev('.input-container')).wrapAll('<div class="input-row" />');
			            //});
			        }
			        
			        var $toWrap = !$this.siblings('label').length ? $this.parents('label').length ? $this.parents('label').parent() : $this : $this.parent();
			        
			        var checkBoxContainer = $toWrap.wrapInner('<div class="checkboxify-dom-container" style="position: absolute; top: 0; left: -99999px;" />');


			        var label = $this.data('settings').label != null ? $this.data('settings').label : $toWrap.find('label').html();



			        var labelClasses = $this.data('labelclass') != null ? $this.data('labelclass') : "";

			        $this.data('checkboxContainer', checkBoxContainer);
			        checkBoxContainer.append('<div class="checkboxify-checkbox-container"><div class="checkbox"><div class="checkbox-inner" /></div><span class="checkbox-label ' + labelClasses + '">' + label + '</span></div>');
			        checkBoxContainer.wrapInner('<div class="checkboxify-wrapper" />');

			        // add checked class if the checkbox is already checked.
			        var isChecked = $this.is(':checked') ? true : false;
			        isChecked ? checkBoxContainer.find('.checkboxify-checkbox-container .checkbox').addClass('checked') : checkBoxContainer.find('.checkboxify-checkbox-container .checkbox').removeClass('checked');
			        isChecked ? checkBoxContainer.find('.checkboxify-checkbox-container .checkbox-inner').html('X') : checkBoxContainer.find('.checkboxify-checkbox-container .checkbox-inner').html('');

			        checkBoxContainer.find('.checkboxify-checkbox-container .checkbox, .checkboxify-checkbox-container .checkbox-label').on('click', checkBoxContainer, function() {

			            $this.click();
			            isChecked = $this.is(':checked') ? true : false;
			            var thisCheckbox = $(this);
			            isChecked ? checkBoxContainer.find('.checkboxify-checkbox-container .checkbox').addClass('checked') : checkBoxContainer.find('.checkboxify-checkbox-container .checkbox').removeClass('checked');
			            isChecked ? checkBoxContainer.find('.checkboxify-checkbox-container .checkbox-inner').html('X') : checkBoxContainer.find('.checkboxify-checkbox-container .checkbox-inner').html('');

			        });

			    }

			});

		},

	};

	/************************************************************************/
	/** PUBLIC METHODS END                                                 **/
	/************************************************************************/

	$.fn[namespace] = function (method) {

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.' + namespace);
		}

	};

	// default plugin options
	$.fn[namespace].defaults = {
	    'label': null, // checkbox label.
	    'extraClasses': null, // checkbox classes.
	};

})(jQuery);;
(function ($) {

    $.fn.tabify = function (options) {

        var settings = $.extend({}, $.fn.tabify.defaultOptions, options);

        $.fx.off = true;
        // .hotel-subnav
        this.each(function () {

            var $this = $(this);
            var tabs = $('.tab',$this.next());
            //var scrollParent = $this.scrollParent();
            //var scrollParentNiceScroll = scrollParent.hasClass("nice-scroll");

            // see if there is something set as active in the html
            var activeTab = $this.find("a.active");

            if (!activeTab.length) {
                activeTab = $this.find('a:eq(0)').addClass('active');
            }

            $(".tab" + activeTab.attr("href")).addClass('active').siblings().hide();

            var tabTriggers = $this.find('a').on('click', function(e) {

                //                e.preventDefault();

                var $thisA = $(this),
                    hash = $thisA.attr("href").replace(/#?\?tab=/, ""),
                    correspondingTab;

                if (!(correspondingTab = tabs.filter("#" + hash)).hasClass('active')) {

                    // if it is non ajax page loading, replace the current page with the new hash, but don't use location.hash
                    //if (!EQTR.ajax.useAjaxLoading) {
                    //    location.replace($thisA.attr("href"));
                    //}

                    //$this.trigger("tabChange", hash);
                    $this.find('a').removeClass('active');
                    $thisA.addClass('active');

                    tabs.filter('.active').fadeOut(settings.speed, function() {
                        var active = correspondingTab.addClass('active').fadeIn(settings.speed);

                        // setup the images if they were invisible before
                        active.find(".cover-image").backgroundCover();
                        active.find(".responsive-background-image").responsiveBackgroundImage();
                        //scrollParentNiceScroll && scrollParent.getNiceScroll().resize();
                    }).removeClass('active');
                }

            })
                // replace the hash with the querystring tab
                .attr("href", function(index, val) {
                    return val.replace("#", (EQTR.ajax.useAjaxLoading ? "?" : "#?") + "tab=");
                });

            // see if there is a hash in the url. If there is use it to make that tab active (if it exists)
            if (location.href.match(/tab=([^&]*)/)) {
                tabTriggers.filter("[href*='tab=" + RegExp.$1 + "']").triggerHandler("click");
            }

        });

        $.fx.off = false;

        return this;
    };

    $.fn.tabify.defaultOptions = {
        speed: 300
    };

})(jQuery);;
; (function ($) {

    'use strict';

    var fitword = function(words) {

//        var t = new Date();

        words.each(function(index) {

            // custom for the panel at the moment. Don't worry about hidden items
            if ($(this).is(":hidden")) return true;
            var text = $(this);

            text.css("font-size", "");

            // get the current width
            var currentWidth = Math.max( text.width(), text[0].scrollWidth);
            // set the font to be 1px and get the new width
            var optimalWidth = text.css("font-size", 1).width();
            text.css("font-size", "");

            if (currentWidth > optimalWidth) {

                var currentFontsize = (text.css("font-size").replace("px", "")) / 10; // get in rems
                //console.log(currentLetterSpacing);
                var currentLetterSpacing = text.css("letter-spacing", "").css("letter-spacing").toString().replace("px", "");
                //console.log(currentLetterSpacing);

                var ratio = optimalWidth / currentWidth;
                
                if ((currentLetterSpacing * ratio) > 1) currentLetterSpacing = currentLetterSpacing * ratio;

                currentFontsize = Math.floor(currentFontsize * ratio) * 10;

                text.css({ fontSize: currentFontsize, letterSpacing: currentLetterSpacing });

                // do second check to make sure
                if ((Math.max(text.width(), text[0].scrollWidth) > optimalWidth) && currentFontsize > 10) {
                    // make the font smaller till it fits. Bad for now, maybe forever
                    if (currentLetterSpacing > 1) currentLetterSpacing -= 0.8;
                    text.css({ fontSize: currentFontsize -= 2, letterSpacing: currentLetterSpacing });
                }

            }

        });

//        console.info(new Date().valueOf() - t.valueOf());

    };

    $.fn.fitword = function () {
        var words = this;

        fitword(words);

        return this;
    };

})(jQuery);;
// if this isn't using ajax loading and there is a tab in querystring format, then reload the page so it reflects just the hash
if (!(window.history && history.pushState) && location.href.match(/([^#]\?tab=)/i)) {
    location.replace(location.href.replace(/\?tab=/, "#?tab="));
}

(function ($) {


    $.fn.contentexpander = function (options) {

        var settings = $.extend({}, $.fn.contentexpander.defaultOptions, options);

        // .content-expander
        return this.each(function () {

             var $this = $(this),
                scrollParent = $this.scrollParent(),
                
                    slideOptions = { duration: settings.speed };

            if (EQTR.detectDevice.isDesktop()) {
            //    // if this is too janky change "step" to "complete"
                slideOptions.step = function () {
                    scrollParent.getNiceScroll().resize();
                };
            }

            $this.on('click', '.item-name a', function (e,ignoreReplaceUrl) {
                var item = $(this).closest('.item'),
                    itemDetails = item.find('.item-details'),
                    isClosing = item.hasClass('active');

                itemDetails[isClosing ? "slideUp" : "slideDown"](slideOptions);

                if( isClosing || !item.prop("id") ) {
                    // so the ajax loading doesn't get called
                    e.preventDefault();
                } else {
                    // if it is non ajax page loading, replace the current page with the new hash, but don't use location.hash
                    if (!EQTR.ajax.useAjaxLoading) {
                        //location.replace($(this).attr("href"));
						e.preventDefault();
                    } else if (ignoreReplaceUrl) {
                        // so the ajax loading doesn't get called if this is page load (was removing tracking parameters in the querystring before scripts could read it (I think)
                        e.preventDefault();
                    }

                }
                // load any responsive images
                !isClosing && itemDetails.find(".responsive-background-image").responsiveBackgroundImage();

                item.toggleClass('active');

                //function scrollToPos() {
                //    var newScrollPos = item.position().top + scrollParent.scrollTop();

                //    scrollParent.animate({ 'scrollTop': newScrollPos }, 1000);
                //}

                //item.hasClass('active') && scrollToPos();
            });

            var item = $this.find('.item').each(function(index) {
                // setup the links so they can be opened via the url
                var id = this.id ? (EQTR.ajax.useAjaxLoading ? "?" : "#?") + "tab=" + this.id : "#";
                $(".item-name", this).html(function (index, val) {
                    return '<a href="' + id + '">' + val + '</a>';
                });
            });

            var itemDetails = item.find('.item-details');


            if (settings.closedOnLoad) {
                itemDetails.hide();
            } else {
                item.addClass('active');
                itemDetails.show();
            }
            
            // see if there is a hash in the url. If there is use it to make that tab active (if it exists)
            if (location.href.match(/tab=([^&]*)/)) {

                //console.info("#" + RegExp.$1 + " .item-name a");
                $("#" + RegExp.$1 + " > .item-name a").trigger("click",[true]);
            }


        });

    };

    $.fn.contentexpander.defaultOptions = {
        speed: 300,
        closedOnLoad: true
    };

})(jQuery);;
(function ($,undefined) {

    var namespace = "togglePanel";
    var counter = 0;


    var methods = {
        init: function (options) {

            return this.each(function () {
                var $this = $(this),
                    data = { };

                data.link = $this;
                data.panel = $(options.panel || $this.data("panel"));
                data.linkOpenClass = options.linkOpenClass || "";
                data.panelOpenClass = options.panelOpenClass || "";
                data.linkCloseClass = options.linkCloseClass || "";
                data.panelCloseClass = options.panelCloseClass || "";
                data.id = counter++;
                data.useJS = options.useJS;
                
                if( !data.panelOpenClass && !data.panelCloseClass ) {
                    // use jquery to open close the panel
                    // and fake the openclass. Assume closed on start
                    data.panelOpenClass = "_toggle-open";
                    data.useJS = true;
                }

                $this.data(namespace, data);
                // ie touch acts funny where mouseleave is triggered on a click
                var mousedOver = false;
                if (EQTR.detectDevice.supportsPointer()) {
                    var eventType;
                    if (window.navigator.pointerEnabled) {
                        eventType = "pointerdown";
                    } else if (window.navigator.msPointerEnabled) {
                        eventType = "MSPointerDown";
                    }
                    $this.on(eventType + " mouseenter", function(e) {
                        e.preventDefault();
                        data.openEventType = e.type;

                        var toggleState = undefined;

                        // mouseenter will always open the menu, so set the state to true
                        // also set a wee variable so a click after the mouseover won't close the menu straight away
                        // transition should take 900ms
                        if (e.type == "mouseenter") {
                            toggleState = true;
                            mousedOver = true;
                            setTimeout(function () { mousedOver = false; }, 600);
                        } else {
                            if (mousedOver)
                                return true;
                        }
                        $this[namespace]("toggle", toggleState);
                    });

                    // backup for cancelling the click
                    $this.on("click", function(e) {
                        e.preventDefault();
                    });
                } else {
                    // everyone else seems to be happy. Haven't tested on chrome touch
                    $this.on("click mouseenter", function (e) {
                        e.preventDefault();
                        var toggleState = undefined;

                        // mouseenter will always open the menu, so set the state to true
                        // also set a wee variable so a click after the mouseover won't close the menu straight away
                        // transition should take 900ms
                        if (e.type == "mouseenter") {
                            toggleState = true;
                            mousedOver = true;
                            setTimeout(function() { mousedOver = false; }, 600);
                        } else {
                            if (mousedOver)
                                return true;
                        }
                        $this[namespace]("toggle",toggleState);
                    });
                }

                if (EQTR.detectDevice.isDesktop()) {
                    setTimeout(function() {
                        var rail = data.panel.getNiceScroll().length ? $(data.panel.data("__nicescroll").rail) : $([]);
                        
                        data.railMouseDown = false;
                        
                        if( rail.length ) {
                            rail.children().mousedown(function() {
                                data.railMouseDown = true;
                                $(document).one("mouseup", function() {
                                    data.railMouseDown = false;
                                });
                            });
                        }

                        data.panel.add(data.link).add(rail).mouseenter(function() {
                            clearTimeout(data.closeTimer);
                        }).on("mouseleave",function (e) {
                            // removing might break pseudo touch laptops. Mouseleave is fired on click.
                            //if (!data.openEventType.match(/pointerdown/i)) {
                                clearTimeout(data.closeTimer);
                                if (!data.railMouseDown) {
                                    data.closeTimer = setTimeout(function() {
                                        $this[namespace]("toggle", false);
                                    }, 1500);
                                }
                            //}
                        });

                    }, 100);
                }

            });

        },
        setTimer:function (timer) {
            var $this = $(this),
                data = $this.data(namespace);

            data.closeTimer = timer;
        },
        toggle:function(boolOpen,undefined) {
            var $this = $(this),
                data = $this.data(namespace),
                panel = data.panel,
                openPromise;

            if( data.state == "open" && boolOpen) {
                return;
            }

            // hide the scroll whether it is being opened or closed. Can't animate the position (easily? at all?)
            panel.getNiceScroll().hide();

            // clear the timer
            clearTimeout(data.closeTimer);

            // remove any transitionend event handlers
            panel.off(".transition");

            // options for toggle. Don't need this for transitions
            var toggleOptions = Modernizr.csstransitions ? undefined : { duration: 900 };

            if (boolOpen === undefined) {
                boolOpen = !((data.panelOpenClass && panel.hasClass(data.panelOpenClass)) || (data.panelCloseClass && !panel.hasClass(data.panelCloseClass)));
            }

            if (boolOpen) {
                openPromise = panel.switchClass(data.panelCloseClass, data.panelOpenClass, toggleOptions).promise();
            } else {
                panel.switchClass(data.panelOpenClass, data.panelCloseClass, toggleOptions);
            }

            data.linkOpenClass && $this.toggleClass(data.linkOpenClass, boolOpen);
            data.linkCloseClass && $this.toggleClass(data.linkCloseClass, !boolOpen);

            // function for opened and closed state
            function panelOpened() {
                // code to execute after transition ends
                panel.getNiceScroll().resize().show();
                panel.off(".transition");
            }
            
            function panelClosed() {
                panel.scrollTop(0);
                panel.off(".transition");
            }

            data.state = boolOpen ? "open" : "closed";

            // isOpen means opening
            if (boolOpen) {
                $(document).on("mouseup." + namespace + data.id, function (e) {
                    // check to see if somewhere in the panel was clicked. If it wasn't then close the nav
                    if (!($(e.target).is($this) || $(e.target).closest($this).length || $(e.target).closest(panel).length || $(e.target).closest("#ui-datepicker-div,.ui-datepicker-header").length)) {
                        if( data.railMouseDown ) {
                            data.closeTimer = setTimeout(function () {
                                $this[namespace]("toggle", false);
                            }, 1500);
                        } else {
                            $this[namespace]("toggle", false);
                        }
                    }
                });

                if (data.useJS) {
                    panel.stop().slideDown(function () {
                        // code to execute after transition ends
                        panelOpened();
                    });
                } else {
                    if (Modernizr.csstransitions) {
                        panel.on(EQTR.GetTransitionEnd() + ".transition",
                            function (e) {
                                if (e.originalEvent.propertyName.match(/transform/)) {
                                    // code to execute after transition ends
                                    panelOpened();
                                }
                            });
                    } else {
                        openPromise && openPromise.done(panelOpened);
                    }
                }
            }
            else {
                $(document).off("." + namespace + data.id);

                if (data.useJS) {
                    panel.stop().slideUp(function () {
                        panelClosed();
                    });
                } else {
                    if (Modernizr.csstransitions) {
                        panel.on(EQTR.GetTransitionEnd() + ".transition",
                            function (e) {
                                if (e.originalEvent.propertyName.match(/transform/)) {
                                    panelClosed();
                                }
                            });
                    } else {
                        panel.scrollTop(0);
                    }
                }

            }

        }
    };
	
    $.fn[namespace] = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + namespace);
        }

    };

    $.fn[namespace].defaults = {
    };

})(jQuery);;
// simple scroller. Assumes that all overflows etc has been taken care of by css
/// add down arrow which can be clicked to go to the next panel
// moves the next panel to the focus point (top of screen) if it can

; (function ($,undefined) {

    var namespace = "simplePanelScroller";
    var counter = 0;
    
    var methods = {
        init: function (options) {
//            return this;

            options = options || {};

            return this.each(function () {
                var $this = $(this),
                    data = { children: options.children, current: 0 },
                    children = data.children ? $(data.children, $this) : $this.children(),
                    $scrollParent = children.eq(0).scrollParent();

                data.scrollTimer = null;
                data.scrollParent = $scrollParent;

                $this.data(namespace, data);
                $scrollParent.scroll(function (e) {
                    if (data.scrolling) {
                        return false;
                    }

                    var _el = $(this);
                    clearTimeout(data.scrollTimer);
                    data.scrollTimer = setTimeout(function () {
                        _el.trigger("scrollEnd");
                    }, 300);

                });

                $scrollParent.on("scrollEnd", function() {
                    $this[namespace]("snapTo");
                });

//                $scrollParent.on("mousewheel", function () {
//                    console.info("asdf");
//                                        if (data.scrolling) {
//                        $this[namespace]("cancelScroll");
//                    }
//                });

            });

        },
        cancelScroll:function () {
            var $this = $(this),
                data = $this.data(namespace),
                $scrollParent = data.scrollParent;

            $scrollParent.stop();
            data.scrolling = false;
        },
        snapTo:function(index) {
            var $this = $(this),
                data = $this.data(namespace),
                // getting the children each time in case they get added or removed
                children = data.children ? $(data.children, $this) : $this.children(),
                $scrollParent = data.scrollParent,
                scrollTop = $scrollParent.scrollTop(),
                scrollPosition = null;
            
            if( isNaN(index) ) {

                // find the child nearest the scrolltop
                children.each(function() {
                    var $child = $(this),
                        top = $child.position().top,
                        height = $child.height(),
                        bottom = top + height;

                    // if we are dead on, don't worry about the scrolling
                    if (top == 0 || bottom == 0) return false;

                    // if we are less than halfway through the child then go to the top of that child, otherwise go to the bottom i.e. top of the next child
                    if (top < scrollTop && bottom > 0) {
                        if (bottom < (height / 2)) {
                            scrollPosition = scrollTop + bottom;
                        } else {
                            scrollPosition = top + scrollTop;
                        }

                        data.current = $child.index();

                        return false;
                    }

                });

            } else {
                index = Math.round(index);

                if (children.eq(index).length) {
                    scrollPosition = scrollTop + children.eq(index).position().top;
                    data.current = index;
                }
            }


            if (scrollPosition != null) {

                data.scrolling = true;
                //    children.eq(0).css({ marginTop: -scrollTop });
                //    $scrollParent.scrollTop(0);

                //    setTimeout(function() {
                //        clearTimeout(data.scrollTimer);
                //    }, 100);

                //    children.eq(0).animate({ marginTop: -scrollPosition }, function() {
                //        children.eq(0).css({ marginTop: 0 });
                //        $scrollParent.scrollTop(scrollPosition);
                //        setTimeout(function() {
                //            clearTimeout(data.scrollTimer);
                //            data.scrolling = false;
                //        }, 100);
                //    });

                (scrollPosition != null) && $scrollParent.stop().animate({ scrollTop: scrollPosition }, function() {
                    setTimeout(function() {
                        $this[namespace]("cancelScroll");
                    }, 100);
                });
            }

        },
        scrollTo: function (index) {
            var $this = $(this);

            $this[namespace]("snapTo", index);

        },
        next:function () {
            var $this = $(this),
                data = $this.data(namespace);
            
            $this[namespace]("snapTo", data.current + 1);
            
        },
        prev:function () {
            var $this = $(this),
                data = $this.data(namespace);

            $this[namespace]("snapTo", data.current - 1);
        }
    };
	
    $.fn[namespace] = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + namespace);
        }

    };

    $.fn[namespace].defaults = {
    };

})(jQuery);;
/**
 * Isotope v1.5.26
 * An exquisite jQuery plugin for magical layouts
 * http://isotope.metafizzy.co
 *
 * Commercial use requires one-time purchase of a commercial license
 * http://isotope.metafizzy.co/docs/license.html
 *
 * Non-commercial use is licensed under the MIT License
 *
 * Copyright 2014 Metafizzy
 */
!function (t, i) { "use strict"; var s, e = t.document, n = e.documentElement, o = t.Modernizr, r = function (t) { return t.charAt(0).toUpperCase() + t.slice(1) }, a = "Moz Webkit O Ms".split(" "), h = function (t) { var i, s = n.style; if ("string" == typeof s[t]) return t; t = r(t); for (var e = 0, o = a.length; o > e; e++) if (i = a[e] + t, "string" == typeof s[i]) return i }, l = h("transform"), u = h("transitionProperty"), c = { csstransforms: function () { return !!l }, csstransforms3d: function () { var t = !!h("perspective"); if (t && "webkitPerspective" in n.style) { var s = i("<style>@media (transform-3d),(-webkit-transform-3d){#modernizr{height:3px}}</style>").appendTo("head"), e = i('<div id="modernizr" />').appendTo("html"); t = 3 === e.height(), e.remove(), s.remove() } return t }, csstransitions: function () { return !!u } }; if (o) for (s in c) o.hasOwnProperty(s) || o.addTest(s, c[s]); else { o = t.Modernizr = { _version: "1.6ish: miniModernizr for Isotope" }; var d, f = " "; for (s in c) d = c[s](), o[s] = d, f += " " + (d ? "" : "no-") + s; i("html").addClass(f) } if (o.csstransforms) { var m = o.csstransforms3d ? { translate: function (t) { return "translate3d(" + t[0] + "px, " + t[1] + "px, 0) " }, scale: function (t) { return "scale3d(" + t + ", " + t + ", 1) " } } : { translate: function (t) { return "translate(" + t[0] + "px, " + t[1] + "px) " }, scale: function (t) { return "scale(" + t + ") " } }, p = function (t, s, e) { var n, o, r = i.data(t, "isoTransform") || {}, a = {}, h = {}; a[s] = e, i.extend(r, a); for (n in r) o = r[n], h[n] = m[n](o); var u = h.translate || "", c = h.scale || "", d = u + c; i.data(t, "isoTransform", r), t.style[l] = d }; i.cssNumber.scale = !0, i.cssHooks.scale = { set: function (t, i) { p(t, "scale", i) }, get: function (t) { var s = i.data(t, "isoTransform"); return s && s.scale ? s.scale : 1 } }, i.fx.step.scale = function (t) { i.cssHooks.scale.set(t.elem, t.now + t.unit) }, i.cssNumber.translate = !0, i.cssHooks.translate = { set: function (t, i) { p(t, "translate", i) }, get: function (t) { var s = i.data(t, "isoTransform"); return s && s.translate ? s.translate : [0, 0] } } } var y, g; o.csstransitions && (y = { WebkitTransitionProperty: "webkitTransitionEnd", MozTransitionProperty: "transitionend", OTransitionProperty: "oTransitionEnd otransitionend", transitionProperty: "transitionend" }[u], g = h("transitionDuration")); var v, _ = i.event, A = i.event.handle ? "handle" : "dispatch"; _.special.smartresize = { setup: function () { i(this).bind("resize", _.special.smartresize.handler) }, teardown: function () { i(this).unbind("resize", _.special.smartresize.handler) }, handler: function (t, i) { var s = this, e = arguments; t.type = "smartresize", v && clearTimeout(v), v = setTimeout(function () { _[A].apply(s, e) }, "execAsap" === i ? 0 : 100) } }, i.fn.smartresize = function (t) { return t ? this.bind("smartresize", t) : this.trigger("smartresize", ["execAsap"]) }, i.Isotope = function (t, s, e) { this.element = i(s), this._create(t), this._init(e) }; var w = ["width", "height"], C = i(t); i.Isotope.settings = { resizable: !0, layoutMode: "masonry", containerClass: "isotope", itemClass: "isotope-item", hiddenClass: "isotope-hidden", hiddenStyle: { opacity: 0, scale: .001 }, visibleStyle: { opacity: 1, scale: 1 }, containerStyle: { position: "relative", overflow: "hidden" }, animationEngine: "best-available", animationOptions: { queue: !1, duration: 800 }, sortBy: "original-order", sortAscending: !0, resizesContainer: !0, transformsEnabled: !0, itemPositionDataEnabled: !1 }, i.Isotope.prototype = { _create: function (t) { this.options = i.extend({}, i.Isotope.settings, t), this.styleQueue = [], this.elemCount = 0; var s = this.element[0].style; this.originalStyle = {}; var e = w.slice(0); for (var n in this.options.containerStyle) e.push(n); for (var o = 0, r = e.length; r > o; o++) n = e[o], this.originalStyle[n] = s[n] || ""; this.element.css(this.options.containerStyle), this._updateAnimationEngine(), this._updateUsingTransforms(); var a = { "original-order": function (t, i) { return i.elemCount++, i.elemCount }, random: function () { return Math.random() } }; this.options.getSortData = i.extend(this.options.getSortData, a), this.reloadItems(), this.offset = { left: parseInt(this.element.css("padding-left") || 0, 10), top: parseInt(this.element.css("padding-top") || 0, 10) }; var h = this; setTimeout(function () { h.element.addClass(h.options.containerClass) }, 0), this.options.resizable && C.bind("smartresize.isotope", function () { h.resize() }), this.element.delegate("." + this.options.hiddenClass, "click", function () { return !1 }) }, _getAtoms: function (t) { var i = this.options.itemSelector, s = i ? t.filter(i).add(t.find(i)) : t, e = { position: "absolute" }; return s = s.filter(function (t, i) { return 1 === i.nodeType }), this.usingTransforms && (e.left = 0, e.top = 0), s.css(e).addClass(this.options.itemClass), this.updateSortData(s, !0), s }, _init: function (t) { this.$filteredAtoms = this._filter(this.$allAtoms), this._sort(), this.reLayout(t) }, option: function (t) { if (i.isPlainObject(t)) { this.options = i.extend(!0, this.options, t); var s; for (var e in t) s = "_update" + r(e), this[s] && this[s]() } }, _updateAnimationEngine: function () { var t, i = this.options.animationEngine.toLowerCase().replace(/[ _\-]/g, ""); switch (i) { case "css": case "none": t = !1; break; case "jquery": t = !0; break; default: t = !o.csstransitions } this.isUsingJQueryAnimation = t, this._updateUsingTransforms() }, _updateTransformsEnabled: function () { this._updateUsingTransforms() }, _updateUsingTransforms: function () { var t = this.usingTransforms = this.options.transformsEnabled && o.csstransforms && o.csstransitions && !this.isUsingJQueryAnimation; t || (delete this.options.hiddenStyle.scale, delete this.options.visibleStyle.scale), this.getPositionStyles = t ? this._translate : this._positionAbs }, _filter: function (t) { var i = "" === this.options.filter ? "*" : this.options.filter; if (!i) return t; var s = this.options.hiddenClass, e = "." + s, n = t.filter(e), o = n; if ("*" !== i) { o = n.filter(i); var r = t.not(e).not(i).addClass(s); this.styleQueue.push({ $el: r, style: this.options.hiddenStyle }) } return this.styleQueue.push({ $el: o, style: this.options.visibleStyle }), o.removeClass(s), t.filter(i) }, updateSortData: function (t, s) { var e, n, o = this, r = this.options.getSortData; t.each(function () { e = i(this), n = {}; for (var t in r) n[t] = s || "original-order" !== t ? r[t](e, o) : i.data(this, "isotope-sort-data")[t]; i.data(this, "isotope-sort-data", n) }) }, _sort: function () { var t = this.options.sortBy, i = this._getSorter, s = this.options.sortAscending ? 1 : -1, e = function (e, n) { var o = i(e, t), r = i(n, t); return o === r && "original-order" !== t && (o = i(e, "original-order"), r = i(n, "original-order")), (o > r ? 1 : r > o ? -1 : 0) * s }; this.$filteredAtoms.sort(e) }, _getSorter: function (t, s) { return i.data(t, "isotope-sort-data")[s] }, _translate: function (t, i) { return { translate: [t, i] } }, _positionAbs: function (t, i) { return { left: t, top: i } }, _pushPosition: function (t, i, s) { i = Math.round(i + this.offset.left), s = Math.round(s + this.offset.top); var e = this.getPositionStyles(i, s); this.styleQueue.push({ $el: t, style: e }), this.options.itemPositionDataEnabled && t.data("isotope-item-position", { x: i, y: s }) }, layout: function (t, i) { var s = this.options.layoutMode; if (this["_" + s + "Layout"](t), this.options.resizesContainer) { var e = this["_" + s + "GetContainerSize"](); this.styleQueue.push({ $el: this.element, style: e }) } this._processStyleQueue(t, i), this.isLaidOut = !0 }, _processStyleQueue: function (t, s) { var e, n, r, a, h = this.isLaidOut ? this.isUsingJQueryAnimation ? "animate" : "css" : "css", l = this.options.animationOptions, u = this.options.onLayout; if (n = function (t, i) { i.$el[h](i.style, l) }, this._isInserting && this.isUsingJQueryAnimation) n = function (t, i) { e = i.$el.hasClass("no-transition") ? "css" : h, i.$el[e](i.style, l) }; else if (s || u || l.complete) { var c = !1, d = [s, u, l.complete], f = this; if (r = !0, a = function () { if (!c) { for (var i, s = 0, e = d.length; e > s; s++) i = d[s], "function" == typeof i && i.call(f.element, t, f); c = !0 } }, this.isUsingJQueryAnimation && "animate" === h) l.complete = a, r = !1; else if (o.csstransitions) { for (var m, p = 0, v = this.styleQueue[0], _ = v && v.$el; !_ || !_.length;) { if (m = this.styleQueue[p++], !m) return; _ = m.$el } var A = parseFloat(getComputedStyle(_[0])[g]); A > 0 && (n = function (t, i) { i.$el[h](i.style, l).one(y, a) }, r = !1) } } i.each(this.styleQueue, n), r && a(), this.styleQueue = [] }, resize: function () { this["_" + this.options.layoutMode + "ResizeChanged"]() && this.reLayout() }, reLayout: function (t) { this["_" + this.options.layoutMode + "Reset"](), this.layout(this.$filteredAtoms, t) }, addItems: function (t, i) { var s = this._getAtoms(t); this.$allAtoms = this.$allAtoms.add(s), i && i(s) }, insert: function (t, i) { this.element.append(t); var s = this; this.addItems(t, function (t) { var e = s._filter(t); s._addHideAppended(e), s._sort(), s.reLayout(), s._revealAppended(e, i) }) }, appended: function (t, i) { var s = this; this.addItems(t, function (t) { s._addHideAppended(t), s.layout(t), s._revealAppended(t, i) }) }, _addHideAppended: function (t) { this.$filteredAtoms = this.$filteredAtoms.add(t), t.addClass("no-transition"), this._isInserting = !0, this.styleQueue.push({ $el: t, style: this.options.hiddenStyle }) }, _revealAppended: function (t, i) { var s = this; setTimeout(function () { t.removeClass("no-transition"), s.styleQueue.push({ $el: t, style: s.options.visibleStyle }), s._isInserting = !1, s._processStyleQueue(t, i) }, 10) }, reloadItems: function () { this.$allAtoms = this._getAtoms(this.element.children()) }, remove: function (t, i) { this.$allAtoms = this.$allAtoms.not(t), this.$filteredAtoms = this.$filteredAtoms.not(t); var s = this, e = function () { t.remove(), i && i.call(s.element) }; t.filter(":not(." + this.options.hiddenClass + ")").length ? (this.styleQueue.push({ $el: t, style: this.options.hiddenStyle }), this._sort(), this.reLayout(e)) : e() }, shuffle: function (t) { this.updateSortData(this.$allAtoms), this.options.sortBy = "random", this._sort(), this.reLayout(t) }, destroy: function () { var t = this.usingTransforms, i = this.options; this.$allAtoms.removeClass(i.hiddenClass + " " + i.itemClass).each(function () { var i = this.style; i.position = "", i.top = "", i.left = "", i.opacity = "", t && (i[l] = "") }); var s = this.element[0].style; for (var e in this.originalStyle) s[e] = this.originalStyle[e]; this.element.unbind(".isotope").undelegate("." + i.hiddenClass, "click").removeClass(i.containerClass).removeData("isotope"), C.unbind(".isotope") }, _getSegments: function (t) { var i, s = this.options.layoutMode, e = t ? "rowHeight" : "columnWidth", n = t ? "height" : "width", o = t ? "rows" : "cols", a = this.element[n](), h = this.options[s] && this.options[s][e] || this.$filteredAtoms["outer" + r(n)](!0) || a; i = Math.floor(a / h), i = Math.max(i, 1), this[s][o] = i, this[s][e] = h }, _checkIfSegmentsChanged: function (t) { var i = this.options.layoutMode, s = t ? "rows" : "cols", e = this[i][s]; return this._getSegments(t), this[i][s] !== e }, _masonryReset: function () { this.masonry = {}, this._getSegments(); var t = this.masonry.cols; for (this.masonry.colYs = []; t--;) this.masonry.colYs.push(0) }, _masonryLayout: function (t) { var s = this, e = s.masonry; t.each(function () { var t = i(this), n = Math.ceil(t.outerWidth(!0) / e.columnWidth); if (n = Math.min(n, e.cols), 1 === n) s._masonryPlaceBrick(t, e.colYs); else { var o, r, a = e.cols + 1 - n, h = []; for (r = 0; a > r; r++) o = e.colYs.slice(r, r + n), h[r] = Math.max.apply(Math, o); s._masonryPlaceBrick(t, h) } }) }, _masonryPlaceBrick: function (t, i) { for (var s = Math.min.apply(Math, i), e = 0, n = 0, o = i.length; o > n; n++) if (i[n] === s) { e = n; break } var r = this.masonry.columnWidth * e, a = s; this._pushPosition(t, r, a); var h = s + t.outerHeight(!0), l = this.masonry.cols + 1 - o; for (n = 0; l > n; n++) this.masonry.colYs[e + n] = h }, _masonryGetContainerSize: function () { var t = Math.max.apply(Math, this.masonry.colYs); return { height: t } }, _masonryResizeChanged: function () { return this._checkIfSegmentsChanged() }, _fitRowsReset: function () { this.fitRows = { x: 0, y: 0, height: 0 } }, _fitRowsLayout: function (t) { var s = this, e = this.element.width(), n = this.fitRows; t.each(function () { var t = i(this), o = t.outerWidth(!0), r = t.outerHeight(!0); 0 !== n.x && o + n.x > e && (n.x = 0, n.y = n.height), s._pushPosition(t, n.x, n.y), n.height = Math.max(n.y + r, n.height), n.x += o }) }, _fitRowsGetContainerSize: function () { return { height: this.fitRows.height } }, _fitRowsResizeChanged: function () { return !0 }, _cellsByRowReset: function () { this.cellsByRow = { index: 0 }, this._getSegments(), this._getSegments(!0) }, _cellsByRowLayout: function (t) { var s = this, e = this.cellsByRow; t.each(function () { var t = i(this), n = e.index % e.cols, o = Math.floor(e.index / e.cols), r = (n + .5) * e.columnWidth - t.outerWidth(!0) / 2, a = (o + .5) * e.rowHeight - t.outerHeight(!0) / 2; s._pushPosition(t, r, a), e.index++ }) }, _cellsByRowGetContainerSize: function () { return { height: Math.ceil(this.$filteredAtoms.length / this.cellsByRow.cols) * this.cellsByRow.rowHeight + this.offset.top } }, _cellsByRowResizeChanged: function () { return this._checkIfSegmentsChanged() }, _straightDownReset: function () { this.straightDown = { y: 0 } }, _straightDownLayout: function (t) { var s = this; t.each(function () { var t = i(this); s._pushPosition(t, 0, s.straightDown.y), s.straightDown.y += t.outerHeight(!0) }) }, _straightDownGetContainerSize: function () { return { height: this.straightDown.y } }, _straightDownResizeChanged: function () { return !0 }, _masonryHorizontalReset: function () { this.masonryHorizontal = {}, this._getSegments(!0); var t = this.masonryHorizontal.rows; for (this.masonryHorizontal.rowXs = []; t--;) this.masonryHorizontal.rowXs.push(0) }, _masonryHorizontalLayout: function (t) { var s = this, e = s.masonryHorizontal; t.each(function () { var t = i(this), n = Math.ceil(t.outerHeight(!0) / e.rowHeight); if (n = Math.min(n, e.rows), 1 === n) s._masonryHorizontalPlaceBrick(t, e.rowXs); else { var o, r, a = e.rows + 1 - n, h = []; for (r = 0; a > r; r++) o = e.rowXs.slice(r, r + n), h[r] = Math.max.apply(Math, o); s._masonryHorizontalPlaceBrick(t, h) } }) }, _masonryHorizontalPlaceBrick: function (t, i) { for (var s = Math.min.apply(Math, i), e = 0, n = 0, o = i.length; o > n; n++) if (i[n] === s) { e = n; break } var r = s, a = this.masonryHorizontal.rowHeight * e; this._pushPosition(t, r, a); var h = s + t.outerWidth(!0), l = this.masonryHorizontal.rows + 1 - o; for (n = 0; l > n; n++) this.masonryHorizontal.rowXs[e + n] = h }, _masonryHorizontalGetContainerSize: function () { var t = Math.max.apply(Math, this.masonryHorizontal.rowXs); return { width: t } }, _masonryHorizontalResizeChanged: function () { return this._checkIfSegmentsChanged(!0) }, _fitColumnsReset: function () { this.fitColumns = { x: 0, y: 0, width: 0 } }, _fitColumnsLayout: function (t) { var s = this, e = this.element.height(), n = this.fitColumns; t.each(function () { var t = i(this), o = t.outerWidth(!0), r = t.outerHeight(!0); 0 !== n.y && r + n.y > e && (n.x = n.width, n.y = 0), s._pushPosition(t, n.x, n.y), n.width = Math.max(n.x + o, n.width), n.y += r }) }, _fitColumnsGetContainerSize: function () { return { width: this.fitColumns.width } }, _fitColumnsResizeChanged: function () { return !0 }, _cellsByColumnReset: function () { this.cellsByColumn = { index: 0 }, this._getSegments(), this._getSegments(!0) }, _cellsByColumnLayout: function (t) { var s = this, e = this.cellsByColumn; t.each(function () { var t = i(this), n = Math.floor(e.index / e.rows), o = e.index % e.rows, r = (n + .5) * e.columnWidth - t.outerWidth(!0) / 2, a = (o + .5) * e.rowHeight - t.outerHeight(!0) / 2; s._pushPosition(t, r, a), e.index++ }) }, _cellsByColumnGetContainerSize: function () { return { width: Math.ceil(this.$filteredAtoms.length / this.cellsByColumn.rows) * this.cellsByColumn.columnWidth } }, _cellsByColumnResizeChanged: function () { return this._checkIfSegmentsChanged(!0) }, _straightAcrossReset: function () { this.straightAcross = { x: 0 } }, _straightAcrossLayout: function (t) { var s = this; t.each(function () { var t = i(this); s._pushPosition(t, s.straightAcross.x, 0), s.straightAcross.x += t.outerWidth(!0) }) }, _straightAcrossGetContainerSize: function () { return { width: this.straightAcross.x } }, _straightAcrossResizeChanged: function () { return !0 } }, i.fn.imagesLoaded = function (t) { function s() { t.call(n, o) } function e(t) { var n = t.target; n.src !== a && -1 === i.inArray(n, h) && (h.push(n), --r <= 0 && (setTimeout(s), o.unbind(".imagesLoaded", e))) } var n = this, o = n.find("img").add(n.filter("img")), r = o.length, a = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==", h = []; return r || s(), o.bind("load.imagesLoaded error.imagesLoaded", e).each(function () { var t = this.src; this.src = a, this.src = t }), n }; var z = function (i) { t.console && t.console.error(i) }; i.fn.isotope = function (t, s) { if ("string" == typeof t) { var e = Array.prototype.slice.call(arguments, 1); this.each(function () { var s = i.data(this, "isotope"); return s ? i.isFunction(s[t]) && "_" !== t.charAt(0) ? void s[t].apply(s, e) : void z("no such method '" + t + "' for isotope instance") : void z("cannot call methods on isotope prior to initialization; attempted to call method '" + t + "'") }) } else this.each(function () { var e = i.data(this, "isotope"); e ? (e.option(t), e._init(s)) : i.data(this, "isotope", new i.Isotope(t, this, s)) }); return this } }(window, jQuery);;
(function ($) {

    var scrollerFadeClass = "sc-faded",
        scrollerClass = "scroller-arrow-plugin",
        arrowMarkup = "<span class='scroller-arrow-pointer'>▼</span>",
        alternativeArrowMarkup = '<a href="#" class="scroller-arrow-pointer--circle {0}"><span>{1}</span><span class="icon icon-scroll-down"></span></a>';

    $.fn.scrollerArrow = function () {
		
		if(!isMobile)
		{
        return this.each(function () {
            var $this = $(this),
                $scrollParent = $this.children().scrollParent(),
                isFaded, ignoreScroll,
                dataExploreText = $this.data('scroller-explore-text'),
                dataExploreExtraClass = $this.data('scroller-explore-class'),
                $exploreLink = null;

            if (!$scrollParent.length) return;

            // setup the parent so it can contain an absolute child
            $scrollParent.addClass(scrollerClass).css({
                'position': function (index, value) {
                    if (value == "static") return "relative";
                }
            });

            // create the arrow and attach to the scrollParent
            if (typeof dataExploreExtraClass !== 'undefined' && typeof dataExploreText !== 'undefined') {
            	arrowMarkup = alternativeArrowMarkup.replace('{0}', dataExploreExtraClass).replace('{1}', dataExploreText);
            }
            var arrow = $(arrowMarkup).appendTo($scrollParent);
                //isFaded = false,
                //ignoreScroll = false;

            $scrollParent.scroll(function () {
                if (ignoreScroll) return true;
                
                var scrollTop = $scrollParent.scrollTop();
                if (!isFaded && scrollTop > 15) {
                    arrow.addClass(scrollerFadeClass);
                    isFaded = true;
                }
                if (isFaded && scrollTop <= 15) {
                    arrow.removeClass(scrollerFadeClass);
                    isFaded = false;
                }
            });

            //click event for scroll arrow
            var $exploreLink = $('.scroller-arrow-pointer--circle', $scrollParent);
            if ($exploreLink != null && $exploreLink.length) {
                var exploreLinkOffset = $exploreLink.offset().top;
                $exploreLink.on("click", function () {
                    $scrollParent.animate({ scrollTop: exploreLinkOffset });
                });
            }

            var arrowToggle = EQTR.AddToResizeQueue(function scrollerArrowResize() {
                if ($scrollParent.height() >= $scrollParent[0].scrollHeight) {
                    //console.info($scrollParent.height() , $scrollParent[0].scrollHeight);
                    arrow.addClass(scrollerFadeClass);
                    ignoreScroll = true;
                } else {
                    arrow.removeClass(scrollerFadeClass);
                    ignoreScroll = false;
                }
            });

            arrowToggle();

            $this.on("destoyed", function() {
                EQTR.RemoveFromResizeQueue(arrowToggle);
            });

        });
		}

    };

})(jQuery);
(function ($) {

    var namespace = "colouredLetters";
    var counter = 0;
    var domReplacementChar = "~";
    var colourArray = ["#EAB865", "#EB6528", "#E42656", "#74BADE", "#26B7B2", "#C4CE4B"];

    var methods = {
        init: function (options) {

            return this.each(function () {
                var $this = $(this),
                    data = { },
                    inject = "", domReplace;

                domReplace = $this.find("em").replaceWith(domReplacementChar);

                var a = $this.text().split("");

                if (a.length) {
                    $(a).each(function (i, item) {
                        inject += item == " " ? item : '<span>' + item + '</span>';
                    });

                    $this
                        .empty()
                        .append(inject)
                        .find(":contains('" + domReplacementChar + "')")
                        .each(function(i) {
                            $(this).replaceWith(domReplace.eq(i));
                        })
                        .end()
                        .find("span").each(function(i) {
                            $(this).css("color", colourArray[i % colourArray.length]);
                        });
                    


                }

            });
        }
    };
	
    $.fn[namespace] = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + namespace);
        }

    };

    $.fn[namespace].defaults = {
    };

})(jQuery);;
window.EQTR.filter = (function (namespace, $, undefined) {

    var _ = namespace,
        filterableItems,
        filterEl,
        filterElName;

	_.init = function (context) {

	    $('[js-filter]').each(function (index, el) {
            
	        var $this = $(this);
	        filterableItems = $this.children();
	        filterEl = $($this.attr('js-filter'));
	        filterElName = filterEl.find('select').attr('name'),
            filterSelect = filterEl.find('select'),
            closestNiceScroll = $this.closest('.nice-scroll').getNiceScroll(),
            lastFilteredMonth = 0;

	        filterEl.find('input[type="submit"]').on('click', function (e) {
	            e.preventDefault();
	            var $thisSelect = filterSelect,
	                value = $thisSelect.val();

	            if (lastFilteredMonth == value) {
	                return false;
	            }

                filteredItems = filterableItems.filter('[data-filter-' + filterElName + '=' + value + ']');

	            $.when(filterableItems.fadeOut()).then(function () {

	                $this.empty();
	                closestNiceScroll.resize();

	                if (!filteredItems.length) {
	                    return false;
	                }

	                $this.append(filteredItems);
	                filteredItems.fadeIn();
	                closestNiceScroll.resize();
	            });

	            lastFilteredMonth = value;
	            
	        });

	    });

	};

    // checks if an element has a scrollbar or not.
	_.hasScrollBar = function (el) {

	    if(!el.length) {
	        return false;
	    }

        return el[0].scrollHeight > el.height();
	};

	_.thing = function () {

	}


	_.showScrollIndicator = function (el, position, message) {

	}

	return _;

})(window.EQTR.filter || {}, jQuery);;
window.EQTR = (function (module, $) {

    $('.video-caption').on("click", function() {
        alert("click!");
    });

    var videoFunctions = {
        init :function() {
            
        },
        loadVideo : function(videodId) {
            
        }
    }

    module.VideoShit = videoFunctions;

    return module;

})(window.EQTR || {}, window.jQuery);


(function($) {



})(jQuery);;
(function(module,$) {

    var sessionCookieName = "takeover_session",
        cookieName,
        timerId,
        currentPopup,
        // timer variables
        now = (new Date()).valueOf(),
        timeStamp,
        triggerTime,
        timeLeft,
        blockCookie,
        customVarName,
        $takeOverContent,
        $takeOverPopup;

    var sub = {
        checkTakeoverStatus: function (context) {



            // check to see if there is a popup on the page to be used. 
            cookieName = window.takeoverPopupConfig && takeoverPopupConfig.cookieName; // ajaxload.

            // check to see what is in the session cookie
            currentPopup = readCookie(sessionCookieName);

            // if there is no cookieName this means there is no popup either on the page or in the takeover "cache".
            // if the session is set to true then the user has seen a takeover, so ignore making more popups
            if (!cookieName) {
                // if there is no cookie and a popup has not been seen, but has been set, reset it
                (currentPopup != "true") && removeCookie(sessionCookieName);
                return;
            }

            // create the popup if it doesn't exist
            ($takeOverPopup =  $('<div class="takeover__popupouter"><div class="takeover__cover"></div><div class="takeover__popup"><a href="#" class="takeover__popup-close">x</a></div><div class="takeover__popup__verticalaligner"></div></div>'));

            // run this on page load and ajax load
            //console.info(cookieName);

            // rules
            // - only one popup per session
            // - each popup cookie will last for 30 days
            // - the persistant cookie will only be set after the user has seen the popup

            // one persistant cookie for each popup (because we need to know the expiry and don't want to handle it manually
            // one session cookie for the session to determine if a takeover has already been seen, also to store what takeover is being processed currently
            // should be server logic to not show the popup html if the cookie exists already

            
            // if there is new takeover in town, kill the timer and the cookie if it isn't true
            
            if (currentPopup != cookieName) {
                (readCookie(currentPopup) != "true") && removeCookie(currentPopup);
                clearTimeout(timerId);
            }
            // create the session cookie storing the current takeover name
            createCookie(sessionCookieName, cookieName);

            // read cookie.
            // if there is not a cookie, create it with a timestamp
            // if there is a cookie, check to see if it is true (already seen)
            // if it is true, don't show it
            // if it is not true it must be a timestamp
            // set a timer based on  "trigger time" - ("now" - "timestamp")

            triggerTime = takeoverPopupConfig.timer;

            if (!(timeStamp = readCookie(cookieName))) {
                timeStamp = now;
                createCookie(cookieName, timeStamp);

                $takeOverContent && $takeOverContent.remove();

                $takeOverContent = $(".js-takeover-content",context).removeClass("js-takeover-content").detach();

            } else {
                timeStamp = parseInt(timeStamp);
                if (isNaN(timeStamp)) return;
            }

            timeLeft = triggerTime - (now - timeStamp);

            if (timeLeft < 0) timeLeft = 0;

            customVarName = cookieName;

            timerId = setTimeout(showTakeover, timeLeft);


        }
    };

    $(window).on("beforeunload", function (e) {
        // block the cookie from being written so user has less chance to miss it on a page load
        clearTimeout(timerId);
        blockCookie = true;
    });

	function setDoneCookie() {
	    if (blockCookie) return;
	    EQTR.Analytics.setCustomVar(5, customVarName, 'Popup seen', 1);
	    EQTR.Analytics.trackEvent(customVarName, 'Popup seen', 'Popup seen: ' + location.pathname);
	    createCookie(cookieName, true, 30);
	}

	function showTakeover() {

	    var $popup = $takeOverPopup,
            $cover = $('.takeover__cover', $popup),
            $content = $takeOverContent,
            $close = $(".takeover__popup-close", $popup);

	    $popup.find(".takeover__popup").append($content).end().appendTo("body");

	    // set the responsive image up
	    $(".responsive-background-image", $content).responsiveBackgroundImage();

	    createCookie(sessionCookieName, true);
	    takeoverPopupConfig = null;
			
	    if( Modernizr.csstransitions ) {
	        $cover.hide().fadeIn("slow",function() {
	            $popup.addClass("takeover__popupouter--reveal");
	            setDoneCookie();
	        });
	    } else {
	        $popup.animate({left:0},setDoneCookie);
	    }
			
	    $close.add($cover).click(function(evt) {
				
	        evt.preventDefault();
	        $cover.fadeOut("slow",function() {
	            //$cover.remove();
	        });
					
	        if( Modernizr.csstransitions ) {
	            $popup.removeClass("takeover__popupouter--reveal");
	            setTimeout(function() {$popup.remove();},1000);
	        } else {
	            $popup.animate({left:"100%"},function() {$(this).remove();});
	        }
									
	    });

	    $("a", $content).click(function() {
	        EQTR.Analytics.setCustomVar(5, customVarName, 'CTA clicked', 1);
	        EQTR.Analytics.trackEvent(customVarName, 'CTA clicked', 'CTA clicked: ' + location.pathname);
	        $close.click();
	    });
		
	}

    // borrowed from http://www.quirksmode.org/js/cookies.html
	function createCookie(name,value,days) {
	    if (days) {
	        var date = new Date();
	        date.setTime(date.getTime()+(days*24*60*60*1000));
	        var expires = "; expires="+date.toGMTString();
	    }
	    else var expires = "";
	    document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
	    var nameEQ = name + "=";
	    var ca = document.cookie.split(';');
	    for (var i = 0; i < ca.length; i++) {
	        var c = ca[i];
	        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
	        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	    }
	    return null;
	}

	function removeCookie(name) {
	    createCookie(name, "", -1);
	}
	
	module.takeover = sub;

	return module;

})(window.EQTR || {}, jQuery);;
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    global.moment = factory()
}(this, function () {
    'use strict';

    var hookCallback;

    function utils_hooks__hooks() {
        return hookCallback.apply(null, arguments);
    }

    // This is done to register the method called with moment()
    // without creating circular dependencies.
    function setHookCallback(callback) {
        hookCallback = callback;
    }

    function isArray(input) {
        return Object.prototype.toString.call(input) === '[object Array]';
    }

    function isDate(input) {
        return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
    }

    function map(arr, fn) {
        var res = [], i;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }

    function hasOwnProp(a, b) {
        return Object.prototype.hasOwnProperty.call(a, b);
    }

    function extend(a, b) {
        for (var i in b) {
            if (hasOwnProp(b, i)) {
                a[i] = b[i];
            }
        }

        if (hasOwnProp(b, 'toString')) {
            a.toString = b.toString;
        }

        if (hasOwnProp(b, 'valueOf')) {
            a.valueOf = b.valueOf;
        }

        return a;
    }

    function create_utc__createUTC(input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, true).utc();
    }

    function defaultParsingFlags() {
        // We need to deep clone this object.
        return {
            empty: false,
            unusedTokens: [],
            unusedInput: [],
            overflow: -2,
            charsLeftOver: 0,
            nullInput: false,
            invalidMonth: null,
            invalidFormat: false,
            userInvalidated: false,
            iso: false
        };
    }

    function getParsingFlags(m) {
        if (m._pf == null) {
            m._pf = defaultParsingFlags();
        }
        return m._pf;
    }

    function valid__isValid(m) {
        if (m._isValid == null) {
            var flags = getParsingFlags(m);
            m._isValid = !isNaN(m._d.getTime()) &&
                flags.overflow < 0 &&
                !flags.empty &&
                !flags.invalidMonth &&
                !flags.invalidWeekday &&
                !flags.nullInput &&
                !flags.invalidFormat &&
                !flags.userInvalidated;

            if (m._strict) {
                m._isValid = m._isValid &&
                    flags.charsLeftOver === 0 &&
                    flags.unusedTokens.length === 0 &&
                    flags.bigHour === undefined;
            }
        }
        return m._isValid;
    }

    function valid__createInvalid(flags) {
        var m = create_utc__createUTC(NaN);
        if (flags != null) {
            extend(getParsingFlags(m), flags);
        }
        else {
            getParsingFlags(m).userInvalidated = true;
        }

        return m;
    }

    var momentProperties = utils_hooks__hooks.momentProperties = [];

    function copyConfig(to, from) {
        var i, prop, val;

        if (typeof from._isAMomentObject !== 'undefined') {
            to._isAMomentObject = from._isAMomentObject;
        }
        if (typeof from._i !== 'undefined') {
            to._i = from._i;
        }
        if (typeof from._f !== 'undefined') {
            to._f = from._f;
        }
        if (typeof from._l !== 'undefined') {
            to._l = from._l;
        }
        if (typeof from._strict !== 'undefined') {
            to._strict = from._strict;
        }
        if (typeof from._tzm !== 'undefined') {
            to._tzm = from._tzm;
        }
        if (typeof from._isUTC !== 'undefined') {
            to._isUTC = from._isUTC;
        }
        if (typeof from._offset !== 'undefined') {
            to._offset = from._offset;
        }
        if (typeof from._pf !== 'undefined') {
            to._pf = getParsingFlags(from);
        }
        if (typeof from._locale !== 'undefined') {
            to._locale = from._locale;
        }

        if (momentProperties.length > 0) {
            for (i in momentProperties) {
                prop = momentProperties[i];
                val = from[prop];
                if (typeof val !== 'undefined') {
                    to[prop] = val;
                }
            }
        }

        return to;
    }

    var updateInProgress = false;

    // Moment prototype object
    function Moment(config) {
        copyConfig(this, config);
        this._d = new Date(config._d != null ? config._d.getTime() : NaN);
        // Prevent infinite loop in case updateOffset creates new moment
        // objects.
        if (updateInProgress === false) {
            updateInProgress = true;
            utils_hooks__hooks.updateOffset(this);
            updateInProgress = false;
        }
    }

    function isMoment(obj) {
        return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
    }

    function absFloor(number) {
        if (number < 0) {
            return Math.ceil(number);
        } else {
            return Math.floor(number);
        }
    }

    function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion,
            value = 0;

        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
            value = absFloor(coercedNumber);
        }

        return value;
    }

    function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    function Locale() {
    }

    var locales = {};
    var globalLocale;

    function normalizeLocale(key) {
        return key ? key.toLowerCase().replace('_', '-') : key;
    }

    // pick the locale from the array
    // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
    // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
    function chooseLocale(names) {
        var i = 0, j, next, locale, split;

        while (i < names.length) {
            split = normalizeLocale(names[i]).split('-');
            j = split.length;
            next = normalizeLocale(names[i + 1]);
            next = next ? next.split('-') : null;
            while (j > 0) {
                locale = loadLocale(split.slice(0, j).join('-'));
                if (locale) {
                    return locale;
                }
                if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return null;
    }

    function loadLocale(name) {
        var oldLocale = null;
        // TODO: Find a better way to register and load all the locales in Node
        if (!locales[name] && typeof module !== 'undefined' &&
                module && module.exports) {
            try {
                oldLocale = globalLocale._abbr;
                require('./locale/' + name);
                // because defineLocale currently also sets the global locale, we
                // want to undo that for lazy loaded locales
                locale_locales__getSetGlobalLocale(oldLocale);
            } catch (e) { }
        }
        return locales[name];
    }

    // This function will load locale and then set the global locale.  If
    // no arguments are passed in, it will simply return the current global
    // locale key.
    function locale_locales__getSetGlobalLocale(key, values) {
        var data;
        if (key) {
            if (typeof values === 'undefined') {
                data = locale_locales__getLocale(key);
            }
            else {
                data = defineLocale(key, values);
            }

            if (data) {
                // moment.duration._locale = moment._locale = data;
                globalLocale = data;
            }
        }

        return globalLocale._abbr;
    }

    function defineLocale(name, values) {
        if (values !== null) {
            values.abbr = name;
            locales[name] = locales[name] || new Locale();
            locales[name].set(values);

            // backwards compat for now: also set the locale
            locale_locales__getSetGlobalLocale(name);

            return locales[name];
        } else {
            // useful for testing
            delete locales[name];
            return null;
        }
    }

    // returns locale data
    function locale_locales__getLocale(key) {
        var locale;

        if (key && key._locale && key._locale._abbr) {
            key = key._locale._abbr;
        }

        if (!key) {
            return globalLocale;
        }

        if (!isArray(key)) {
            //short-circuit everything else
            locale = loadLocale(key);
            if (locale) {
                return locale;
            }
            key = [key];
        }

        return chooseLocale(key);
    }

    var aliases = {};

    function addUnitAlias(unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
    }

    function normalizeUnits(units) {
        return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
    }

    function normalizeObjectUnits(inputObject) {
        var normalizedInput = {},
            normalizedProp,
            prop;

        for (prop in inputObject) {
            if (hasOwnProp(inputObject, prop)) {
                normalizedProp = normalizeUnits(prop);
                if (normalizedProp) {
                    normalizedInput[normalizedProp] = inputObject[prop];
                }
            }
        }

        return normalizedInput;
    }

    function makeGetSet(unit, keepTime) {
        return function (value) {
            if (value != null) {
                get_set__set(this, unit, value);
                utils_hooks__hooks.updateOffset(this, keepTime);
                return this;
            } else {
                return get_set__get(this, unit);
            }
        };
    }

    function get_set__get(mom, unit) {
        return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
    }

    function get_set__set(mom, unit, value) {
        return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
    }

    // MOMENTS

    function getSet(units, value) {
        var unit;
        if (typeof units === 'object') {
            for (unit in units) {
                this.set(unit, units[unit]);
            }
        } else {
            units = normalizeUnits(units);
            if (typeof this[units] === 'function') {
                return this[units](value);
            }
        }
        return this;
    }

    function zeroFill(number, targetLength, forceSign) {
        var absNumber = '' + Math.abs(number),
            zerosToFill = targetLength - absNumber.length,
            sign = number >= 0;
        return (sign ? (forceSign ? '+' : '') : '-') +
            Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
    }

    var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

    var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

    var formatFunctions = {};

    var formatTokenFunctions = {};

    // token:    'M'
    // padded:   ['MM', 2]
    // ordinal:  'Mo'
    // callback: function () { this.month() + 1 }
    function addFormatToken(token, padded, ordinal, callback) {
        var func = callback;
        if (typeof callback === 'string') {
            func = function () {
                return this[callback]();
            };
        }
        if (token) {
            formatTokenFunctions[token] = func;
        }
        if (padded) {
            formatTokenFunctions[padded[0]] = function () {
                return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
            };
        }
        if (ordinal) {
            formatTokenFunctions[ordinal] = function () {
                return this.localeData().ordinal(func.apply(this, arguments), token);
            };
        }
    }

    function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
            return input.replace(/^\[|\]$/g, '');
        }
        return input.replace(/\\/g, '');
    }

    function makeFormatFunction(format) {
        var array = format.match(formattingTokens), i, length;

        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }

        return function (mom) {
            var output = '';
            for (i = 0; i < length; i++) {
                output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
            }
            return output;
        };
    }

    // format date using native date object
    function formatMoment(m, format) {
        if (!m.isValid()) {
            return m.localeData().invalidDate();
        }

        format = expandFormat(format, m.localeData());
        formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);

        return formatFunctions[format](m);
    }

    function expandFormat(format, locale) {
        var i = 5;

        function replaceLongDateFormatTokens(input) {
            return locale.longDateFormat(input) || input;
        }

        localFormattingTokens.lastIndex = 0;
        while (i >= 0 && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
            localFormattingTokens.lastIndex = 0;
            i -= 1;
        }

        return format;
    }

    var match1 = /\d/;            //       0 - 9
    var match2 = /\d\d/;          //      00 - 99
    var match3 = /\d{3}/;         //     000 - 999
    var match4 = /\d{4}/;         //    0000 - 9999
    var match6 = /[+-]?\d{6}/;    // -999999 - 999999
    var match1to2 = /\d\d?/;         //       0 - 99
    var match1to3 = /\d{1,3}/;       //       0 - 999
    var match1to4 = /\d{1,4}/;       //       0 - 9999
    var match1to6 = /[+-]?\d{1,6}/;  // -999999 - 999999

    var matchUnsigned = /\d+/;           //       0 - inf
    var matchSigned = /[+-]?\d+/;      //    -inf - inf

    var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z

    var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123

    // any word (or two) characters or numbers including two/three word month in arabic.
    var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;

    var regexes = {};

    function isFunction(sth) {
        // https://github.com/moment/moment/issues/2325
        return typeof sth === 'function' &&
            Object.prototype.toString.call(sth) === '[object Function]';
    }


    function addRegexToken(token, regex, strictRegex) {
        regexes[token] = isFunction(regex) ? regex : function (isStrict) {
            return (isStrict && strictRegex) ? strictRegex : regex;
        };
    }

    function getParseRegexForToken(token, config) {
        if (!hasOwnProp(regexes, token)) {
            return new RegExp(unescapeFormat(token));
        }

        return regexes[token](config._strict, config._locale);
    }

    // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    function unescapeFormat(s) {
        return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
            return p1 || p2 || p3 || p4;
        }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }

    var tokens = {};

    function addParseToken(token, callback) {
        var i, func = callback;
        if (typeof token === 'string') {
            token = [token];
        }
        if (typeof callback === 'number') {
            func = function (input, array) {
                array[callback] = toInt(input);
            };
        }
        for (i = 0; i < token.length; i++) {
            tokens[token[i]] = func;
        }
    }

    function addWeekParseToken(token, callback) {
        addParseToken(token, function (input, array, config, token) {
            config._w = config._w || {};
            callback(input, config._w, config, token);
        });
    }

    function addTimeToArrayFromToken(token, input, config) {
        if (input != null && hasOwnProp(tokens, token)) {
            tokens[token](input, config._a, config, token);
        }
    }

    var YEAR = 0;
    var MONTH = 1;
    var DATE = 2;
    var HOUR = 3;
    var MINUTE = 4;
    var SECOND = 5;
    var MILLISECOND = 6;

    function daysInMonth(year, month) {
        return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    }

    // FORMATTING

    addFormatToken('M', ['MM', 2], 'Mo', function () {
        return this.month() + 1;
    });

    addFormatToken('MMM', 0, 0, function (format) {
        return this.localeData().monthsShort(this, format);
    });

    addFormatToken('MMMM', 0, 0, function (format) {
        return this.localeData().months(this, format);
    });

    // ALIASES

    addUnitAlias('month', 'M');

    // PARSING

    addRegexToken('M', match1to2);
    addRegexToken('MM', match1to2, match2);
    addRegexToken('MMM', matchWord);
    addRegexToken('MMMM', matchWord);

    addParseToken(['M', 'MM'], function (input, array) {
        array[MONTH] = toInt(input) - 1;
    });

    addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
        var month = config._locale.monthsParse(input, token, config._strict);
        // if we didn't find a month name, mark the date as invalid.
        if (month != null) {
            array[MONTH] = month;
        } else {
            getParsingFlags(config).invalidMonth = input;
        }
    });

    // LOCALES

    var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
    function localeMonths(m) {
        return this._months[m.month()];
    }

    var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
    function localeMonthsShort(m) {
        return this._monthsShort[m.month()];
    }

    function localeMonthsParse(monthName, format, strict) {
        var i, mom, regex;

        if (!this._monthsParse) {
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
        }

        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = create_utc__createUTC([2000, i]);
            if (strict && !this._longMonthsParse[i]) {
                this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
                this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
            }
            if (!strict && !this._monthsParse[i]) {
                regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
                return i;
            } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
                return i;
            } else if (!strict && this._monthsParse[i].test(monthName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function setMonth(mom, value) {
        var dayOfMonth;

        // TODO: Move this out of here!
        if (typeof value === 'string') {
            value = mom.localeData().monthsParse(value);
            // TODO: Another silent failure?
            if (typeof value !== 'number') {
                return mom;
            }
        }

        dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        return mom;
    }

    function getSetMonth(value) {
        if (value != null) {
            setMonth(this, value);
            utils_hooks__hooks.updateOffset(this, true);
            return this;
        } else {
            return get_set__get(this, 'Month');
        }
    }

    function getDaysInMonth() {
        return daysInMonth(this.year(), this.month());
    }

    function checkOverflow(m) {
        var overflow;
        var a = m._a;

        if (a && getParsingFlags(m).overflow === -2) {
            overflow =
                a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
                a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
                a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
                a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
                a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
                a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
                -1;

            if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
                overflow = DATE;
            }

            getParsingFlags(m).overflow = overflow;
        }

        return m;
    }

    function warn(msg) {
        if (utils_hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
            console.warn('Deprecation warning: ' + msg);
        }
    }

    function deprecate(msg, fn) {
        var firstTime = true;

        return extend(function () {
            if (firstTime) {
                warn(msg + '\n' + (new Error()).stack);
                firstTime = false;
            }
            return fn.apply(this, arguments);
        }, fn);
    }

    var deprecations = {};

    function deprecateSimple(name, msg) {
        if (!deprecations[name]) {
            warn(msg);
            deprecations[name] = true;
        }
    }

    utils_hooks__hooks.suppressDeprecationWarnings = false;

    var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;

    var isoDates = [
        ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
        ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
        ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
        ['GGGG-[W]WW', /\d{4}-W\d{2}/],
        ['YYYY-DDD', /\d{4}-\d{3}/]
    ];

    // iso time formats and regexes
    var isoTimes = [
        ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
        ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
        ['HH:mm', /(T| )\d\d:\d\d/],
        ['HH', /(T| )\d\d/]
    ];

    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

    // date from iso format
    function configFromISO(config) {
        var i, l,
            string = config._i,
            match = from_string__isoRegex.exec(string);

        if (match) {
            getParsingFlags(config).iso = true;
            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(string)) {
                    config._f = isoDates[i][0];
                    break;
                }
            }
            for (i = 0, l = isoTimes.length; i < l; i++) {
                if (isoTimes[i][1].exec(string)) {
                    // match[6] should be 'T' or space
                    config._f += (match[6] || ' ') + isoTimes[i][0];
                    break;
                }
            }
            if (string.match(matchOffset)) {
                config._f += 'Z';
            }
            configFromStringAndFormat(config);
        } else {
            config._isValid = false;
        }
    }

    // date from iso format or fallback
    function configFromString(config) {
        var matched = aspNetJsonRegex.exec(config._i);

        if (matched !== null) {
            config._d = new Date(+matched[1]);
            return;
        }

        configFromISO(config);
        if (config._isValid === false) {
            delete config._isValid;
            utils_hooks__hooks.createFromInputFallback(config);
        }
    }

    utils_hooks__hooks.createFromInputFallback = deprecate(
        'moment construction falls back to js Date. This is ' +
        'discouraged and will be removed in upcoming major ' +
        'release. Please refer to ' +
        'https://github.com/moment/moment/issues/1407 for more info.',
        function (config) {
            config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
        }
    );

    function createDate(y, m, d, h, M, s, ms) {
        //can't just apply() to create a date:
        //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
        var date = new Date(y, m, d, h, M, s, ms);

        //the date constructor doesn't accept years < 1970
        if (y < 1970) {
            date.setFullYear(y);
        }
        return date;
    }

    function createUTCDate(y) {
        var date = new Date(Date.UTC.apply(null, arguments));
        if (y < 1970) {
            date.setUTCFullYear(y);
        }
        return date;
    }

    addFormatToken(0, ['YY', 2], 0, function () {
        return this.year() % 100;
    });

    addFormatToken(0, ['YYYY', 4], 0, 'year');
    addFormatToken(0, ['YYYYY', 5], 0, 'year');
    addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');

    // ALIASES

    addUnitAlias('year', 'y');

    // PARSING

    addRegexToken('Y', matchSigned);
    addRegexToken('YY', match1to2, match2);
    addRegexToken('YYYY', match1to4, match4);
    addRegexToken('YYYYY', match1to6, match6);
    addRegexToken('YYYYYY', match1to6, match6);

    addParseToken(['YYYYY', 'YYYYYY'], YEAR);
    addParseToken('YYYY', function (input, array) {
        array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input);
    });
    addParseToken('YY', function (input, array) {
        array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input);
    });

    // HELPERS

    function daysInYear(year) {
        return isLeapYear(year) ? 366 : 365;
    }

    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }

    // HOOKS

    utils_hooks__hooks.parseTwoDigitYear = function (input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
    };

    // MOMENTS

    var getSetYear = makeGetSet('FullYear', false);

    function getIsLeapYear() {
        return isLeapYear(this.year());
    }

    addFormatToken('w', ['ww', 2], 'wo', 'week');
    addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');

    // ALIASES

    addUnitAlias('week', 'w');
    addUnitAlias('isoWeek', 'W');

    // PARSING

    addRegexToken('w', match1to2);
    addRegexToken('ww', match1to2, match2);
    addRegexToken('W', match1to2);
    addRegexToken('WW', match1to2, match2);

    addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
        week[token.substr(0, 1)] = toInt(input);
    });

    // HELPERS

    // firstDayOfWeek       0 = sun, 6 = sat
    //                      the day of the week that starts the week
    //                      (usually sunday or monday)
    // firstDayOfWeekOfYear 0 = sun, 6 = sat
    //                      the first week is the week that contains the first
    //                      of this day of the week
    //                      (eg. ISO weeks use thursday (4))
    function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
        var end = firstDayOfWeekOfYear - firstDayOfWeek,
            daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
            adjustedMoment;


        if (daysToDayOfWeek > end) {
            daysToDayOfWeek -= 7;
        }

        if (daysToDayOfWeek < end - 7) {
            daysToDayOfWeek += 7;
        }

        adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd');
        return {
            week: Math.ceil(adjustedMoment.dayOfYear() / 7),
            year: adjustedMoment.year()
        };
    }

    // LOCALES

    function localeWeek(mom) {
        return weekOfYear(mom, this._week.dow, this._week.doy).week;
    }

    var defaultLocaleWeek = {
        dow: 0, // Sunday is the first day of the week.
        doy: 6  // The week that contains Jan 1st is the first week of the year.
    };

    function localeFirstDayOfWeek() {
        return this._week.dow;
    }

    function localeFirstDayOfYear() {
        return this._week.doy;
    }

    // MOMENTS

    function getSetWeek(input) {
        var week = this.localeData().week(this);
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    function getSetISOWeek(input) {
        var week = weekOfYear(this, 1, 4).week;
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');

    // ALIASES

    addUnitAlias('dayOfYear', 'DDD');

    // PARSING

    addRegexToken('DDD', match1to3);
    addRegexToken('DDDD', match3);
    addParseToken(['DDD', 'DDDD'], function (input, array, config) {
        config._dayOfYear = toInt(input);
    });

    // HELPERS

    //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
    function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
        var week1Jan = 6 + firstDayOfWeek - firstDayOfWeekOfYear, janX = createUTCDate(year, 0, 1 + week1Jan), d = janX.getUTCDay(), dayOfYear;
        if (d < firstDayOfWeek) {
            d += 7;
        }

        weekday = weekday != null ? 1 * weekday : firstDayOfWeek;

        dayOfYear = 1 + week1Jan + 7 * (week - 1) - d + weekday;

        return {
            year: dayOfYear > 0 ? year : year - 1,
            dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
        };
    }

    // MOMENTS

    function getSetDayOfYear(input) {
        var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
        return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
    }

    // Pick the first defined of two or three arguments.
    function defaults(a, b, c) {
        if (a != null) {
            return a;
        }
        if (b != null) {
            return b;
        }
        return c;
    }

    function currentDateArray(config) {
        var now = new Date();
        if (config._useUTC) {
            return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()];
        }
        return [now.getFullYear(), now.getMonth(), now.getDate()];
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function configFromArray(config) {
        var i, date, input = [], currentDate, yearToUse;

        if (config._d) {
            return;
        }

        currentDate = currentDateArray(config);

        //compute day of the year from weeks and weekdays
        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
            dayOfYearFromWeekInfo(config);
        }

        //if the day of the year is set, figure out what it is
        if (config._dayOfYear) {
            yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);

            if (config._dayOfYear > daysInYear(yearToUse)) {
                getParsingFlags(config)._overflowDayOfYear = true;
            }

            date = createUTCDate(yearToUse, 0, config._dayOfYear);
            config._a[MONTH] = date.getUTCMonth();
            config._a[DATE] = date.getUTCDate();
        }

        // Default to current date.
        // * if no year, month, day of month are given, default to today
        // * if day of month is given, default month and year
        // * if month is given, default only year
        // * if year is given, don't default anything
        for (i = 0; i < 3 && config._a[i] == null; ++i) {
            config._a[i] = input[i] = currentDate[i];
        }

        // Zero out whatever was not defaulted, including time
        for (; i < 7; i++) {
            config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
        }

        // Check for 24:00:00.000
        if (config._a[HOUR] === 24 &&
                config._a[MINUTE] === 0 &&
                config._a[SECOND] === 0 &&
                config._a[MILLISECOND] === 0) {
            config._nextDay = true;
            config._a[HOUR] = 0;
        }

        config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
        // Apply timezone offset from input. The actual utcOffset can be changed
        // with parseZone.
        if (config._tzm != null) {
            config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
        }

        if (config._nextDay) {
            config._a[HOUR] = 24;
        }
    }

    function dayOfYearFromWeekInfo(config) {
        var w, weekYear, week, weekday, dow, doy, temp;

        w = config._w;
        if (w.GG != null || w.W != null || w.E != null) {
            dow = 1;
            doy = 4;

            // TODO: We need to take the current isoWeekYear, but that depends on
            // how we interpret now (local, utc, fixed offset). So create
            // a now version of current config (take local/utc/offset flags, and
            // create now).
            weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year);
            week = defaults(w.W, 1);
            weekday = defaults(w.E, 1);
        } else {
            dow = config._locale._week.dow;
            doy = config._locale._week.doy;

            weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year);
            week = defaults(w.w, 1);

            if (w.d != null) {
                // weekday -- low day numbers are considered next week
                weekday = w.d;
                if (weekday < dow) {
                    ++week;
                }
            } else if (w.e != null) {
                // local weekday -- counting starts from begining of week
                weekday = w.e + dow;
            } else {
                // default to begining of week
                weekday = dow;
            }
        }
        temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);

        config._a[YEAR] = temp.year;
        config._dayOfYear = temp.dayOfYear;
    }

    utils_hooks__hooks.ISO_8601 = function () { };

    // date from string and format string
    function configFromStringAndFormat(config) {
        // TODO: Move this to another part of the creation flow to prevent circular deps
        if (config._f === utils_hooks__hooks.ISO_8601) {
            configFromISO(config);
            return;
        }

        config._a = [];
        getParsingFlags(config).empty = true;

        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var string = '' + config._i,
            i, parsedInput, tokens, token, skipped,
            stringLength = string.length,
            totalParsedInputLength = 0;

        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            if (parsedInput) {
                skipped = string.substr(0, string.indexOf(parsedInput));
                if (skipped.length > 0) {
                    getParsingFlags(config).unusedInput.push(skipped);
                }
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
                totalParsedInputLength += parsedInput.length;
            }
            // don't parse if it's not a known token
            if (formatTokenFunctions[token]) {
                if (parsedInput) {
                    getParsingFlags(config).empty = false;
                }
                else {
                    getParsingFlags(config).unusedTokens.push(token);
                }
                addTimeToArrayFromToken(token, parsedInput, config);
            }
            else if (config._strict && !parsedInput) {
                getParsingFlags(config).unusedTokens.push(token);
            }
        }

        // add remaining unparsed input length to the string
        getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
            getParsingFlags(config).unusedInput.push(string);
        }

        // clear _12h flag if hour is <= 12
        if (getParsingFlags(config).bigHour === true &&
                config._a[HOUR] <= 12 &&
                config._a[HOUR] > 0) {
            getParsingFlags(config).bigHour = undefined;
        }
        // handle meridiem
        config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);

        configFromArray(config);
        checkOverflow(config);
    }


    function meridiemFixWrap(locale, hour, meridiem) {
        var isPm;

        if (meridiem == null) {
            // nothing to do
            return hour;
        }
        if (locale.meridiemHour != null) {
            return locale.meridiemHour(hour, meridiem);
        } else if (locale.isPM != null) {
            // Fallback
            isPm = locale.isPM(meridiem);
            if (isPm && hour < 12) {
                hour += 12;
            }
            if (!isPm && hour === 12) {
                hour = 0;
            }
            return hour;
        } else {
            // this is not supposed to happen
            return hour;
        }
    }

    function configFromStringAndArray(config) {
        var tempConfig,
            bestMoment,

            scoreToBeat,
            i,
            currentScore;

        if (config._f.length === 0) {
            getParsingFlags(config).invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._f = config._f[i];
            configFromStringAndFormat(tempConfig);

            if (!valid__isValid(tempConfig)) {
                continue;
            }

            // if there is any input that was not parsed add a penalty for that format
            currentScore += getParsingFlags(tempConfig).charsLeftOver;

            //or tokens
            currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;

            getParsingFlags(tempConfig).score = currentScore;

            if (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    function configFromObject(config) {
        if (config._d) {
            return;
        }

        var i = normalizeObjectUnits(config._i);
        config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond];

        configFromArray(config);
    }

    function createFromConfig(config) {
        var res = new Moment(checkOverflow(prepareConfig(config)));
        if (res._nextDay) {
            // Adding is smart enough around DST
            res.add(1, 'd');
            res._nextDay = undefined;
        }

        return res;
    }

    function prepareConfig(config) {
        var input = config._i,
            format = config._f;

        config._locale = config._locale || locale_locales__getLocale(config._l);

        if (input === null || (format === undefined && input === '')) {
            return valid__createInvalid({ nullInput: true });
        }

        if (typeof input === 'string') {
            config._i = input = config._locale.preparse(input);
        }

        if (isMoment(input)) {
            return new Moment(checkOverflow(input));
        } else if (isArray(format)) {
            configFromStringAndArray(config);
        } else if (format) {
            configFromStringAndFormat(config);
        } else if (isDate(input)) {
            config._d = input;
        } else {
            configFromInput(config);
        }

        return config;
    }

    function configFromInput(config) {
        var input = config._i;
        if (input === undefined) {
            config._d = new Date();
        } else if (isDate(input)) {
            config._d = new Date(+input);
        } else if (typeof input === 'string') {
            configFromString(config);
        } else if (isArray(input)) {
            config._a = map(input.slice(0), function (obj) {
                return parseInt(obj, 10);
            });
            configFromArray(config);
        } else if (typeof (input) === 'object') {
            configFromObject(config);
        } else if (typeof (input) === 'number') {
            // from milliseconds
            config._d = new Date(input);
        } else {
            utils_hooks__hooks.createFromInputFallback(config);
        }
    }

    function createLocalOrUTC(input, format, locale, strict, isUTC) {
        var c = {};

        if (typeof (locale) === 'boolean') {
            strict = locale;
            locale = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c._isAMomentObject = true;
        c._useUTC = c._isUTC = isUTC;
        c._l = locale;
        c._i = input;
        c._f = format;
        c._strict = strict;

        return createFromConfig(c);
    }

    function local__createLocal(input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, false);
    }

    var prototypeMin = deprecate(
         'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
         function () {
             var other = local__createLocal.apply(null, arguments);
             return other < this ? this : other;
         }
     );

    var prototypeMax = deprecate(
        'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
        function () {
            var other = local__createLocal.apply(null, arguments);
            return other > this ? this : other;
        }
    );

    // Pick a moment m from moments so that m[fn](other) is true for all
    // other. This relies on the function fn to be transitive.
    //
    // moments should either be an array of moment objects or an array, whose
    // first element is an array of moment objects.
    function pickBy(fn, moments) {
        var res, i;
        if (moments.length === 1 && isArray(moments[0])) {
            moments = moments[0];
        }
        if (!moments.length) {
            return local__createLocal();
        }
        res = moments[0];
        for (i = 1; i < moments.length; ++i) {
            if (!moments[i].isValid() || moments[i][fn](res)) {
                res = moments[i];
            }
        }
        return res;
    }

    // TODO: Use [].sort instead?
    function min() {
        var args = [].slice.call(arguments, 0);

        return pickBy('isBefore', args);
    }

    function max() {
        var args = [].slice.call(arguments, 0);

        return pickBy('isAfter', args);
    }

    function Duration(duration) {
        var normalizedInput = normalizeObjectUnits(duration),
            years = normalizedInput.year || 0,
            quarters = normalizedInput.quarter || 0,
            months = normalizedInput.month || 0,
            weeks = normalizedInput.week || 0,
            days = normalizedInput.day || 0,
            hours = normalizedInput.hour || 0,
            minutes = normalizedInput.minute || 0,
            seconds = normalizedInput.second || 0,
            milliseconds = normalizedInput.millisecond || 0;

        // representation for dateAddRemove
        this._milliseconds = +milliseconds +
            seconds * 1e3 + // 1000
            minutes * 6e4 + // 1000 * 60
            hours * 36e5; // 1000 * 60 * 60
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = +days +
            weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = +months +
            quarters * 3 +
            years * 12;

        this._data = {};

        this._locale = locale_locales__getLocale();

        this._bubble();
    }

    function isDuration(obj) {
        return obj instanceof Duration;
    }

    function offset(token, separator) {
        addFormatToken(token, 0, 0, function () {
            var offset = this.utcOffset();
            var sign = '+';
            if (offset < 0) {
                offset = -offset;
                sign = '-';
            }
            return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
        });
    }

    offset('Z', ':');
    offset('ZZ', '');

    // PARSING

    addRegexToken('Z', matchOffset);
    addRegexToken('ZZ', matchOffset);
    addParseToken(['Z', 'ZZ'], function (input, array, config) {
        config._useUTC = true;
        config._tzm = offsetFromString(input);
    });

    // HELPERS

    // timezone chunker
    // '+10:00' > ['10',  '00']
    // '-1530'  > ['-15', '30']
    var chunkOffset = /([\+\-]|\d\d)/gi;

    function offsetFromString(string) {
        var matches = ((string || '').match(matchOffset) || []);
        var chunk = matches[matches.length - 1] || [];
        var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
        var minutes = +(parts[1] * 60) + toInt(parts[2]);

        return parts[0] === '+' ? minutes : -minutes;
    }

    // Return a moment from input, that is local/utc/zone equivalent to model.
    function cloneWithOffset(input, model) {
        var res, diff;
        if (model._isUTC) {
            res = model.clone();
            diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res);
            // Use low-level api, because this fn is low-level api.
            res._d.setTime(+res._d + diff);
            utils_hooks__hooks.updateOffset(res, false);
            return res;
        } else {
            return local__createLocal(input).local();
        }
    }

    function getDateOffset(m) {
        // On Firefox.24 Date#getTimezoneOffset returns a floating point.
        // https://github.com/moment/moment/pull/1871
        return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
    }

    // HOOKS

    // This function will be called whenever a moment is mutated.
    // It is intended to keep the offset in sync with the timezone.
    utils_hooks__hooks.updateOffset = function () { };

    // MOMENTS

    // keepLocalTime = true means only change the timezone, without
    // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
    // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
    // +0200, so we adjust the time as needed, to be valid.
    //
    // Keeping the time actually adds/subtracts (one hour)
    // from the actual represented time. That is why we call updateOffset
    // a second time. In case it wants us to change the offset again
    // _changeInProgress == true case, then we have to adjust, because
    // there is no such time in the given timezone.
    function getSetOffset(input, keepLocalTime) {
        var offset = this._offset || 0,
            localAdjust;
        if (input != null) {
            if (typeof input === 'string') {
                input = offsetFromString(input);
            }
            if (Math.abs(input) < 16) {
                input = input * 60;
            }
            if (!this._isUTC && keepLocalTime) {
                localAdjust = getDateOffset(this);
            }
            this._offset = input;
            this._isUTC = true;
            if (localAdjust != null) {
                this.add(localAdjust, 'm');
            }
            if (offset !== input) {
                if (!keepLocalTime || this._changeInProgress) {
                    add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false);
                } else if (!this._changeInProgress) {
                    this._changeInProgress = true;
                    utils_hooks__hooks.updateOffset(this, true);
                    this._changeInProgress = null;
                }
            }
            return this;
        } else {
            return this._isUTC ? offset : getDateOffset(this);
        }
    }

    function getSetZone(input, keepLocalTime) {
        if (input != null) {
            if (typeof input !== 'string') {
                input = -input;
            }

            this.utcOffset(input, keepLocalTime);

            return this;
        } else {
            return -this.utcOffset();
        }
    }

    function setOffsetToUTC(keepLocalTime) {
        return this.utcOffset(0, keepLocalTime);
    }

    function setOffsetToLocal(keepLocalTime) {
        if (this._isUTC) {
            this.utcOffset(0, keepLocalTime);
            this._isUTC = false;

            if (keepLocalTime) {
                this.subtract(getDateOffset(this), 'm');
            }
        }
        return this;
    }

    function setOffsetToParsedOffset() {
        if (this._tzm) {
            this.utcOffset(this._tzm);
        } else if (typeof this._i === 'string') {
            this.utcOffset(offsetFromString(this._i));
        }
        return this;
    }

    function hasAlignedHourOffset(input) {
        input = input ? local__createLocal(input).utcOffset() : 0;

        return (this.utcOffset() - input) % 60 === 0;
    }

    function isDaylightSavingTime() {
        return (
            this.utcOffset() > this.clone().month(0).utcOffset() ||
            this.utcOffset() > this.clone().month(5).utcOffset()
        );
    }

    function isDaylightSavingTimeShifted() {
        if (typeof this._isDSTShifted !== 'undefined') {
            return this._isDSTShifted;
        }

        var c = {};

        copyConfig(c, this);
        c = prepareConfig(c);

        if (c._a) {
            var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a);
            this._isDSTShifted = this.isValid() &&
                compareArrays(c._a, other.toArray()) > 0;
        } else {
            this._isDSTShifted = false;
        }

        return this._isDSTShifted;
    }

    function isLocal() {
        return !this._isUTC;
    }

    function isUtcOffset() {
        return this._isUTC;
    }

    function isUtc() {
        return this._isUTC && this._offset === 0;
    }

    var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/;

    // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
    // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
    var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;

    function create__createDuration(input, key) {
        var duration = input,
            // matching against regexp is expensive, do it on demand
            match = null,
            sign,
            ret,
            diffRes;

        if (isDuration(input)) {
            duration = {
                ms: input._milliseconds,
                d: input._days,
                M: input._months
            };
        } else if (typeof input === 'number') {
            duration = {};
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        } else if (!!(match = aspNetRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y: 0,
                d: toInt(match[DATE]) * sign,
                h: toInt(match[HOUR]) * sign,
                m: toInt(match[MINUTE]) * sign,
                s: toInt(match[SECOND]) * sign,
                ms: toInt(match[MILLISECOND]) * sign
            };
        } else if (!!(match = create__isoRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y: parseIso(match[2], sign),
                M: parseIso(match[3], sign),
                d: parseIso(match[4], sign),
                h: parseIso(match[5], sign),
                m: parseIso(match[6], sign),
                s: parseIso(match[7], sign),
                w: parseIso(match[8], sign)
            };
        } else if (duration == null) {// checks for null or undefined
            duration = {};
        } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
            diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to));

            duration = {};
            duration.ms = diffRes.milliseconds;
            duration.M = diffRes.months;
        }

        ret = new Duration(duration);

        if (isDuration(input) && hasOwnProp(input, '_locale')) {
            ret._locale = input._locale;
        }

        return ret;
    }

    create__createDuration.fn = Duration.prototype;

    function parseIso(inp, sign) {
        // We'd normally use ~~inp for this, but unfortunately it also
        // converts floats to ints.
        // inp may be undefined, so careful calling replace on it.
        var res = inp && parseFloat(inp.replace(',', '.'));
        // apply sign while we're at it
        return (isNaN(res) ? 0 : res) * sign;
    }

    function positiveMomentsDifference(base, other) {
        var res = { milliseconds: 0, months: 0 };

        res.months = other.month() - base.month() +
            (other.year() - base.year()) * 12;
        if (base.clone().add(res.months, 'M').isAfter(other)) {
            --res.months;
        }

        res.milliseconds = +other - +(base.clone().add(res.months, 'M'));

        return res;
    }

    function momentsDifference(base, other) {
        var res;
        other = cloneWithOffset(other, base);
        if (base.isBefore(other)) {
            res = positiveMomentsDifference(base, other);
        } else {
            res = positiveMomentsDifference(other, base);
            res.milliseconds = -res.milliseconds;
            res.months = -res.months;
        }

        return res;
    }

    function createAdder(direction, name) {
        return function (val, period) {
            var dur, tmp;
            //invert the arguments, but complain about it
            if (period !== null && !isNaN(+period)) {
                deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
                tmp = val; val = period; period = tmp;
            }

            val = typeof val === 'string' ? +val : val;
            dur = create__createDuration(val, period);
            add_subtract__addSubtract(this, dur, direction);
            return this;
        };
    }

    function add_subtract__addSubtract(mom, duration, isAdding, updateOffset) {
        var milliseconds = duration._milliseconds,
            days = duration._days,
            months = duration._months;
        updateOffset = updateOffset == null ? true : updateOffset;

        if (milliseconds) {
            mom._d.setTime(+mom._d + milliseconds * isAdding);
        }
        if (days) {
            get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding);
        }
        if (months) {
            setMonth(mom, get_set__get(mom, 'Month') + months * isAdding);
        }
        if (updateOffset) {
            utils_hooks__hooks.updateOffset(mom, days || months);
        }
    }

    var add_subtract__add = createAdder(1, 'add');
    var add_subtract__subtract = createAdder(-1, 'subtract');

    function moment_calendar__calendar(time, formats) {
        // We want to compare the start of today, vs this.
        // Getting start-of-today depends on whether we're local/utc/offset or not.
        var now = time || local__createLocal(),
            sod = cloneWithOffset(now, this).startOf('day'),
            diff = this.diff(sod, 'days', true),
            format = diff < -6 ? 'sameElse' :
                diff < -1 ? 'lastWeek' :
                diff < 0 ? 'lastDay' :
                diff < 1 ? 'sameDay' :
                diff < 2 ? 'nextDay' :
                diff < 7 ? 'nextWeek' : 'sameElse';
        return this.format(formats && formats[format] || this.localeData().calendar(format, this, local__createLocal(now)));
    }

    function clone() {
        return new Moment(this);
    }

    function isAfter(input, units) {
        var inputMs;
        units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
        if (units === 'millisecond') {
            input = isMoment(input) ? input : local__createLocal(input);
            return +this > +input;
        } else {
            inputMs = isMoment(input) ? +input : +local__createLocal(input);
            return inputMs < +this.clone().startOf(units);
        }
    }

    function isBefore(input, units) {
        var inputMs;
        units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
        if (units === 'millisecond') {
            input = isMoment(input) ? input : local__createLocal(input);
            return +this < +input;
        } else {
            inputMs = isMoment(input) ? +input : +local__createLocal(input);
            return +this.clone().endOf(units) < inputMs;
        }
    }

    function isBetween(from, to, units) {
        return this.isAfter(from, units) && this.isBefore(to, units);
    }

    function isSame(input, units) {
        var inputMs;
        units = normalizeUnits(units || 'millisecond');
        if (units === 'millisecond') {
            input = isMoment(input) ? input : local__createLocal(input);
            return +this === +input;
        } else {
            inputMs = +local__createLocal(input);
            return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units));
        }
    }

    function diff(input, units, asFloat) {
        var that = cloneWithOffset(input, this),
            zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4,
            delta, output;

        units = normalizeUnits(units);

        if (units === 'year' || units === 'month' || units === 'quarter') {
            output = monthDiff(this, that);
            if (units === 'quarter') {
                output = output / 3;
            } else if (units === 'year') {
                output = output / 12;
            }
        } else {
            delta = this - that;
            output = units === 'second' ? delta / 1e3 : // 1000
                units === 'minute' ? delta / 6e4 : // 1000 * 60
                units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
                units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
                units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
                delta;
        }
        return asFloat ? output : absFloor(output);
    }

    function monthDiff(a, b) {
        // difference in months
        var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
            // b is in (anchor - 1 month, anchor + 1 month)
            anchor = a.clone().add(wholeMonthDiff, 'months'),
            anchor2, adjust;

        if (b - anchor < 0) {
            anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor - anchor2);
        } else {
            anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor2 - anchor);
        }

        return -(wholeMonthDiff + adjust);
    }

    utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';

    function toString() {
        return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
    }

    function moment_format__toISOString() {
        var m = this.clone().utc();
        if (0 < m.year() && m.year() <= 9999) {
            if ('function' === typeof Date.prototype.toISOString) {
                // native implementation is ~50x faster, use it when we can
                return this.toDate().toISOString();
            } else {
                return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            }
        } else {
            return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
        }
    }

    function moment_format__format(inputString) {
        var output = formatMoment(this, inputString || utils_hooks__hooks.defaultFormat);
        return this.localeData().postformat(output);
    }

    function from(time, withoutSuffix) {
        if (!this.isValid()) {
            return this.localeData().invalidDate();
        }
        return create__createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix);
    }

    function fromNow(withoutSuffix) {
        return this.from(local__createLocal(), withoutSuffix);
    }

    function to(time, withoutSuffix) {
        if (!this.isValid()) {
            return this.localeData().invalidDate();
        }
        return create__createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix);
    }

    function toNow(withoutSuffix) {
        return this.to(local__createLocal(), withoutSuffix);
    }

    function locale(key) {
        var newLocaleData;

        if (key === undefined) {
            return this._locale._abbr;
        } else {
            newLocaleData = locale_locales__getLocale(key);
            if (newLocaleData != null) {
                this._locale = newLocaleData;
            }
            return this;
        }
    }

    var lang = deprecate(
        'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
        function (key) {
            if (key === undefined) {
                return this.localeData();
            } else {
                return this.locale(key);
            }
        }
    );

    function localeData() {
        return this._locale;
    }

    function startOf(units) {
        units = normalizeUnits(units);
        // the following switch intentionally omits break keywords
        // to utilize falling through the cases.
        switch (units) {
            case 'year':
                this.month(0);
                /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
                /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
                this.hours(0);
                /* falls through */
            case 'hour':
                this.minutes(0);
                /* falls through */
            case 'minute':
                this.seconds(0);
                /* falls through */
            case 'second':
                this.milliseconds(0);
        }

        // weeks are a special case
        if (units === 'week') {
            this.weekday(0);
        }
        if (units === 'isoWeek') {
            this.isoWeekday(1);
        }

        // quarters are also special
        if (units === 'quarter') {
            this.month(Math.floor(this.month() / 3) * 3);
        }

        return this;
    }

    function endOf(units) {
        units = normalizeUnits(units);
        if (units === undefined || units === 'millisecond') {
            return this;
        }
        return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
    }

    function to_type__valueOf() {
        return +this._d - ((this._offset || 0) * 60000);
    }

    function unix() {
        return Math.floor(+this / 1000);
    }

    function toDate() {
        return this._offset ? new Date(+this) : this._d;
    }

    function toArray() {
        var m = this;
        return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
    }

    function toObject() {
        var m = this;
        return {
            years: m.year(),
            months: m.month(),
            date: m.date(),
            hours: m.hours(),
            minutes: m.minutes(),
            seconds: m.seconds(),
            milliseconds: m.milliseconds()
        };
    }

    function moment_valid__isValid() {
        return valid__isValid(this);
    }

    function parsingFlags() {
        return extend({}, getParsingFlags(this));
    }

    function invalidAt() {
        return getParsingFlags(this).overflow;
    }

    addFormatToken(0, ['gg', 2], 0, function () {
        return this.weekYear() % 100;
    });

    addFormatToken(0, ['GG', 2], 0, function () {
        return this.isoWeekYear() % 100;
    });

    function addWeekYearFormatToken(token, getter) {
        addFormatToken(0, [token, token.length], 0, getter);
    }

    addWeekYearFormatToken('gggg', 'weekYear');
    addWeekYearFormatToken('ggggg', 'weekYear');
    addWeekYearFormatToken('GGGG', 'isoWeekYear');
    addWeekYearFormatToken('GGGGG', 'isoWeekYear');

    // ALIASES

    addUnitAlias('weekYear', 'gg');
    addUnitAlias('isoWeekYear', 'GG');

    // PARSING

    addRegexToken('G', matchSigned);
    addRegexToken('g', matchSigned);
    addRegexToken('GG', match1to2, match2);
    addRegexToken('gg', match1to2, match2);
    addRegexToken('GGGG', match1to4, match4);
    addRegexToken('gggg', match1to4, match4);
    addRegexToken('GGGGG', match1to6, match6);
    addRegexToken('ggggg', match1to6, match6);

    addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
        week[token.substr(0, 2)] = toInt(input);
    });

    addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
        week[token] = utils_hooks__hooks.parseTwoDigitYear(input);
    });

    // HELPERS

    function weeksInYear(year, dow, doy) {
        return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week;
    }

    // MOMENTS

    function getSetWeekYear(input) {
        var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
        return input == null ? year : this.add((input - year), 'y');
    }

    function getSetISOWeekYear(input) {
        var year = weekOfYear(this, 1, 4).year;
        return input == null ? year : this.add((input - year), 'y');
    }

    function getISOWeeksInYear() {
        return weeksInYear(this.year(), 1, 4);
    }

    function getWeeksInYear() {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
    }

    addFormatToken('Q', 0, 0, 'quarter');

    // ALIASES

    addUnitAlias('quarter', 'Q');

    // PARSING

    addRegexToken('Q', match1);
    addParseToken('Q', function (input, array) {
        array[MONTH] = (toInt(input) - 1) * 3;
    });

    // MOMENTS

    function getSetQuarter(input) {
        return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
    }

    addFormatToken('D', ['DD', 2], 'Do', 'date');

    // ALIASES

    addUnitAlias('date', 'D');

    // PARSING

    addRegexToken('D', match1to2);
    addRegexToken('DD', match1to2, match2);
    addRegexToken('Do', function (isStrict, locale) {
        return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
    });

    addParseToken(['D', 'DD'], DATE);
    addParseToken('Do', function (input, array) {
        array[DATE] = toInt(input.match(match1to2)[0], 10);
    });

    // MOMENTS

    var getSetDayOfMonth = makeGetSet('Date', true);

    addFormatToken('d', 0, 'do', 'day');

    addFormatToken('dd', 0, 0, function (format) {
        return this.localeData().weekdaysMin(this, format);
    });

    addFormatToken('ddd', 0, 0, function (format) {
        return this.localeData().weekdaysShort(this, format);
    });

    addFormatToken('dddd', 0, 0, function (format) {
        return this.localeData().weekdays(this, format);
    });

    addFormatToken('e', 0, 0, 'weekday');
    addFormatToken('E', 0, 0, 'isoWeekday');

    // ALIASES

    addUnitAlias('day', 'd');
    addUnitAlias('weekday', 'e');
    addUnitAlias('isoWeekday', 'E');

    // PARSING

    addRegexToken('d', match1to2);
    addRegexToken('e', match1to2);
    addRegexToken('E', match1to2);
    addRegexToken('dd', matchWord);
    addRegexToken('ddd', matchWord);
    addRegexToken('dddd', matchWord);

    addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) {
        var weekday = config._locale.weekdaysParse(input);
        // if we didn't get a weekday name, mark the date as invalid
        if (weekday != null) {
            week.d = weekday;
        } else {
            getParsingFlags(config).invalidWeekday = input;
        }
    });

    addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
        week[token] = toInt(input);
    });

    // HELPERS

    function parseWeekday(input, locale) {
        if (typeof input !== 'string') {
            return input;
        }

        if (!isNaN(input)) {
            return parseInt(input, 10);
        }

        input = locale.weekdaysParse(input);
        if (typeof input === 'number') {
            return input;
        }

        return null;
    }

    // LOCALES

    var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
    function localeWeekdays(m) {
        return this._weekdays[m.day()];
    }

    var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
    function localeWeekdaysShort(m) {
        return this._weekdaysShort[m.day()];
    }

    var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
    function localeWeekdaysMin(m) {
        return this._weekdaysMin[m.day()];
    }

    function localeWeekdaysParse(weekdayName) {
        var i, mom, regex;

        this._weekdaysParse = this._weekdaysParse || [];

        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already
            if (!this._weekdaysParse[i]) {
                mom = local__createLocal([2000, 1]).day(i);
                regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
                this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (this._weekdaysParse[i].test(weekdayName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function getSetDayOfWeek(input) {
        var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        if (input != null) {
            input = parseWeekday(input, this.localeData());
            return this.add(input - day, 'd');
        } else {
            return day;
        }
    }

    function getSetLocaleDayOfWeek(input) {
        var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
        return input == null ? weekday : this.add(input - weekday, 'd');
    }

    function getSetISODayOfWeek(input) {
        // behaves the same as moment#day except
        // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
        // as a setter, sunday should belong to the previous week.
        return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
    }

    addFormatToken('H', ['HH', 2], 0, 'hour');
    addFormatToken('h', ['hh', 2], 0, function () {
        return this.hours() % 12 || 12;
    });

    function meridiem(token, lowercase) {
        addFormatToken(token, 0, 0, function () {
            return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
        });
    }

    meridiem('a', true);
    meridiem('A', false);

    // ALIASES

    addUnitAlias('hour', 'h');

    // PARSING

    function matchMeridiem(isStrict, locale) {
        return locale._meridiemParse;
    }

    addRegexToken('a', matchMeridiem);
    addRegexToken('A', matchMeridiem);
    addRegexToken('H', match1to2);
    addRegexToken('h', match1to2);
    addRegexToken('HH', match1to2, match2);
    addRegexToken('hh', match1to2, match2);

    addParseToken(['H', 'HH'], HOUR);
    addParseToken(['a', 'A'], function (input, array, config) {
        config._isPm = config._locale.isPM(input);
        config._meridiem = input;
    });
    addParseToken(['h', 'hh'], function (input, array, config) {
        array[HOUR] = toInt(input);
        getParsingFlags(config).bigHour = true;
    });

    // LOCALES

    function localeIsPM(input) {
        // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
        // Using charAt should be more compatible.
        return ((input + '').toLowerCase().charAt(0) === 'p');
    }

    var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
    function localeMeridiem(hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'pm' : 'PM';
        } else {
            return isLower ? 'am' : 'AM';
        }
    }


    // MOMENTS

    // Setting the hour should keep the time, because the user explicitly
    // specified which hour he wants. So trying to maintain the same hour (in
    // a new timezone) makes sense. Adding/subtracting hours does not follow
    // this rule.
    var getSetHour = makeGetSet('Hours', true);

    addFormatToken('m', ['mm', 2], 0, 'minute');

    // ALIASES

    addUnitAlias('minute', 'm');

    // PARSING

    addRegexToken('m', match1to2);
    addRegexToken('mm', match1to2, match2);
    addParseToken(['m', 'mm'], MINUTE);

    // MOMENTS

    var getSetMinute = makeGetSet('Minutes', false);

    addFormatToken('s', ['ss', 2], 0, 'second');

    // ALIASES

    addUnitAlias('second', 's');

    // PARSING

    addRegexToken('s', match1to2);
    addRegexToken('ss', match1to2, match2);
    addParseToken(['s', 'ss'], SECOND);

    // MOMENTS

    var getSetSecond = makeGetSet('Seconds', false);

    addFormatToken('S', 0, 0, function () {
        return ~~(this.millisecond() / 100);
    });

    addFormatToken(0, ['SS', 2], 0, function () {
        return ~~(this.millisecond() / 10);
    });

    addFormatToken(0, ['SSS', 3], 0, 'millisecond');
    addFormatToken(0, ['SSSS', 4], 0, function () {
        return this.millisecond() * 10;
    });
    addFormatToken(0, ['SSSSS', 5], 0, function () {
        return this.millisecond() * 100;
    });
    addFormatToken(0, ['SSSSSS', 6], 0, function () {
        return this.millisecond() * 1000;
    });
    addFormatToken(0, ['SSSSSSS', 7], 0, function () {
        return this.millisecond() * 10000;
    });
    addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
        return this.millisecond() * 100000;
    });
    addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
        return this.millisecond() * 1000000;
    });


    // ALIASES

    addUnitAlias('millisecond', 'ms');

    // PARSING

    addRegexToken('S', match1to3, match1);
    addRegexToken('SS', match1to3, match2);
    addRegexToken('SSS', match1to3, match3);

    var token;
    for (token = 'SSSS'; token.length <= 9; token += 'S') {
        addRegexToken(token, matchUnsigned);
    }

    function parseMs(input, array) {
        array[MILLISECOND] = toInt(('0.' + input) * 1000);
    }

    for (token = 'S'; token.length <= 9; token += 'S') {
        addParseToken(token, parseMs);
    }
    // MOMENTS

    var getSetMillisecond = makeGetSet('Milliseconds', false);

    addFormatToken('z', 0, 0, 'zoneAbbr');
    addFormatToken('zz', 0, 0, 'zoneName');

    // MOMENTS

    function getZoneAbbr() {
        return this._isUTC ? 'UTC' : '';
    }

    function getZoneName() {
        return this._isUTC ? 'Coordinated Universal Time' : '';
    }

    var momentPrototype__proto = Moment.prototype;

    momentPrototype__proto.add = add_subtract__add;
    momentPrototype__proto.calendar = moment_calendar__calendar;
    momentPrototype__proto.clone = clone;
    momentPrototype__proto.diff = diff;
    momentPrototype__proto.endOf = endOf;
    momentPrototype__proto.format = moment_format__format;
    momentPrototype__proto.from = from;
    momentPrototype__proto.fromNow = fromNow;
    momentPrototype__proto.to = to;
    momentPrototype__proto.toNow = toNow;
    momentPrototype__proto.get = getSet;
    momentPrototype__proto.invalidAt = invalidAt;
    momentPrototype__proto.isAfter = isAfter;
    momentPrototype__proto.isBefore = isBefore;
    momentPrototype__proto.isBetween = isBetween;
    momentPrototype__proto.isSame = isSame;
    momentPrototype__proto.isValid = moment_valid__isValid;
    momentPrototype__proto.lang = lang;
    momentPrototype__proto.locale = locale;
    momentPrototype__proto.localeData = localeData;
    momentPrototype__proto.max = prototypeMax;
    momentPrototype__proto.min = prototypeMin;
    momentPrototype__proto.parsingFlags = parsingFlags;
    momentPrototype__proto.set = getSet;
    momentPrototype__proto.startOf = startOf;
    momentPrototype__proto.subtract = add_subtract__subtract;
    momentPrototype__proto.toArray = toArray;
    momentPrototype__proto.toObject = toObject;
    momentPrototype__proto.toDate = toDate;
    momentPrototype__proto.toISOString = moment_format__toISOString;
    momentPrototype__proto.toJSON = moment_format__toISOString;
    momentPrototype__proto.toString = toString;
    momentPrototype__proto.unix = unix;
    momentPrototype__proto.valueOf = to_type__valueOf;

    // Year
    momentPrototype__proto.year = getSetYear;
    momentPrototype__proto.isLeapYear = getIsLeapYear;

    // Week Year
    momentPrototype__proto.weekYear = getSetWeekYear;
    momentPrototype__proto.isoWeekYear = getSetISOWeekYear;

    // Quarter
    momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter;

    // Month
    momentPrototype__proto.month = getSetMonth;
    momentPrototype__proto.daysInMonth = getDaysInMonth;

    // Week
    momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek;
    momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek;
    momentPrototype__proto.weeksInYear = getWeeksInYear;
    momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear;

    // Day
    momentPrototype__proto.date = getSetDayOfMonth;
    momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek;
    momentPrototype__proto.weekday = getSetLocaleDayOfWeek;
    momentPrototype__proto.isoWeekday = getSetISODayOfWeek;
    momentPrototype__proto.dayOfYear = getSetDayOfYear;

    // Hour
    momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour;

    // Minute
    momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute;

    // Second
    momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond;

    // Millisecond
    momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond;

    // Offset
    momentPrototype__proto.utcOffset = getSetOffset;
    momentPrototype__proto.utc = setOffsetToUTC;
    momentPrototype__proto.local = setOffsetToLocal;
    momentPrototype__proto.parseZone = setOffsetToParsedOffset;
    momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset;
    momentPrototype__proto.isDST = isDaylightSavingTime;
    momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted;
    momentPrototype__proto.isLocal = isLocal;
    momentPrototype__proto.isUtcOffset = isUtcOffset;
    momentPrototype__proto.isUtc = isUtc;
    momentPrototype__proto.isUTC = isUtc;

    // Timezone
    momentPrototype__proto.zoneAbbr = getZoneAbbr;
    momentPrototype__proto.zoneName = getZoneName;

    // Deprecations
    momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
    momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
    momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
    momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone);

    var momentPrototype = momentPrototype__proto;

    function moment_moment__createUnix(input) {
        return local__createLocal(input * 1000);
    }

    function moment_moment__createInZone() {
        return local__createLocal.apply(null, arguments).parseZone();
    }

    var defaultCalendar = {
        sameDay: '[Today at] LT',
        nextDay: '[Tomorrow at] LT',
        nextWeek: 'dddd [at] LT',
        lastDay: '[Yesterday at] LT',
        lastWeek: '[Last] dddd [at] LT',
        sameElse: 'L'
    };

    function locale_calendar__calendar(key, mom, now) {
        var output = this._calendar[key];
        return typeof output === 'function' ? output.call(mom, now) : output;
    }

    var defaultLongDateFormat = {
        LTS: 'h:mm:ss A',
        LT: 'h:mm A',
        L: 'MM/DD/YYYY',
        LL: 'MMMM D, YYYY',
        LLL: 'MMMM D, YYYY h:mm A',
        LLLL: 'dddd, MMMM D, YYYY h:mm A'
    };

    function longDateFormat(key) {
        var format = this._longDateFormat[key],
            formatUpper = this._longDateFormat[key.toUpperCase()];

        if (format || !formatUpper) {
            return format;
        }

        this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
            return val.slice(1);
        });

        return this._longDateFormat[key];
    }

    var defaultInvalidDate = 'Invalid date';

    function invalidDate() {
        return this._invalidDate;
    }

    var defaultOrdinal = '%d';
    var defaultOrdinalParse = /\d{1,2}/;

    function ordinal(number) {
        return this._ordinal.replace('%d', number);
    }

    function preParsePostFormat(string) {
        return string;
    }

    var defaultRelativeTime = {
        future: 'in %s',
        past: '%s ago',
        s: 'a few seconds',
        m: 'a minute',
        mm: '%d minutes',
        h: 'an hour',
        hh: '%d hours',
        d: 'a day',
        dd: '%d days',
        M: 'a month',
        MM: '%d months',
        y: 'a year',
        yy: '%d years'
    };

    function relative__relativeTime(number, withoutSuffix, string, isFuture) {
        var output = this._relativeTime[string];
        return (typeof output === 'function') ?
            output(number, withoutSuffix, string, isFuture) :
            output.replace(/%d/i, number);
    }

    function pastFuture(diff, output) {
        var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
        return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
    }

    function locale_set__set(config) {
        var prop, i;
        for (i in config) {
            prop = config[i];
            if (typeof prop === 'function') {
                this[i] = prop;
            } else {
                this['_' + i] = prop;
            }
        }
        // Lenient ordinal parsing accepts just a number in addition to
        // number + (possibly) stuff coming from _ordinalParseLenient.
        this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
    }

    var prototype__proto = Locale.prototype;

    prototype__proto._calendar = defaultCalendar;
    prototype__proto.calendar = locale_calendar__calendar;
    prototype__proto._longDateFormat = defaultLongDateFormat;
    prototype__proto.longDateFormat = longDateFormat;
    prototype__proto._invalidDate = defaultInvalidDate;
    prototype__proto.invalidDate = invalidDate;
    prototype__proto._ordinal = defaultOrdinal;
    prototype__proto.ordinal = ordinal;
    prototype__proto._ordinalParse = defaultOrdinalParse;
    prototype__proto.preparse = preParsePostFormat;
    prototype__proto.postformat = preParsePostFormat;
    prototype__proto._relativeTime = defaultRelativeTime;
    prototype__proto.relativeTime = relative__relativeTime;
    prototype__proto.pastFuture = pastFuture;
    prototype__proto.set = locale_set__set;

    // Month
    prototype__proto.months = localeMonths;
    prototype__proto._months = defaultLocaleMonths;
    prototype__proto.monthsShort = localeMonthsShort;
    prototype__proto._monthsShort = defaultLocaleMonthsShort;
    prototype__proto.monthsParse = localeMonthsParse;

    // Week
    prototype__proto.week = localeWeek;
    prototype__proto._week = defaultLocaleWeek;
    prototype__proto.firstDayOfYear = localeFirstDayOfYear;
    prototype__proto.firstDayOfWeek = localeFirstDayOfWeek;

    // Day of Week
    prototype__proto.weekdays = localeWeekdays;
    prototype__proto._weekdays = defaultLocaleWeekdays;
    prototype__proto.weekdaysMin = localeWeekdaysMin;
    prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin;
    prototype__proto.weekdaysShort = localeWeekdaysShort;
    prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort;
    prototype__proto.weekdaysParse = localeWeekdaysParse;

    // Hours
    prototype__proto.isPM = localeIsPM;
    prototype__proto._meridiemParse = defaultLocaleMeridiemParse;
    prototype__proto.meridiem = localeMeridiem;

    function lists__get(format, index, field, setter) {
        var locale = locale_locales__getLocale();
        var utc = create_utc__createUTC().set(setter, index);
        return locale[field](utc, format);
    }

    function list(format, index, field, count, setter) {
        if (typeof format === 'number') {
            index = format;
            format = undefined;
        }

        format = format || '';

        if (index != null) {
            return lists__get(format, index, field, setter);
        }

        var i;
        var out = [];
        for (i = 0; i < count; i++) {
            out[i] = lists__get(format, i, field, setter);
        }
        return out;
    }

    function lists__listMonths(format, index) {
        return list(format, index, 'months', 12, 'month');
    }

    function lists__listMonthsShort(format, index) {
        return list(format, index, 'monthsShort', 12, 'month');
    }

    function lists__listWeekdays(format, index) {
        return list(format, index, 'weekdays', 7, 'day');
    }

    function lists__listWeekdaysShort(format, index) {
        return list(format, index, 'weekdaysShort', 7, 'day');
    }

    function lists__listWeekdaysMin(format, index) {
        return list(format, index, 'weekdaysMin', 7, 'day');
    }

    locale_locales__getSetGlobalLocale('en', {
        ordinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (toInt(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    // Side effect imports
    utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale);
    utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale);

    var mathAbs = Math.abs;

    function duration_abs__abs() {
        var data = this._data;

        this._milliseconds = mathAbs(this._milliseconds);
        this._days = mathAbs(this._days);
        this._months = mathAbs(this._months);

        data.milliseconds = mathAbs(data.milliseconds);
        data.seconds = mathAbs(data.seconds);
        data.minutes = mathAbs(data.minutes);
        data.hours = mathAbs(data.hours);
        data.months = mathAbs(data.months);
        data.years = mathAbs(data.years);

        return this;
    }

    function duration_add_subtract__addSubtract(duration, input, value, direction) {
        var other = create__createDuration(input, value);

        duration._milliseconds += direction * other._milliseconds;
        duration._days += direction * other._days;
        duration._months += direction * other._months;

        return duration._bubble();
    }

    // supports only 2.0-style add(1, 's') or add(duration)
    function duration_add_subtract__add(input, value) {
        return duration_add_subtract__addSubtract(this, input, value, 1);
    }

    // supports only 2.0-style subtract(1, 's') or subtract(duration)
    function duration_add_subtract__subtract(input, value) {
        return duration_add_subtract__addSubtract(this, input, value, -1);
    }

    function absCeil(number) {
        if (number < 0) {
            return Math.floor(number);
        } else {
            return Math.ceil(number);
        }
    }

    function bubble() {
        var milliseconds = this._milliseconds;
        var days = this._days;
        var months = this._months;
        var data = this._data;
        var seconds, minutes, hours, years, monthsFromDays;

        // if we have a mix of positive and negative values, bubble down first
        // check: https://github.com/moment/moment/issues/2166
        if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
                (milliseconds <= 0 && days <= 0 && months <= 0))) {
            milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
            days = 0;
            months = 0;
        }

        // The following code bubbles up values, see the tests for
        // examples of what that means.
        data.milliseconds = milliseconds % 1000;

        seconds = absFloor(milliseconds / 1000);
        data.seconds = seconds % 60;

        minutes = absFloor(seconds / 60);
        data.minutes = minutes % 60;

        hours = absFloor(minutes / 60);
        data.hours = hours % 24;

        days += absFloor(hours / 24);

        // convert days to months
        monthsFromDays = absFloor(daysToMonths(days));
        months += monthsFromDays;
        days -= absCeil(monthsToDays(monthsFromDays));

        // 12 months -> 1 year
        years = absFloor(months / 12);
        months %= 12;

        data.days = days;
        data.months = months;
        data.years = years;

        return this;
    }

    function daysToMonths(days) {
        // 400 years have 146097 days (taking into account leap year rules)
        // 400 years have 12 months === 4800
        return days * 4800 / 146097;
    }

    function monthsToDays(months) {
        // the reverse of daysToMonths
        return months * 146097 / 4800;
    }

    function as(units) {
        var days;
        var months;
        var milliseconds = this._milliseconds;

        units = normalizeUnits(units);

        if (units === 'month' || units === 'year') {
            days = this._days + milliseconds / 864e5;
            months = this._months + daysToMonths(days);
            return units === 'month' ? months : months / 12;
        } else {
            // handle milliseconds separately because of floating point math errors (issue #1867)
            days = this._days + Math.round(monthsToDays(this._months));
            switch (units) {
                case 'week': return days / 7 + milliseconds / 6048e5;
                case 'day': return days + milliseconds / 864e5;
                case 'hour': return days * 24 + milliseconds / 36e5;
                case 'minute': return days * 1440 + milliseconds / 6e4;
                case 'second': return days * 86400 + milliseconds / 1000;
                    // Math.floor prevents floating point math errors here
                case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
                default: throw new Error('Unknown unit ' + units);
            }
        }
    }

    // TODO: Use this.as('ms')?
    function duration_as__valueOf() {
        return (
            this._milliseconds +
            this._days * 864e5 +
            (this._months % 12) * 2592e6 +
            toInt(this._months / 12) * 31536e6
        );
    }

    function makeAs(alias) {
        return function () {
            return this.as(alias);
        };
    }

    var asMilliseconds = makeAs('ms');
    var asSeconds = makeAs('s');
    var asMinutes = makeAs('m');
    var asHours = makeAs('h');
    var asDays = makeAs('d');
    var asWeeks = makeAs('w');
    var asMonths = makeAs('M');
    var asYears = makeAs('y');

    function duration_get__get(units) {
        units = normalizeUnits(units);
        return this[units + 's']();
    }

    function makeGetter(name) {
        return function () {
            return this._data[name];
        };
    }

    var milliseconds = makeGetter('milliseconds');
    var seconds = makeGetter('seconds');
    var minutes = makeGetter('minutes');
    var hours = makeGetter('hours');
    var days = makeGetter('days');
    var duration_get__months = makeGetter('months');
    var years = makeGetter('years');

    function weeks() {
        return absFloor(this.days() / 7);
    }

    var round = Math.round;
    var thresholds = {
        s: 45,  // seconds to minute
        m: 45,  // minutes to hour
        h: 22,  // hours to day
        d: 26,  // days to month
        M: 11   // months to year
    };

    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
        return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }

    function duration_humanize__relativeTime(posNegDuration, withoutSuffix, locale) {
        var duration = create__createDuration(posNegDuration).abs();
        var seconds = round(duration.as('s'));
        var minutes = round(duration.as('m'));
        var hours = round(duration.as('h'));
        var days = round(duration.as('d'));
        var months = round(duration.as('M'));
        var years = round(duration.as('y'));

        var a = seconds < thresholds.s && ['s', seconds] ||
                minutes === 1 && ['m'] ||
                minutes < thresholds.m && ['mm', minutes] ||
                hours === 1 && ['h'] ||
                hours < thresholds.h && ['hh', hours] ||
                days === 1 && ['d'] ||
                days < thresholds.d && ['dd', days] ||
                months === 1 && ['M'] ||
                months < thresholds.M && ['MM', months] ||
                years === 1 && ['y'] || ['yy', years];

        a[2] = withoutSuffix;
        a[3] = +posNegDuration > 0;
        a[4] = locale;
        return substituteTimeAgo.apply(null, a);
    }

    // This function allows you to set a threshold for relative time strings
    function duration_humanize__getSetRelativeTimeThreshold(threshold, limit) {
        if (thresholds[threshold] === undefined) {
            return false;
        }
        if (limit === undefined) {
            return thresholds[threshold];
        }
        thresholds[threshold] = limit;
        return true;
    }

    function humanize(withSuffix) {
        var locale = this.localeData();
        var output = duration_humanize__relativeTime(this, !withSuffix, locale);

        if (withSuffix) {
            output = locale.pastFuture(+this, output);
        }

        return locale.postformat(output);
    }

    var iso_string__abs = Math.abs;

    function iso_string__toISOString() {
        // for ISO strings we do not use the normal bubbling rules:
        //  * milliseconds bubble up until they become hours
        //  * days do not bubble at all
        //  * months bubble up until they become years
        // This is because there is no context-free conversion between hours and days
        // (think of clock changes)
        // and also not between days and months (28-31 days per month)
        var seconds = iso_string__abs(this._milliseconds) / 1000;
        var days = iso_string__abs(this._days);
        var months = iso_string__abs(this._months);
        var minutes, hours, years;

        // 3600 seconds -> 60 minutes -> 1 hour
        minutes = absFloor(seconds / 60);
        hours = absFloor(minutes / 60);
        seconds %= 60;
        minutes %= 60;

        // 12 months -> 1 year
        years = absFloor(months / 12);
        months %= 12;


        // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
        var Y = years;
        var M = months;
        var D = days;
        var h = hours;
        var m = minutes;
        var s = seconds;
        var total = this.asSeconds();

        if (!total) {
            // this is the same as C#'s (Noda) and python (isodate)...
            // but not other JS (goog.date)
            return 'P0D';
        }

        return (total < 0 ? '-' : '') +
            'P' +
            (Y ? Y + 'Y' : '') +
            (M ? M + 'M' : '') +
            (D ? D + 'D' : '') +
            ((h || m || s) ? 'T' : '') +
            (h ? h + 'H' : '') +
            (m ? m + 'M' : '') +
            (s ? s + 'S' : '');
    }

    var duration_prototype__proto = Duration.prototype;

    duration_prototype__proto.abs = duration_abs__abs;
    duration_prototype__proto.add = duration_add_subtract__add;
    duration_prototype__proto.subtract = duration_add_subtract__subtract;
    duration_prototype__proto.as = as;
    duration_prototype__proto.asMilliseconds = asMilliseconds;
    duration_prototype__proto.asSeconds = asSeconds;
    duration_prototype__proto.asMinutes = asMinutes;
    duration_prototype__proto.asHours = asHours;
    duration_prototype__proto.asDays = asDays;
    duration_prototype__proto.asWeeks = asWeeks;
    duration_prototype__proto.asMonths = asMonths;
    duration_prototype__proto.asYears = asYears;
    duration_prototype__proto.valueOf = duration_as__valueOf;
    duration_prototype__proto._bubble = bubble;
    duration_prototype__proto.get = duration_get__get;
    duration_prototype__proto.milliseconds = milliseconds;
    duration_prototype__proto.seconds = seconds;
    duration_prototype__proto.minutes = minutes;
    duration_prototype__proto.hours = hours;
    duration_prototype__proto.days = days;
    duration_prototype__proto.weeks = weeks;
    duration_prototype__proto.months = duration_get__months;
    duration_prototype__proto.years = years;
    duration_prototype__proto.humanize = humanize;
    duration_prototype__proto.toISOString = iso_string__toISOString;
    duration_prototype__proto.toString = iso_string__toISOString;
    duration_prototype__proto.toJSON = iso_string__toISOString;
    duration_prototype__proto.locale = locale;
    duration_prototype__proto.localeData = localeData;

    // Deprecations
    duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString);
    duration_prototype__proto.lang = lang;

    // Side effect imports

    addFormatToken('X', 0, 0, 'unix');
    addFormatToken('x', 0, 0, 'valueOf');

    // PARSING

    addRegexToken('x', matchSigned);
    addRegexToken('X', matchTimestamp);
    addParseToken('X', function (input, array, config) {
        config._d = new Date(parseFloat(input, 10) * 1000);
    });
    addParseToken('x', function (input, array, config) {
        config._d = new Date(toInt(input));
    });

    // Side effect imports

    ;

    //! moment.js
    //! version : 2.10.6
    //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
    //! license : MIT
    //! momentjs.com

    utils_hooks__hooks.version = '2.10.6';

    setHookCallback(local__createLocal);

    utils_hooks__hooks.fn = momentPrototype;
    utils_hooks__hooks.min = min;
    utils_hooks__hooks.max = max;
    utils_hooks__hooks.utc = create_utc__createUTC;
    utils_hooks__hooks.unix = moment_moment__createUnix;
    utils_hooks__hooks.months = lists__listMonths;
    utils_hooks__hooks.isDate = isDate;
    utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale;
    utils_hooks__hooks.invalid = valid__createInvalid;
    utils_hooks__hooks.duration = create__createDuration;
    utils_hooks__hooks.isMoment = isMoment;
    utils_hooks__hooks.weekdays = lists__listWeekdays;
    utils_hooks__hooks.parseZone = moment_moment__createInZone;
    utils_hooks__hooks.localeData = locale_locales__getLocale;
    utils_hooks__hooks.isDuration = isDuration;
    utils_hooks__hooks.monthsShort = lists__listMonthsShort;
    utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin;
    utils_hooks__hooks.defineLocale = defineLocale;
    utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort;
    utils_hooks__hooks.normalizeUnits = normalizeUnits;
    utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold;

    var _moment__default = utils_hooks__hooks;

    //! moment.js locale configuration
    //! locale : afrikaans (af)
    //! author : Werner Mollentze : https://github.com/wernerm

    var af = _moment__default.defineLocale('af', {
        months: 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'),
        weekdays: 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'),
        weekdaysShort: 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'),
        weekdaysMin: 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'),
        meridiemParse: /vm|nm/i,
        isPM: function (input) {
            return /^nm$/i.test(input);
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 12) {
                return isLower ? 'vm' : 'VM';
            } else {
                return isLower ? 'nm' : 'NM';
            }
        },
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Vandag om] LT',
            nextDay: '[Môre om] LT',
            nextWeek: 'dddd [om] LT',
            lastDay: '[Gister om] LT',
            lastWeek: '[Laas] dddd [om] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'oor %s',
            past: '%s gelede',
            s: '\'n paar sekondes',
            m: '\'n minuut',
            mm: '%d minute',
            h: '\'n uur',
            hh: '%d ure',
            d: '\'n dag',
            dd: '%d dae',
            M: '\'n maand',
            MM: '%d maande',
            y: '\'n jaar',
            yy: '%d jaar'
        },
        ordinalParse: /\d{1,2}(ste|de)/,
        ordinal: function (number) {
            return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); // Thanks to Joris Röling : https://github.com/jjupiter
        },
        week: {
            dow: 1, // Maandag is die eerste dag van die week.
            doy: 4  // Die week wat die 4de Januarie bevat is die eerste week van die jaar.
        }
    });

    //! moment.js locale configuration
    //! locale : Moroccan Arabic (ar-ma)
    //! author : ElFadili Yassine : https://github.com/ElFadiliY
    //! author : Abdel Said : https://github.com/abdelsaid

    var ar_ma = _moment__default.defineLocale('ar-ma', {
        months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
        monthsShort: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
        weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Arabic Saudi Arabia (ar-sa)
    //! author : Suhail Alkowaileet : https://github.com/xsoh

    var ar_sa__symbolMap = {
        '1': '١',
        '2': '٢',
        '3': '٣',
        '4': '٤',
        '5': '٥',
        '6': '٦',
        '7': '٧',
        '8': '٨',
        '9': '٩',
        '0': '٠'
    }, ar_sa__numberMap = {
        '١': '1',
        '٢': '2',
        '٣': '3',
        '٤': '4',
        '٥': '5',
        '٦': '6',
        '٧': '7',
        '٨': '8',
        '٩': '9',
        '٠': '0'
    };

    var ar_sa = _moment__default.defineLocale('ar-sa', {
        months: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        monthsShort: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        meridiemParse: /ص|م/,
        isPM: function (input) {
            return 'م' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ص';
            } else {
                return 'م';
            }
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        preparse: function (string) {
            return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
                return ar_sa__numberMap[match];
            }).replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return ar_sa__symbolMap[match];
            }).replace(/,/g, '،');
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale  : Tunisian Arabic (ar-tn)

    var ar_tn = _moment__default.defineLocale('ar-tn', {
        months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! Locale: Arabic (ar)
    //! Author: Abdel Said: https://github.com/abdelsaid
    //! Changes in months, weekdays: Ahmed Elkhatib
    //! Native plural forms: forabi https://github.com/forabi

    var ar__symbolMap = {
        '1': '١',
        '2': '٢',
        '3': '٣',
        '4': '٤',
        '5': '٥',
        '6': '٦',
        '7': '٧',
        '8': '٨',
        '9': '٩',
        '0': '٠'
    }, ar__numberMap = {
        '١': '1',
        '٢': '2',
        '٣': '3',
        '٤': '4',
        '٥': '5',
        '٦': '6',
        '٧': '7',
        '٨': '8',
        '٩': '9',
        '٠': '0'
    }, pluralForm = function (n) {
        return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5;
    }, plurals = {
        s: ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'],
        m: ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'],
        h: ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'],
        d: ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'],
        M: ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'],
        y: ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام']
    }, pluralize = function (u) {
        return function (number, withoutSuffix, string, isFuture) {
            var f = pluralForm(number),
                str = plurals[u][pluralForm(number)];
            if (f === 2) {
                str = str[withoutSuffix ? 0 : 1];
            }
            return str.replace(/%d/i, number);
        };
    }, ar__months = [
        'كانون الثاني يناير',
        'شباط فبراير',
        'آذار مارس',
        'نيسان أبريل',
        'أيار مايو',
        'حزيران يونيو',
        'تموز يوليو',
        'آب أغسطس',
        'أيلول سبتمبر',
        'تشرين الأول أكتوبر',
        'تشرين الثاني نوفمبر',
        'كانون الأول ديسمبر'
    ];

    var ar = _moment__default.defineLocale('ar', {
        months: ar__months,
        monthsShort: ar__months,
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'D/\u200FM/\u200FYYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        meridiemParse: /ص|م/,
        isPM: function (input) {
            return 'م' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ص';
            } else {
                return 'م';
            }
        },
        calendar: {
            sameDay: '[اليوم عند الساعة] LT',
            nextDay: '[غدًا عند الساعة] LT',
            nextWeek: 'dddd [عند الساعة] LT',
            lastDay: '[أمس عند الساعة] LT',
            lastWeek: 'dddd [عند الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'بعد %s',
            past: 'منذ %s',
            s: pluralize('s'),
            m: pluralize('m'),
            mm: pluralize('m'),
            h: pluralize('h'),
            hh: pluralize('h'),
            d: pluralize('d'),
            dd: pluralize('d'),
            M: pluralize('M'),
            MM: pluralize('M'),
            y: pluralize('y'),
            yy: pluralize('y')
        },
        preparse: function (string) {
            return string.replace(/\u200f/g, '').replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
                return ar__numberMap[match];
            }).replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return ar__symbolMap[match];
            }).replace(/,/g, '،');
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : azerbaijani (az)
    //! author : topchiyev : https://github.com/topchiyev

    var az__suffixes = {
        1: '-inci',
        5: '-inci',
        8: '-inci',
        70: '-inci',
        80: '-inci',
        2: '-nci',
        7: '-nci',
        20: '-nci',
        50: '-nci',
        3: '-üncü',
        4: '-üncü',
        100: '-üncü',
        6: '-ncı',
        9: '-uncu',
        10: '-uncu',
        30: '-uncu',
        60: '-ıncı',
        90: '-ıncı'
    };

    var az = _moment__default.defineLocale('az', {
        months: 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'),
        monthsShort: 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'),
        weekdays: 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'),
        weekdaysShort: 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'),
        weekdaysMin: 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[bugün saat] LT',
            nextDay: '[sabah saat] LT',
            nextWeek: '[gələn həftə] dddd [saat] LT',
            lastDay: '[dünən] LT',
            lastWeek: '[keçən həftə] dddd [saat] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s sonra',
            past: '%s əvvəl',
            s: 'birneçə saniyyə',
            m: 'bir dəqiqə',
            mm: '%d dəqiqə',
            h: 'bir saat',
            hh: '%d saat',
            d: 'bir gün',
            dd: '%d gün',
            M: 'bir ay',
            MM: '%d ay',
            y: 'bir il',
            yy: '%d il'
        },
        meridiemParse: /gecə|səhər|gündüz|axşam/,
        isPM: function (input) {
            return /^(gündüz|axşam)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'gecə';
            } else if (hour < 12) {
                return 'səhər';
            } else if (hour < 17) {
                return 'gündüz';
            } else {
                return 'axşam';
            }
        },
        ordinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,
        ordinal: function (number) {
            if (number === 0) {  // special case for zero
                return number + '-ıncı';
            }
            var a = number % 10,
                b = number % 100 - a,
                c = number >= 100 ? 100 : null;
            return number + (az__suffixes[a] || az__suffixes[b] || az__suffixes[c]);
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : belarusian (be)
    //! author : Dmitry Demidov : https://github.com/demidov91
    //! author: Praleska: http://praleska.pro/
    //! Author : Menelion Elensúle : https://github.com/Oire

    function be__plural(word, num) {
        var forms = word.split('_');
        return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
    }
    function be__relativeTimeWithPlural(number, withoutSuffix, key) {
        var format = {
            'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін',
            'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін',
            'dd': 'дзень_дні_дзён',
            'MM': 'месяц_месяцы_месяцаў',
            'yy': 'год_гады_гадоў'
        };
        if (key === 'm') {
            return withoutSuffix ? 'хвіліна' : 'хвіліну';
        }
        else if (key === 'h') {
            return withoutSuffix ? 'гадзіна' : 'гадзіну';
        }
        else {
            return number + ' ' + be__plural(format[key], +number);
        }
    }
    function be__monthsCaseReplace(m, format) {
        var months = {
            'nominative': 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_'),
            'accusative': 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_')
        },
        nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
            'accusative' :
            'nominative';
        return months[nounCase][m.month()];
    }
    function be__weekdaysCaseReplace(m, format) {
        var weekdays = {
            'nominative': 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'),
            'accusative': 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_')
        },
        nounCase = (/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/).test(format) ?
            'accusative' :
            'nominative';
        return weekdays[nounCase][m.day()];
    }

    var be = _moment__default.defineLocale('be', {
        months: be__monthsCaseReplace,
        monthsShort: 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'),
        weekdays: be__weekdaysCaseReplace,
        weekdaysShort: 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
        weekdaysMin: 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY г.',
            LLL: 'D MMMM YYYY г., HH:mm',
            LLLL: 'dddd, D MMMM YYYY г., HH:mm'
        },
        calendar: {
            sameDay: '[Сёння ў] LT',
            nextDay: '[Заўтра ў] LT',
            lastDay: '[Учора ў] LT',
            nextWeek: function () {
                return '[У] dddd [ў] LT';
            },
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 5:
                    case 6:
                        return '[У мінулую] dddd [ў] LT';
                    case 1:
                    case 2:
                    case 4:
                        return '[У мінулы] dddd [ў] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'праз %s',
            past: '%s таму',
            s: 'некалькі секунд',
            m: be__relativeTimeWithPlural,
            mm: be__relativeTimeWithPlural,
            h: be__relativeTimeWithPlural,
            hh: be__relativeTimeWithPlural,
            d: 'дзень',
            dd: be__relativeTimeWithPlural,
            M: 'месяц',
            MM: be__relativeTimeWithPlural,
            y: 'год',
            yy: be__relativeTimeWithPlural
        },
        meridiemParse: /ночы|раніцы|дня|вечара/,
        isPM: function (input) {
            return /^(дня|вечара)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ночы';
            } else if (hour < 12) {
                return 'раніцы';
            } else if (hour < 17) {
                return 'дня';
            } else {
                return 'вечара';
            }
        },
        ordinalParse: /\d{1,2}-(і|ы|га)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'M':
                case 'd':
                case 'DDD':
                case 'w':
                case 'W':
                    return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы';
                case 'D':
                    return number + '-га';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : bulgarian (bg)
    //! author : Krasen Borisov : https://github.com/kraz

    var bg = _moment__default.defineLocale('bg', {
        months: 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'),
        monthsShort: 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'),
        weekdays: 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'),
        weekdaysShort: 'нед_пон_вто_сря_чет_пет_съб'.split('_'),
        weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'D.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd, D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[Днес в] LT',
            nextDay: '[Утре в] LT',
            nextWeek: 'dddd [в] LT',
            lastDay: '[Вчера в] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 6:
                        return '[В изминалата] dddd [в] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[В изминалия] dddd [в] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'след %s',
            past: 'преди %s',
            s: 'няколко секунди',
            m: 'минута',
            mm: '%d минути',
            h: 'час',
            hh: '%d часа',
            d: 'ден',
            dd: '%d дни',
            M: 'месец',
            MM: '%d месеца',
            y: 'година',
            yy: '%d години'
        },
        ordinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/,
        ordinal: function (number) {
            var lastDigit = number % 10,
                last2Digits = number % 100;
            if (number === 0) {
                return number + '-ев';
            } else if (last2Digits === 0) {
                return number + '-ен';
            } else if (last2Digits > 10 && last2Digits < 20) {
                return number + '-ти';
            } else if (lastDigit === 1) {
                return number + '-ви';
            } else if (lastDigit === 2) {
                return number + '-ри';
            } else if (lastDigit === 7 || lastDigit === 8) {
                return number + '-ми';
            } else {
                return number + '-ти';
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Bengali (bn)
    //! author : Kaushik Gandhi : https://github.com/kaushikgandhi

    var bn__symbolMap = {
        '1': '১',
        '2': '২',
        '3': '৩',
        '4': '৪',
        '5': '৫',
        '6': '৬',
        '7': '৭',
        '8': '৮',
        '9': '৯',
        '0': '০'
    },
    bn__numberMap = {
        '১': '1',
        '২': '2',
        '৩': '3',
        '৪': '4',
        '৫': '5',
        '৬': '6',
        '৭': '7',
        '৮': '8',
        '৯': '9',
        '০': '0'
    };

    var bn = _moment__default.defineLocale('bn', {
        months: 'জানুয়ারী_ফেবুয়ারী_মার্চ_এপ্রিল_মে_জুন_জুলাই_অগাস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'),
        monthsShort: 'জানু_ফেব_মার্চ_এপর_মে_জুন_জুল_অগ_সেপ্ট_অক্টো_নভ_ডিসেম্'.split('_'),
        weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পত্তিবার_শুক্রুবার_শনিবার'.split('_'),
        weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পত্তি_শুক্রু_শনি'.split('_'),
        weekdaysMin: 'রব_সম_মঙ্গ_বু_ব্রিহ_শু_শনি'.split('_'),
        longDateFormat: {
            LT: 'A h:mm সময়',
            LTS: 'A h:mm:ss সময়',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm সময়',
            LLLL: 'dddd, D MMMM YYYY, A h:mm সময়'
        },
        calendar: {
            sameDay: '[আজ] LT',
            nextDay: '[আগামীকাল] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[গতকাল] LT',
            lastWeek: '[গত] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s পরে',
            past: '%s আগে',
            s: 'কএক সেকেন্ড',
            m: 'এক মিনিট',
            mm: '%d মিনিট',
            h: 'এক ঘন্টা',
            hh: '%d ঘন্টা',
            d: 'এক দিন',
            dd: '%d দিন',
            M: 'এক মাস',
            MM: '%d মাস',
            y: 'এক বছর',
            yy: '%d বছর'
        },
        preparse: function (string) {
            return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) {
                return bn__numberMap[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return bn__symbolMap[match];
            });
        },
        meridiemParse: /রাত|সকাল|দুপুর|বিকেল|রাত/,
        isPM: function (input) {
            return /^(দুপুর|বিকেল|রাত)$/.test(input);
        },
        //Bengali is a vast language its spoken
        //in different forms in various parts of the world.
        //I have just generalized with most common one used
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'রাত';
            } else if (hour < 10) {
                return 'সকাল';
            } else if (hour < 17) {
                return 'দুপুর';
            } else if (hour < 20) {
                return 'বিকেল';
            } else {
                return 'রাত';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : tibetan (bo)
    //! author : Thupten N. Chakrishar : https://github.com/vajradog

    var bo__symbolMap = {
        '1': '༡',
        '2': '༢',
        '3': '༣',
        '4': '༤',
        '5': '༥',
        '6': '༦',
        '7': '༧',
        '8': '༨',
        '9': '༩',
        '0': '༠'
    },
    bo__numberMap = {
        '༡': '1',
        '༢': '2',
        '༣': '3',
        '༤': '4',
        '༥': '5',
        '༦': '6',
        '༧': '7',
        '༨': '8',
        '༩': '9',
        '༠': '0'
    };

    var bo = _moment__default.defineLocale('bo', {
        months: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
        monthsShort: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
        weekdays: 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'),
        weekdaysShort: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'),
        weekdaysMin: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'),
        longDateFormat: {
            LT: 'A h:mm',
            LTS: 'A h:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm',
            LLLL: 'dddd, D MMMM YYYY, A h:mm'
        },
        calendar: {
            sameDay: '[དི་རིང] LT',
            nextDay: '[སང་ཉིན] LT',
            nextWeek: '[བདུན་ཕྲག་རྗེས་མ], LT',
            lastDay: '[ཁ་སང] LT',
            lastWeek: '[བདུན་ཕྲག་མཐའ་མ] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s ལ་',
            past: '%s སྔན་ལ',
            s: 'ལམ་སང',
            m: 'སྐར་མ་གཅིག',
            mm: '%d སྐར་མ',
            h: 'ཆུ་ཚོད་གཅིག',
            hh: '%d ཆུ་ཚོད',
            d: 'ཉིན་གཅིག',
            dd: '%d ཉིན་',
            M: 'ཟླ་བ་གཅིག',
            MM: '%d ཟླ་བ',
            y: 'ལོ་གཅིག',
            yy: '%d ལོ'
        },
        preparse: function (string) {
            return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) {
                return bo__numberMap[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return bo__symbolMap[match];
            });
        },
        meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,
        isPM: function (input) {
            return /^(ཉིན་གུང|དགོང་དག|མཚན་མོ)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'མཚན་མོ';
            } else if (hour < 10) {
                return 'ཞོགས་ཀས';
            } else if (hour < 17) {
                return 'ཉིན་གུང';
            } else if (hour < 20) {
                return 'དགོང་དག';
            } else {
                return 'མཚན་མོ';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : breton (br)
    //! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou

    function relativeTimeWithMutation(number, withoutSuffix, key) {
        var format = {
            'mm': 'munutenn',
            'MM': 'miz',
            'dd': 'devezh'
        };
        return number + ' ' + mutation(format[key], number);
    }
    function specialMutationForYears(number) {
        switch (lastNumber(number)) {
            case 1:
            case 3:
            case 4:
            case 5:
            case 9:
                return number + ' bloaz';
            default:
                return number + ' vloaz';
        }
    }
    function lastNumber(number) {
        if (number > 9) {
            return lastNumber(number % 10);
        }
        return number;
    }
    function mutation(text, number) {
        if (number === 2) {
            return softMutation(text);
        }
        return text;
    }
    function softMutation(text) {
        var mutationTable = {
            'm': 'v',
            'b': 'v',
            'd': 'z'
        };
        if (mutationTable[text.charAt(0)] === undefined) {
            return text;
        }
        return mutationTable[text.charAt(0)] + text.substring(1);
    }

    var br = _moment__default.defineLocale('br', {
        months: 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'),
        monthsShort: 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'),
        weekdays: 'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'),
        weekdaysShort: 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'),
        weekdaysMin: 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'),
        longDateFormat: {
            LT: 'h[e]mm A',
            LTS: 'h[e]mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D [a viz] MMMM YYYY',
            LLL: 'D [a viz] MMMM YYYY h[e]mm A',
            LLLL: 'dddd, D [a viz] MMMM YYYY h[e]mm A'
        },
        calendar: {
            sameDay: '[Hiziv da] LT',
            nextDay: '[Warc\'hoazh da] LT',
            nextWeek: 'dddd [da] LT',
            lastDay: '[Dec\'h da] LT',
            lastWeek: 'dddd [paset da] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'a-benn %s',
            past: '%s \'zo',
            s: 'un nebeud segondennoù',
            m: 'ur vunutenn',
            mm: relativeTimeWithMutation,
            h: 'un eur',
            hh: '%d eur',
            d: 'un devezh',
            dd: relativeTimeWithMutation,
            M: 'ur miz',
            MM: relativeTimeWithMutation,
            y: 'ur bloaz',
            yy: specialMutationForYears
        },
        ordinalParse: /\d{1,2}(añ|vet)/,
        ordinal: function (number) {
            var output = (number === 1) ? 'añ' : 'vet';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : bosnian (bs)
    //! author : Nedim Cholich : https://github.com/frontyard
    //! based on (hr) translation by Bojan Marković

    function bs__translate(number, withoutSuffix, key) {
        var result = number + ' ';
        switch (key) {
            case 'm':
                return withoutSuffix ? 'jedna minuta' : 'jedne minute';
            case 'mm':
                if (number === 1) {
                    result += 'minuta';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'minute';
                } else {
                    result += 'minuta';
                }
                return result;
            case 'h':
                return withoutSuffix ? 'jedan sat' : 'jednog sata';
            case 'hh':
                if (number === 1) {
                    result += 'sat';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'sata';
                } else {
                    result += 'sati';
                }
                return result;
            case 'dd':
                if (number === 1) {
                    result += 'dan';
                } else {
                    result += 'dana';
                }
                return result;
            case 'MM':
                if (number === 1) {
                    result += 'mjesec';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'mjeseca';
                } else {
                    result += 'mjeseci';
                }
                return result;
            case 'yy':
                if (number === 1) {
                    result += 'godina';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'godine';
                } else {
                    result += 'godina';
                }
                return result;
        }
    }

    var bs = _moment__default.defineLocale('bs', {
        months: 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'),
        monthsShort: 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'),
        weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
        weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
        weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD. MM. YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sutra u] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedjelju] [u] LT';
                    case 3:
                        return '[u] [srijedu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[jučer u] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                        return '[prošlu] dddd [u] LT';
                    case 6:
                        return '[prošle] [subote] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[prošli] dddd [u] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'prije %s',
            s: 'par sekundi',
            m: bs__translate,
            mm: bs__translate,
            h: bs__translate,
            hh: bs__translate,
            d: 'dan',
            dd: bs__translate,
            M: 'mjesec',
            MM: bs__translate,
            y: 'godinu',
            yy: bs__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : catalan (ca)
    //! author : Juan G. Hurtado : https://github.com/juanghurtado

    var ca = _moment__default.defineLocale('ca', {
        months: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'),
        monthsShort: 'gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.'.split('_'),
        weekdays: 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'),
        weekdaysShort: 'dg._dl._dt._dc._dj._dv._ds.'.split('_'),
        weekdaysMin: 'Dg_Dl_Dt_Dc_Dj_Dv_Ds'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'LT:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: function () {
                return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            nextDay: function () {
                return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            lastDay: function () {
                return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            lastWeek: function () {
                return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'en %s',
            past: 'fa %s',
            s: 'uns segons',
            m: 'un minut',
            mm: '%d minuts',
            h: 'una hora',
            hh: '%d hores',
            d: 'un dia',
            dd: '%d dies',
            M: 'un mes',
            MM: '%d mesos',
            y: 'un any',
            yy: '%d anys'
        },
        ordinalParse: /\d{1,2}(r|n|t|è|a)/,
        ordinal: function (number, period) {
            var output = (number === 1) ? 'r' :
                (number === 2) ? 'n' :
                (number === 3) ? 'r' :
                (number === 4) ? 't' : 'è';
            if (period === 'w' || period === 'W') {
                output = 'a';
            }
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : czech (cs)
    //! author : petrbela : https://github.com/petrbela

    var cs__months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'),
        cs__monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_');
    function cs__plural(n) {
        return (n > 1) && (n < 5) && (~~(n / 10) !== 1);
    }
    function cs__translate(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':  // a few seconds / in a few seconds / a few seconds ago
                return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami';
            case 'm':  // a minute / in a minute / a minute ago
                return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou');
            case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
                if (withoutSuffix || isFuture) {
                    return result + (cs__plural(number) ? 'minuty' : 'minut');
                } else {
                    return result + 'minutami';
                }
                break;
            case 'h':  // an hour / in an hour / an hour ago
                return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
            case 'hh': // 9 hours / in 9 hours / 9 hours ago
                if (withoutSuffix || isFuture) {
                    return result + (cs__plural(number) ? 'hodiny' : 'hodin');
                } else {
                    return result + 'hodinami';
                }
                break;
            case 'd':  // a day / in a day / a day ago
                return (withoutSuffix || isFuture) ? 'den' : 'dnem';
            case 'dd': // 9 days / in 9 days / 9 days ago
                if (withoutSuffix || isFuture) {
                    return result + (cs__plural(number) ? 'dny' : 'dní');
                } else {
                    return result + 'dny';
                }
                break;
            case 'M':  // a month / in a month / a month ago
                return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem';
            case 'MM': // 9 months / in 9 months / 9 months ago
                if (withoutSuffix || isFuture) {
                    return result + (cs__plural(number) ? 'měsíce' : 'měsíců');
                } else {
                    return result + 'měsíci';
                }
                break;
            case 'y':  // a year / in a year / a year ago
                return (withoutSuffix || isFuture) ? 'rok' : 'rokem';
            case 'yy': // 9 years / in 9 years / 9 years ago
                if (withoutSuffix || isFuture) {
                    return result + (cs__plural(number) ? 'roky' : 'let');
                } else {
                    return result + 'lety';
                }
                break;
        }
    }

    var cs = _moment__default.defineLocale('cs', {
        months: cs__months,
        monthsShort: cs__monthsShort,
        monthsParse: (function (months, monthsShort) {
            var i, _monthsParse = [];
            for (i = 0; i < 12; i++) {
                // use custom parser to solve problem with July (červenec)
                _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i');
            }
            return _monthsParse;
        }(cs__months, cs__monthsShort)),
        weekdays: 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'),
        weekdaysShort: 'ne_po_út_st_čt_pá_so'.split('_'),
        weekdaysMin: 'ne_po_út_st_čt_pá_so'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[dnes v] LT',
            nextDay: '[zítra v] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[v neděli v] LT';
                    case 1:
                    case 2:
                        return '[v] dddd [v] LT';
                    case 3:
                        return '[ve středu v] LT';
                    case 4:
                        return '[ve čtvrtek v] LT';
                    case 5:
                        return '[v pátek v] LT';
                    case 6:
                        return '[v sobotu v] LT';
                }
            },
            lastDay: '[včera v] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[minulou neděli v] LT';
                    case 1:
                    case 2:
                        return '[minulé] dddd [v] LT';
                    case 3:
                        return '[minulou středu v] LT';
                    case 4:
                    case 5:
                        return '[minulý] dddd [v] LT';
                    case 6:
                        return '[minulou sobotu v] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'před %s',
            s: cs__translate,
            m: cs__translate,
            mm: cs__translate,
            h: cs__translate,
            hh: cs__translate,
            d: cs__translate,
            dd: cs__translate,
            M: cs__translate,
            MM: cs__translate,
            y: cs__translate,
            yy: cs__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : chuvash (cv)
    //! author : Anatoly Mironov : https://github.com/mirontoli

    var cv = _moment__default.defineLocale('cv', {
        months: 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'),
        monthsShort: 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'),
        weekdays: 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'),
        weekdaysShort: 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'),
        weekdaysMin: 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD-MM-YYYY',
            LL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]',
            LLL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm',
            LLLL: 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm'
        },
        calendar: {
            sameDay: '[Паян] LT [сехетре]',
            nextDay: '[Ыран] LT [сехетре]',
            lastDay: '[Ӗнер] LT [сехетре]',
            nextWeek: '[Ҫитес] dddd LT [сехетре]',
            lastWeek: '[Иртнӗ] dddd LT [сехетре]',
            sameElse: 'L'
        },
        relativeTime: {
            future: function (output) {
                var affix = /сехет$/i.exec(output) ? 'рен' : /ҫул$/i.exec(output) ? 'тан' : 'ран';
                return output + affix;
            },
            past: '%s каялла',
            s: 'пӗр-ик ҫеккунт',
            m: 'пӗр минут',
            mm: '%d минут',
            h: 'пӗр сехет',
            hh: '%d сехет',
            d: 'пӗр кун',
            dd: '%d кун',
            M: 'пӗр уйӑх',
            MM: '%d уйӑх',
            y: 'пӗр ҫул',
            yy: '%d ҫул'
        },
        ordinalParse: /\d{1,2}-мӗш/,
        ordinal: '%d-мӗш',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Welsh (cy)
    //! author : Robert Allen

    var cy = _moment__default.defineLocale('cy', {
        months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'),
        monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'),
        weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'),
        weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'),
        weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'),
        // time formats are the same as en-gb
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Heddiw am] LT',
            nextDay: '[Yfory am] LT',
            nextWeek: 'dddd [am] LT',
            lastDay: '[Ddoe am] LT',
            lastWeek: 'dddd [diwethaf am] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'mewn %s',
            past: '%s yn ôl',
            s: 'ychydig eiliadau',
            m: 'munud',
            mm: '%d munud',
            h: 'awr',
            hh: '%d awr',
            d: 'diwrnod',
            dd: '%d diwrnod',
            M: 'mis',
            MM: '%d mis',
            y: 'blwyddyn',
            yy: '%d flynedd'
        },
        ordinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,
        // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh
        ordinal: function (number) {
            var b = number,
                output = '',
                lookup = [
                    '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed
                    'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed
                ];
            if (b > 20) {
                if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) {
                    output = 'fed'; // not 30ain, 70ain or 90ain
                } else {
                    output = 'ain';
                }
            } else if (b > 0) {
                output = lookup[b];
            }
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : danish (da)
    //! author : Ulrik Nielsen : https://github.com/mrbase

    var da = _moment__default.defineLocale('da', {
        months: 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),
        weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),
        weekdaysShort: 'søn_man_tir_ons_tor_fre_lør'.split('_'),
        weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY HH:mm',
            LLLL: 'dddd [d.] D. MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[I dag kl.] LT',
            nextDay: '[I morgen kl.] LT',
            nextWeek: 'dddd [kl.] LT',
            lastDay: '[I går kl.] LT',
            lastWeek: '[sidste] dddd [kl] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: '%s siden',
            s: 'få sekunder',
            m: 'et minut',
            mm: '%d minutter',
            h: 'en time',
            hh: '%d timer',
            d: 'en dag',
            dd: '%d dage',
            M: 'en måned',
            MM: '%d måneder',
            y: 'et år',
            yy: '%d år'
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : austrian german (de-at)
    //! author : lluchs : https://github.com/lluchs
    //! author: Menelion Elensúle: https://github.com/Oire
    //! author : Martin Groller : https://github.com/MadMG

    function de_at__processRelativeTime(number, withoutSuffix, key, isFuture) {
        var format = {
            'm': ['eine Minute', 'einer Minute'],
            'h': ['eine Stunde', 'einer Stunde'],
            'd': ['ein Tag', 'einem Tag'],
            'dd': [number + ' Tage', number + ' Tagen'],
            'M': ['ein Monat', 'einem Monat'],
            'MM': [number + ' Monate', number + ' Monaten'],
            'y': ['ein Jahr', 'einem Jahr'],
            'yy': [number + ' Jahre', number + ' Jahren']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }

    var de_at = _moment__default.defineLocale('de-at', {
        months: 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
        monthsShort: 'Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
        weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
        weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
        weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY HH:mm',
            LLLL: 'dddd, D. MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Heute um] LT [Uhr]',
            sameElse: 'L',
            nextDay: '[Morgen um] LT [Uhr]',
            nextWeek: 'dddd [um] LT [Uhr]',
            lastDay: '[Gestern um] LT [Uhr]',
            lastWeek: '[letzten] dddd [um] LT [Uhr]'
        },
        relativeTime: {
            future: 'in %s',
            past: 'vor %s',
            s: 'ein paar Sekunden',
            m: de_at__processRelativeTime,
            mm: '%d Minuten',
            h: de_at__processRelativeTime,
            hh: '%d Stunden',
            d: de_at__processRelativeTime,
            dd: de_at__processRelativeTime,
            M: de_at__processRelativeTime,
            MM: de_at__processRelativeTime,
            y: de_at__processRelativeTime,
            yy: de_at__processRelativeTime
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : german (de)
    //! author : lluchs : https://github.com/lluchs
    //! author: Menelion Elensúle: https://github.com/Oire

    function de__processRelativeTime(number, withoutSuffix, key, isFuture) {
        var format = {
            'm': ['eine Minute', 'einer Minute'],
            'h': ['eine Stunde', 'einer Stunde'],
            'd': ['ein Tag', 'einem Tag'],
            'dd': [number + ' Tage', number + ' Tagen'],
            'M': ['ein Monat', 'einem Monat'],
            'MM': [number + ' Monate', number + ' Monaten'],
            'y': ['ein Jahr', 'einem Jahr'],
            'yy': [number + ' Jahre', number + ' Jahren']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }

    var de = _moment__default.defineLocale('de', {
        months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
        monthsShort: 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
        weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
        weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
        weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY HH:mm',
            LLLL: 'dddd, D. MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Heute um] LT [Uhr]',
            sameElse: 'L',
            nextDay: '[Morgen um] LT [Uhr]',
            nextWeek: 'dddd [um] LT [Uhr]',
            lastDay: '[Gestern um] LT [Uhr]',
            lastWeek: '[letzten] dddd [um] LT [Uhr]'
        },
        relativeTime: {
            future: 'in %s',
            past: 'vor %s',
            s: 'ein paar Sekunden',
            m: de__processRelativeTime,
            mm: '%d Minuten',
            h: de__processRelativeTime,
            hh: '%d Stunden',
            d: de__processRelativeTime,
            dd: de__processRelativeTime,
            M: de__processRelativeTime,
            MM: de__processRelativeTime,
            y: de__processRelativeTime,
            yy: de__processRelativeTime
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : modern greek (el)
    //! author : Aggelos Karalias : https://github.com/mehiel

    var el = _moment__default.defineLocale('el', {
        monthsNominativeEl: 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),
        monthsGenitiveEl: 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),
        months: function (momentToFormat, format) {
            if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
                return this._monthsGenitiveEl[momentToFormat.month()];
            } else {
                return this._monthsNominativeEl[momentToFormat.month()];
            }
        },
        monthsShort: 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),
        weekdays: 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),
        weekdaysShort: 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),
        weekdaysMin: 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'μμ' : 'ΜΜ';
            } else {
                return isLower ? 'πμ' : 'ΠΜ';
            }
        },
        isPM: function (input) {
            return ((input + '').toLowerCase()[0] === 'μ');
        },
        meridiemParse: /[ΠΜ]\.?Μ?\.?/i,
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendarEl: {
            sameDay: '[Σήμερα {}] LT',
            nextDay: '[Αύριο {}] LT',
            nextWeek: 'dddd [{}] LT',
            lastDay: '[Χθες {}] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 6:
                        return '[το προηγούμενο] dddd [{}] LT';
                    default:
                        return '[την προηγούμενη] dddd [{}] LT';
                }
            },
            sameElse: 'L'
        },
        calendar: function (key, mom) {
            var output = this._calendarEl[key],
                hours = mom && mom.hours();
            if (typeof output === 'function') {
                output = output.apply(mom);
            }
            return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις'));
        },
        relativeTime: {
            future: 'σε %s',
            past: '%s πριν',
            s: 'λίγα δευτερόλεπτα',
            m: 'ένα λεπτό',
            mm: '%d λεπτά',
            h: 'μία ώρα',
            hh: '%d ώρες',
            d: 'μία μέρα',
            dd: '%d μέρες',
            M: 'ένας μήνας',
            MM: '%d μήνες',
            y: 'ένας χρόνος',
            yy: '%d χρόνια'
        },
        ordinalParse: /\d{1,2}η/,
        ordinal: '%dη',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : australian english (en-au)

    var en_au = _moment__default.defineLocale('en-au', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'in %s',
            past: '%s ago',
            s: 'a few seconds',
            m: 'a minute',
            mm: '%d minutes',
            h: 'an hour',
            hh: '%d hours',
            d: 'a day',
            dd: '%d days',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        ordinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : canadian english (en-ca)
    //! author : Jonathan Abourbih : https://github.com/jonbca

    var en_ca = _moment__default.defineLocale('en-ca', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'YYYY-MM-DD',
            LL: 'D MMMM, YYYY',
            LLL: 'D MMMM, YYYY h:mm A',
            LLLL: 'dddd, D MMMM, YYYY h:mm A'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'in %s',
            past: '%s ago',
            s: 'a few seconds',
            m: 'a minute',
            mm: '%d minutes',
            h: 'an hour',
            hh: '%d hours',
            d: 'a day',
            dd: '%d days',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        ordinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    //! moment.js locale configuration
    //! locale : great britain english (en-gb)
    //! author : Chris Gedrim : https://github.com/chrisgedrim

    var en_gb = _moment__default.defineLocale('en-gb', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'in %s',
            past: '%s ago',
            s: 'a few seconds',
            m: 'a minute',
            mm: '%d minutes',
            h: 'an hour',
            hh: '%d hours',
            d: 'a day',
            dd: '%d days',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        ordinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : esperanto (eo)
    //! author : Colin Dean : https://github.com/colindean
    //! komento: Mi estas malcerta se mi korekte traktis akuzativojn en tiu traduko.
    //!          Se ne, bonvolu korekti kaj avizi min por ke mi povas lerni!

    var eo = _moment__default.defineLocale('eo', {
        months: 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'),
        weekdays: 'Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato'.split('_'),
        weekdaysShort: 'Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab'.split('_'),
        weekdaysMin: 'Di_Lu_Ma_Me_Ĵa_Ve_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'D[-an de] MMMM, YYYY',
            LLL: 'D[-an de] MMMM, YYYY HH:mm',
            LLLL: 'dddd, [la] D[-an de] MMMM, YYYY HH:mm'
        },
        meridiemParse: /[ap]\.t\.m/i,
        isPM: function (input) {
            return input.charAt(0).toLowerCase() === 'p';
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'p.t.m.' : 'P.T.M.';
            } else {
                return isLower ? 'a.t.m.' : 'A.T.M.';
            }
        },
        calendar: {
            sameDay: '[Hodiaŭ je] LT',
            nextDay: '[Morgaŭ je] LT',
            nextWeek: 'dddd [je] LT',
            lastDay: '[Hieraŭ je] LT',
            lastWeek: '[pasinta] dddd [je] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'je %s',
            past: 'antaŭ %s',
            s: 'sekundoj',
            m: 'minuto',
            mm: '%d minutoj',
            h: 'horo',
            hh: '%d horoj',
            d: 'tago',//ne 'diurno', ĉar estas uzita por proksimumo
            dd: '%d tagoj',
            M: 'monato',
            MM: '%d monatoj',
            y: 'jaro',
            yy: '%d jaroj'
        },
        ordinalParse: /\d{1,2}a/,
        ordinal: '%da',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : spanish (es)
    //! author : Julio Napurí : https://github.com/julionc

    var monthsShortDot = 'Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.'.split('_'),
        es__monthsShort = 'Ene_Feb_Mar_Abr_May_Jun_Jul_Ago_Sep_Oct_Nov_Dic'.split('_');

    var es = _moment__default.defineLocale('es', {
        months: 'Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre'.split('_'),
        monthsShort: function (m, format) {
            if (/-MMM-/.test(format)) {
                return es__monthsShort[m.month()];
            } else {
                return monthsShortDot[m.month()];
            }
        },
        weekdays: 'Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado'.split('_'),
        weekdaysShort: 'Dom._Lun._Mar._Mié._Jue._Vie._Sáb.'.split('_'),
        weekdaysMin: 'Do_Lu_Ma_Mi_Ju_Vi_Sá'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY H:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm'
        },
        calendar: {
            sameDay: function () {
                return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextDay: function () {
                return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastDay: function () {
                return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastWeek: function () {
                return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'en %s',
            past: 'hace %s',
            s: 'unos segundos',
            m: 'un minuto',
            mm: '%d minutos',
            h: 'una hora',
            hh: '%d horas',
            d: 'un día',
            dd: '%d días',
            M: 'un mes',
            MM: '%d meses',
            y: 'un año',
            yy: '%d años'
        },
        ordinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : estonian (et)
    //! author : Henry Kehlmann : https://github.com/madhenry
    //! improvements : Illimar Tambek : https://github.com/ragulka

    function et__processRelativeTime(number, withoutSuffix, key, isFuture) {
        var format = {
            's': ['mõne sekundi', 'mõni sekund', 'paar sekundit'],
            'm': ['ühe minuti', 'üks minut'],
            'mm': [number + ' minuti', number + ' minutit'],
            'h': ['ühe tunni', 'tund aega', 'üks tund'],
            'hh': [number + ' tunni', number + ' tundi'],
            'd': ['ühe päeva', 'üks päev'],
            'M': ['kuu aja', 'kuu aega', 'üks kuu'],
            'MM': [number + ' kuu', number + ' kuud'],
            'y': ['ühe aasta', 'aasta', 'üks aasta'],
            'yy': [number + ' aasta', number + ' aastat']
        };
        if (withoutSuffix) {
            return format[key][2] ? format[key][2] : format[key][1];
        }
        return isFuture ? format[key][0] : format[key][1];
    }

    var et = _moment__default.defineLocale('et', {
        months: 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'),
        monthsShort: 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'),
        weekdays: 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'),
        weekdaysShort: 'P_E_T_K_N_R_L'.split('_'),
        weekdaysMin: 'P_E_T_K_N_R_L'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[Täna,] LT',
            nextDay: '[Homme,] LT',
            nextWeek: '[Järgmine] dddd LT',
            lastDay: '[Eile,] LT',
            lastWeek: '[Eelmine] dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s pärast',
            past: '%s tagasi',
            s: et__processRelativeTime,
            m: et__processRelativeTime,
            mm: et__processRelativeTime,
            h: et__processRelativeTime,
            hh: et__processRelativeTime,
            d: et__processRelativeTime,
            dd: '%d päeva',
            M: et__processRelativeTime,
            MM: et__processRelativeTime,
            y: et__processRelativeTime,
            yy: et__processRelativeTime
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : euskara (eu)
    //! author : Eneko Illarramendi : https://github.com/eillarra

    var eu = _moment__default.defineLocale('eu', {
        months: 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'),
        monthsShort: 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'),
        weekdays: 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'),
        weekdaysShort: 'ig._al._ar._az._og._ol._lr.'.split('_'),
        weekdaysMin: 'ig_al_ar_az_og_ol_lr'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'YYYY[ko] MMMM[ren] D[a]',
            LLL: 'YYYY[ko] MMMM[ren] D[a] HH:mm',
            LLLL: 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm',
            l: 'YYYY-M-D',
            ll: 'YYYY[ko] MMM D[a]',
            lll: 'YYYY[ko] MMM D[a] HH:mm',
            llll: 'ddd, YYYY[ko] MMM D[a] HH:mm'
        },
        calendar: {
            sameDay: '[gaur] LT[etan]',
            nextDay: '[bihar] LT[etan]',
            nextWeek: 'dddd LT[etan]',
            lastDay: '[atzo] LT[etan]',
            lastWeek: '[aurreko] dddd LT[etan]',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s barru',
            past: 'duela %s',
            s: 'segundo batzuk',
            m: 'minutu bat',
            mm: '%d minutu',
            h: 'ordu bat',
            hh: '%d ordu',
            d: 'egun bat',
            dd: '%d egun',
            M: 'hilabete bat',
            MM: '%d hilabete',
            y: 'urte bat',
            yy: '%d urte'
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Persian (fa)
    //! author : Ebrahim Byagowi : https://github.com/ebraminio

    var fa__symbolMap = {
        '1': '۱',
        '2': '۲',
        '3': '۳',
        '4': '۴',
        '5': '۵',
        '6': '۶',
        '7': '۷',
        '8': '۸',
        '9': '۹',
        '0': '۰'
    }, fa__numberMap = {
        '۱': '1',
        '۲': '2',
        '۳': '3',
        '۴': '4',
        '۵': '5',
        '۶': '6',
        '۷': '7',
        '۸': '8',
        '۹': '9',
        '۰': '0'
    };

    var fa = _moment__default.defineLocale('fa', {
        months: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
        monthsShort: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
        weekdays: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
        weekdaysShort: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
        weekdaysMin: 'ی_د_س_چ_پ_ج_ش'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        meridiemParse: /قبل از ظهر|بعد از ظهر/,
        isPM: function (input) {
            return /بعد از ظهر/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'قبل از ظهر';
            } else {
                return 'بعد از ظهر';
            }
        },
        calendar: {
            sameDay: '[امروز ساعت] LT',
            nextDay: '[فردا ساعت] LT',
            nextWeek: 'dddd [ساعت] LT',
            lastDay: '[دیروز ساعت] LT',
            lastWeek: 'dddd [پیش] [ساعت] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'در %s',
            past: '%s پیش',
            s: 'چندین ثانیه',
            m: 'یک دقیقه',
            mm: '%d دقیقه',
            h: 'یک ساعت',
            hh: '%d ساعت',
            d: 'یک روز',
            dd: '%d روز',
            M: 'یک ماه',
            MM: '%d ماه',
            y: 'یک سال',
            yy: '%d سال'
        },
        preparse: function (string) {
            return string.replace(/[۰-۹]/g, function (match) {
                return fa__numberMap[match];
            }).replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return fa__symbolMap[match];
            }).replace(/,/g, '،');
        },
        ordinalParse: /\d{1,2}م/,
        ordinal: '%dم',
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12 // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : finnish (fi)
    //! author : Tarmo Aidantausta : https://github.com/bleadof

    var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '),
        numbersFuture = [
            'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden',
            numbersPast[7], numbersPast[8], numbersPast[9]
        ];
    function fi__translate(number, withoutSuffix, key, isFuture) {
        var result = '';
        switch (key) {
            case 's':
                return isFuture ? 'muutaman sekunnin' : 'muutama sekunti';
            case 'm':
                return isFuture ? 'minuutin' : 'minuutti';
            case 'mm':
                result = isFuture ? 'minuutin' : 'minuuttia';
                break;
            case 'h':
                return isFuture ? 'tunnin' : 'tunti';
            case 'hh':
                result = isFuture ? 'tunnin' : 'tuntia';
                break;
            case 'd':
                return isFuture ? 'päivän' : 'päivä';
            case 'dd':
                result = isFuture ? 'päivän' : 'päivää';
                break;
            case 'M':
                return isFuture ? 'kuukauden' : 'kuukausi';
            case 'MM':
                result = isFuture ? 'kuukauden' : 'kuukautta';
                break;
            case 'y':
                return isFuture ? 'vuoden' : 'vuosi';
            case 'yy':
                result = isFuture ? 'vuoden' : 'vuotta';
                break;
        }
        result = verbalNumber(number, isFuture) + ' ' + result;
        return result;
    }
    function verbalNumber(number, isFuture) {
        return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number;
    }

    var fi = _moment__default.defineLocale('fi', {
        months: 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'),
        monthsShort: 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'),
        weekdays: 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'),
        weekdaysShort: 'su_ma_ti_ke_to_pe_la'.split('_'),
        weekdaysMin: 'su_ma_ti_ke_to_pe_la'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD.MM.YYYY',
            LL: 'Do MMMM[ta] YYYY',
            LLL: 'Do MMMM[ta] YYYY, [klo] HH.mm',
            LLLL: 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm',
            l: 'D.M.YYYY',
            ll: 'Do MMM YYYY',
            lll: 'Do MMM YYYY, [klo] HH.mm',
            llll: 'ddd, Do MMM YYYY, [klo] HH.mm'
        },
        calendar: {
            sameDay: '[tänään] [klo] LT',
            nextDay: '[huomenna] [klo] LT',
            nextWeek: 'dddd [klo] LT',
            lastDay: '[eilen] [klo] LT',
            lastWeek: '[viime] dddd[na] [klo] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s päästä',
            past: '%s sitten',
            s: fi__translate,
            m: fi__translate,
            mm: fi__translate,
            h: fi__translate,
            hh: fi__translate,
            d: fi__translate,
            dd: fi__translate,
            M: fi__translate,
            MM: fi__translate,
            y: fi__translate,
            yy: fi__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : faroese (fo)
    //! author : Ragnar Johannesen : https://github.com/ragnar123

    var fo = _moment__default.defineLocale('fo', {
        months: 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
        monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),
        weekdays: 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'),
        weekdaysShort: 'sun_mán_týs_mik_hós_frí_ley'.split('_'),
        weekdaysMin: 'su_má_tý_mi_hó_fr_le'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D. MMMM, YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Í dag kl.] LT',
            nextDay: '[Í morgin kl.] LT',
            nextWeek: 'dddd [kl.] LT',
            lastDay: '[Í gjár kl.] LT',
            lastWeek: '[síðstu] dddd [kl] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'um %s',
            past: '%s síðani',
            s: 'fá sekund',
            m: 'ein minutt',
            mm: '%d minuttir',
            h: 'ein tími',
            hh: '%d tímar',
            d: 'ein dagur',
            dd: '%d dagar',
            M: 'ein mánaði',
            MM: '%d mánaðir',
            y: 'eitt ár',
            yy: '%d ár'
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : canadian french (fr-ca)
    //! author : Jonathan Abourbih : https://github.com/jonbca

    var fr_ca = _moment__default.defineLocale('fr-ca', {
        months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
        monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
        weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
        weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
        weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Aujourd\'hui à] LT',
            nextDay: '[Demain à] LT',
            nextWeek: 'dddd [à] LT',
            lastDay: '[Hier à] LT',
            lastWeek: 'dddd [dernier à] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dans %s',
            past: 'il y a %s',
            s: 'quelques secondes',
            m: 'une minute',
            mm: '%d minutes',
            h: 'une heure',
            hh: '%d heures',
            d: 'un jour',
            dd: '%d jours',
            M: 'un mois',
            MM: '%d mois',
            y: 'un an',
            yy: '%d ans'
        },
        ordinalParse: /\d{1,2}(er|e)/,
        ordinal: function (number) {
            return number + (number === 1 ? 'er' : 'e');
        }
    });

    //! moment.js locale configuration
    //! locale : french (fr)
    //! author : John Fischer : https://github.com/jfroffice

    var fr = _moment__default.defineLocale('fr', {
        months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
        monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
        weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
        weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
        weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Aujourd\'hui à] LT',
            nextDay: '[Demain à] LT',
            nextWeek: 'dddd [à] LT',
            lastDay: '[Hier à] LT',
            lastWeek: 'dddd [dernier à] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dans %s',
            past: 'il y a %s',
            s: 'quelques secondes',
            m: 'une minute',
            mm: '%d minutes',
            h: 'une heure',
            hh: '%d heures',
            d: 'un jour',
            dd: '%d jours',
            M: 'un mois',
            MM: '%d mois',
            y: 'un an',
            yy: '%d ans'
        },
        ordinalParse: /\d{1,2}(er|)/,
        ordinal: function (number) {
            return number + (number === 1 ? 'er' : '');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : frisian (fy)
    //! author : Robin van der Vliet : https://github.com/robin0van0der0v

    var fy__monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'),
        fy__monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_');

    var fy = _moment__default.defineLocale('fy', {
        months: 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'),
        monthsShort: function (m, format) {
            if (/-MMM-/.test(format)) {
                return fy__monthsShortWithoutDots[m.month()];
            } else {
                return fy__monthsShortWithDots[m.month()];
            }
        },
        weekdays: 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'),
        weekdaysShort: 'si._mo._ti._wo._to._fr._so.'.split('_'),
        weekdaysMin: 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD-MM-YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[hjoed om] LT',
            nextDay: '[moarn om] LT',
            nextWeek: 'dddd [om] LT',
            lastDay: '[juster om] LT',
            lastWeek: '[ôfrûne] dddd [om] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'oer %s',
            past: '%s lyn',
            s: 'in pear sekonden',
            m: 'ien minút',
            mm: '%d minuten',
            h: 'ien oere',
            hh: '%d oeren',
            d: 'ien dei',
            dd: '%d dagen',
            M: 'ien moanne',
            MM: '%d moannen',
            y: 'ien jier',
            yy: '%d jierren'
        },
        ordinalParse: /\d{1,2}(ste|de)/,
        ordinal: function (number) {
            return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : galician (gl)
    //! author : Juan G. Hurtado : https://github.com/juanghurtado

    var gl = _moment__default.defineLocale('gl', {
        months: 'Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro'.split('_'),
        monthsShort: 'Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.'.split('_'),
        weekdays: 'Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado'.split('_'),
        weekdaysShort: 'Dom._Lun._Mar._Mér._Xov._Ven._Sáb.'.split('_'),
        weekdaysMin: 'Do_Lu_Ma_Mé_Xo_Ve_Sá'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: function () {
                return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
            },
            nextDay: function () {
                return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
            },
            lastDay: function () {
                return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT';
            },
            lastWeek: function () {
                return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: function (str) {
                if (str === 'uns segundos') {
                    return 'nuns segundos';
                }
                return 'en ' + str;
            },
            past: 'hai %s',
            s: 'uns segundos',
            m: 'un minuto',
            mm: '%d minutos',
            h: 'unha hora',
            hh: '%d horas',
            d: 'un día',
            dd: '%d días',
            M: 'un mes',
            MM: '%d meses',
            y: 'un ano',
            yy: '%d anos'
        },
        ordinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Hebrew (he)
    //! author : Tomer Cohen : https://github.com/tomer
    //! author : Moshe Simantov : https://github.com/DevelopmentIL
    //! author : Tal Ater : https://github.com/TalAter

    var he = _moment__default.defineLocale('he', {
        months: 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'),
        monthsShort: 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'),
        weekdays: 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'),
        weekdaysShort: 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'),
        weekdaysMin: 'א_ב_ג_ד_ה_ו_ש'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [ב]MMMM YYYY',
            LLL: 'D [ב]MMMM YYYY HH:mm',
            LLLL: 'dddd, D [ב]MMMM YYYY HH:mm',
            l: 'D/M/YYYY',
            ll: 'D MMM YYYY',
            lll: 'D MMM YYYY HH:mm',
            llll: 'ddd, D MMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[היום ב־]LT',
            nextDay: '[מחר ב־]LT',
            nextWeek: 'dddd [בשעה] LT',
            lastDay: '[אתמול ב־]LT',
            lastWeek: '[ביום] dddd [האחרון בשעה] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'בעוד %s',
            past: 'לפני %s',
            s: 'מספר שניות',
            m: 'דקה',
            mm: '%d דקות',
            h: 'שעה',
            hh: function (number) {
                if (number === 2) {
                    return 'שעתיים';
                }
                return number + ' שעות';
            },
            d: 'יום',
            dd: function (number) {
                if (number === 2) {
                    return 'יומיים';
                }
                return number + ' ימים';
            },
            M: 'חודש',
            MM: function (number) {
                if (number === 2) {
                    return 'חודשיים';
                }
                return number + ' חודשים';
            },
            y: 'שנה',
            yy: function (number) {
                if (number === 2) {
                    return 'שנתיים';
                } else if (number % 10 === 0 && number !== 10) {
                    return number + ' שנה';
                }
                return number + ' שנים';
            }
        }
    });

    //! moment.js locale configuration
    //! locale : hindi (hi)
    //! author : Mayank Singhal : https://github.com/mayanksinghal

    var hi__symbolMap = {
        '1': '१',
        '2': '२',
        '3': '३',
        '4': '४',
        '5': '५',
        '6': '६',
        '7': '७',
        '8': '८',
        '9': '९',
        '0': '०'
    },
    hi__numberMap = {
        '१': '1',
        '२': '2',
        '३': '3',
        '४': '4',
        '५': '5',
        '६': '6',
        '७': '7',
        '८': '8',
        '९': '9',
        '०': '0'
    };

    var hi = _moment__default.defineLocale('hi', {
        months: 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'),
        monthsShort: 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'),
        weekdays: 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),
        weekdaysShort: 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'),
        weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'),
        longDateFormat: {
            LT: 'A h:mm बजे',
            LTS: 'A h:mm:ss बजे',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm बजे',
            LLLL: 'dddd, D MMMM YYYY, A h:mm बजे'
        },
        calendar: {
            sameDay: '[आज] LT',
            nextDay: '[कल] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[कल] LT',
            lastWeek: '[पिछले] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s में',
            past: '%s पहले',
            s: 'कुछ ही क्षण',
            m: 'एक मिनट',
            mm: '%d मिनट',
            h: 'एक घंटा',
            hh: '%d घंटे',
            d: 'एक दिन',
            dd: '%d दिन',
            M: 'एक महीने',
            MM: '%d महीने',
            y: 'एक वर्ष',
            yy: '%d वर्ष'
        },
        preparse: function (string) {
            return string.replace(/[१२३४५६७८९०]/g, function (match) {
                return hi__numberMap[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return hi__symbolMap[match];
            });
        },
        // Hindi notation for meridiems are quite fuzzy in practice. While there exists
        // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi.
        meridiemParse: /रात|सुबह|दोपहर|शाम/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'रात') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'सुबह') {
                return hour;
            } else if (meridiem === 'दोपहर') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'शाम') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'रात';
            } else if (hour < 10) {
                return 'सुबह';
            } else if (hour < 17) {
                return 'दोपहर';
            } else if (hour < 20) {
                return 'शाम';
            } else {
                return 'रात';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : hrvatski (hr)
    //! author : Bojan Marković : https://github.com/bmarkovic

    function hr__translate(number, withoutSuffix, key) {
        var result = number + ' ';
        switch (key) {
            case 'm':
                return withoutSuffix ? 'jedna minuta' : 'jedne minute';
            case 'mm':
                if (number === 1) {
                    result += 'minuta';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'minute';
                } else {
                    result += 'minuta';
                }
                return result;
            case 'h':
                return withoutSuffix ? 'jedan sat' : 'jednog sata';
            case 'hh':
                if (number === 1) {
                    result += 'sat';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'sata';
                } else {
                    result += 'sati';
                }
                return result;
            case 'dd':
                if (number === 1) {
                    result += 'dan';
                } else {
                    result += 'dana';
                }
                return result;
            case 'MM':
                if (number === 1) {
                    result += 'mjesec';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'mjeseca';
                } else {
                    result += 'mjeseci';
                }
                return result;
            case 'yy':
                if (number === 1) {
                    result += 'godina';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'godine';
                } else {
                    result += 'godina';
                }
                return result;
        }
    }

    var hr = _moment__default.defineLocale('hr', {
        months: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_'),
        monthsShort: 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'),
        weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
        weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
        weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD. MM. YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sutra u] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedjelju] [u] LT';
                    case 3:
                        return '[u] [srijedu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[jučer u] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                        return '[prošlu] dddd [u] LT';
                    case 6:
                        return '[prošle] [subote] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[prošli] dddd [u] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'prije %s',
            s: 'par sekundi',
            m: hr__translate,
            mm: hr__translate,
            h: hr__translate,
            hh: hr__translate,
            d: 'dan',
            dd: hr__translate,
            M: 'mjesec',
            MM: hr__translate,
            y: 'godinu',
            yy: hr__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : hungarian (hu)
    //! author : Adam Brunner : https://github.com/adambrunner

    var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' ');
    function hu__translate(number, withoutSuffix, key, isFuture) {
        var num = number,
            suffix;
        switch (key) {
            case 's':
                return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce';
            case 'm':
                return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce');
            case 'mm':
                return num + (isFuture || withoutSuffix ? ' perc' : ' perce');
            case 'h':
                return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája');
            case 'hh':
                return num + (isFuture || withoutSuffix ? ' óra' : ' órája');
            case 'd':
                return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja');
            case 'dd':
                return num + (isFuture || withoutSuffix ? ' nap' : ' napja');
            case 'M':
                return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
            case 'MM':
                return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
            case 'y':
                return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve');
            case 'yy':
                return num + (isFuture || withoutSuffix ? ' év' : ' éve');
        }
        return '';
    }
    function week(isFuture) {
        return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]';
    }

    var hu = _moment__default.defineLocale('hu', {
        months: 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'),
        monthsShort: 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'),
        weekdays: 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'),
        weekdaysShort: 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'),
        weekdaysMin: 'v_h_k_sze_cs_p_szo'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'YYYY.MM.DD.',
            LL: 'YYYY. MMMM D.',
            LLL: 'YYYY. MMMM D. H:mm',
            LLLL: 'YYYY. MMMM D., dddd H:mm'
        },
        meridiemParse: /de|du/i,
        isPM: function (input) {
            return input.charAt(1).toLowerCase() === 'u';
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 12) {
                return isLower === true ? 'de' : 'DE';
            } else {
                return isLower === true ? 'du' : 'DU';
            }
        },
        calendar: {
            sameDay: '[ma] LT[-kor]',
            nextDay: '[holnap] LT[-kor]',
            nextWeek: function () {
                return week.call(this, true);
            },
            lastDay: '[tegnap] LT[-kor]',
            lastWeek: function () {
                return week.call(this, false);
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s múlva',
            past: '%s',
            s: hu__translate,
            m: hu__translate,
            mm: hu__translate,
            h: hu__translate,
            hh: hu__translate,
            d: hu__translate,
            dd: hu__translate,
            M: hu__translate,
            MM: hu__translate,
            y: hu__translate,
            yy: hu__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Armenian (hy-am)
    //! author : Armendarabyan : https://github.com/armendarabyan

    function hy_am__monthsCaseReplace(m, format) {
        var months = {
            'nominative': 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_'),
            'accusative': 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_')
        },
        nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
            'accusative' :
            'nominative';
        return months[nounCase][m.month()];
    }
    function hy_am__monthsShortCaseReplace(m, format) {
        var monthsShort = 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_');
        return monthsShort[m.month()];
    }
    function hy_am__weekdaysCaseReplace(m, format) {
        var weekdays = 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_');
        return weekdays[m.day()];
    }

    var hy_am = _moment__default.defineLocale('hy-am', {
        months: hy_am__monthsCaseReplace,
        monthsShort: hy_am__monthsShortCaseReplace,
        weekdays: hy_am__weekdaysCaseReplace,
        weekdaysShort: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),
        weekdaysMin: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY թ.',
            LLL: 'D MMMM YYYY թ., HH:mm',
            LLLL: 'dddd, D MMMM YYYY թ., HH:mm'
        },
        calendar: {
            sameDay: '[այսօր] LT',
            nextDay: '[վաղը] LT',
            lastDay: '[երեկ] LT',
            nextWeek: function () {
                return 'dddd [օրը ժամը] LT';
            },
            lastWeek: function () {
                return '[անցած] dddd [օրը ժամը] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s հետո',
            past: '%s առաջ',
            s: 'մի քանի վայրկյան',
            m: 'րոպե',
            mm: '%d րոպե',
            h: 'ժամ',
            hh: '%d ժամ',
            d: 'օր',
            dd: '%d օր',
            M: 'ամիս',
            MM: '%d ամիս',
            y: 'տարի',
            yy: '%d տարի'
        },
        meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,
        isPM: function (input) {
            return /^(ցերեկվա|երեկոյան)$/.test(input);
        },
        meridiem: function (hour) {
            if (hour < 4) {
                return 'գիշերվա';
            } else if (hour < 12) {
                return 'առավոտվա';
            } else if (hour < 17) {
                return 'ցերեկվա';
            } else {
                return 'երեկոյան';
            }
        },
        ordinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'DDD':
                case 'w':
                case 'W':
                case 'DDDo':
                    if (number === 1) {
                        return number + '-ին';
                    }
                    return number + '-րդ';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Bahasa Indonesia (id)
    //! author : Mohammad Satrio Utomo : https://github.com/tyok
    //! reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan

    var id = _moment__default.defineLocale('id', {
        months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des'.split('_'),
        weekdays: 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'),
        weekdaysShort: 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'),
        weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /pagi|siang|sore|malam/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'pagi') {
                return hour;
            } else if (meridiem === 'siang') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'sore' || meridiem === 'malam') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'pagi';
            } else if (hours < 15) {
                return 'siang';
            } else if (hours < 19) {
                return 'sore';
            } else {
                return 'malam';
            }
        },
        calendar: {
            sameDay: '[Hari ini pukul] LT',
            nextDay: '[Besok pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kemarin pukul] LT',
            lastWeek: 'dddd [lalu pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dalam %s',
            past: '%s yang lalu',
            s: 'beberapa detik',
            m: 'semenit',
            mm: '%d menit',
            h: 'sejam',
            hh: '%d jam',
            d: 'sehari',
            dd: '%d hari',
            M: 'sebulan',
            MM: '%d bulan',
            y: 'setahun',
            yy: '%d tahun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : icelandic (is)
    //! author : Hinrik Örn Sigurðsson : https://github.com/hinrik

    function is__plural(n) {
        if (n % 100 === 11) {
            return true;
        } else if (n % 10 === 1) {
            return false;
        }
        return true;
    }
    function is__translate(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':
                return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum';
            case 'm':
                return withoutSuffix ? 'mínúta' : 'mínútu';
            case 'mm':
                if (is__plural(number)) {
                    return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum');
                } else if (withoutSuffix) {
                    return result + 'mínúta';
                }
                return result + 'mínútu';
            case 'hh':
                if (is__plural(number)) {
                    return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum');
                }
                return result + 'klukkustund';
            case 'd':
                if (withoutSuffix) {
                    return 'dagur';
                }
                return isFuture ? 'dag' : 'degi';
            case 'dd':
                if (is__plural(number)) {
                    if (withoutSuffix) {
                        return result + 'dagar';
                    }
                    return result + (isFuture ? 'daga' : 'dögum');
                } else if (withoutSuffix) {
                    return result + 'dagur';
                }
                return result + (isFuture ? 'dag' : 'degi');
            case 'M':
                if (withoutSuffix) {
                    return 'mánuður';
                }
                return isFuture ? 'mánuð' : 'mánuði';
            case 'MM':
                if (is__plural(number)) {
                    if (withoutSuffix) {
                        return result + 'mánuðir';
                    }
                    return result + (isFuture ? 'mánuði' : 'mánuðum');
                } else if (withoutSuffix) {
                    return result + 'mánuður';
                }
                return result + (isFuture ? 'mánuð' : 'mánuði');
            case 'y':
                return withoutSuffix || isFuture ? 'ár' : 'ári';
            case 'yy':
                if (is__plural(number)) {
                    return result + (withoutSuffix || isFuture ? 'ár' : 'árum');
                }
                return result + (withoutSuffix || isFuture ? 'ár' : 'ári');
        }
    }

    var is = _moment__default.defineLocale('is', {
        months: 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'),
        weekdays: 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'),
        weekdaysShort: 'sun_mán_þri_mið_fim_fös_lau'.split('_'),
        weekdaysMin: 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY [kl.] H:mm',
            LLLL: 'dddd, D. MMMM YYYY [kl.] H:mm'
        },
        calendar: {
            sameDay: '[í dag kl.] LT',
            nextDay: '[á morgun kl.] LT',
            nextWeek: 'dddd [kl.] LT',
            lastDay: '[í gær kl.] LT',
            lastWeek: '[síðasta] dddd [kl.] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'eftir %s',
            past: 'fyrir %s síðan',
            s: is__translate,
            m: is__translate,
            mm: is__translate,
            h: 'klukkustund',
            hh: is__translate,
            d: is__translate,
            dd: is__translate,
            M: is__translate,
            MM: is__translate,
            y: is__translate,
            yy: is__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : italian (it)
    //! author : Lorenzo : https://github.com/aliem
    //! author: Mattia Larentis: https://github.com/nostalgiaz

    var it = _moment__default.defineLocale('it', {
        months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'),
        monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),
        weekdays: 'Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato'.split('_'),
        weekdaysShort: 'Dom_Lun_Mar_Mer_Gio_Ven_Sab'.split('_'),
        weekdaysMin: 'D_L_Ma_Me_G_V_S'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Oggi alle] LT',
            nextDay: '[Domani alle] LT',
            nextWeek: 'dddd [alle] LT',
            lastDay: '[Ieri alle] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[la scorsa] dddd [alle] LT';
                    default:
                        return '[lo scorso] dddd [alle] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: function (s) {
                return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s;
            },
            past: '%s fa',
            s: 'alcuni secondi',
            m: 'un minuto',
            mm: '%d minuti',
            h: 'un\'ora',
            hh: '%d ore',
            d: 'un giorno',
            dd: '%d giorni',
            M: 'un mese',
            MM: '%d mesi',
            y: 'un anno',
            yy: '%d anni'
        },
        ordinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : japanese (ja)
    //! author : LI Long : https://github.com/baryon

    var ja = _moment__default.defineLocale('ja', {
        months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'),
        weekdaysShort: '日_月_火_水_木_金_土'.split('_'),
        weekdaysMin: '日_月_火_水_木_金_土'.split('_'),
        longDateFormat: {
            LT: 'Ah時m分',
            LTS: 'Ah時m分s秒',
            L: 'YYYY/MM/DD',
            LL: 'YYYY年M月D日',
            LLL: 'YYYY年M月D日Ah時m分',
            LLLL: 'YYYY年M月D日Ah時m分 dddd'
        },
        meridiemParse: /午前|午後/i,
        isPM: function (input) {
            return input === '午後';
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return '午前';
            } else {
                return '午後';
            }
        },
        calendar: {
            sameDay: '[今日] LT',
            nextDay: '[明日] LT',
            nextWeek: '[来週]dddd LT',
            lastDay: '[昨日] LT',
            lastWeek: '[前週]dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s後',
            past: '%s前',
            s: '数秒',
            m: '1分',
            mm: '%d分',
            h: '1時間',
            hh: '%d時間',
            d: '1日',
            dd: '%d日',
            M: '1ヶ月',
            MM: '%dヶ月',
            y: '1年',
            yy: '%d年'
        }
    });

    //! moment.js locale configuration
    //! locale : Boso Jowo (jv)
    //! author : Rony Lantip : https://github.com/lantip
    //! reference: http://jv.wikipedia.org/wiki/Basa_Jawa

    var jv = _moment__default.defineLocale('jv', {
        months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'),
        weekdays: 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'),
        weekdaysShort: 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'),
        weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /enjing|siyang|sonten|ndalu/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'enjing') {
                return hour;
            } else if (meridiem === 'siyang') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'sonten' || meridiem === 'ndalu') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'enjing';
            } else if (hours < 15) {
                return 'siyang';
            } else if (hours < 19) {
                return 'sonten';
            } else {
                return 'ndalu';
            }
        },
        calendar: {
            sameDay: '[Dinten puniko pukul] LT',
            nextDay: '[Mbenjang pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kala wingi pukul] LT',
            lastWeek: 'dddd [kepengker pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'wonten ing %s',
            past: '%s ingkang kepengker',
            s: 'sawetawis detik',
            m: 'setunggal menit',
            mm: '%d menit',
            h: 'setunggal jam',
            hh: '%d jam',
            d: 'sedinten',
            dd: '%d dinten',
            M: 'sewulan',
            MM: '%d wulan',
            y: 'setaun',
            yy: '%d taun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Georgian (ka)
    //! author : Irakli Janiashvili : https://github.com/irakli-janiashvili

    function ka__monthsCaseReplace(m, format) {
        var months = {
            'nominative': 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'),
            'accusative': 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_')
        },
        nounCase = (/D[oD] *MMMM?/).test(format) ?
            'accusative' :
            'nominative';
        return months[nounCase][m.month()];
    }
    function ka__weekdaysCaseReplace(m, format) {
        var weekdays = {
            'nominative': 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'),
            'accusative': 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_')
        },
        nounCase = (/(წინა|შემდეგ)/).test(format) ?
            'accusative' :
            'nominative';
        return weekdays[nounCase][m.day()];
    }

    var ka = _moment__default.defineLocale('ka', {
        months: ka__monthsCaseReplace,
        monthsShort: 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'),
        weekdays: ka__weekdaysCaseReplace,
        weekdaysShort: 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'),
        weekdaysMin: 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendar: {
            sameDay: '[დღეს] LT[-ზე]',
            nextDay: '[ხვალ] LT[-ზე]',
            lastDay: '[გუშინ] LT[-ზე]',
            nextWeek: '[შემდეგ] dddd LT[-ზე]',
            lastWeek: '[წინა] dddd LT-ზე',
            sameElse: 'L'
        },
        relativeTime: {
            future: function (s) {
                return (/(წამი|წუთი|საათი|წელი)/).test(s) ?
                    s.replace(/ი$/, 'ში') :
                    s + 'ში';
            },
            past: function (s) {
                if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) {
                    return s.replace(/(ი|ე)$/, 'ის წინ');
                }
                if ((/წელი/).test(s)) {
                    return s.replace(/წელი$/, 'წლის წინ');
                }
            },
            s: 'რამდენიმე წამი',
            m: 'წუთი',
            mm: '%d წუთი',
            h: 'საათი',
            hh: '%d საათი',
            d: 'დღე',
            dd: '%d დღე',
            M: 'თვე',
            MM: '%d თვე',
            y: 'წელი',
            yy: '%d წელი'
        },
        ordinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/,
        ordinal: function (number) {
            if (number === 0) {
                return number;
            }
            if (number === 1) {
                return number + '-ლი';
            }
            if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) {
                return 'მე-' + number;
            }
            return number + '-ე';
        },
        week: {
            dow: 1,
            doy: 7
        }
    });

    //! moment.js locale configuration
    //! locale : khmer (km)
    //! author : Kruy Vanna : https://github.com/kruyvanna

    var km = _moment__default.defineLocale('km', {
        months: 'មករា_កុម្ភៈ_មិនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'),
        monthsShort: 'មករា_កុម្ភៈ_មិនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'),
        weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),
        weekdaysShort: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),
        weekdaysMin: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[ថ្ងៃនៈ ម៉ោង] LT',
            nextDay: '[ស្អែក ម៉ោង] LT',
            nextWeek: 'dddd [ម៉ោង] LT',
            lastDay: '[ម្សិលមិញ ម៉ោង] LT',
            lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%sទៀត',
            past: '%sមុន',
            s: 'ប៉ុន្មានវិនាទី',
            m: 'មួយនាទី',
            mm: '%d នាទី',
            h: 'មួយម៉ោង',
            hh: '%d ម៉ោង',
            d: 'មួយថ្ងៃ',
            dd: '%d ថ្ងៃ',
            M: 'មួយខែ',
            MM: '%d ខែ',
            y: 'មួយឆ្នាំ',
            yy: '%d ឆ្នាំ'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : korean (ko)
    //!
    //! authors
    //!
    //! - Kyungwook, Park : https://github.com/kyungw00k
    //! - Jeeeyul Lee <jeeeyul@gmail.com>

    var ko = _moment__default.defineLocale('ko', {
        months: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
        monthsShort: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
        weekdays: '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'),
        weekdaysShort: '일_월_화_수_목_금_토'.split('_'),
        weekdaysMin: '일_월_화_수_목_금_토'.split('_'),
        longDateFormat: {
            LT: 'A h시 m분',
            LTS: 'A h시 m분 s초',
            L: 'YYYY.MM.DD',
            LL: 'YYYY년 MMMM D일',
            LLL: 'YYYY년 MMMM D일 A h시 m분',
            LLLL: 'YYYY년 MMMM D일 dddd A h시 m분'
        },
        calendar: {
            sameDay: '오늘 LT',
            nextDay: '내일 LT',
            nextWeek: 'dddd LT',
            lastDay: '어제 LT',
            lastWeek: '지난주 dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s 후',
            past: '%s 전',
            s: '몇초',
            ss: '%d초',
            m: '일분',
            mm: '%d분',
            h: '한시간',
            hh: '%d시간',
            d: '하루',
            dd: '%d일',
            M: '한달',
            MM: '%d달',
            y: '일년',
            yy: '%d년'
        },
        ordinalParse: /\d{1,2}일/,
        ordinal: '%d일',
        meridiemParse: /오전|오후/,
        isPM: function (token) {
            return token === '오후';
        },
        meridiem: function (hour, minute, isUpper) {
            return hour < 12 ? '오전' : '오후';
        }
    });

    //! moment.js locale configuration
    //! locale : Luxembourgish (lb)
    //! author : mweimerskirch : https://github.com/mweimerskirch, David Raison : https://github.com/kwisatz

    function lb__processRelativeTime(number, withoutSuffix, key, isFuture) {
        var format = {
            'm': ['eng Minutt', 'enger Minutt'],
            'h': ['eng Stonn', 'enger Stonn'],
            'd': ['een Dag', 'engem Dag'],
            'M': ['ee Mount', 'engem Mount'],
            'y': ['ee Joer', 'engem Joer']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }
    function processFutureTime(string) {
        var number = string.substr(0, string.indexOf(' '));
        if (eifelerRegelAppliesToNumber(number)) {
            return 'a ' + string;
        }
        return 'an ' + string;
    }
    function processPastTime(string) {
        var number = string.substr(0, string.indexOf(' '));
        if (eifelerRegelAppliesToNumber(number)) {
            return 'viru ' + string;
        }
        return 'virun ' + string;
    }
    /**
     * Returns true if the word before the given number loses the '-n' ending.
     * e.g. 'an 10 Deeg' but 'a 5 Deeg'
     *
     * @param number {integer}
     * @returns {boolean}
     */
    function eifelerRegelAppliesToNumber(number) {
        number = parseInt(number, 10);
        if (isNaN(number)) {
            return false;
        }
        if (number < 0) {
            // Negative Number --> always true
            return true;
        } else if (number < 10) {
            // Only 1 digit
            if (4 <= number && number <= 7) {
                return true;
            }
            return false;
        } else if (number < 100) {
            // 2 digits
            var lastDigit = number % 10, firstDigit = number / 10;
            if (lastDigit === 0) {
                return eifelerRegelAppliesToNumber(firstDigit);
            }
            return eifelerRegelAppliesToNumber(lastDigit);
        } else if (number < 10000) {
            // 3 or 4 digits --> recursively check first digit
            while (number >= 10) {
                number = number / 10;
            }
            return eifelerRegelAppliesToNumber(number);
        } else {
            // Anything larger than 4 digits: recursively check first n-3 digits
            number = number / 1000;
            return eifelerRegelAppliesToNumber(number);
        }
    }

    var lb = _moment__default.defineLocale('lb', {
        months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
        monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
        weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'),
        weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'),
        weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'H:mm [Auer]',
            LTS: 'H:mm:ss [Auer]',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm [Auer]',
            LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]'
        },
        calendar: {
            sameDay: '[Haut um] LT',
            sameElse: 'L',
            nextDay: '[Muer um] LT',
            nextWeek: 'dddd [um] LT',
            lastDay: '[Gëschter um] LT',
            lastWeek: function () {
                // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule
                switch (this.day()) {
                    case 2:
                    case 4:
                        return '[Leschten] dddd [um] LT';
                    default:
                        return '[Leschte] dddd [um] LT';
                }
            }
        },
        relativeTime: {
            future: processFutureTime,
            past: processPastTime,
            s: 'e puer Sekonnen',
            m: lb__processRelativeTime,
            mm: '%d Minutten',
            h: lb__processRelativeTime,
            hh: '%d Stonnen',
            d: lb__processRelativeTime,
            dd: '%d Deeg',
            M: lb__processRelativeTime,
            MM: '%d Méint',
            y: lb__processRelativeTime,
            yy: '%d Joer'
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Lithuanian (lt)
    //! author : Mindaugas Mozūras : https://github.com/mmozuras

    var lt__units = {
        'm': 'minutė_minutės_minutę',
        'mm': 'minutės_minučių_minutes',
        'h': 'valanda_valandos_valandą',
        'hh': 'valandos_valandų_valandas',
        'd': 'diena_dienos_dieną',
        'dd': 'dienos_dienų_dienas',
        'M': 'mėnuo_mėnesio_mėnesį',
        'MM': 'mėnesiai_mėnesių_mėnesius',
        'y': 'metai_metų_metus',
        'yy': 'metai_metų_metus'
    },
    weekDays = 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_');
    function translateSeconds(number, withoutSuffix, key, isFuture) {
        if (withoutSuffix) {
            return 'kelios sekundės';
        } else {
            return isFuture ? 'kelių sekundžių' : 'kelias sekundes';
        }
    }
    function lt__monthsCaseReplace(m, format) {
        var months = {
            'nominative': 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'),
            'accusative': 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_')
        },
            nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
                'accusative' :
                'nominative';
        return months[nounCase][m.month()];
    }
    function translateSingular(number, withoutSuffix, key, isFuture) {
        return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]);
    }
    function special(number) {
        return number % 10 === 0 || (number > 10 && number < 20);
    }
    function forms(key) {
        return lt__units[key].split('_');
    }
    function lt__translate(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        if (number === 1) {
            return result + translateSingular(number, withoutSuffix, key[0], isFuture);
        } else if (withoutSuffix) {
            return result + (special(number) ? forms(key)[1] : forms(key)[0]);
        } else {
            if (isFuture) {
                return result + forms(key)[1];
            } else {
                return result + (special(number) ? forms(key)[1] : forms(key)[2]);
            }
        }
    }
    function relativeWeekDay(moment, format) {
        var nominative = format.indexOf('dddd HH:mm') === -1,
            weekDay = weekDays[moment.day()];
        return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + 'į';
    }

    var lt = _moment__default.defineLocale('lt', {
        months: lt__monthsCaseReplace,
        monthsShort: 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'),
        weekdays: relativeWeekDay,
        weekdaysShort: 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'),
        weekdaysMin: 'S_P_A_T_K_Pn_Š'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'YYYY [m.] MMMM D [d.]',
            LLL: 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
            LLLL: 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]',
            l: 'YYYY-MM-DD',
            ll: 'YYYY [m.] MMMM D [d.]',
            lll: 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
            llll: 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]'
        },
        calendar: {
            sameDay: '[Šiandien] LT',
            nextDay: '[Rytoj] LT',
            nextWeek: 'dddd LT',
            lastDay: '[Vakar] LT',
            lastWeek: '[Praėjusį] dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'po %s',
            past: 'prieš %s',
            s: translateSeconds,
            m: translateSingular,
            mm: lt__translate,
            h: translateSingular,
            hh: lt__translate,
            d: translateSingular,
            dd: lt__translate,
            M: translateSingular,
            MM: lt__translate,
            y: translateSingular,
            yy: lt__translate
        },
        ordinalParse: /\d{1,2}-oji/,
        ordinal: function (number) {
            return number + '-oji';
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : latvian (lv)
    //! author : Kristaps Karlsons : https://github.com/skakri
    //! author : Jānis Elmeris : https://github.com/JanisE

    var lv__units = {
        'm': 'minūtes_minūtēm_minūte_minūtes'.split('_'),
        'mm': 'minūtes_minūtēm_minūte_minūtes'.split('_'),
        'h': 'stundas_stundām_stunda_stundas'.split('_'),
        'hh': 'stundas_stundām_stunda_stundas'.split('_'),
        'd': 'dienas_dienām_diena_dienas'.split('_'),
        'dd': 'dienas_dienām_diena_dienas'.split('_'),
        'M': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),
        'MM': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),
        'y': 'gada_gadiem_gads_gadi'.split('_'),
        'yy': 'gada_gadiem_gads_gadi'.split('_')
    };
    /**
     * @param withoutSuffix boolean true = a length of time; false = before/after a period of time.
     */
    function lv__format(forms, number, withoutSuffix) {
        if (withoutSuffix) {
            // E.g. "21 minūte", "3 minūtes".
            return number % 10 === 1 && number !== 11 ? forms[2] : forms[3];
        } else {
            // E.g. "21 minūtes" as in "pēc 21 minūtes".
            // E.g. "3 minūtēm" as in "pēc 3 minūtēm".
            return number % 10 === 1 && number !== 11 ? forms[0] : forms[1];
        }
    }
    function lv__relativeTimeWithPlural(number, withoutSuffix, key) {
        return number + ' ' + lv__format(lv__units[key], number, withoutSuffix);
    }
    function relativeTimeWithSingular(number, withoutSuffix, key) {
        return lv__format(lv__units[key], number, withoutSuffix);
    }
    function relativeSeconds(number, withoutSuffix) {
        return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm';
    }

    var lv = _moment__default.defineLocale('lv', {
        months: 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'),
        monthsShort: 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'),
        weekdays: 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'),
        weekdaysShort: 'Sv_P_O_T_C_Pk_S'.split('_'),
        weekdaysMin: 'Sv_P_O_T_C_Pk_S'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY.',
            LL: 'YYYY. [gada] D. MMMM',
            LLL: 'YYYY. [gada] D. MMMM, HH:mm',
            LLLL: 'YYYY. [gada] D. MMMM, dddd, HH:mm'
        },
        calendar: {
            sameDay: '[Šodien pulksten] LT',
            nextDay: '[Rīt pulksten] LT',
            nextWeek: 'dddd [pulksten] LT',
            lastDay: '[Vakar pulksten] LT',
            lastWeek: '[Pagājušā] dddd [pulksten] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'pēc %s',
            past: 'pirms %s',
            s: relativeSeconds,
            m: relativeTimeWithSingular,
            mm: lv__relativeTimeWithPlural,
            h: relativeTimeWithSingular,
            hh: lv__relativeTimeWithPlural,
            d: relativeTimeWithSingular,
            dd: lv__relativeTimeWithPlural,
            M: relativeTimeWithSingular,
            MM: lv__relativeTimeWithPlural,
            y: relativeTimeWithSingular,
            yy: lv__relativeTimeWithPlural
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Montenegrin (me)
    //! author : Miodrag Nikač <miodrag@restartit.me> : https://github.com/miodragnikac

    var me__translator = {
        words: { //Different grammatical cases
            m: ['jedan minut', 'jednog minuta'],
            mm: ['minut', 'minuta', 'minuta'],
            h: ['jedan sat', 'jednog sata'],
            hh: ['sat', 'sata', 'sati'],
            dd: ['dan', 'dana', 'dana'],
            MM: ['mjesec', 'mjeseca', 'mjeseci'],
            yy: ['godina', 'godine', 'godina']
        },
        correctGrammaticalCase: function (number, wordKey) {
            return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
        },
        translate: function (number, withoutSuffix, key) {
            var wordKey = me__translator.words[key];
            if (key.length === 1) {
                return withoutSuffix ? wordKey[0] : wordKey[1];
            } else {
                return number + ' ' + me__translator.correctGrammaticalCase(number, wordKey);
            }
        }
    };

    var me = _moment__default.defineLocale('me', {
        months: ['januar', 'februar', 'mart', 'april', 'maj', 'jun', 'jul', 'avgust', 'septembar', 'oktobar', 'novembar', 'decembar'],
        monthsShort: ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun', 'jul', 'avg.', 'sep.', 'okt.', 'nov.', 'dec.'],
        weekdays: ['nedjelja', 'ponedjeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'],
        weekdaysShort: ['ned.', 'pon.', 'uto.', 'sri.', 'čet.', 'pet.', 'sub.'],
        weekdaysMin: ['ne', 'po', 'ut', 'sr', 'če', 'pe', 'su'],
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD. MM. YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sjutra u] LT',

            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedjelju] [u] LT';
                    case 3:
                        return '[u] [srijedu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[juče u] LT',
            lastWeek: function () {
                var lastWeekDays = [
                    '[prošle] [nedjelje] [u] LT',
                    '[prošlog] [ponedjeljka] [u] LT',
                    '[prošlog] [utorka] [u] LT',
                    '[prošle] [srijede] [u] LT',
                    '[prošlog] [četvrtka] [u] LT',
                    '[prošlog] [petka] [u] LT',
                    '[prošle] [subote] [u] LT'
                ];
                return lastWeekDays[this.day()];
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'prije %s',
            s: 'nekoliko sekundi',
            m: me__translator.translate,
            mm: me__translator.translate,
            h: me__translator.translate,
            hh: me__translator.translate,
            d: 'dan',
            dd: me__translator.translate,
            M: 'mjesec',
            MM: me__translator.translate,
            y: 'godinu',
            yy: me__translator.translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : macedonian (mk)
    //! author : Borislav Mickov : https://github.com/B0k0

    var mk = _moment__default.defineLocale('mk', {
        months: 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'),
        monthsShort: 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'),
        weekdays: 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'),
        weekdaysShort: 'нед_пон_вто_сре_чет_пет_саб'.split('_'),
        weekdaysMin: 'нe_пo_вт_ср_че_пе_сa'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'D.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd, D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[Денес во] LT',
            nextDay: '[Утре во] LT',
            nextWeek: 'dddd [во] LT',
            lastDay: '[Вчера во] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 6:
                        return '[Во изминатата] dddd [во] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[Во изминатиот] dddd [во] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'после %s',
            past: 'пред %s',
            s: 'неколку секунди',
            m: 'минута',
            mm: '%d минути',
            h: 'час',
            hh: '%d часа',
            d: 'ден',
            dd: '%d дена',
            M: 'месец',
            MM: '%d месеци',
            y: 'година',
            yy: '%d години'
        },
        ordinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/,
        ordinal: function (number) {
            var lastDigit = number % 10,
                last2Digits = number % 100;
            if (number === 0) {
                return number + '-ев';
            } else if (last2Digits === 0) {
                return number + '-ен';
            } else if (last2Digits > 10 && last2Digits < 20) {
                return number + '-ти';
            } else if (lastDigit === 1) {
                return number + '-ви';
            } else if (lastDigit === 2) {
                return number + '-ри';
            } else if (lastDigit === 7 || lastDigit === 8) {
                return number + '-ми';
            } else {
                return number + '-ти';
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : malayalam (ml)
    //! author : Floyd Pink : https://github.com/floydpink

    var ml = _moment__default.defineLocale('ml', {
        months: 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'),
        monthsShort: 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'),
        weekdays: 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'),
        weekdaysShort: 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'),
        weekdaysMin: 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'),
        longDateFormat: {
            LT: 'A h:mm -നു',
            LTS: 'A h:mm:ss -നു',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm -നു',
            LLLL: 'dddd, D MMMM YYYY, A h:mm -നു'
        },
        calendar: {
            sameDay: '[ഇന്ന്] LT',
            nextDay: '[നാളെ] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[ഇന്നലെ] LT',
            lastWeek: '[കഴിഞ്ഞ] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s കഴിഞ്ഞ്',
            past: '%s മുൻപ്',
            s: 'അൽപ നിമിഷങ്ങൾ',
            m: 'ഒരു മിനിറ്റ്',
            mm: '%d മിനിറ്റ്',
            h: 'ഒരു മണിക്കൂർ',
            hh: '%d മണിക്കൂർ',
            d: 'ഒരു ദിവസം',
            dd: '%d ദിവസം',
            M: 'ഒരു മാസം',
            MM: '%d മാസം',
            y: 'ഒരു വർഷം',
            yy: '%d വർഷം'
        },
        meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i,
        isPM: function (input) {
            return /^(ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'രാത്രി';
            } else if (hour < 12) {
                return 'രാവിലെ';
            } else if (hour < 17) {
                return 'ഉച്ച കഴിഞ്ഞ്';
            } else if (hour < 20) {
                return 'വൈകുന്നേരം';
            } else {
                return 'രാത്രി';
            }
        }
    });

    //! moment.js locale configuration
    //! locale : Marathi (mr)
    //! author : Harshad Kale : https://github.com/kalehv

    var mr__symbolMap = {
        '1': '१',
        '2': '२',
        '3': '३',
        '4': '४',
        '5': '५',
        '6': '६',
        '7': '७',
        '8': '८',
        '9': '९',
        '0': '०'
    },
    mr__numberMap = {
        '१': '1',
        '२': '2',
        '३': '3',
        '४': '4',
        '५': '5',
        '६': '6',
        '७': '7',
        '८': '8',
        '९': '9',
        '०': '0'
    };

    var mr = _moment__default.defineLocale('mr', {
        months: 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'),
        monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'),
        weekdays: 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),
        weekdaysShort: 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'),
        weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'),
        longDateFormat: {
            LT: 'A h:mm वाजता',
            LTS: 'A h:mm:ss वाजता',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm वाजता',
            LLLL: 'dddd, D MMMM YYYY, A h:mm वाजता'
        },
        calendar: {
            sameDay: '[आज] LT',
            nextDay: '[उद्या] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[काल] LT',
            lastWeek: '[मागील] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s नंतर',
            past: '%s पूर्वी',
            s: 'सेकंद',
            m: 'एक मिनिट',
            mm: '%d मिनिटे',
            h: 'एक तास',
            hh: '%d तास',
            d: 'एक दिवस',
            dd: '%d दिवस',
            M: 'एक महिना',
            MM: '%d महिने',
            y: 'एक वर्ष',
            yy: '%d वर्षे'
        },
        preparse: function (string) {
            return string.replace(/[१२३४५६७८९०]/g, function (match) {
                return mr__numberMap[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return mr__symbolMap[match];
            });
        },
        meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'रात्री') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'सकाळी') {
                return hour;
            } else if (meridiem === 'दुपारी') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'सायंकाळी') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'रात्री';
            } else if (hour < 10) {
                return 'सकाळी';
            } else if (hour < 17) {
                return 'दुपारी';
            } else if (hour < 20) {
                return 'सायंकाळी';
            } else {
                return 'रात्री';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Bahasa Malaysia (ms-MY)
    //! author : Weldan Jamili : https://github.com/weldan

    var ms_my = _moment__default.defineLocale('ms-my', {
        months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),
        monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),
        weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),
        weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),
        weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /pagi|tengahari|petang|malam/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'pagi') {
                return hour;
            } else if (meridiem === 'tengahari') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'petang' || meridiem === 'malam') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'pagi';
            } else if (hours < 15) {
                return 'tengahari';
            } else if (hours < 19) {
                return 'petang';
            } else {
                return 'malam';
            }
        },
        calendar: {
            sameDay: '[Hari ini pukul] LT',
            nextDay: '[Esok pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kelmarin pukul] LT',
            lastWeek: 'dddd [lepas pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dalam %s',
            past: '%s yang lepas',
            s: 'beberapa saat',
            m: 'seminit',
            mm: '%d minit',
            h: 'sejam',
            hh: '%d jam',
            d: 'sehari',
            dd: '%d hari',
            M: 'sebulan',
            MM: '%d bulan',
            y: 'setahun',
            yy: '%d tahun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Bahasa Malaysia (ms-MY)
    //! author : Weldan Jamili : https://github.com/weldan

    var locale_ms = _moment__default.defineLocale('ms', {
        months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),
        monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),
        weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),
        weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),
        weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /pagi|tengahari|petang|malam/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'pagi') {
                return hour;
            } else if (meridiem === 'tengahari') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'petang' || meridiem === 'malam') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'pagi';
            } else if (hours < 15) {
                return 'tengahari';
            } else if (hours < 19) {
                return 'petang';
            } else {
                return 'malam';
            }
        },
        calendar: {
            sameDay: '[Hari ini pukul] LT',
            nextDay: '[Esok pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kelmarin pukul] LT',
            lastWeek: 'dddd [lepas pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dalam %s',
            past: '%s yang lepas',
            s: 'beberapa saat',
            m: 'seminit',
            mm: '%d minit',
            h: 'sejam',
            hh: '%d jam',
            d: 'sehari',
            dd: '%d hari',
            M: 'sebulan',
            MM: '%d bulan',
            y: 'setahun',
            yy: '%d tahun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Burmese (my)
    //! author : Squar team, mysquar.com

    var my__symbolMap = {
        '1': '၁',
        '2': '၂',
        '3': '၃',
        '4': '၄',
        '5': '၅',
        '6': '၆',
        '7': '၇',
        '8': '၈',
        '9': '၉',
        '0': '၀'
    }, my__numberMap = {
        '၁': '1',
        '၂': '2',
        '၃': '3',
        '၄': '4',
        '၅': '5',
        '၆': '6',
        '၇': '7',
        '၈': '8',
        '၉': '9',
        '၀': '0'
    };

    var my = _moment__default.defineLocale('my', {
        months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'),
        monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'),
        weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'),
        weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),
        weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),

        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[ယနေ.] LT [မှာ]',
            nextDay: '[မနက်ဖြန်] LT [မှာ]',
            nextWeek: 'dddd LT [မှာ]',
            lastDay: '[မနေ.က] LT [မှာ]',
            lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'လာမည့် %s မှာ',
            past: 'လွန်ခဲ့သော %s က',
            s: 'စက္ကန်.အနည်းငယ်',
            m: 'တစ်မိနစ်',
            mm: '%d မိနစ်',
            h: 'တစ်နာရီ',
            hh: '%d နာရီ',
            d: 'တစ်ရက်',
            dd: '%d ရက်',
            M: 'တစ်လ',
            MM: '%d လ',
            y: 'တစ်နှစ်',
            yy: '%d နှစ်'
        },
        preparse: function (string) {
            return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) {
                return my__numberMap[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return my__symbolMap[match];
            });
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : norwegian bokmål (nb)
    //! authors : Espen Hovlandsdal : https://github.com/rexxars
    //!           Sigurd Gartmann : https://github.com/sigurdga

    var nb = _moment__default.defineLocale('nb', {
        months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
        monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),
        weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),
        weekdaysShort: 'søn_man_tirs_ons_tors_fre_lør'.split('_'),
        weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'),
        longDateFormat: {
            LT: 'H.mm',
            LTS: 'H.mm.ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY [kl.] H.mm',
            LLLL: 'dddd D. MMMM YYYY [kl.] H.mm'
        },
        calendar: {
            sameDay: '[i dag kl.] LT',
            nextDay: '[i morgen kl.] LT',
            nextWeek: 'dddd [kl.] LT',
            lastDay: '[i går kl.] LT',
            lastWeek: '[forrige] dddd [kl.] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: 'for %s siden',
            s: 'noen sekunder',
            m: 'ett minutt',
            mm: '%d minutter',
            h: 'en time',
            hh: '%d timer',
            d: 'en dag',
            dd: '%d dager',
            M: 'en måned',
            MM: '%d måneder',
            y: 'ett år',
            yy: '%d år'
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : nepali/nepalese
    //! author : suvash : https://github.com/suvash

    var ne__symbolMap = {
        '1': '१',
        '2': '२',
        '3': '३',
        '4': '४',
        '5': '५',
        '6': '६',
        '7': '७',
        '8': '८',
        '9': '९',
        '0': '०'
    },
    ne__numberMap = {
        '१': '1',
        '२': '2',
        '३': '3',
        '४': '4',
        '५': '5',
        '६': '6',
        '७': '7',
        '८': '8',
        '९': '9',
        '०': '0'
    };

    var ne = _moment__default.defineLocale('ne', {
        months: 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'),
        monthsShort: 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'),
        weekdays: 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'),
        weekdaysShort: 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'),
        weekdaysMin: 'आइ._सो._मङ्_बु._बि._शु._श.'.split('_'),
        longDateFormat: {
            LT: 'Aको h:mm बजे',
            LTS: 'Aको h:mm:ss बजे',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, Aको h:mm बजे',
            LLLL: 'dddd, D MMMM YYYY, Aको h:mm बजे'
        },
        preparse: function (string) {
            return string.replace(/[१२३४५६७८९०]/g, function (match) {
                return ne__numberMap[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return ne__symbolMap[match];
            });
        },
        meridiemParse: /राती|बिहान|दिउँसो|बेलुका|साँझ|राती/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'राती') {
                return hour < 3 ? hour : hour + 12;
            } else if (meridiem === 'बिहान') {
                return hour;
            } else if (meridiem === 'दिउँसो') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'बेलुका' || meridiem === 'साँझ') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 3) {
                return 'राती';
            } else if (hour < 10) {
                return 'बिहान';
            } else if (hour < 15) {
                return 'दिउँसो';
            } else if (hour < 18) {
                return 'बेलुका';
            } else if (hour < 20) {
                return 'साँझ';
            } else {
                return 'राती';
            }
        },
        calendar: {
            sameDay: '[आज] LT',
            nextDay: '[भोली] LT',
            nextWeek: '[आउँदो] dddd[,] LT',
            lastDay: '[हिजो] LT',
            lastWeek: '[गएको] dddd[,] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%sमा',
            past: '%s अगाडी',
            s: 'केही समय',
            m: 'एक मिनेट',
            mm: '%d मिनेट',
            h: 'एक घण्टा',
            hh: '%d घण्टा',
            d: 'एक दिन',
            dd: '%d दिन',
            M: 'एक महिना',
            MM: '%d महिना',
            y: 'एक बर्ष',
            yy: '%d बर्ष'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : dutch (nl)
    //! author : Joris Röling : https://github.com/jjupiter

    var nl__monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
        nl__monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_');

    var nl = _moment__default.defineLocale('nl', {
        months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),
        monthsShort: function (m, format) {
            if (/-MMM-/.test(format)) {
                return nl__monthsShortWithoutDots[m.month()];
            } else {
                return nl__monthsShortWithDots[m.month()];
            }
        },
        weekdays: 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),
        weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'),
        weekdaysMin: 'Zo_Ma_Di_Wo_Do_Vr_Za'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD-MM-YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[vandaag om] LT',
            nextDay: '[morgen om] LT',
            nextWeek: 'dddd [om] LT',
            lastDay: '[gisteren om] LT',
            lastWeek: '[afgelopen] dddd [om] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'over %s',
            past: '%s geleden',
            s: 'een paar seconden',
            m: 'één minuut',
            mm: '%d minuten',
            h: 'één uur',
            hh: '%d uur',
            d: 'één dag',
            dd: '%d dagen',
            M: 'één maand',
            MM: '%d maanden',
            y: 'één jaar',
            yy: '%d jaar'
        },
        ordinalParse: /\d{1,2}(ste|de)/,
        ordinal: function (number) {
            return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : norwegian nynorsk (nn)
    //! author : https://github.com/mechuwind

    var nn = _moment__default.defineLocale('nn', {
        months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
        monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),
        weekdays: 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'),
        weekdaysShort: 'sun_mån_tys_ons_tor_fre_lau'.split('_'),
        weekdaysMin: 'su_må_ty_on_to_fr_lø'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[I dag klokka] LT',
            nextDay: '[I morgon klokka] LT',
            nextWeek: 'dddd [klokka] LT',
            lastDay: '[I går klokka] LT',
            lastWeek: '[Føregåande] dddd [klokka] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: 'for %s sidan',
            s: 'nokre sekund',
            m: 'eit minutt',
            mm: '%d minutt',
            h: 'ein time',
            hh: '%d timar',
            d: 'ein dag',
            dd: '%d dagar',
            M: 'ein månad',
            MM: '%d månader',
            y: 'eit år',
            yy: '%d år'
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : polish (pl)
    //! author : Rafal Hirsz : https://github.com/evoL

    var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'),
        monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_');
    function pl__plural(n) {
        return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1);
    }
    function pl__translate(number, withoutSuffix, key) {
        var result = number + ' ';
        switch (key) {
            case 'm':
                return withoutSuffix ? 'minuta' : 'minutę';
            case 'mm':
                return result + (pl__plural(number) ? 'minuty' : 'minut');
            case 'h':
                return withoutSuffix ? 'godzina' : 'godzinę';
            case 'hh':
                return result + (pl__plural(number) ? 'godziny' : 'godzin');
            case 'MM':
                return result + (pl__plural(number) ? 'miesiące' : 'miesięcy');
            case 'yy':
                return result + (pl__plural(number) ? 'lata' : 'lat');
        }
    }

    var pl = _moment__default.defineLocale('pl', {
        months: function (momentToFormat, format) {
            if (format === '') {
                // Hack: if format empty we know this is used to generate
                // RegExp by moment. Give then back both valid forms of months
                // in RegExp ready format.
                return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')';
            } else if (/D MMMM/.test(format)) {
                return monthsSubjective[momentToFormat.month()];
            } else {
                return monthsNominative[momentToFormat.month()];
            }
        },
        monthsShort: 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'),
        weekdays: 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'),
        weekdaysShort: 'nie_pon_wt_śr_czw_pt_sb'.split('_'),
        weekdaysMin: 'N_Pn_Wt_Śr_Cz_Pt_So'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Dziś o] LT',
            nextDay: '[Jutro o] LT',
            nextWeek: '[W] dddd [o] LT',
            lastDay: '[Wczoraj o] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[W zeszłą niedzielę o] LT';
                    case 3:
                        return '[W zeszłą środę o] LT';
                    case 6:
                        return '[W zeszłą sobotę o] LT';
                    default:
                        return '[W zeszły] dddd [o] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: '%s temu',
            s: 'kilka sekund',
            m: pl__translate,
            mm: pl__translate,
            h: pl__translate,
            hh: pl__translate,
            d: '1 dzień',
            dd: '%d dni',
            M: 'miesiąc',
            MM: pl__translate,
            y: 'rok',
            yy: pl__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : brazilian portuguese (pt-br)
    //! author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira

    var pt_br = _moment__default.defineLocale('pt-br', {
        months: 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'),
        monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),
        weekdays: 'Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado'.split('_'),
        weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
        weekdaysMin: 'Dom_2ª_3ª_4ª_5ª_6ª_Sáb'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY [às] HH:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY [às] HH:mm'
        },
        calendar: {
            sameDay: '[Hoje às] LT',
            nextDay: '[Amanhã às] LT',
            nextWeek: 'dddd [às] LT',
            lastDay: '[Ontem às] LT',
            lastWeek: function () {
                return (this.day() === 0 || this.day() === 6) ?
                    '[Último] dddd [às] LT' : // Saturday + Sunday
                    '[Última] dddd [às] LT'; // Monday - Friday
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'em %s',
            past: '%s atrás',
            s: 'poucos segundos',
            m: 'um minuto',
            mm: '%d minutos',
            h: 'uma hora',
            hh: '%d horas',
            d: 'um dia',
            dd: '%d dias',
            M: 'um mês',
            MM: '%d meses',
            y: 'um ano',
            yy: '%d anos'
        },
        ordinalParse: /\d{1,2}º/,
        ordinal: '%dº'
    });

    //! moment.js locale configuration
    //! locale : portuguese (pt)
    //! author : Jefferson : https://github.com/jalex79

    var pt = _moment__default.defineLocale('pt', {
        months: 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'),
        monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),
        weekdays: 'Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado'.split('_'),
        weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
        weekdaysMin: 'Dom_2ª_3ª_4ª_5ª_6ª_Sáb'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY HH:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Hoje às] LT',
            nextDay: '[Amanhã às] LT',
            nextWeek: 'dddd [às] LT',
            lastDay: '[Ontem às] LT',
            lastWeek: function () {
                return (this.day() === 0 || this.day() === 6) ?
                    '[Último] dddd [às] LT' : // Saturday + Sunday
                    '[Última] dddd [às] LT'; // Monday - Friday
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'em %s',
            past: 'há %s',
            s: 'segundos',
            m: 'um minuto',
            mm: '%d minutos',
            h: 'uma hora',
            hh: '%d horas',
            d: 'um dia',
            dd: '%d dias',
            M: 'um mês',
            MM: '%d meses',
            y: 'um ano',
            yy: '%d anos'
        },
        ordinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : romanian (ro)
    //! author : Vlad Gurdiga : https://github.com/gurdiga
    //! author : Valentin Agachi : https://github.com/avaly

    function ro__relativeTimeWithPlural(number, withoutSuffix, key) {
        var format = {
            'mm': 'minute',
            'hh': 'ore',
            'dd': 'zile',
            'MM': 'luni',
            'yy': 'ani'
        },
            separator = ' ';
        if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) {
            separator = ' de ';
        }
        return number + separator + format[key];
    }

    var ro = _moment__default.defineLocale('ro', {
        months: 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'),
        monthsShort: 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'),
        weekdays: 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'),
        weekdaysShort: 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'),
        weekdaysMin: 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd, D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[azi la] LT',
            nextDay: '[mâine la] LT',
            nextWeek: 'dddd [la] LT',
            lastDay: '[ieri la] LT',
            lastWeek: '[fosta] dddd [la] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'peste %s',
            past: '%s în urmă',
            s: 'câteva secunde',
            m: 'un minut',
            mm: ro__relativeTimeWithPlural,
            h: 'o oră',
            hh: ro__relativeTimeWithPlural,
            d: 'o zi',
            dd: ro__relativeTimeWithPlural,
            M: 'o lună',
            MM: ro__relativeTimeWithPlural,
            y: 'un an',
            yy: ro__relativeTimeWithPlural
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : russian (ru)
    //! author : Viktorminator : https://github.com/Viktorminator
    //! Author : Menelion Elensúle : https://github.com/Oire

    function ru__plural(word, num) {
        var forms = word.split('_');
        return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
    }
    function ru__relativeTimeWithPlural(number, withoutSuffix, key) {
        var format = {
            'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут',
            'hh': 'час_часа_часов',
            'dd': 'день_дня_дней',
            'MM': 'месяц_месяца_месяцев',
            'yy': 'год_года_лет'
        };
        if (key === 'm') {
            return withoutSuffix ? 'минута' : 'минуту';
        }
        else {
            return number + ' ' + ru__plural(format[key], +number);
        }
    }
    function ru__monthsCaseReplace(m, format) {
        var months = {
            'nominative': 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
            'accusative': 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_')
        },
        nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
            'accusative' :
            'nominative';
        return months[nounCase][m.month()];
    }
    function ru__monthsShortCaseReplace(m, format) {
        var monthsShort = {
            'nominative': 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),
            'accusative': 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_')
        },
        nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
            'accusative' :
            'nominative';
        return monthsShort[nounCase][m.month()];
    }
    function ru__weekdaysCaseReplace(m, format) {
        var weekdays = {
            'nominative': 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'),
            'accusative': 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_')
        },
        nounCase = (/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/).test(format) ?
            'accusative' :
            'nominative';
        return weekdays[nounCase][m.day()];
    }

    var ru = _moment__default.defineLocale('ru', {
        months: ru__monthsCaseReplace,
        monthsShort: ru__monthsShortCaseReplace,
        weekdays: ru__weekdaysCaseReplace,
        weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
        weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
        monthsParse: [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[й|я]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i],
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY г.',
            LLL: 'D MMMM YYYY г., HH:mm',
            LLLL: 'dddd, D MMMM YYYY г., HH:mm'
        },
        calendar: {
            sameDay: '[Сегодня в] LT',
            nextDay: '[Завтра в] LT',
            lastDay: '[Вчера в] LT',
            nextWeek: function () {
                return this.day() === 2 ? '[Во] dddd [в] LT' : '[В] dddd [в] LT';
            },
            lastWeek: function (now) {
                if (now.week() !== this.week()) {
                    switch (this.day()) {
                        case 0:
                            return '[В прошлое] dddd [в] LT';
                        case 1:
                        case 2:
                        case 4:
                            return '[В прошлый] dddd [в] LT';
                        case 3:
                        case 5:
                        case 6:
                            return '[В прошлую] dddd [в] LT';
                    }
                } else {
                    if (this.day() === 2) {
                        return '[Во] dddd [в] LT';
                    } else {
                        return '[В] dddd [в] LT';
                    }
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'через %s',
            past: '%s назад',
            s: 'несколько секунд',
            m: ru__relativeTimeWithPlural,
            mm: ru__relativeTimeWithPlural,
            h: 'час',
            hh: ru__relativeTimeWithPlural,
            d: 'день',
            dd: ru__relativeTimeWithPlural,
            M: 'месяц',
            MM: ru__relativeTimeWithPlural,
            y: 'год',
            yy: ru__relativeTimeWithPlural
        },
        meridiemParse: /ночи|утра|дня|вечера/i,
        isPM: function (input) {
            return /^(дня|вечера)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ночи';
            } else if (hour < 12) {
                return 'утра';
            } else if (hour < 17) {
                return 'дня';
            } else {
                return 'вечера';
            }
        },
        ordinalParse: /\d{1,2}-(й|го|я)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'M':
                case 'd':
                case 'DDD':
                    return number + '-й';
                case 'D':
                    return number + '-го';
                case 'w':
                case 'W':
                    return number + '-я';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Sinhalese (si)
    //! author : Sampath Sitinamaluwa : https://github.com/sampathsris

    var si = _moment__default.defineLocale('si', {
        months: 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'),
        monthsShort: 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'),
        weekdays: 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'),
        weekdaysShort: 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'),
        weekdaysMin: 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'),
        longDateFormat: {
            LT: 'a h:mm',
            LTS: 'a h:mm:ss',
            L: 'YYYY/MM/DD',
            LL: 'YYYY MMMM D',
            LLL: 'YYYY MMMM D, a h:mm',
            LLLL: 'YYYY MMMM D [වැනි] dddd, a h:mm:ss'
        },
        calendar: {
            sameDay: '[අද] LT[ට]',
            nextDay: '[හෙට] LT[ට]',
            nextWeek: 'dddd LT[ට]',
            lastDay: '[ඊයේ] LT[ට]',
            lastWeek: '[පසුගිය] dddd LT[ට]',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%sකින්',
            past: '%sකට පෙර',
            s: 'තත්පර කිහිපය',
            m: 'මිනිත්තුව',
            mm: 'මිනිත්තු %d',
            h: 'පැය',
            hh: 'පැය %d',
            d: 'දිනය',
            dd: 'දින %d',
            M: 'මාසය',
            MM: 'මාස %d',
            y: 'වසර',
            yy: 'වසර %d'
        },
        ordinalParse: /\d{1,2} වැනි/,
        ordinal: function (number) {
            return number + ' වැනි';
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'ප.ව.' : 'පස් වරු';
            } else {
                return isLower ? 'පෙ.ව.' : 'පෙර වරු';
            }
        }
    });

    //! moment.js locale configuration
    //! locale : slovak (sk)
    //! author : Martin Minka : https://github.com/k2s
    //! based on work of petrbela : https://github.com/petrbela

    var sk__months = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'),
        sk__monthsShort = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_');
    function sk__plural(n) {
        return (n > 1) && (n < 5);
    }
    function sk__translate(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':  // a few seconds / in a few seconds / a few seconds ago
                return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami';
            case 'm':  // a minute / in a minute / a minute ago
                return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou');
            case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
                if (withoutSuffix || isFuture) {
                    return result + (sk__plural(number) ? 'minúty' : 'minút');
                } else {
                    return result + 'minútami';
                }
                break;
            case 'h':  // an hour / in an hour / an hour ago
                return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
            case 'hh': // 9 hours / in 9 hours / 9 hours ago
                if (withoutSuffix || isFuture) {
                    return result + (sk__plural(number) ? 'hodiny' : 'hodín');
                } else {
                    return result + 'hodinami';
                }
                break;
            case 'd':  // a day / in a day / a day ago
                return (withoutSuffix || isFuture) ? 'deň' : 'dňom';
            case 'dd': // 9 days / in 9 days / 9 days ago
                if (withoutSuffix || isFuture) {
                    return result + (sk__plural(number) ? 'dni' : 'dní');
                } else {
                    return result + 'dňami';
                }
                break;
            case 'M':  // a month / in a month / a month ago
                return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom';
            case 'MM': // 9 months / in 9 months / 9 months ago
                if (withoutSuffix || isFuture) {
                    return result + (sk__plural(number) ? 'mesiace' : 'mesiacov');
                } else {
                    return result + 'mesiacmi';
                }
                break;
            case 'y':  // a year / in a year / a year ago
                return (withoutSuffix || isFuture) ? 'rok' : 'rokom';
            case 'yy': // 9 years / in 9 years / 9 years ago
                if (withoutSuffix || isFuture) {
                    return result + (sk__plural(number) ? 'roky' : 'rokov');
                } else {
                    return result + 'rokmi';
                }
                break;
        }
    }

    var sk = _moment__default.defineLocale('sk', {
        months: sk__months,
        monthsShort: sk__monthsShort,
        monthsParse: (function (months, monthsShort) {
            var i, _monthsParse = [];
            for (i = 0; i < 12; i++) {
                // use custom parser to solve problem with July (červenec)
                _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i');
            }
            return _monthsParse;
        }(sk__months, sk__monthsShort)),
        weekdays: 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'),
        weekdaysShort: 'ne_po_ut_st_št_pi_so'.split('_'),
        weekdaysMin: 'ne_po_ut_st_št_pi_so'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[dnes o] LT',
            nextDay: '[zajtra o] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[v nedeľu o] LT';
                    case 1:
                    case 2:
                        return '[v] dddd [o] LT';
                    case 3:
                        return '[v stredu o] LT';
                    case 4:
                        return '[vo štvrtok o] LT';
                    case 5:
                        return '[v piatok o] LT';
                    case 6:
                        return '[v sobotu o] LT';
                }
            },
            lastDay: '[včera o] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[minulú nedeľu o] LT';
                    case 1:
                    case 2:
                        return '[minulý] dddd [o] LT';
                    case 3:
                        return '[minulú stredu o] LT';
                    case 4:
                    case 5:
                        return '[minulý] dddd [o] LT';
                    case 6:
                        return '[minulú sobotu o] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'pred %s',
            s: sk__translate,
            m: sk__translate,
            mm: sk__translate,
            h: sk__translate,
            hh: sk__translate,
            d: sk__translate,
            dd: sk__translate,
            M: sk__translate,
            MM: sk__translate,
            y: sk__translate,
            yy: sk__translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : slovenian (sl)
    //! author : Robert Sedovšek : https://github.com/sedovsek

    function sl__processRelativeTime(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':
                return withoutSuffix || isFuture ? 'nekaj sekund' : 'nekaj sekundami';
            case 'm':
                return withoutSuffix ? 'ena minuta' : 'eno minuto';
            case 'mm':
                if (number === 1) {
                    result += withoutSuffix ? 'minuta' : 'minuto';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'minuti' : 'minutama';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'minute' : 'minutami';
                } else {
                    result += withoutSuffix || isFuture ? 'minut' : 'minutami';
                }
                return result;
            case 'h':
                return withoutSuffix ? 'ena ura' : 'eno uro';
            case 'hh':
                if (number === 1) {
                    result += withoutSuffix ? 'ura' : 'uro';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'uri' : 'urama';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'ure' : 'urami';
                } else {
                    result += withoutSuffix || isFuture ? 'ur' : 'urami';
                }
                return result;
            case 'd':
                return withoutSuffix || isFuture ? 'en dan' : 'enim dnem';
            case 'dd':
                if (number === 1) {
                    result += withoutSuffix || isFuture ? 'dan' : 'dnem';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'dni' : 'dnevoma';
                } else {
                    result += withoutSuffix || isFuture ? 'dni' : 'dnevi';
                }
                return result;
            case 'M':
                return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem';
            case 'MM':
                if (number === 1) {
                    result += withoutSuffix || isFuture ? 'mesec' : 'mesecem';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'meseca' : 'mesecema';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'mesece' : 'meseci';
                } else {
                    result += withoutSuffix || isFuture ? 'mesecev' : 'meseci';
                }
                return result;
            case 'y':
                return withoutSuffix || isFuture ? 'eno leto' : 'enim letom';
            case 'yy':
                if (number === 1) {
                    result += withoutSuffix || isFuture ? 'leto' : 'letom';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'leti' : 'letoma';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'leta' : 'leti';
                } else {
                    result += withoutSuffix || isFuture ? 'let' : 'leti';
                }
                return result;
        }
    }

    var sl = _moment__default.defineLocale('sl', {
        months: 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'),
        monthsShort: 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'),
        weekdays: 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'),
        weekdaysShort: 'ned._pon._tor._sre._čet._pet._sob.'.split('_'),
        weekdaysMin: 'ne_po_to_sr_če_pe_so'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD. MM. YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danes ob] LT',
            nextDay: '[jutri ob] LT',

            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[v] [nedeljo] [ob] LT';
                    case 3:
                        return '[v] [sredo] [ob] LT';
                    case 6:
                        return '[v] [soboto] [ob] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[v] dddd [ob] LT';
                }
            },
            lastDay: '[včeraj ob] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[prejšnjo] [nedeljo] [ob] LT';
                    case 3:
                        return '[prejšnjo] [sredo] [ob] LT';
                    case 6:
                        return '[prejšnjo] [soboto] [ob] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[prejšnji] dddd [ob] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'čez %s',
            past: 'pred %s',
            s: sl__processRelativeTime,
            m: sl__processRelativeTime,
            mm: sl__processRelativeTime,
            h: sl__processRelativeTime,
            hh: sl__processRelativeTime,
            d: sl__processRelativeTime,
            dd: sl__processRelativeTime,
            M: sl__processRelativeTime,
            MM: sl__processRelativeTime,
            y: sl__processRelativeTime,
            yy: sl__processRelativeTime
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Albanian (sq)
    //! author : Flakërim Ismani : https://github.com/flakerimi
    //! author: Menelion Elensúle: https://github.com/Oire (tests)
    //! author : Oerd Cukalla : https://github.com/oerd (fixes)

    var sq = _moment__default.defineLocale('sq', {
        months: 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'),
        monthsShort: 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'),
        weekdays: 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'),
        weekdaysShort: 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'),
        weekdaysMin: 'D_H_Ma_Më_E_P_Sh'.split('_'),
        meridiemParse: /PD|MD/,
        isPM: function (input) {
            return input.charAt(0) === 'M';
        },
        meridiem: function (hours, minutes, isLower) {
            return hours < 12 ? 'PD' : 'MD';
        },
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Sot në] LT',
            nextDay: '[Nesër në] LT',
            nextWeek: 'dddd [në] LT',
            lastDay: '[Dje në] LT',
            lastWeek: 'dddd [e kaluar në] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'në %s',
            past: '%s më parë',
            s: 'disa sekonda',
            m: 'një minutë',
            mm: '%d minuta',
            h: 'një orë',
            hh: '%d orë',
            d: 'një ditë',
            dd: '%d ditë',
            M: 'një muaj',
            MM: '%d muaj',
            y: 'një vit',
            yy: '%d vite'
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Serbian-cyrillic (sr-cyrl)
    //! author : Milan Janačković<milanjanackovic@gmail.com> : https://github.com/milan-j

    var sr_cyrl__translator = {
        words: { //Different grammatical cases
            m: ['један минут', 'једне минуте'],
            mm: ['минут', 'минуте', 'минута'],
            h: ['један сат', 'једног сата'],
            hh: ['сат', 'сата', 'сати'],
            dd: ['дан', 'дана', 'дана'],
            MM: ['месец', 'месеца', 'месеци'],
            yy: ['година', 'године', 'година']
        },
        correctGrammaticalCase: function (number, wordKey) {
            return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
        },
        translate: function (number, withoutSuffix, key) {
            var wordKey = sr_cyrl__translator.words[key];
            if (key.length === 1) {
                return withoutSuffix ? wordKey[0] : wordKey[1];
            } else {
                return number + ' ' + sr_cyrl__translator.correctGrammaticalCase(number, wordKey);
            }
        }
    };

    var sr_cyrl = _moment__default.defineLocale('sr-cyrl', {
        months: ['јануар', 'фебруар', 'март', 'април', 'мај', 'јун', 'јул', 'август', 'септембар', 'октобар', 'новембар', 'децембар'],
        monthsShort: ['јан.', 'феб.', 'мар.', 'апр.', 'мај', 'јун', 'јул', 'авг.', 'сеп.', 'окт.', 'нов.', 'дец.'],
        weekdays: ['недеља', 'понедељак', 'уторак', 'среда', 'четвртак', 'петак', 'субота'],
        weekdaysShort: ['нед.', 'пон.', 'уто.', 'сре.', 'чет.', 'пет.', 'суб.'],
        weekdaysMin: ['не', 'по', 'ут', 'ср', 'че', 'пе', 'су'],
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD. MM. YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[данас у] LT',
            nextDay: '[сутра у] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[у] [недељу] [у] LT';
                    case 3:
                        return '[у] [среду] [у] LT';
                    case 6:
                        return '[у] [суботу] [у] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[у] dddd [у] LT';
                }
            },
            lastDay: '[јуче у] LT',
            lastWeek: function () {
                var lastWeekDays = [
                    '[прошле] [недеље] [у] LT',
                    '[прошлог] [понедељка] [у] LT',
                    '[прошлог] [уторка] [у] LT',
                    '[прошле] [среде] [у] LT',
                    '[прошлог] [четвртка] [у] LT',
                    '[прошлог] [петка] [у] LT',
                    '[прошле] [суботе] [у] LT'
                ];
                return lastWeekDays[this.day()];
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'за %s',
            past: 'пре %s',
            s: 'неколико секунди',
            m: sr_cyrl__translator.translate,
            mm: sr_cyrl__translator.translate,
            h: sr_cyrl__translator.translate,
            hh: sr_cyrl__translator.translate,
            d: 'дан',
            dd: sr_cyrl__translator.translate,
            M: 'месец',
            MM: sr_cyrl__translator.translate,
            y: 'годину',
            yy: sr_cyrl__translator.translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Serbian-latin (sr)
    //! author : Milan Janačković<milanjanackovic@gmail.com> : https://github.com/milan-j

    var sr__translator = {
        words: { //Different grammatical cases
            m: ['jedan minut', 'jedne minute'],
            mm: ['minut', 'minute', 'minuta'],
            h: ['jedan sat', 'jednog sata'],
            hh: ['sat', 'sata', 'sati'],
            dd: ['dan', 'dana', 'dana'],
            MM: ['mesec', 'meseca', 'meseci'],
            yy: ['godina', 'godine', 'godina']
        },
        correctGrammaticalCase: function (number, wordKey) {
            return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
        },
        translate: function (number, withoutSuffix, key) {
            var wordKey = sr__translator.words[key];
            if (key.length === 1) {
                return withoutSuffix ? wordKey[0] : wordKey[1];
            } else {
                return number + ' ' + sr__translator.correctGrammaticalCase(number, wordKey);
            }
        }
    };

    var sr = _moment__default.defineLocale('sr', {
        months: ['januar', 'februar', 'mart', 'april', 'maj', 'jun', 'jul', 'avgust', 'septembar', 'oktobar', 'novembar', 'decembar'],
        monthsShort: ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun', 'jul', 'avg.', 'sep.', 'okt.', 'nov.', 'dec.'],
        weekdays: ['nedelja', 'ponedeljak', 'utorak', 'sreda', 'četvrtak', 'petak', 'subota'],
        weekdaysShort: ['ned.', 'pon.', 'uto.', 'sre.', 'čet.', 'pet.', 'sub.'],
        weekdaysMin: ['ne', 'po', 'ut', 'sr', 'če', 'pe', 'su'],
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD. MM. YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sutra u] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedelju] [u] LT';
                    case 3:
                        return '[u] [sredu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[juče u] LT',
            lastWeek: function () {
                var lastWeekDays = [
                    '[prošle] [nedelje] [u] LT',
                    '[prošlog] [ponedeljka] [u] LT',
                    '[prošlog] [utorka] [u] LT',
                    '[prošle] [srede] [u] LT',
                    '[prošlog] [četvrtka] [u] LT',
                    '[prošlog] [petka] [u] LT',
                    '[prošle] [subote] [u] LT'
                ];
                return lastWeekDays[this.day()];
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'pre %s',
            s: 'nekoliko sekundi',
            m: sr__translator.translate,
            mm: sr__translator.translate,
            h: sr__translator.translate,
            hh: sr__translator.translate,
            d: 'dan',
            dd: sr__translator.translate,
            M: 'mesec',
            MM: sr__translator.translate,
            y: 'godinu',
            yy: sr__translator.translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : swedish (sv)
    //! author : Jens Alm : https://github.com/ulmus

    var sv = _moment__default.defineLocale('sv', {
        months: 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),
        weekdays: 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'),
        weekdaysShort: 'sön_mån_tis_ons_tor_fre_lör'.split('_'),
        weekdaysMin: 'sö_må_ti_on_to_fr_lö'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Idag] LT',
            nextDay: '[Imorgon] LT',
            lastDay: '[Igår] LT',
            nextWeek: '[På] dddd LT',
            lastWeek: '[I] dddd[s] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: 'för %s sedan',
            s: 'några sekunder',
            m: 'en minut',
            mm: '%d minuter',
            h: 'en timme',
            hh: '%d timmar',
            d: 'en dag',
            dd: '%d dagar',
            M: 'en månad',
            MM: '%d månader',
            y: 'ett år',
            yy: '%d år'
        },
        ordinalParse: /\d{1,2}(e|a)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'e' :
                (b === 1) ? 'a' :
                (b === 2) ? 'a' :
                (b === 3) ? 'e' : 'e';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : tamil (ta)
    //! author : Arjunkumar Krishnamoorthy : https://github.com/tk120404

    var ta = _moment__default.defineLocale('ta', {
        months: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
        monthsShort: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
        weekdays: 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'),
        weekdaysShort: 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'),
        weekdaysMin: 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, HH:mm',
            LLLL: 'dddd, D MMMM YYYY, HH:mm'
        },
        calendar: {
            sameDay: '[இன்று] LT',
            nextDay: '[நாளை] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[நேற்று] LT',
            lastWeek: '[கடந்த வாரம்] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s இல்',
            past: '%s முன்',
            s: 'ஒரு சில விநாடிகள்',
            m: 'ஒரு நிமிடம்',
            mm: '%d நிமிடங்கள்',
            h: 'ஒரு மணி நேரம்',
            hh: '%d மணி நேரம்',
            d: 'ஒரு நாள்',
            dd: '%d நாட்கள்',
            M: 'ஒரு மாதம்',
            MM: '%d மாதங்கள்',
            y: 'ஒரு வருடம்',
            yy: '%d ஆண்டுகள்'
        },
        ordinalParse: /\d{1,2}வது/,
        ordinal: function (number) {
            return number + 'வது';
        },
        // refer http://ta.wikipedia.org/s/1er1
        meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,
        meridiem: function (hour, minute, isLower) {
            if (hour < 2) {
                return ' யாமம்';
            } else if (hour < 6) {
                return ' வைகறை';  // வைகறை
            } else if (hour < 10) {
                return ' காலை'; // காலை
            } else if (hour < 14) {
                return ' நண்பகல்'; // நண்பகல்
            } else if (hour < 18) {
                return ' எற்பாடு'; // எற்பாடு
            } else if (hour < 22) {
                return ' மாலை'; // மாலை
            } else {
                return ' யாமம்';
            }
        },
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'யாமம்') {
                return hour < 2 ? hour : hour + 12;
            } else if (meridiem === 'வைகறை' || meridiem === 'காலை') {
                return hour;
            } else if (meridiem === 'நண்பகல்') {
                return hour >= 10 ? hour : hour + 12;
            } else {
                return hour + 12;
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : thai (th)
    //! author : Kridsada Thanabulpong : https://github.com/sirn

    var th = _moment__default.defineLocale('th', {
        months: 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'),
        monthsShort: 'มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา'.split('_'),
        weekdays: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),
        weekdaysShort: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference
        weekdaysMin: 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'),
        longDateFormat: {
            LT: 'H นาฬิกา m นาที',
            LTS: 'H นาฬิกา m นาที s วินาที',
            L: 'YYYY/MM/DD',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY เวลา H นาฬิกา m นาที',
            LLLL: 'วันddddที่ D MMMM YYYY เวลา H นาฬิกา m นาที'
        },
        meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/,
        isPM: function (input) {
            return input === 'หลังเที่ยง';
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ก่อนเที่ยง';
            } else {
                return 'หลังเที่ยง';
            }
        },
        calendar: {
            sameDay: '[วันนี้ เวลา] LT',
            nextDay: '[พรุ่งนี้ เวลา] LT',
            nextWeek: 'dddd[หน้า เวลา] LT',
            lastDay: '[เมื่อวานนี้ เวลา] LT',
            lastWeek: '[วัน]dddd[ที่แล้ว เวลา] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'อีก %s',
            past: '%sที่แล้ว',
            s: 'ไม่กี่วินาที',
            m: '1 นาที',
            mm: '%d นาที',
            h: '1 ชั่วโมง',
            hh: '%d ชั่วโมง',
            d: '1 วัน',
            dd: '%d วัน',
            M: '1 เดือน',
            MM: '%d เดือน',
            y: '1 ปี',
            yy: '%d ปี'
        }
    });

    //! moment.js locale configuration
    //! locale : Tagalog/Filipino (tl-ph)
    //! author : Dan Hagman

    var tl_ph = _moment__default.defineLocale('tl-ph', {
        months: 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'),
        monthsShort: 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'),
        weekdays: 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'),
        weekdaysShort: 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'),
        weekdaysMin: 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'MM/D/YYYY',
            LL: 'MMMM D, YYYY',
            LLL: 'MMMM D, YYYY HH:mm',
            LLLL: 'dddd, MMMM DD, YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Ngayon sa] LT',
            nextDay: '[Bukas sa] LT',
            nextWeek: 'dddd [sa] LT',
            lastDay: '[Kahapon sa] LT',
            lastWeek: 'dddd [huling linggo] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'sa loob ng %s',
            past: '%s ang nakalipas',
            s: 'ilang segundo',
            m: 'isang minuto',
            mm: '%d minuto',
            h: 'isang oras',
            hh: '%d oras',
            d: 'isang araw',
            dd: '%d araw',
            M: 'isang buwan',
            MM: '%d buwan',
            y: 'isang taon',
            yy: '%d taon'
        },
        ordinalParse: /\d{1,2}/,
        ordinal: function (number) {
            return number;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : turkish (tr)
    //! authors : Erhan Gundogan : https://github.com/erhangundogan,
    //!           Burak Yiğit Kaya: https://github.com/BYK

    var tr__suffixes = {
        1: '\'inci',
        5: '\'inci',
        8: '\'inci',
        70: '\'inci',
        80: '\'inci',
        2: '\'nci',
        7: '\'nci',
        20: '\'nci',
        50: '\'nci',
        3: '\'üncü',
        4: '\'üncü',
        100: '\'üncü',
        6: '\'ncı',
        9: '\'uncu',
        10: '\'uncu',
        30: '\'uncu',
        60: '\'ıncı',
        90: '\'ıncı'
    };

    var tr = _moment__default.defineLocale('tr', {
        months: 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'),
        monthsShort: 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'),
        weekdays: 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'),
        weekdaysShort: 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'),
        weekdaysMin: 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[bugün saat] LT',
            nextDay: '[yarın saat] LT',
            nextWeek: '[haftaya] dddd [saat] LT',
            lastDay: '[dün] LT',
            lastWeek: '[geçen hafta] dddd [saat] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s sonra',
            past: '%s önce',
            s: 'birkaç saniye',
            m: 'bir dakika',
            mm: '%d dakika',
            h: 'bir saat',
            hh: '%d saat',
            d: 'bir gün',
            dd: '%d gün',
            M: 'bir ay',
            MM: '%d ay',
            y: 'bir yıl',
            yy: '%d yıl'
        },
        ordinalParse: /\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/,
        ordinal: function (number) {
            if (number === 0) {  // special case for zero
                return number + '\'ıncı';
            }
            var a = number % 10,
                b = number % 100 - a,
                c = number >= 100 ? 100 : null;
            return number + (tr__suffixes[a] || tr__suffixes[b] || tr__suffixes[c]);
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : talossan (tzl)
    //! author : Robin van der Vliet : https://github.com/robin0van0der0v with the help of Iustì Canun


    var tzl = _moment__default.defineLocale('tzl', {
        months: 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'),
        monthsShort: 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'),
        weekdays: 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'),
        weekdaysShort: 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'),
        weekdaysMin: 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'LT.ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM [dallas] YYYY',
            LLL: 'D. MMMM [dallas] YYYY LT',
            LLLL: 'dddd, [li] D. MMMM [dallas] YYYY LT'
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'd\'o' : 'D\'O';
            } else {
                return isLower ? 'd\'a' : 'D\'A';
            }
        },
        calendar: {
            sameDay: '[oxhi à] LT',
            nextDay: '[demà à] LT',
            nextWeek: 'dddd [à] LT',
            lastDay: '[ieiri à] LT',
            lastWeek: '[sür el] dddd [lasteu à] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'osprei %s',
            past: 'ja%s',
            s: tzl__processRelativeTime,
            m: tzl__processRelativeTime,
            mm: tzl__processRelativeTime,
            h: tzl__processRelativeTime,
            hh: tzl__processRelativeTime,
            d: tzl__processRelativeTime,
            dd: tzl__processRelativeTime,
            M: tzl__processRelativeTime,
            MM: tzl__processRelativeTime,
            y: tzl__processRelativeTime,
            yy: tzl__processRelativeTime
        },
        ordinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    function tzl__processRelativeTime(number, withoutSuffix, key, isFuture) {
        var format = {
            's': ['viensas secunds', '\'iensas secunds'],
            'm': ['\'n míut', '\'iens míut'],
            'mm': [number + ' míuts', ' ' + number + ' míuts'],
            'h': ['\'n þora', '\'iensa þora'],
            'hh': [number + ' þoras', ' ' + number + ' þoras'],
            'd': ['\'n ziua', '\'iensa ziua'],
            'dd': [number + ' ziuas', ' ' + number + ' ziuas'],
            'M': ['\'n mes', '\'iens mes'],
            'MM': [number + ' mesen', ' ' + number + ' mesen'],
            'y': ['\'n ar', '\'iens ar'],
            'yy': [number + ' ars', ' ' + number + ' ars']
        };
        return isFuture ? format[key][0] : (withoutSuffix ? format[key][0] : format[key][1].trim());
    }

    //! moment.js locale configuration
    //! locale : Morocco Central Atlas Tamaziɣt in Latin (tzm-latn)
    //! author : Abdel Said : https://github.com/abdelsaid

    var tzm_latn = _moment__default.defineLocale('tzm-latn', {
        months: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),
        monthsShort: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),
        weekdays: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
        weekdaysShort: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
        weekdaysMin: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[asdkh g] LT',
            nextDay: '[aska g] LT',
            nextWeek: 'dddd [g] LT',
            lastDay: '[assant g] LT',
            lastWeek: 'dddd [g] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dadkh s yan %s',
            past: 'yan %s',
            s: 'imik',
            m: 'minuḍ',
            mm: '%d minuḍ',
            h: 'saɛa',
            hh: '%d tassaɛin',
            d: 'ass',
            dd: '%d ossan',
            M: 'ayowr',
            MM: '%d iyyirn',
            y: 'asgas',
            yy: '%d isgasn'
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : Morocco Central Atlas Tamaziɣt (tzm)
    //! author : Abdel Said : https://github.com/abdelsaid

    var tzm = _moment__default.defineLocale('tzm', {
        months: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
        monthsShort: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
        weekdays: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
        weekdaysShort: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
        weekdaysMin: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[ⴰⵙⴷⵅ ⴴ] LT',
            nextDay: '[ⴰⵙⴽⴰ ⴴ] LT',
            nextWeek: 'dddd [ⴴ] LT',
            lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT',
            lastWeek: 'dddd [ⴴ] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s',
            past: 'ⵢⴰⵏ %s',
            s: 'ⵉⵎⵉⴽ',
            m: 'ⵎⵉⵏⵓⴺ',
            mm: '%d ⵎⵉⵏⵓⴺ',
            h: 'ⵙⴰⵄⴰ',
            hh: '%d ⵜⴰⵙⵙⴰⵄⵉⵏ',
            d: 'ⴰⵙⵙ',
            dd: '%d oⵙⵙⴰⵏ',
            M: 'ⴰⵢoⵓⵔ',
            MM: '%d ⵉⵢⵢⵉⵔⵏ',
            y: 'ⴰⵙⴳⴰⵙ',
            yy: '%d ⵉⵙⴳⴰⵙⵏ'
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : ukrainian (uk)
    //! author : zemlanin : https://github.com/zemlanin
    //! Author : Menelion Elensúle : https://github.com/Oire

    function uk__plural(word, num) {
        var forms = word.split('_');
        return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
    }
    function uk__relativeTimeWithPlural(number, withoutSuffix, key) {
        var format = {
            'mm': 'хвилина_хвилини_хвилин',
            'hh': 'година_години_годин',
            'dd': 'день_дні_днів',
            'MM': 'місяць_місяці_місяців',
            'yy': 'рік_роки_років'
        };
        if (key === 'm') {
            return withoutSuffix ? 'хвилина' : 'хвилину';
        }
        else if (key === 'h') {
            return withoutSuffix ? 'година' : 'годину';
        }
        else {
            return number + ' ' + uk__plural(format[key], +number);
        }
    }
    function uk__monthsCaseReplace(m, format) {
        var months = {
            'nominative': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_'),
            'accusative': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_')
        },
        nounCase = (/D[oD]? *MMMM?/).test(format) ?
            'accusative' :
            'nominative';
        return months[nounCase][m.month()];
    }
    function uk__weekdaysCaseReplace(m, format) {
        var weekdays = {
            'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'),
            'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'),
            'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_')
        },
        nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ?
            'accusative' :
            ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ?
                'genitive' :
                'nominative');
        return weekdays[nounCase][m.day()];
    }
    function processHoursFunction(str) {
        return function () {
            return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT';
        };
    }

    var uk = _moment__default.defineLocale('uk', {
        months: uk__monthsCaseReplace,
        monthsShort: 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'),
        weekdays: uk__weekdaysCaseReplace,
        weekdaysShort: 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
        weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY р.',
            LLL: 'D MMMM YYYY р., HH:mm',
            LLLL: 'dddd, D MMMM YYYY р., HH:mm'
        },
        calendar: {
            sameDay: processHoursFunction('[Сьогодні '),
            nextDay: processHoursFunction('[Завтра '),
            lastDay: processHoursFunction('[Вчора '),
            nextWeek: processHoursFunction('[У] dddd ['),
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 5:
                    case 6:
                        return processHoursFunction('[Минулої] dddd [').call(this);
                    case 1:
                    case 2:
                    case 4:
                        return processHoursFunction('[Минулого] dddd [').call(this);
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'за %s',
            past: '%s тому',
            s: 'декілька секунд',
            m: uk__relativeTimeWithPlural,
            mm: uk__relativeTimeWithPlural,
            h: 'годину',
            hh: uk__relativeTimeWithPlural,
            d: 'день',
            dd: uk__relativeTimeWithPlural,
            M: 'місяць',
            MM: uk__relativeTimeWithPlural,
            y: 'рік',
            yy: uk__relativeTimeWithPlural
        },
        // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason
        meridiemParse: /ночі|ранку|дня|вечора/,
        isPM: function (input) {
            return /^(дня|вечора)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ночі';
            } else if (hour < 12) {
                return 'ранку';
            } else if (hour < 17) {
                return 'дня';
            } else {
                return 'вечора';
            }
        },
        ordinalParse: /\d{1,2}-(й|го)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'M':
                case 'd':
                case 'DDD':
                case 'w':
                case 'W':
                    return number + '-й';
                case 'D':
                    return number + '-го';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : uzbek (uz)
    //! author : Sardor Muminov : https://github.com/muminoff

    var uz = _moment__default.defineLocale('uz', {
        months: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
        monthsShort: 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'),
        weekdays: 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'),
        weekdaysShort: 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'),
        weekdaysMin: 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'D MMMM YYYY, dddd HH:mm'
        },
        calendar: {
            sameDay: '[Бугун соат] LT [да]',
            nextDay: '[Эртага] LT [да]',
            nextWeek: 'dddd [куни соат] LT [да]',
            lastDay: '[Кеча соат] LT [да]',
            lastWeek: '[Утган] dddd [куни соат] LT [да]',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'Якин %s ичида',
            past: 'Бир неча %s олдин',
            s: 'фурсат',
            m: 'бир дакика',
            mm: '%d дакика',
            h: 'бир соат',
            hh: '%d соат',
            d: 'бир кун',
            dd: '%d кун',
            M: 'бир ой',
            MM: '%d ой',
            y: 'бир йил',
            yy: '%d йил'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : vietnamese (vi)
    //! author : Bang Nguyen : https://github.com/bangnk

    var vi = _moment__default.defineLocale('vi', {
        months: 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'),
        monthsShort: 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'),
        weekdays: 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'),
        weekdaysShort: 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
        weekdaysMin: 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM [năm] YYYY',
            LLL: 'D MMMM [năm] YYYY HH:mm',
            LLLL: 'dddd, D MMMM [năm] YYYY HH:mm',
            l: 'DD/M/YYYY',
            ll: 'D MMM YYYY',
            lll: 'D MMM YYYY HH:mm',
            llll: 'ddd, D MMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Hôm nay lúc] LT',
            nextDay: '[Ngày mai lúc] LT',
            nextWeek: 'dddd [tuần tới lúc] LT',
            lastDay: '[Hôm qua lúc] LT',
            lastWeek: 'dddd [tuần rồi lúc] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s tới',
            past: '%s trước',
            s: 'vài giây',
            m: 'một phút',
            mm: '%d phút',
            h: 'một giờ',
            hh: '%d giờ',
            d: 'một ngày',
            dd: '%d ngày',
            M: 'một tháng',
            MM: '%d tháng',
            y: 'một năm',
            yy: '%d năm'
        },
        ordinalParse: /\d{1,2}/,
        ordinal: function (number) {
            return number;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : chinese (zh-cn)
    //! author : suupic : https://github.com/suupic
    //! author : Zeno Zeng : https://github.com/zenozeng

    var zh_cn = _moment__default.defineLocale('zh-cn', {
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        longDateFormat: {
            LT: 'Ah点mm分',
            LTS: 'Ah点m分s秒',
            L: 'YYYY-MM-DD',
            LL: 'YYYY年MMMD日',
            LLL: 'YYYY年MMMD日Ah点mm分',
            LLLL: 'YYYY年MMMD日ddddAh点mm分',
            l: 'YYYY-MM-DD',
            ll: 'YYYY年MMMD日',
            lll: 'YYYY年MMMD日Ah点mm分',
            llll: 'YYYY年MMMD日ddddAh点mm分'
        },
        meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === '凌晨' || meridiem === '早上' ||
                    meridiem === '上午') {
                return hour;
            } else if (meridiem === '下午' || meridiem === '晚上') {
                return hour + 12;
            } else {
                // '中午'
                return hour >= 11 ? hour : hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 600) {
                return '凌晨';
            } else if (hm < 900) {
                return '早上';
            } else if (hm < 1130) {
                return '上午';
            } else if (hm < 1230) {
                return '中午';
            } else if (hm < 1800) {
                return '下午';
            } else {
                return '晚上';
            }
        },
        calendar: {
            sameDay: function () {
                return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT';
            },
            nextDay: function () {
                return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT';
            },
            lastDay: function () {
                return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT';
            },
            nextWeek: function () {
                var startOfWeek, prefix;
                startOfWeek = _moment__default().startOf('week');
                prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]';
                return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
            },
            lastWeek: function () {
                var startOfWeek, prefix;
                startOfWeek = _moment__default().startOf('week');
                prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]';
                return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
            },
            sameElse: 'LL'
        },
        ordinalParse: /\d{1,2}(日|月|周)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                case 'M':
                    return number + '月';
                case 'w':
                case 'W':
                    return number + '周';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s内',
            past: '%s前',
            s: '几秒',
            m: '1 分钟',
            mm: '%d 分钟',
            h: '1 小时',
            hh: '%d 小时',
            d: '1 天',
            dd: '%d 天',
            M: '1 个月',
            MM: '%d 个月',
            y: '1 年',
            yy: '%d 年'
        },
        week: {
            // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration
    //! locale : traditional chinese (zh-tw)
    //! author : Ben : https://github.com/ben-lin

    var zh_tw = _moment__default.defineLocale('zh-tw', {
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        longDateFormat: {
            LT: 'Ah點mm分',
            LTS: 'Ah點m分s秒',
            L: 'YYYY年MMMD日',
            LL: 'YYYY年MMMD日',
            LLL: 'YYYY年MMMD日Ah點mm分',
            LLLL: 'YYYY年MMMD日ddddAh點mm分',
            l: 'YYYY年MMMD日',
            ll: 'YYYY年MMMD日',
            lll: 'YYYY年MMMD日Ah點mm分',
            llll: 'YYYY年MMMD日ddddAh點mm分'
        },
        meridiemParse: /早上|上午|中午|下午|晚上/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === '早上' || meridiem === '上午') {
                return hour;
            } else if (meridiem === '中午') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === '下午' || meridiem === '晚上') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 900) {
                return '早上';
            } else if (hm < 1130) {
                return '上午';
            } else if (hm < 1230) {
                return '中午';
            } else if (hm < 1800) {
                return '下午';
            } else {
                return '晚上';
            }
        },
        calendar: {
            sameDay: '[今天]LT',
            nextDay: '[明天]LT',
            nextWeek: '[下]ddddLT',
            lastDay: '[昨天]LT',
            lastWeek: '[上]ddddLT',
            sameElse: 'L'
        },
        ordinalParse: /\d{1,2}(日|月|週)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                case 'M':
                    return number + '月';
                case 'w':
                case 'W':
                    return number + '週';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s內',
            past: '%s前',
            s: '幾秒',
            m: '一分鐘',
            mm: '%d分鐘',
            h: '一小時',
            hh: '%d小時',
            d: '一天',
            dd: '%d天',
            M: '一個月',
            MM: '%d個月',
            y: '一年',
            yy: '%d年'
        }
    });

    var moment_with_locales = _moment__default;
    moment_with_locales.locale('en');

    return moment_with_locales;

}));;
/**
 * findAndReplaceDOMText v 0.4.3
 * @author James Padolsey http://james.padolsey.com
 * @license http://unlicense.org/UNLICENSE
 *
 * Matches the text of a DOM node against a regular expression
 * and replaces each match (or node-separated portions of the match)
 * in the specified element.
 */
(function (root, factory) {
    if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else {
        // Browser globals
        root.findAndReplaceDOMText = factory();
    }
}(this, function factory() {

    var PORTION_MODE_RETAIN = 'retain';
    var PORTION_MODE_FIRST = 'first';

    var doc = document;
    var hasOwn = {}.hasOwnProperty;

    function escapeRegExp(s) {
        return String(s).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    }

    function exposed() {
        // Try deprecated arg signature first:
        return deprecated.apply(null, arguments) || findAndReplaceDOMText.apply(null, arguments);
    }

    function deprecated(regex, node, replacement, captureGroup, elFilter) {
        if ((node && !node.nodeType) && arguments.length <= 2) {
            return false;
        }
        var isReplacementFunction = typeof replacement == 'function';

        if (isReplacementFunction) {
            replacement = (function (original) {
                return function (portion, match) {
                    return original(portion.text, match.startIndex);
                };
            }(replacement));
        }

        // Awkward support for deprecated argument signature (<0.4.0)
        var instance = findAndReplaceDOMText(node, {

            find: regex,

            wrap: isReplacementFunction ? null : replacement,
            replace: isReplacementFunction ? replacement : '$' + (captureGroup || '&'),

            prepMatch: function (m, mi) {

                // Support captureGroup (a deprecated feature)

                if (!m[0]) throw 'findAndReplaceDOMText cannot handle zero-length matches';

                if (captureGroup > 0) {
                    var cg = m[captureGroup];
                    m.index += m[0].indexOf(cg);
                    m[0] = cg;
                }

                m.endIndex = m.index + m[0].length;
                m.startIndex = m.index;
                m.index = mi;

                return m;
            },
            filterElements: elFilter
        });

        exposed.revert = function () {
            return instance.revert();
        };

        return true;
    }

    /** 
	 * findAndReplaceDOMText
	 * 
	 * Locates matches and replaces with replacementNode
	 *
	 * @param {Node} node Element or Text node to search within
	 * @param {RegExp} options.find The regular expression to match
	 * @param {String|Element} [options.wrap] A NodeName, or a Node to clone
	 * @param {String|Function} [options.replace='$&'] What to replace each match with
	 * @param {Function} [options.filterElements] A Function to be called to check whether to
	 *	process an element. (returning true = process element,
	 *	returning false = avoid element)
	 */
    function findAndReplaceDOMText(node, options) {
        return new Finder(node, options);
    }

    exposed.NON_PROSE_ELEMENTS = {
        br: 1, hr: 1,
        // Media / Source elements:
        script: 1, style: 1, img: 1, video: 1, audio: 1, canvas: 1, svg: 1, map: 1, object: 1,
        // Input elements
        input: 1, textarea: 1, select: 1, option: 1, optgroup: 1, button: 1
    };

    exposed.NON_CONTIGUOUS_PROSE_ELEMENTS = {

        // Elements that will not contain prose or block elements where we don't
        // want prose to be matches across element borders:

        // Block Elements
        address: 1, article: 1, aside: 1, blockquote: 1, dd: 1, div: 1,
        dl: 1, fieldset: 1, figcaption: 1, figure: 1, footer: 1, form: 1, h1: 1, h2: 1, h3: 1,
        h4: 1, h5: 1, h6: 1, header: 1, hgroup: 1, hr: 1, main: 1, nav: 1, noscript: 1, ol: 1,
        output: 1, p: 1, pre: 1, section: 1, ul: 1,
        // Other misc. elements that are not part of continuous inline prose:
        br: 1, li: 1, summary: 1, dt: 1, details: 1, rp: 1, rt: 1, rtc: 1,
        // Media / Source elements:
        script: 1, style: 1, img: 1, video: 1, audio: 1, canvas: 1, svg: 1, map: 1, object: 1,
        // Input elements
        input: 1, textarea: 1, select: 1, option: 1, optgroup: 1, button: 1,
        // Table related elements:
        table: 1, tbody: 1, thead: 1, th: 1, tr: 1, td: 1, caption: 1, col: 1, tfoot: 1, colgroup: 1

    };

    exposed.NON_INLINE_PROSE = function (el) {
        return hasOwn.call(exposed.NON_CONTIGUOUS_PROSE_ELEMENTS, el.nodeName.toLowerCase());
    };

    // Presets accessed via `options.preset` when calling findAndReplaceDOMText():
    exposed.PRESETS = {
        prose: {
            forceContext: exposed.NON_INLINE_PROSE,
            filterElements: function (el) {
                return !hasOwn.call(exposed.NON_PROSE_ELEMENTS, el.nodeName.toLowerCase());
            }
        }
    };

    exposed.Finder = Finder;

    /**
	 * Finder -- encapsulates logic to find and replace.
	 */
    function Finder(node, options) {

        var preset = options.preset && exposed.PRESETS[options.preset];

        options.portionMode = options.portionMode || PORTION_MODE_RETAIN;

        if (preset) {
            for (var i in preset) {
                if (hasOwn.call(preset, i) && !hasOwn.call(options, i)) {
                    options[i] = preset[i];
                }
            }
        }

        this.node = node;
        this.options = options;

        // Enable match-preparation method to be passed as option:
        this.prepMatch = options.prepMatch || this.prepMatch;

        this.reverts = [];

        this.matches = this.search();

        if (this.matches.length) {
            this.processMatches();
        }

    }

    Finder.prototype = {

        /**
		 * Searches for all matches that comply with the instance's 'match' option
		 */
        search: function () {

            var match;
            var matchIndex = 0;
            var offset = 0;
            var regex = this.options.find;
            var textAggregation = this.getAggregateText();
            var matches = [];
            var self = this;

            regex = typeof regex === 'string' ? RegExp(escapeRegExp(regex), 'g') : regex;

            matchAggregation(textAggregation);

            function matchAggregation(textAggregation) {
                for (var i = 0, l = textAggregation.length; i < l; ++i) {

                    var text = textAggregation[i];

                    if (typeof text !== 'string') {
                        // Deal with nested contexts: (recursive)
                        matchAggregation(text);
                        continue;
                    }

                    if (regex.global) {
                        while (match = regex.exec(text)) {
                            matches.push(self.prepMatch(match, matchIndex++, offset));
                        }
                    } else {
                        if (match = text.match(regex)) {
                            matches.push(self.prepMatch(match, 0, offset));
                        }
                    }

                    offset += text.length;
                }
            }

            return matches;

        },

        /**
		 * Prepares a single match with useful meta info:
		 */
        prepMatch: function (match, matchIndex, characterOffset) {

            if (!match[0]) {
                throw new Error('findAndReplaceDOMText cannot handle zero-length matches');
            }

            match.endIndex = characterOffset + match.index + match[0].length;
            match.startIndex = characterOffset + match.index;
            match.index = matchIndex;

            return match;
        },

        /**
		 * Gets aggregate text within subject node
		 */
        getAggregateText: function () {

            var elementFilter = this.options.filterElements;
            var forceContext = this.options.forceContext;

            return getText(this.node);

            /**
			 * Gets aggregate text of a node without resorting
			 * to broken innerText/textContent
			 */
            function getText(node) {

                if (node.nodeType === 3) {
                    return [node.data];
                }

                if (elementFilter && !elementFilter(node)) {
                    return [];
                }

                var txt = [''];
                var i = 0;

                if (node = node.firstChild) do {

                    if (node.nodeType === 3) {
                        txt[i] += node.data;
                        continue;
                    }

                    var innerText = getText(node);

                    if (
						forceContext &&
						node.nodeType === 1 &&
						(forceContext === true || forceContext(node))
					) {
                        txt[++i] = innerText;
                        txt[++i] = '';
                    } else {
                        if (typeof innerText[0] === 'string') {
                            // Bridge nested text-node data so that they're
                            // not considered their own contexts:
                            // I.e. ['some', ['thing']] -> ['something']
                            txt[i] += innerText.shift();
                        }
                        if (innerText.length) {
                            txt[++i] = innerText;
                            txt[++i] = '';
                        }
                    }
                } while (node = node.nextSibling);

                return txt;

            }

        },

        /** 
		 * Steps through the target node, looking for matches, and
		 * calling replaceFn when a match is found.
		 */
        processMatches: function () {

            var matches = this.matches;
            var node = this.node;
            var elementFilter = this.options.filterElements;

            var startPortion,
				endPortion,
				innerPortions = [],
				curNode = node,
				match = matches.shift(),
				atIndex = 0, // i.e. nodeAtIndex
				matchIndex = 0,
				portionIndex = 0,
				doAvoidNode,
				nodeStack = [node];

            out: while (true) {

                if (curNode.nodeType === 3) {

                    if (!endPortion && curNode.length + atIndex >= match.endIndex) {

                        // We've found the ending
                        endPortion = {
                            node: curNode,
                            index: portionIndex++,
                            text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex),
                            indexInMatch: atIndex - match.startIndex,
                            indexInNode: match.startIndex - atIndex, // always zero for end-portions
                            endIndexInNode: match.endIndex - atIndex,
                            isEnd: true
                        };

                    } else if (startPortion) {
                        // Intersecting node
                        innerPortions.push({
                            node: curNode,
                            index: portionIndex++,
                            text: curNode.data,
                            indexInMatch: atIndex - match.startIndex,
                            indexInNode: 0 // always zero for inner-portions
                        });
                    }

                    if (!startPortion && curNode.length + atIndex > match.startIndex) {
                        // We've found the match start
                        startPortion = {
                            node: curNode,
                            index: portionIndex++,
                            indexInMatch: 0,
                            indexInNode: match.startIndex - atIndex,
                            endIndexInNode: match.endIndex - atIndex,
                            text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex)
                        };
                    }

                    atIndex += curNode.data.length;

                }

                doAvoidNode = curNode.nodeType === 1 && elementFilter && !elementFilter(curNode);

                if (startPortion && endPortion) {

                    curNode = this.replaceMatch(match, startPortion, innerPortions, endPortion);

                    // processMatches has to return the node that replaced the endNode
                    // and then we step back so we can continue from the end of the 
                    // match:

                    atIndex -= (endPortion.node.data.length - endPortion.endIndexInNode);

                    startPortion = null;
                    endPortion = null;
                    innerPortions = [];
                    match = matches.shift();
                    portionIndex = 0;
                    matchIndex++;

                    if (!match) {
                        break; // no more matches
                    }

                } else if (
					!doAvoidNode &&
					(curNode.firstChild || curNode.nextSibling)
				) {
                    // Move down or forward:
                    if (curNode.firstChild) {
                        nodeStack.push(curNode);
                        curNode = curNode.firstChild;
                    } else {
                        curNode = curNode.nextSibling;
                    }
                    continue;
                }

                // Move forward or up:
                while (true) {
                    if (curNode.nextSibling) {
                        curNode = curNode.nextSibling;
                        break;
                    }
                    curNode = nodeStack.pop();
                    if (curNode === node) {
                        break out;
                    }
                }

            }

        },

        /**
		 * Reverts ... TODO
		 */
        revert: function () {
            // Reversion occurs backwards so as to avoid nodes subsequently
            // replaced during the matching phase (a forward process):
            for (var l = this.reverts.length; l--;) {
                this.reverts[l]();
            }
            this.reverts = [];
        },

        prepareReplacementString: function (string, portion, match, matchIndex) {
            var portionMode = this.options.portionMode;
            if (
				portionMode === PORTION_MODE_FIRST &&
				portion.indexInMatch > 0
			) {
                return '';
            }
            string = string.replace(/\$(\d+|&|`|')/g, function ($0, t) {
                var replacement;
                switch (t) {
                    case '&':
                        replacement = match[0];
                        break;
                    case '`':
                        replacement = match.input.substring(0, match.startIndex);
                        break;
                    case '\'':
                        replacement = match.input.substring(match.endIndex);
                        break;
                    default:
                        replacement = match[+t];
                }
                return replacement;
            });

            if (portionMode === PORTION_MODE_FIRST) {
                return string;
            }

            if (portion.isEnd) {
                return string.substring(portion.indexInMatch);
            }

            return string.substring(portion.indexInMatch, portion.indexInMatch + portion.text.length);
        },

        getPortionReplacementNode: function (portion, match, matchIndex) {

            var replacement = this.options.replace || '$&';
            var wrapper = this.options.wrap;

            if (wrapper && wrapper.nodeType) {
                // Wrapper has been provided as a stencil-node for us to clone:
                var clone = doc.createElement('div');
                clone.innerHTML = wrapper.outerHTML || new XMLSerializer().serializeToString(wrapper);
                wrapper = clone.firstChild;
            }

            if (typeof replacement == 'function') {
                replacement = replacement(portion, match, matchIndex);
                if (replacement && replacement.nodeType) {
                    return replacement;
                }
                return doc.createTextNode(String(replacement));
            }

            var el = typeof wrapper == 'string' ? doc.createElement(wrapper) : wrapper;

            replacement = doc.createTextNode(
				this.prepareReplacementString(
					replacement, portion, match, matchIndex
				)
			);

            if (!replacement.data) {
                return replacement;
            }

            if (!el) {
                return replacement;
            }

            el.appendChild(replacement);

            return el;
        },

        replaceMatch: function (match, startPortion, innerPortions, endPortion) {

            var matchStartNode = startPortion.node;
            var matchEndNode = endPortion.node;

            var precedingTextNode;
            var followingTextNode;

            if (matchStartNode === matchEndNode) {

                var node = matchStartNode;

                if (startPortion.indexInNode > 0) {
                    // Add `before` text node (before the match)
                    precedingTextNode = doc.createTextNode(node.data.substring(0, startPortion.indexInNode));
                    node.parentNode.insertBefore(precedingTextNode, node);
                }

                // Create the replacement node:
                var newNode = this.getPortionReplacementNode(
					endPortion,
					match
				);

                node.parentNode.insertBefore(newNode, node);

                if (endPortion.endIndexInNode < node.length) { // ?????
                    // Add `after` text node (after the match)
                    followingTextNode = doc.createTextNode(node.data.substring(endPortion.endIndexInNode));
                    node.parentNode.insertBefore(followingTextNode, node);
                }

                node.parentNode.removeChild(node);

                this.reverts.push(function () {
                    if (precedingTextNode === newNode.previousSibling) {
                        precedingTextNode.parentNode.removeChild(precedingTextNode);
                    }
                    if (followingTextNode === newNode.nextSibling) {
                        followingTextNode.parentNode.removeChild(followingTextNode);
                    }
                    newNode.parentNode.replaceChild(node, newNode);
                });

                return newNode;

            } else {
                // Replace matchStartNode -> [innerMatchNodes...] -> matchEndNode (in that order)


                precedingTextNode = doc.createTextNode(
					matchStartNode.data.substring(0, startPortion.indexInNode)
				);

                followingTextNode = doc.createTextNode(
					matchEndNode.data.substring(endPortion.endIndexInNode)
				);

                var firstNode = this.getPortionReplacementNode(
					startPortion,
					match
				);

                var innerNodes = [];

                for (var i = 0, l = innerPortions.length; i < l; ++i) {
                    var portion = innerPortions[i];
                    var innerNode = this.getPortionReplacementNode(
						portion,
						match
					);
                    portion.node.parentNode.replaceChild(innerNode, portion.node);
                    this.reverts.push((function (portion, innerNode) {
                        return function () {
                            innerNode.parentNode.replaceChild(portion.node, innerNode);
                        };
                    }(portion, innerNode)));
                    innerNodes.push(innerNode);
                }

                var lastNode = this.getPortionReplacementNode(
					endPortion,
					match
				);

                matchStartNode.parentNode.insertBefore(precedingTextNode, matchStartNode);
                matchStartNode.parentNode.insertBefore(firstNode, matchStartNode);
                matchStartNode.parentNode.removeChild(matchStartNode);

                matchEndNode.parentNode.insertBefore(lastNode, matchEndNode);
                matchEndNode.parentNode.insertBefore(followingTextNode, matchEndNode);
                matchEndNode.parentNode.removeChild(matchEndNode);

                this.reverts.push(function () {
                    precedingTextNode.parentNode.removeChild(precedingTextNode);
                    firstNode.parentNode.replaceChild(matchStartNode, firstNode);
                    followingTextNode.parentNode.removeChild(followingTextNode);
                    lastNode.parentNode.replaceChild(matchEndNode, lastNode);
                });

                return lastNode;
            }
        }

    };

    return exposed;

}));;
/*! jssocials - v1.2.1 - 2016-04-10
* http://js-socials.com
* Copyright (c) 2016 Artem Tabalin; Licensed MIT */
(function (window, $, undefined) {

    var JSSOCIALS = "JSSocials",
        JSSOCIALS_DATA_KEY = JSSOCIALS;

    var getOrApply = function (value, context) {
        if ($.isFunction(value)) {
            return value.apply(context, $.makeArray(arguments).slice(2));
        }
        return value;
    };

    var IMG_SRC_REGEX = /(\.(jpeg|png|gif|bmp)$|^data:image\/(jpeg|png|gif|bmp);base64)/i;
    var URL_PARAMS_REGEX = /(&?[a-zA-Z0-9]+=)?\{([a-zA-Z0-9]+)\}/g;

    var MEASURES = {
        "G": 1000000000,
        "M": 1000000,
        "K": 1000
    };

    var shares = {};

    function Socials(element, config) {
        var $element = $(element);

        $element.data(JSSOCIALS_DATA_KEY, this);

        this._$element = $element;

        this.shares = [];

        this._init(config);
        this._render();
    }

    Socials.prototype = {
        url: "",
        text: "",
        shareIn: "blank",

        showLabel: function (screenWidth) {
            return (this.showCount === false) ?
                (screenWidth > this.smallScreenWidth) :
                (screenWidth >= this.largeScreenWidth);
        },

        showCount: function (screenWidth) {
            return (screenWidth <= this.smallScreenWidth) ? "inside" : true;
        },

        smallScreenWidth: 640,
        largeScreenWidth: 1024,

        resizeTimeout: 200,

        elementClass: "jssocials",
        sharesClass: "jssocials-shares",
        shareClass: "jssocials-share",
        shareButtonClass: "jssocials-share-button",
        shareLinkClass: "jssocials-share-link",
        shareLogoClass: "jssocials-share-logo",
        shareLabelClass: "jssocials-share-label",
        shareLinkCountClass: "jssocials-share-link-count",
        shareCountBoxClass: "jssocials-share-count-box",
        shareCountClass: "jssocials-share-count",
        shareZeroCountClass: "jssocials-share-no-count",

        _init: function (config) {
            this._initDefaults();
            $.extend(this, config);
            this._initShares();
            this._attachWindowResizeCallback();
        },

        _initDefaults: function () {
            this.url = window.location.href;
            this.text = $.trim($("meta[name=description]").attr("content") || $("title").text());
        },

        _initShares: function () {
            this.shares = $.map(this.shares, $.proxy(function (shareConfig) {
                if (typeof shareConfig === "string") {
                    shareConfig = { share: shareConfig };
                }

                var share = (shareConfig.share && shares[shareConfig.share]);

                if (!share && !shareConfig.renderer) {
                    throw Error("Share '" + shareConfig.share + "' is not found");
                }

                return $.extend({ url: this.url, text: this.text }, share, shareConfig);
            }, this));
        },

        _attachWindowResizeCallback: function () {
            $(window).on("resize", $.proxy(this._windowResizeHandler, this));
        },

        _detachWindowResizeCallback: function () {
            $(window).off("resize", this._windowResizeHandler);
        },

        _windowResizeHandler: function () {
            if ($.isFunction(this.showLabel) || $.isFunction(this.showCount)) {
                window.clearTimeout(this._resizeTimer);
                this._resizeTimer = setTimeout($.proxy(this.refresh, this), this.resizeTimeout);
            }
        },

        _render: function () {
            this._clear();

            this._defineOptionsByScreen();

            this._$element.addClass(this.elementClass);

            this._$shares = $("<div>").addClass(this.sharesClass)
                .appendTo(this._$element);

            this._renderShares();
        },

        _defineOptionsByScreen: function () {
            this._screenWidth = $(window).width();
            this._showLabel = getOrApply(this.showLabel, this, this._screenWidth);
            this._showCount = getOrApply(this.showCount, this, this._screenWidth);
        },

        _renderShares: function () {
            $.each(this.shares, $.proxy(function (_, share) {
                this._renderShare(share);
            }, this));
        },

        _renderShare: function (share) {
            var $share;

            if ($.isFunction(share.renderer)) {
                $share = $(share.renderer());
            } else {
                $share = this._createShare(share);
            }

            $share.addClass(this.shareClass)
                .addClass(share.share ? "jssocials-share-" + share.share : "")
                .addClass(share.css)
                .appendTo(this._$shares);
        },

        _createShare: function (share) {
            var $result = $("<div>");
            var $shareLink = this._createShareLink(share).appendTo($result);

            if (this._showCount) {
                var isInsideCount = (this._showCount === "inside");
                var $countContainer = isInsideCount ? $shareLink : $("<div>").addClass(this.shareCountBoxClass).appendTo($result);
                $countContainer.addClass(isInsideCount ? this.shareLinkCountClass : this.shareCountBoxClass);
                this._renderShareCount(share, $countContainer);
            }

            return $result;
        },

        _createShareLink: function (share) {
            var shareStrategy = this._getShareStrategy(share);

            var $result = shareStrategy.call(share, {
                shareUrl: this._getShareUrl(share)
            });

            $result.addClass(this.shareLinkClass)
                .append(this._createShareLogo(share));

            if (this._showLabel) {
                $result.append(this._createShareLabel(share));
            }

            $.each(this.on || {}, function (event, handler) {
                if ($.isFunction(handler)) {
                    $result.on(event, $.proxy(handler, share));
                }
            });

            return $result;
        },

        _getShareStrategy: function (share) {
            var result = shareStrategies[share.shareIn || this.shareIn];

            if (!result)
                throw Error("Share strategy '" + this.shareIn + "' not found");

            return result;
        },

        _getShareUrl: function (share) {
            var shareUrl = getOrApply(share.shareUrl, share);
            return this._formatShareUrl(shareUrl, share);
        },

        _createShareLogo: function (share) {
            var logo = share.logo;

            var $result = IMG_SRC_REGEX.test(logo) ?
                $("<img>").attr("src", share.logo) :
                $("<i>").addClass(logo);

            $result.addClass(this.shareLogoClass);

            return $result;
        },

        _createShareLabel: function (share) {
            return $("<span>").addClass(this.shareLabelClass)
                .text(share.label);
        },

        _renderShareCount: function (share, $container) {
            var $count = $("<span>").addClass(this.shareCountClass);

            $container.addClass(this.shareZeroCountClass)
                .append($count);

            this._loadCount(share).done($.proxy(function (count) {
                if (count) {
                    $container.removeClass(this.shareZeroCountClass);
                    $count.text(count);
                }
            }, this));
        },

        _loadCount: function (share) {
            var deferred = $.Deferred();
            var countUrl;

            if (share.isSelfContainerCountFunction && share.isSelfContainerCountFunction) {
                var count = share.getCount();
                return deferred.resolve(count);
            } else {
                countUrl = this._getCountUrl(share);
            }

            if (!countUrl) {
                return deferred.resolve(0).promise();
            }

            var handleSuccess = $.proxy(function (response) {
                deferred.resolve(this._getCountValue(response, share));
            }, this);

            $.getJSON(countUrl).done(handleSuccess)
                .fail(function () {
                    $.get(countUrl).done(handleSuccess)
                        .fail(function () {
                            deferred.resolve(0);
                        });
                });

            return deferred.promise();
        },

        _getCountUrl: function (share) {
            var countUrl = getOrApply(share.countUrl, share);
            return this._formatShareUrl(countUrl, share);
        },

        _getCountValue: function (response, share) {
            var count = ($.isFunction(share.getCount) ? share.getCount(response) : response) || 0;
            return (typeof count === "string") ? count : this._formatNumber(count);
        },

        _formatNumber: function (number) {
            $.each(MEASURES, function (letter, value) {
                if (number >= value) {
                    number = parseFloat((number / value).toFixed(2)) + letter;
                    return false;
                }
            });

            return number;
        },

        _formatShareUrl: function (url, share) {
            return url.replace(URL_PARAMS_REGEX, function (match, key, field) {
                var value = share[field] || "";
                return value ? (key || "") + window.encodeURIComponent(value) : "";
            });
        },

        _clear: function () {
            window.clearTimeout(this._resizeTimer);
            this._$element.empty();
        },

        _passOptionToShares: function (key, value) {
            var shares = this.shares;

            $.each(["url", "text"], function (_, optionName) {
                if (optionName !== key)
                    return;

                $.each(shares, function (_, share) {
                    share[key] = value;
                });
            });
        },

        _normalizeShare: function (share) {
            if ($.isNumeric(share)) {
                return this.shares[share];
            }

            if (typeof share === "string") {
                return $.grep(this.shares, function (s) {
                    return s.share === share;
                })[0];
            }

            return share;
        },

        refresh: function () {
            this._render();
        },

        destroy: function () {
            this._clear();
            this._detachWindowResizeCallback();

            this._$element
                .removeClass(this.elementClass)
                .removeData(JSSOCIALS_DATA_KEY);
        },

        option: function (key, value) {
            if (arguments.length === 1) {
                return this[key];
            }

            this[key] = value;

            this._passOptionToShares(key, value);

            this.refresh();
        },

        shareOption: function (share, key, value) {
            share = this._normalizeShare(share);

            if (arguments.length === 2) {
                return share[key];
            }

            share[key] = value;
            this.refresh();
        }
    };


    $.fn.jsSocials = function (config) {
        var args = $.makeArray(arguments),
            methodArgs = args.slice(1),
            result = this;

        this.each(function () {
            var $element = $(this),
                instance = $element.data(JSSOCIALS_DATA_KEY),
                methodResult;

            if (instance) {
                if (typeof config === "string") {
                    methodResult = instance[config].apply(instance, methodArgs);
                    if (methodResult !== undefined && methodResult !== instance) {
                        result = methodResult;
                        return false;
                    }
                } else {
                    instance._detachWindowResizeCallback();
                    instance._init(config);
                    instance._render();
                }
            } else {
                new Socials($element, config);
            }
        });

        return result;
    };

    var setDefaults = function (config) {
        var component;

        if ($.isPlainObject(config)) {
            component = Socials.prototype;
        } else {
            component = shares[config];
            config = arguments[1] || {};
        }

        $.extend(component, config);
    };

    var shareStrategies = {
        popup: function (args) {
            return $("<a>").attr("href", "#")
                .on("click", function () {
                    window.open(args.shareUrl, null, "width=600, height=400, location=0, menubar=0, resizeable=0, scrollbars=0, status=0, titlebar=0, toolbar=0");
                    return false;
                });
        },

        blank: function (args) {
            return $("<a>").attr({ target: "_blank", href: args.shareUrl });
        },

        self: function (args) {
            return $("<a>").attr({ target: "_self", href: args.shareUrl });
        }
    };

    window.jsSocials = {
        Socials: Socials,
        shares: shares,
        shareStrategies: shareStrategies,
        setDefaults: setDefaults
    };

}(window, jQuery));


(function (window, $, jsSocials, undefined) {

    $.extend(jsSocials.shares, {

        email: {
            label: "E-mail",
            logo: "fa fa-at",
            shareUrl: "mailto:{to}?subject={text}&body={url}",
            countUrl: "",
            shareIn: "self"
        },

        twitter: {
            label: "Tweet",
            logo: "icon-twitter",
            shareUrl: "https://twitter.com/share?url={url}&text={text}&via={via}&hashtags={hashtags}",
            countUrl: ""
        },

        facebook: {
            label: "Share",
            logo: "icon-facebook",
            shareUrl: "https://facebook.com/sharer/sharer.php?u={url}",
            countUrl: function () {
                return "https://graph.facebook.com/fql?q=SELECT total_count FROM link_stat WHERE url='" + window.encodeURIComponent(this.url) + "'";
            },
            getCount: function (data) {
                return (data.data.length && data.data[0].total_count) || 0;
            }
        },

        googleplus: {
            label: "+1",
            logo: "icon-google-plus",
            shareUrl: "https://plus.google.com/share?url={url}",
            countUrl: function () {
            },
            isSelfContainerCountFunction: true,
            getCount: function (data) {
                var uri = this.url;

                var response = $.ajax({
                    type: 'POST',
                    url: 'https://clients6.google.com/rpc',
                    processData: true,
                    contentType: 'application/json',
                    data: JSON.stringify({
                        'method': 'pos.plusones.get',
                        'id': uri,
                        'params': {
                            'nolog': true,
                            'id': uri,
                            'source': 'widget',
                            'userId': '@viewer',
                            'groupId': '@self'
                        },
                        'jsonrpc': '2.0',
                        'key': 'p',
                        'apiVersion': 'v1'
                    }),
                    success: function (response) {
                        var $container = $('.jssocials-share-googleplus .jssocials-share-count'),
                            count = response.result.metadata.globalCounts.count;

                        if (count) {
                            $container.parent().removeClass('jssocials-share-no-count');
                            $container.text(count);
                        }
                        return;
                    }
                });
            }
        },

        linkedin: {
            label: "Share",
            logo: "fa fa-linkedin",
            shareUrl: "https://www.linkedin.com/shareArticle?mini=true&url={url}",
            countUrl: "https://www.linkedin.com/countserv/count/share?format=jsonp&url={url}&callback=?",
            getCount: function (data) {
                return data.count;
            }
        },

        pinterest: {
            label: "Pin it",
            logo: "icon-pintrest",
            shareUrl: "https://pinterest.com/pin/create/bookmarklet/?media={media}&url={url}&description={text}",
            countUrl: "https://api.pinterest.com/v1/urls/count.json?&url={url}&callback=?",
            getCount: function (data) {
                return data.count;
            }
        },

        stumbleupon: {
            label: "Share",
            logo: "fa fa-stumbleupon",
            shareUrl: "http://www.stumbleupon.com/submit?url={url}&title={title}",
            countUrl: "https://cors-anywhere.herokuapp.com/https://www.stumbleupon.com/services/1.01/badge.getinfo?url={url}",
            getCount: function (data) {
                return data.result.views;
            }
        },

        whatsapp: {
            label: "WhatsApp",
            logo: "fa fa-whatsapp",
            shareUrl: "whatsapp://send?text={url} {text}",
            countUrl: "",
            shareIn: "self"
        },

        line: {
            label: "LINE",
            logo: "fa fa-comment",
            shareUrl: "http://line.me/R/msg/text/?{text} {url}",
            countUrl: ""
        }

    });

}(window, jQuery, window.jsSocials));

;
/*!
 * jQuery imagesLoaded plugin v2.1.0
 * http://github.com/desandro/imagesloaded
 *
 * MIT License. by Paul Irish et al.
 */
(function (c, q) {
    var m = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; c.fn.imagesLoaded = function (f) {
        function n() { var b = c(j), a = c(h); d && (h.length ? d.reject(e, b, a) : d.resolve(e)); c.isFunction(f) && f.call(g, e, b, a) } function p(b) { k(b.target, "error" === b.type) } function k(b, a) {
            b.src === m || -1 !== c.inArray(b, l) || (l.push(b), a ? h.push(b) : j.push(b), c.data(b, "imagesLoaded", { isBroken: a, src: b.src }), r && d.notifyWith(c(b), [a, e, c(j), c(h)]), e.length === l.length && (setTimeout(n), e.unbind(".imagesLoaded",
            p)))
        } var g = this, d = c.isFunction(c.Deferred) ? c.Deferred() : 0, r = c.isFunction(d.notify), e = g.find("img").add(g.filter("img")), l = [], j = [], h = []; c.isPlainObject(f) && c.each(f, function (b, a) { if ("callback" === b) f = a; else if (d) d[b](a) }); e.length ? e.bind("load.imagesLoaded error.imagesLoaded", p).each(function (b, a) { var d = a.src, e = c.data(a, "imagesLoaded"); if (e && e.src === d) k(a, e.isBroken); else if (a.complete && a.naturalWidth !== q) k(a, 0 === a.naturalWidth || 0 === a.naturalHeight); else if (a.readyState || a.complete) a.src = m, a.src = d }) :
        n(); return d ? d.promise(g) : g
    }
})(jQuery);;
/*!
 * Masonry PACKAGED v3.2.2
 * Cascading grid layout library
 * http://masonry.desandro.com
 * MIT License
 * by David DeSandro
 */

!function(a){function b(){}function c(a){function c(b){b.prototype.option||(b.prototype.option=function(b){a.isPlainObject(b)&&(this.options=a.extend(!0,this.options,b))})}function e(b,c){a.fn[b]=function(e){if("string"==typeof e){for(var g=d.call(arguments,1),h=0,i=this.length;i>h;h++){var j=this[h],k=a.data(j,b);if(k)if(a.isFunction(k[e])&&"_"!==e.charAt(0)){var l=k[e].apply(k,g);if(void 0!==l)return l}else f("no such method '"+e+"' for "+b+" instance");else f("cannot call methods on "+b+" prior to initialization; attempted to call '"+e+"'")}return this}return this.each(function(){var d=a.data(this,b);d?(d.option(e),d._init()):(d=new c(this,e),a.data(this,b,d))})}}if(a){var f="undefined"==typeof console?b:function(a){console.error(a)};return a.bridget=function(a,b){c(b),e(a,b)},a.bridget}}var d=Array.prototype.slice;"function"==typeof define&&define.amd?define("jquery-bridget/jquery.bridget",["jquery"],c):c("object"==typeof exports?require("jquery"):a.jQuery)}(window),function(a){function b(b){var c=a.event;return c.target=c.target||c.srcElement||b,c}var c=document.documentElement,d=function(){};c.addEventListener?d=function(a,b,c){a.addEventListener(b,c,!1)}:c.attachEvent&&(d=function(a,c,d){a[c+d]=d.handleEvent?function(){var c=b(a);d.handleEvent.call(d,c)}:function(){var c=b(a);d.call(a,c)},a.attachEvent("on"+c,a[c+d])});var e=function(){};c.removeEventListener?e=function(a,b,c){a.removeEventListener(b,c,!1)}:c.detachEvent&&(e=function(a,b,c){a.detachEvent("on"+b,a[b+c]);try{delete a[b+c]}catch(d){a[b+c]=void 0}});var f={bind:d,unbind:e};"function"==typeof define&&define.amd?define("eventie/eventie",f):"object"==typeof exports?module.exports=f:a.eventie=f}(this),function(a){function b(a){"function"==typeof a&&(b.isReady?a():g.push(a))}function c(a){var c="readystatechange"===a.type&&"complete"!==f.readyState;b.isReady||c||d()}function d(){b.isReady=!0;for(var a=0,c=g.length;c>a;a++){var d=g[a];d()}}function e(e){return"complete"===f.readyState?d():(e.bind(f,"DOMContentLoaded",c),e.bind(f,"readystatechange",c),e.bind(a,"load",c)),b}var f=a.document,g=[];b.isReady=!1,"function"==typeof define&&define.amd?define("doc-ready/doc-ready",["eventie/eventie"],e):"object"==typeof exports?module.exports=e(require("eventie")):a.docReady=e(a.eventie)}(window),function(){function a(){}function b(a,b){for(var c=a.length;c--;)if(a[c].listener===b)return c;return-1}function c(a){return function(){return this[a].apply(this,arguments)}}var d=a.prototype,e=this,f=e.EventEmitter;d.getListeners=function(a){var b,c,d=this._getEvents();if(a instanceof RegExp){b={};for(c in d)d.hasOwnProperty(c)&&a.test(c)&&(b[c]=d[c])}else b=d[a]||(d[a]=[]);return b},d.flattenListeners=function(a){var b,c=[];for(b=0;b<a.length;b+=1)c.push(a[b].listener);return c},d.getListenersAsObject=function(a){var b,c=this.getListeners(a);return c instanceof Array&&(b={},b[a]=c),b||c},d.addListener=function(a,c){var d,e=this.getListenersAsObject(a),f="object"==typeof c;for(d in e)e.hasOwnProperty(d)&&-1===b(e[d],c)&&e[d].push(f?c:{listener:c,once:!1});return this},d.on=c("addListener"),d.addOnceListener=function(a,b){return this.addListener(a,{listener:b,once:!0})},d.once=c("addOnceListener"),d.defineEvent=function(a){return this.getListeners(a),this},d.defineEvents=function(a){for(var b=0;b<a.length;b+=1)this.defineEvent(a[b]);return this},d.removeListener=function(a,c){var d,e,f=this.getListenersAsObject(a);for(e in f)f.hasOwnProperty(e)&&(d=b(f[e],c),-1!==d&&f[e].splice(d,1));return this},d.off=c("removeListener"),d.addListeners=function(a,b){return this.manipulateListeners(!1,a,b)},d.removeListeners=function(a,b){return this.manipulateListeners(!0,a,b)},d.manipulateListeners=function(a,b,c){var d,e,f=a?this.removeListener:this.addListener,g=a?this.removeListeners:this.addListeners;if("object"!=typeof b||b instanceof RegExp)for(d=c.length;d--;)f.call(this,b,c[d]);else for(d in b)b.hasOwnProperty(d)&&(e=b[d])&&("function"==typeof e?f.call(this,d,e):g.call(this,d,e));return this},d.removeEvent=function(a){var b,c=typeof a,d=this._getEvents();if("string"===c)delete d[a];else if(a instanceof RegExp)for(b in d)d.hasOwnProperty(b)&&a.test(b)&&delete d[b];else delete this._events;return this},d.removeAllListeners=c("removeEvent"),d.emitEvent=function(a,b){var c,d,e,f,g=this.getListenersAsObject(a);for(e in g)if(g.hasOwnProperty(e))for(d=g[e].length;d--;)c=g[e][d],c.once===!0&&this.removeListener(a,c.listener),f=c.listener.apply(this,b||[]),f===this._getOnceReturnValue()&&this.removeListener(a,c.listener);return this},d.trigger=c("emitEvent"),d.emit=function(a){var b=Array.prototype.slice.call(arguments,1);return this.emitEvent(a,b)},d.setOnceReturnValue=function(a){return this._onceReturnValue=a,this},d._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},d._getEvents=function(){return this._events||(this._events={})},a.noConflict=function(){return e.EventEmitter=f,a},"function"==typeof define&&define.amd?define("eventEmitter/EventEmitter",[],function(){return a}):"object"==typeof module&&module.exports?module.exports=a:e.EventEmitter=a}.call(this),function(a){function b(a){if(a){if("string"==typeof d[a])return a;a=a.charAt(0).toUpperCase()+a.slice(1);for(var b,e=0,f=c.length;f>e;e++)if(b=c[e]+a,"string"==typeof d[b])return b}}var c="Webkit Moz ms Ms O".split(" "),d=document.documentElement.style;"function"==typeof define&&define.amd?define("get-style-property/get-style-property",[],function(){return b}):"object"==typeof exports?module.exports=b:a.getStyleProperty=b}(window),function(a){function b(a){var b=parseFloat(a),c=-1===a.indexOf("%")&&!isNaN(b);return c&&b}function c(){}function d(){for(var a={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},b=0,c=g.length;c>b;b++){var d=g[b];a[d]=0}return a}function e(c){function e(){if(!m){m=!0;var d=a.getComputedStyle;if(j=function(){var a=d?function(a){return d(a,null)}:function(a){return a.currentStyle};return function(b){var c=a(b);return c||f("Style returned "+c+". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"),c}}(),k=c("boxSizing")){var e=document.createElement("div");e.style.width="200px",e.style.padding="1px 2px 3px 4px",e.style.borderStyle="solid",e.style.borderWidth="1px 2px 3px 4px",e.style[k]="border-box";var g=document.body||document.documentElement;g.appendChild(e);var h=j(e);l=200===b(h.width),g.removeChild(e)}}}function h(a){if(e(),"string"==typeof a&&(a=document.querySelector(a)),a&&"object"==typeof a&&a.nodeType){var c=j(a);if("none"===c.display)return d();var f={};f.width=a.offsetWidth,f.height=a.offsetHeight;for(var h=f.isBorderBox=!(!k||!c[k]||"border-box"!==c[k]),m=0,n=g.length;n>m;m++){var o=g[m],p=c[o];p=i(a,p);var q=parseFloat(p);f[o]=isNaN(q)?0:q}var r=f.paddingLeft+f.paddingRight,s=f.paddingTop+f.paddingBottom,t=f.marginLeft+f.marginRight,u=f.marginTop+f.marginBottom,v=f.borderLeftWidth+f.borderRightWidth,w=f.borderTopWidth+f.borderBottomWidth,x=h&&l,y=b(c.width);y!==!1&&(f.width=y+(x?0:r+v));var z=b(c.height);return z!==!1&&(f.height=z+(x?0:s+w)),f.innerWidth=f.width-(r+v),f.innerHeight=f.height-(s+w),f.outerWidth=f.width+t,f.outerHeight=f.height+u,f}}function i(b,c){if(a.getComputedStyle||-1===c.indexOf("%"))return c;var d=b.style,e=d.left,f=b.runtimeStyle,g=f&&f.left;return g&&(f.left=b.currentStyle.left),d.left=c,c=d.pixelLeft,d.left=e,g&&(f.left=g),c}var j,k,l,m=!1;return h}var f="undefined"==typeof console?c:function(a){console.error(a)},g=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];"function"==typeof define&&define.amd?define("get-size/get-size",["get-style-property/get-style-property"],e):"object"==typeof exports?module.exports=e(require("desandro-get-style-property")):a.getSize=e(a.getStyleProperty)}(window),function(a){function b(a,b){return a[g](b)}function c(a){if(!a.parentNode){var b=document.createDocumentFragment();b.appendChild(a)}}function d(a,b){c(a);for(var d=a.parentNode.querySelectorAll(b),e=0,f=d.length;f>e;e++)if(d[e]===a)return!0;return!1}function e(a,d){return c(a),b(a,d)}var f,g=function(){if(a.matchesSelector)return"matchesSelector";for(var b=["webkit","moz","ms","o"],c=0,d=b.length;d>c;c++){var e=b[c],f=e+"MatchesSelector";if(a[f])return f}}();if(g){var h=document.createElement("div"),i=b(h,"div");f=i?b:e}else f=d;"function"==typeof define&&define.amd?define("matches-selector/matches-selector",[],function(){return f}):"object"==typeof exports?module.exports=f:window.matchesSelector=f}(Element.prototype),function(a){function b(a,b){for(var c in b)a[c]=b[c];return a}function c(a){for(var b in a)return!1;return b=null,!0}function d(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}function e(a,e,f){function h(a,b){a&&(this.element=a,this.layout=b,this.position={x:0,y:0},this._create())}var i=f("transition"),j=f("transform"),k=i&&j,l=!!f("perspective"),m={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend",transition:"transitionend"}[i],n=["transform","transition","transitionDuration","transitionProperty"],o=function(){for(var a={},b=0,c=n.length;c>b;b++){var d=n[b],e=f(d);e&&e!==d&&(a[d]=e)}return a}();b(h.prototype,a.prototype),h.prototype._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},h.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},h.prototype.getSize=function(){this.size=e(this.element)},h.prototype.css=function(a){var b=this.element.style;for(var c in a){var d=o[c]||c;b[d]=a[c]}},h.prototype.getPosition=function(){var a=g(this.element),b=this.layout.options,c=b.isOriginLeft,d=b.isOriginTop,e=parseInt(a[c?"left":"right"],10),f=parseInt(a[d?"top":"bottom"],10);e=isNaN(e)?0:e,f=isNaN(f)?0:f;var h=this.layout.size;e-=c?h.paddingLeft:h.paddingRight,f-=d?h.paddingTop:h.paddingBottom,this.position.x=e,this.position.y=f},h.prototype.layoutPosition=function(){var a=this.layout.size,b=this.layout.options,c={};b.isOriginLeft?(c.left=this.position.x+a.paddingLeft+"px",c.right=""):(c.right=this.position.x+a.paddingRight+"px",c.left=""),b.isOriginTop?(c.top=this.position.y+a.paddingTop+"px",c.bottom=""):(c.bottom=this.position.y+a.paddingBottom+"px",c.top=""),this.css(c),this.emitEvent("layout",[this])};var p=l?function(a,b){return"translate3d("+a+"px, "+b+"px, 0)"}:function(a,b){return"translate("+a+"px, "+b+"px)"};h.prototype._transitionTo=function(a,b){this.getPosition();var c=this.position.x,d=this.position.y,e=parseInt(a,10),f=parseInt(b,10),g=e===this.position.x&&f===this.position.y;if(this.setPosition(a,b),g&&!this.isTransitioning)return void this.layoutPosition();var h=a-c,i=b-d,j={},k=this.layout.options;h=k.isOriginLeft?h:-h,i=k.isOriginTop?i:-i,j.transform=p(h,i),this.transition({to:j,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},h.prototype.goTo=function(a,b){this.setPosition(a,b),this.layoutPosition()},h.prototype.moveTo=k?h.prototype._transitionTo:h.prototype.goTo,h.prototype.setPosition=function(a,b){this.position.x=parseInt(a,10),this.position.y=parseInt(b,10)},h.prototype._nonTransition=function(a){this.css(a.to),a.isCleaning&&this._removeStyles(a.to);for(var b in a.onTransitionEnd)a.onTransitionEnd[b].call(this)},h.prototype._transition=function(a){if(!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(a);var b=this._transn;for(var c in a.onTransitionEnd)b.onEnd[c]=a.onTransitionEnd[c];for(c in a.to)b.ingProperties[c]=!0,a.isCleaning&&(b.clean[c]=!0);if(a.from){this.css(a.from);var d=this.element.offsetHeight;d=null}this.enableTransition(a.to),this.css(a.to),this.isTransitioning=!0};var q=j&&d(j)+",opacity";h.prototype.enableTransition=function(){this.isTransitioning||(this.css({transitionProperty:q,transitionDuration:this.layout.options.transitionDuration}),this.element.addEventListener(m,this,!1))},h.prototype.transition=h.prototype[i?"_transition":"_nonTransition"],h.prototype.onwebkitTransitionEnd=function(a){this.ontransitionend(a)},h.prototype.onotransitionend=function(a){this.ontransitionend(a)};var r={"-webkit-transform":"transform","-moz-transform":"transform","-o-transform":"transform"};h.prototype.ontransitionend=function(a){if(a.target===this.element){var b=this._transn,d=r[a.propertyName]||a.propertyName;if(delete b.ingProperties[d],c(b.ingProperties)&&this.disableTransition(),d in b.clean&&(this.element.style[a.propertyName]="",delete b.clean[d]),d in b.onEnd){var e=b.onEnd[d];e.call(this),delete b.onEnd[d]}this.emitEvent("transitionEnd",[this])}},h.prototype.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(m,this,!1),this.isTransitioning=!1},h.prototype._removeStyles=function(a){var b={};for(var c in a)b[c]="";this.css(b)};var s={transitionProperty:"",transitionDuration:""};return h.prototype.removeTransitionStyles=function(){this.css(s)},h.prototype.removeElem=function(){this.element.parentNode.removeChild(this.element),this.emitEvent("remove",[this])},h.prototype.remove=function(){if(!i||!parseFloat(this.layout.options.transitionDuration))return void this.removeElem();var a=this;this.on("transitionEnd",function(){return a.removeElem(),!0}),this.hide()},h.prototype.reveal=function(){delete this.isHidden,this.css({display:""});var a=this.layout.options;this.transition({from:a.hiddenStyle,to:a.visibleStyle,isCleaning:!0})},h.prototype.hide=function(){this.isHidden=!0,this.css({display:""});var a=this.layout.options;this.transition({from:a.visibleStyle,to:a.hiddenStyle,isCleaning:!0,onTransitionEnd:{opacity:function(){this.isHidden&&this.css({display:"none"})}}})},h.prototype.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},h}var f=a.getComputedStyle,g=f?function(a){return f(a,null)}:function(a){return a.currentStyle};"function"==typeof define&&define.amd?define("outlayer/item",["eventEmitter/EventEmitter","get-size/get-size","get-style-property/get-style-property"],e):"object"==typeof exports?module.exports=e(require("wolfy87-eventemitter"),require("get-size"),require("desandro-get-style-property")):(a.Outlayer={},a.Outlayer.Item=e(a.EventEmitter,a.getSize,a.getStyleProperty))}(window),function(a){function b(a,b){for(var c in b)a[c]=b[c];return a}function c(a){return"[object Array]"===l.call(a)}function d(a){var b=[];if(c(a))b=a;else if(a&&"number"==typeof a.length)for(var d=0,e=a.length;e>d;d++)b.push(a[d]);else b.push(a);return b}function e(a,b){var c=n(b,a);-1!==c&&b.splice(c,1)}function f(a){return a.replace(/(.)([A-Z])/g,function(a,b,c){return b+"-"+c}).toLowerCase()}function g(c,g,l,n,o,p){function q(a,c){if("string"==typeof a&&(a=h.querySelector(a)),!a||!m(a))return void(i&&i.error("Bad "+this.constructor.namespace+" element: "+a));this.element=a,this.options=b({},this.constructor.defaults),this.option(c);var d=++r;this.element.outlayerGUID=d,s[d]=this,this._create(),this.options.isInitLayout&&this.layout()}var r=0,s={};return q.namespace="outlayer",q.Item=p,q.defaults={containerStyle:{position:"relative"},isInitLayout:!0,isOriginLeft:!0,isOriginTop:!0,isResizeBound:!0,isResizingContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}},b(q.prototype,l.prototype),q.prototype.option=function(a){b(this.options,a)},q.prototype._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),b(this.element.style,this.options.containerStyle),this.options.isResizeBound&&this.bindResize()},q.prototype.reloadItems=function(){this.items=this._itemize(this.element.children)},q.prototype._itemize=function(a){for(var b=this._filterFindItemElements(a),c=this.constructor.Item,d=[],e=0,f=b.length;f>e;e++){var g=b[e],h=new c(g,this);d.push(h)}return d},q.prototype._filterFindItemElements=function(a){a=d(a);for(var b=this.options.itemSelector,c=[],e=0,f=a.length;f>e;e++){var g=a[e];if(m(g))if(b){o(g,b)&&c.push(g);for(var h=g.querySelectorAll(b),i=0,j=h.length;j>i;i++)c.push(h[i])}else c.push(g)}return c},q.prototype.getItemElements=function(){for(var a=[],b=0,c=this.items.length;c>b;b++)a.push(this.items[b].element);return a},q.prototype.layout=function(){this._resetLayout(),this._manageStamps();var a=void 0!==this.options.isLayoutInstant?this.options.isLayoutInstant:!this._isLayoutInited;this.layoutItems(this.items,a),this._isLayoutInited=!0},q.prototype._init=q.prototype.layout,q.prototype._resetLayout=function(){this.getSize()},q.prototype.getSize=function(){this.size=n(this.element)},q.prototype._getMeasurement=function(a,b){var c,d=this.options[a];d?("string"==typeof d?c=this.element.querySelector(d):m(d)&&(c=d),this[a]=c?n(c)[b]:d):this[a]=0},q.prototype.layoutItems=function(a,b){a=this._getItemsForLayout(a),this._layoutItems(a,b),this._postLayout()},q.prototype._getItemsForLayout=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];e.isIgnored||b.push(e)}return b},q.prototype._layoutItems=function(a,b){function c(){d.emitEvent("layoutComplete",[d,a])}var d=this;if(!a||!a.length)return void c();this._itemsOn(a,"layout",c);for(var e=[],f=0,g=a.length;g>f;f++){var h=a[f],i=this._getItemLayoutPosition(h);i.item=h,i.isInstant=b||h.isLayoutInstant,e.push(i)}this._processLayoutQueue(e)},q.prototype._getItemLayoutPosition=function(){return{x:0,y:0}},q.prototype._processLayoutQueue=function(a){for(var b=0,c=a.length;c>b;b++){var d=a[b];this._positionItem(d.item,d.x,d.y,d.isInstant)}},q.prototype._positionItem=function(a,b,c,d){d?a.goTo(b,c):a.moveTo(b,c)},q.prototype._postLayout=function(){this.resizeContainer()},q.prototype.resizeContainer=function(){if(this.options.isResizingContainer){var a=this._getContainerSize();a&&(this._setContainerMeasure(a.width,!0),this._setContainerMeasure(a.height,!1))}},q.prototype._getContainerSize=k,q.prototype._setContainerMeasure=function(a,b){if(void 0!==a){var c=this.size;c.isBorderBox&&(a+=b?c.paddingLeft+c.paddingRight+c.borderLeftWidth+c.borderRightWidth:c.paddingBottom+c.paddingTop+c.borderTopWidth+c.borderBottomWidth),a=Math.max(a,0),this.element.style[b?"width":"height"]=a+"px"}},q.prototype._itemsOn=function(a,b,c){function d(){return e++,e===f&&c.call(g),!0}for(var e=0,f=a.length,g=this,h=0,i=a.length;i>h;h++){var j=a[h];j.on(b,d)}},q.prototype.ignore=function(a){var b=this.getItem(a);b&&(b.isIgnored=!0)},q.prototype.unignore=function(a){var b=this.getItem(a);b&&delete b.isIgnored},q.prototype.stamp=function(a){if(a=this._find(a)){this.stamps=this.stamps.concat(a);for(var b=0,c=a.length;c>b;b++){var d=a[b];this.ignore(d)}}},q.prototype.unstamp=function(a){if(a=this._find(a))for(var b=0,c=a.length;c>b;b++){var d=a[b];e(d,this.stamps),this.unignore(d)}},q.prototype._find=function(a){return a?("string"==typeof a&&(a=this.element.querySelectorAll(a)),a=d(a)):void 0},q.prototype._manageStamps=function(){if(this.stamps&&this.stamps.length){this._getBoundingRect();for(var a=0,b=this.stamps.length;b>a;a++){var c=this.stamps[a];this._manageStamp(c)}}},q.prototype._getBoundingRect=function(){var a=this.element.getBoundingClientRect(),b=this.size;this._boundingRect={left:a.left+b.paddingLeft+b.borderLeftWidth,top:a.top+b.paddingTop+b.borderTopWidth,right:a.right-(b.paddingRight+b.borderRightWidth),bottom:a.bottom-(b.paddingBottom+b.borderBottomWidth)}},q.prototype._manageStamp=k,q.prototype._getElementOffset=function(a){var b=a.getBoundingClientRect(),c=this._boundingRect,d=n(a),e={left:b.left-c.left-d.marginLeft,top:b.top-c.top-d.marginTop,right:c.right-b.right-d.marginRight,bottom:c.bottom-b.bottom-d.marginBottom};return e},q.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},q.prototype.bindResize=function(){this.isResizeBound||(c.bind(a,"resize",this),this.isResizeBound=!0)},q.prototype.unbindResize=function(){this.isResizeBound&&c.unbind(a,"resize",this),this.isResizeBound=!1},q.prototype.onresize=function(){function a(){b.resize(),delete b.resizeTimeout}this.resizeTimeout&&clearTimeout(this.resizeTimeout);var b=this;this.resizeTimeout=setTimeout(a,100)},q.prototype.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},q.prototype.needsResizeLayout=function(){var a=n(this.element),b=this.size&&a;return b&&a.innerWidth!==this.size.innerWidth},q.prototype.addItems=function(a){var b=this._itemize(a);return b.length&&(this.items=this.items.concat(b)),b},q.prototype.appended=function(a){var b=this.addItems(a);b.length&&(this.layoutItems(b,!0),this.reveal(b))},q.prototype.prepended=function(a){var b=this._itemize(a);if(b.length){var c=this.items.slice(0);this.items=b.concat(c),this._resetLayout(),this._manageStamps(),this.layoutItems(b,!0),this.reveal(b),this.layoutItems(c)}},q.prototype.reveal=function(a){var b=a&&a.length;if(b)for(var c=0;b>c;c++){var d=a[c];d.reveal()}},q.prototype.hide=function(a){var b=a&&a.length;if(b)for(var c=0;b>c;c++){var d=a[c];d.hide()}},q.prototype.getItem=function(a){for(var b=0,c=this.items.length;c>b;b++){var d=this.items[b];if(d.element===a)return d}},q.prototype.getItems=function(a){if(a&&a.length){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c],f=this.getItem(e);f&&b.push(f)}return b}},q.prototype.remove=function(a){a=d(a);var b=this.getItems(a);if(b&&b.length){this._itemsOn(b,"remove",function(){this.emitEvent("removeComplete",[this,b])});for(var c=0,f=b.length;f>c;c++){var g=b[c];g.remove(),e(g,this.items)}}},q.prototype.destroy=function(){var a=this.element.style;a.height="",a.position="",a.width="";for(var b=0,c=this.items.length;c>b;b++){var d=this.items[b];d.destroy()}this.unbindResize();var e=this.element.outlayerGUID;delete s[e],delete this.element.outlayerGUID,j&&j.removeData(this.element,this.constructor.namespace)},q.data=function(a){var b=a&&a.outlayerGUID;return b&&s[b]},q.create=function(a,c){function d(){q.apply(this,arguments)}return Object.create?d.prototype=Object.create(q.prototype):b(d.prototype,q.prototype),d.prototype.constructor=d,d.defaults=b({},q.defaults),b(d.defaults,c),d.prototype.settings={},d.namespace=a,d.data=q.data,d.Item=function(){p.apply(this,arguments)},d.Item.prototype=new p,g(function(){for(var b=f(a),c=h.querySelectorAll(".js-"+b),e="data-"+b+"-options",g=0,k=c.length;k>g;g++){var l,m=c[g],n=m.getAttribute(e);try{l=n&&JSON.parse(n)}catch(o){i&&i.error("Error parsing "+e+" on "+m.nodeName.toLowerCase()+(m.id?"#"+m.id:"")+": "+o);continue}var p=new d(m,l);j&&j.data(m,a,p)}}),j&&j.bridget&&j.bridget(a,d),d},q.Item=p,q}var h=a.document,i=a.console,j=a.jQuery,k=function(){},l=Object.prototype.toString,m="function"==typeof HTMLElement||"object"==typeof HTMLElement?function(a){return a instanceof HTMLElement}:function(a){return a&&"object"==typeof a&&1===a.nodeType&&"string"==typeof a.nodeName},n=Array.prototype.indexOf?function(a,b){return a.indexOf(b)}:function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1};"function"==typeof define&&define.amd?define("outlayer/outlayer",["eventie/eventie","doc-ready/doc-ready","eventEmitter/EventEmitter","get-size/get-size","matches-selector/matches-selector","./item"],g):"object"==typeof exports?module.exports=g(require("eventie"),require("doc-ready"),require("wolfy87-eventemitter"),require("get-size"),require("desandro-matches-selector"),require("./item")):a.Outlayer=g(a.eventie,a.docReady,a.EventEmitter,a.getSize,a.matchesSelector,a.Outlayer.Item)}(window),function(a){function b(a,b){var d=a.create("masonry");return d.prototype._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns();var a=this.cols;for(this.colYs=[];a--;)this.colYs.push(0);this.maxY=0},d.prototype.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var a=this.items[0],c=a&&a.element;this.columnWidth=c&&b(c).outerWidth||this.containerWidth}this.columnWidth+=this.gutter,this.cols=Math.floor((this.containerWidth+this.gutter)/this.columnWidth),this.cols=Math.max(this.cols,1)},d.prototype.getContainerWidth=function(){var a=this.options.isFitWidth?this.element.parentNode:this.element,c=b(a);this.containerWidth=c&&c.innerWidth},d.prototype._getItemLayoutPosition=function(a){a.getSize();var b=a.size.outerWidth%this.columnWidth,d=b&&1>b?"round":"ceil",e=Math[d](a.size.outerWidth/this.columnWidth);e=Math.min(e,this.cols);for(var f=this._getColGroup(e),g=Math.min.apply(Math,f),h=c(f,g),i={x:this.columnWidth*h,y:g},j=g+a.size.outerHeight,k=this.cols+1-f.length,l=0;k>l;l++)this.colYs[h+l]=j;return i},d.prototype._getColGroup=function(a){if(2>a)return this.colYs;for(var b=[],c=this.cols+1-a,d=0;c>d;d++){var e=this.colYs.slice(d,d+a);b[d]=Math.max.apply(Math,e)}return b},d.prototype._manageStamp=function(a){var c=b(a),d=this._getElementOffset(a),e=this.options.isOriginLeft?d.left:d.right,f=e+c.outerWidth,g=Math.floor(e/this.columnWidth);g=Math.max(0,g);var h=Math.floor(f/this.columnWidth);h-=f%this.columnWidth?0:1,h=Math.min(this.cols-1,h);for(var i=(this.options.isOriginTop?d.top:d.bottom)+c.outerHeight,j=g;h>=j;j++)this.colYs[j]=Math.max(i,this.colYs[j])},d.prototype._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var a={height:this.maxY};return this.options.isFitWidth&&(a.width=this._getContainerFitWidth()),a},d.prototype._getContainerFitWidth=function(){for(var a=0,b=this.cols;--b&&0===this.colYs[b];)a++;return(this.cols-a)*this.columnWidth-this.gutter},d.prototype.needsResizeLayout=function(){var a=this.containerWidth;return this.getContainerWidth(),a!==this.containerWidth},d}var c=Array.prototype.indexOf?function(a,b){return a.indexOf(b)}:function(a,b){for(var c=0,d=a.length;d>c;c++){var e=a[c];if(e===b)return c}return-1};"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size"],b):"object"==typeof exports?module.exports=b(require("outlayer"),require("get-size")):a.Masonry=b(a.Outlayer,a.getSize)}(window);;
window.EQTR = (function (module, $) {
  "use strict";

  var _useAjaxLoading = !window.disableAjaxPageLoading && (window.history && history.pushState && !EQTR.detectDevice.isIOS5());

  // stick some stuff onto the base object
  //    module. = {
  //    };

  var TransitionTypes = {
    PopupOpen: "open-popup",
    PopupClose: "popup-close",
    Standard: "standard"
  },
      pageframe = $(".page-frame"),
      cache = {},
      pageAjaxRequest,
      previousHref = "";

  //window.cache = cache;
  // specific submodule for ajax loading
  var submodule = {
    init: function () {
      if (!submodule.useAjaxLoading) return;

      //module.ajaxCurrentContent = $(".page-frame .page-content").slice(0,1);

      // setup the history object
      History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
        var state = History.getState(); // Note: We are using History.getState() instead of event.state

        // clear out a javascript popup if it exists
        $(".js-fake-popup").click();

        // get the page with ajax
        //                console.info(state.data, state.url, location.href);
        //                state.data.tabChange = null;
        if (previousHref.replace(/\?tab=.*/, "") != state.url.replace(/\?tab=.*/, "")) {
          submodule.switchPageContent(state.url, state.data, pageframe);
        }

        previousHref = "";

      });

      var hashRegExp = new RegExp(location.host + "/#", "i");
      var hostRegExp = new RegExp(location.host, "i");

      // capture all anchor clicks on the body.
      // NOTE: This used to use "document" as the bubble capture, but the VEInteractive tags have caused the document to preventDefault on clicks. Don't know why

      $("body").on("click", "a:not(.no-ajax-load)", function (e) {
        var href = this.href;

        // make sure the link is good to ajaxify
        // - no links that have been stopped with javascript
        // - must have an href
        // - must be linking to the current host
        // - mustn't be an anchor hash
        // - mustn't open in a new open window
        // - mustn't be link to a file
        // - mustn't be a sitemap link
        // - mustn't be stopped from the link itself with .no-ajax-load

        if (e.isDefaultPrevented() || !href || !hostRegExp.test(href) || hashRegExp.test(href) || this.target || href.match(/\.(pdf|jpg|png|gif|jpeg)/i) || $(".sitemap-page").find(this).length) return true;

        // get the type of transition from the type of link
        // "open-popup"
        // "popup-close"
        // nowt = use single frame transition "standard"
        var contentTransition = "standard";
        if (this.className.match(/(open-popup|popup-close)/)) {
          contentTransition = RegExp.$1;
        } else if ($("> .page-content:first", pageframe).hasClass("page-content-popup")) {
          contentTransition = "popup-close";
        }

        // replace the history state if we are closing a popup, don't want to go back to it after it is closed
        //                if (module.ajaxCurrentContent.hasClass("page-content-popup")) {
        //                    History.replaceState(null, "", href);
        //                } else {

        // check to see if this is a tab and on the same page. If it is then replace the history. Need to also do the same check in the stateChange event
        previousHref = location.href;
        if (location.href.replace(/\?tab=.*/, "") != href.replace(/\?tab=.*/, "")) {
			alert("yes");
          History.pushState({ contentTransition: contentTransition }, "", href);
        } else {
			alert("No");
          History.replaceState({ contentTransition: contentTransition }, "", href);
        }


        e.preventDefault();
      });
    },
    useAjaxLoading: _useAjaxLoading
  };

  //    submodule.replaceUrl = function(href) {
  //        History.replaceState({replaceOnly:true}, "", href);
  //    };

  submodule.RetrieveAjaxContent = function (href, frame) {
    var deferred = new $.Deferred();

    pageAjaxRequest = getPageHTML(href);
    if (pageAjaxRequest.fail) {
      pageAjaxRequest.fail(function (xhr, status, error) {
        if (status != "abort") {
          location.href = href;
        } else {
          deferred.reject();
        }
      });
    }

    $.when(pageAjaxRequest).then(function (html) {
      // test to see if we grabbed the whole page instead of just the content.
      // think this has to be done everytime, as we would need to do another deferred within getPageHTML?
      
      if (/<html/.test(html)) {
        var content = $("<div/>");
        content[0].innerHTML = html;
        html = content.find(".page-content:first");
      }

      var newPage = $(html).addClass("ajax-prep").appendTo(frame);

      pageAjaxRequest.abort && (pageAjaxRequest = null);

      // artifical delay to testing loading image
      //            setTimeout(function() {
      deferred.resolve(newPage);
      //            }, 3000);
    });

    return deferred.promise();
  };

  submodule.CancelPage = function () {
    // if the page request is defined, is an xhr request, abort and set to null;
    pageAjaxRequest && pageAjaxRequest.abort && pageAjaxRequest.abort() && (pageAjaxRequest = null);
  };

  function getPageHTML(href) {
    //        alert(href + (/\?/.test(href) ? '&' : '?') + "ajax_request=true");
    return cache[href] ||
        $.ajax({
          url: href + (/\?/.test(href) ? '&' : '?') + "ajax_request=true",
          success: function (html) {
            // this is for pages that have problems with the querystring and redirects are involved
            // the whole page is returned rather than just the partial e.g. Packages
            if (/<html/.test(html)) {
              var content = $("<div/>");
              content[0].innerHTML = html;
              html = content.find(".page-content:first");
              html = $("<div/>").append(html).html();
            }

                    // check to see if this should be cached or not
                    //if (!html.match(/nocache=.true/i)) {
                    //    cache[href] = html;
                    //}

          }
        });
  }

  submodule.switchPageContent = function (href, data, frame) {

    // cancel the current page loading (if it is ajax)
    submodule.CancelPage();
	/*var headerHeight = $("#header_holder").height(),
			winHeight = Math.floor(window.innerHeight || $(window).height()),
			frameSize = winHeight - headerHeight - $(".footer.clear-b").outerHeight(true);
	if(frame.find(".panel-scroll").length > 0)
			{
				if (isMobile) {
					EQTR.css.changeRule(".js .page-frame .panel-scroll", { height: frameSize + "px" });
					EQTR.css.changeRule(".js .page-frame", { height: "auto" });
				}
				else
				{
					EQTR.css.changeRule(".js .page-frame", { height: frameSize + "px"  });
				}
			}*/
    var oldPage = $("> .page-content:first", frame),
        contentPromise = submodule.RetrieveAjaxContent(href, frame);

    if (data.contentTransition == TransitionTypes.PopupClose) {
      submodule.popupOutPageSwitch(frame, oldPage, contentPromise);
    } else if (data.contentTransition == TransitionTypes.PopupOpen) {
      submodule.popupInPageSwitch(frame, contentPromise, oldPage);
    } else {
      submodule.singleFrameSwitch(frame, contentPromise, oldPage);
    }

    $.when(contentPromise).then(function () {
      //console.info(href);
      // need a wee delay on this, because if someone is navigating quickly then lots of pageviews will show up
      EQTR.Analytics.trackPage(href, false, true);
    });

  };

  submodule.singleFrameSwitch = function (frame, contentPromise, oldPage) {

    var overlay = createOverlay(false, frame),
        transitionDeferred;

    if (!overlay.data("init")) {
      overlay
          .data("fadingIn", true)
          .data("init", true)
          .data("deferred", new $.Deferred())
          .on(EQTR.GetTransitionEnd(), function (e) {
            if (overlay.data("fadingIn")) {
              transitionDeferred.resolve();
            } else {
              $(".fade-area").remove();
            }
          });
    }

    transitionDeferred = overlay.data("deferred");

    $.when(contentPromise, transitionDeferred).then(function (newPage) {
      EQTR.InitPageContent(newPage);

      // force layout change. Problem in firefox where transitionend is not fired
      EQTR.ForcePageLayout();

      requestAnimationFrame(function () {
        newPage.addClass("fade-in-underlay").removeClass("ajax-prep");
        oldPage.trigger("close").remove();
        newPage.removeClass("fade-in-underlay");
        //                console.info(overlay.length);
        overlay.addClass("faded").data("fadingIn", false);
        EQTR.ForcePageLayout();

        newPage.trigger("open");
        //                console.info(overlay.hasClass("faded"));
      });
    });

    // force layout change. Problem in firefox where transitionend is not fired
    EQTR.ForcePageLayout();

    requestAnimationFrame(function () {
      overlay.removeClass("faded");
    });
  };

  submodule.popupInPageSwitch = function (frame, contentPromise, oldPage) {
    var overlay;
    // is the popup is generated from code rather than ajax, do something slightly different
    if (contentPromise instanceof jQuery) {
      popIn(contentPromise.addClass("ajax-prep").appendTo(frame), true);
    } else {
      overlay = createOverlay(true, frame).removeClass("faded");
      $.when(contentPromise).then(popIn);
    }

    function popIn(newPage, ignoreInit) {

      if (!ignoreInit) {
        EQTR.InitPageContent(newPage);
      }

      newPage.addClass("popup-in").trigger("opening");

      // force layout change. Transition was happening straightaway. Ajax-prep has "none" transition
      EQTR.ForcePageLayout();

      newPage.removeClass("ajax-prep");

      requestAnimationFrame(function () {

        newPage.one(EQTR.GetTransitionEnd(), function () {
          overlay && overlay.remove();
          if (oldPage) {
            oldPage.trigger("close").remove();
          }
          newPage.trigger("open");
        });

        // force layout change. Problem in firefox where transitionend is not fired
        EQTR.ForcePageLayout();
        newPage.removeClass("popup-in");
      });
    }

  };

  submodule.popupOutPageSwitch = function (frame, oldPage, contentPromise) {

    if (contentPromise) {
      if (contentPromise instanceof jQuery) {
        popOut(contentPromise);
      } else {
        $.when(contentPromise).then(popOut);
      }
    } else {
      popOut();
    }

    function popOut(newPage) {
      requestAnimationFrame(function () {

        function removeOld() {
          // hack for popups that contain iframes that contain flash. Only relevent to vimeo iframe embed in IE10/9 at the moment.
          // removing the iframe with this method causes the browser history to change, so only testing for ie at the moment
          // there is no discrimation, all IE's will probably be targeted.
          var iframe = oldPage.find("iframe");
          if (iframe.length && EQTR.detectDevice.isIE()) {
            iframe.each(function () {
              var f = this;
              f.src = "";
            });

            setTimeout(function () {
              iframe.remove();
              oldPage.remove();
            }, 0);
          } else {
            oldPage.remove();
          }
        }

        if (Modernizr.csstransitions) {
          oldPage.one(EQTR.GetTransitionEnd(), removeOld);
        } else {
          oldPage.fadeOut(removeOld);
        }

        if (newPage) {
          EQTR.InitPageContent(newPage);
          newPage.removeClass("ajax-prep");
        }

        oldPage.trigger("close");

        if (Modernizr.csstransitions) {
          oldPage.addClass("popup-in");
        }

        // force layout change. Problem in firefox where transitionend is not fired
        EQTR.ForcePageLayout();
      });
    }

  };

  /*    submodule.squareSwitch = function (frame, oldPage, newPage) {
          var r = 1,
              c = 2,
              n = r * c,
              w = 100 / c,
              h = 100 / r,
              timer = 750,
              t = timer / (n * 1000);
  
          frame.append(newPage.addClass("fade-in-underlay"));
  
          EQTR.InitPageContent(newPage);
  
          // create the squares
          for (var a = [], x = 0; x < c; x++) {
              for (var y = 0; y < r; y++) {
                  var index = x * r + y;
                  a[index] = { n: index + 1, c: x, r: y };
              }
          }
  
          a = EQTR.helpers.shuffleArray(a);
  
          var squares = [];
  
  
  
          for (var x = 0; x < n; x++) {
              var s = a[x];
              squares.push('<div class="fade-area fa' + x + '" style="transition-delay:' + (t * x) + 's;width:' + w + '%;height:' + h + '%;left:' + (s.c * w) + '%;top:' + (s.r * h) + '%;" />');
          }
  
          var squareContainer = $('<div class="fade-container" />').addClass("faded").append(squares.join(""));
  
          var fadingIn = true;
  
          squareContainer.appendTo(frame).on(EQTR.GetTransitionEnd(), ".fa" + (n - 1), function () {
              if (fadingIn) {
                  requestAnimationFrame(function () {
                      oldPage.remove();
                      newPage.removeClass("fade-in-underlay");
                      squareContainer.addClass("faded");
                      fadingIn = false;
                  });
              } else {
                  squareContainer.remove();
              }
          });
  
          setTimeout(function () {
              squareContainer.removeClass("faded");
          }, 1);
      };*/

  function createOverlay(isPopup, frame) {
    // see if there is already an overlay and use that
    var overlay = $(".fade-area");

    if (!overlay.length) {
      overlay = $('<div class="fade-area faded"><span class="icon-rocco"></span></div>');
      var logo = overlay.find("span");
      var transitioned = false;
      logo.on(EQTR.GetTransitionEnd(), function (e) {
        // all properties that change are passed through here, but I only care about the first one, because they all finish at the same time
        if (!transitioned) {
          overlay.toggleClass("logo-transition");
          setTimeout(function () {
            transitioned = false;
          }, 1);
        }
        transitioned = true;
        return false;
      });

      overlay.appendTo(frame);

      requestAnimationFrame(function () {
        overlay.toggleClass("logo-transition");
      });
    }

    overlay.toggleClass("fade-area-popup", !!isPopup);

    return overlay;
  }

  module.ajax = submodule;

  return module;
})(window.EQTR || {}, window.jQuery);;
window.EQTR = (function (module, $, undefined) {
    "use strict";

    // nicescroll setup
    var niceScrollOptions = {
        //                autohidemode: "cursor",
        cursorborderradius: 12,
        cursorwidth: 14,
        cursropacitymax: 0.4,
        cursorcolor: "#fff",
        horizrailenabled: false,
        autohidemode: false,
        //        railoffset:{left:20},
        cursorborder: "3px solid transparent"
    },
        _transitionEnd,
        _pageframe = $(".page-frame");

    // all of these methods will be called when the page loads. They should be specific to the outer frame and required to be loaded again if content is requested via ajax
    var startupMethods = {
        languagePicker: function () {

            var languagePicker = $(".language-picker"),
                languageList = $(".language-picker-list", languagePicker),
                languageFriendlyName = EQTR.language.localName;

            // put the anchor in place for selecting the language
            var toggleLanguage = $('<a class="language-toggle" id="language-toggle" href="#">' + languageFriendlyName + ' <span class="icon icon-angle-down"></span></a>');

            // insert the toggle before the current list
            toggleLanguage.insertBefore(languageList);

            // move the list into the frame. Should make it easier for sizing etc
            $(".page-main").append(languageList);

            toggleLanguage.togglePanel({
                panel: languageList,
                linkOpenClass: "open"
            });


            //            $('.language-picker').on("mouseenter", function () {
            //               $('.footer-section-title .icon').addClass('rotated-half');
            //          }).on("mouseleave", function () {
            //             setTimeout(function () {
            //                $('.footer-section-title .icon').removeClass('rotated-half');
            //           }, 1500);
            //      });

        },

        CookieWarning: function () {
            // check the cookie and see if they have seen the warning before,
            // if not show the warning and set the cookie. Going to use the same setup as the cookie created by .net
            // not doing this in .net because of the caching
            if (!/cookie_warning/i.test(document.cookie)) {
                // move this to the top of the page in the header
                var cookieWarning = $(".cookie-warning");
                $(".page-header").prepend(cookieWarning);

                $(".cookie-warning").show()
                    .find("input")
                    .click(function (event) {
                        event.preventDefault();
                    });

                $("body").one("click", function () {
					
						var carousel = $('#myCarousel');
                            var header_holder = $('#header_holder');
                            var mobile_buttons = $('.mobile-buttons');
                            var cookie_warning = $('.cookie-warning');
							var slick_slider = $('.slick-slider');

							slick_slider.find('.item').each(function (index) {
								if (isMobile)
								{
									$(this).height($(window).height() - header_holder.height() - mobile_buttons.height() );
								}
								else
								{
									$(this).height($(window).height() - header_holder.height());
								}
							});
							if (isMobile)
							{
								slick_slider.height($(window).height() - header_holder.height() - mobile_buttons.height() );
							}
							else
							{
								slick_slider.height($(window).height() - header_holder.height());
							}
							
							var travel_information_top = 150;
							if (isMobile) {
								travel_information_top = 80;
							}
							$(".travel-information").css("top", travel_information_top);
							
							$(".cookie-warning").remove();
							EQTR.ExecResizeQueue();
					//setTimeout(function () {
						$(".cookie-warning").slideUp(function () {

							
							
					//}, 1000);

                });
				
            });
    var expire = new Date();
    expire.setMonth(expire.getMonth() + 6);
    document.cookie = "cookie_warning=viewed=1;path=/;expires=" + expire.toUTCString();
}

		},

SetupPageFrameSize: function () {
    EQTR.AddToResizeQueue(module.SetPageFrameSize, 0);
},
BasePageSetup: function () {

    if (EQTR.detectDevice.supportsPointer) {
        // add this to help ie10+ work on desktop. Don't know about the surface
        //$("body").css("-ms-touch-action", "none").css("touch-action", "none");
    }

    // site-nav uses different nicescroll styling
    if (EQTR.detectDevice.isDesktop() || EQTR.detectDevice.isIOS5()) {
        var siteNavScroll = $(".site-nav").niceScroll($.extend({}, niceScrollOptions, { background: "#292929", cursoropacitymax: 1 })).hide();
        siteNavScroll.each(function () {
            $(this.rail).addClass("site-nav-nicescroll");
        });
    }

    // Mad ios7 bug
    if (navigator.userAgent.match(/iPad;.*CPU.*OS 7_\d/i) && window.innerHeight != document.documentElement.clientHeight) {
        var fixViewportHeight = function () {
            document.documentElement.style.height = window.innerHeight + "px";
            if (document.body.scrollTop !== 0) {
                window.scrollTo(0, 0);
            }
        }.bind(this);

        window.addEventListener("orientationchange", fixViewportHeight, false);
        fixViewportHeight();

        //document.body.style.webkitTransform = "translate3d(0,0,0)";
    }

    // virtual tour setup
    // video popup setup
    var iframePopupHTML = '<div class="page-content page-content-popup"><div class="iframe-container"><iframe id="iframePopup" name="iframePopup{1}" scrolling="no" frameborder="0" src="{0}"></iframe></div></div>';

    $("body").on("click", ".virtual-tour a", function (e) {
        e.preventDefault();

        var href = this.href,
            pageContent = $(".page-content");

        var niceScroll = pageContent.find(".nice-scroll");

        niceScroll.getNiceScroll().hide();

        var iframe = $(iframePopupHTML.format(href, EQTR.helpers.generateUuid())),
            close = $('<a href="#" class="popup-close js-fake-popup">x</a>').appendTo(_pageframe);

        iframe.on("destroyed", function () {
            // need to get the nicescroll instances because they are destroyed when then the content block is destroyed by the ajax loading script
            // the script calls this function, but the scrollers were already gone.
            niceScroll.getNiceScroll().show();
            close.remove();
        });

        close.click(function () {
			EQTR.ajax.popupOutPageSwitch(_pageframe, iframe);
            return false;
        });

        EQTR.ajax.popupInPageSwitch(_pageframe, iframe);

    });



    // content resizing setup
    EQTR.AddToResizeQueue(function () {
        $(".content-heading").fitword();
    });


    // ajax page loading init setup
    EQTR.ajax.init();

    // print page setup
    $(window).on("print", function () {
        $(".forte-team:not(.print-set)").addClass("print-set").find(".responsive-background-image,.responsive-background").each(function () {
            $(this).before('<img class="print-only" src="' + $(this).data("image") + '?width=320&height=197&mode=crop" />');
        });
    });
},
AddLanguageWrapper: function () {
    //EQTR.language.arabicEnconder = function(content) {
    //	//content should be a string
    //	if (EQTR.language.isRTL) {
    //		findAndReplaceDOMText($(content)[0], {
    //			find: /(?:\$|£|€) ?\d+(?:\.\d+)?|\[\[([^\]]+)\]\]/g,
    //			wrap: 'ltre',
    //			portionMode: "retain"
    //			//replace: function (portion, match) {
    //			//  return portion.text.replace(/\[|\]/g, "");
    //			//}
    //		});

    //		$(content).find('ltre').attr('dir', 'ltr');
    //	}
    //};
}
	};

module.SetPageFrameSize = function () {
    var bookingPanel = $(".booking-panel"),
        headerHeight = $("#header_holder").height(),
        winHeight = Math.floor(window.innerHeight || $(window).height()),
        bookingTabs = $('.booking-panel-tabs'),
        bookingBarHeight = $(".booking-panel").length ? Math.max(bookingTabs[0].offsetHeight, !bookingTabs.is(":visible") && bookingPanel.css("visibility") == "visible" ? bookingPanel.outerHeight() : 0) : 0;

    var frameSize = winHeight - headerHeight - $(".footer.clear-b").outerHeight(true);

    EQTR.css.changeRule(".js .booking-panel.menu-open", { height: frameSize + 'px' });

    if (_pageframe.length > 0) {
        if (_pageframe.find(".panel-scroll").length > 0 || _pageframe.find(".horizontal-half.nice-scroll").length > 0 || _pageframe.find(".iframe-container").length) {
            if (isMobile) {
                EQTR.css.changeRule(".js .page-frame .panel-scroll", { height: frameSize + "px" });
				if(_pageframe.find(".iframe-container").length)
				{
					EQTR.css.changeRule(".js .page-frame", { height: frameSize + "px" });
				}
				else
				{
					EQTR.css.changeRule(".js .page-frame", { height: "auto" });
					
				}
                //EQTR.css.changeRule(".js .page-frame", { height: "auto" });
            }
            else {
                //frameSize=frameSize+50;
                EQTR.css.changeRule(".js .page-frame", { height: frameSize + "px" });
            }
        }
        else {
            EQTR.css.changeRule(".js .page-frame", { height: "auto" });
        }
    }
    //}
    //EQTR.css.changeRule(".js .page-frame", { height: "320px" });
};

// this only happens at full page load. I think.
module.ShowPageContent = function (skipTransition) {
    var html = $("html");

    if (skipTransition) {
        html.addClass("skip-transition");
    }

    requestAnimationFrame(function () {
        $("html").removeClass("hide-page-content").removeClass("skip-transition");
    });

    if (!Modernizr.csstransitions) {
        // fade the page in
        $(".page-content").hide().fadeIn(800);
    }

    /*if (window.sessionStorage && !sessionStorage["menureveal"] && EQTR.detectDevice.isHandHeld()) {
        if (!$(".booking-panel-tabs:visible").length) {*/
    /*EQTR.navigation.open(800, function () {
        EQTR.navigation.close(5000);
    });*/
    /*sessionStorage["menureveal"] = true;
}
}*/
};

module.GetTransitionEnd = function () {
    if (_transitionEnd != undefined) {
        return _transitionEnd;
    }

    _transitionEnd = null;

    var t;
    var el = document.createElement('div');
    var transitions = {
        'transition': 'transitionend',
        'MSTransition': 'msTransitionEnd',
        'MozTransition': 'transitionend',
        'WebkitTransition': 'webkitTransitionEnd'
    };

    for (t in transitions) {
        if (el.style[t] !== undefined) {
            _transitionEnd = transitions[t];
        }
    }

    return _transitionEnd;
};

// Adding some Jank, for force a repaint
module.ForcePageLayout = function () {
    var temp = _pageframe[0].offsetHeight;
};

module.GotoPage = function (href) {

    if (module.ajax.useAjaxLoading) {
        History.pushState(null, "", href);
    } else {
        location.href = href;
    }
};

var _noBackground;
module.NoBackgroundStyle = function () {
    if (!_noBackground) {

        var div = $('<div style="background:none;"/>').appendTo("body");
        _noBackground = div.css("background");
    }
    return _noBackground;
};

// google maps helpers

module.loadGoogleMapApi = function (callback, strOptions) {

    strOptions = strOptions ? [strOptions] : [];

    // check to see if maps has been loaded
    if (window.google && google.maps) {
        callback && callback();

    } else {
        // make sure that this is only being called the once
        if (module.loadGoogleMapApi.loading) {
            return;
        }

        module.loadGoogleMapApi.loading = true;

        // add temp callback
        window.googleMapsCallBack = function () {
            module.loadGoogleMapApi.loading = false;
            callback && callback();
            // delete the callback
            window.googleMapsCallBack = null;
        };

        if (EQTR.language.code != "en") {
            strOptions.push("language=" + EQTR.language.code);
        }

        var script = document.createElement("script");
        script.type = 'text/javascript';
        script.async = true;
        //script.src = "//maps.google.com/maps/api/js?v=3&sensor=false&callback=googleMapsCallBack&" + (strOptions.length ? strOptions.join("&") : "");
		script.src = "//maps.google.com/maps/api/js?v=3&sensor=false&key=AIzaSyBMVUVUvF7H8eO9k2PXZpQZ4d3ld6yg83s&callback=googleMapsCallBack&" + (strOptions.length ? strOptions.join("&") : "");
		
        document.getElementsByTagName('head')[0].appendChild(script);
    }
};

// used only to initialise the page content area
module.InitPageContent = function (context) {
    var splitScroll, coverImage, panelScroll, niceScroll, falseAnchorClick, simpleScroll, focus, scrollerArrow, form, popup, ajaxContent = context != undefined, pageContentContainer;

    // if the context has been set i.e. from ajax, do things.

    if (ajaxContent) {
        //get the page title from the element
        document.title = context.data("pagetitle");

        // set the language urls
        var languageUrls = context.data("languageurls");
        if (languageUrls && languageUrls.length) {
            $(".language-picker-list a").attr("href", function (index) {
                return languageUrls[index].Url;
            });
        }

        // set the menu if it hasn't been set
        //EQTR.navigation.setMenu(context.data("menunodeid"), context.data("nodeid"), context);

        // remove ajax stuff from forms just in case
        $("form[action]", context).attr("action", function (index, value) { return value.replace(/(\?|%3F)ajax_request(=|%3D).*/i, ""); });

        // set the language warning message for pages that aren't translated
        var isTranslated = context.data("pagetranslated") == "True";

        $(".locale-error-message").toggleClass("hide-locale-error-message", isTranslated);

        // find out if the main content is a popup
        context.hasClass("page-content-popup") && (popup = context);

        pageContentContainer = context;

    } else {
        // find out if the main content is a popup
        popup = _pageframe.find("> .page-content-popup");
        pageContentContainer = $(".page-content", document).eq(0);
    }

    context = context || document;

    // ARABIC ENCODE FINDER: check whether is arabic(rtl) and find and replace (?:\$|£|€) ?\d+(?:\.\d+)?|\[\[([^\]]+)\]\]
    EQTR.language.arabicEnconder(context);

    // social media frame dynamic links
    var facebookUrl = pageContentContainer.data("facebookurl");
    $('.frame-social .facebook-link').attr("href", function () {
        $(this)[facebookUrl ? "show" : "hide"]();
        return facebookUrl || "";
    });

    var instagramUrl = pageContentContainer.data("instagramurl");
    $('.frame-social .instagram-link').attr("href", function () {
        $(this)[instagramUrl ? "show" : "hide"]();
        return instagramUrl || "";
    });

    var twitterUrl = pageContentContainer.data('twitterurl');
    $('.frame-social .twitter-link').attr("href", function () {
        $(this)[twitterUrl ? "show" : "hide"]();
        return twitterUrl || "";
    });

    var googlePlusUrl = pageContentContainer.data('googleplusurl');
    $('.frame-social .googleplus-link').attr("href", function () {
        $(this)[googlePlusUrl ? "show" : "hide"]();
        return googlePlusUrl || "";
    });

    // this needs to happen once to each new select. The booking panel is being double dipped
    $('select', context).on('onLoad.selectify', function (e) {
        $(this).data().selectMenuContainer.find('.selectify-selectmenu').niceScroll($.extend({ zindex: 9000, autohidemode: false }, niceScrollOptions));
        //$(this).data('selectMenuContainer').find('.selectify-selectmenu').jScrollPane();
    }).on('openmenu.selectify', function (e) {
        //$(this).data('selectMenuContainer').find('.selectify-selectmenu').jScrollPane({ animateScroll: true });
        $(this).data().selectMenuContainer.find('.selectify-selectmenu').getNiceScroll().resize().show();
    }).on('closemenu.selectify', function () {
        $(this).data().selectMenuContainer.find('.selectify-selectmenu').getNiceScroll().hide();
    });

    /* remove empty p tags from rich content */
    $('.rich-content p', context).each(function () {
        var $this = $(this);
        if ($this.html().replace(/\s|&nbsp;/g, '').length == 0)
            $this.remove();
    });

    /* setup booking bar and frame as most other things */
    EQTR.bookingBar.init(context);

    // Trigger the search button override
    EQTR.searchButton.init(context);

    module.SetPageFrameSize();

    // setup the word frame. this is independant of context as it will be inserted in the frame, not the content. The binding to the content
    // happens with an id lookup, so no need to pass the context through (onpageload the context is document)
    // the frame has already been partially primed at this point

    //var hasWordFrame = EQTR.wordFrame.init();

    // if this is the alternate layout, hide the underneath panels
    /*
    var hotelOverlay = $(".hoel-alternate-overlay", context);
	
    if (hotelOverlay.length) {
	
        var overlaySiblings = hotelOverlay.on("click", ".explore-link", function(e) {
            e.preventDefault();
	
            // a popup close is created so click it
            // would be better to do a different method for this, but we are reusing the popup
            overlaySiblings
                .css("visibility", "visible")
                .getNiceScroll().resize().show();
	
            $(".popup-close").click();
	
        }).siblings(".horizontal-half").css("visibility", "hidden");
    }*/

    // popup setup e.g. menus. need to put the close button outside, because devices and transitions are having problems with the position fixed
    if (popup && popup.length) {
        var popupclose = popup.find(".popup-close").appendTo(_pageframe);
        popup.on("opening", function () {
            popupclose.hide();
        }).on("open", function () {
            popupclose.fadeIn("slow");
            niceScroll.getNiceScroll().resize().show();
        }).on("close", function () {
            popupclose.fadeOut("fast", function () { $(this).remove(); });
        }).on("destroyed", function () {
            // catchall fix to remove the popup close. The transitions are sometimes confused when the back button is used
            popupclose.remove();
        });
    }

    /**** component detection *****/
    if ((splitScroll = $(".split-scroll", context)).length) {
        var cloneScroll = splitScroll.clone().addClass("modified").insertBefore(splitScroll).panelScroller({ dualScroll: true, focus: true, dots: false });
        // this is for mobile
        splitScroll.addClass("original").find(".primary-panel").addClass("panel-scroller");
        /*.simplePanelScroller({
        children: ".fill-panel"
    });*/

    }

    if ((simpleScroll = $(".simple-panel-scroller", context)).length) {
        simpleScroll.each(function () {
            $(this).simplePanelScroller();
        });
    }

    if (EQTR.detectDevice.isDesktop() && (coverImage = $(".cover-image", context)).length) {
        coverImage.backgroundCover({ ignoreResize: true });
    }

    if ((scrollerArrow = $(".scroller-arrow", context)).length) {
        scrollerArrow.scrollerArrow();
    }

    // nicescroll setup for content panels
    if ((EQTR.detectDevice.isDesktop() || EQTR.detectDevice.isIOS5()) && (niceScroll = $(".nice-scroll", context).addBack(".nice-scroll")).length) {
        niceScroll
            .on("destroyed", function () {
                $(this).getNiceScroll().remove();
            }).niceScroll($.extend({}, niceScrollOptions)).hide();
    }

    if ((panelScroll = $(".panel-scroll", context)).length) {
        panelScroll.panelScroller({ autoScroll: true, dots: false });
        //panelScroll.panelScroller({ autoScroll: !hasWordFrame, dots: false });

        //EQTR.wordFrame.onClose(function () {
        //    panelScroll.panelScroller("startAutoScroll");
        //});

        //$(".content-heading", panelScroll).fitword();
    }

    if ((falseAnchorClick = $(".hotel-listing li")).length) {
        falseAnchorClick.click(function (e) {

            if ($(this).data("src")) {
                // need to prevent default because of links within the falseAnchorClick call the ajax module twice
                e.preventDefault();
                module.GotoPage($(this).data("src"));
            }
        });
    }

    // focus scrollers so they can be scrolled with keyboard
    if (EQTR.detectDevice.isDesktop() && (focus = $(".focus", context)).length) {
        if (focus[0].scrollHeight > focus.outerHeight()) {
            focus.focus();
            $("body").click(function () {
                if (document.activeElement && document.activeElement.tagName == "BODY") {
                    focus.focus();
                }
            });
        }
    }

    EQTR.restaurantBooking.init(context);

    EQTR.roomBooking.init();

    EQTR.formPages.init();

    EQTR.packages.init(context);

    EQTR.newsletter.init();

    EQTR.travel.init();

    EQTR.grid.init();

    EQTR.blog.init();

    EQTR.filter.init();

    // setup the tabs
    $('.hotel-subnav:not(.ignore-js)', context).tabify({ speed: 300 });

    $('.content-expander:not(.ignore-js)', context).contentexpander({ speed: 600 });

    //        $('.contact-page .content-expander .item:eq(0) .item-name',context).click();

    // hopefully all layouts are sorted by this time for image layout purposes
    $(".responsive-background-image", context).responsiveBackgroundImage();
    $(".responsive-cover-background-image", context).responsiveInlineBackgroundImage();

    // set the content heading sizes.
    $(".content-heading", context).fitword();

    // print-confirmation
    $(".print-button", context).click(function (e) {
        e.preventDefault();
        window.print();
    });

    // change the colours on the families page titles
    // make sure that the url is families. The url bit was a quick fix for pages that used the "families" template, but could possibly work indefinitely
    // The other solution is to put a check in the "families" shared translation document type which has something like "use coloured headings",but that involves a reasonable amount of work.
    if (location.href.match(/families/i)) {
        $(".ltr .families").addClass("coloured-headings").find(".content-heading,h3").colouredLetters();
    }

    EQTR.restaurantPageLayout.init(context);

    // the page should be initialised by this point so show the content. Don't show for word frame as it takes care of it internally
    // don't show for ajaxcontent as this is also taken care of

    //        if (!(hasWordFrame || ajaxContent)) {


    if (!ajaxContent) {
        module.ShowPageContent();
        setTimeout(function () {
            // only check for visible for non-ajax pages. There is an issue with the restaurant layout on smaller height screens.
            // seems to be okay with ajax, probably because of the delay here.
            EQTR.detectDevice.isDesktop() && niceScroll && niceScroll.length && niceScroll.filter(":cssVisible").getNiceScroll().resize().show();
            niceScroll && EQTR.css.addRule(".nicescroll-rails", "background: rgba(200,200,200,0.6);");
        }, 300);
    } else {
        //            if (hasWordFrame) {
        //                EQTR.wordFrame.onClose(function () {
        //                    EQTR.detectDevice.isDesktop() && niceScroll && niceScroll.length && niceScroll.getNiceScroll().resize().show();
        //                });
        //            } else {
        !(popup && popup.length) && EQTR.detectDevice.isDesktop() && niceScroll && niceScroll.length && niceScroll.getNiceScroll().resize().show();
        //            }
    }


    var scrollableIndictorEls = $('.scrollable-indicator');
    // set up the popup that indicates that you can scroll the page.
    // add the class 'scrollable-indicator' to the element in question.
    if (scrollableIndictorEls.length) {

        scrollableIndictorEls.each(function (index, el) {
            EQTR.scrollIndicator.showScrollIndicator($(el), 'top right', 'Scroll for more ');
        });

        //var leftPanel = $('.horizontal-half.panel-left'),
        //rightPanel;

        //if (leftPanel.length && EQTR.scrollIndicator.hasScrollBar(leftPanel)) {
        //} else if (EQTR.scrollIndicator.hasScrollBar(rightPanel = $('.horizontal-half.panel-right'))) {
        //EQTR.scrollIndicator.showScrollIndicator(rightPanel, 'top left', 'Scroll for more');
        //}
    }


    // check to see if there is a popup to takeover the site
    module.takeover.checkTakeoverStatus(context);

    //generic show-hide
    $('.js-show-hide-trigger').on('click', function (e) {
        e.preventDefault();
        var trigger = $(this).toggleClass('show-hide-open');
        var container = $(this).closest('.js-show-hide-container');
        var content = container.find('.js-show-hide-content').slideToggle();
    });

    //reasons to book - open on desktop
    $(window).smartresize(function () {
        if (!window.EQTR.helpers.getScreenView().match(/small/g)) {
            $('.best-rate-content.js-show-hide-content').removeAttr('style');
        }
    });

    //Account section
    module.accountSection();

    //forms functionality
    module.forms();
};

module.ResizeQueue = [];

module.AddToResizeQueue = function (func, index) {
    if (!isNaN(index)) {
        module.ResizeQueue.splice(index, 0, func);
    } else {
        module.ResizeQueue.push(func);
    }
    return func;
};

module.RemoveFromResizeQueue = function (queueItem) {
    if (typeof queueItem == "function") {
        queueItem = module.ResizeQueue.indexOf(queueItem);
    }

    module.ResizeQueue.splice(queueItem, 1);
};

module.ExecResizeQueue = function (isInit) {
    $.each(module.ResizeQueue, function (index, queueItem) {
        if (isInit && queueItem.ignoreResizeOnInit) return true;
        queueItem();
    });
};

module.accountSection = function () {
    //account menu
    $('.account-toggle').togglePanel({
        panel: $('.account-nav__sub-menu'),
        linkOpenClass: "open"
    });

    if ($('.rf-account-page').length == 0) { return false; }


    $('.accountFilters .dateselector').datepicker({
        dateFormat: 'dd/mm/yy',
        onSelect: function (date) {
            var endDate = $('.input#fromDate').datepicker('getDate', '+1d');
            endDate.setDate(endDate.getDate() + 1);
            $('.input#toDate').datepicker('option', 'minDate', endDate);
            $(this).change();
        },
        beforeShow: function (input, inst) {

            if ($(window).width() > 520) {

                var calendrier = inst.dpDiv;
                var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 40;
                setTimeout(function () { calendrier.css({ 'left': left }); }, 10);

            } else {

                var calendrier = inst.dpDiv;
                setTimeout(function () {
                    calendrier.css({
                        'left': '50%',
                        'top': '50%',
                        'margin-left': (-calendrier.width() / 2) + 'px',
                        'margin-top': (-calendrier.height() / 2) + 'px'
                    });
                }, 10);
            }
        }
    });
};

module.forms = function () {
    var mobileScrollingForms = $('.js-mobile-scrolling-form');

    if (!mobileScrollingForms.length) { return false; }

    mobileScrollingForms.find('input').on('focus', function () {
        if (!window.EQTR.helpers.getScreenView().match(/small/g) || !window.EQTR.helpers.isTouchDevice()) { return false; }
        var currentPos = $('.page-content').scrollTop();
        var inputOffset = $(this).offset().top;
        var header = $('.page-header').innerHeight();

        var whereTo = currentPos + inputOffset - (header * 2);
        $('.page-content').stop().animate({
            scrollTop: whereTo
        }, 800, function () {
            $('.page-content').clearQueue();
        });
    });
};

$(window).smartresize(function () {
    module.ExecResizeQueue(false);
});

$(function () {

    // run all of the page outer startup methods
    for (var s in startupMethods) {
        startupMethods[s]();
    }

    module.InitPageContent();

    // trigger any defined background image covers on resize. 
    module.AddToResizeQueue($.backgroundCoverTrigger);

    // trigger anything that needs resizing
    if (module.ResizeQueue.length) {
        setTimeout(function () {
            module.ExecResizeQueue(true);
        }, 1);
    }



});

return module;
})(window.EQTR || {}, window.jQuery);


// onbefore print setup.

(function () {

    // IE 5.5+ support upto and including IE10
    if ("onbeforeprint" in window) {
        window.onbeforeprint = function () {
            $(window).trigger("print");
        };
    } else if (window.matchMedia) {
        var mqList = window.matchMedia("print"),
            isPrinting = false;

        mqList.addListener(function (mql) {
            if (mql.matches && !isPrinting) {
                isPrinting = true;
                $(window).trigger("print");
                setTimeout(function () { isPrinting = false; }, 500);
            }
        });

    }

})(jQuery);

/* jquery reverse  */
jQuery.fn.reverse = [].reverse;

/* Targeted Link Tracking */

function trackInternalLink(link, action, eventType, abFrameworkRef) {

    try {
        _gaq.push(['_trackEvent', eventType, action, abFrameworkRef]);
    } catch (err) { }

    setTimeout(function () {
        document.location.href = link.href;
    }, 100);
}

function trackPageEvent(link, action, eventType, abFrameworkRef) {
    try {
        _gaq.push(['_trackEvent', eventType, action, abFrameworkRef]);
    } catch (err) { }

};
(function ($) {

    var namespace = "panelScroller";

    var methods = {
        init: function (options) {
            if (!this.length) return this;

            return this.each(function () {


                var $this = $(this),
                    data = $this.data(namespace);

                options = $.extend(true, {}, $.fn[namespace].defaults, options);

                // If the plugin hasn't been initialized yet run the plugin
                if (!data) {

                    data = {
                        isScrolling: false,
                        currentCenter: 0,
                        dualScroll: options.dualScroll,
                        autoScroll: options.autoScroll,
                        timer: options.scrollTimer
                    };

                    $this.addClass('panel-scroller-wrapper').each(function () {
                        var id = "scroller-" + EQTR.helpers.generateUuid(),
                            instance = $(this).attr("id", id),
                            primary = instance.find(".primary-panel").addClass("panel-scroller"),
                            secondary = $('<ul class="panel-scroller secondary-panel" />'),
                            panels,
                            secondaryPanels = $([]),
                            // get any data (in json format) off of the element
                            instanceOptions = instance.data("scrolloptions") || {},
                            instanceData = $.extend({}, data, instanceOptions),
                            hasButton = false;

                        // find each of the panel containers.
                        if (options.panel) {
                            panels = $(options.panel, primary);
                        } else {
                            panels = primary.children();
                        }

                        if ($this.data("randomisegallery")) {
                            panels = panels.shuffle();
                        }

                        var panelWrapper = $('<li class="panel" draggable="false" />');

                        // won't work well with only 2 panels, so need to dupe the whole thing to make 4
                        if (panels.length == 2) {

                            panels = panels.add(panels.clone());

                        }

                        // setup the panels. If this is a dual scroller, then set up the secondary scroller
                        panels.each(function (index) {
                            var primaryPanel = $(this).attr({ "data-index": index, "draggable": false }).addClass("panel"),
                                secondaryFiller;

                            if (instanceData.dualScroll) {
                                var s = primaryPanel.children().eq(1);

                                if (!s.length) {
                                    if (index == 0) {
                                        primaryPanel.addClass("fade-in-content");
                                    }
                                    secondaryFiller = primaryPanel.addClass("panel-fullwidth").clone();

                                    // need to match the buttons hovering for the split panel
                                    // going to add a reference to each for the other.
                                    $(".button,.explore-link", primaryPanel).each(function () {

                                        var primaryButton = $(this).attr("id", "panel_button_" + index + "_p");
                                        var secondaryButton = $(".button,.explore-link", secondaryFiller).attr("id", "panel_button_" + index + "_s");

                                        // somthing happening where the "data" is being set on the primary, so doing it old-school.
                                        primaryButton.attr("data-companion", "#" + secondaryButton.attr("id"));
                                        secondaryButton.attr("data-companion", "#" + primaryButton.attr("id"));

                                        // this may get hit multiple times, but it isn't expensive
                                        hasButton = true;
                                    });

                                } else {
                                    secondaryFiller = panelWrapper.clone().attr("data-index", index).append(s);
                                }

                                secondaryPanels = secondaryPanels.add(secondaryFiller);
                            }

                        });

                        // setup the button hover bubble
                        if (hasButton) {
                            $this.on("mouseenter", ".button,.explore-link", function () {
                                $($(this).data("companion")).addClass("hover");
                            }).on("mouseleave", ".button,.explore-link", function () {
                                $($(this).data("companion")).removeClass("hover");
                            });
                        }

                        // hover to any text areas will stop the auto scroll from happening
                        $this.on("mouseenter", ".content-slider", function () {
                            $this[namespace]("stopAutoScroll");
                        }).on("mouseleave", ".content-slider", function () {
                            // don't start it back up if it has been stopped elsewhere by user interaction
                            if (instanceData.autoScroll) {
                                $this[namespace]("startAutoScroll");
                            }
                        });

                        if (panels.length < 2) {
                            return;
                        }

                        instanceData.length = panels.length;
                        instanceData.panels = panels;

                        // empty the panel ready for new item insertion
                        primary.empty();

                        // and the secondary is
                        if (instanceData.dualScroll) {
                            primary.after(secondary);
                            instanceData.secondaryPanels = secondaryPanels;
                        }

                        instanceData.itemsInScroller = primary.children().length;

                        // attach the data to the plugins instance
                        instance.data(namespace, instanceData);


                        // this handles mouse wheel and keypress for arrows
                        function handleEvent(e, delta) {

                            if (instanceData.isScrolling || instance[0].style.height == "auto") return true;

                            if (e.type == "keyup" && !e.which.toString().match(/37|38|39|40/)) {
                                return true;
                            }

                            if (e.type.match(/mouse/) && instanceData.xScroll) return true;

                            e.preventDefault();

                            if (delta > 0 || e.which == 38 || e.which == 37) {
                                instance[namespace](this.className.match(/primary/) ? "prev" : "next");
                            } else {
                                instance[namespace](this.className.match(/primary/) ? "next" : "prev");
                            }

                            $this[namespace]("stopAutoScroll", true);

                        }

                        var scrollStart,
                            isPrimaryScroll,
                            scrollStartTime,
                            pageScrollStart,
                            pageContent = $this.closest(".page-content");

                        // adding a very slight drag start offset to stop the click prevent default from happening
                        jQuery.event.special.drag.defaults.distance = 2;

                        primary.add(secondary).attr("tabindex", 0)
                            .on("mousewheel keyup", handleEvent)
                        // using dragging because having issues with chrome android touchend and touchmove not firing
                            .on("draginit", function (e, dd) {
                                if (instanceData.isScrolling) return;
                                //			                wasScrolling = instanceData.isScrolling;
                                //			                instanceData.isScrolling = false;
                                //			                primary.stop();
                                scrollStart = primary[instanceData.xScroll ? "scrollLeft" : "scrollTop"]();
                                isPrimaryScroll = primary.is(this);
                                scrollStartTime = new Date().valueOf();
                                pageScrollStart = pageContent.scrollTop();

                            })
                            .on("dragstart", function (e, dd) {
                                instanceData.panelDragged = true;

                                $this.addClass("no-transition");

                                instanceData.panels.removeClass("scroll-up-in scroll-down-in scroll-up-out scroll-down-out");
                                instanceData.secondaryPanels && instanceData.secondaryPanels.removeClass("scroll-up-in scroll-down-in scroll-up-out scroll-down-out");

                                EQTR.ForcePageLayout();
                                $this.removeClass("no-transition");

                                $this[namespace]("stopAutoScroll", true);
                            })
                            .on("drag", function (e, dd) {
                                if (instanceData.isScrolling) return;

                                if (instanceData.xScroll) {

                                    // scroll the gallery if the gradient of drag is less than 1.2 (slighty favours the y ), otherwise scroll the content (used for touch mainly[only?])
                                    if (Math.abs(dd.deltaY / dd.deltaX) < 0.8) {
                                        primary.scrollLeft(scrollStart + ((isPrimaryScroll ? -1 : 1)) * dd.deltaX);
                                    } else {
                                        //console.info(pageScrollStart,dd.deltaY);
                                        pageContent.scrollTop(pageScrollStart - dd.deltaY);
                                    }
                                } else {
                                    primary.scrollTop(scrollStart + ((isPrimaryScroll ? -1 : 1)) * dd.deltaY);
                                }
                                //panelDragged = true;

                            })
                            .on("dragend", function (e, dd) {
                                var scrollDistance = primary[instanceData.xScroll ? "scrollLeft" : "scrollTop"]() - scrollStart;

                                if (!instanceData.isScrolling && scrollDistance) {

                                    // try and get the velocity
                                    var scrollTimeElapsed = new Date().valueOf() - scrollStartTime;
                                    var scrollVelocity = Math.abs(scrollDistance) / scrollTimeElapsed;

                                    instanceData.easing = "easeOutExpo";
                                    // need to make this smaller for touchend delay (was 0.25). If a swipe then advance, otherwise snap into place
                                    if (scrollVelocity > 0.1) {
                                        instance[namespace](scrollDistance > 0 ? "next" : "prev");
                                    } else {
                                        instance[namespace]("snapToPanel", 1);
                                    }

                                    instanceData.easing = null;

                                }
                            });

                        primary.scroll(function () {
                            var scrollLayout = instanceData.xScroll ? "scrollLeft" : "scrollTop",
                                thisScrollOffset = $(this)[scrollLayout]();

                            var scrollDiff = instanceData.initialScroll - thisScrollOffset;

                            secondary[scrollLayout](instanceData.initialScroll + scrollDiff);
                        });

                        if (options.focus) {
                            primary.focus();
                        }

                        // get the scrollAxis by checking what state the primary scroller is in. white-space nowrap means that it is horizontal scroll mode
                        instanceData.xScroll = primary.css("white-space") == "nowrap";

                        instance[namespace]("placePanels");

                        // add the arrow navigation 
                        //					$('<a href="#" class="scroll-nav up">&#x2191;</a><a href="#" class="scroll-nav left">&#x2190;</a><a href="#" class="scroll-nav down">&#x2193;</a><a href="#" class="scroll-nav right">&#x2192;</a>').appendTo(instance);
                        var arrowNav = $('<a href="#" id="gallery-nav-left" class="scroll-nav left">&#x2190;</a><a id="gallery-nav-down" href="#" class="scroll-nav down">&#x2193;</a><a id="gallery-nav-right" href="#" class="scroll-nav right">&#x2192;</a>').hide().appendTo(instance);

                        instance.on("click", ".scroll-nav", function (e) {
                            e.preventDefault();
                            instance[namespace](this.className.match(/right|down/) ? "next" : "prev");
                            $this[namespace]("stopAutoScroll", true);
                        });

                        // set the arrows based on scroll axis. This is the wrong place to do it, but there is a quandary about handling 
                        // media query driven scroll direction vs user set (e.g. from script)
                        if (instanceData.xScroll) {
                            arrowNav.filter(".right,.left").show();
                        } else {
                            arrowNav.filter(".down,.up").show();
                        }

                        instanceData.resize = EQTR.AddToResizeQueue(function panelScrollerResize() {

                            // using css styling to set class width for panels in the horizontal mode. 100% isn't working as it is sometimes a pixel off
                            EQTR.css.changeRule("#" + id + ".horizontal .panel-scroller .panel", { width: primary.width() + "px" });

                            $.fx.off = true;
                            instance[namespace]("setScrollCenter");
                            $.fx.off = false;

                            // get the scrollAxis by checking what state the primary scroller is in. white-space nowrap means that it is horizontal scroll mode
                            instanceData.xScroll = primary.css("white-space") == "nowrap";

                            arrowNav.hide();
                            // set the arrows based on scroll axis. This is the wrong place to do it, but there is a quandary about handling 
                            // media query driven scroll direction vs user set (e.g. from script)
                            if (instanceData.xScroll) {
                                arrowNav.filter(".right,.left").show();
                            } else {
                                arrowNav.filter(".down,.up").show();
                            }

                        });

                        // put in the dots
                        if (options.dots || $this.data('dots')) {
                            // create the container for the dots

                            var dots = [], dotsContainer;
                            for (var dot = 0; dot < instanceData.length; dot++) {
                                dots.push('<li><a class="dot" href="#" data-index="' + dot + '"></a></li>');
                            }

                            dots.push('<li class="overlay"><span class="dot"></span></li>');

                            dotsContainer = $('<div class="panel-scroll__dots"><ul>' + dots.join("") + '</ul></div>');

                            instanceData.dotsContainer = dotsContainer;

                            $this.append(dotsContainer);
                            dotsContainer.on("click", "a", function (e) {
                                e.preventDefault();
                                $this[namespace]("stopAutoScroll");
                                $this[namespace]("scrollTo", $(this).data("index"));
                            });
                        }

                        // only do this on desktop because touch devices disable click on drag? Maybe
                        if (EQTR.detectDevice.isDesktop()) {
                            $this.on("click", function (e) {
                                primary.focus();
                                // prevent the bubble if a drag has happened
                                if (instanceData.panelDragged) {
                                    instanceData.panelDragged = false;
                                    return false;
                                }
                            });
                        }

                        // handle the destroy event when the gallery is removed from the dom
                        $this.on("destroyed", methods.cleanup);

                        if (instanceData.autoScroll) {
                            $this[namespace]("startAutoScroll");
                        }

                    });

                }
            });

        },
        // setter/getter for the scroll axis
        scrollAxis: function (axis) {
            var $this = $(this),
                data = $this.data(namespace);

            if (axis && axis.match(/^x|y$/i)) {
                if (axis.match(/x/i)) {
                    $this.addClass("horizontal");
                    data.xScroll = true;
                } else {
                    $this.removeClass("horizontal");
                    data.xScroll = false;
                }

                $this[namespace]("setScrollCenter");

                return $this;

            }
            return data.xScroll ? "x" : "y";
        },
        // place the centre panel put in surrounding panels 
        placePanels: function () {
            return this.each(function () {

                var $this = $(this),
                    data = $this.data(namespace),
                    primary = $(".primary-panel", $this), secondary = $(".secondary-panel", $this),
                    primaryPanels = data.panels, secondaryPanels = data.secondaryPanels,
                    current = data.currentCenter,
                    prevIndex = $this[namespace]("getPrevious"),
                    nextIndex = $this[namespace]("getNext");
                // if there is no direction, assume you are starting from nothing, otherwise assume that a scroll has happened and that 2 items are correct
                if (!primary.children().length) {
                    primary.append(primaryPanels.eq(prevIndex), primaryPanels.eq(current), primaryPanels.eq(nextIndex));
                    if (data.dualScroll) {
                        secondary.append(secondaryPanels.eq(nextIndex), secondaryPanels.eq(current), secondaryPanels.eq(prevIndex));
                    }
                } else {
                    // if the current item is the last panel we need to populate the end and remove the front, otherwise populate the front and remove the end
                    var primaryFirst = primary.find(".panel:first"),
                        primaryLast = primary.find(".panel:last"),
                        secondaryFirst = secondary.find(".panel:first"),
                        secondaryLast = secondary.find(".panel:last");

                    // TODO: JM - refactor this. is basically duplicate
                    if (primaryLast.data("index") == current) {
                        //                    alert("placing primary");
                        primaryLast.addClass("fixed-placement");
                        //                    alert("primary fixed");
                        primaryFirst.detach();
                        //                    alert("primary detach");

                        if (data.forcePanelUpdate) {
                            primaryLast.siblings().detach();
                            primary.prepend(primaryPanels.eq(prevIndex));
                            primaryPanels.eq(prevIndex).find(".responsive-background-image").responsiveBackgroundImage();
                            primaryPanels.eq(prevIndex).find(".content-heading").fitword();
                        }

                        primary.append(primaryPanels.eq(nextIndex));
                        //                    alert("primary append");
                        primaryPanels.eq(nextIndex).find(".responsive-background-image").responsiveBackgroundImage();
                        primaryPanels.eq(nextIndex).find(".content-heading").fitword();

                        if (data.dualScroll) {
                            //            ,.            alert("secondary");
                            secondaryFirst.addClass("fixed-placement");
                            //                        alert("secondary fixed");
                            secondaryLast.detach();
                            //                        alert("secondary detach");

                            if (data.forcePanelUpdate) {
                                secondaryFirst.siblings().detach();
                                secondary.append(secondaryPanels.eq(prevIndex));
                                secondaryPanels.eq(prevIndex).find(".responsive-background-image").responsiveBackgroundImage();
                                secondaryPanels.eq(prevIndex).find(".content-heading").fitword();
                            }

                            secondary.prepend(secondaryPanels.eq(nextIndex));
                            //                        alert("secondary append");
                            secondaryPanels.eq(nextIndex).find(".responsive-background-image").responsiveBackgroundImage();
                            secondaryPanels.eq(nextIndex).find(".content-heading").fitword();

                        }
                    } else {
                        primaryFirst.addClass("fixed-placement");
                        primaryLast.detach();

                        if (data.forcePanelUpdate) {
                            primaryFirst.siblings().detach();
                            primary.append(primaryPanels.eq(nextIndex));
                            primaryPanels.eq(nextIndex).find(".responsive-background-image").responsiveBackgroundImage();
                            primaryPanels.eq(nextIndex).find(".content-heading").fitword();
                        }

                        primary.prepend(primaryPanels.eq(prevIndex));
                        primaryPanels.eq(prevIndex).find(".responsive-background-image").responsiveBackgroundImage();
                        primaryPanels.eq(prevIndex).find(".content-heading").fitword();

                        if (data.dualScroll) {
                            secondaryLast.addClass("fixed-placement");
                            secondaryFirst.detach();

                            if (data.forcePanelUpdate) {
                                secondaryLast.siblings().detach();
                                secondary.prepend(secondaryPanels.eq(nextIndex));
                                secondaryPanels.eq(nextIndex).find(".responsive-background-image").responsiveBackgroundImage();
                                secondaryPanels.eq(nextIndex).find(".content-heading").fitword();
                            }

                            secondary.append(secondaryPanels.eq(prevIndex));
                            secondaryPanels.eq(prevIndex).find(".responsive-background-image").responsiveBackgroundImage();
                            secondaryPanels.eq(prevIndex).find(".content-heading").fitword();

                        }
                    }

                    data.forcePanelUpdate = false;
                }

                // setup the scroll position
                $this[namespace]("setScrollCenter");
                //            alert("set center");

                // remove the fixed class after all have been moved and remove the placeholders
                $(".fixed-placement").removeClass("fixed-placement");
                //            alert("remove fixed");

                if (!data.xScroll) {
                    $this.addClass("no-transition");
                    primary.children().eq(2).addClass("scroll-up-in");
                    primary.children().eq(0).addClass("scroll-down-in");
                    if (data.dualScroll) {
                        secondary.children().eq(2).addClass("scroll-up-in");
                        secondary.children().eq(0).addClass("scroll-down-in");
                    }

                    EQTR.ForcePageLayout();
                    $this.removeClass("no-transition");
                }
            });
        },
        setScrollCenter: function () {
            return this.each(function () {

                // assumes that each panel is the same height
                var $this = $(this),
		            data = $this.data(namespace),
		            primary = $(".primary-panel", $this), secondary = $(".secondary-panel", $this),
		            //scrollPos,
		            isHorizontal = data.xScroll,
		            //		        scrollTotal = primary[0][isHorizontal ? "scrollWidth" : "scrollHeight"],
		            scrollPos = primary[isHorizontal ? "width" : "height"]();

                // set the scroll position for the panels. Will always be one panel length from the top/side
                //scrollPos = scrollView;

                data.initialScroll = scrollPos;
                data.isScrolling = false;

                if (isHorizontal) {
                    primary.scrollLeft(scrollPos);
                    secondary.scrollLeft(scrollPos);
                } else {
                    primary.scrollTop(scrollPos);
                    secondary.scrollTop(scrollPos);
                }

                primary.add(secondary).attr("data-scrolltop", scrollPos);
            });
        },
        snapToPanel: function (index) {
            return this.each(function () {

                var $this = $(this),
		            data = $this.data(namespace),
		            primary = $(".primary-panel", $this), secondary = $(".secondary-panel", $this),
		            isHorizontal = data.xScroll,
		            scrollLayout = isHorizontal ? "scrollLeft" : "scrollTop",
		            // see which panel is in view (primary)
		            scrollDimension = primary[isHorizontal ? "width" : "height"]();

                index = index == undefined ? 1 : index;

                if (data.isScrolling) {
                    return;
                }

                if (index != 1) {
                    primary.children().removeClass("scroll-up-in scroll-down-in scroll-up-out scroll-down-out fade-in-content fade-out-content").eq(1).addClass(index ? "scroll-down-out" : "scroll-up-out").removeClass("fade-in-content").addClass("fade-out-content");
                    secondary.children().removeClass("scroll-up-in scroll-down-in scroll-up-out scroll-down-out fade-in-content fade-out-content").eq(1).addClass(index ? "scroll-up-out" : "scroll-down-out").removeClass("fade-in-content").addClass("fade-out-content");
                }

                data.isScrolling = true;

                var animateObject = {};
                animateObject[scrollLayout] = index * scrollDimension;

                data.currentCenter = primary.find(".panel:eq(" + index + ")").data("index");

                // scroll the dots if there are any
                if (data.dotsContainer) {
                    $this[namespace]("setDots");
                }

                // animate the primary scroller
                primary.animate(animateObject, 1300, data.easing || "easeInOutCubic", function () {

                    data.isScrolling = false;

                    // do a shift so the focused item is always in the middle, but don't if it hasn't moved
                    if (index != 1) {
                        // set the current to be the item that has been scrolled to

                        $this[namespace]("placePanels");
                        // check to see if the middle panels are full width and fade the content in
                        var middlePrimary = primary.children().eq(1);
                        if (middlePrimary.hasClass("panel-fullwidth")) {
                            middlePrimary.addClass("fade-in-content");
                            secondary.children().eq(1).addClass("fade-in-content");
                        }


                    }
                });

            });
        },
        scrollTo: function (index) {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data(namespace),
                    primary = $(".primary-panel", $this), secondary = $(".secondary-panel", $this),
                    primaryPanels = data.panels, secondaryPanels = data.secondaryPanels,
                    current = data.currentCenter,
                    // check to see if the index is already in view and move to it,
                    prevIndex = $this[namespace]("getPrevious"),
                    nextIndex = $this[namespace]("getNext");

                if (current == index) {
                    return;
                } else if (index == prevIndex) {
                    $this[namespace]("prev");
                } else if (index == nextIndex) {
                    $this[namespace]("next");
                } else {
                    // otherwise we will need grab the items them update the surrounding panels afterwards the scroll
                    //$(this)[namespace]("snapToPanel", index);
                    var primaryFirst = primary.find(".panel:first"),
                        primaryLast = primary.find(".panel:last"),
                        secondaryFirst = secondary.find(".panel:first"),
                        secondaryLast = secondary.find(".panel:last"),
                        primaryCurrent = primary.children().eq(1),
                        secondaryCurrent = secondary.children().eq(1);

                    data.forcePanelUpdate = true;

                    // TODO: JM - refactor this. is basically duplicate
                    if (current > index) {
                        primaryCurrent.addClass("fixed-placement");
                        primary.prepend(primaryPanels.eq(index));
                        primaryFirst.detach();
                        primaryCurrent.removeClass("fixed-placement");
                        primaryPanels.eq(index).find(".cover-image").backgroundCover();
                        primaryPanels.eq(index).find(".content-heading").fitword();
                        ;
                        if (data.dualScroll) {
                            secondaryLast.detach();
                            secondary.append(secondaryPanels.eq(index));
                            secondaryPanels.eq(index).find(".cover-image").backgroundCover();
                            secondaryPanels.eq(index).find(".content-heading").fitword();
                            ;
                        }
                        $this[namespace]("prev");
                    } else {
                        primaryLast.detach();
                        primary.append(primaryPanels.eq(index));
                        primaryPanels.eq(index).find(".cover-image").backgroundCover();
                        primaryPanels.eq(index).find(".content-heading").fitword();
                        ;
                        if (data.dualScroll) {
                            secondaryCurrent.addClass("fixed-placement");
                            secondaryFirst.detach();
                            secondary.prepend(secondaryPanels.eq(index));
                            secondaryCurrent.removeClass("fixed-placement");
                            secondaryPanels.eq(index).find(".cover-image").backgroundCover();
                            secondaryPanels.eq(index).find(".content-heading").fitword();
                            ;
                        }
                        $this[namespace]("next");
                    }
                }
            });

        },
        setDots: function () {
            var $this = $(this),
                data = $this.data(namespace),
                current = $this[namespace]("getCurrent"),
                dotsContainer = data.dotsContainer,
                currentDot = dotsContainer.find("li").eq(current),
                currentDotOffset = currentDot.position(),
                overlayDot = dotsContainer.find(".overlay");

            overlayDot.animate({ left: currentDotOffset.left }, 1300, data.easing || "easeInOutCubic");

        },
        // merge next and prev?
        next: function () {
            var $this = $(this);
            return $this[namespace]("snapToPanel", 2);
        },
        prev: function () {
            var $this = $(this);

            return $this[namespace]("snapToPanel", 0);
        },
        getCurrent: function () {
            var $this = $(this),
                data = $this.data(namespace);

            return (data.currentCenter + data.length) % data.length;
        },
        getNext: function (index) {
            var $this = $(this),
                data = $this.data(namespace);
            return (index || data.currentCenter + data.length + 1) % data.length;
        },
        getPrevious: function (index) {
            var $this = $(this),
                data = $this.data(namespace);
            return (index || data.currentCenter + data.length - 1) % data.length;
        },
        stopAutoScroll: function (stopData) {
            return this.each(function () {
                var data = $(this).data(namespace);

                clearTimeout(data.timerId);
                data.timerId = null;
                if (stopData) {
                    data.autoScroll = false;
                }

            });
        },
        startAutoScroll: function () {
            return this.each(function () {
                var $this = $(this),
                    data = $(this).data(namespace);

                function scroll() {
                    requestAnimationFrame(function () {
                        $this[namespace]("next");
                        data.timerId = setTimeout(scroll, data.timer);
                    });
                }

                data.timerId = setTimeout(scroll, data.timer);
            });
        },
        cleanup: function () {
            return $(this).each(function () {
                var $this = $(this),
                    data = $this.data(namespace);
                EQTR.RemoveFromResizeQueue(data.resize);
                $this[namespace]("stopAutoScroll");
            });
        }
    };

    $.fn[namespace] = function (method) {
        // Method calling logic
        if (methods[method]) {
            var validElements = this.filter(function () {
                return $(this).data(namespace);
            });

            return methods[method].apply(validElements, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + namespace);
        }

    };

    $.fn[namespace].defaults = {
        dualScroll: false,
        autoScroll: true,
        scrollTimer: 6000,
        dots: true
    };

})(jQuery);;
window.EQTR.bookingBar = (function (namespace, $, undefined) {

    var _ = namespace,
        bookingPanel,
        toolTipTimeout;

    _.init = function (context) {

        // any selects that have a comma in the options need to be split. This happens in the booking bar and on the restaurant step one booking page
        // this happens before selectify hits it and will happen each load to make sure that we have caught any in the ajax pages
        /*_.setCitySplit();*/

        if ($('.booking-panel-form').length > 0) {
            //if (!bookingPanel) {

            bookingPanel = $('.booking-panel-form');

            // don't do the info panel if we are on a handheld (no hover and there is no capacity for click-to-show)
            if (EQTR.detectDevice.isDesktop()) {
                /*EQTR.bookingBar.initInfoPanel();*/
            }

            if ($('.selectpicker', bookingPanel).length > 0) {

                //$('input#datepicker-table', bookingPanel).prop('disabled', true);
                /*$('select.input:not(.no-label)', bookingPanel).selectify({
                    'hasCloseButton': true
                });
                $('select.input.no-label', bookingPanel).selectify({
                    'firstOptionVisibleInDropDown': false,
                    'hasCloseButton': true
                });*/

            }

            /*if ($('.input.datepicker-here', bookingPanel).length) {

                $('.input.datepicker-here').datepicker({
                    minDate: 0,
                    dateFormat: 'dd/mm/yy',
                    onSelect: function (date) {
                        var endDate = $('.input.datepicker-here').datepicker('getDate', '+1d');
                        endDate.setDate(endDate.getDate() + 1);
                        $('.input#datepicker-room').datepicker('option', 'minDate', endDate);
                        //$(this).change();


                    }*/
            /*,
            beforeShow: function (input, inst) {

                if ($(window).width() > 520) {

                    var calendrier = inst.dpDiv;
                    var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 40;
                    setTimeout(function () { calendrier.css({ 'left': left }); }, 10);

                } else {

                    var calendrier = inst.dpDiv;
                    setTimeout(function () {
                        calendrier.css({
                            'left': '50%',
                            'top': '50%',
                            'margin-left': (-calendrier.width() / 2) + 'px',
                            'margin-top': (-calendrier.height() / 2) + 'px'
                        });
                    }, 10);

                }
            }*/
            /*});
        }*/

            if ($('input#datepicker-room', bookingPanel).length) {

                $('input#datepicker-room', bookingPanel).datepicker({
                    minDate: 0,
                    dateFormat: 'dd/mm/yy',
                    /*beforeShow: function (input, inst) {

                        if ($(window).width() > 520) {

                            var calendrier = inst.dpDiv;
                            var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 40;
                            setTimeout(function () { calendrier.css({ 'left': left }); }, 10);

                        } else {

                            var calendrier = inst.dpDiv;
                            setTimeout(function () {
                                calendrier.css({
                                    'left': '50%',
                                    'top': '50%',
                                    'margin-left': (-calendrier.width() / 2) + 'px',
                                    'margin-top': (-calendrier.height() / 2) + 'px'
                                });
                            }, 10);

                        }
                    }*/
                });

            }
            if ($('input#datepicker-table', bookingPanel).length) {

                $('input#datepicker-table', bookingPanel).datepicker({
                    minDate: 0,
                    dateFormat: 'dd/mm/yy',
                    /*beforeShow: function (input, inst) {

                        if ($(window).width() > 520) {

                            var calendrier = inst.dpDiv;
                            var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 40;
                            setTimeout(function () { calendrier.css({ 'left': left }); }, 10);

                        } else {

                            var calendrier = inst.dpDiv;
                            setTimeout(function () {
                                calendrier.css({
                                    'left': '50%',
                                    'top': '50%',
                                    'margin-left': (-calendrier.width() / 2) + 'px',
                                    'margin-top': (-calendrier.height() / 2) + 'px'
                                });
                            }, 10);

                        }
                    }*/
                });

            }

            /*$('.input#Form_Room_Depart_Date').datepicker({
                minDate: 0,
                dateFormat: 'dd/mm/yy',
                beforeShow: function (input, inst) {
                    var calendrier = inst.dpDiv;
                    //var top = $(this).offset().top + $(this).outerHeight();
                    var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 20;
                    setTimeout(function () { calendrier.css({ 'left': left }); }, 10);
                }
            });*/

            /*$('select#Form_MealType', bookingPanel).selectify('disable');
            $('select#Form_NumberOfCovers', bookingPanel).selectify('disable');*/

            /*$('select.chooser').on('change', function (e) {
                if ($(this).val() != null) {
                    alert("desk");
                    var selectedval = $("option:selected", this).val();
                    $('.select-group').hide().removeClass('active').filter('.' + $(this).val() + '-group').show().addClass('active');
                    $('.' + $(this).val() + '-group').find('.chooser').val(selectedval);
                    $('.selectpicker').selectpicker('refresh');
                }*/
            //window.EQTR.bookingBar.resizeBookingBarHeight();
            /*});*/


            $('select#TableBookingComponent_RestaurantId', bookingPanel).change(function () {

                var language = $('html')[0].lang,
                    $restaurantIdSelect = $(this),
                    restaurantId = $(this).val();

                if (restaurantId.match(/http/)) {

                    $(".book-a-table-options").addClass("restaurant-direct-link");
                    $(".table-booking-link a").attr("href", restaurantId);

                } else {
                    //alert("1");
                    $(".book-a-table-options").removeClass("restaurant-direct-link");

                    $.get('/api/restaurant/getrestaurantconfiguration/?lang=' + language + '&restaurantReference=' + restaurantId, function (data) {
                        //alert($('select#Form_MealType', bookingPanel).attr('id'));
                        // setting a timeout because something isn't picking up quick enough, but can't see where it is right now
                        //setTimeout(function () {
                        //window.EQTR.restaurantBooking.updateTimeDropDown(data.MealTypes, $('select#Form_MealType'), $('select#Form_MealType').attr('data-translation'));
                        //window.EQTR.restaurantBooking.updatePeopleDropDown(data.MaxCovers, $('select#Form_NumberOfCovers'), $('select#Form_NumberOfCovers').attr('data-translationsingular'), $('select#Form_NumberOfCovers').attr('data-translationplural'));
                        //$('select#Form_MealType', bookingPanel).change().selectify('enable');
                        //$('select#Form_NumberOfCovers', bookingPanel).change().selectify('enable');
                        //$('#datepicker-table', bookingPanel).prop('disabled', false);

                        // set the enquiry form hotel. Probably should do this in restaurantBooking.js?
                        $(".js-restaurantenquiry").attr("href", function (index, val) {
                            return $(this).data("href") + data.HotelDataWarehouseReference + "/";
                        });

                        $restaurantIdSelect.trigger("apicomplete");
                        //}, 0);
                    });
                }
                /*$restaurantIdSelect.selectpicker('refresh');*/

            });

            /*$(".js-table-link").click(function(e) {
                e.preventDefault();

                // create the modal
                var cover = $('<div class="modal-cover"></div>').appendTo("body");

                // create an iframe and container
                var iframe = $('<div class="restaurant-booking-iframe"><iframe src="' + this.href + '" style="width:250px; height:350px;" scrolling="no" frameborder="0" allowtransparency="true"></iframe><a class="popup-close" href="#">x</a></div>').appendTo("body");

                cover.add(iframe.find("a")).click(function() {
                    cover.add(iframe).remove();
                });
            });*/

            /*if ($('select#TableBookingComponent_RestaurantId', bookingPanel).val() != '') {
                $('select#TableBookingComponent_RestaurantId', bookingPanel).change().selectify("disable");
            }*/

            /*if (bookingBarInitStateConfig && bookingBarInitStateConfig['table']['location']) {
                $('.booking-panel select#TableBookingComponent_RestaurantId').val(bookingBarInitStateConfig['table']['location']).change();
            }*/
			this.hideToolTip();
			this.hideChildAgePanel();
            this.bookingBarTabs();
            this.table();
            this.room();
            this.gifts();

            var matched = bookingPanel.data('bookingbarmode');

            window.EQTR.bookingBar.changeBookingBar(matched);

            bookingPanel.animate({ 'opacity': 1 }, 300);

            // clicking anywhere on the page will close all selectmenus.
            /*$(document).on('click', function() {
                $('select').each(function() {
                    if ($(this).data('isSelectified')) {
                        $(this).selectify('closeMenu');
                    }
                });
            });*/

            /*if ($('.best-rate').length > 0 && !$('.booking-panel').hasClass('small-screen')) {

                $('.best-rate_title').on('click', function() {
                    $('.best-rate_inner').toggle();
                });

                var bestRateTimer;
                $(".best-rate").mouseenter(function() {
                    clearTimeout(bestRateTimer);
                    $('.best-rate_inner').show();
                }).mouseleave(function() {
                    bestRateTimer = setTimeout(function () { $('.best-rate_inner').hide(); }, 1500);
                });
                

                $('.best-rate a').on('click', function() {
                    if ($('.best-rate_inner').is(":visible")) {
                        $('.best-rate_inner').hide();
                    }
                });
            }*/

            //}

            /*else {
                window.EQTR.bookingBar.changeBookingBar(context.data('bookingbarmode'));
                var hotelCode = context.data('bookingbarhotel');
                var restaurantCode = context.data('bookingbarrestaurant');
                var enabled = context.data('bookingbardisabled') == "False";

                (hotelCode || hotelCode == "") && _.setHotel(hotelCode);

                _.setRestaurant(restaurantCode);

                _.setVisible(enabled);

                $('.best-rate_inner').hide();   
            }*/

            if ($(window).width() < 521) {
                $('.booking-panel').addClass('small-screen');
            }

            $(window).smartresize(function () {

                if ($(window).width() < 521) {
                    $('.booking-panel').addClass('small-screen');
                } else {
                    $('.booking-panel').removeClass('small-screen');
                }

            });
        }
        if ($('.booking-panel-form-mob').length > 0) {

            //if (!bookingPanel) {

            bookingPanel = $('.booking-panel-form-mob');

            // don't do the info panel if we are on a handheld (no hover and there is no capacity for click-to-show)
            if (EQTR.detectDevice.isDesktop()) {
                /*EQTR.bookingBar.initInfoPanel();*/
            }

            if ($('.selectpicker', bookingPanel).length > 0) {

                //$('input#datepicker-table-mob', bookingPanel).prop('disabled', true);
                /*$('select.input:not(.no-label)', bookingPanel).selectify({
                    'hasCloseButton': true
                });
                $('select.input.no-label', bookingPanel).selectify({
                    'firstOptionVisibleInDropDown': false,
                    'hasCloseButton': true
                });*/

            }

            /*if ($('.input.datepicker-here', bookingPanel).length) {

                $('.input.datepicker-here', bookingPanel).datepicker({
                    minDate: 0,
                    dateFormat: 'dd/mm/yy',
                    onSelect: function (date) {
                        var endDate = $('.input.datepicker-here').datepicker('getDate', '+1d');
                        endDate.setDate(endDate.getDate() + 1);
                        $('.input#datepicker-room-mob').datepicker('option', 'minDate', endDate);
                        $(this).change();
                    }*/
            /*,
            beforeShow: function (input, inst) {

                if ($(window).width() > 520) {

                    var calendrier = inst.dpDiv;
                    var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 40;
                    setTimeout(function () { calendrier.css({ 'left': left }); }, 10);

                } else {

                    var calendrier = inst.dpDiv;
                    setTimeout(function () {
                        calendrier.css({
                            'left': '50%',
                            'top': '50%',
                            'margin-left': (-calendrier.width() / 2) + 'px',
                            'margin-top': (-calendrier.height() / 2) + 'px'
                        });
                    }, 10);

                }
            }*/
            /* });
         }*/

            if ($('input#datepicker-room-mob', bookingPanel).length) {

                $('input#datepicker-room-mob', bookingPanel).datepicker({
                    minDate: 0,
                    dateFormat: 'dd/mm/yy',
                    /*beforeShow: function (input, inst) {

                        if ($(window).width() > 520) {

                            var calendrier = inst.dpDiv;
                            var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 40;
                            setTimeout(function () { calendrier.css({ 'left': left }); }, 10);

                        } else {

                            var calendrier = inst.dpDiv;
                            setTimeout(function () {
                                calendrier.css({
                                    'left': '50%',
                                    'top': '50%',
                                    'margin-left': (-calendrier.width() / 2) + 'px',
                                    'margin-top': (-calendrier.height() / 2) + 'px'
                                });
                            }, 10);

                        }
                    }*/
                });

            }

            /*$('.input#Form_Room_Depart_Date').datepicker({
                minDate: 0,
                dateFormat: 'dd/mm/yy',
                beforeShow: function (input, inst) {
                    var calendrier = inst.dpDiv;
                    //var top = $(this).offset().top + $(this).outerHeight();
                    var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 20;
                    setTimeout(function () { calendrier.css({ 'left': left }); }, 10);
                }
            });*/

            /*$('select#Form_MealType', bookingPanel).selectify('disable');
            $('select#Form_NumberOfCovers', bookingPanel).selectify('disable');*/

            // $('select.chooser').on('change', function (e) {
                // if ($(this).val() != null) {

                    // var selectedval = $("option:selected", this).val();
                    // alert("bar" + $("option:selected", this).val());
                    // $('.select-group').hide().removeClass('active').filter('.' + $(this).val() + '-group').show().addClass('active');
                    // $('.' + $(this).val() + '-group').find('.chooser').val(selectedval);
                    // $('.selectpicker').selectpicker('refresh');
                    // /*if (selectedval == "table") {
                        // window.EQTR.bookingBar.ShowDropdown($('#TableBookingComponent_RestaurantIdmob'));
                    // }
                    // else if (selectedval == "voucher") {
                        // window.EQTR.bookingBar.ShowDropdown($('#GiftVoucherComponent_HotelGiftVoucherUrlmob'))
                    // }
                    // else if (selectedval == "venue") {
                        // window.EQTR.bookingBar.ShowDropdown($('#MeetingsBookingComponent_VenueIdmob'))
                    // }
                    // else {
                        // window.EQTR.bookingBar.triggerDropdown($('#RoomBookingComponent_HotelIdmob'))
                    // }*/
                // }
                // //window.EQTR.bookingBar.resizeBookingBarHeight();
            // });

            $('select#TableBookingComponent_RestaurantIdmob', bookingPanel).change(function () {

                var language = $('html')[0].lang,
                    $restaurantIdSelect = $(this),
                    restaurantId = $(this).val();

                if (restaurantId.match(/http/)) {

                    $(".book-a-table-options-mob").addClass("restaurant-direct-link");
                    $(".table-booking-link a").attr("href", restaurantId);

                } else {

                    $(".book-a-table-options-mob").removeClass("restaurant-direct-link");

                    $.get('/api/restaurant/getrestaurantconfiguration/?lang=' + language + '&restaurantReference=' + restaurantId, function (data) {
                        // setting a timeout because something isn't picking up quick enough, but can't see where it is right now
                        //setTimeout(function () {
                        window.EQTR.restaurantBooking.updateTimeDropDown(data.MealTypes, $('select#Form_MealTypemob'), $('select#Form_MealTypmob').attr('data-translation'));
                        window.EQTR.restaurantBooking.updatePeopleDropDown(data.MaxCovers, $('select#Form_NumberOfCoversmob'), $('select#Form_NumberOfCoversmob').attr('data-translationsingular'), $('select#Form_NumberOfCoversmob').attr('data-translationplural'));
                        //$('select#Form_MealType', bookingPanel).change().selectify('enable');
                        //$('select#Form_NumberOfCovers', bookingPanel).change().selectify('enable');
                        $('#datepicker-table', bookingPanel).prop('disabled', false);

                        // set the enquiry form hotel. Probably should do this in restaurantBooking.js?
                        $(".js-restaurantenquiry").attr("href", function (index, val) {
                            return $(this).data("href") + data.HotelDataWarehouseReference + "/";
                        });

                        $restaurantIdSelect.trigger("apicomplete");
                        // }, 0);
                    });
                }
                /*window.EQTR.bookingBar.HideDropdown($('#TableBookingComponent_RestaurantIdmob'));
                window.EQTR.bookingBar.ShowDropdown($('#Form_MealTypemob'));*/
            });
            /*$('select#Form_MealTypemob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
                var myDatepicker = $("#datepicker-table-mob").datepicker().data('datepicker');
                myDatepicker.show();
            });
            $('select#RoomBookingComponent_HotelIdmob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
                var myDatepicker = $("#datepicker-room-mob").datepicker().data('datepicker');
                myDatepicker.show();
            });
            $('select#numberofnightsmob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
                window.EQTR.bookingBar.ShowDropdown($("#numberofroomsmob"));
            });
            $('select#numberofadultsmob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
                window.EQTR.bookingBar.ShowDropdown($("#numberofchildrenmob"));
            });
            $('select#Form_NumberOfCoversmob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
            });
            $('select#numberofchildrenmob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
            });
            $('select#MeetingsBookingComponent_VenueIdmob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
            });
            $('select#GiftVoucherComponent_HotelGiftVoucherUrlmob', bookingPanel).change(function () {
                window.EQTR.bookingBar.HideDropdown($(this));
            });*/
            /*$(".js-table-link").click(function(e) {
                e.preventDefault();

                // create the modal
                var cover = $('<div class="modal-cover"></div>').appendTo("body");

                // create an iframe and container
                var iframe = $('<div class="restaurant-booking-iframe"><iframe src="' + this.href + '" style="width:250px; height:350px;" scrolling="no" frameborder="0" allowtransparency="true"></iframe><a class="popup-close" href="#">x</a></div>').appendTo("body");

                cover.add(iframe.find("a")).click(function() {
                    cover.add(iframe).remove();
                });
            });*/

            /*if ($('select#TableBookingComponent_RestaurantId', bookingPanel).val() != '') {
                $('select#TableBookingComponent_RestaurantId', bookingPanel).change().selectify("disable");
            }*/

            /*if (bookingBarInitStateConfig && bookingBarInitStateConfig['table']['location']) {
                $('.booking-panel select#TableBookingComponent_RestaurantId').val(bookingBarInitStateConfig['table']['location']).change();
            }*/
			this.hideToolTip();
			this.hideChildAgePanel();
            //this.bookingBarTabs();
            this.tablemobile();
            this.roommobile();
            this.giftsmobile();

            var matched = bookingPanel.data('bookingbarmode');

            window.EQTR.bookingBar.changeBookingBar(matched);

            bookingPanel.animate({ 'opacity': 1 }, 300);

            // clicking anywhere on the page will close all selectmenus.
            /*$(document).on('click', function() {
                $('select').each(function() {
                    if ($(this).data('isSelectified')) {
                        $(this).selectify('closeMenu');
                    }
                });
            });*/

            /*if ($('.best-rate').length > 0 && !$('.booking-panel').hasClass('small-screen')) {

                $('.best-rate_title').on('click', function() {
                    $('.best-rate_inner').toggle();
                });

                var bestRateTimer;
                $(".best-rate").mouseenter(function() {
                    clearTimeout(bestRateTimer);
                    $('.best-rate_inner').show();
                }).mouseleave(function() {
                    bestRateTimer = setTimeout(function () { $('.best-rate_inner').hide(); }, 1500);
                });
                

                $('.best-rate a').on('click', function() {
                    if ($('.best-rate_inner').is(":visible")) {
                        $('.best-rate_inner').hide();
                    }
                });
            }*/

            //}

            /*else {
                window.EQTR.bookingBar.changeBookingBar(context.data('bookingbarmode'));
                var hotelCode = context.data('bookingbarhotel');
                var restaurantCode = context.data('bookingbarrestaurant');
                var enabled = context.data('bookingbardisabled') == "False";

                (hotelCode || hotelCode == "") && _.setHotel(hotelCode);

                _.setRestaurant(restaurantCode);

                _.setVisible(enabled);

                $('.best-rate_inner').hide();   
            }*/

            if ($(window).width() < 521) {
                $('.booking-panel').addClass('small-screen');
            }

            $(window).smartresize(function () {

                if ($(window).width() < 521) {
                    $('.booking-panel').addClass('small-screen');
                } else {
                    $('.booking-panel').removeClass('small-screen');
                }

            });
        }
    };

    /*_.setCitySplit = function (el) {
        $('select.comma').on('onLoad.selectify', function (e) {
            $(this).data().selectMenuContainer.find('.selectify-selectmenu li').each(function () {

                var $this = $(this);

                $this.html(function (index, oldHtml) {

                    if (oldHtml.indexOf(',') != -1) {
                        var oldHtmlSplit = oldHtml.split(',');
                        return oldHtml == 'All Hotels' ? oldHtml : '<span class="location-name">' + $.trim(oldHtmlSplit.slice(0, -1).join()) + '</span><span class="city-name">' + $.trim(oldHtmlSplit.slice(-1).toString()) + '</span>';
                    }
                });

            });
        }).removeClass("comma");
    }*/

    /*_.initInfoPanel = function() {

        var panel = $('<div class="booking-bar-hotel-info-panel-container"><div class="booking-bar-hotel-info-panel-inner hotel-summary"><p id="summaryLogo"></p><p class="hotel-name"></p><div class="rich-content"><p class="summary"></p></div><a class="explore-link" href="">Explore</a></div></div>');
        panel.appendTo('body').hide();
        var panelTimeout;

        // munge the hotel summary data for faster lookup

        var hotelSummaryArray = bookingPanel.data("hotelsummary"),
            hotelSummary = {};
        
        for (var i = 0; i < hotelSummaryArray.length; i++) {
            hotelSummary[hotelSummaryArray[i].NodeId] = hotelSummaryArray[i];
        }

        function hidePanel() {
            $('.booking-bar-hotel-info-panel-container').fadeOut(300);
        }

        $("#RoomBookingComponent_HotelId").on("mouseenter.selectify", function(e, li, value) {
            var $this = $(li);
            clearTimeout(panelTimeout);
            EQTR.bookingBar.showInfoPanel($this, hotelSummary[value]);
        }).on("mouseleave.selectify", function(e, li) {
            panelTimeout = setTimeout(function () { EQTR.bookingBar.hideInfoPanel(300); }, 500);
        }).on("closemenu.selectify", function () {
            EQTR.bookingBar.hideInfoPanel();
        });

        $(document).on('mouseleave', '.booking-bar-hotel-info-panel-container', function() {
            panelTimeout = setTimeout(function () { EQTR.bookingBar.hideInfoPanel(300); }, 500);
        }).on('mouseenter', '.booking-bar-hotel-info-panel-container', function() {
            clearTimeout(panelTimeout);
        });

    };*/

    /*_.showInfoPanel = function (el,data) {

        var panel = $('.booking-bar-hotel-info-panel-container'),
            selectmenuUl = el.closest('.selectify-selectmenu'),
            showCss = { };

        $(".hotel-name", panel).html( data.HotelName );
        $(".summary", panel).html(data.HotelSummary);
        $("a", panel).attr("href", data.LocalisedNiceUrl);
        $("#summaryLogo", panel)[0].className = "hotel-logo icon-" + data.LogoClass;

        if( !panel.is(":visible") )
        {
            panel.css({ visibility: "hidden", display: 'block', width: 380 });
            showCss.display = "none";
            showCss.visibility = "visible";
        }

        // the top will follow the li top, unless it is above the ul top, or the bottom is below the ul bottom
        var panelHeight = panel.height(),
            menuTop = selectmenuUl.offset().top,
            liTop = el.offset().top,
            menuBottom = menuTop + selectmenuUl.height(),
            panelTop = liTop;
        
        if( liTop < menuTop ) {
            panelTop = menuTop;
        } else if( liTop + panelHeight > menuBottom ) {
            panelTop = menuBottom - panelHeight;
        }

        showCss.top = panelTop;
        showCss.left = (selectmenuUl.offset().left + selectmenuUl.width() - 35);

        panel.css(showCss).fadeIn();

    };*/

    _.hideInfoPanel = function (speed) {

        if (isNaN(speed)) {
            $('.booking-bar-hotel-info-panel-container').hide();
        } else {
            $('.booking-bar-hotel-info-panel-container').fadeOut(speed);
        }
    };

    _.changeBookingBar = function (selection) {
		
        $('.select-group').hide().removeClass('active').filter('.' + selection + '-group').show().addClass('active');
		var chooser=$('.' + selection + '-group').find('.chooser');
                    chooser.val(selection);
                    //$('.' + $(this).val() + '-group').closest('booking-form').find('.selectpicker').selectpicker('refresh');
					$('.booking-form .selectpicker').selectpicker('refresh');
					if(selection=='table')
					{
						var restaurantId=$("#TableBookingComponent_RestaurantId").val();
						
						var language = $('html')[0].lang;
		 ($.get('/api/restaurant/getrestaurantconfiguration/?lang=' + language + '&restaurantReference=' + restaurantId, function (data) {
            window.EQTR.restaurantBooking.updateTimeDropDown(data.MealTypes, $('select#Form_MealType'), $('select#Form_MealType').attr('data-translation'));
            window.EQTR.restaurantBooking.updatePeopleDropDown(data.MaxCovers, $('select#Form_NumberOfCovers'), $('select#Form_NumberOfCovers').attr('data-translationsingular'), $('select#Form_NumberOfCovers').attr('data-translationplural'));
			window.EQTR.restaurantBooking.updateTimeDropDown(data.MealTypes, $('select#Form_MealTypemob'), $('select#Form_MealTypemob').attr('data-translation'));
			window.EQTR.restaurantBooking.updatePeopleDropDown(data.MaxCovers, $('select#Form_NumberOfCoversmob'), $('select#Form_NumberOfCoversmob').attr('data-translationsingular'), $('select#Form_NumberOfCoversmob').attr('data-translationplural'));
        }));
					}
					  

    };

    _.setVisible = function (bEnabled) {
        $(".booking-panel-form").toggleClass("booking-panel-disabled", !bEnabled);
        EQTR.SetPageFrameSize();
    };

    _.setHotel = function (hotelCode) {
        $("#RoomBookingComponent_HotelId").val(hotelCode).change();
    };

    _.setRestaurant = function (restaurantCode) {
        if (restaurantCode) {
            $("#TableBookingComponent_RestaurantId").val(restaurantCode).change().selectify("disable");;
        } else {
            $("#TableBookingComponent_RestaurantId").selectify("enable");
        }
    };

    _.bookingBarTabs = function () {

        // open/close the menu

        $(".booking-panel-tabs .tab-1").togglePanel({
            panel: ".booking-panel",
            panelOpenClass: "menu-open",
            linkOpenClass: "active"
        });

        var conciergePanel = $(".booking-panel-tabs .tab-2").togglePanel({
            panel: ".site-nav.concierge",
            panelCloseClass: "site-nav-hide",
            linkOpenClass: "active"
        });

        // always close the concierge panel because it will only be seen on mobile
        $(".site-nav.concierge a").click(function () {
            conciergePanel.togglePanel("toggle", false);
        });

    };

    _.table = function () {

        var restaurantId = $('#TableBookingComponent_RestaurantId');
        var mealTime = $('#Form_MealType');
        var date = $('#datepicker-table');
        var numberOfCovers = $('#Form_NumberOfCovers');

        $('select#chooser').on("selected.selectify", function (event, val) {
            if (val == "table") {
                setTimeout(function () {
                    restaurantId.selectify("openMenu");
                }, 1);
            }
        });

        /*restaurantId.on("selected.selectify", function () {
            $(this).one("apicomplete", function() {
                mealTime.selectify('openMenu');
            });
        });
        
        mealTime.on("selected.selectify", function () {
            date.focus().click();
        });

        date.change(function () {
            numberOfCovers.selectify('openMenu');
        });*/

        $('#book-table-submit').on('click', function (e) {

            e.preventDefault();

            if (numberOfCovers.val().match(/\+/)) {
                EQTR.bookingBar.showToolTip("covers");
                return;
            }
			if (!restaurantId.val()) {
				window.EQTR.bookingBar.triggerDropdown('.restuarents-drp');
				return;
            }
            /*if (!restaurantId.val() || restaurantId.val() == restaurantId.attr('placeholder')) {

                restaurantId.selectify('openMenu');

            } else if (!mealTime.val() || mealTime.val() == mealTime.attr('placeholder')) {

                mealTime.selectify('openMenu');

            } else if (!date.val() || date.val() == date.attr('placeholder')) {

                date.focus().click();

            } else if (!numberOfCovers.val() || numberOfCovers.val() == numberOfCovers.attr('placeholder')) {

                numberOfCovers.selectify('openMenu');

            } else {

                //$('.booking-panel .book-a-table-options input#Form_Date'); //.attr('name', 'Form.Date').attr('id', 'Form_Date');
                $('#TableBookingComponent_RestaurantId').attr('name', 'Form.RestaurantId').attr('id', 'Form_RestaurantId').removeAttr('disabled');
            */
			var selecteddate = $('#datepicker-table').val();
            $('#tableDatestring').val(selecteddate);
            $(this).closest('form').submit();
            //}

        });
    };

    _.room = function () {
		
        var synxisURL = $('.booking-panel-form').data('synxisurl');
        var startDate = $('#datepicker-room');
        var duration = $('#numberofnights');
        var hotelCode = $('#RoomBookingComponent_HotelId');
        var rooms = $('#numberofrooms');
		if(hotelCode.val()=="58527")
		{
			rooms = $('#numberofbedroomsuite', bookingPanel);
		}
        var language = $('html')[0].lang;
        var adults = $('#numberofadults');
        var childrens = $('#numberofchildren');
		var encryptedData=$('.booking-panel-form input[name="Data"]');
        var bf = $('.booking-panel-form').data('trustbookerbfcode');
        /*$('select#chooser').on("selected.selectify", function (event,val) {
            if (val == "room") {
                setTimeout(function() {
                    hotelCode.selectify("openMenu");
                }, 1);
            }
        });

        hotelCode.on("selected.selectify",function() {
            startDate.focus().click();
        });

        startDate.change(function() {
            duration.selectify('openMenu');
        });

        duration.change(function() {
            rooms.selectify('openMenu');
        });*/

        //rooms.change(function () {
        //    EQTR.bookingBar.updateAdultDropDown(rooms.val(), adults);
        //    EQTR.bookingBar.updateChildrenDropDown(rooms.val(), childrens);

        //});

        /*rooms.on("click", function () {
            window.EQTR.bookingBar.HideDropdown($(".rooms-drp"));
            window.EQTR.bookingBar.ShowDropdown($(".adults-drp"));
        });*/
		if(hotelCode.val()){
				
			if(hotelCode.val()=="58527"){
				
				setTimeout(function () {
					$('.selectpicker.hotels-drp').trigger('change');
					$('.selectpicker.bedroomsuite-drp').trigger('change');
				}, 50);
			
			}
			else{
				
				setTimeout(function () {
					$('.selectpicker.hotels-drp').trigger('change');
				}, 50);
			
			}
        }
        $('#book-avail-calendar').on('click', function (e) {
            //alert("desk");
            e.preventDefault();

            var synxisAvailabiltyUrl = $('.booking-panel-form').data('synxisavailurl');
            console.log(synxisAvailabiltyUrl);
            moment.locale(language)

            var rooms_count = rooms.val();
            if (hotelCode.val() == "53138") {
                rooms_count = 1;
            }
            console.log("room=" + rooms_count);

            var data = {
                Language: language,
                BaseSynxisUrl: synxisAvailabiltyUrl,
                HotelId: hotelCode.val(),
                SelectedRooms: rooms_count,
                SelectedNights: duration.val(),
                SelectedAdults: adults.val(),
                SelectedChildrens: childrens.val().substring(0, 1),
                SelectedDateTime: startDate.val(),
                SelectedChildAges: window.EQTR.bookingBar.generateChildAgeAPIString(childrens, rooms_count, childrens.val().substring(0, 1)),
                EncryptedCRSID: encryptedData.val(),
                isAvailabilityCalendarRequest: true
            };
            //return;
            $.post("/book/room/details", data).done(function (responseData) {

                var form = document.createElement("form");

                form.method = "POST";
                form.action = responseData.url;
                console.log(responseData.url);

                $.each(responseData.params, function (key, value) {
                    var element = document.createElement("input");
                    element.value = value;
                    element.name = key;
                    form.appendChild(element);
                });
                document.body.appendChild(form);

                form.submit();
            });
            //}

        });
        /*$('.bootstrap-select.btn-group .dropdown-menu.open.show li').click(function(){alert("yes");});*/
        $('#book-room-submit').on('click', function (e) {
//alert("desk");
            e.preventDefault();

            //3 rooms or more tool tip check
            if (rooms.val().indexOf("+") >= 0) {

                EQTR.bookingBar.showToolTip("rooms");
                //$('.rooms-tooltip').width($('.booking-panel').width()).slideDown(400);
                return;
            }
			if(!hotelCode.val()){
				window.EQTR.bookingBar.triggerDropdown('.hotels-drp');
				return;
			}
			else if(!duration.val()){
				window.EQTR.bookingBar.triggerDropdown('.nights-drp');
				return;
			}
			else if(!rooms.val()){
				window.EQTR.bookingBar.triggerDropdown('.rooms-drp');
				return;
			}
            /*if (!hotelCode.val() || hotelCode.val() == hotelCode.attr('placeholder')) {

                hotelCode.selectify('openMenu');

            } else if (!startDate.val() || startDate.val() == startDate.attr('placeholder')) {

                startDate.focus().click();*/

            //} //else if (!$('.book-a-room-options #Form_Room_Depart_Date').val() || $('.book-a-room-options #Form_Room_Depart_Date').val() == 'Depart') {

            //$('.book-a-room-options #Form_Room_Depart_Date').focus().click();

            //} 
            /* else if (!duration.val() || duration.val() == duration.attr('placeholder')) {
 
                 duration.selectify('openMenu');
 
             } else if (!rooms.val() || rooms.val() == rooms.attr('placeholder')) {
 
                 rooms.selectify('openMenu');
 
             } else {*/

            moment.locale(language)
			
			var rooms_count=rooms.val();
			if(hotelCode.val()=="58527")
			{
				rooms_count=1;
			}

            var data = {
                Language: language,
                BaseSynxisUrl: synxisURL,
                HotelId: hotelCode.val(),
                SelectedRooms: rooms_count,
                SelectedNights: duration.val(),
                SelectedAdults: adults.val(),
                SelectedChildrens: childrens.val().substring(0, 1),
                SelectedDateTime: startDate.val(),
				SelectedChildAges: window.EQTR.bookingBar.generateChildAgeAPIString(childrens,rooms.val(),childrens.val().substring(0, 1)),
				EncryptedCRSID:encryptedData.val()
            };
			//return;
            $.post("/book/room/details", data).done(function (responseData) {

                var form = document.createElement("form");

                form.method = "POST";
                form.action = EQTR.Analytics.getLinkerUrl(responseData.url);

                $.each(responseData.params, function (key, value) {
                    var element = document.createElement("input");
                    element.value = value;
                    element.name = key;
                    form.appendChild(element);
                });
                document.body.appendChild(form);

                form.submit();
            });
            //}

        });

    };
    _.triggerDropdown = function (el) {

        //el.trigger('click');
        setTimeout(function () {
							  $(el+'.bootstrap-select .dropdown-toggle').trigger('click')
							 }, 50);
    };
    _.ShowDropdown = function (el1, el2) {

        //if (!(el.parent('.bootstrap-select').find('.dropdown-menu.open').hasClass("show"))) {
        //    el.trigger('click');

        //alert('click works');
        $('.bootstrap-select' + el1).click(function () {
            if ($('.bootstrap-select' + el1).hasClass('open')) {
                //el2.selectpicker('toggle');
                el2.selectpicker('toggle');
                el2.selectpicker('refresh');
            }
        });

        //}
    };
    _.HideDropdown = function (el) {

        //if (el.parent('.bootstrap-select').find('.dropdown-menu.open').hasClass("show")) {
        //    el.trigger('click');
        el.find('.dropdown-menu').removeClass('show');
        //}
    };
    _.updateChildrenDropDown = function (noofrooms, el) {

        //!label ? 'Select' : label;
        var html = '';
		var roomscount=noofrooms.substring(0, 1);
        //var html = '<option value="">' + translation + '</option>';
        //var html = '<option value="">Time</option>';
		if(roomscount>4)
		{
			roomscount=4;
		}
        MaxAdultChildrenDropDownItems = 3 * roomscount;
        for (i = 0; i <= MaxAdultChildrenDropDownItems; i++) {
            html += '<option value="' + i + '">' + i + '</option>';
        }
        el.html(html).selectpicker('refresh');
        //.selectify('buildMenu');

    };
    _.updateAdultDropDown = function (noofrooms, el) {

        //!label ? 'Select' : label;
        var html = '';
		var roomscount=noofrooms.substring(0, 1);
        //var html = '<option value="">' + translation + '</option>';
        //var html = '<option value="">Time</option>';
		if(roomscount>4)
		{
			roomscount=4;
		}
        MaxAdultChildrenDropDownItems = 3 * roomscount;
        for (i = 1; i <= MaxAdultChildrenDropDownItems; i++) {
            html += '<option value="' + i + '">' + i + '</option>';
        }
        el.html(html).selectpicker('refresh');
        //.selectify('buildMenu');

    };
	_.updateBedRoomSuiteChildrenDropDown = function (noofrooms, el, adultscount = 0, hotelIdnum = 0) {

        //!label ? 'Select' : label;
        var html = '';
		var roomscount=noofrooms.substring(0, 1);
		var hotelCode = $('#RoomBookingComponent_HotelId');
        //var html = '<option value="">' + translation + '</option>';
        //var html = '<option value="">Time</option>';
		if(hotelIdnum == "58527")	
		{	
			MaxAdultChildrenDropDownItems = (5 * roomscount) - adultscount;
		}else{
			MaxAdultChildrenDropDownItems = 3 * roomscount;
		}
        
        for (i = 0; i <= MaxAdultChildrenDropDownItems; i++) {
            html += '<option value="' + i + '">' + i + '</option>';
        }
        el.html(html).selectpicker('refresh');
        //.selectify('buildMenu');

    };
    _.updateBedRoomSuiteAdultDropDown = function (noofrooms, el, hotelIdnum = 0) {

        //!label ? 'Select' : label;
        var html = '';
		var roomscount=noofrooms.substring(0, 1);
		var hotelCode = $('#RoomBookingComponent_HotelId');
        //var html = '<option value="">' + translation + '</option>';
        //var html = '<option value="">Time</option>';
		if(hotelIdnum == "58527"){
			MaxAdultChildrenDropDownItems = 5 * roomscount;
		}else{
			MaxAdultChildrenDropDownItems = 4 * roomscount;
		}
        
        for (i = 1; i <= MaxAdultChildrenDropDownItems; i++) {
            html += '<option value="' + i + '">' + i + '</option>';
        }
        el.html(html).selectpicker('refresh');
        //.selectify('buildMenu');

    };
    _.showToolTip = function (tooltipType) {

        var toolTip = $('.' + tooltipType + '-tooltip');
		toolTip.show();
        //toolTip.width($('.booking-panel').width()).slideDown(400);
        //var toolTipTimeout = setTimeout(EQTR.bookingBar.hideToolTip, 5000);

        toolTip.find('.btn-close').on('click', function () {
			//e.preventDefault();
			//console.log('check');
            EQTR.bookingBar.hideToolTip();
        });

        /*toolTip.on('mouseenter', function () {
            clearTimeout(toolTipTimeout);
        }).on('mouseleave', function () {
            toolTipTimeout = setTimeout(EQTR.bookingBar.hideToolTip, 5000);
        });*/

    };

    _.hideToolTip = function () {

        var toolTip = $('.booking-tooltip');
		toolTip.hide();
        //toolTip.slideUp(300);
        //        clearTimeout(toolTipTimeout);
        //        toolTip.find('.button').on('click');
    };
	
	_.generateChildAgeAPIString = function (el,rooms,childrens) {
		var childAgePanel = el.closest('.forms').find('.child-ages-row');
		var ChildAgeAPIString="";
		var childrencount=0;
		for (i = 0; i < rooms; i++) { 
			var currentRoomChildrens=parseInt(childrens/rooms);
			//console.log(currentRoomChildrens);
			if(childrens%rooms >0 && ((childrens%rooms)>i))
			{
				currentRoomChildrens++;
			}
			//console.log(currentRoomChildrens);
			var currentRoomChildrensAPIString="";
			for (j = childrencount; j < (childrencount+currentRoomChildrens); j++) { 
				currentRoomChildrensAPIString+=childAgePanel.find('div.col-child-ages').eq(j).find('.selectpicker.ages-drp').val();
				if(j<((childrencount+currentRoomChildrens)-1))
				{
					currentRoomChildrensAPIString+='|';
				}
				//console.log(childrencount+currentRoomChildrens);
				//console.log(currentRoomChildrensAPIString);
			}
			childrencount+=currentRoomChildrens;
			ChildAgeAPIString+=currentRoomChildrensAPIString;
			if((rooms<=childrens) && (i<(rooms-1)))
			{
				ChildAgeAPIString+=',';
			}
			else if ((rooms>childrens) && (i<(childrens-1)))
			{
				ChildAgeAPIString+=',';
			}
			//console.log(ChildAgeAPIString);
		}
		//console.log(ChildAgeAPIString);
		return ChildAgeAPIString;
    };
	
	_.hideChildAgePanel = function () {
		
		var childAgeRow = $('div.child-ages-row');
        var childAgePanel = $('div.col-child-ages');
		childAgePanel.hide();
		childAgeRow.hide();
    };
	_.showChildAgePanel = function (childNumber,el) {
		this.hideChildAgePanel();
		var ChildAgesInARow = 5;
        if (el.hasClass('FormNights')) {
            ChildAgesInARow = 4;
        }
		if(childNumber>0)
		{
			if (childNumber > ChildAgesInARow)
			{
				el.closest('.forms').find('.child-ages-row').show();
			}
			else{
				el.closest('.forms').find('.child-ages-row').first().show();
			}
			var childAgePanel = el.closest('.forms').find('.child-ages-row');
			for (i = 0; i < childNumber; i++) { 
				childAgePanel.find('div.col-child-ages').eq(i).show();
			}
			
			setTimeout(function () {
				childAgePanel.find('div.col-child-ages').eq(0).find('.bootstrap-select .dropdown-toggle').trigger('click');
			}, 50);
		}
    };

    var startDateReformat = function (date) {
        // assume we have a value at this point because of the jquery ui datepicker.
        return date.toDateString();
    };

    _.gifts = function () {

        $('select#chooser').on("selected.selectify", function (event, val) {
            if (val == "voucher") {
                setTimeout(function () {
                    $("#GiftVoucherComponent_HotelGiftVoucherUrl").selectify("openMenu");
                }, 1);
            }
        });

        $('.buy-a-voucher-options input[type="submit"]').on('click', function (e) {

            e.preventDefault();
            var url = generateGiftsUrl();
			
			var hotelCode =$('#GiftVoucherComponent_HotelGiftVoucherUrl');
			if(!hotelCode.val()){
				window.EQTR.bookingBar.triggerDropdown('.vouchers-drp');
				return;
			}
			
            if (url != null || url != '' || url != undefined) {
                window.open(url, '_blank');
            }

            return false;

        });
        $('.meetings-options input[type="submit"]').on('click', function (e) {

            e.preventDefault();
            var url = generateMeetingsUrl();

			var hotelCode =$('#MeetingsBookingComponent_VenueId');
			if(!hotelCode.val()){
				window.EQTR.bookingBar.triggerDropdown('.venues-drp');
				return;
			}
			
            if (url != null || url != '' || url != undefined) {
                location.href = url;
            }

            return false;

        });
        var generateMeetingsUrl = function () {

            return $('#MeetingsBookingComponent_VenueId').val();
        };
        var generateGiftsUrl = function () {

            return EQTR.Analytics.getLinkerUrl($('.buy-a-voucher-options #GiftVoucherComponent_HotelGiftVoucherUrl').val());

            /*var giftTypePlaceholder = '{{GIFTTYPE}}';
	        var locationPlaceholder = '{{LOCATION}}';
	        var url = 'http://gifts.roccforte.com/?gifttype=' + giftTypePlaceholder + '&location=' + locationPlaceholder + '';
	        var giftType = $('.buy-a-voucher-options #typeofgift').val();
	        var giftLocation = $('.buy-a-voucher-options #location2').val();
	        var mapper = [];
	        mapper[giftTypePlaceholder] = giftType;
	        mapper[locationPlaceholder] = giftLocation;

	        url = url.replace(/{{GIFTTYPE}}|{{LOCATION}}/gi, function (matched) {
	            return mapper[matched];
	        });

	        return url;*/
        };

    };

    //Mobile

    _.tablemobile = function () {
        var bookingPanel = $('.booking-panel-form-mob');
        var restaurantId = $('.book-a-table-options-mob #TableBookingComponent_RestaurantIdmob', bookingPanel);
        var mealTime = $('#Form_MealTypemob', bookingPanel);
        var date = $('#datepicker-table-mob', bookingPanel);
        var numberOfCovers = $('#Form_NumberOfCoversmob', bookingPanel);

        $('select#chooser', bookingPanel).on("selected.selectify", function (event, val) {
            if (val == "table") {
                setTimeout(function () {
                    restaurantId.selectify("openMenu");
                }, 1);
            }
        });

        /*restaurantId.on("selected.selectify", function () {
            $(this).one("apicomplete", function() {
                mealTime.selectify('openMenu');
            });
        });
        
        mealTime.on("selected.selectify", function () {
            date.focus().click();
        });

        date.change(function () {
            numberOfCovers.selectify('openMenu');
        });*/

        $('#book-table-submit-mob').on('click', function (e) {

            e.preventDefault();

            if (numberOfCovers.val().match(/\+/)) {
                EQTR.bookingBar.showToolTip("covers");
                return;
            }
			if (!restaurantId.val()) {
				window.EQTR.bookingBar.triggerDropdown('.restuarents-drp-mob');
				return;
            }
            /*if (!restaurantId.val() || restaurantId.val() == restaurantId.attr('placeholder')) {

                restaurantId.selectify('openMenu');

            } else if (!mealTime.val() || mealTime.val() == mealTime.attr('placeholder')) {

                mealTime.selectify('openMenu');

            } else if (!date.val() || date.val() == date.attr('placeholder')) {

                date.focus().click();

            } else if (!numberOfCovers.val() || numberOfCovers.val() == numberOfCovers.attr('placeholder')) {

                numberOfCovers.selectify('openMenu');

            } else {

                //$('.booking-panel .book-a-table-options input#Form_Date'); //.attr('name', 'Form.Date').attr('id', 'Form_Date');
                $('#TableBookingComponent_RestaurantId').attr('name', 'Form.RestaurantId').attr('id', 'Form_RestaurantId').removeAttr('disabled');
            */
			var selecteddate = $('#datepicker-table-mob').val();
            $('#tableDatestring-mob').val(selecteddate);
            $(this).closest('form').submit();
            //}

        });
    };

    _.roommobile = function () {
        var bookingPanel = $('.booking-panel-form-mob');
        var synxisURL = bookingPanel.data('synxisurl');
        var startDate = $('#datepicker-room-mob', bookingPanel);
        var duration = $('#numberofnightsmob', bookingPanel);
        var hotelCode = $('#RoomBookingComponent_HotelIdmob', bookingPanel);
        var rooms = $('#numberofroomsmob', bookingPanel);
		if(hotelCode.val()=="58527")
		{
			rooms = $('#numberofbedroomsuitemob', bookingPanel);
		}
        var language = $('html')[0].lang;
        var adults = $('#numberofadultsmob');
        var childrens = $('#numberofchildrenmob');
        var bf = bookingPanel.data('trustbookerbfcode');
		var encryptedData=$('.booking-panel-form input[name="Data"]');
        /*$('select#chooser').on("selected.selectify", function (event,val) {
            if (val == "room") {
                setTimeout(function() {
                    hotelCode.selectify("openMenu");
                }, 1);
            }
        });

        hotelCode.on("selected.selectify",function() {
            startDate.focus().click();
        });

        startDate.change(function() {
            duration.selectify('openMenu');
        });

        duration.change(function() {
            rooms.selectify('openMenu');
        });*/

        //rooms.change(function () {
        //    EQTR.bookingBar.updateAdultDropDown(rooms.val(), adults);
        //    EQTR.bookingBar.updateChildrenDropDown(rooms.val(), childrens);

        //});
        // rooms.on("click", function () {
        //     window.EQTR.bookingBar.HideDropdown($(this));
        //     window.EQTR.bookingBar.ShowDropdown($("#numberofadultsmob"));
        // });
		
		if(hotelCode.val()){
				
			if(hotelCode.val()=="58527"){
				
				setTimeout(function () {
					$('.selectpicker.hotels-drp-mob').trigger('change');
					$('.selectpicker.bedroomsuite-drp-mob').trigger('change');
				}, 50);
			
			}
			else{
				
				setTimeout(function () {
					$('.selectpicker.hotels-drp-mob').trigger('change');
				}, 50);
			
			}
        }
        $('#book-avail-calendar-mob').on('click', function (e) {
            //alert("desk");
            e.preventDefault();

            var synxisAvailabiltyUrl = $('.booking-panel-form').data('synxisavailurl');
            console.log(synxisAvailabiltyUrl);
            moment.locale(language)

            var rooms_count = rooms.val();
            if (hotelCode.val() == "53138") {
                rooms_count = 1;
            }
            console.log("room=" + rooms_count);

            var data = {
                Language: language,
                BaseSynxisUrl: synxisAvailabiltyUrl,
                HotelId: hotelCode.val(),
                SelectedRooms: rooms_count,
                SelectedNights: duration.val(),
                SelectedAdults: adults.val(),
                SelectedChildrens: childrens.val().substring(0, 1),
                SelectedDateTime: startDate.val(),
                SelectedChildAges: window.EQTR.bookingBar.generateChildAgeAPIString(childrens, rooms_count, childrens.val().substring(0, 1)),
                EncryptedCRSID: encryptedData.val(),
                isAvailabilityCalendarRequest: true
            };
            //return;
            $.post("/book/room/details", data).done(function (responseData) {

                var form = document.createElement("form");

                form.method = "POST";
                form.action = responseData.url;
                console.log(responseData.url);

                $.each(responseData.params, function (key, value) {
                    var element = document.createElement("input");
                    element.value = value;
                    element.name = key;
                    form.appendChild(element);
                });
                document.body.appendChild(form);

                form.submit();
            });
            //}

        });
        $('#book-room-submit-mob').on('click', function (e) {
			//alert("mobile");
            e.preventDefault();

            //3 rooms or more tool tip check
            if (rooms.val().indexOf("+") >= 0) {
				
                EQTR.bookingBar.showToolTip("rooms");
                //$('.rooms-tooltip').width($('.booking-panel').width()).slideDown(400);
                return;
            }
			if(!hotelCode.val()){
				window.EQTR.bookingBar.triggerDropdown('.hotels-drp-mob');
				return;
			}
			else if(!duration.val()){
				window.EQTR.bookingBar.triggerDropdown('.nights-drp-mob');
				return;
			}
			else if(!rooms.val()){
				window.EQTR.bookingBar.triggerDropdown('.rooms-drp-mob');
				return;
			}
            /*if (!hotelCode.val() || hotelCode.val() == hotelCode.attr('placeholder')) {

                hotelCode.selectify('openMenu');

            } else if (!startDate.val() || startDate.val() == startDate.attr('placeholder')) {

                startDate.focus().click();*/

            //} //else if (!$('.book-a-room-options #Form_Room_Depart_Date').val() || $('.book-a-room-options #Form_Room_Depart_Date').val() == 'Depart') {

            //$('.book-a-room-options #Form_Room_Depart_Date').focus().click();

            //} 
            /* else if (!duration.val() || duration.val() == duration.attr('placeholder')) {
 
                 duration.selectify('openMenu');
 
             } else if (!rooms.val() || rooms.val() == rooms.attr('placeholder')) {
 
                 rooms.selectify('openMenu');
 
             } else {*/

            moment.locale(language)

			var rooms_count=rooms.val();
			if(hotelCode.val()=="58527")
			{
				rooms_count=1;
			}
			
            var data = {
                Language: language,
                BaseSynxisUrl: synxisURL,
                HotelId: hotelCode.val(),
                SelectedRooms: rooms_count,
                SelectedNights: duration.val(),
                SelectedDateTime: startDate.val(),
                SelectedAdults: adults.val(),
                SelectedChildrens: childrens.val().substring(0, 1),
				SelectedChildAges: window.EQTR.bookingBar.generateChildAgeAPIString(childrens,rooms.val(),childrens.val().substring(0, 1)),
				EncryptedCRSID:encryptedData.val()
            };

            $.post("/book/room/details", data).done(function (responseData) {

                var form = document.createElement("form");

                form.method = "POST";
                form.action = EQTR.Analytics.getLinkerUrl(responseData.url);

                $.each(responseData.params, function (key, value) {
                    var element = document.createElement("input");
                    element.value = value;
                    element.name = key;
                    form.appendChild(element);
                });
                document.body.appendChild(form);

                form.submit();
            });
            //}

        });

    };

    _.giftsmobile = function () {
        var bookingPanel = $('.booking-panel-form-mob');
        $('select#chooser', bookingPanel).on("selected.selectify", function (event, val) {
            if (val == "voucher") {
                setTimeout(function () {
                    $("#GiftVoucherComponent_HotelGiftVoucherUrlmob", bookingPanel).selectify("openMenu");
                }, 1);
            }
        });

        $('.buy-a-voucher-options-mob input[type="submit"]').on('click', function (e) {

            e.preventDefault();
            var url = generateGiftsUrl();
			var hotelCode =$('#GiftVoucherComponent_HotelGiftVoucherUrlmob');
			if(!hotelCode.val()){
				window.EQTR.bookingBar.triggerDropdown('.vouchers-drp-mob');
				return;
			}
			
            if (url != null || url != '' || url != undefined) {
                window.open(url, '_blank');
            }

            return false;

        });
        $('.meetings-options-mob input[type="submit"]').on('click', function (e) {

            e.preventDefault();
            var url = generateMeetingsUrl();
			
			var hotelCode =$('#MeetingsBookingComponent_VenueIdmob');
			if(!hotelCode.val()){
				window.EQTR.bookingBar.triggerDropdown('.venues-drp-mob');
				return;
			}
			
            if (url != null || url != '' || url != undefined) {
                location.href = url;
            }

            return false;

        });
        var generateMeetingsUrl = function () {

            return $('#MeetingsBookingComponent_VenueIdmob', bookingPanel).val();
        };
        var generateGiftsUrl = function () {

            return EQTR.Analytics.getLinkerUrl($('.buy-a-voucher-options #GiftVoucherComponent_HotelGiftVoucherUrlmob', bookingPanel).val());

            /*var giftTypePlaceholder = '{{GIFTTYPE}}';
	        var locationPlaceholder = '{{LOCATION}}';
	        var url = 'http://gifts.roccforte.com/?gifttype=' + giftTypePlaceholder + '&location=' + locationPlaceholder + '';
	        var giftType = $('.buy-a-voucher-options #typeofgift').val();
	        var giftLocation = $('.buy-a-voucher-options #location2').val();
	        var mapper = [];
	        mapper[giftTypePlaceholder] = giftType;
	        mapper[locationPlaceholder] = giftLocation;

	        url = url.replace(/{{GIFTTYPE}}|{{LOCATION}}/gi, function (matched) {
	            return mapper[matched];
	        });

	        return url;*/
        };

    };

    return _;

})(window.EQTR.bookingBar || {}, jQuery);;
window.EQTR.grid = (function (namespace, $, undefined) {

  var _ = namespace;

  _.init = function (context) {

    // masonry

    // initialize masonry in blog section
    if ($('.grid-post-group').length) {
      var $masonryContainer = $('.grid-post-group');
      $masonryContainer.imagesLoaded(function () {
        console.log('init masonry');
        //$masonryContainer.find('.grid-post__image').each(function () {
        //  $(this).responsiveBackgroundImage();
        //});

        setTimeout(function () {
          $masonryContainer.masonry({
            itemSelector: '.grid-post'
          });
        }, 100); // its required because of fonts
      });
    }

  };

  return _;

})(window.EQTR.grid || {}, jQuery);;
window.EQTR.blog = (function (namespace, $, undefined) {

    var _ = namespace;

    _.init = function (context) {

        if ($('.blog-page').length) {

            //if ($('.blog-main-page').length) {
                //window.EQTR.blog.resizePostContainer();
            //}

            //$(window).smartresize(function () {

                //window.EQTR.blog.resizePostContainer();

            //});

        }

        // masonry

        // initialize masonry in blog section
        if ($('.blog-post-group').length) {
            var $masonryContainer = $('.blog-post-group');
            $masonryContainer.imagesLoaded(function () {
                console.log('init masonry');

                setTimeout(function () {
                    $masonryContainer.masonry({
                        itemSelector: '.blog-post'
                    });
                }, 100); // its required because of fonts
            });
        }

        $('.js-locations .blog-categories__trigger').click(function () {
            var $this = $(this);
            
            var $locations = $this.parents('.js-locations');
            var $content = $('.blog-categories__content', $locations);
            console.log('test', $locations, $content);

            $content.slideToggle();
            $locations.toggleClass('blog-categories--is-open');
        });


        // //masonry

        //Social
        jsSocials.shares.pinterest.media = $('meta[property="og:image"]').attr('content') || '';
        $('.social-media.social-media--blog').jsSocials({
            showLabel: true,
            showCount: true,
            shares: ["twitter", "facebook", "googleplus", "pinterest"]
        });
    };

    _.resizePostContainer = function () {

        var coloumnCount = 2;

        $('.blog-post-listing').height(function () {

            var height = 0;

            $(this).find('> li.image-content-two-panel').each(function () {
                height += $(this).height();
                console.log(height);
            });

            return (height / coloumnCount);

        });
    }

    return _;

})(window.EQTR.blog || {}, jQuery);;
window.EQTR.restaurantBooking = (function (namespace, $, undefined) {

    var _ = namespace,
	    $bookingPanel,
        $covers,
        $meals,
        $restaurant;

	_.init = function (context) {

        context = context == document ? $(".page-content",context) : $(context)

	    if (!context.is(".restaurant-booking")) return;

	    var bookingTimes;

	    $bookingPanel = $('.booking-panel');
        
	    $('input[type="checkbox"]',context).checkboxify();

	    $("#enquireContainer").hide();
		$covers = $("select#Form_NumberOfCovers",context);
		$meals = $("select#Form_MealType",context);
	    /*$covers = $("select#Form_NumberOfCovers",context)
            .find("option")
            .remove()
            .end()
            .append('<option value="">' + $('select#Form_NumberOfCovers', context).attr('data-translationsingular') + '</option>')
            .change(function () {
                $("#bookContainer")[this.value.indexOf("+") >= 0 ? "hide" : "show"]();
                $("#enquireContainer")[this.value.indexOf("+") >= 0 ? "show" : "hide"]();
            });

	    $meals = $("select#Form_MealType",context).find("option").remove().end().append('<option value="">' + $('select#Form_MealType', context).attr('data-translation') + '</option>');*/

		/*if ($('select.input',context).length > 0) {
		    $('select.input',context).each(function () {

		        var el = $(this);

		        el.selectify({
		            'width': '260',
		            'maxHeight': '300',
		            'firstOptionVisibleInDropDown': false,
		        });
		    });

		}*/

		if ($('.input#Form_Date',context).length) {

		    $('.input#Form_Date',context).attr("readonly",true).datepicker({
				minDate: 0,
				dateFormat: 'dd/mm/yy',
				beforeShow: function (input, inst) {
				    var calendrier = inst.dpDiv;
				    var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 20;
				    setTimeout(function () { calendrier.css({ 'left': left }); }, 10);
				}
			});

		}

		if ((bookingTimes = $('.booking-times',context)).length) {

			bookingTimes.on('click', 'label.available', function () {

				var $this = $(this);
				var labels = $(bookingTimes).find('label');
				var index = labels.index($this);

				labels.removeClass('selected');
				$this.addClass('selected');

			});
		}

		if (($restaurant = $('select#Form_RestaurantId',context)).length > 0) {

			
			$.ajaxSetup({
				cache: false
			});

			$restaurant.change(function () {

			    var language = $('html')[0].lang,
                    $restaurantIdSelect = $(this),
                    restaurantId = $(this).val();
					

			    if (restaurantId) {

			        if (restaurantId.match(/http/)) {
			            $(this).closest(".form").addClass("restaurant-direct-link");
			            $(".restaurant-booking-link a").attr("href", restaurantId);

			        } else {
							var selectedmeal=$meals.val();
					var selectedpeople=$covers.val();
			            $.get('/api/restaurant/getrestaurantconfiguration/?lang=' + language + '&restaurantReference=' + restaurantId, function (data) {
			                // setting a timeout because something isn't picking up quick enough, but can't see where it is right now
			                setTimeout(function () {
			                    window.EQTR.restaurantBooking.updateTimeDropDown(data.MealTypes, $meals, $("select#Form_MealType",context).attr('data-translation'));
			                    window.EQTR.restaurantBooking.updatePeopleDropDown(data.MaxCovers, $covers, $("select#Form_NumberOfCovers",context).attr('data-translationsingular'), $("select#Form_NumberOfCovers",context).attr('data-translationplural'));
			                    if(selectedmeal!=null && selectedmeal!="")
								{
									$meals.val(selectedmeal);
									$meals.selectpicker('refresh');
								}
								if(selectedpeople!=null && selectedpeople!="")
								{
									$covers.val(selectedpeople);
									$covers.selectpicker('refresh');
								}
								//$covers.change().selectify('enable');
			                    //$meals.change().selectify('enable');

			                    // set the enquiry form hotel. Probably should do this in restaurantBooking.js?
			                    $(".js-restaurantenquiry").attr("href", function (index, val) {
			                        return $(this).data("href") + data.HotelDataWarehouseReference + "/";
			                    });
								var defaultDate=window.EQTR.restaurantBooking.getDefaultDate();
									
								if($('.preload-wrapper').hasClass('loaded') && $('#tableDatestring').val()==defaultDate)	
								{
									if (data.StartingDateString) {
									$('#Form_Date').val(data.StartingDateString);
									}
									else
									{
										$('#Form_Date').val(defaultDate);
									}
								}
			                }, 0);
			            });

			            $(this).closest(".form").removeClass("restaurant-direct-link");

			        }
			    } else {
			        //$meals.selectify('disable');
			        //$covers.selectify('disable');
			    }

			}).triggerHandler("change");


		}



		if ($('#canceltable').length) {

		    var cancelButton = $('#canceltable');

		    var html = $('<div class="rich-content"><p class="sub-text">' + cancelButton.attr('data-popupcontent') + '</p><div class="input-container"><input type="button" class="button" id="popup-cancel" name="popup-cancel" value="' + cancelButton.attr('data-popupcancel') + '" /></div><div class="input-container"><input type="button" class="button" id="popup-confirm" name="popup-confirm" value="' + cancelButton.attr('data-popupconfirm') + '" /></div></div>');

		    $(document).on('click', '#canceltable', function () {
		        window.EQTR.restaurantBooking.popupBox({ 'content': html });
		        return false;

		    });

		    html.find('#popup-cancel').on('click', function () {
		        $('.eqtr-popup-container').find('.popup-close').click();
		        return false;
		    });

		    html.find('#popup-confirm').on('click', function () {
		        $('#canceltable').closest('form').submit();
		        $('.eqtr-popup-container').find('.popup-close').click();
		        return false;
		    });

		}

		function vAlignCol2Text() {

			if ($('.banner-2col .col2 .text').length && $(window).width() >= 768) {
				$('.banner-2col .col2').valign();
			} else {
				$('.banner-2col .col2').css({ 'margin-top': '0px' });
			}

		}

		vAlignCol2Text();
		$(window).smartresize(vAlignCol2Text);
		
		
		
		$('.restaurant-booking form').submit(function (e) {
            var selecteddate = $('.restaurant-booking .restaurant-booking-date .datepicker-here').val();
            $('#tableDatestring').val(selecteddate);
        });
	};

	_.updatePeopleDropDown = function (number, el, singular, plural) {

	    //!label ? 'Select' : plural;

	    var html = '';

	    for (var i = 1; i <= number; i++) {
	        html += '<option value="' + i + '">' + i + ' ' + ( i == 1 ? singular : plural) + '</option>';
		}

	    html += '<option value="' + i + '+">' + i + '+ ' + plural + '</option>';

		el.html(html).selectpicker('refresh');
		//.val("").selectify('buildMenu');

	};

    _.updateTimeDropDown = function(mealTypes, el, translation) {

        //!label ? 'Select' : label;

        var html = '';
		//var html = '<option value="">Time</option>';

        $.each(mealTypes, function(key, value) {

            html += '<option value="' + key + '">' + value + '</option>';

        });
		el.html(html).selectpicker('refresh');
		//.selectify('buildMenu');

    };
_.updateTablePeopleDropDown = function (number, el, singular, plural) {

	    //!label ? 'Select' : plural;

	    var html = '';

	    for (var i = 1; i <= number; i++) {
	        html += '<option value="' + i + '">' + i + ' ' + ( i == 1 ? singular : plural) + '</option>';
		}

	    html += '<option value="' + i + '+">' + i + '+ ' + plural + '</option>';

		el.html(html).selectify('buildMenu');

	};

    _.updateTableTimeDropDown = function(mealTypes, el, translation) {

        //!label ? 'Select' : label;

        var html = '';
		var html = '<option value="">translation</option>';

        $.each(mealTypes, function(key, value) {
           
            html += '<option value="' + key + '">' + value + '</option>';

        });
		
		el.html(html).selectify('buildMenu');

    };
	_.getDefaultDate=function(){
		var date=new Date();
		var day = date.getDate();
		var month = date.getMonth() + 1;
		var year = date.getFullYear();
		if (day < 10) {
			day = "0" + day;
		}
		if (month < 10) {
			month = "0" + month;
		}
		var defaultDate =  day + "/" + month + "/" + year;
		return defaultDate;
	};
	_.popupBox = function (options) {

	    var defaults = {
	        speedIn: 300, // fade in speed.
	        speedOut: 300, // fade out speed.
	        closeButton: true, // has close button.
	        content: null,
	        customClass: null // custom  class to aply to the popup parent container
	    };

	    var settings = $.extend({}, defaults, options);
	    var randomNum = Math.floor(Math.random() * (900000) + 100000);
	    var popupHtml = $('<div id="reb-popup-container-' + randomNum + '" class="eqtr-popup-container" style="display: none;"><div class="popup-document-mask"></div><div class="popup-inner"><a class="popup-close">X</a><div class="popup-content"></div></div></div>');
	    var triggerEvent = settings.triggerEvent != null ? settings.triggerEvent : 'click';
	    var popupInner = popupHtml.find('.popup-inner');
	    var popupMask = popupHtml.find('.popup-document-mask');
	    var popupClose = popupHtml.find('.popup-close');

	    if (settings.customClass) {
	        popupHtml.addClass(settings.customClass);
	    }

	    if (!settings.closeButton) {
	        popupClose.remove();
	    }

	    if (settings.content instanceof jQuery) {
	        var popupContent = settings.content;
	    } else {
	        var popupContent = $(settings.content).html() || settings.content || 'Error loading content';
	    }

	    popupHtml.find('.popup-content').html(popupContent);

	    popupHtml.appendTo('body');

	    /*if (settings.triggerEl) {

	        $(document).on(triggerEvent, settings.triggerEl, function () {
	            // create callback method within the options that can be passed in.

	            //positionPopup(popupInner);
	            popupHtml.fadeIn(settings.speedIn, function () {
	                // create callback method within the options that can be passed in.
	            });

	            positionPopup(popupInner);

	            return false;

	        });

	    } else {*/

	        popupHtml.fadeIn(settings.speedIn); //, function () {
	            // create callback method within the options that can be passed in.
	        //});

	        positionPopup(popupInner);

	    //}

	    popupClose.on('click', function () {
	        // create callback method within the options that can be passed in.

	        popupHtml.fadeOut(settings.speedOut); //, function () {
	            // create callback method within the options that can be passed in.
	        //});

	        return false;

	    });

	    if (settings.closeButton === true) {

	        popupMask.on('click', function () {

	            popupClose.click();

	            return false;

	        });

	    }

	    $(window).smartresize(function () {

	        positionPopup(popupInner);

	    });

	    function positionPopup(el) {

	        var popupHeight = el.outerHeight();
	        var popupWidth = el.outerWidth();
	        var screenHeight = $(window).height();
	        var screenWidth = $(window).width();

	        var marginTop = parseInt((popupHeight / 2), 10);
	        var marginLeft = parseInt((popupWidth / 2), 10);

	        el.css({

	            'margin-left': -marginLeft + 'px',
	            'margin-top': -marginTop + 'px'

	        });

	    }

	};

	return _;

})(window.EQTR.restaurantBooking || {}, jQuery);;
window.EQTR = (function (module, $, undefined) {

    var _ = {};

	_.init = function () {
		
	    var roomBooking = $(".room-booking");

	    if (!roomBooking.length) return;

	    $("#Form_SelectedRooms").each(function() {
	        var select = $(this),
	            lastOption = $("option", select).last(),
	            lastVal = lastOption.val(),
	            lastText = lastOption.text(),
	            newVal = lastVal*1 + 1,
	            newText = lastText.replace(lastVal, newVal + "+"),
	            newOption = $("<option />").val(newVal).text(newText);

	        select
	            .append(newOption)
	            .change(function() {
	                $("#bookContainer")[this.value == newVal ? "hide" : "show"]();
	                $("#enquireContainer")[this.value == newVal ? "show" : "hide"]();
	            }).triggerHandler("change");
	        
	    });

		/*$('select.input',roomBooking).each(function () {

		    var el = $(this);
		    el.selectify({
		        'width': '260',
                'maxHeight': '300'
		    });
		});*/

		$('.input.dateselector',roomBooking).attr("readonly", true).datepicker({
			minDate: 0,
			dateFormat: 'dd/mm/yy',
			beforeShow: function (input, inst) {
				var calendrier = inst.dpDiv;
				var top = $(this).offset().top + $(this).outerHeight();
				var left = $(this).offset().left + ($(this).width() / 2) - (calendrier.width() / 2) - 20;
				setTimeout(function () { calendrier.css({ 'top': top, 'left': left }); }, 10);
			}
		});

	    $("#book-room", roomBooking).click(function(e) {

	        // put the google cross domain tracking into the GoogleLinkerParam input. This needs to be done as late as possible (well within 2 minutes) because GA checks the time of the link
	        $("#GoogleLinkerParam").val(EQTR.Analytics.getLinkerParam());

	        /*if (!$("#Form_HotelId").val()) {
	            $("#Form_HotelId").selectify('openMenu');
	            e.preventDefault();
	        }*/
	    });

	    $('.room-booking form').submit(function (e) {
	        e.preventDefault();
			
			if($('#Form_HotelId').val()==""){
				return false;
			}
			var selecteddate = $('#Form_SelectedDateTime').val();
			var rooms = $('#Form_SelectedRooms');
			var adults = $('#numberofadults');
			var childrens = $('#numberofchildren');
			
            $('#roomDatestring').val(selecteddate);
			
			if($('#Form_HotelId').val()=="58527")
			{
				$("#Form_SelectedRooms").val("1");
			}
			
			$('#selectedAdults').val(adults.val());
			$('#selectedChildrens').val(childrens.val());
			$('#selectedChildAges').val(window.EQTR.bookingBar.generateChildAgeAPIString(childrens,rooms.val(), childrens.val().substring(0, 1)));
			
			
	        var data = $(this).serialize();

	        $.post("/book/room/details", data).done(function (responseData) {

	            var form = document.createElement("form");

	            form.method = "POST";
	            form.action = EQTR.Analytics.getLinkerUrl(responseData.url);

	            $.each(responseData.params, function (key, value) {
	                var element = document.createElement("input");
	                element.value = value;
	                element.name = key;
	                form.appendChild(element);
	            });
	            document.body.appendChild(form);

	            form.submit();
	        });
	    });

	};
    
	_.updateRoomDropDown = function(rooms, el, translation) {

        //!label ? 'Select' : label;

        var html = '';
		//var html = '<option value="">Time</option>';

        $.each(rooms, function(key, value) {

            html += '<option value="' + key + '">' + value + '</option>';

        });
		el.html(html).selectpicker('refresh');
		//.selectify('buildMenu');

    };

    module.roomBooking = _;

	return module;

})(window.EQTR || {}, jQuery);;
window.EQTR = (function(namespace, $, undefined) {

	var _ = {};

	var pagination = function() {
		var paginationContainer = $('.account-stays-pagination');

		if (paginationContainer.length == 0) { return false; }

		var stayGroups = $('.account-stay-item__group');

		$('body').on('click', '.pagination__button', function(e) {
			e.preventDefault();
			var trigger = $(this);

			if (trigger.hasClass('pagination__button--hidden')) { return false; }

			// positive is -> negative is <-
			var direction = trigger.hasClass('button-next') ? 1 : -1;

			var currentGroup = stayGroups.filter('.account-stay-item__group--current');

			var newCurrentGroupIdx = currentGroup.index() + direction;

			currentGroup.fadeOut(400, function() {
				$(this).removeClass('account-stay-item__group--current');
				stayGroups.eq(newCurrentGroupIdx).fadeIn(400).addClass('account-stay-item__group--current');

				var paginationButtons = $('.pagination__button').removeClass('pagination__button--hidden');

				switch (true) {
					case stayGroups.first().hasClass('account-stay-item__group--current'):
						$('.pagination__button.button-previous').addClass('pagination__button--hidden');
						break;
					case newCurrentGroupIdx > 0 && newCurrentGroupIdx < stayGroups.length - 1:
						$('.pagination__button').removeClass('pagination__button--hidden');
						break;
					case stayGroups.last().hasClass('account-stay-item__group--current'):
						$('.pagination__button.button-next').addClass('pagination__button--hidden');
						break;
				}
			});

			
		});
	};

	_.init = function() {


		$('.travel-login').each(function() {
			$('select.input', this).selectify({
				'width': '260'
			});

			$('input[type="checkbox"]', this).checkboxify();
		});

		pagination();
	};

	namespace.travel = _;

	return namespace;

})(window.EQTR || {}, jQuery);;
window.EQTR = (function (namespace, $, undefined) {

	var _ = {};

	_.init = function (context) {

	    context = context || document;

		$('.filter-container select.input',context).selectify({
		    'width': '200'
		});

		function setOfferData(el, skipHotelId) {
		    var $this = $(el),
                date = $this.data("bookdate"),
                nights = $this.data("minstay"),
                hotelcode = $this.data("hotelid");

		    date && $(".js-room-booking-date").val(date);
		    nights && $(".js-room-booking-nights").val(nights);
		    !skipHotelId && hotelcode && $(".js-room-booking-hotelcode").val(hotelcode);
		}

	    $(".js-room-booking-hotelcode").change(function () {
		    setOfferData($('.js-hotel-package-selector[data-hotelid=' + this.value + ']'));
		}).trigger("change");

		$('.js-hotel-package-selector').on('click', function (e) {
		    e.preventDefault();

		    setOfferData(this);

		    $("input.submit").click();
		});
	    
	};


    namespace.packages = _;

	return namespace;

})(window.EQTR || {}, jQuery);;
window.EQTR = (function (namespace, $, undefined) {

	var _ = {};

	_.init = function () {

	    $(".contact-page, .rf-account-page").each(function () {
	        $('select.input',this).selectify({
	            'width': '260'
	        });

	        $('input[type="checkbox"]',this).checkboxify();

	        // just in case there are 2 submit buttons
	        var formSubmittedBy;
	        $("form input[type='submit']",this).click(function() {
	            formSubmittedBy = $(this);
	            if (document.selection && document.selection.empty) {
	                document.selection.empty();
	            } else if (window.getSelection) {
	                var sel = window.getSelection();
	                sel.removeAllRanges();
	            }
	        });

	        $("form", this).submit(function() {
	            // get the button and turn it off
	            // create a overlay that prevents the user from clicking the button again
	            if (formSubmittedBy) {
	                var position = formSubmittedBy.position(),
	                    width = formSubmittedBy.outerWidth(),
	                    height = formSubmittedBy.outerHeight();

	                    $('<div style="background:blue;position:absolute;top:{0}px;left:{1}px;width:{2}px;height:{3}px;" />'.format(position.top, position.left, width, height)).css("opacity",0).insertAfter(formSubmittedBy).click(function () {
	                        if (document.selection && document.selection.empty) {
	                            document.selection.empty();
	                        } else if (window.getSelection) {
	                            var sel = window.getSelection();
	                            sel.removeAllRanges();
	                        }
	                    });
	            }
	        });

	    });

	};

    namespace.formPages = _;

	return namespace;

})(window.EQTR || {}, jQuery);;
window.EQTR = (function(module,undefined) {
    "use strict";

    var overlayColour,
        overlayText,
        guid,
        scrollText,
        closeStack = [];

    module.wordFrame = {
        prime: function (settings) {
            // check the sessionStorage to make sure that we haven't already seen this frame. Base it on the url. Also check to make that that we actually need to make the frame.

            if (!(settings && Modernizr.canvas && Modernizr.canvastext && window.sessionStorage && !window.sessionStorage[location.href + "overlay"])) return;
            overlayColour = settings.overlayColour;
            overlayText = settings.overlayText,
            guid = settings.guid;
            scrollText = settings.scrollText || "Scroll";
            $("html").addClass("hide-page-content");
            // take care of destroying the overlay when the page is destroyed
            $("#" + guid).on("destroyed", function () {
                $("#overlay-" + this.id).remove();
            });

        },
        init: function () {

            if (!overlayText) return false;
            // cancel the page-content fade in.
            //            EQTR.CancelFadeInContent();

            function removeFrame(duration, easing) {
                window.sessionStorage[location.href + "overlay"] = "true";

                overlay.animate({ top: "-100%" }, {
                    duration: duration || 1500,
                    easing: easing || "easeInOutCubic",
                    complete: function() {
                        $(this).remove();

                        for (var f in closeStack) {
                            $.isFunction(closeStack[f]) && closeStack[f]();
                        }

                        closeStack = [];
                    }
                });
            }


            function setFont() {
                fontSize = 50;
                // needs to be bold for some reason, otherwise the stroke makes jaggies. Julius sans one has no bold. Weird
                ctx.font = "bold " + fontSize + "px sans-serif";

                // can't get bigger than about 257 fontsize because chrome has issues. Keep it to 245 just to be safe 
                while ((ctx.measureText(text).width < width * 0.75) && fontSize < 245) {
                    fontSize += 5;
                    ctx.font = "bold " + fontSize + "px sans-serif";
                }

                // set the stroke width as a percentage of the font size
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
            }

            function drawWord() {
                width = canvas.width();
                height = canvas.height();
                canvas[0].width = width;
                canvas[0].height = height;
                centerX = width / 2;
                centerY = height / 2;

                setFont();

                // Draw background
                ctx.fillStyle = bgPattern;
                ctx.fillRect(0, 0, width, height);

                // Punch out the text with the bigger stroke
                ctx.globalCompositeOperation = 'destination-out';
                ctx.fillStyle = '#000';
                ctx.fillText(text, centerX + 1, centerY + 1);
                ctx.fillText(text, centerX - 1, centerY - 1);

                // put the shadows in
                ctx.globalCompositeOperation = 'source-over';

                // black top left
                ctx.fillStyle = "rgba(0,0,0,1)";
                ctx.fillText(text, centerX - 1, centerY - 1);

                // white bottom right
                ctx.fillStyle = "rgba(150, 150, 150, 1)";
                ctx.fillText(text, centerX + 1, centerY + 1);

                // punch (again) out the shadow
                ctx.globalCompositeOperation = 'destination-out';
                ctx.fillStyle = "#fff";
                ctx.fillText(text, centerX, centerY);

            }

            var overlay = $('<div class="hotel-overlay" id="overlay-' + guid + '" />').appendTo(".page-frame").css({ visibility: "hidden" }),
                canvas = $('<canvas />').appendTo(overlay),
                scrollDown = $('<a href="#" class="scroller-arrow-nav"><span>' + scrollText + '</span><span class="icon icon-scroll-down"></span></a>').appendTo(overlay),
                // Get a handle to our canvas
                ctx = canvas[0].getContext("2d"),
                width,
                height,
                fontSize,
                centerX,
                centerY,
                // normalise the text. Uppercase and single space between each letter
                text = $.trim(overlayText);
            
                text = EQTR.language.isRTL ? text : text.toUpperCase().split(/ */).join(" ");

            var imageObj = new Image(),
                bgPattern;


            imageObj.onload = function() {
                bgPattern = ctx.createPattern(fillPattern(overlayColour, imageObj), 'repeat');

                drawWord();
                // do a background cover on the canvas
                //canvas.backgroundCover({ ignoreIndex: true });

                overlay.css({ visibility: "visible", opacity: 0 }).animate({ opacity: 1 }, 100, function() {
                    EQTR.ShowPageContent(true);
                    overlayText = null;
                    overlayColour = null;
                    guid = null;
                    scrollText = null;
                    // set a resize event on the body. Not using EQTR resize because I think it happens twice
                    canvas.on("destroyed", function() {
                        EQTR.RemoveFromResizeQueue(drawWord);
                    });

                    drawWord.ignoreResizeOnInit = true;

                    EQTR.AddToResizeQueue(drawWord);
                });

            };

            imageObj.src = '/assets/images/hotel-overlay.jpg';


            // add the events for moving
            overlay.on("mousewheel", function(e, delta) {
                if (delta < 0) {
                    removeFrame();
                }
            }).on("drag", function(e, dd) {
                if (dd.deltaY < 0) {
                    overlay.css({ top: dd.deltaY });
                }
            }).on("dragend", function(e, dd) {
                removeFrame(800, "easeOutExpo");
            });

            scrollDown.click(function(e) {
                e.preventDefault();
                removeFrame();
            });


            return true;

        },
        onClose : function (func) {
            closeStack.push(func);
        }

    };

    return module;

    // helper functions

    function fillPattern(hex, img) {

        function blend(a, b) {
            return (a * b) / 255;
        }

        var canvas = document.createElement("canvas"),
            ctx = canvas.getContext("2d"), rgb = hexToRgb(hex);


        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);

        var imageData = ctx.getImageData(0, 0, img.width, img.height),
            pixels = imageData.data,
            r = rgb.r, g = rgb.g, b = rgb.b;

        // blend images
        for (var i = 0, il = pixels.length; i < il; i += 4) {
            pixels[i] = blend(pixels[i], r);
            pixels[i + 1] = blend(pixels[i + 1], g);
            pixels[i + 2] = blend(pixels[i + 2], b);
        }

        ctx.putImageData(imageData, 0, 0);

        return canvas;
    }

    function hexToRgb(hex) {
        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i, result;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; });
        result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null;
    }

})(window.EQTR || { });;
window.EQTR = (function(module, $) {
    "use strict";

    module.restaurantPageLayout = {
        init: function(context) {

            context = context || document;

            var pageContentPopup = $(".page-content-popup", context),
                popupClose,
                resizeFunc;

            if (pageContentPopup.length) {
//                pageContentPopup.filter(".popup-hidden").getNiceScroll().hide();

                // create the generic close button
                popupClose = $('<a href="#" class="popup-close">x</a>').hide()
                    .appendTo(".content-wrapper")
                    .click(function(e) {
                        e.preventDefault();
                        pageContentPopup.addClass("popup-in").getNiceScroll().hide();
                        $(this).hide();
                    });

                if (EQTR.detectDevice.isHandHeld()) {
                    //pageContentPopup.addClass("existing-page-content-popup").appendTo(".content-wrapper");
                }
            }

            if ($(".restaurant-landing-panel", context).length) {
                // get the panels to show the popups
                $(".restaurant-landing-panel[data-panel]").each(function() {
                    var $landingPanel = $(this),
                        panel;

                    // get the content inner content if there is a data-panel. Otherwise assume it is going to be getting the content via ajax
                    if (panel = $landingPanel.data("panel")) {
                        panel = $(".restaurant-" + panel);

                        // wrap the content-inner with an anchor
                        $landingPanel.click(function(e) {
                            e.preventDefault();
                            panel.removeClass("popup-in");

                            // settimeout rather than the transitionend. Too late in the day
                            setTimeout(function() {
                                panel.getNiceScroll().resize().show();
                            },400);
                            popupClose.show();
                        });

                    }

                });

                // slight hack for the fixing the height and width of the panels because chrome has issues with half pixels and transitions
                if (EQTR.detectDevice.isDesktop()) {

                    var headingPanel = $(".restaurant-heading-panel"),
                        headingPanelImage = $("img", headingPanel);

                    resizeFunc = EQTR.AddToResizeQueue(function() {
                        $(".restaurant-landing-panel", context).each(function() {
                            //$(this).width("").width($(this).width());
                            //$(this).height("").height($(this).height());
                        });
                        
                        // check the heading panel to make the content fit if it is too big
                        // reset first 
                        headingPanel.removeClass("small-height").each(function() {
                        //    EQTR.ForcePageLayout();
                            headingPanelImage.length && headingPanelImage.css({ maxHeight: "" });
                            if (this.scrollHeight > this.offsetHeight) {
                                $(this).addClass("small-height");
                                var overflow = this.scrollHeight - this.offsetHeight;
                                //alert(overflow);
                                // find out how much space there is to remove. It should be the amount that the overflow is less the height of the container 

                                if (headingPanelImage.length) {
                                    var newSize = Math.max(headingPanelImage.height() - overflow, 20);

                                    headingPanelImage.css({ maxHeight: newSize });
                                }
                            }
                        });

                    }, 1);
                }

                $(context == document ? ".restaurant-room.page-content" : context).on("destroyed", function() {
                    resizeFunc && EQTR.RemoveFromResizeQueue(resizeFunc);
                    pageContentPopup.length && pageContentPopup.remove();
                    popupClose && popupClose.remove();
                });
            }
        }
    };

    return module;
})(window.EQTR || { }, window.jQuery);;
window.EQTR = (function (namespace, $, undefined) {
    var _ = {};

    _.init = function () {

        $('.newsletter-signup').each(function() {
            $('select.input', this).selectify({
                'width': '260'
            });

            // the check list isn't really a list and ie8 is getting confused, so going to wrap the elements first
            // mvc checkbox input seems to have closing input tag?
            // bit of a hack, but time is tight
            var cb = $('input[type="checkbox"]', this).each(function() {
                var wrapper = $('<span />').insertBefore($(this));
                
                // next child nor working for ie8 either, so finding the label with the for element
                wrapper.append( $("label[for='"+this.id+"']")).prepend($(this));
            });

            cb.checkboxify();

        });


        /*if ($this.parents('.compact').length) {
            $this.next('label[for="' + $this.attr('id') + '"]').addBack().wrapAll('<div class="input-container" />');
            // 0-based index.
            var evenInputContainers = $this.parents('.compact').find('.input-container:odd')
            evenInputContainers.addClass('last');

            evenInputContainers.each(function () {
                console.log($(this).add($(this).prev('.input-container')));
                $(this).add($(this).prev('.input-container')).wrapAll('<div class="input-row" />');
            });
        }*/


    };

    namespace.newsletter = _;

    return namespace;


})(window.EQTR || {}, jQuery);;
window.EQTR.scrollIndicator = (function (namespace, $, undefined) {

    var _ = namespace;

	_.init = function (context) {

        //context = context == document ? $(".page-content", context) : $(context)

	    //if (!context.is(".restaurant-booking")) return;


	};

    // checks if an element has a scrollbar or not.
	_.hasScrollBar = function (el) {

	    if(!el.length) {
	        return false;
	    }

        return el[0].scrollHeight > el.height();
	};

    // displays the scroll indictor helper.
	_.showScrollIndicator = function (el, position, message) {

	    if(!el.length) {
            return false;
	    }

	    position = position || 'right center';
	    message = message || 'scroll for more';

	    var html = $('<div class="scroll-indictor" style="position: fixed; z-index: 1000;"><span>' + message + '</span></div>'),
            htmlVisible = true;

	    $('.page-content').append(html);

	    var indicatorPosition = position,
            elOffset,
            elHeight = el.outerHeight(),
            elWidth = el.outerWidth(),
            indictorXY,
            htmlHeight = html.outerHeight(true),
	        htmlWidth = html.outerWidth(true),
            cssPositionClass = ['center','center'];

	    el.on('scroll', function () {

	        if (!htmlVisible) {
	            return false;
	        }

	        html.fadeOut(400, function () {
	            htmlVisible = false;
	        });
	    });

	    $(window).smartresize(function () {

	        if (!htmlVisible) {
	            return false;
	        }

	        elHeight = el.outerHeight();
	        elWidth = el.outerWidth();
	        htmlHeight = html.outerHeight(true);
	        htmlWidth = html.outerWidth(true);


	        if (EQTR.scrollIndicator.hasScrollBar(el)) {
	            positionScrollIndicator();
	            html.show();
	        }

	    });
        
	    setTimeout(function () {

	        positionScrollIndicator();

	        if (EQTR.scrollIndicator.hasScrollBar(el)) {
	            html.fadeIn(600);
	        }

	    }, 1000);

	    function positionScrollIndicator() {

	        elOffset = el.offset();

	        indictorXY = [(elOffset.top + (elHeight / 2) - (htmlHeight / 2)), (elOffset.left + (elWidth / 2) - (htmlWidth / 2))];

	        if (indicatorPosition.indexOf('left') > -1) {
	            indictorXY[0] = elOffset.left - htmlWidth;
	            cssPositionClass[0] = 'left';
	        }
	        if (indicatorPosition.indexOf('right') > -1) {
	            indictorXY[0] = elOffset.left + elWidth;
	            cssPositionClass[0] = 'right';
	        }

	        if (indicatorPosition.indexOf('top') > -1) {
	            indictorXY[1] = elOffset.top; // - htmlHeight;
	            cssPositionClass[1] = 'top';
	        }

	        if (indicatorPosition.indexOf('bottom') > -1) {
	            indictorXY[1] = elOffset.top; // + elHeight;
	            cssPositionClass[1] = 'bottom';
	        }

	        html.addClass(cssPositionClass.join('-')).css({
	            'left': indictorXY[0] + 'px',
	            'top': indictorXY[1] + 'px'
	        });
	    }
	    
	}

	return _;

})(window.EQTR.scrollIndicator || {}, jQuery);;
function initMap(mapInfo) {
	        
    EQTR.loadGoogleMapApi(function() {

        /** constructor */
        function MarkerIcon(options) {
            var _this = this;

            // Initialize all properties.
            _this.latLng_ = options.position;
            _this.icon_ = options.icon;
            _this.image_ = options.image;
            _this.map_ = options.map;
            _this.markerSrc_ = options.markerSrc;
            _this.markerClass_ = options.markerType ? options.markerType + "-marker" : "";

            // Define a property to hold the image's div. We'll
            // actually create this div upon receipt of the onAdd()
            // method so we'll leave it null for now.
            _this.div_ = null;

            // load the icon then set on the map
            var _iconBG = new Image();
	        
            _iconBG.onload = function() {
                // Explicitly call setMap on this overlay.
                _this.width_ = _iconBG.width;
                _this.height_ = _iconBG.height;
                _this.backgroundImage_ = _iconBG.src;
                _this.setMap(_this.map_);
	            
            };

            _iconBG.src = _this.markerSrc_;

        }

        MarkerIcon.prototype = new google.maps.OverlayView();

        /**
         * onAdd is called when the map's panes are ready and the overlay has been
         * added to the map.
         */
        MarkerIcon.prototype.onAdd = function() {
            var me = this;
            var div = document.createElement('div');
            div.style.position = 'absolute';
            if (me.image_) {
                div.innerHTML = '<div class="google-hotel-icon"><img alt="" src="' + me.image_ + '" /></div>';
            } else {
                div.innerHTML = '<div class="google-hotel-icon"><span class="icon ' + me.icon_ + '"></span></div>';
            }

            if( me.markerClass_ ) {
                div.className = me.markerClass_;
            }

            // Create the img element and attach it to the div.

            me.div_ = div;

            //console.info(me.backgroundImage_);

            div.style.width = me.width_ + 'px';
            div.style.height = me.height_ + 'px';
            div.style.backgroundImage = 'url("' + me.backgroundImage_ + '")';
            div.style.zIndex = 0;
            //div.style.cursor = "pointer";

            // Add the element to the "overlayLayer" pane.
            var panes = me.getPanes();

            panes.overlayMouseTarget.appendChild(div);

            google.maps.event.addDomListener(div, 'click', function() {
                google.maps.event.trigger(me, 'click');
            });

        };

        MarkerIcon.prototype.draw = function() {

            // retrieve the projection from the overlay.
            var overlayProjection = this.getProjection();

            var latLng = overlayProjection.fromLatLngToDivPixel(this.latLng_);

            // Resize the image's div to fit the indicated dimensions.
            var div = this.div_;

            div.style.left = (latLng.x - (this.width_/2) ) + 'px';
            div.style.top = (latLng.y - this.height_) + 'px';
        };

        // The onRemove() method will be called automatically from the API if
        // we ever set the overlay's map property to 'null'.
        MarkerIcon.prototype.onRemove = function() {
            this.div_.style.background = "none";
            this.div_.parentNode.removeChild(this.div_);
            this.div_ = null;
        };



        var point = new google.maps.LatLng(mapInfo.Lat, mapInfo.Lng );

        styles = {
            paledawn:[{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]},{"featureType":"landscape","stylers":[{"color":"#f2e5d4"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"administrative","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"road"},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{},{"featureType":"road","stylers":[{"lightness":20}]}],
            subtlegray:[{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}],
            greyscale:[{"featureType":"all","stylers":[{"saturation":-100},{"gamma":0.7}]},{
                featureType: 'poi.business',
                elementType: 'all',
                stylers: [
                    { hue: '#ffffff' },
                    { saturation: -100 },
                    { lightness: 100 },
                    { visibility: 'off' }
                ]
            }]

        };

        var isDraggable = $(document).width() > 480 ? true : false; // If document (your website) is wider than 480px, isDraggable = true, else isDraggable = false

        var myMapOptions = {
            zoom: mapInfo.Zoom,
            center: point,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            styles: styles.greyscale,
            draggable: true,
            scrollwheel: false
        },
            thisMap = document.getElementById(mapInfo.Map || "map"),
            parentContent = $(thisMap).closest(".page-content");
	            
        var map = new google.maps.Map(thisMap, myMapOptions);

        var markerOptions = {
            icon: mapInfo.Logo,
            image: mapInfo.Image,
            map: map,
            position: point,
            markerType: mapInfo.MarkerType,
            markerSrc: mapInfo.MarkerType == "restaurant" ? "/assets/images/map/restaurantIcon.png" : "/assets/images/map/roccoHotelIcon.png"
        };

        var icon = new MarkerIcon(markerOptions);

        google.maps.event.addListener(icon, "click", function() {
        });

        var infowindow = new google.maps.InfoWindow();

        function setInfowindow(favouriteTitle, marker) {
            infowindow.setContent('<div class="google-maps-infowindow">' + favouriteTitle + '</div>');
            infowindow.open(map, marker);
        }

        // favourites markers
        $(".favourite",parentContent).each(function() {
            var coords = $(this).data("geocoords"),
                $favourite = $(this),
                $favouriteParent = $(this).scrollParent();

            if(coords && coords.match(/(.*);(.*)/)) {

                var markerPos = new google.maps.LatLng( RegExp.$1, RegExp.$2 );
                var favouriteTitle = $("h3",this).text();

                var marker = new google.maps.Marker({
                    position: markerPos,
                    map: map,
                    icon: "/assets/images/map/hotelFeatureIcon.png"
                });
	            
                $favourite.addClass("clickable");

                google.maps.event.addListener(marker, "click", function() {

                    setInfowindow(favouriteTitle, marker);

                    $favouriteParent.stop().animate({ scrollTop: $favouriteParent.scrollTop() + $favourite.offset().top });
                });

                $favourite.click(function () {
                    var bounds = new google.maps.LatLngBounds();
                    bounds.extend(point);
                    bounds.extend(marker.getPosition());
                    map.fitBounds(bounds);
                    setInfowindow(favouriteTitle, marker);
                });

            }
        });

    });
};
// generic plugin starter

; (function ($, window, document, undefined) {

    // Create the defaults once
    var pluginName = "tableScroller",
        defaults = {
        };

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;

        this.$element = $(element);

        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    // plugin public methods
    Plugin.prototype = {

        init: function () {
            
            // copy the table
            var $tableClone = this.$element.clone(),
                // rip out the first row or head and stick in a table
                $tableHead = $(this.element.cloneNode()).addClass("table-scroller__header"),$tableHeadFixed,
                $tableHeadRow = $("thead",$tableClone);

            if( !$tableHeadRow.length ) {
                $tableHeadRow = $("tr:first",$tableClone);
            }

            $tableHead.append($tableHeadRow.clone());
            $tableHeadFixed = $tableHead.clone();

            var $wrapper = $('<div class="table-scroller"><div class="table-scroller__scrollable"/><div class="table-scroller__fixed"/></div>'),
                $scrollable = $(".table-scroller__scrollable",$wrapper),
                $fixed = $(".table-scroller__fixed",$wrapper);

            $wrapper.insertBefore(this.$element);

            $scrollable.append(this.$element, $tableHead);

            $fixed.append($tableClone,$tableHeadFixed);

            // need to set the width if the fixed div because the row is still visible, even though the cells aren't
            // + 1 for the border on the right. Don't know the best way to calculate this. Maybe add as options to pass in?
            $fixed.width($tableHead.find("tr :first").outerWidth()+1);


            var scrollTopStart;
            $(window).on("scrollEnd",function() {
                
                var scrollTop = $(window).scrollTop(),
                    // this shouldn't change during the scroll. Put it in scroll start
                    offsetTop = $wrapper.offset().top,
                    diff = Math.max(0,scrollTop - offsetTop + 35);

                $tableHead[0].style.top = diff + "px";
                $tableHeadFixed[0].style.top = diff + "px";

                $wrapper.removeClass("hidden");

                scrollTopStart = scrollTop;
            }).on("touchmove",function() {
                var scrollTop = $(window).scrollTop();

                if( scrollTop != scrollTopStart ) {
                    $wrapper.addClass("hidden");
                }

            }).on("touchstart",function() {
                scrollTopStart = $(window).scrollTop();
            });

        }

    };
    
    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (method) {
        
        var args = arguments;
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin(this, method));
            } else {
                if (Plugin.prototype[method]) {
                    var plugin = $(this).data("plugin_" + pluginName);
                    plugin[method].apply(plugin, Array.prototype.slice.call(args, 1))
                } else {
                    $.error('Method ' + method + ' does not exist on ' + pluginName);
                }
            }
        });
    };

})(jQuery, window, document);


    /*** scroll start/end events ***/
;(function($) {
    var scrolltimerId;

    $('.page-content').scroll(function () {
        if (!scrolltimerId) {
            $('.page-content').trigger("scrollStart");
        }

        clearTimeout(scrolltimerId);
        
        scrolltimerId = setTimeout(function () {
            
            $('.page-content').trigger("scrollEnd");
            scrolltimerId = null;
        }, 300);

    });
})(jQuery);;
window.EQTR = (function (namespace, $, undefined) {
    var _ = {};

    _.init = function (context) {

        context = context == document ? $(".page-content", context) : $(context)

        if (context.data("hidesearch") == "True") {
            $('.js-search-button, .js-search-divider').hide();
        } else {
            $('.js-search-button, .js-search-divider').show();
        }

        $('.js-search-button').each(function () {

            var currentPageNodeId = context.data('nodeid');
            var searchUrl = $(this).data('link');

            var newUrl = searchUrl + "?pageId=" + currentPageNodeId;

            $(this).attr('href', newUrl);
        });
    };

    namespace.searchButton = _;

    return namespace;

})(window.EQTR || {}, jQuery);;
/*!
 * Bootstrap-select v1.12.4 (http://silviomoreto.github.io/bootstrap-select)
 *
 * Copyright 2013-2017 bootstrap-select
 * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
 */
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof module&&module.exports?module.exports=b(require("jquery")):b(a.jQuery)}(this,function(a){!function(a){"use strict";function b(b){var c=[{re:/[\xC0-\xC6]/g,ch:"A"},{re:/[\xE0-\xE6]/g,ch:"a"},{re:/[\xC8-\xCB]/g,ch:"E"},{re:/[\xE8-\xEB]/g,ch:"e"},{re:/[\xCC-\xCF]/g,ch:"I"},{re:/[\xEC-\xEF]/g,ch:"i"},{re:/[\xD2-\xD6]/g,ch:"O"},{re:/[\xF2-\xF6]/g,ch:"o"},{re:/[\xD9-\xDC]/g,ch:"U"},{re:/[\xF9-\xFC]/g,ch:"u"},{re:/[\xC7-\xE7]/g,ch:"c"},{re:/[\xD1]/g,ch:"N"},{re:/[\xF1]/g,ch:"n"}];return a.each(c,function(){b=b?b.replace(this.re,this.ch):""}),b}function c(b){var c=arguments,d=b;[].shift.apply(c);var e,f=this.each(function(){var b=a(this);if(b.is("select")){var f=b.data("selectpicker"),g="object"==typeof d&&d;if(f){if(g)for(var h in g)g.hasOwnProperty(h)&&(f.options[h]=g[h])}else{var i=a.extend({},l.DEFAULTS,a.fn.selectpicker.defaults||{},b.data(),g);i.template=a.extend({},l.DEFAULTS.template,a.fn.selectpicker.defaults?a.fn.selectpicker.defaults.template:{},b.data().template,g.template),b.data("selectpicker",f=new l(this,i))}"string"==typeof d&&(e=f[d]instanceof Function?f[d].apply(f,c):f.options[d])}});return"undefined"!=typeof e?e:f}String.prototype.includes||!function(){var a={}.toString,b=function(){try{var a={},b=Object.defineProperty,c=b(a,a,a)&&b}catch(a){}return c}(),c="".indexOf,d=function(b){if(null==this)throw new TypeError;var d=String(this);if(b&&"[object RegExp]"==a.call(b))throw new TypeError;var e=d.length,f=String(b),g=f.length,h=arguments.length>1?arguments[1]:void 0,i=h?Number(h):0;i!=i&&(i=0);var j=Math.min(Math.max(i,0),e);return!(g+j>e)&&c.call(d,f,i)!=-1};b?b(String.prototype,"includes",{value:d,configurable:!0,writable:!0}):String.prototype.includes=d}(),String.prototype.startsWith||!function(){var a=function(){try{var a={},b=Object.defineProperty,c=b(a,a,a)&&b}catch(a){}return c}(),b={}.toString,c=function(a){if(null==this)throw new TypeError;var c=String(this);if(a&&"[object RegExp]"==b.call(a))throw new TypeError;var d=c.length,e=String(a),f=e.length,g=arguments.length>1?arguments[1]:void 0,h=g?Number(g):0;h!=h&&(h=0);var i=Math.min(Math.max(h,0),d);if(f+i>d)return!1;for(var j=-1;++j<f;)if(c.charCodeAt(i+j)!=e.charCodeAt(j))return!1;return!0};a?a(String.prototype,"startsWith",{value:c,configurable:!0,writable:!0}):String.prototype.startsWith=c}(),Object.keys||(Object.keys=function(a,b,c){c=[];for(b in a)c.hasOwnProperty.call(a,b)&&c.push(b);return c});var d={useDefault:!1,_set:a.valHooks.select.set};a.valHooks.select.set=function(b,c){return c&&!d.useDefault&&a(b).data("selected",!0),d._set.apply(this,arguments)};var e=null,f=function(){try{return new Event("change"),!0}catch(a){return!1}}();a.fn.triggerNative=function(a){var b,c=this[0];c.dispatchEvent?(f?b=new Event(a,{bubbles:!0}):(b=document.createEvent("Event"),b.initEvent(a,!0,!1)),c.dispatchEvent(b)):c.fireEvent?(b=document.createEventObject(),b.eventType=a,c.fireEvent("on"+a,b)):this.trigger(a)},a.expr.pseudos.icontains=function(b,c,d){var e=a(b).find("a"),f=(e.data("tokens")||e.text()).toString().toUpperCase();return f.includes(d[3].toUpperCase())},a.expr.pseudos.ibegins=function(b,c,d){var e=a(b).find("a"),f=(e.data("tokens")||e.text()).toString().toUpperCase();return f.startsWith(d[3].toUpperCase())},a.expr.pseudos.aicontains=function(b,c,d){var e=a(b).find("a"),f=(e.data("tokens")||e.data("normalizedText")||e.text()).toString().toUpperCase();return f.includes(d[3].toUpperCase())},a.expr.pseudos.aibegins=function(b,c,d){var e=a(b).find("a"),f=(e.data("tokens")||e.data("normalizedText")||e.text()).toString().toUpperCase();return f.startsWith(d[3].toUpperCase())};var g={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},h={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#x27;":"'","&#x60;":"`"},i=function(a){var b=function(b){return a[b]},c="(?:"+Object.keys(a).join("|")+")",d=RegExp(c),e=RegExp(c,"g");return function(a){return a=null==a?"":""+a,d.test(a)?a.replace(e,b):a}},j=i(g),k=i(h),l=function(b,c){d.useDefault||(a.valHooks.select.set=d._set,d.useDefault=!0),this.$element=a(b),this.$newElement=null,this.$button=null,this.$menu=null,this.$lis=null,this.options=c,null===this.options.title&&(this.options.title=this.$element.attr("title"));var e=this.options.windowPadding;"number"==typeof e&&(this.options.windowPadding=[e,e,e,e]),this.val=l.prototype.val,this.render=l.prototype.render,this.refresh=l.prototype.refresh,this.setStyle=l.prototype.setStyle,this.selectAll=l.prototype.selectAll,this.deselectAll=l.prototype.deselectAll,this.destroy=l.prototype.destroy,this.remove=l.prototype.remove,this.show=l.prototype.show,this.hide=l.prototype.hide,this.init()};l.VERSION="1.12.4",l.DEFAULTS={noneSelectedText:"Nothing selected",noneResultsText:"No results matched {0}",countSelectedText:function(a,b){return 1==a?"{0} item selected":"{0} items selected"},maxOptionsText:function(a,b){return[1==a?"Limit reached ({n} item max)":"Limit reached ({n} items max)",1==b?"Group limit reached ({n} item max)":"Group limit reached ({n} items max)"]},selectAllText:"Select All",deselectAllText:"Deselect All",doneButton:!1,doneButtonText:"Close",multipleSeparator:", ",styleBase:"btn",style:"btn-default",size:"auto",title:null,selectedTextFormat:"values",width:!1,container:!1,hideDisabled:!1,showSubtext:!1,showIcon:!0,showContent:!0,dropupAuto:!0,header:!1,liveSearch:!1,liveSearchPlaceholder:null,liveSearchNormalize:!1,liveSearchStyle:"contains",actionsBox:!1,iconBase:"glyphicon",tickIcon:"glyphicon-ok",showTick:!1,template:{caret:'<span class="caret"></span>'},maxOptions:!1,mobile:!1,selectOnTab:!1,dropdownAlignRight:!1,windowPadding:0},l.prototype={constructor:l,init:function(){var b=this,c=this.$element.attr("id");this.$element.addClass("bs-select-hidden"),this.liObj={},this.multiple=this.$element.prop("multiple"),this.autofocus=this.$element.prop("autofocus"),this.$newElement=this.createView(),this.$element.after(this.$newElement).appendTo(this.$newElement),this.$button=this.$newElement.children("button"),this.$menu=this.$newElement.children(".dropdown-menu"),this.$menuInner=this.$menu.children(".inner"),this.$searchbox=this.$menu.find("input"),this.$element.removeClass("bs-select-hidden"),this.options.dropdownAlignRight===!0&&this.$menu.addClass("dropdown-menu-right"),"undefined"!=typeof c&&(this.$button.attr("data-id",c),a('label[for="'+c+'"]').click(function(a){a.preventDefault(),b.$button.focus()})),this.checkDisabled(),this.clickListener(),this.options.liveSearch&&this.liveSearchListener(),this.render(),this.setStyle(),this.setWidth(),this.options.container&&this.selectPosition(),this.$menu.data("this",this),this.$newElement.data("this",this),this.options.mobile&&this.mobile(),this.$newElement.on({"hide.bs.dropdown":function(a){b.$menuInner.attr("aria-expanded",!1),b.$element.trigger("hide.bs.select",a)},"hidden.bs.dropdown":function(a){b.$element.trigger("hidden.bs.select",a)},"show.bs.dropdown":function(a){b.$menuInner.attr("aria-expanded",!0),b.$element.trigger("show.bs.select",a)},"shown.bs.dropdown":function(a){b.$element.trigger("shown.bs.select",a)}}),b.$element[0].hasAttribute("required")&&this.$element.on("invalid",function(){b.$button.addClass("bs-invalid"),b.$element.on({"focus.bs.select":function(){b.$button.focus(),b.$element.off("focus.bs.select")},"shown.bs.select":function(){b.$element.val(b.$element.val()).off("shown.bs.select")},"rendered.bs.select":function(){this.validity.valid&&b.$button.removeClass("bs-invalid"),b.$element.off("rendered.bs.select")}}),b.$button.on("blur.bs.select",function(){b.$element.focus().blur(),b.$button.off("blur.bs.select")})}),setTimeout(function(){b.$element.trigger("loaded.bs.select")})},createDropdown:function(){var b=this.multiple||this.options.showTick?" show-tick":"",c=this.$element.parent().hasClass("input-group")?" input-group-btn":"",d=this.autofocus?" autofocus":"",e=this.options.header?'<div class="popover-title"><button type="button" class="close" aria-hidden="true">&times;</button>'+this.options.header+"</div>":"",f=this.options.liveSearch?'<div class="bs-searchbox"><input type="text" class="form-control" autocomplete="off"'+(null===this.options.liveSearchPlaceholder?"":' placeholder="'+j(this.options.liveSearchPlaceholder)+'"')+' role="textbox" aria-label="Search"></div>':"",g=this.multiple&&this.options.actionsBox?'<div class="bs-actionsbox"><div class="btn-group btn-group-sm btn-block"><button type="button" class="actions-btn bs-select-all btn btn-default">'+this.options.selectAllText+'</button><button type="button" class="actions-btn bs-deselect-all btn btn-default">'+this.options.deselectAllText+"</button></div></div>":"",h=this.multiple&&this.options.doneButton?'<div class="bs-donebutton"><div class="btn-group btn-block"><button type="button" class="btn btn-sm btn-default">'+this.options.doneButtonText+"</button></div></div>":"",i='<div class="btn-group bootstrap-select'+b+c+'"><button type="button" class="'+this.options.styleBase+' dropdown-toggle" data-toggle="dropdown"'+d+' role="button"><span class="filter-option pull-left"></span>&nbsp;<span class="bs-caret">'+this.options.template.caret+'</span></button><div class="dropdown-menu open" role="combobox">'+e+f+g+'<ul class="dropdown-menu inner" role="listbox" aria-expanded="false"></ul>'+h+"</div></div>";return a(i)},createView:function(){var a=this.createDropdown(),b=this.createLi();return a.find("ul")[0].innerHTML=b,a},reloadLi:function(){var a=this.createLi();this.$menuInner[0].innerHTML=a},createLi:function(){var c=this,d=[],e=0,f=document.createElement("option"),g=-1,h=function(a,b,c,d){return"<li"+("undefined"!=typeof c&&""!==c?' class="'+c+'"':"")+("undefined"!=typeof b&&null!==b?' data-original-index="'+b+'"':"")+("undefined"!=typeof d&&null!==d?'data-optgroup="'+d+'"':"")+">"+a+"</li>"},i=function(d,e,f,g){return'<a tabindex="0"'+("undefined"!=typeof e?' class="'+e+'"':"")+(f?' style="'+f+'"':"")+(c.options.liveSearchNormalize?' data-normalized-text="'+b(j(a(d).html()))+'"':"")+("undefined"!=typeof g||null!==g?' data-tokens="'+g+'"':"")+' role="option">'+d+'<span class="'+c.options.iconBase+" "+c.options.tickIcon+' check-mark"></span></a>'};if(this.options.title&&!this.multiple&&(g--,!this.$element.find(".bs-title-option").length)){var k=this.$element[0];f.className="bs-title-option",f.innerHTML=this.options.title,f.value="",k.insertBefore(f,k.firstChild);var l=a(k.options[k.selectedIndex]);void 0===l.attr("selected")&&void 0===this.$element.data("selected")&&(f.selected=!0)}var m=this.$element.find("option");return m.each(function(b){var f=a(this);if(g++,!f.hasClass("bs-title-option")){var k,l=this.className||"",n=j(this.style.cssText),o=f.data("content")?f.data("content"):f.html(),p=f.data("tokens")?f.data("tokens"):null,q="undefined"!=typeof f.data("subtext")?'<small class="text-muted">'+f.data("subtext")+"</small>":"",r="undefined"!=typeof f.data("icon")?'<span class="'+c.options.iconBase+" "+f.data("icon")+'"></span> ':"",s=f.parent(),t="OPTGROUP"===s[0].tagName,u=t&&s[0].disabled,v=this.disabled||u;if(""!==r&&v&&(r="<span>"+r+"</span>"),c.options.hideDisabled&&(v&&!t||u))return k=f.data("prevHiddenIndex"),f.next().data("prevHiddenIndex",void 0!==k?k:b),void g--;if(f.data("content")||(o=r+'<span class="text">'+o+q+"</span>"),t&&f.data("divider")!==!0){if(c.options.hideDisabled&&v){if(void 0===s.data("allOptionsDisabled")){var w=s.children();s.data("allOptionsDisabled",w.filter(":disabled").length===w.length)}if(s.data("allOptionsDisabled"))return void g--}var x=" "+s[0].className||"";if(0===f.index()){e+=1;var y=s[0].label,z="undefined"!=typeof s.data("subtext")?'<small class="text-muted">'+s.data("subtext")+"</small>":"",A=s.data("icon")?'<span class="'+c.options.iconBase+" "+s.data("icon")+'"></span> ':"";y=A+'<span class="text">'+j(y)+z+"</span>",0!==b&&d.length>0&&(g++,d.push(h("",null,"divider",e+"div"))),g++,d.push(h(y,null,"dropdown-header"+x,e))}if(c.options.hideDisabled&&v)return void g--;d.push(h(i(o,"opt "+l+x,n,p),b,"",e))}else if(f.data("divider")===!0)d.push(h("",b,"divider"));else if(f.data("hidden")===!0)k=f.data("prevHiddenIndex"),f.next().data("prevHiddenIndex",void 0!==k?k:b),d.push(h(i(o,l,n,p),b,"hidden is-hidden"));else{var B=this.previousElementSibling&&"OPTGROUP"===this.previousElementSibling.tagName;if(!B&&c.options.hideDisabled&&(k=f.data("prevHiddenIndex"),void 0!==k)){var C=m.eq(k)[0].previousElementSibling;C&&"OPTGROUP"===C.tagName&&!C.disabled&&(B=!0)}B&&(g++,d.push(h("",null,"divider",e+"div"))),d.push(h(i(o,l,n,p),b))}c.liObj[b]=g}}),this.multiple||0!==this.$element.find("option:selected").length||this.options.title||this.$element.find("option").eq(0).prop("selected",!0).attr("selected","selected"),d.join("")},findLis:function(){return null==this.$lis&&(this.$lis=this.$menu.find("li")),this.$lis},render:function(b){var c,d=this,e=this.$element.find("option");b!==!1&&e.each(function(a){var b=d.findLis().eq(d.liObj[a]);d.setDisabled(a,this.disabled||"OPTGROUP"===this.parentNode.tagName&&this.parentNode.disabled,b),d.setSelected(a,this.selected,b)}),this.togglePlaceholder(),this.tabIndex();var f=e.map(function(){if(this.selected){if(d.options.hideDisabled&&(this.disabled||"OPTGROUP"===this.parentNode.tagName&&this.parentNode.disabled))return;var b,c=a(this),e=c.data("icon")&&d.options.showIcon?'<i class="'+d.options.iconBase+" "+c.data("icon")+'"></i> ':"";return b=d.options.showSubtext&&c.data("subtext")&&!d.multiple?' <small class="text-muted">'+c.data("subtext")+"</small>":"","undefined"!=typeof c.attr("title")?c.attr("title"):c.data("content")&&d.options.showContent?c.data("content").toString():e+c.html()+b}}).toArray(),g=this.multiple?f.join(this.options.multipleSeparator):f[0];if(this.multiple&&this.options.selectedTextFormat.indexOf("count")>-1){var h=this.options.selectedTextFormat.split(">");if(h.length>1&&f.length>h[1]||1==h.length&&f.length>=2){c=this.options.hideDisabled?", [disabled]":"";var i=e.not('[data-divider="true"], [data-hidden="true"]'+c).length,j="function"==typeof this.options.countSelectedText?this.options.countSelectedText(f.length,i):this.options.countSelectedText;g=j.replace("{0}",f.length.toString()).replace("{1}",i.toString())}}void 0==this.options.title&&(this.options.title=this.$element.attr("title")),"static"==this.options.selectedTextFormat&&(g=this.options.title),g||(g="undefined"!=typeof this.options.title?this.options.title:this.options.noneSelectedText),this.$button.attr("title",k(a.trim(g.replace(/<[^>]*>?/g,"")))),this.$button.children(".filter-option").html(g),this.$element.trigger("rendered.bs.select")},setStyle:function(a,b){this.$element.attr("class")&&this.$newElement.addClass(this.$element.attr("class").replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi,""));var c=a?a:this.options.style;"add"==b?this.$button.addClass(c):"remove"==b?this.$button.removeClass(c):(this.$button.removeClass(this.options.style),this.$button.addClass(c))},liHeight:function(b){if(b||this.options.size!==!1&&!this.sizeInfo){var c=document.createElement("div"),d=document.createElement("div"),e=document.createElement("ul"),f=document.createElement("li"),g=document.createElement("li"),h=document.createElement("a"),i=document.createElement("span"),j=this.options.header&&this.$menu.find(".popover-title").length>0?this.$menu.find(".popover-title")[0].cloneNode(!0):null,k=this.options.liveSearch?document.createElement("div"):null,l=this.options.actionsBox&&this.multiple&&this.$menu.find(".bs-actionsbox").length>0?this.$menu.find(".bs-actionsbox")[0].cloneNode(!0):null,m=this.options.doneButton&&this.multiple&&this.$menu.find(".bs-donebutton").length>0?this.$menu.find(".bs-donebutton")[0].cloneNode(!0):null;if(i.className="text",c.className=this.$menu[0].parentNode.className+" open",d.className="dropdown-menu open",e.className="dropdown-menu inner",f.className="divider",i.appendChild(document.createTextNode("Inner text")),h.appendChild(i),g.appendChild(h),e.appendChild(g),e.appendChild(f),j&&d.appendChild(j),k){var n=document.createElement("input");k.className="bs-searchbox",n.className="form-control",k.appendChild(n),d.appendChild(k)}l&&d.appendChild(l),d.appendChild(e),m&&d.appendChild(m),c.appendChild(d),document.body.appendChild(c);var o=h.offsetHeight,p=j?j.offsetHeight:0,q=k?k.offsetHeight:0,r=l?l.offsetHeight:0,s=m?m.offsetHeight:0,t=a(f).outerHeight(!0),u="function"==typeof getComputedStyle&&getComputedStyle(d),v=u?null:a(d),w={vert:parseInt(u?u.paddingTop:v.css("paddingTop"))+parseInt(u?u.paddingBottom:v.css("paddingBottom"))+parseInt(u?u.borderTopWidth:v.css("borderTopWidth"))+parseInt(u?u.borderBottomWidth:v.css("borderBottomWidth")),horiz:parseInt(u?u.paddingLeft:v.css("paddingLeft"))+parseInt(u?u.paddingRight:v.css("paddingRight"))+parseInt(u?u.borderLeftWidth:v.css("borderLeftWidth"))+parseInt(u?u.borderRightWidth:v.css("borderRightWidth"))},x={vert:w.vert+parseInt(u?u.marginTop:v.css("marginTop"))+parseInt(u?u.marginBottom:v.css("marginBottom"))+2,horiz:w.horiz+parseInt(u?u.marginLeft:v.css("marginLeft"))+parseInt(u?u.marginRight:v.css("marginRight"))+2};document.body.removeChild(c),this.sizeInfo={liHeight:o,headerHeight:p,searchHeight:q,actionsHeight:r,doneButtonHeight:s,dividerHeight:t,menuPadding:w,menuExtras:x}}},setSize:function(){if(this.findLis(),this.liHeight(),this.options.header&&this.$menu.css("padding-top",0),this.options.size!==!1){var b,c,d,e,f,g,h,i,j=this,k=this.$menu,l=this.$menuInner,m=a(window),n=this.$newElement[0].offsetHeight,o=this.$newElement[0].offsetWidth,p=this.sizeInfo.liHeight,q=this.sizeInfo.headerHeight,r=this.sizeInfo.searchHeight,s=this.sizeInfo.actionsHeight,t=this.sizeInfo.doneButtonHeight,u=this.sizeInfo.dividerHeight,v=this.sizeInfo.menuPadding,w=this.sizeInfo.menuExtras,x=this.options.hideDisabled?".disabled":"",y=function(){var b,c=j.$newElement.offset(),d=a(j.options.container);j.options.container&&!d.is("body")?(b=d.offset(),b.top+=parseInt(d.css("borderTopWidth")),b.left+=parseInt(d.css("borderLeftWidth"))):b={top:0,left:0};var e=j.options.windowPadding;f=c.top-b.top-m.scrollTop(),g=m.height()-f-n-b.top-e[2],h=c.left-b.left-m.scrollLeft(),i=m.width()-h-o-b.left-e[1],f-=e[0],h-=e[3]};if(y(),"auto"===this.options.size){var z=function(){var m,n=function(b,c){return function(d){return c?d.classList?d.classList.contains(b):a(d).hasClass(b):!(d.classList?d.classList.contains(b):a(d).hasClass(b))}},u=j.$menuInner[0].getElementsByTagName("li"),x=Array.prototype.filter?Array.prototype.filter.call(u,n("hidden",!1)):j.$lis.not(".hidden"),z=Array.prototype.filter?Array.prototype.filter.call(x,n("dropdown-header",!0)):x.filter(".dropdown-header");y(),b=g-w.vert,c=i-w.horiz,j.options.container?(k.data("height")||k.data("height",k.height()),d=k.data("height"),k.data("width")||k.data("width",k.width()),e=k.data("width")):(d=k.height(),e=k.width()),j.options.dropupAuto&&j.$newElement.toggleClass("dropup",f>g&&b-w.vert<d),j.$newElement.hasClass("dropup")&&(b=f-w.vert),"auto"===j.options.dropdownAlignRight&&k.toggleClass("dropdown-menu-right",h>i&&c-w.horiz<e-o),m=x.length+z.length>3?3*p+w.vert-2:0,k.css({"max-height":b+"px",overflow:"hidden","min-height":m+q+r+s+t+"px"}),l.css({"max-height":b-q-r-s-t-v.vert+"px","overflow-y":"auto","min-height":Math.max(m-v.vert,0)+"px"})};z(),this.$searchbox.off("input.getSize propertychange.getSize").on("input.getSize propertychange.getSize",z),m.off("resize.getSize scroll.getSize").on("resize.getSize scroll.getSize",z)}else if(this.options.size&&"auto"!=this.options.size&&this.$lis.not(x).length>this.options.size){var A=this.$lis.not(".divider").not(x).children().slice(0,this.options.size).last().parent().index(),B=this.$lis.slice(0,A+1).filter(".divider").length;b=p*this.options.size+B*u+v.vert,j.options.container?(k.data("height")||k.data("height",k.height()),d=k.data("height")):d=k.height(),j.options.dropupAuto&&this.$newElement.toggleClass("dropup",f>g&&b-w.vert<d),k.css({"max-height":b+q+r+s+t+"px",overflow:"hidden","min-height":""}),l.css({"max-height":b-v.vert+"px","overflow-y":"auto","min-height":""})}}},setWidth:function(){if("auto"===this.options.width){this.$menu.css("min-width","0");var a=this.$menu.parent().clone().appendTo("body"),b=this.options.container?this.$newElement.clone().appendTo("body"):a,c=a.children(".dropdown-menu").outerWidth(),d=b.css("width","auto").children("button").outerWidth();a.remove(),b.remove(),this.$newElement.css("width",Math.max(c,d)+"px")}else"fit"===this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width","").addClass("fit-width")):this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width",this.options.width)):(this.$menu.css("min-width",""),this.$newElement.css("width",""));this.$newElement.hasClass("fit-width")&&"fit"!==this.options.width&&this.$newElement.removeClass("fit-width")},selectPosition:function(){this.$bsContainer=a('<div class="bs-container" />');var b,c,d,e=this,f=a(this.options.container),g=function(a){e.$bsContainer.addClass(a.attr("class").replace(/form-control|fit-width/gi,"")).toggleClass("dropup",a.hasClass("dropup")),b=a.offset(),f.is("body")?c={top:0,left:0}:(c=f.offset(),c.top+=parseInt(f.css("borderTopWidth"))-f.scrollTop(),c.left+=parseInt(f.css("borderLeftWidth"))-f.scrollLeft()),d=a.hasClass("dropup")?0:a[0].offsetHeight,e.$bsContainer.css({top:b.top-c.top+d,left:b.left-c.left,width:a[0].offsetWidth})};this.$button.on("click",function(){var b=a(this);e.isDisabled()||(g(e.$newElement),e.$bsContainer.appendTo(e.options.container).toggleClass("open",!b.hasClass("open")).append(e.$menu))}),a(window).on("resize scroll",function(){g(e.$newElement)}),this.$element.on("hide.bs.select",function(){e.$menu.data("height",e.$menu.height()),e.$bsContainer.detach()})},setSelected:function(a,b,c){c||(this.togglePlaceholder(),c=this.findLis().eq(this.liObj[a])),c.toggleClass("selected",b).find("a").attr("aria-selected",b)},setDisabled:function(a,b,c){c||(c=this.findLis().eq(this.liObj[a])),b?c.addClass("disabled").children("a").attr("href","#").attr("tabindex",-1).attr("aria-disabled",!0):c.removeClass("disabled").children("a").removeAttr("href").attr("tabindex",0).attr("aria-disabled",!1)},isDisabled:function(){return this.$element[0].disabled},checkDisabled:function(){var a=this;this.isDisabled()?(this.$newElement.addClass("disabled"),this.$button.addClass("disabled").attr("tabindex",-1).attr("aria-disabled",!0)):(this.$button.hasClass("disabled")&&(this.$newElement.removeClass("disabled"),this.$button.removeClass("disabled").attr("aria-disabled",!1)),this.$button.attr("tabindex")!=-1||this.$element.data("tabindex")||this.$button.removeAttr("tabindex")),this.$button.click(function(){return!a.isDisabled()})},togglePlaceholder:function(){var a=this.$element.val();this.$button.toggleClass("bs-placeholder",null===a||""===a||a.constructor===Array&&0===a.length)},tabIndex:function(){this.$element.data("tabindex")!==this.$element.attr("tabindex")&&this.$element.attr("tabindex")!==-98&&"-98"!==this.$element.attr("tabindex")&&(this.$element.data("tabindex",this.$element.attr("tabindex")),this.$button.attr("tabindex",this.$element.data("tabindex"))),this.$element.attr("tabindex",-98)},clickListener:function(){var b=this,c=a(document);c.data("spaceSelect",!1),this.$button.on("keyup",function(a){/(32)/.test(a.keyCode.toString(10))&&c.data("spaceSelect")&&(a.preventDefault(),c.data("spaceSelect",!1))}),this.$button.on("click",function(){b.setSize()}),this.$element.on("shown.bs.select",function(){if(b.options.liveSearch||b.multiple){if(!b.multiple){var a=b.liObj[b.$element[0].selectedIndex];if("number"!=typeof a||b.options.size===!1)return;var c=b.$lis.eq(a)[0].offsetTop-b.$menuInner[0].offsetTop;c=c-b.$menuInner[0].offsetHeight/2+b.sizeInfo.liHeight/2,b.$menuInner[0].scrollTop=c}}else b.$menuInner.find(".selected a").focus()}),this.$menuInner.on("click","li a",function(c){var d=a(this),f=d.parent().data("originalIndex"),g=b.$element.val(),h=b.$element.prop("selectedIndex"),i=!0;if(b.multiple&&1!==b.options.maxOptions&&c.stopPropagation(),c.preventDefault(),!b.isDisabled()&&!d.parent().hasClass("disabled")){var j=b.$element.find("option"),k=j.eq(f),l=k.prop("selected"),m=k.parent("optgroup"),n=b.options.maxOptions,o=m.data("maxOptions")||!1;if(b.multiple){if(k.prop("selected",!l),b.setSelected(f,!l),d.blur(),n!==!1||o!==!1){var p=n<j.filter(":selected").length,q=o<m.find("option:selected").length;if(n&&p||o&&q)if(n&&1==n)j.prop("selected",!1),k.prop("selected",!0),b.$menuInner.find(".selected").removeClass("selected"),b.setSelected(f,!0);else if(o&&1==o){m.find("option:selected").prop("selected",!1),k.prop("selected",!0);var r=d.parent().data("optgroup");b.$menuInner.find('[data-optgroup="'+r+'"]').removeClass("selected"),b.setSelected(f,!0)}else{var s="string"==typeof b.options.maxOptionsText?[b.options.maxOptionsText,b.options.maxOptionsText]:b.options.maxOptionsText,t="function"==typeof s?s(n,o):s,u=t[0].replace("{n}",n),v=t[1].replace("{n}",o),w=a('<div class="notify"></div>');t[2]&&(u=u.replace("{var}",t[2][n>1?0:1]),v=v.replace("{var}",t[2][o>1?0:1])),k.prop("selected",!1),b.$menu.append(w),n&&p&&(w.append(a("<div>"+u+"</div>")),i=!1,b.$element.trigger("maxReached.bs.select")),o&&q&&(w.append(a("<div>"+v+"</div>")),i=!1,b.$element.trigger("maxReachedGrp.bs.select")),setTimeout(function(){b.setSelected(f,!1)},10),w.delay(750).fadeOut(300,function(){a(this).remove()})}}}else j.prop("selected",!1),k.prop("selected",!0),b.$menuInner.find(".selected").removeClass("selected").find("a").attr("aria-selected",!1),b.setSelected(f,!0);!b.multiple||b.multiple&&1===b.options.maxOptions?b.$button.focus():b.options.liveSearch&&b.$searchbox.focus(),i&&(g!=b.$element.val()&&b.multiple||h!=b.$element.prop("selectedIndex")&&!b.multiple)&&(e=[f,k.prop("selected"),l],b.$element.triggerNative("change"))}}),this.$menu.on("click","li.disabled a, .popover-title, .popover-title :not(.close)",function(c){c.currentTarget==this&&(c.preventDefault(),c.stopPropagation(),b.options.liveSearch&&!a(c.target).hasClass("close")?b.$searchbox.focus():b.$button.focus())}),this.$menuInner.on("click",".divider, .dropdown-header",function(a){a.preventDefault(),a.stopPropagation(),b.options.liveSearch?b.$searchbox.focus():b.$button.focus()}),this.$menu.on("click",".popover-title .close",function(){b.$button.click()}),this.$searchbox.on("click",function(a){a.stopPropagation()}),this.$menu.on("click",".actions-btn",function(c){b.options.liveSearch?b.$searchbox.focus():b.$button.focus(),c.preventDefault(),c.stopPropagation(),a(this).hasClass("bs-select-all")?b.selectAll():b.deselectAll()}),this.$element.change(function(){b.render(!1),b.$element.trigger("changed.bs.select",e),e=null})},liveSearchListener:function(){var c=this,d=a('<li class="no-results"></li>');this.$button.on("click.dropdown.data-api",function(){c.$menuInner.find(".active").removeClass("active"),c.$searchbox.val()&&(c.$searchbox.val(""),c.$lis.not(".is-hidden").removeClass("hidden"),d.parent().length&&d.remove()),c.multiple||c.$menuInner.find(".selected").addClass("active"),setTimeout(function(){c.$searchbox.focus()},10)}),this.$searchbox.on("click.dropdown.data-api focus.dropdown.data-api touchend.dropdown.data-api",function(a){a.stopPropagation()}),this.$searchbox.on("input propertychange",function(){if(c.$lis.not(".is-hidden").removeClass("hidden"),c.$lis.filter(".active").removeClass("active"),d.remove(),c.$searchbox.val()){var e,f=c.$lis.not(".is-hidden, .divider, .dropdown-header");if(e=c.options.liveSearchNormalize?f.not(":a"+c._searchStyle()+'("'+b(c.$searchbox.val())+'")'):f.not(":"+c._searchStyle()+'("'+c.$searchbox.val()+'")'),e.length===f.length)d.html(c.options.noneResultsText.replace("{0}",'"'+j(c.$searchbox.val())+'"')),c.$menuInner.append(d),c.$lis.addClass("hidden");else{e.addClass("hidden");var g,h=c.$lis.not(".hidden");h.each(function(b){var c=a(this);c.hasClass("divider")?void 0===g?c.addClass("hidden"):(g&&g.addClass("hidden"),g=c):c.hasClass("dropdown-header")&&h.eq(b+1).data("optgroup")!==c.data("optgroup")?c.addClass("hidden"):g=null}),g&&g.addClass("hidden"),f.not(".hidden").first().addClass("active"),c.$menuInner.scrollTop(0)}}})},_searchStyle:function(){var a={begins:"ibegins",startsWith:"ibegins"};return a[this.options.liveSearchStyle]||"icontains"},val:function(a){return"undefined"!=typeof a?(this.$element.val(a),this.render(),this.$element):this.$element.val()},changeAll:function(b){if(this.multiple){"undefined"==typeof b&&(b=!0),this.findLis();var c=this.$element.find("option"),d=this.$lis.not(".divider, .dropdown-header, .disabled, .hidden"),e=d.length,f=[];if(b){if(d.filter(".selected").length===d.length)return}else if(0===d.filter(".selected").length)return;d.toggleClass("selected",b);for(var g=0;g<e;g++){var h=d[g].getAttribute("data-original-index");f[f.length]=c.eq(h)[0]}a(f).prop("selected",b),this.render(!1),this.togglePlaceholder(),this.$element.triggerNative("change")}},selectAll:function(){return this.changeAll(!0)},deselectAll:function(){return this.changeAll(!1)},toggle:function(a){a=a||window.event,a&&a.stopPropagation(),this.$button.trigger("click")},keydown:function(b){var c,d,e,f,g=a(this),h=g.is("input")?g.parent().parent():g.parent(),i=h.data("this"),j=":not(.disabled, .hidden, .dropdown-header, .divider)",k={32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9"};if(f=i.$newElement.hasClass("open"),!f&&(b.keyCode>=48&&b.keyCode<=57||b.keyCode>=96&&b.keyCode<=105||b.keyCode>=65&&b.keyCode<=90))return i.options.container?i.$button.trigger("click"):(i.setSize(),i.$menu.parent().addClass("open"),f=!0),void i.$searchbox.focus();if(i.options.liveSearch&&/(^9$|27)/.test(b.keyCode.toString(10))&&f&&(b.preventDefault(),b.stopPropagation(),i.$menuInner.click(),i.$button.focus()),/(38|40)/.test(b.keyCode.toString(10))){if(c=i.$lis.filter(j),!c.length)return;d=i.options.liveSearch?c.index(c.filter(".active")):c.index(c.find("a").filter(":focus").parent()),e=i.$menuInner.data("prevIndex"),38==b.keyCode?(!i.options.liveSearch&&d!=e||d==-1||d--,d<0&&(d+=c.length)):40==b.keyCode&&((i.options.liveSearch||d==e)&&d++,d%=c.length),i.$menuInner.data("prevIndex",d),i.options.liveSearch?(b.preventDefault(),g.hasClass("dropdown-toggle")||(c.removeClass("active").eq(d).addClass("active").children("a").focus(),g.focus())):c.eq(d).children("a").focus()}else if(!g.is("input")){var l,m,n=[];c=i.$lis.filter(j),c.each(function(c){a.trim(a(this).children("a").text().toLowerCase()).substring(0,1)==k[b.keyCode]&&n.push(c)}),l=a(document).data("keycount"),l++,a(document).data("keycount",l),m=a.trim(a(":focus").text().toLowerCase()).substring(0,1),m!=k[b.keyCode]?(l=1,a(document).data("keycount",l)):l>=n.length&&(a(document).data("keycount",0),l>n.length&&(l=1)),c.eq(n[l-1]).children("a").focus()}if((/(13|32)/.test(b.keyCode.toString(10))||/(^9$)/.test(b.keyCode.toString(10))&&i.options.selectOnTab)&&f){if(/(32)/.test(b.keyCode.toString(10))||b.preventDefault(),i.options.liveSearch)/(32)/.test(b.keyCode.toString(10))||(i.$menuInner.find(".active a").click(),g.focus());else{var o=a(":focus");o.click(),o.focus(),b.preventDefault(),a(document).data("spaceSelect",!0)}a(document).data("keycount",0)}(/(^9$|27)/.test(b.keyCode.toString(10))&&f&&(i.multiple||i.options.liveSearch)||/(27)/.test(b.keyCode.toString(10))&&!f)&&(i.$menu.parent().removeClass("open"),i.options.container&&i.$newElement.removeClass("open"),i.$button.focus())},mobile:function(){this.$element.addClass("mobile-device")},refresh:function(){this.$lis=null,this.liObj={},this.reloadLi(),this.render(),this.checkDisabled(),this.liHeight(!0),this.setStyle(),
this.setWidth(),this.$lis&&this.$searchbox.trigger("propertychange"),this.$element.trigger("refreshed.bs.select")},hide:function(){this.$newElement.hide()},show:function(){this.$newElement.show()},remove:function(){this.$newElement.remove(),this.$element.remove()},destroy:function(){this.$newElement.before(this.$element).remove(),this.$bsContainer?this.$bsContainer.remove():this.$menu.remove(),this.$element.off(".bs.select").removeData("selectpicker").removeClass("bs-select-hidden selectpicker")}};var m=a.fn.selectpicker;a.fn.selectpicker=c,a.fn.selectpicker.Constructor=l,a.fn.selectpicker.noConflict=function(){return a.fn.selectpicker=m,this},a(document).data("keycount",0).on("keydown.bs.select",'.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input',l.prototype.keydown).on("focusin.modal",'.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input',function(a){a.stopPropagation()}),a(window).on("load.bs.select.data-api",function(){a(".selectpicker").each(function(){var b=a(this);c.call(b,b.data())})})}(a)});
//# sourceMappingURL=bootstrap-select.js.map;
// jQuery HC-Sticky
// =============
// Version: 1.2.43
// Copyright: Some Web Media
// Author: Some Web Guy
// Author URL: http://twitter.com/some_web_guy
// Website: http://someweblog.com/
// Plugin URL: https://github.com/somewebmedia/hc-sticky
// License: Released under the MIT License www.opensource.org/licenses/mit-license.php
// Description: Cross-browser jQuery plugin that makes any element attached to the page and always visible while you scroll.

(function(e,t,n){"use strict";var r=function(e){console.log(e)};var i=e(t),s=t.document,o=e(s);var u=function(){var e,t=3,n=s.createElement("div"),r=n.getElementsByTagName("i");while(n.innerHTML="<!--[if gt IE "+ ++t+"]><i></i><![endif]-->",r[0]){}return t>4?t:e}();var a=function(){var e=t.pageXOffset!==n?t.pageXOffset:s.compatMode=="CSS1Compat"?t.document.documentElement.scrollLeft:t.document.body.scrollLeft,r=t.pageYOffset!==n?t.pageYOffset:s.compatMode=="CSS1Compat"?t.document.documentElement.scrollTop:t.document.body.scrollTop;if(typeof a.x=="undefined"){a.x=e;a.y=r}if(typeof a.distanceX=="undefined"){a.distanceX=e;a.distanceY=r}else{a.distanceX=e-a.x;a.distanceY=r-a.y}var i=a.x-e,o=a.y-r;a.direction=i<0?"right":i>0?"left":o<=0?"down":o>0?"up":"first";a.x=e;a.y=r};i.on("scroll",a);e.fn.style=function(n){if(!n)return null;var r=e(this),i;var o=r.clone().css("display","none");o.find("input:radio").attr("name","copy-"+Math.floor(Math.random()*100+1));r.after(o);var u=function(e,n){var i;if(e.currentStyle){i=e.currentStyle[n.replace(/-\w/g,function(e){return e.toUpperCase().replace("-","")})]}else if(t.getComputedStyle){i=s.defaultView.getComputedStyle(e,null).getPropertyValue(n)}i=/margin/g.test(n)?parseInt(i)===r[0].offsetLeft?i:"auto":i;return i};if(typeof n=="string"){i=u(o[0],n)}else{i={};e.each(n,function(e,t){i[t]=u(o[0],t)})}o.remove();return i||null};e.fn.extend({hcSticky:function(r){if(this.length==0)return this;this.pluginOptions("hcSticky",{top:0,bottom:0,bottomEnd:0,innerTop:0,innerSticker:null,className:"sticky",wrapperClassName:"wrapper-sticky",stickTo:null,responsive:true,followScroll:true,offResolutions:null,onStart:e.noop,onStop:e.noop,on:true,fn:null},r||{},{reinit:function(){e(this).hcSticky()},stop:function(){e(this).pluginOptions("hcSticky",{on:false}).each(function(){var t=e(this),n=t.pluginOptions("hcSticky"),r=t.parent("."+n.wrapperClassName);var i=t.offset().top-r.offset().top;t.css({position:"absolute",top:i,bottom:"auto",left:"auto",right:"auto"}).removeClass(n.className)})},off:function(){e(this).pluginOptions("hcSticky",{on:false}).each(function(){var t=e(this),n=t.pluginOptions("hcSticky"),r=t.parent("."+n.wrapperClassName);t.css({position:"relative",top:"auto",bottom:"auto",left:"auto",right:"auto"}).removeClass(n.className);r.css("height","auto")})},on:function(){e(this).each(function(){e(this).pluginOptions("hcSticky",{on:true,remember:{offsetTop:i.scrollTop()}}).hcSticky()})},destroy:function(){var t=e(this),n=t.pluginOptions("hcSticky"),r=t.parent("."+n.wrapperClassName);t.removeData("hcStickyInit").css({position:r.css("position"),top:r.css("top"),bottom:r.css("bottom"),left:r.css("left"),right:r.css("right")}).removeClass(n.className);i.off("resize",n.fn.resize).off("scroll",n.fn.scroll);t.unwrap()}});if(r&&typeof r.on!="undefined"){if(r.on){this.hcSticky("on")}else{this.hcSticky("off")}}if(typeof r=="string")return this;return this.each(function(){var r=e(this),s=r.pluginOptions("hcSticky");var f=function(){var e=r.parent("."+s.wrapperClassName);if(e.length>0){e.css({height:r.outerHeight(true),width:function(){var t=e.style("width");if(t.indexOf("%")>=0||t=="auto"){if(r.css("box-sizing")=="border-box"||r.css("-moz-box-sizing")=="border-box"){r.css("width",e.width())}else{r.css("width",e.width()-parseInt(r.css("padding-left")-parseInt(r.css("padding-right"))))}return t}else{return r.outerWidth(true)}}()});return e}else{return false}}()||function(){var t=r.style(["width","margin-left","left","right","top","bottom","float","display"]);var n=r.css("display");var i=e("<div>",{"class":s.wrapperClassName}).css({display:n,height:r.outerHeight(true),width:function(){if(t["width"].indexOf("%")>=0||t["width"]=="auto"&&n!="inline-block"&&n!="inline"){r.css("width",parseFloat(r.css("width")));return t["width"]}else if(t["width"]=="auto"&&(n=="inline-block"||n=="inline")){return r.width()}else{return t["margin-left"]=="auto"?r.outerWidth():r.outerWidth(true)}}(),margin:t["margin-left"]?"auto":null,position:function(){var e=r.css("position");return e=="static"?"relative":e}(),"float":t["float"]||null,left:t["left"],right:t["right"],top:t["top"],bottom:t["bottom"],"vertical-align":"top"});r.wrap(i);if(u===7){if(e("head").find("style#hcsticky-iefix").length===0){e('<style id="hcsticky-iefix">.'+s.wrapperClassName+" {zoom: 1;}</style>").appendTo("head")}}return r.parent()}();if(r.data("hcStickyInit"))return;r.data("hcStickyInit",true);var l=s.stickTo&&(s.stickTo=="document"||s.stickTo.nodeType&&s.stickTo.nodeType==9||typeof s.stickTo=="object"&&s.stickTo instanceof(typeof HTMLDocument!="undefined"?HTMLDocument:Document))?true:false;var c=s.stickTo?l?o:typeof s.stickTo=="string"?e(s.stickTo):s.stickTo:f.parent();r.css({top:"auto",bottom:"auto",left:"auto",right:"auto"});i.load(function(){if(r.outerHeight(true)>c.height()){f.css("height",r.outerHeight(true));r.hcSticky("reinit")}});var h=function(e){if(r.hasClass(s.className))return;e=e||{};r.css({position:"fixed",top:e.top||0,left:e.left||f.offset().left}).addClass(s.className);s.onStart.apply(r[0]);f.addClass("sticky-active")},p=function(e){e=e||{};e.position=e.position||"absolute";e.top=e.top||0;e.left=e.left||0;if(r.css("position")!="fixed"&&parseInt(r.css("top"))==e.top)return;r.css({position:e.position,top:e.top,left:e.left}).removeClass(s.className);s.onStop.apply(r[0]);f.removeClass("sticky-active")};var d=function(t){if(!s.on||!r.is(":visible"))return;if(r.outerHeight(true)>=c.height()){p();return}var n=s.innerSticker?e(s.innerSticker).position().top:s.innerTop?s.innerTop:0,o=f.offset().top,u=c.height()-s.bottomEnd+(l?0:o),d=f.offset().top-s.top+n,v=r.outerHeight(true)+s.bottom,m=i.height(),g=i.scrollTop(),y=r.offset().top,b=y-g,w;if(typeof s.remember!="undefined"&&s.remember){var E=y-s.top-n;if(v-n>m&&s.followScroll){if(E<g&&g+m<=E+r.height()){s.remember=false}}else{if(s.remember.offsetTop>E){if(g<=E){h({top:s.top-n});s.remember=false}}else{if(g>=E){h({top:s.top-n});s.remember=false}}}return}if(g>d){if(u+s.bottom-(s.followScroll&&m<v?0:s.top)<=g+v-n-(v-n>m-(d-n)&&s.followScroll?(w=v-m-n)>0?w:0:0)){p({top:u-v+s.bottom-o})}else if(v-n>m&&s.followScroll){if(b+v<=m){if(a.direction=="down"){h({top:m-v})}else{if(b<0&&r.css("position")=="fixed"){p({top:y-(d+s.top-n)-a.distanceY})}}}else{if(a.direction=="up"&&y>=g+s.top-n){h({top:s.top-n})}else if(a.direction=="down"&&y+v>m&&r.css("position")=="fixed"){p({top:y-(d+s.top-n)-a.distanceY})}}}else{h({top:s.top-n})}}else{p()}};var v=false,m=false;var g=function(){b();y();if(!s.on)return;var e=function(){if(r.css("position")=="fixed"){r.css("left",f.offset().left)}else{r.css("left",0)}};if(s.responsive){if(!m){m=r.clone().attr("style","").css({visibility:"hidden",height:0,overflow:"hidden",paddingTop:0,paddingBottom:0,marginTop:0,marginBottom:0});f.after(m)}var t=f.style("width");var n=m.style("width");if(n=="auto"&&t!="auto"){n=parseInt(r.css("width"))}if(n!=t){f.width(n)}if(v){clearTimeout(v)}v=setTimeout(function(){v=false;m.remove();m=false},250)}e();if(r.outerWidth(true)!=f.width()){var i=r.css("box-sizing")=="border-box"||r.css("-moz-box-sizing")=="border-box"?f.width():f.width()-parseInt(r.css("padding-left"))-parseInt(r.css("padding-right"));i=i-parseInt(r.css("margin-left"))-parseInt(r.css("margin-right"));r.css("width",i)}};r.pluginOptions("hcSticky",{fn:{scroll:d,resize:g}});var y=function(){if(s.offResolutions){if(!e.isArray(s.offResolutions)){s.offResolutions=[s.offResolutions]}var t=true;e.each(s.offResolutions,function(e,n){if(n<0){if(i.width()<n*-1){t=false;r.hcSticky("off")}}else{if(i.width()>n){t=false;r.hcSticky("off")}}});if(t&&!s.on){r.hcSticky("on")}}};y();i.on("resize",g);var b=function(){var r=false;if(e._data(t,"events").scroll!=n){e.each(e._data(t,"events").scroll,function(e,t){if(t.handler==s.fn.scroll){r=true}})}if(!r){s.fn.scroll(true);i.on("scroll",s.fn.scroll)}};b()})}})})(jQuery,this);(function(e,t){"use strict";e.fn.extend({pluginOptions:function(n,r,i,s){if(!this.data(n))this.data(n,{});if(n&&typeof r=="undefined")return this.data(n).options;i=i||r||{};if(typeof i=="object"||i===t){return this.each(function(){var t=e(this);if(!t.data(n).options){t.data(n,{options:e.extend(r,i||{})});if(s){t.data(n).commands=s}}else{t.data(n,e.extend(t.data(n),{options:e.extend(t.data(n).options,i||{})}))}})}else if(typeof i=="string"){return this.each(function(){e(this).data(n).commands[i].call(this)})}else{return this}}})})(jQuery)
;
!function(t,e,i){!function(){var s,a,n,h="2.2.3",o="datepicker",r=".datepicker-here",c=!1,d='<div class="datepicker"><i class="datepicker--pointer"></i><nav class="datepicker--nav"></nav><div class="datepicker--content"></div></div>',l={classes:"",inline:!1,language:"en",startDate:new Date,firstDay:"",weekends:[6,0],dateFormat:"",altField:"",altFieldDateFormat:"@",toggleSelected:!0,keyboardNav:!0,position:"bottom left",offset:12,view:"days",minView:"days",showOtherMonths:!0,selectOtherMonths:!0,moveToOtherMonthsOnSelect:!0,showOtherYears:!0,selectOtherYears:!0,moveToOtherYearsOnSelect:!0,minDate:"",maxDate:"",disableNavWhenOutOfRange:!0,multipleDates:!1,multipleDatesSeparator:",",range:!1,todayButton:!1,clearButton:!1,showEvent:"focus",autoClose:!1,monthsField:"monthsShort",prevHtml:'<svg><path d="M 17,12 l -5,5 l 5,5"></path></svg>',nextHtml:'<svg><path d="M 14,12 l 5,5 l -5,5"></path></svg>',navTitles:{days:"MM, <i>yyyy</i>",months:"yyyy",years:"yyyy1 - yyyy2"},timepicker:!1,onlyTimepicker:!1,dateTimeSeparator:" ",timeFormat:"",minHours:0,maxHours:24,minMinutes:0,maxMinutes:59,hoursStep:1,minutesStep:1,onSelect:"",onShow:"",onHide:"",onChangeMonth:"",onChangeYear:"",onChangeDecade:"",onChangeView:"",onRenderCell:""},u={ctrlRight:[17,39],ctrlUp:[17,38],ctrlLeft:[17,37],ctrlDown:[17,40],shiftRight:[16,39],shiftUp:[16,38],shiftLeft:[16,37],shiftDown:[16,40],altUp:[18,38],altRight:[18,39],altLeft:[18,37],altDown:[18,40],ctrlShiftUp:[16,17,38]},m=function(t,a){this.el=t,this.$el=e(t),this.opts=e.extend(!0,{},l,a,this.$el.data()),s==i&&(s=e("body")),this.opts.startDate||(this.opts.startDate=new Date),"INPUT"==this.el.nodeName&&(this.elIsInput=!0),this.opts.altField&&(this.$altField="string"==typeof this.opts.altField?e(this.opts.altField):this.opts.altField),this.inited=!1,this.visible=!1,this.silent=!1,this.currentDate=this.opts.startDate,this.currentView=this.opts.view,this._createShortCuts(),this.selectedDates=[],this.views={},this.keys=[],this.minRange="",this.maxRange="",this._prevOnSelectValue="",this.init()};n=m,n.prototype={VERSION:h,viewIndexes:["days","months","years"],init:function(){c||this.opts.inline||!this.elIsInput||this._buildDatepickersContainer(),this._buildBaseHtml(),this._defineLocale(this.opts.language),this._syncWithMinMaxDates(),this.elIsInput&&(this.opts.inline||(this._setPositionClasses(this.opts.position),this._bindEvents()),this.opts.keyboardNav&&!this.opts.onlyTimepicker&&this._bindKeyboardEvents(),this.$datepicker.on("mousedown",this._onMouseDownDatepicker.bind(this)),this.$datepicker.on("mouseup",this._onMouseUpDatepicker.bind(this))),this.opts.classes&&this.$datepicker.addClass(this.opts.classes),this.opts.timepicker&&(this.timepicker=new e.fn.datepicker.Timepicker(this,this.opts),this._bindTimepickerEvents()),this.opts.onlyTimepicker&&this.$datepicker.addClass("-only-timepicker-"),this.views[this.currentView]=new e.fn.datepicker.Body(this,this.currentView,this.opts),this.views[this.currentView].show(),this.nav=new e.fn.datepicker.Navigation(this,this.opts),this.view=this.currentView,this.$el.on("clickCell.adp",this._onClickCell.bind(this)),this.$datepicker.on("mouseenter",".datepicker--cell",this._onMouseEnterCell.bind(this)),this.$datepicker.on("mouseleave",".datepicker--cell",this._onMouseLeaveCell.bind(this)),this.inited=!0},_createShortCuts:function(){this.minDate=this.opts.minDate?this.opts.minDate:new Date(-86399999136e5),this.maxDate=this.opts.maxDate?this.opts.maxDate:new Date(86399999136e5)},_bindEvents:function(){this.$el.on(this.opts.showEvent+".adp",this._onShowEvent.bind(this)),this.$el.on("mouseup.adp",this._onMouseUpEl.bind(this)),this.$el.on("blur.adp",this._onBlur.bind(this)),this.$el.on("keyup.adp",this._onKeyUpGeneral.bind(this)),e(t).on("resize.adp",this._onResize.bind(this)),e("body").on("mouseup.adp",this._onMouseUpBody.bind(this))},_bindKeyboardEvents:function(){this.$el.on("keydown.adp",this._onKeyDown.bind(this)),this.$el.on("keyup.adp",this._onKeyUp.bind(this)),this.$el.on("hotKey.adp",this._onHotKey.bind(this))},_bindTimepickerEvents:function(){this.$el.on("timeChange.adp",this._onTimeChange.bind(this))},isWeekend:function(t){return-1!==this.opts.weekends.indexOf(t)},_defineLocale:function(t){"string"==typeof t?(this.loc=e.fn.datepicker.language[t],this.loc||(console.warn("Can't find language \""+t+'" in Datepicker.language, will use "ru" instead'),this.loc=e.extend(!0,{},e.fn.datepicker.language.ru)),this.loc=e.extend(!0,{},e.fn.datepicker.language.ru,e.fn.datepicker.language[t])):this.loc=e.extend(!0,{},e.fn.datepicker.language.ru,t),this.opts.dateFormat&&(this.loc.dateFormat=this.opts.dateFormat),this.opts.timeFormat&&(this.loc.timeFormat=this.opts.timeFormat),""!==this.opts.firstDay&&(this.loc.firstDay=this.opts.firstDay),this.opts.timepicker&&(this.loc.dateFormat=[this.loc.dateFormat,this.loc.timeFormat].join(this.opts.dateTimeSeparator)),this.opts.onlyTimepicker&&(this.loc.dateFormat=this.loc.timeFormat);var i=this._getWordBoundaryRegExp;(this.loc.timeFormat.match(i("aa"))||this.loc.timeFormat.match(i("AA")))&&(this.ampm=!0)},_buildDatepickersContainer:function(){c=!0,s.append('<div class="datepickers-container" id="datepickers-container"></div>'),a=e("#datepickers-container")},_buildBaseHtml:function(){var t,i=e('<div class="datepicker-inline">');t="INPUT"==this.el.nodeName?this.opts.inline?i.insertAfter(this.$el):a:i.appendTo(this.$el),this.$datepicker=e(d).appendTo(t),this.$content=e(".datepicker--content",this.$datepicker),this.$nav=e(".datepicker--nav",this.$datepicker)},_triggerOnChange:function(){if(!this.selectedDates.length){if(""===this._prevOnSelectValue)return;return this._prevOnSelectValue="",this.opts.onSelect("","",this)}var t,e=this.selectedDates,i=n.getParsedDate(e[0]),s=this,a=new Date(i.year,i.month,i.date,i.hours,i.minutes);t=e.map(function(t){return s.formatDate(s.loc.dateFormat,t)}).join(this.opts.multipleDatesSeparator),(this.opts.multipleDates||this.opts.range)&&(a=e.map(function(t){var e=n.getParsedDate(t);return new Date(e.year,e.month,e.date,e.hours,e.minutes)})),this._prevOnSelectValue=t,this.opts.onSelect(t,a,this)},next:function(){var t=this.parsedDate,e=this.opts;switch(this.view){case"days":this.date=new Date(t.year,t.month+1,1),e.onChangeMonth&&e.onChangeMonth(this.parsedDate.month,this.parsedDate.year);break;case"months":this.date=new Date(t.year+1,t.month,1),e.onChangeYear&&e.onChangeYear(this.parsedDate.year);break;case"years":this.date=new Date(t.year+10,0,1),e.onChangeDecade&&e.onChangeDecade(this.curDecade)}},prev:function(){var t=this.parsedDate,e=this.opts;switch(this.view){case"days":this.date=new Date(t.year,t.month-1,1),e.onChangeMonth&&e.onChangeMonth(this.parsedDate.month,this.parsedDate.year);break;case"months":this.date=new Date(t.year-1,t.month,1),e.onChangeYear&&e.onChangeYear(this.parsedDate.year);break;case"years":this.date=new Date(t.year-10,0,1),e.onChangeDecade&&e.onChangeDecade(this.curDecade)}},formatDate:function(t,e){e=e||this.date;var i,s=t,a=this._getWordBoundaryRegExp,h=this.loc,o=n.getLeadingZeroNum,r=n.getDecade(e),c=n.getParsedDate(e),d=c.fullHours,l=c.hours,u=t.match(a("aa"))||t.match(a("AA")),m="am",p=this._replacer;switch(this.opts.timepicker&&this.timepicker&&u&&(i=this.timepicker._getValidHoursFromDate(e,u),d=o(i.hours),l=i.hours,m=i.dayPeriod),!0){case/@/.test(s):s=s.replace(/@/,e.getTime());case/aa/.test(s):s=p(s,a("aa"),m);case/AA/.test(s):s=p(s,a("AA"),m.toUpperCase());case/dd/.test(s):s=p(s,a("dd"),c.fullDate);case/d/.test(s):s=p(s,a("d"),c.date);case/DD/.test(s):s=p(s,a("DD"),h.days[c.day]);case/D/.test(s):s=p(s,a("D"),h.daysShort[c.day]);case/mm/.test(s):s=p(s,a("mm"),c.fullMonth);case/m/.test(s):s=p(s,a("m"),c.month+1);case/MM/.test(s):s=p(s,a("MM"),this.loc.months[c.month]);case/M/.test(s):s=p(s,a("M"),h.monthsShort[c.month]);case/ii/.test(s):s=p(s,a("ii"),c.fullMinutes);case/i/.test(s):s=p(s,a("i"),c.minutes);case/hh/.test(s):s=p(s,a("hh"),d);case/h/.test(s):s=p(s,a("h"),l);case/yyyy/.test(s):s=p(s,a("yyyy"),c.year);case/yyyy1/.test(s):s=p(s,a("yyyy1"),r[0]);case/yyyy2/.test(s):s=p(s,a("yyyy2"),r[1]);case/yy/.test(s):s=p(s,a("yy"),c.year.toString().slice(-2))}return s},_replacer:function(t,e,i){return t.replace(e,function(t,e,s,a){return e+i+a})},_getWordBoundaryRegExp:function(t){var e="\\s|\\.|-|/|\\\\|,|\\$|\\!|\\?|:|;";return new RegExp("(^|>|"+e+")("+t+")($|<|"+e+")","g")},selectDate:function(t){var e=this,i=e.opts,s=e.parsedDate,a=e.selectedDates,h=a.length,o="";if(Array.isArray(t))return void t.forEach(function(t){e.selectDate(t)});if(t instanceof Date){if(this.lastSelectedDate=t,this.timepicker&&this.timepicker._setTime(t),e._trigger("selectDate",t),this.timepicker&&(t.setHours(this.timepicker.hours),t.setMinutes(this.timepicker.minutes)),"days"==e.view&&t.getMonth()!=s.month&&i.moveToOtherMonthsOnSelect&&(o=new Date(t.getFullYear(),t.getMonth(),1)),"years"==e.view&&t.getFullYear()!=s.year&&i.moveToOtherYearsOnSelect&&(o=new Date(t.getFullYear(),0,1)),o&&(e.silent=!0,e.date=o,e.silent=!1,e.nav._render()),i.multipleDates&&!i.range){if(h===i.multipleDates)return;e._isSelected(t)||e.selectedDates.push(t)}else i.range?2==h?(e.selectedDates=[t],e.minRange=t,e.maxRange=""):1==h?(e.selectedDates.push(t),e.maxRange?e.minRange=t:e.maxRange=t,n.bigger(e.maxRange,e.minRange)&&(e.maxRange=e.minRange,e.minRange=t),e.selectedDates=[e.minRange,e.maxRange]):(e.selectedDates=[t],e.minRange=t):e.selectedDates=[t];e._setInputValue(),i.onSelect&&e._triggerOnChange(),i.autoClose&&!this.timepickerIsActive&&(i.multipleDates||i.range?i.range&&2==e.selectedDates.length&&e.hide():e.hide()),e.views[this.currentView]._render()}},removeDate:function(t){var e=this.selectedDates,i=this;if(t instanceof Date)return e.some(function(s,a){return n.isSame(s,t)?(e.splice(a,1),i.selectedDates.length?i.lastSelectedDate=i.selectedDates[i.selectedDates.length-1]:(i.minRange="",i.maxRange="",i.lastSelectedDate=""),i.views[i.currentView]._render(),i._setInputValue(),i.opts.onSelect&&i._triggerOnChange(),!0):void 0})},today:function(){this.silent=!0,this.view=this.opts.minView,this.silent=!1,this.date=new Date,this.opts.todayButton instanceof Date&&this.selectDate(this.opts.todayButton)},clear:function(){this.selectedDates=[],this.minRange="",this.maxRange="",this.views[this.currentView]._render(),this._setInputValue(),this.opts.onSelect&&this._triggerOnChange()},update:function(t,i){var s=arguments.length,a=this.lastSelectedDate;return 2==s?this.opts[t]=i:1==s&&"object"==typeof t&&(this.opts=e.extend(!0,this.opts,t)),this._createShortCuts(),this._syncWithMinMaxDates(),this._defineLocale(this.opts.language),this.nav._addButtonsIfNeed(),this.opts.onlyTimepicker||this.nav._render(),this.views[this.currentView]._render(),this.elIsInput&&!this.opts.inline&&(this._setPositionClasses(this.opts.position),this.visible&&this.setPosition(this.opts.position)),this.opts.classes&&this.$datepicker.addClass(this.opts.classes),this.opts.onlyTimepicker&&this.$datepicker.addClass("-only-timepicker-"),this.opts.timepicker&&(a&&this.timepicker._handleDate(a),this.timepicker._updateRanges(),this.timepicker._updateCurrentTime(),a&&(a.setHours(this.timepicker.hours),a.setMinutes(this.timepicker.minutes))),this._setInputValue(),this},_syncWithMinMaxDates:function(){var t=this.date.getTime();this.silent=!0,this.minTime>t&&(this.date=this.minDate),this.maxTime<t&&(this.date=this.maxDate),this.silent=!1},_isSelected:function(t,e){var i=!1;return this.selectedDates.some(function(s){return n.isSame(s,t,e)?(i=s,!0):void 0}),i},_setInputValue:function(){var t,e=this,i=e.opts,s=e.loc.dateFormat,a=i.altFieldDateFormat,n=e.selectedDates.map(function(t){return e.formatDate(s,t)});i.altField&&e.$altField.length&&(t=this.selectedDates.map(function(t){return e.formatDate(a,t)}),t=t.join(this.opts.multipleDatesSeparator),this.$altField.val(t)),n=n.join(this.opts.multipleDatesSeparator),this.$el.val(n)},_isInRange:function(t,e){var i=t.getTime(),s=n.getParsedDate(t),a=n.getParsedDate(this.minDate),h=n.getParsedDate(this.maxDate),o=new Date(s.year,s.month,a.date).getTime(),r=new Date(s.year,s.month,h.date).getTime(),c={day:i>=this.minTime&&i<=this.maxTime,month:o>=this.minTime&&r<=this.maxTime,year:s.year>=a.year&&s.year<=h.year};return e?c[e]:c.day},_getDimensions:function(t){var e=t.offset();return{width:t.outerWidth(),height:t.outerHeight(),left:e.left,top:e.top}},_getDateFromCell:function(t){var e=this.parsedDate,s=t.data("year")||e.year,a=t.data("month")==i?e.month:t.data("month"),n=t.data("date")||1;return new Date(s,a,n)},_setPositionClasses:function(t){t=t.split(" ");var e=t[0],i=t[1],s="datepicker -"+e+"-"+i+"- -from-"+e+"-";this.visible&&(s+=" active"),this.$datepicker.removeAttr("class").addClass(s)},setPosition:function(t){t=t||this.opts.position;var e,i,s=this._getDimensions(this.$el),a=this._getDimensions(this.$datepicker),n=t.split(" "),h=this.opts.offset,o=n[0],r=n[1];switch(o){case"top":e=s.top-a.height-h;break;case"right":i=s.left+s.width+h;break;case"bottom":e=s.top+s.height+h;break;case"left":i=s.left-a.width-h}switch(r){case"top":e=s.top;break;case"right":i=s.left+s.width-a.width;break;case"bottom":e=s.top+s.height-a.height;break;case"left":i=s.left;break;case"center":/left|right/.test(o)?e=s.top+s.height/2-a.height/2:i=s.left+s.width/2-a.width/2}this.$datepicker.css({left:i,top:e})},show:function(){var t=this.opts.onShow;this.setPosition(this.opts.position),this.$datepicker.addClass("active"),this.visible=!0,t&&this._bindVisionEvents(t)},hide:function(){var t=this.opts.onHide;this.$datepicker.removeClass("active").css({left:"-100000px"}),this.focused="",this.keys=[],this.inFocus=!1,this.visible=!1,this.$el.blur(),t&&this._bindVisionEvents(t)},down:function(t){this._changeView(t,"down")},up:function(t){this._changeView(t,"up")},_bindVisionEvents:function(t){this.$datepicker.off("transitionend.dp"),t(this,!1),this.$datepicker.one("transitionend.dp",t.bind(this,this,!0))},_changeView:function(t,e){t=t||this.focused||this.date;var i="up"==e?this.viewIndex+1:this.viewIndex-1;i>2&&(i=2),0>i&&(i=0),this.silent=!0,this.date=new Date(t.getFullYear(),t.getMonth(),1),this.silent=!1,this.view=this.viewIndexes[i]},_handleHotKey:function(t){var e,i,s,a=n.getParsedDate(this._getFocusedDate()),h=this.opts,o=!1,r=!1,c=!1,d=a.year,l=a.month,u=a.date;switch(t){case"ctrlRight":case"ctrlUp":l+=1,o=!0;break;case"ctrlLeft":case"ctrlDown":l-=1,o=!0;break;case"shiftRight":case"shiftUp":r=!0,d+=1;break;case"shiftLeft":case"shiftDown":r=!0,d-=1;break;case"altRight":case"altUp":c=!0,d+=10;break;case"altLeft":case"altDown":c=!0,d-=10;break;case"ctrlShiftUp":this.up()}s=n.getDaysCount(new Date(d,l)),i=new Date(d,l,u),u>s&&(u=s),i.getTime()<this.minTime?i=this.minDate:i.getTime()>this.maxTime&&(i=this.maxDate),this.focused=i,e=n.getParsedDate(i),o&&h.onChangeMonth&&h.onChangeMonth(e.month,e.year),r&&h.onChangeYear&&h.onChangeYear(e.year),c&&h.onChangeDecade&&h.onChangeDecade(this.curDecade)},_registerKey:function(t){var e=this.keys.some(function(e){return e==t});e||this.keys.push(t)},_unRegisterKey:function(t){var e=this.keys.indexOf(t);this.keys.splice(e,1)},_isHotKeyPressed:function(){var t,e=!1,i=this,s=this.keys.sort();for(var a in u)t=u[a],s.length==t.length&&t.every(function(t,e){return t==s[e]})&&(i._trigger("hotKey",a),e=!0);return e},_trigger:function(t,e){this.$el.trigger(t,e)},_focusNextCell:function(t,e){e=e||this.cellType;var i=n.getParsedDate(this._getFocusedDate()),s=i.year,a=i.month,h=i.date;if(!this._isHotKeyPressed()){switch(t){case 37:"day"==e?h-=1:"","month"==e?a-=1:"","year"==e?s-=1:"";break;case 38:"day"==e?h-=7:"","month"==e?a-=3:"","year"==e?s-=4:"";break;case 39:"day"==e?h+=1:"","month"==e?a+=1:"","year"==e?s+=1:"";break;case 40:"day"==e?h+=7:"","month"==e?a+=3:"","year"==e?s+=4:""}var o=new Date(s,a,h);o.getTime()<this.minTime?o=this.minDate:o.getTime()>this.maxTime&&(o=this.maxDate),this.focused=o}},_getFocusedDate:function(){var t=this.focused||this.selectedDates[this.selectedDates.length-1],e=this.parsedDate;if(!t)switch(this.view){case"days":t=new Date(e.year,e.month,(new Date).getDate());break;case"months":t=new Date(e.year,e.month,1);break;case"years":t=new Date(e.year,0,1)}return t},_getCell:function(t,i){i=i||this.cellType;var s,a=n.getParsedDate(t),h='.datepicker--cell[data-year="'+a.year+'"]';switch(i){case"month":h='[data-month="'+a.month+'"]';break;case"day":h+='[data-month="'+a.month+'"][data-date="'+a.date+'"]'}return s=this.views[this.currentView].$el.find(h),s.length?s:e("")},destroy:function(){var t=this;t.$el.off(".adp").data("datepicker",""),t.selectedDates=[],t.focused="",t.views={},t.keys=[],t.minRange="",t.maxRange="",t.opts.inline||!t.elIsInput?t.$datepicker.closest(".datepicker-inline").remove():t.$datepicker.remove()},_handleAlreadySelectedDates:function(t,e){this.opts.range?this.opts.toggleSelected?this.removeDate(e):2!=this.selectedDates.length&&this._trigger("clickCell",e):this.opts.toggleSelected&&this.removeDate(e),this.opts.toggleSelected||(this.lastSelectedDate=t,this.opts.timepicker&&(this.timepicker._setTime(t),this.timepicker.update()))},_onShowEvent:function(t){this.visible||this.show()},_onBlur:function(){!this.inFocus&&this.visible&&this.hide()},_onMouseDownDatepicker:function(t){this.inFocus=!0},_onMouseUpDatepicker:function(t){this.inFocus=!1,t.originalEvent.inFocus=!0,t.originalEvent.timepickerFocus||this.$el.focus()},_onKeyUpGeneral:function(t){var e=this.$el.val();e||this.clear()},_onResize:function(){this.visible&&this.setPosition()},_onMouseUpBody:function(t){t.originalEvent.inFocus||this.visible&&!this.inFocus&&this.hide()},_onMouseUpEl:function(t){t.originalEvent.inFocus=!0,setTimeout(this._onKeyUpGeneral.bind(this),4)},_onKeyDown:function(t){var e=t.which;if(this._registerKey(e),e>=37&&40>=e&&(t.preventDefault(),this._focusNextCell(e)),13==e&&this.focused){if(this._getCell(this.focused).hasClass("-disabled-"))return;if(this.view!=this.opts.minView)this.down();else{var i=this._isSelected(this.focused,this.cellType);if(!i)return this.timepicker&&(this.focused.setHours(this.timepicker.hours),this.focused.setMinutes(this.timepicker.minutes)),void this.selectDate(this.focused);this._handleAlreadySelectedDates(i,this.focused)}}27==e&&this.hide()},_onKeyUp:function(t){var e=t.which;this._unRegisterKey(e)},_onHotKey:function(t,e){this._handleHotKey(e)},_onMouseEnterCell:function(t){var i=e(t.target).closest(".datepicker--cell"),s=this._getDateFromCell(i);this.silent=!0,this.focused&&(this.focused=""),i.addClass("-focus-"),this.focused=s,this.silent=!1,this.opts.range&&1==this.selectedDates.length&&(this.minRange=this.selectedDates[0],this.maxRange="",n.less(this.minRange,this.focused)&&(this.maxRange=this.minRange,this.minRange=""),this.views[this.currentView]._update())},_onMouseLeaveCell:function(t){var i=e(t.target).closest(".datepicker--cell");i.removeClass("-focus-"),this.silent=!0,this.focused="",this.silent=!1},_onTimeChange:function(t,e,i){var s=new Date,a=this.selectedDates,n=!1;a.length&&(n=!0,s=this.lastSelectedDate),s.setHours(e),s.setMinutes(i),n||this._getCell(s).hasClass("-disabled-")?(this._setInputValue(),this.opts.onSelect&&this._triggerOnChange()):this.selectDate(s)},_onClickCell:function(t,e){this.timepicker&&(e.setHours(this.timepicker.hours),e.setMinutes(this.timepicker.minutes)),this.selectDate(e)},set focused(t){if(!t&&this.focused){var e=this._getCell(this.focused);e.length&&e.removeClass("-focus-")}this._focused=t,this.opts.range&&1==this.selectedDates.length&&(this.minRange=this.selectedDates[0],this.maxRange="",n.less(this.minRange,this._focused)&&(this.maxRange=this.minRange,this.minRange="")),this.silent||(this.date=t)},get focused(){return this._focused},get parsedDate(){return n.getParsedDate(this.date)},set date(t){return t instanceof Date?(this.currentDate=t,this.inited&&!this.silent&&(this.views[this.view]._render(),this.nav._render(),this.visible&&this.elIsInput&&this.setPosition()),t):void 0},get date(){return this.currentDate},set view(t){return this.viewIndex=this.viewIndexes.indexOf(t),this.viewIndex<0?void 0:(this.prevView=this.currentView,this.currentView=t,this.inited&&(this.views[t]?this.views[t]._render():this.views[t]=new e.fn.datepicker.Body(this,t,this.opts),this.views[this.prevView].hide(),this.views[t].show(),this.nav._render(),this.opts.onChangeView&&this.opts.onChangeView(t),this.elIsInput&&this.visible&&this.setPosition()),t)},get view(){return this.currentView},get cellType(){return this.view.substring(0,this.view.length-1)},get minTime(){var t=n.getParsedDate(this.minDate);return new Date(t.year,t.month,t.date).getTime()},get maxTime(){var t=n.getParsedDate(this.maxDate);return new Date(t.year,t.month,t.date).getTime()},get curDecade(){return n.getDecade(this.date)}},n.getDaysCount=function(t){return new Date(t.getFullYear(),t.getMonth()+1,0).getDate()},n.getParsedDate=function(t){return{year:t.getFullYear(),month:t.getMonth(),fullMonth:t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,date:t.getDate(),fullDate:t.getDate()<10?"0"+t.getDate():t.getDate(),day:t.getDay(),hours:t.getHours(),fullHours:t.getHours()<10?"0"+t.getHours():t.getHours(),minutes:t.getMinutes(),fullMinutes:t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes()}},n.getDecade=function(t){var e=10*Math.floor(t.getFullYear()/10);return[e,e+9]},n.template=function(t,e){return t.replace(/#\{([\w]+)\}/g,function(t,i){return e[i]||0===e[i]?e[i]:void 0})},n.isSame=function(t,e,i){if(!t||!e)return!1;var s=n.getParsedDate(t),a=n.getParsedDate(e),h=i?i:"day",o={day:s.date==a.date&&s.month==a.month&&s.year==a.year,month:s.month==a.month&&s.year==a.year,year:s.year==a.year};return o[h]},n.less=function(t,e,i){return t&&e?e.getTime()<t.getTime():!1},n.bigger=function(t,e,i){return t&&e?e.getTime()>t.getTime():!1},n.getLeadingZeroNum=function(t){return parseInt(t)<10?"0"+t:t},n.resetTime=function(t){return"object"==typeof t?(t=n.getParsedDate(t),new Date(t.year,t.month,t.date)):void 0},e.fn.datepicker=function(t){return this.each(function(){if(e.data(this,o)){var i=e.data(this,o);i.opts=e.extend(!0,i.opts,t),i.update()}else e.data(this,o,new m(this,t))})},e.fn.datepicker.Constructor=m,e.fn.datepicker.language={ru:{days:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"],daysShort:["Вос","Пон","Вто","Сре","Чет","Пят","Суб"],daysMin:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"],months:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],monthsShort:["Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек"],today:"Сегодня",clear:"Очистить",dateFormat:"dd.mm.yyyy",timeFormat:"hh:ii",firstDay:1}},e(function(){e(r).datepicker()})}(),function(){var t={days:'<div class="datepicker--days datepicker--body"><div class="datepicker--days-names"></div><div class="datepicker--cells datepicker--cells-days"></div></div>',months:'<div class="datepicker--months datepicker--body"><div class="datepicker--cells datepicker--cells-months"></div></div>',years:'<div class="datepicker--years datepicker--body"><div class="datepicker--cells datepicker--cells-years"></div></div>'},s=e.fn.datepicker,a=s.Constructor;s.Body=function(t,i,s){this.d=t,this.type=i,this.opts=s,this.$el=e(""),this.opts.onlyTimepicker||this.init()},s.Body.prototype={init:function(){this._buildBaseHtml(),this._render(),this._bindEvents()},_bindEvents:function(){this.$el.on("click",".datepicker--cell",e.proxy(this._onClickCell,this))},_buildBaseHtml:function(){this.$el=e(t[this.type]).appendTo(this.d.$content),this.$names=e(".datepicker--days-names",this.$el),this.$cells=e(".datepicker--cells",this.$el)},_getDayNamesHtml:function(t,e,s,a){return e=e!=i?e:t,s=s?s:"",a=a!=i?a:0,a>7?s:7==e?this._getDayNamesHtml(t,0,s,++a):(s+='<div class="datepicker--day-name'+(this.d.isWeekend(e)?" -weekend-":"")+'">'+this.d.loc.daysMin[e]+"</div>",this._getDayNamesHtml(t,++e,s,++a))},_getCellContents:function(t,e){var i="datepicker--cell datepicker--cell-"+e,s=new Date,n=this.d,h=a.resetTime(n.minRange),o=a.resetTime(n.maxRange),r=n.opts,c=a.getParsedDate(t),d={},l=c.date;switch(e){case"day":n.isWeekend(c.day)&&(i+=" -weekend-"),c.month!=this.d.parsedDate.month&&(i+=" -other-month-",r.selectOtherMonths||(i+=" -disabled-"),r.showOtherMonths||(l=""));break;case"month":l=n.loc[n.opts.monthsField][c.month];break;case"year":var u=n.curDecade;l=c.year,(c.year<u[0]||c.year>u[1])&&(i+=" -other-decade-",r.selectOtherYears||(i+=" -disabled-"),r.showOtherYears||(l=""))}return r.onRenderCell&&(d=r.onRenderCell(t,e)||{},l=d.html?d.html:l,i+=d.classes?" "+d.classes:""),r.range&&(a.isSame(h,t,e)&&(i+=" -range-from-"),a.isSame(o,t,e)&&(i+=" -range-to-"),1==n.selectedDates.length&&n.focused?((a.bigger(h,t)&&a.less(n.focused,t)||a.less(o,t)&&a.bigger(n.focused,t))&&(i+=" -in-range-"),a.less(o,t)&&a.isSame(n.focused,t)&&(i+=" -range-from-"),a.bigger(h,t)&&a.isSame(n.focused,t)&&(i+=" -range-to-")):2==n.selectedDates.length&&a.bigger(h,t)&&a.less(o,t)&&(i+=" -in-range-")),a.isSame(s,t,e)&&(i+=" -current-"),n.focused&&a.isSame(t,n.focused,e)&&(i+=" -focus-"),n._isSelected(t,e)&&(i+=" -selected-"),(!n._isInRange(t,e)||d.disabled)&&(i+=" -disabled-"),{html:l,classes:i}},_getDaysHtml:function(t){var e=a.getDaysCount(t),i=new Date(t.getFullYear(),t.getMonth(),1).getDay(),s=new Date(t.getFullYear(),t.getMonth(),e).getDay(),n=i-this.d.loc.firstDay,h=6-s+this.d.loc.firstDay;n=0>n?n+7:n,h=h>6?h-7:h;for(var o,r,c=-n+1,d="",l=c,u=e+h;u>=l;l++)r=t.getFullYear(),o=t.getMonth(),d+=this._getDayHtml(new Date(r,o,l));return d},_getDayHtml:function(t){var e=this._getCellContents(t,"day");return'<div class="'+e.classes+'" data-date="'+t.getDate()+'" data-month="'+t.getMonth()+'" data-year="'+t.getFullYear()+'">'+e.html+"</div>"},_getMonthsHtml:function(t){for(var e="",i=a.getParsedDate(t),s=0;12>s;)e+=this._getMonthHtml(new Date(i.year,s)),s++;return e},_getMonthHtml:function(t){var e=this._getCellContents(t,"month");return'<div class="'+e.classes+'" data-month="'+t.getMonth()+'">'+e.html+"</div>"},_getYearsHtml:function(t){var e=(a.getParsedDate(t),a.getDecade(t)),i=e[0]-1,s="",n=i;for(n;n<=e[1]+1;n++)s+=this._getYearHtml(new Date(n,0));return s},_getYearHtml:function(t){var e=this._getCellContents(t,"year");return'<div class="'+e.classes+'" data-year="'+t.getFullYear()+'">'+e.html+"</div>"},_renderTypes:{days:function(){var t=this._getDayNamesHtml(this.d.loc.firstDay),e=this._getDaysHtml(this.d.currentDate);this.$cells.html(e),this.$names.html(t)},months:function(){var t=this._getMonthsHtml(this.d.currentDate);this.$cells.html(t)},years:function(){var t=this._getYearsHtml(this.d.currentDate);this.$cells.html(t)}},_render:function(){this.opts.onlyTimepicker||this._renderTypes[this.type].bind(this)()},_update:function(){var t,i,s,a=e(".datepicker--cell",this.$cells),n=this;a.each(function(a,h){i=e(this),s=n.d._getDateFromCell(e(this)),t=n._getCellContents(s,n.d.cellType),i.attr("class",t.classes)})},show:function(){this.opts.onlyTimepicker||(this.$el.addClass("active"),this.acitve=!0)},hide:function(){this.$el.removeClass("active"),this.active=!1},_handleClick:function(t){var e=t.data("date")||1,i=t.data("month")||0,s=t.data("year")||this.d.parsedDate.year,a=this.d;if(a.view!=this.opts.minView)return void a.down(new Date(s,i,e));var n=new Date(s,i,e),h=this.d._isSelected(n,this.d.cellType);return h?void a._handleAlreadySelectedDates.bind(a,h,n)():void a._trigger("clickCell",n)},_onClickCell:function(t){var i=e(t.target).closest(".datepicker--cell");i.hasClass("-disabled-")||this._handleClick.bind(this)(i)}}}(),function(){var t='<div class="datepicker--nav-action" data-action="prev">#{prevHtml}</div><div class="datepicker--nav-title">#{title}</div><div class="datepicker--nav-action" data-action="next">#{nextHtml}</div>',i='<div class="datepicker--buttons"></div>',s='<span class="datepicker--button" data-action="#{action}">#{label}</span>',a=e.fn.datepicker,n=a.Constructor;a.Navigation=function(t,e){this.d=t,this.opts=e,this.$buttonsContainer="",this.init()},a.Navigation.prototype={init:function(){this._buildBaseHtml(),this._bindEvents()},_bindEvents:function(){this.d.$nav.on("click",".datepicker--nav-action",e.proxy(this._onClickNavButton,this)),this.d.$nav.on("click",".datepicker--nav-title",e.proxy(this._onClickNavTitle,this)),this.d.$datepicker.on("click",".datepicker--button",e.proxy(this._onClickNavButton,this))},_buildBaseHtml:function(){this.opts.onlyTimepicker||this._render(),this._addButtonsIfNeed()},_addButtonsIfNeed:function(){this.opts.todayButton&&this._addButton("today"),this.opts.clearButton&&this._addButton("clear")},_render:function(){var i=this._getTitle(this.d.currentDate),s=n.template(t,e.extend({title:i},this.opts));this.d.$nav.html(s),"years"==this.d.view&&e(".datepicker--nav-title",this.d.$nav).addClass("-disabled-"),this.setNavStatus()},_getTitle:function(t){return this.d.formatDate(this.opts.navTitles[this.d.view],t)},_addButton:function(t){this.$buttonsContainer.length||this._addButtonsContainer();var i={action:t,label:this.d.loc[t]},a=n.template(s,i);e("[data-action="+t+"]",this.$buttonsContainer).length||this.$buttonsContainer.append(a)},_addButtonsContainer:function(){this.d.$datepicker.append(i),this.$buttonsContainer=e(".datepicker--buttons",this.d.$datepicker)},setNavStatus:function(){if((this.opts.minDate||this.opts.maxDate)&&this.opts.disableNavWhenOutOfRange){var t=this.d.parsedDate,e=t.month,i=t.year,s=t.date;switch(this.d.view){case"days":this.d._isInRange(new Date(i,e-1,1),"month")||this._disableNav("prev"),this.d._isInRange(new Date(i,e+1,1),"month")||this._disableNav("next");break;case"months":this.d._isInRange(new Date(i-1,e,s),"year")||this._disableNav("prev"),this.d._isInRange(new Date(i+1,e,s),"year")||this._disableNav("next");break;case"years":var a=n.getDecade(this.d.date);this.d._isInRange(new Date(a[0]-1,0,1),"year")||this._disableNav("prev"),this.d._isInRange(new Date(a[1]+1,0,1),"year")||this._disableNav("next")}}},_disableNav:function(t){e('[data-action="'+t+'"]',this.d.$nav).addClass("-disabled-")},_activateNav:function(t){e('[data-action="'+t+'"]',this.d.$nav).removeClass("-disabled-")},_onClickNavButton:function(t){var i=e(t.target).closest("[data-action]"),s=i.data("action");this.d[s]()},_onClickNavTitle:function(t){return e(t.target).hasClass("-disabled-")?void 0:"days"==this.d.view?this.d.view="months":void(this.d.view="years")}}}(),function(){var t='<div class="datepicker--time"><div class="datepicker--time-current">   <span class="datepicker--time-current-hours">#{hourVisible}</span>   <span class="datepicker--time-current-colon">:</span>   <span class="datepicker--time-current-minutes">#{minValue}</span></div><div class="datepicker--time-sliders">   <div class="datepicker--time-row">      <input type="range" name="hours" value="#{hourValue}" min="#{hourMin}" max="#{hourMax}" step="#{hourStep}"/>   </div>   <div class="datepicker--time-row">      <input type="range" name="minutes" value="#{minValue}" min="#{minMin}" max="#{minMax}" step="#{minStep}"/>   </div></div></div>',i=e.fn.datepicker,s=i.Constructor;i.Timepicker=function(t,e){this.d=t,this.opts=e,this.init()},i.Timepicker.prototype={init:function(){var t="input";this._setTime(this.d.date),this._buildHTML(),navigator.userAgent.match(/trident/gi)&&(t="change"),this.d.$el.on("selectDate",this._onSelectDate.bind(this)),this.$ranges.on(t,this._onChangeRange.bind(this)),this.$ranges.on("mouseup",this._onMouseUpRange.bind(this)),this.$ranges.on("mousemove focus ",this._onMouseEnterRange.bind(this)),this.$ranges.on("mouseout blur",this._onMouseOutRange.bind(this))},_setTime:function(t){var e=s.getParsedDate(t);this._handleDate(t),this.hours=e.hours<this.minHours?this.minHours:e.hours,this.minutes=e.minutes<this.minMinutes?this.minMinutes:e.minutes},_setMinTimeFromDate:function(t){this.minHours=t.getHours(),this.minMinutes=t.getMinutes(),this.d.lastSelectedDate&&this.d.lastSelectedDate.getHours()>t.getHours()&&(this.minMinutes=this.opts.minMinutes)},_setMaxTimeFromDate:function(t){
this.maxHours=t.getHours(),this.maxMinutes=t.getMinutes(),this.d.lastSelectedDate&&this.d.lastSelectedDate.getHours()<t.getHours()&&(this.maxMinutes=this.opts.maxMinutes)},_setDefaultMinMaxTime:function(){var t=23,e=59,i=this.opts;this.minHours=i.minHours<0||i.minHours>t?0:i.minHours,this.minMinutes=i.minMinutes<0||i.minMinutes>e?0:i.minMinutes,this.maxHours=i.maxHours<0||i.maxHours>t?t:i.maxHours,this.maxMinutes=i.maxMinutes<0||i.maxMinutes>e?e:i.maxMinutes},_validateHoursMinutes:function(t){this.hours<this.minHours?this.hours=this.minHours:this.hours>this.maxHours&&(this.hours=this.maxHours),this.minutes<this.minMinutes?this.minutes=this.minMinutes:this.minutes>this.maxMinutes&&(this.minutes=this.maxMinutes)},_buildHTML:function(){var i=s.getLeadingZeroNum,a={hourMin:this.minHours,hourMax:i(this.maxHours),hourStep:this.opts.hoursStep,hourValue:this.hours,hourVisible:i(this.displayHours),minMin:this.minMinutes,minMax:i(this.maxMinutes),minStep:this.opts.minutesStep,minValue:i(this.minutes)},n=s.template(t,a);this.$timepicker=e(n).appendTo(this.d.$datepicker),this.$ranges=e('[type="range"]',this.$timepicker),this.$hours=e('[name="hours"]',this.$timepicker),this.$minutes=e('[name="minutes"]',this.$timepicker),this.$hoursText=e(".datepicker--time-current-hours",this.$timepicker),this.$minutesText=e(".datepicker--time-current-minutes",this.$timepicker),this.d.ampm&&(this.$ampm=e('<span class="datepicker--time-current-ampm">').appendTo(e(".datepicker--time-current",this.$timepicker)).html(this.dayPeriod),this.$timepicker.addClass("-am-pm-"))},_updateCurrentTime:function(){var t=s.getLeadingZeroNum(this.displayHours),e=s.getLeadingZeroNum(this.minutes);this.$hoursText.html(t),this.$minutesText.html(e),this.d.ampm&&this.$ampm.html(this.dayPeriod)},_updateRanges:function(){this.$hours.attr({min:this.minHours,max:this.maxHours}).val(this.hours),this.$minutes.attr({min:this.minMinutes,max:this.maxMinutes}).val(this.minutes)},_handleDate:function(t){this._setDefaultMinMaxTime(),t&&(s.isSame(t,this.d.opts.minDate)?this._setMinTimeFromDate(this.d.opts.minDate):s.isSame(t,this.d.opts.maxDate)&&this._setMaxTimeFromDate(this.d.opts.maxDate)),this._validateHoursMinutes(t)},update:function(){this._updateRanges(),this._updateCurrentTime()},_getValidHoursFromDate:function(t,e){var i=t,a=t;t instanceof Date&&(i=s.getParsedDate(t),a=i.hours);var n=e||this.d.ampm,h="am";if(n)switch(!0){case 0==a:a=12;break;case 12==a:h="pm";break;case a>11:a-=12,h="pm"}return{hours:a,dayPeriod:h}},set hours(t){this._hours=t;var e=this._getValidHoursFromDate(t);this.displayHours=e.hours,this.dayPeriod=e.dayPeriod},get hours(){return this._hours},_onChangeRange:function(t){var i=e(t.target),s=i.attr("name");this.d.timepickerIsActive=!0,this[s]=i.val(),this._updateCurrentTime(),this.d._trigger("timeChange",[this.hours,this.minutes]),this._handleDate(this.d.lastSelectedDate),this.update()},_onSelectDate:function(t,e){this._handleDate(e),this.update()},_onMouseEnterRange:function(t){var i=e(t.target).attr("name");e(".datepicker--time-current-"+i,this.$timepicker).addClass("-focus-")},_onMouseOutRange:function(t){var i=e(t.target).attr("name");this.d.inFocus||e(".datepicker--time-current-"+i,this.$timepicker).removeClass("-focus-")},_onMouseUpRange:function(t){this.d.timepickerIsActive=!1}}}()}(window,jQuery);;
/*!
 * jQuery Mobile Virtual Mouse @VERSION
 * http://jquerymobile.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Virtual Mouse (vmouse) Bindings
//>>group: Core
//>>description: Normalizes touch/mouse events.
//>>docs: http://api.jquerymobile.com/?s=vmouse

// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"

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

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

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

var dataPropertyName = "virtualMouseBindings",
	touchTargetPropertyName = "virtualTouchID",
	touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
	virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
	generalProps = ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " +
		"metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ),
	mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
	mouseEventProps = generalProps.concat( mouseHookProps ),
	activeDocHandlers = {},
	resetTimerID = 0,
	startX = 0,
	startY = 0,
	didScroll = false,
	clickBlockList = [],
	blockMouseTriggers = false,
	blockTouchTriggers = false,
	eventCaptureSupported = "addEventListener" in document,
	$document = $( document ),
	nextTouchID = 1,
	lastTouchID = 0, threshold,
	i;

$.vmouse = {
	moveDistanceThreshold: 10,
	clickDistanceThreshold: 10,
	resetTimerDuration: 1500,
	maximumTimeBetweenTouches: 100
};

function getNativeEvent( event ) {

	while ( event && typeof event.originalEvent !== "undefined" ) {
		event = event.originalEvent;
	}
	return event;
}

function createVirtualEvent( event, eventType ) {

	var t = event.type,
		oe, props, ne, prop, ct, touch, i, j, len;

	event = $.Event( event );
	event.type = eventType;

	oe = event.originalEvent;
	props = generalProps;

	// addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
	// https://github.com/jquery/jquery-mobile/issues/3280
	if ( t.search( /^(mouse|click)/ ) > -1 ) {
		props = mouseEventProps;
	}

	// copy original event properties over to the new event
	// this would happen if we could call $.event.fix instead of $.Event
	// but we don't have a way to force an event to be fixed multiple times
	if ( oe ) {
		for ( i = props.length; i; ) {
			prop = props[ --i ];
			event[ prop ] = oe[ prop ];
		}
	}

	// make sure that if the mouse and click virtual events are generated
	// without a .which one is defined
	if ( t.search( /mouse(down|up)|click/ ) > -1 && !event.which ) {
		event.which = 1;
	}

	if ( t.search( /^touch/ ) !== -1 ) {
		ne = getNativeEvent( oe );
		t = ne.touches;
		ct = ne.changedTouches;
		touch = ( t && t.length ) ? t[ 0 ] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined );

		if ( touch ) {
			for ( j = 0, len = touchEventProps.length; j < len; j++ ) {
				prop = touchEventProps[ j ];
				event[ prop ] = touch[ prop ];
			}
		}
	}

	return event;
}

function getVirtualBindingFlags( element ) {

	var flags = {},
		b, k;

	while ( element ) {

		b = $.data( element, dataPropertyName );

		for ( k in b ) {
			if ( b[ k ] ) {
				flags[ k ] = flags.hasVirtualBinding = true;
			}
		}
		element = element.parentNode;
	}
	return flags;
}

function getClosestElementWithVirtualBinding( element, eventType ) {
	var b;
	while ( element ) {

		b = $.data( element, dataPropertyName );

		if ( b && ( !eventType || b[ eventType ] ) ) {
			return element;
		}
		element = element.parentNode;
	}
	return null;
}

function enableTouchBindings() {
	blockTouchTriggers = false;
}

function disableTouchBindings() {
	blockTouchTriggers = true;
}

function enableMouseBindings() {
	lastTouchID = 0;
	clickBlockList.length = 0;
	blockMouseTriggers = false;

	// When mouse bindings are enabled, our
	// touch bindings are disabled.
	disableTouchBindings();
}

function disableMouseBindings() {
	// When mouse bindings are disabled, our
	// touch bindings are enabled.
	enableTouchBindings();
}

function clearResetTimer() {
	if ( resetTimerID ) {
		clearTimeout( resetTimerID );
		resetTimerID = 0;
	}
}

function startResetTimer() {
	clearResetTimer();
	resetTimerID = setTimeout( function() {
		resetTimerID = 0;
		enableMouseBindings();
	}, $.vmouse.resetTimerDuration );
}

function triggerVirtualEvent( eventType, event, flags ) {
	var ve;

	if ( ( flags && flags[ eventType ] ) ||
			( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {

		ve = createVirtualEvent( event, eventType );

		$( event.target ).trigger( ve );
	}

	return ve;
}

function mouseEventCallback( event ) {
	var touchID = $.data( event.target, touchTargetPropertyName ),
		ve;

	// It is unexpected if a click event is received before a touchend
	// or touchmove event, however this is a known behavior in Mobile
	// Safari when Mobile VoiceOver (as of iOS 8) is enabled and the user
	// double taps to activate a link element. In these cases if a touch
	// event is not received within the maximum time between touches,
	// re-enable mouse bindings and call the mouse event handler again.
	if ( event.type === "click" && $.data( event.target, "lastTouchType" ) === "touchstart" ) {
		setTimeout( function() {
			if ( $.data( event.target, "lastTouchType" ) === "touchstart" ) {
				enableMouseBindings();
				delete $.data( event.target ).lastTouchType;
				mouseEventCallback( event );
			}
		}, $.vmouse.maximumTimeBetweenTouches );
	}

	if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) {
		ve = triggerVirtualEvent( "v" + event.type, event );
		if ( ve ) {
			if ( ve.isDefaultPrevented() ) {
				event.preventDefault();
			}
			if ( ve.isPropagationStopped() ) {
				event.stopPropagation();
			}
			if ( ve.isImmediatePropagationStopped() ) {
				event.stopImmediatePropagation();
			}
		}
	}
}

function handleTouchStart( event ) {

	var touches = getNativeEvent( event ).touches,
		target, flags, t;

	if ( touches && touches.length === 1 ) {

		target = event.target;
		flags = getVirtualBindingFlags( target );

		$.data( event.target, "lastTouchType", event.type );

		if ( flags.hasVirtualBinding ) {

			lastTouchID = nextTouchID++;
			$.data( target, touchTargetPropertyName, lastTouchID );

			clearResetTimer();

			disableMouseBindings();
			didScroll = false;

			t = getNativeEvent( event ).touches[ 0 ];
			startX = t.pageX;
			startY = t.pageY;

			triggerVirtualEvent( "vmouseover", event, flags );
			triggerVirtualEvent( "vmousedown", event, flags );
		}
	}
}

function handleScroll( event ) {
	if ( blockTouchTriggers ) {
		return;
	}

	if ( !didScroll ) {
		triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
	}

	$.data( event.target, "lastTouchType", event.type );

	didScroll = true;
	startResetTimer();
}

function handleTouchMove( event ) {
	if ( blockTouchTriggers ) {
		return;
	}

	var t = getNativeEvent( event ).touches[ 0 ],
		didCancel = didScroll,
		moveThreshold = $.vmouse.moveDistanceThreshold,
		flags = getVirtualBindingFlags( event.target );

	$.data( event.target, "lastTouchType", event.type );

	didScroll = didScroll ||
		( Math.abs( t.pageX - startX ) > moveThreshold ||
		Math.abs( t.pageY - startY ) > moveThreshold );

	if ( didScroll && !didCancel ) {
		triggerVirtualEvent( "vmousecancel", event, flags );
	}

	triggerVirtualEvent( "vmousemove", event, flags );
	startResetTimer();
}

function handleTouchEnd( event ) {
	if ( blockTouchTriggers || $.data( event.target, "lastTouchType" ) === undefined ) {
		return;
	}

	disableTouchBindings();
	delete $.data( event.target ).lastTouchType;

	var flags = getVirtualBindingFlags( event.target ),
		ve, t;
	triggerVirtualEvent( "vmouseup", event, flags );

	if ( !didScroll ) {
		ve = triggerVirtualEvent( "vclick", event, flags );
		if ( ve && ve.isDefaultPrevented() ) {
			// The target of the mouse events that follow the touchend
			// event don't necessarily match the target used during the
			// touch. This means we need to rely on coordinates for blocking
			// any click that is generated.
			t = getNativeEvent( event ).changedTouches[ 0 ];
			clickBlockList.push( {
				touchID: lastTouchID,
				x: t.clientX,
				y: t.clientY
			} );

			// Prevent any mouse events that follow from triggering
			// virtual event notifications.
			blockMouseTriggers = true;
		}
	}
	triggerVirtualEvent( "vmouseout", event, flags );
	didScroll = false;

	startResetTimer();
}

function hasVirtualBindings( ele ) {
	var bindings = $.data( ele, dataPropertyName ),
		k;

	if ( bindings ) {
		for ( k in bindings ) {
			if ( bindings[ k ] ) {
				return true;
			}
		}
	}
	return false;
}

function dummyMouseHandler() {
}

function getSpecialEventObject( eventType ) {
	var realType = eventType.substr( 1 );

	return {
		setup: function( /* data, namespace */ ) {
			// If this is the first virtual mouse binding for this element,
			// add a bindings object to its data.

			if ( !hasVirtualBindings( this ) ) {
				$.data( this, dataPropertyName, {} );
			}

			// If setup is called, we know it is the first binding for this
			// eventType, so initialize the count for the eventType to zero.
			var bindings = $.data( this, dataPropertyName );
			bindings[ eventType ] = true;

			// If this is the first virtual mouse event for this type,
			// register a global handler on the document.

			activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;

			if ( activeDocHandlers[ eventType ] === 1 ) {
				$document.bind( realType, mouseEventCallback );
			}

			// Some browsers, like Opera Mini, won't dispatch mouse/click events
			// for elements unless they actually have handlers registered on them.
			// To get around this, we register dummy handlers on the elements.

			$( this ).bind( realType, dummyMouseHandler );

			// For now, if event capture is not supported, we rely on mouse handlers.
			if ( eventCaptureSupported ) {
				// If this is the first virtual mouse binding for the document,
				// register our touchstart handler on the document.

				activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0 ) + 1;

				if ( activeDocHandlers[ "touchstart" ] === 1 ) {
					$document.bind( "touchstart", handleTouchStart )
						.bind( "touchend", handleTouchEnd )

						// On touch platforms, touching the screen and then dragging your finger
						// causes the window content to scroll after some distance threshold is
						// exceeded. On these platforms, a scroll prevents a click event from being
						// dispatched, and on some platforms, even the touchend is suppressed. To
						// mimic the suppression of the click event, we need to watch for a scroll
						// event. Unfortunately, some platforms like iOS don't dispatch scroll
						// events until *AFTER* the user lifts their finger (touchend). This means
						// we need to watch both scroll and touchmove events to figure out whether
						// or not a scroll happenens before the touchend event is fired.

						.bind( "touchmove", handleTouchMove )
						.bind( "scroll", handleScroll );
				}
			}
		},

		teardown: function( /* data, namespace */ ) {
			// If this is the last virtual binding for this eventType,
			// remove its global handler from the document.

			--activeDocHandlers[eventType];

			if ( !activeDocHandlers[ eventType ] ) {
				$document.unbind( realType, mouseEventCallback );
			}

			if ( eventCaptureSupported ) {
				// If this is the last virtual mouse binding in existence,
				// remove our document touchstart listener.

				--activeDocHandlers["touchstart"];

				if ( !activeDocHandlers[ "touchstart" ] ) {
					$document.unbind( "touchstart", handleTouchStart )
						.unbind( "touchmove", handleTouchMove )
						.unbind( "touchend", handleTouchEnd )
						.unbind( "scroll", handleScroll );
				}
			}

			var $this = $( this ),
				bindings = $.data( this, dataPropertyName );

			// teardown may be called when an element was
			// removed from the DOM. If this is the case,
			// jQuery core may have already stripped the element
			// of any data bindings so we need to check it before
			// using it.
			if ( bindings ) {
				bindings[ eventType ] = false;
			}

			// Unregister the dummy event handler.

			$this.unbind( realType, dummyMouseHandler );

			// If this is the last virtual mouse binding on the
			// element, remove the binding data from the element.

			if ( !hasVirtualBindings( this ) ) {
				$this.removeData( dataPropertyName );
			}
		}
	};
}

// Expose our custom events to the jQuery bind/unbind mechanism.

for ( i = 0; i < virtualEventNames.length; i++ ) {
	$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
}

// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if ( eventCaptureSupported ) {
	document.addEventListener( "click", function( e ) {
		var cnt = clickBlockList.length,
			target = e.target,
			x, y, ele, i, o, touchID;

		if ( cnt ) {
			x = e.clientX;
			y = e.clientY;
			threshold = $.vmouse.clickDistanceThreshold;

			// The idea here is to run through the clickBlockList to see if
			// the current click event is in the proximity of one of our
			// vclick events that had preventDefault() called on it. If we find
			// one, then we block the click.
			//
			// Why do we have to rely on proximity?
			//
			// Because the target of the touch event that triggered the vclick
			// can be different from the target of the click event synthesized
			// by the browser. The target of a mouse/click event that is synthesized
			// from a touch event seems to be implementation specific. For example,
			// some browsers will fire mouse/click events for a link that is near
			// a touch event, even though the target of the touchstart/touchend event
			// says the user touched outside the link. Also, it seems that with most
			// browsers, the target of the mouse/click event is not calculated until the
			// time it is dispatched, so if you replace an element that you touched
			// with another element, the target of the mouse/click will be the new
			// element underneath that point.
			//
			// Aside from proximity, we also check to see if the target and any
			// of its ancestors were the ones that blocked a click. This is necessary
			// because of the strange mouse/click target calculation done in the
			// Android 2.1 browser, where if you click on an element, and there is a
			// mouse/click handler on one of its ancestors, the target will be the
			// innermost child of the touched element, even if that child is no where
			// near the point of touch.

			ele = target;

			while ( ele ) {
				for ( i = 0; i < cnt; i++ ) {
					o = clickBlockList[ i ];
					touchID = 0;

					if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
							$.data( ele, touchTargetPropertyName ) === o.touchID ) {
						// XXX: We may want to consider removing matches from the block list
						//      instead of waiting for the reset timer to fire.
						e.preventDefault();
						e.stopPropagation();
						return;
					}
				}
				ele = ele.parentNode;
			}
		}
	}, true );
}
} );
;
//Rocco Hero slider 
var slideWrapper = $(".main-slider"),
    iframes = slideWrapper.find('.embed-player'),
    lazyImages = slideWrapper.find('.slide-image'),
    lazyCounter = 0,
    currentPlayer,
    playerState = false,
    playerInterval;

// POST commands to YouTube or Vimeo API
function postMessageToPlayer(player, command) {
    if (player == null || command == null)
        return;
    player.contentWindow.postMessage(JSON.stringify(command), "*");
}

// When the slide is changing
function playPauseVideo(slick, control) {
    var currentSlide, slideType, startTime, player, video;
    currentSlide = slick.find(".slick-active");

    if (currentSlide.length === 0) {
        currentSlide = slick;
    }

    slideType = currentSlide.attr("class").split(" ")[1];
    player = currentSlide.find("iframe").get(0);
    startTime = currentSlide.data("video-start");

    if (slideType === "vimeo") {
        switch (control) {
            case "play":
                if ((startTime != null && startTime > 0) && !currentSlide.hasClass('started')) {
                    currentSlide.addClass('started');
                    postMessageToPlayer(player, {
                        "method": "setCurrentTime",
                        "value": startTime
                    });
                }
                postMessageToPlayer(player, {
                    "method": "play",
                    "value": 1
                });
                playerState = true;
                break;
            case "pause":
                postMessageToPlayer(player, {
                    "method": "pause",
                    "value": 1
                });
                playerState = false;
                break;
        }
    } else if (slideType === "youtube") {
        switch (control) {
            case "play":
                postMessageToPlayer(player, {
                    "event": "command",
                    "func": "mute"
                });
                postMessageToPlayer(player, {
                    "event": "command",
                    "func": "playVideo"
                });
                playerState = true;
                break;
            case "pause":
                postMessageToPlayer(player, {
                    "event": "command",
                    "func": "pauseVideo"
                });
                playerState = false;
                break;
        }
    } else if (slideType === "video") {
        video = currentSlide.children("video").get(0);
        if (video != null) {
            if (control === "play") {
                video.play();
                playerState = true;
            } else {
                video.pause();
                playerState = false;
            }
        }
    }
}

// Resize player
function resizePlayer(iframes, ratio) {
    if (!iframes[0])
        return;

    var win = $(".slick-slide"),
        width = win.width(),
        playerWidth,
        height = win.height(),
        playerHeight,
        ratio = ratio || 16 / 9;
    iframes.each(function () {
        var current = $(this);
        if (width / ratio < height) {
            playerWidth = Math.ceil(height * ratio);
            current.width(playerWidth).height(height).css({
                left: (width - playerWidth) / 2,
                top: 0
            });
        } else {
            playerHeight = Math.ceil(width / ratio);
            current.width(width).height(playerHeight).css({
                left: 0,
                top: (height - playerHeight) / 2
            });
        }
    });

}
function resetResizePlayer(iframes) {
    if (!iframes[0])
        return;
    iframes.each(function () {
        var current = $(this);
        current.removeAttr("style");
    });
}

// Resize event
var resizeTimer;
$(window).on("resize.slickVideoPlayer", function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function () {

        var w = $(".slick-slide.slick-active");
        if (w.height() > w.width()) {
            resizePlayer(iframes, 9 / 16);
        } else {
            resetResizePlayer(iframes)
        }

    }, 250);
});
function allFunctions() {
    $('select.inputt').selectify();
    heroSliderRatio();

    $('.carousel').carousel({

        interval: 4000,
        pause: 'none'
    });

	var $slideshow = $('.js-variable-slidespeed-slick');
	$slideshow.slick({
        autoplay: true,
		autoplaySpeed: 6000,
        pauseOnFocus: false,
        pauseOnHover: false,
        cssEase: 'linear',
        infinite: true,
        variableWidth: false,
        slide: '.item',
        onBeforeChange: function (slider, currentIndex, targetIndex) {
            if ($(slider.$slides[targetIndex]).find('.slider-content').hasClass("black-text")) {
                $('.slick-slider .hero-scrolldown').addClass("black");
            } else {
                if ($('.slick-slider .hero-scrolldown').hasClass("black")) {
                    $('.slick-slider .hero-scrolldown').removeClass("black");
                }
            }
        },
		onAfterChange: function (slider, currentIndex, targetIndex) {
			//console.log(currentIndex!=0);
			if(currentIndex!=0)
			{
					// Update autoplay speed according to slide index
					$slideshow.slickSetOption('autoplaySpeed', 4000, true);
					//console.log($slideshow.slickGetOption('autoplaySpeed'));
			}
			else{
				// Update autoplay speed according to slide index
					$slideshow.slickSetOption('autoplaySpeed', 6000, true);
					//console.log($slideshow.slickGetOption('autoplaySpeed'));
			}
			},
			onInit: function (slider) {
				$(".js-variable-slidespeed-slick .slick-slide .responsive-cover-background-image").responsiveInlineBackgroundImage();
			}
    });
	$('.js-variable-slidespeed-slick').on('onAChange', function (slick, currentIndex, targetIndex) {
        if ($(this.$slides[targetIndex]).find('.slider-content').hasClass("black-text")) {
            $('.slick-slider .hero-scrolldown').addClass("black");
        } else {
            if ($('.slick-slider .hero-scrolldown').hasClass("black")) {
                $('.slick-slider .hero-scrolldown').removeClass("black");
            }
        }
    });
	$('.js-variable-slidespeed-slick').on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        if ($(slick.$slides[nextSlide]).find('.slider-content').hasClass("black-text")) {
            $('.slick-slider .hero-scrolldown').addClass("black");
        } else {
            if ($('.slick-slider .hero-scrolldown').hasClass("black")) {
                $('.slick-slider .hero-scrolldown').removeClass("black");
            }
        }
    });
	
	
    $('.js-slick').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        pauseOnFocus: false,
        pauseOnHover: false,
        cssEase: 'linear',
        infinite: true,
        variableWidth: false,
        slide: '.item',
        onBeforeChange: function (slider, currentIndex, targetIndex) {
            if ($(slider.$slides[targetIndex]).find('.slider-content').hasClass("black-text")) {
                $('.slick-slider .hero-scrolldown').addClass("black");
            } else {
                if ($('.slick-slider .hero-scrolldown').hasClass("black")) {
                    $('.slick-slider .hero-scrolldown').removeClass("black");
                }
            }
        },
        onInit: function (slider) {
            $(".js-slick .slick-slide .responsive-cover-background-image").responsiveInlineBackgroundImage();
        }
    });
    //autoplay: false,
    //dots: false,
    //fade: false,
    //speed: 4000,
    //slidesToShow: 1,
    //slidesToScroll: 1
    //pauseOnFocus:false,
    //pauseOnHover:false,
    //swipeToSlide:true,
    //slidesToShow:1,
    //slidesToScroll:1
    // });
	if ($(window).height() >= 375) {
        $('.slick-slider .item .center-align-text-inner.italic-title').css('vertical-align', 'middle');
    }
    $('.slick-slider .item.slick-active .slider-content ').hasClass("black-text")
    {
        if ($('.slick-slider .item.slick-active .slider-content ').hasClass("black-text")) {
            $('.slick-slider .hero-scrolldown').addClass("black");
        } else {
            if ($('.slick-slider .hero-scrolldown').hasClass("black")) {
                $('.slick-slider .hero-scrolldown').removeClass("black");
            }
        }
    }
    $('.js-slick').on('onAChange', function (slick, currentIndex, targetIndex) {
        if ($(this.$slides[targetIndex]).find('.slider-content').hasClass("black-text")) {
            $('.slick-slider .hero-scrolldown').addClass("black");
        } else {
            if ($('.slick-slider .hero-scrolldown').hasClass("black")) {
                $('.slick-slider .hero-scrolldown').removeClass("black");
            }
        }
    });
    $('.js-slick').on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        if ($(slick.$slides[nextSlide]).find('.slider-content').hasClass("black-text")) {
            $('.slick-slider .hero-scrolldown').addClass("black");
        } else {
            if ($('.slick-slider .hero-scrolldown').hasClass("black")) {
                $('.slick-slider .hero-scrolldown').removeClass("black");
            }
        }
    });

    $('.carousel .item.active .slider-content ').hasClass("black-text")
    {
        if ($('.carousel .item.active .slider-content ').hasClass("black-text")) {
            $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').addClass("black");
        } else {
            if ($('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').hasClass("black")) {
                $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').removeClass("black");
            }
        }
    }
    $('.carousel').on('slide.bs.carousel', function () {

        var index = $(".carousel .item.active").index() + 1;
        var length = $(".carousel .item").length;
        if (index == length) {
            index = 0;
        }
        if ($('.carousel .item').eq(index).find('.slider-content').hasClass("black-text")) {
            $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').addClass("black");
        } else {
            if ($('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').hasClass("black")) {
                $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').removeClass("black");
            }
        }
    });
    $('.carousel .glyphicon-menu-left').on('click', function () {
        var index = $(".carousel .item.active").index() - 1;
        if ($('.carousel .item').eq(index).find('.slider-content').hasClass("black-text")) {
            $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').addClass("black");
        } else {
            if ($('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').hasClass("black")) {
                $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').removeClass("black");
            }
        }
    });
    $('.carousel .glyphicon-menu-right').on('click', function () {
        var index = $(".carousel .item.active").index() + 1;
        var length = $(".carousel .item").length;
        if (index == length) {
            index = 0;
        }
        if ($('.carousel .item').eq(index).find('.slider-content').hasClass("black-text")) {
            $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').addClass("black");
        } else {
            if ($('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').hasClass("black")) {
                $('.carousel .glyphicon-menu-right,.carousel .glyphicon-menu-left,.carousel .hero-scrolldown').removeClass("black");
            }
        }
    });

    //Magnific Popup 
    $('.js-video-link').magnificPopup({
        type: 'iframe',
        iframe: {
            markup: '<div class="mfp-iframe-scaler">' +
            '<div class="mfp-close"></div>' +
            '<iframe class="mfp-iframe" scrolling="no" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>' +
            '</div>', // HTML markup of popup, `mfp-close` will be replaced by the close button

            patterns: {
                youtube: {
                    index: 'youtube.com/',
                    id: 'v=',
                    src: '//www.youtube.com/embed/%id%'
                },
                vimeo: {
                    index: 'vimeo.com/',
                    id: '/',
                    src: '//player.vimeo.com/video/%id%',
                }
            }
        },
	callbacks: {
    		open: function() {
      			$('.js-slick').slickPause();
				$('.js-slick .item').removeClass('responsive-cover-background-image');
				$('.js-variable-slidespeed-slick').slickPause();
				$('.js-variable-slidespeed-slick .item').removeClass('responsive-cover-background-image');
				$('html').addClass('video-popup-margin');
    		},
    		close: function() {
			heroSliderRatio();
      			$('.js-slick').slickPlay();
			$('.js-slick .item').addClass('responsive-cover-background-image');
			$('.js-variable-slidespeed-slick').slickPlay();
			$('.js-variable-slidespeed-slick .item').addClass('responsive-cover-background-image');
			$('html').removeClass('video-popup-margin');

    		}
  	}
    });
	$('.wechat-popup').magnificPopup({
		type: 'inline',
          //preloader: false,
		  closeBtnInside: true,  
		  //fixedContentPos: 'auto',
		  //overflowY:scroll,
          //modal: true,
		  //closeBtnInside:true;
		  callbacks: {
			beforeOpen: function() {
				startWindowScroll = $(window).scrollTop();
				$('html').addClass('mfp-helper');
				$("html, body").animate({ scrollTop: 0 }, 0)
		} , 
            open: function() {
				$('body').css('overflow', 'hidden'); 
				jQuery('.section__container').outerHeight('auto');
				var w_height = jQuery(window).innerHeight();
                var n_height = w_height * .75;
                var d_height = jQuery('#wechat-popup .section__container').height();

                if(d_height > n_height){
                    jQuery('.section__container').outerHeight(n_height);
                }else{
                    jQuery('.section__container').outerHeight('auto');
                }
				jQuery(window).resize(function () {
					jQuery('.section__container').outerHeight('auto');
					var w_height = jQuery(window).innerHeight();
					var n_height = w_height * .75;
					var d_height = jQuery('#wechat-popup .section__container').height();

					if(d_height > n_height){
						jQuery('.section__container').outerHeight(n_height);
					}else{
						jQuery('.section__container').outerHeight('auto');
					}
					if ($(window).height() >= 375) {
                        $('.slick-slider .item .center-align-text-inner.italic-title').css('vertical-align', 'middle');
                    }			
				});	// When you open the
            
        },                                        // "body" is used "overflow: hidden".

        close: function() {                       // When the window
            $('body').css('overflow', ''); 
			$('html').removeClass('mfp-helper');
        setTimeout(function(){
          $('body').animate({ scrollTop: startWindowScroll }, 0);
        }, 0);
//console.log('close');			// is closed, the 
        }, 
        }
	});
	$(document).on('click', '.popup-modal-dismiss', function (e) {
          e.preventDefault();
          $.magnificPopup.close();
        });
		
	$('.hero-scrolldown').click(function(){
		$('body,html').animate({ scrollTop: 600 }, 800);
	})

    manipulateMainMenuHtml();
    manipulateFormSelectHtml();
    mainMenu();
    stickyMenu();
    modalEvents();
    rfAccordion();
    toggleDownUp();
    toggleWhyBook();
    dateTimePicker();
	dobdateTimePicker();
    heroScrolldown();
    homeBlocksRatio();
    scrollHideMainMenu();
    toggleMainMenuLeft();
    manipulateLangSwitch();
    animateMobileFooterButtons();
    SetSimiliarHeightBlocks();
	PromotionFilterDropdownTrigger();
	SetNotebookBlocksHeight();
    NotebookFilterDropdownTrigger();
    SetformInputLabelHeight();
	if ($(".cookie-warning").is(':visible')) {
        var window_width = $(window).width();
        var travel_information_top = 150 + $(".cookie-warning").height();
        if (window_width < 768) {
            travel_information_top = $(".cookie-warning").height();
        }
        $(".travel-information").css("top", travel_information_top);
    }
    $(".travel-information input").click(function (event) {
        event.preventDefault();
        $(".travel-information").slideUp();
        var expire = new Date();
        expire.setMonth(expire.getMonth() + 6);
        document.cookie = "travel_info=viewed=1;path=/;expires=" + expire.toUTCString();
    });
    //setSimilarElementsWidth({ ".header-middle .navbar-nav": [".same-width"] });
}


var root = $('html, body');
var window_width = $(window).width();
var isDesktop = window_width >= 768;
var isMobile = window_width < 767;
var header_height = 150;
var header_height_mobile = 80;
var sliding_speed = 350;

if (window_width > 768 && window_width < 992)
    isTablet = true;
else
    isTablet = false;


jQuery(window).resize(function () {
    window_width = $(window).width();
    isDesktop = window_width >= 768;
    var isTablet = false;

    if (window_width > 768 && window_width < 992)
        isTablet = true;

    isMobile = window_width < 767;

    stickyMenu();
    homeBlocksRatio();
    manipulateMainMenuHtml();
    heroSliderRatio();
    SetSimiliarHeightBlocks();
    $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
    TabletScondLineMenuHeight();
    SetformInputLabelHeight();
});
$(window).ready(function () {
    allFunctions();
    bookingFromDropdownTrigger();
    var theLanguage = $('html').attr('lang');
    if (theLanguage == 'zh') {
        $("a").not(".header-right .navbar ul.lang .lang-switcher .dropdown-menu > li > a").not(".blocks .block-description .block-social-icons a.wechat-popup").not(".footer-right .copy-rights a").not(".footer-right .social-icons a").each(function () {
            var URL = this.href;
			var eng_url=$('#hdRootlUrl').val();
            var URLsplit = URL.split('/');
            var host = URLsplit[0] + "//" + URLsplit[2] + "/";
			if(host.indexOf(eng_url) >= 0)
			{
				var newURL = URL.replace(host, '/');
				$(this).attr("href", newURL);
			}
        });
        $("#MeetingsBookingComponent_VenueId option").each(function () {
            var URL = $(this).val();
            var URLsplit = URL.split('/');
            var host = URLsplit[0] + "//" + URLsplit[2] + "/";
            var newURL = URL.replace(host, '/');
            $(this).val(newURL);
        });
        $('.venues-drp.selectpicker').selectpicker('refresh');
    }
    TabletScondLineMenuHeight();
	var IS_ANDROID = navigator.userAgent.match(/Android/i)  != null;
	if(IS_ANDROID)
	{
		$('.js .slick-slider.js-slick .item .slider-content .js-video-link').addClass('android-mobile');
		$('.js .slick-slider.js-slick .item .slider-content.new-layout').addClass('android-mobile');
		$('.js .slick-slider.js-variable-slidespeed-slick .item .slider-content .js-video-link').addClass('android-mobile');
		$('.js .slick-slider.js-variable-slidespeed-slick .item .slider-content.new-layout').addClass('android-mobile');
	}
	else{
		$('.js .slick-slider.js-slick .item .slider-content .js-video-link').removeClass('android-mobile');
		$('.js .slick-slider.js-slick .item .slider-content.new-layout').removeClass('android-mobile');
		$('.js .slick-slider.js-variable-slidespeed-slick .item .slider-content .js-video-link').removeClass('android-mobile');
		$('.js .slick-slider.js-variable-slidespeed-slick .item .slider-content.new-layout').removeClass('android-mobile');
	}
	$('.selectpicker').selectpicker();
});
$(window).load(function () {

    // Initialize
    if (!slideWrapper.length > 0)
        return;

    slideWrapper.slick({
        autoplaySpeed: 4000,
        pauseOnFocus: false,
        pauseOnHover: false,
        cssEase: 'linear',
        infinite: true,
        variableWidth: false,
        slide: '.item',
        onBeforeChange: function (slider, currentIndex, targetIndex) {
            var slick = $(slider.$slider);
            playPauseVideo(slick, "pause");
        },
        onInit: function (slider) {
            var slick = $(slider.$slider);
            var w = $(".slick-slide.slick-active");
            if (w.height() > w.width()) {
                resizePlayer(iframes, 9 / 16);
            } else {
                resetResizePlayer(iframes)
            }
            w.bind('vclick', function () {
                if (!playerState) {
                    playPauseVideo(slick, "play");
                } else {
                    playPauseVideo(slick, "pause");
                }
            });
			$(".main-slider .slick-slide .responsive-cover-background-image").responsiveInlineBackgroundImage();
        },
        onAfterChange: function (slider, index) {
            var slick = $(slider.$slider);
            var w = $(".slick-slide.slick-active");

            w.unbind('vclick');
            playerState = false;
            w.bind('vclick', function () {
                if (!playerState) {
                    playPauseVideo(slick, "play");
                } else {
                    playPauseVideo(slick, "pause");
                }

            });
        }
    });
    $(window).scroll(function () {
        var topOfOthDiv = $(".content-wrapper").offset().top - 100;
        var scrollEvent = $(".slick-slide.slick-active");
        if ($(window).scrollTop() > topOfOthDiv) {
            playPauseVideo(scrollEvent, "pause");
        }
    });
});


function toggleWhyBook() {
    var container = $('.popup-direct');

    $("a.why-book:not(.bound)").addClass('bound').click(function (e) {
        e.preventDefault();

        container.fadeToggle(sliding_speed);
    });

    // Click outside
    $(document).mouseup(function (e) {
        // if the target of the click isn't the container nor a descendant of the container
        if (!container.is(e.target) && container.has(e.target).length === 0 && !$(e.target).hasClass('why-book')) {
            container.fadeOut(sliding_speed);
        }
    });

}

function modalEvents() {
    var booking_mask = $('#exampleModal');
    var modal_button = $('.header-right-bottom-box button');
    var modal_book_placeholder = $('#modal_book_placeholder').val();
    var modal_close_placeholder = $('#modal_close_placeholder').val();

    booking_mask.on('show.bs.modal', function (e) {
        $('.header-middle .navbar .navbar-nav .dropdown-menu').css({ "display": "none" });
        $('.header-middle .navbar .navbar-nav li a span.glyphicon').removeClass("glyphicon-menu-up");
        $('.main-menu-holder').removeClass('open');
        $('.lang-switcher .dropdown-menu').removeClass('open');
        $('#toggleMainMenu').removeClass('open');
        $('.navbar-nav>li.acc-menu').removeClass('open');
        $('.header-right .navbar .menu-top-right li.dropdown.acc-menu .dropdown-menu').css("display", "none");

		var travel_information = $('.travel-information');
        if (travel_information.length > 0) {
            $('.travel-information').addClass("sandwitch-open");
        }
		
		setTimeout(function () {
				var synx_avail_cta_width=$(".btn-avail-calendar-span" ).width();
				$(".btn-avail-calendar-inner-span").css("width", synx_avail_cta_width);
		}, 500);

        modal_button.text(modal_close_placeholder);
    })

    booking_mask.on('hidden.bs.modal', function (e) {
        modal_button.text(modal_book_placeholder);
    })
}

function scrollHideMainMenu() {
    if (isMobile)
        return false;

	
    var last_scroll_top = 0;

    $(window).scroll(function () {
        if (isMobile)
            return false;

        var menu = $('.main-menu-holder.open .navbar-collapse');
        var menu_origin = $('.main-menu-holder');
        var scroll_top = $(this).scrollTop();
        var position_top = header_height;

        if (scroll_top < last_scroll_top) {
            // upscroll
            if (scroll_top > 60)
                position_top = header_height_mobile;
            else
                position_top = header_height;

            menu_origin.css({ "top": (scroll_top + position_top) + 'px' });
        }

        last_scroll_top = scroll_top;


        if (menu.length < 1)
            return false;

        var menu_height = menu.height() - 100;
        var menu_offset_top = menu.offset().top;
        var window_offset = menu_offset_top - $(window).scrollTop();


        if ((menu_height + window_offset) < 0)
            fireMainMenu(0, 0, 'hide');

    });
}

function closeHeaderDropdowns() {
    if (isMobile)
        return false;

    // Close Middle Nav
    closeMiddleNav();

    // Close Language Selector
    $('.header-right .lang-switcher').find(".bootstrap-select.open").each(function () {
        var that = $(this);
        var lang_switcher = that.closest('.lang-switcher');

        that.removeClass('open');
        that.find("button").attr('aria-expanded', 'false');
        that.find('ul.dropdown-menu').attr('aria-expanded', 'false');
        lang_switcher.find('.glyphicon').removeClass('glyphicon-menu-up').addClass('glyphicon-menu-down');
    });
}

function closeMiddleNav() {
    // Close Middle Nav
    
	$('.header-middle .nav .dropdown').each(function(){
		var that = $(this);
		if(that.hasClass('open-up')){
			that.toggleClass('open-up', 'not-open');
        		that.find('.glyphicon').first().toggleClass('glyphicon-menu-up', 'glyphicon-menu-down');
			that.find('.dropdown-menu').hide();
		}	
	});
    }

function toggleDownUp() {
    if (isMobile)
        return false;

    $(".dropdown-toggle:not(.bound)").addClass('bound').click(function (e) {
        e.preventDefault();
        var that = $(this);
        var target = that.closest('.dropdown').find('.dropdown-menu').first();

        that.find('.glyphicon.desktop-only').first().toggleClass('glyphicon-menu-up', 'glyphicon-menu-down');
        target.slideToggle(sliding_speed);

    });
}

function mainMenu() {
    $("#toggleMainMenu:not(.bound)").addClass('bound').click(function () {
        var sandwich = $(this);
        var target = $('.main-menu-holder');
		$('html').css("margin-top", 0);
        fireMainMenu(sandwich, target);
    });
}

function fireMainMenu(sandwich, target, event_name) {
    if (typeof sandwich === 'undefined' && typeof target === 'undefined')
        return false;

    if (typeof event_name === 'undefined')
        event_name = "toggle";

    if (event_name === 'hide') {
        sandwich = $('#toggleMainMenu');
        target = $('.main-menu-holder');
    }


    toggleSandwich(sandwich, target, event_name);

}

function toggleSandwich(sandwich, target, event_name) {
    // Close second children
    var booking_mask = $('#exampleModal');
    $("#exampleModal").modal('hide');
    //$('.main-menu-holder').removeClass('open');
    $('.lang-switcher .dropdown-menu').removeClass('open');
    $('.header-middle .navbar .navbar-nav .dropdown-menu').css({ "display": "none" });
    $('.header-middle .navbar .navbar-nav li a span.glyphicon').removeClass("glyphicon-menu-up");
    $('.navbar-nav>li.acc-menu').removeClass('open');
    $('.header-right .navbar .menu-top-right li.dropdown.acc-menu .dropdown-menu').css("display", "none");

	 var travel_information = $('.travel-information');
    if (travel_information.length > 0) {
        if (!sandwich.hasClass('open')) {
            $('.travel-information').addClass("sandwitch-open");
        }
        else {
            $('.travel-information').removeClass("sandwitch-open");
        }
    }
	
    if (isMobile) {
        $('.mobile-lang-button').removeClass('open-mobile');
        $('.lang-switcher .bootstrap-select').removeClass('open-mobile');
        $('#mob_footer_conteiner_1, #mob_footer_button_1').removeClass('open');
        $('#mob_footer_conteiner_2, #mob_footer_button_2').removeClass('open');
        target.find('.first-open').each(function () {
            $(this).removeClass('first-open').hide();
        })
    }

    if (event_name === 'hide') {

        sandwich.removeClass('open');
        target.removeClass('open');

        if (isMobile) {
            $('body').removeClass('overflow-hidden');
            $("body").css({ "overflow": "inherit", "position": "relative" });
        }
    } else {
        if (!sandwich.hasClass('open') && !isMobile) {
            var scroll_top = $(window).scrollTop();

            if (scroll_top > 60)
                position_top = header_height_mobile;
            else
                position_top = header_height;


            target.css({ "top": (scroll_top + position_top) + 'px' });
        }


        sandwich.toggleClass('open');
        target.toggleClass('open');

        if (isMobile) {
            $('body').toggleClass('overflow-hidden');
            //$("body").css({ "overflow": "hidden", "position": "fixed" });

            if ((target).hasClass('open')) {
                $("body").css({ "overflow": "hidden", "position": "fixed" });
            } else {
                $("body").css({ "overflow": "inherit", "position": "relative" });
            }
        }
    }
}

function toggleMainMenuLeft() {
    if (isDesktop)
        return false;

    $(".main-toggle-child:not(.bound)").addClass('bound').click(function () {
        var that = $(this);

        if (that.prop("tagName") == 'A')
            var tagretedUL = that.closest('.dropdown').find('.dropdown-menu-mobile').first();
        else
            var tagretedUL = that.closest('.dropdown-menu-mobile');

        toggleLeftRight(tagretedUL);


        if (isMobile) {
            // Close children on ancestor
            // if (tagretedUL.hasClass('ancestor')) {
            var tagreted = tagretedUL.find('.dropdown-menu-mobile');
            tagreted.hide();
            tagreted.find('.main-toggle-child').hide();
            // }
        }


    });
}

function toggleLeftRight(tagretedUL) {

    tagretedUL.animate({
        width: "toggle",
        duration: sliding_speed
    }, {
            complete: function () {
                var that = $(this);
                var parent_title = that.find('.parent-title').first();

                if (isMobile) {
                    if (that.css('display') == 'block') {
                        that.addClass('first-open');
                        parent_title.slideDown(sliding_speed);
                    } else {
                        that.removeClass('first-open');
                        parent_title.slideUp(sliding_speed);
                    }
                }

            }
        });
}

function manipulateMainMenuHtml() {
    var wrapper_sticky = $('.wrapper-sticky');
    var wrapper_sticky_height = wrapper_sticky.height();
    var main_menu_holder = $('.main-menu-holder');

    if (isMobile) {
        if (wrapper_sticky_height != header_height_mobile)
            wrapper_sticky.height(header_height_mobile);
    } else {
        if (wrapper_sticky_height != header_height)
            wrapper_sticky.height(header_height);
    }

    main_menu_holder.find('li.dropdown').each(function () {
        var that = $(this);

        if (isMobile) {
            that
                .find('.dropdown-toggle')
                .removeClass('dropdown-toggle')
                .addClass('main-toggle-child')

            that
                .find('.dropdown-menu')
                .removeClass('dropdown-menu')
                .addClass('dropdown-menu-mobile first-children');

            that.find('.desktop-only').hide();
            that.find('.mobile-only').show();
        } else {
            that
                .find('.main-toggle-child')
                .removeClass('main-toggle-child')
                .addClass('dropdown-toggle')

            that
                .find('.dropdown-menu-mobile')
                .removeClass('dropdown-menu-mobile first-children')
                .addClass('dropdown-menu');

            that.find('.desktop-only').show();
            that.find('.mobile-only').hide();
        }
    })
}

function animateMobileFooterButtons() {
    if (isDesktop)
        return false;

    // Button #1
    $('#mob_footer_button_1').on('click', function () {
        if ($(this).closest('.mobile-buttons').find('#mob_footer_button_2').hasClass('open'))
            return false;


        var $el = $('#mob_footer_conteiner_1, #mob_footer_button_1').toggleClass('open');
        if ($el.hasClass('open'))
            $("body").css({ "overflow": "hidden", "position": "fixed" });
        else
            $("body").css({ "overflow": "inherit", "position": "relative" });
        $('#toggleMainMenu').removeClass('open');
        $('.main-menu-holder').removeClass('open');
        $('.mobile-lang-button').removeClass('open-mobile');
        $('.lang-switcher .bootstrap-select').removeClass('open-mobile');
		var travel_information = $('.travel-information');
        if (travel_information.length > 0) {
            $('.travel-information').addClass("sandwitch-open");
        }
    });


    // Button #2
    $('#mob_footer_button_2').on('click', function () {
        if ($(this).closest('.mobile-buttons').find('#mob_footer_button_1').hasClass('open'))
            return false;


        var $el = $('#mob_footer_conteiner_2, #mob_footer_button_2').toggleClass('open');
        if ($el.hasClass('open'))
            $("body").css({ "overflow": "hidden", "position": "fixed" });
        else
            $("body").css({ "overflow": "inherit", "position": "relative" });

        $('#toggleMainMenu').removeClass('open');
        $('.main-menu-holder').removeClass('open');
        $('.mobile-lang-button').removeClass('open-mobile');
        $('.lang-switcher .bootstrap-select').removeClass('open-mobile');
		
		 var travel_information = $('.travel-information');
        if (travel_information.length > 0) {
            $('.travel-information').addClass("sandwitch-open");
        }
		
		setTimeout(function () {
				var synx_avail_cta_width=$(".btn-avail-calendar-span-mob" ).width();
				$(".btn-avail-calendar-inner-span-mob").css("width", synx_avail_cta_width);
		}, 500);
    });
}

function rfAccordion() {
    $(".rf-accordion-label:not(.bound)").addClass('bound').click(function () {
        var that = $(this);
        var wrapper = that.closest('.rf-accordion');

        if (wrapper.hasClass('mobile-js') && isDesktop)
            return false

        var item = that.closest('.rf-accordion-item');

        var target = item.find('.rf-accordion-body');

        if (item.hasClass('open')) {
            item.removeClass('open');
            target.slideUp(sliding_speed);
        } else {
            item.toggleClass('open');
            target.slideToggle(sliding_speed);
        }

    });
}

function setSimilarElementsWidth(selectors) {
    $.each(selectors, function (row_class, value) {
        $.each(value, function (key, element_class) {
            if (isMobile)
                return false;

            var news_blocks = $(row_class);
            if (news_blocks.length < 1)
                return false;

            $(row_class).css('width', '');
            $(element_class).css('width', '');
            // ROWS
            news_blocks.each(function () {
                // BLOCKS
                var this_news_blocks = $(this);
                this_news_blocks;

                var row_width = 0;
                var row_width_modified = 0;

                this_news_blocks.find(element_class).each(function (index) {
                    // TEXTS
                    var this_text_width = $(this).width();

                    if (index === 0)
                        row_width = this_text_width;


                    if (this_text_width !== row_width) {
                        row_width_modified = 1;

                        if (this_text_width > row_width)
                            row_width = this_text_width;

                    }

                });

                // SET width
                if (row_width_modified) {
                    // '.description-block .block-text-holder'
                    this_news_blocks.find(element_class).each(function (index) {
                        $(this).width(row_width + 8);
                    });
                }

            });
        });
    });
}

function stickyMenu() {
    var topValue = -64;
    if (isMobile)
        topValue = -14;

    var toggleComponents = '.header-right-bottom-box .why-book, .header-middle .navbar';

    $('#header_holder').hcSticky(
        {
            top: topValue,
            onStart: function () {
                $("body").addClass("sticky-on");
                closeHeaderDropdowns();
                $(toggleComponents).hide();
				
            },
            onStop: function () {
                $("body").removeClass("sticky-on");
                $(toggleComponents).fadeIn(200);
				TabletScondLineMenuHeight();
            }
        });
}
$('.lang-switcher').on('show.bs.dropdown', function () {
    $('.header-middle .navbar .navbar-nav .dropdown-menu').css({ "display": "none" });
    $('.header-middle .navbar .navbar-nav li a span.glyphicon').removeClass("glyphicon-menu-up");
    $('.main-menu-holder').removeClass('open');
    $('#toggleMainMenu').removeClass('open');
    $("#exampleModal").modal('hide');
    //$('.lang-switcher .dropdown-menu').removeClass('open');
    $('.navbar-nav>li.acc-menu').removeClass('open');
    $('.header-right .navbar .menu-top-right li.dropdown.acc-menu .dropdown-menu').css("display", "none");
	var travel_information = $('.travel-information');
    if (travel_information.length > 0) {
        $('.travel-information').addClass("sandwitch-open");
    }
})

$('.acc-menu').on('show.bs.dropdown', function () {
    $('.header-middle .navbar .navbar-nav .dropdown-menu').css({ "display": "none" });
    $('.header-middle .navbar .navbar-nav li a span.glyphicon').removeClass("glyphicon-menu-up");
    $('.main-menu-holder').removeClass('open');
    $('#toggleMainMenu').removeClass('open');
    $("#exampleModal").modal('hide');
    //$('.lang-switcher .dropdown-menu').removeClass('open');
    $('.navbar-nav>li.lang-switcher').removeClass('open');
    $('.header-right .navbar .menu-top-right li.dropdown.lang-switcher .dropdown-menu').css("display", "none");
	var travel_information = $('.travel-information');
    if (travel_information.length > 0) {
        $('.travel-information').addClass("sandwitch-open");
    }
})

$('.header-middle .navbar .navbar-nav').on('show.bs.dropdown', function () {

    $('.main-menu-holder').removeClass('open');
    $('#toggleMainMenu').removeClass('open');
    $("#exampleModal").modal('hide');
    $('.lang-switcher .dropdown-menu').removeClass('open');
    $('.navbar-nav>li.acc-menu').removeClass('open');
    $('.header-right .navbar .menu-top-right li.dropdown.acc-menu .dropdown-menu').css("display", "none");
    $('.header-middle .navbar .navbar-nav  li a span.glyphicon').addClass("glyphicon-menu-up");
	var travel_information = $('.travel-information');
    if (travel_information.length > 0) {
        $('.travel-information').addClass("sandwitch-open");
    }
    //$('.dropdown-toggle').next().css({"display": "none"});
    //$(this).next().css({"display": "block"});
    //$('.header-middle .navbar .navbar-nav .dropdown-menu').not(this).css({"display": "none"});
})
$('.header-middle .navbar .navbar-nav').on('hide.bs.dropdown', function () {
    $('.header-middle .navbar .navbar-nav  li a span.glyphicon').removeClass("glyphicon-menu-up");
})
$(".header-middle .navbar .navbar-nav .dropdown").on("show.bs.dropdown", function () {
    $('.header-middle .navbar .navbar-nav .dropdown-menu').css({ "display": "none" });
    //$(this).find('.dropdown-toggle').next().css({"display": "none"});
    $(this).find('.dropdown-menu').css({ "display": "block" });
});

function manipulateLangSwitch() {
    // Init Bootstrap Select


    // Mobile slide from let to right
    if (isMobile) {
        $('header-right .selectpicker').selectpicker('hide');
        /*var lang_wrapper = $('.lang .bootstrap-select');
        var mobile_lang_button = lang_wrapper.closest('.lang-switcher').find('button.mobile-lang-button').first();

        $(".mobile-lang-button:not(.bound), .mob-close:not(.bound)").addClass('bound').click(function () {
            lang_wrapper.toggleClass('open-mobile');
            mobile_lang_button.toggleClass('open-mobile');
            $('body').toggleClass('overflow-hidden');
            $('#mob_footer_conteiner_1, #mob_footer_button_1').removeClass('open');
            $('#mob_footer_conteiner_2, #mob_footer_button_2').removeClass('open');
            $('#toggleMainMenu').removeClass('open');
            $('.main-menu-holder').removeClass('open');
        });*/
		$(".mobile-lang-button:not(.bound)").addClass('bound').click(function () {
			var lang_wrapper = $('.lang .bootstrap-select');
			var mobile_lang_button = lang_wrapper.closest('.lang-switcher').find('button.mobile-lang-button').first();
			lang_wrapper.toggleClass('open-mobile');
            mobile_lang_button.toggleClass('open-mobile');
            $('body').toggleClass('overflow-hidden');
            $('#mob_footer_conteiner_1, #mob_footer_button_1').removeClass('open');
            $('#mob_footer_conteiner_2, #mob_footer_button_2').removeClass('open');
            $('#toggleMainMenu').removeClass('open');
            $('.main-menu-holder').removeClass('open');
			 var travel_information = $('.travel-information');
            if (travel_information.length > 0) {
                $('.travel-information').addClass("sandwitch-open");
            }
        });
		$(".mob-close:not(.bound)").addClass('bound').click(function () {
			var lang_wrapper = $('.lang .bootstrap-select');
			var mobile_lang_button = lang_wrapper.closest('.lang-switcher').find('button.mobile-lang-button').first();
			lang_wrapper.removeClass('open-mobile');
            mobile_lang_button.removeClass('open-mobile');
            $('body').toggleClass('overflow-hidden');
            $('#mob_footer_conteiner_1, #mob_footer_button_1').removeClass('open');
            $('#mob_footer_conteiner_2, #mob_footer_button_2').removeClass('open');
            $('#toggleMainMenu').removeClass('open');
            $('.main-menu-holder').removeClass('open');
			 var travel_information = $('.travel-information');
            if (travel_information.length > 0) {
                $('.travel-information').addClass("sandwitch-open");
            }
        });
    }

    var langSelect = $('#langSelect');

    //swich languages
    langSelect.on('change', function () {
        var lang_button = $(this).closest('.lang-switcher').find('.btn.dropdown-toggle .filter-option');
        var button_text = lang_button.text();
        var arabic = /[\u0600-\u06FF]/;

        if (!arabic.test(button_text))
            lang_button.text(button_text.substring(0, 3));
        var lang_selected = this.value;
        if (lang_selected != "null") {
            location = this.value;
        }
    });

    // Switch Arrows
    langSelect.on('show.bs.select', function (e) {
        var lang_switcher = $(this).closest('.lang-switcher');
        lang_switcher.find('.glyphicon').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-up');
    });

    langSelect.on('hidden.bs.select', function (e) {
        var lang_switcher = $(this).closest('.lang-switcher');
        lang_switcher.find('.glyphicon').removeClass('glyphicon-menu-up').addClass('glyphicon-menu-down');
    });

    langSelect.on('loaded.bs.select', function (e) {
        var lang_button = $(this).closest('.lang-switcher').find('.btn.dropdown-toggle .filter-option');
        var button_text = lang_button.text();
        var arabic = /[\u0600-\u06FF]/;

        if (!arabic.test(button_text))
            lang_button.text(button_text.substring(0, 3));

    });
    // Add close button
    if (isMobile)
        $('.lang-switcher .mob-close').text("x  close");

}

function heroScrolldown() {

    $('.hero-slider .hero-scrolldown').click(function () {
        root.animate({
            //scrollTop: jQuery(this).offset().top - 0
            scrollTop: jQuery(this).closest('.hero-slider').outerHeight() - 0
        }, 600);
        return false;
    });
    $('.item .hero-scrolldown').click(function () {
        root.animate({
            //scrollTop: jQuery(this).offset().top - 0
            scrollTop: $('.slick-slider').outerHeight() - 0
        }, 600);
        return false;
    });
	$('.gen-subpage-new-carousel #gallery-nav-down').click(function (e) { 
		// e.preventDefault();
			$('html, body').animate({
				//scrollTop: jQuery(this).offset().top - 0
				scrollTop: $('.gen-subpage-new-carousel').outerHeight() - 0
			}, 600);
			return false;
		});
}

function homeBlocksRatio() {
    var wrapper3inrow = $('.three-inline-blocks');
    var width3 = wrapper3inrow.find('.block-boot-inner').width();
    var ratio3 = 0.73;

    wrapper3inrow.find('.block-boot-inner').each(function () {
        $(this).height(width3 * ratio3);
    });


    var wrapper2inrow = $('.two-inline-blocks');
    var width2 = wrapper2inrow.find('.block-image-holder').width();
    var ratio2 = 0.73;

    $('.home-blocks').find(wrapper2inrow).each(function () {
        $(this).find('.block-image-holder').each(function () {
            $(this).height(width2 * ratio2);
        });
    });

}

function manipulateFormSelectHtml() {
    if (isMobile)
        return false;

    $('body').find(".booking-form").each(function () {
        var form = $(this);

        /*form.find(".manipulate-html").each(function () {
         var that = $(this);
         var label = that.find('label').text();
         
         that.find("option").each(function (i) {
         $(this).text(i + ' ' + label);
         });
         
         });*/

    });
}
function dobdateTimePicker() {
    $('body').find(".datepicker-here-dob").each(function () {
        var that = $(this);
        var $btn = that.closest('div').find('i');
        var prevDay = new Date;
		var datepicker_visible = false;
        var datepicker = that.datepicker({
            showEvent: "none",
            autoClose: true,
            onShow: function (dp, animationCompleted) {
                if (that.attr('id') == 'DateOfBirth') {
                    var defaultDate = new Date();
                    dobselected = $('#DOBDatestring').val();
					dobmaxvalue = $('#DOBMinDatestring').val();
					console.log(dobselected);
                    if (dobselected) {
                        defaultDate = new Date(dobmaxvalue.substring(6, 10), dobmaxvalue.substring(3, 5) - 1, dobmaxvalue.substring(0, 2));
                        dp.date = dobselected;
                        dp.update('maxDate', defaultDate);
                        $('#Form_Date').val(dobselected);
                    }
                    else {
                        dp.date = new Date();
                        dp.update('maxDate', new Date());
                        $('#DateOfBirth').val(window.EQTR.restaurantBooking.getDefaultDate());
                    }
                }

            },
            onHide: function (inst, animationCompleted) {
                
            },
            onSelect: function onSelect(date, d) {
            }

        });
		
		var $input = that,
		dp = datepicker;
		dp.data('datepicker').selectDate(new Date());
		$btn.on('click', function() {
			var dpdob = dp.data('datepicker');
			dpdob.show();
		});
		
        if (that.attr('id') == 'DateOfBirth') {
            var dateselected = that.attr('value');
			if (that.attr('id') == 'DateOfBirth') {
                dateselected = $('#DOBDatestring').val();
            }

            if (!dateselected) {
                datepicker.data('datepicker').selectDate(new Date());
            } else {
                datepicker.data('datepicker').selectDate(new Date(dateselected.substring(6, 10), dateselected.substring(3, 5) - 1, dateselected.substring(0, 2)));

            }
        } else {

            datepicker.data('datepicker').selectDate(new Date());
        }
    });
	
    

}
function dateTimePicker() {
    $('body').find(".datepicker-here").each(function () {
        var that = $(this);
        var $btn = that.closest('div').find('i');
        var prevDay = new Date;
        var datepicker = that.datepicker({
            showEvent: "blur",
            autoClose: true,
            onShow: function (dp, animationCompleted) {
                if (that.attr('id') == "datepicker-table") {
                    var datastartingdate=$('#datepicker-table').data('startingdate');
					if(datastartingdate)
					{
						var	startingdate = new Date(datastartingdate.substring(6, 10), datastartingdate.substring(3, 5) - 1, datastartingdate.substring(0, 2));
						dp.date = startingdate;
						dp.update('minDate', startingdate);
						$('#datepicker-table').val(datastartingdate);
						
					}
					else
					{
						dp.date = new Date();
						dp.update('minDate', new Date());
						$('#datepicker-table').val(window.EQTR.restaurantBooking.getDefaultDate());
						
					}
					
                } else if (that.attr('id') == "datepicker-room") {
                    
					var datastartingdate=$('#datepicker-room').data('startingdate');
					if(datastartingdate)
					{
						var	startingdate = new Date(datastartingdate.substring(6, 10), datastartingdate.substring(3, 5) - 1, datastartingdate.substring(0, 2));
						dp.date = startingdate;
						dp.update('minDate', startingdate);
						$('#datepicker-room').val(datastartingdate);
					}
					else
					{
						dp.date = new Date();
						dp.update('minDate', new Date());
						$('#datepicker-room').val(window.EQTR.restaurantBooking.getDefaultDate());
					}
					
                    
                } else if (that.attr('id') == "datepicker-table-mob") {
                    var datastartingdate=$('#datepicker-table-mob').data('startingdate');
					if(datastartingdate)
					{
						var	startingdate = new Date(datastartingdate.substring(6, 10), datastartingdate.substring(3, 5) - 1, datastartingdate.substring(0, 2));
						dp.date = startingdate;
						dp.update('minDate', startingdate);
						$('#datepicker-table-mob').val(datastartingdate);
					}
					else
					{
						dp.date = new Date();
						dp.update('minDate', new Date());
						$('#datepicker-table-mob').val(window.EQTR.restaurantBooking.getDefaultDate());
					}
                    that.attr("disabled", true);
                } else if (that.attr('id') == "datepicker-room-mob") {
                    var datastartingdate=$('#datepicker-room-mob').data('startingdate');
                    if(datastartingdate)
					{
						var	startingdate = new Date(datastartingdate.substring(6, 10), datastartingdate.substring(3, 5) - 1, datastartingdate.substring(0, 2));
						dp.date = startingdate;
						dp.update('minDate', startingdate);
						$('#datepicker-room-mob').val(datastartingdate);
					}
					else
					{
						dp.date = new Date();
						dp.update('minDate', new Date());
						$('#datepicker-room-mob').val(window.EQTR.restaurantBooking.getDefaultDate());
					}
                    that.attr("disabled", true);
                }
				else if (that.attr('id') == "Form_SelectedDateTime") {
					var hotelsdrp = $('#Form_HotelId');
                    var startingdate = new Date();
                    $.get('/api/hotelroomsandsuites/en/gethotelconfiguration/?id=' + hotelsdrp.val(), function (data) {

                       dp = $('#Form_SelectedDateTime').datepicker().data('datepicker');
						 
						if (data.StartingDateString) {
							startingdate = new Date(data.StartingDateString.substring(6, 10), data.StartingDateString.substring(3, 5) - 1, data.StartingDateString.substring(0, 2));
							dp.date = startingdate;
							dp.update('minDate', startingdate);
							$('#Form_SelectedDateTime').val(data.StartingDateString);
                        }
                        else
						{
							dp.date = new Date();
							dp.update('minDate', new Date());
							$('#Form_SelectedDateTime').val(window.EQTR.restaurantBooking.getDefaultDate());
						}

                    })
                    
                }
				else if (that.attr('id') == "Form_Date") {
					
					var hotelsdrp = $('#Form_RestaurantId');
                    var startingdate = new Date();
                    $.get('/api/restaurant/getrestaurantconfiguration/?lang=en&restaurantReference=' + hotelsdrp.val(), function (data) {

                       dp = $('#Form_Date').datepicker().data('datepicker');
						 
						if (data.StartingDateString) {
							startingdate = new Date(data.StartingDateString.substring(6, 10), data.StartingDateString.substring(3, 5) - 1, data.StartingDateString.substring(0, 2));
							dp.date = startingdate;
							dp.update('minDate', startingdate);
							$('#Form_Date').val(data.StartingDateString);
                        }
                        else
						{
							dp.date = new Date();
							dp.update('minDate', new Date());
							$('#Form_Date').val(window.EQTR.restaurantBooking.getDefaultDate());
						}

                    })
                    
                }
                else if (that.attr('id') == 'DateOfBirth') {
                    var defaultDate = new Date();
                    dobselected = $('#DOBDatestring').val();
                    dobmaxvalue = $('#DOBMinDatestring').val();
                    console.log(dobselected);
                    if (dobselected) {
                        defaultDate = new Date(dobmaxvalue.substring(6, 10), dobmaxvalue.substring(3, 5) - 1, dobmaxvalue.substring(0, 2));
                        dp.date = dobselected;
                        dp.update('maxDate', defaultDate);
                        $('#Form_Date').val(dobselected);
                    }
                    else {
                        dp.date = new Date();
                        dp.update('maxDate', new Date());
                        $('#DateOfBirth').val(window.EQTR.restaurantBooking.getDefaultDate());
                    }
                }

            },
            onHide: function (inst, animationCompleted) {
                if (that.attr('id') == "datepicker-room-mob" || that.attr('id') == "datepicker-table-mob") {
                    that.attr("disabled", false);
                }
				
            },
            onSelect: function onSelect(date, d) {
                var myDatepicker = that.datepicker().data('datepicker');
                if (date == "") {
                    myDatepicker.selectDate(new Date(prevDay.substring(6), prevDay.substring(3, 5) - 1, prevDay.substring(0, 2)))
                } else {
                    prevDay = date
                }
                if (that.attr('id') == "datepicker-room") {
                    var hotelsdrp = $('#RoomBookingComponent_HotelId');
                    if (hotelsdrp.val() !== "") {
                        setTimeout(function () {
                            $('.nights-drp.bootstrap-select .dropdown-toggle').trigger('click')
                        }, 50);
                    }
                } else if (that.attr('id') == "datepicker-table") {
                    var hotelsdrp = $('#TableBookingComponent_RestaurantId');
                    if (hotelsdrp.val() !== "") {
                        setTimeout(function () {
                            $('.covers-drp.bootstrap-select .dropdown-toggle').trigger('click')
                        }, 50);
                    }
                } else if (that.attr('id') == "datepicker-room-mob") {
                    var hotelsdrp = $('#RoomBookingComponent_HotelIdmob');
                    if (hotelsdrp.val() !== "") {
                        setTimeout(function () {
                            $('.nights-drp-mob.bootstrap-select .dropdown-toggle').trigger('click')
                        }, 50);
                    }
                } else if (that.attr('id') == "datepicker-table-mob") {
                    var hotelsdrp = $('#TableBookingComponent_RestaurantIdmob');
                    if (hotelsdrp.val() !== "") {
                        setTimeout(function () {
                            $('.covers-drp-mob.bootstrap-select .dropdown-toggle').trigger('click')
                        }, 50);

                    }
                }
            }
			
        });
        if (that.attr('id') == 'Form_Date' || that.attr('id') == 'Form_SelectedDateTime'|| that.attr('id') == 'DateOfBirth') {
            var dateselected = that.attr('value');
			if (that.attr('id') == 'Form_SelectedDateTime') {
                dateselected = $('#hd_SelectedDateTime').val();
            }
			if (that.attr('id') == 'Form_Date') {
                dateselected = $('#tableDatestring').val();
            }
			if (that.attr('id') == 'DateOfBirth') {
                dateselected = $('#DOBDatestring').val();
            }
			
            if (!dateselected) {
                datepicker.data('datepicker').selectDate(new Date());
            } else {
                datepicker.data('datepicker').selectDate(new Date(dateselected.substring(6, 10), dateselected.substring(3, 5) - 1, dateselected.substring(0, 2)));

            }
        } else {
			
					datepicker.data('datepicker').selectDate(new Date());
		}


        var $input = that,
            dp = datepicker;


    });
    var $btnroom = $('#datepicker-room').closest('div').find('i');
    var $btnroommob = $('#datepicker-room-mob').closest('div').find('i');
    var $btntable = $('#datepicker-table').closest('div').find('i');
    var $btntablemob = $('#datepicker-table-mob').closest('div').find('i');
    $btnroom.on('click', function () {
        var dproom = $('#datepicker-room').datepicker().data('datepicker');
        dproom.show();
    });
    $btnroommob.on('click', function () {
        var dproommob = $('#datepicker-room-mob').datepicker().data('datepicker');
        dproommob.show();
    });
    $btntable.on('click', function () {
        var dptable = $('#datepicker-table').datepicker().data('datepicker');
        dptable.show();
    });
    $btntablemob.on('click', function () {
        var dptablemob = $('#datepicker-table-mob').datepicker().data('datepicker');
        dptablemob.show();
    });

}

function heroSliderRatio() {
var carousel = $('#myCarousel');
    var slick_slider = $('.slick-slider').not('.slick-not');
    var header_holder = $('#header_holder');
    var mobile_buttons = $('.mobile-buttons');
    var restaurant_map = $('#restaurant-map');
    var cookie_warning_height = 0;
    if ($(".cookie-warning").css('display') !== 'none') {
        cookie_warning_height = $(".cookie-warning").height();
    }


    slick_slider.find('.item').each(function (index) {
        if (isMobile) {
            $(this).height($(window).height() - header_holder.height() - mobile_buttons.height());
        } else {
            $(this).height($(window).height() - header_holder.height() - cookie_warning_height);
        }
    });
    carousel.find('.item').each(function (index) {
        if (isMobile) {
            $(this).height($(window).height() - header_holder.height() - mobile_buttons.height());
        }
    });
    if (isMobile) {
        slick_slider.height($(window).height() - header_holder.height() - mobile_buttons.height());
        restaurant_map.height($(window).height() - header_holder.height() - mobile_buttons.height());
    } else {
        slick_slider.height($(window).height() - header_holder.height() - cookie_warning_height);
    }
	
	if (isMobile) {
		$('.GenericSubPageTemplate .gen-subpage-new-carousel .primary-panel.panel-scroller').height($(window).height() - header_holder.height() - mobile_buttons.height());
	}else{
		$('.GenericSubPageTemplate .gen-subpage-new-carousel .primary-panel.panel-scroller').height('100%');
	}
}
function SetSimiliarHeightBlocks() {
    var block_content_ht = 0;
    $('.blocks .two-inline-blocks .block-boot-inner .block-content-holder:not(".experince-blocks")').each(function () {

        if ($(this).outerHeight() > block_content_ht) {
            block_content_ht = $(this).outerHeight();
        }
    });
    $('.blocks .two-inline-blocks .block-boot-inner .block-content-holder:not(".experince-blocks")').outerHeight(block_content_ht);
    var block_exp_content_ht = 0;
    $('.blocks .two-inline-blocks .block-boot-inner .block-content-holder.experince-blocks').each(function () {

        if ($(this).outerHeight() > block_exp_content_ht) {
            block_exp_content_ht = $(this).outerHeight();
        }
    });
    $('.blocks .two-inline-blocks .block-boot-inner .block-content-holder.experince-blocks').outerHeight(block_exp_content_ht);

    $(".js .page-content.restaurant-room .container .responsive-background-image").responsiveBackgroundImage();
    if (!isMobile) {
        var restuarent_landing_ht = 0;
        $('.js .restaurant-landing-panel').each(function () {
            restuarent_landing_ht = $(this).closest('.container').find('.restaurant-heading-panel').outerHeight();
            $(this).outerHeight(restuarent_landing_ht);
        });
    }
}
function bookingFromDropdownTrigger() {

    $('.booking-form .forms').not('.active').hide();

    $('select.chooser').on('change', function (e) {
        if ($(this).val() != null) {
            var selectedval = $("option:selected", this).val();
            $('.select-group').hide().removeClass('active').filter('.' + $(this).val() + '-group').show().addClass('active');
            $('.' + $(this).val() + '-group').find('.chooser').val(selectedval);
            //$('.' + $(this).val() + '-group').closest('booking-form').find('.selectpicker').selectpicker('refresh');
            $('.booking-form .selectpicker').selectpicker('refresh');
            setTimeout(function () {
                if ($(window).width() < 768) {
                    $('.booking-form .book-pop-mask-mob.forms.active .dynamic-ddl .bootstrap-select .dropdown-toggle').each(function () {
                        $(this).trigger('click');

                    });
                } else {
                    $('.booking-form .forms.active .dynamic-ddl .bootstrap-select .dropdown-toggle').each(function () {
                        $(this).trigger('click');
                    });
                }
            }, 50);
        }
    });

    //rooms

    $('.selectpicker.nights-drp').on('change', function (e) {
        hotelId = $('#RoomBookingComponent_HotelId').val();
		if(hotelId)
		{
			if (hotelId == "58527") {
				window.EQTR.bookingBar.triggerDropdown('.bedroomsuite-drp');
			}
			else {
				window.EQTR.bookingBar.triggerDropdown('.rooms-drp');
			}
		}
		else
		{
			window.EQTR.bookingBar.triggerDropdown('.rooms-drp');
		}
    });
    $('.selectpicker.nights-drp-mob').on('change', function (e) {
        hotelId = $('#RoomBookingComponent_HotelId').val();
		if(hotelId)
		{
			if (hotelId == "58527") {
				window.EQTR.bookingBar.triggerDropdown('.bedroomsuite-drp-mob');
			}
			else {
				window.EQTR.bookingBar.triggerDropdown('.rooms-drp-mob');
			}
		}
		else
		{
			window.EQTR.bookingBar.triggerDropdown('.rooms-drp-mob');
		}
    });
	$(".hotels-drp .dropdown-menu").on("click", "li", function (event) {
        setTimeout(function () {
            var myDatepicker = $("#datepicker-room").datepicker().data('datepicker');
			myDatepicker.show();
        }, 50);
    });
    $(".hotels-drp-mob .dropdown-menu").on("click", "li", function (event) {
		setTimeout(function () {
			var myDatepicker = $("#datepicker-room-mob").datepicker().data('datepicker');
			myDatepicker.show();
		}, 50);
    });
    $('.selectpicker.rooms-drp').on('changed.bs.select', function (e) {
        var rooms = $(this).val();
        var adults = $('#numberofadults');
        var childrens = $('#numberofchildren');
		if(childrens.val()=="") {
			childrens.val(0);
		}
        window.EQTR.bookingBar.updateAdultDropDown(rooms, adults);
        window.EQTR.bookingBar.updateChildrenDropDown(rooms, childrens);
        window.EQTR.bookingBar.triggerDropdown('.adults-drp');
    });
    $('.selectpicker.rooms-drp-mob').on('change', function (e) {
        var rooms = $(this).val();
        var adults = $('#numberofadultsmob');
        var childrens = $('#numberofchildrenmob');
		if(childrens.val()=="") {
			childrens.val(0);
		}
        window.EQTR.bookingBar.updateAdultDropDown(rooms, adults);
        window.EQTR.bookingBar.updateChildrenDropDown(rooms, childrens);
        window.EQTR.bookingBar.triggerDropdown('.adults-drp-mob');
    });
	$('.selectpicker.bedroomsuite-drp').on('change', function (e) {
        var rooms = $(this).val();
        var adults = $('#numberofadults');
        var childrens = $('#numberofchildren');
		var hotelidnum = $('#RoomBookingComponent_HotelId').val();
        window.EQTR.bookingBar.updateBedRoomSuiteAdultDropDown(rooms, adults, hotelidnum);
		var adultscount = $('#numberofadults').val();
        window.EQTR.bookingBar.updateBedRoomSuiteChildrenDropDown(rooms, childrens, adultscount, hotelidnum);
        window.EQTR.bookingBar.triggerDropdown('.adults-drp');
    });
    $('.selectpicker.bedroomsuite-drp-mob').on('change', function (e) {
        var rooms = $(this).val();
        var adults = $('#numberofadultsmob');
        var childrens = $('#numberofchildrenmob');
		var hotelidnum = $('#RoomBookingComponent_HotelIdmob').val();
        window.EQTR.bookingBar.updateBedRoomSuiteAdultDropDown(rooms, adults, hotelidnum);
		var adultscountmob = $('#numberofadultsmob').val();
        window.EQTR.bookingBar.updateBedRoomSuiteChildrenDropDown(rooms, childrens, adultscountmob, hotelidnum);
        window.EQTR.bookingBar.triggerDropdown('.adults-drp-mob');
    });
    $('.selectpicker.adults-drp').on('change', function (e) {
		var rooms = $('.selectpicker.bedroomsuite-drp').val();
		var childrens = $('#numberofchildren');
		var adultscount = $('#numberofadults').val();
		var hotelidnum = $('#RoomBookingComponent_HotelId').val();
		window.EQTR.bookingBar.updateBedRoomSuiteChildrenDropDown(rooms, childrens, adultscount, hotelidnum);
        window.EQTR.bookingBar.triggerDropdown('.childrens-drp');
		var childNumber = $('.selectpicker.childrens-drp').val();
        window.EQTR.bookingBar.showChildAgePanel(childNumber, $(this));
    });
    $('.selectpicker.adults-drp-mob').on('changed.bs.select', function (e) {
		var rooms = $('.selectpicker.bedroomsuite-drp-mob').val();
        var childrens = $('#numberofchildrenmob');
		var adultscountmob = $('#numberofadultsmob').val();
		var hotelidnum = $('#RoomBookingComponent_HotelIdmob').val();
		window.EQTR.bookingBar.updateBedRoomSuiteChildrenDropDown(rooms, childrens, adultscountmob, hotelidnum);
        window.EQTR.bookingBar.triggerDropdown('.childrens-drp-mob');
		var childNumber = $('.selectpicker.childrens-drp-mob').val();
        window.EQTR.bookingBar.showChildAgePanel(childNumber, $(this));
    });
    $('.selectpicker.childrens-drp').on('change', function (e) {
        var childNumber = $(this).val();
        window.EQTR.bookingBar.showChildAgePanel(childNumber, $(this));
    });
    $('.selectpicker.childrens-drp-mob').on('change', function (e) {
        var childNumber = $(this).val();
        window.EQTR.bookingBar.showChildAgePanel(childNumber, $(this));
    });
    $('select.ages-drp').on('change', function (e) {
        var childAgespickers = $(this).closest('.col-child-ages');
        var nextDropdown = childAgespickers.next();

        if (childAgespickers.next().length == 0) {
            nextDropdown = childAgespickers.closest('.child-ages-row').next().find('.col-child-ages').first();
        }
        setTimeout(function () {
            nextDropdown.find('.bootstrap-select .dropdown-toggle').trigger('click');
        }, 50);
    });

    //table
    $('.selectpicker.restuarents-drp').on('change', function (e) {
        var language = $('html')[0].lang,
            $restaurantIdSelect = $(this),
            restaurantId = $(this).val();
        $.when($.get('/api/restaurant/getrestaurantconfiguration/?lang=' + language + '&restaurantReference=' + restaurantId, function (data) {
            window.EQTR.restaurantBooking.updateTimeDropDown(data.MealTypes, $('select#Form_MealType'), $('select#Form_MealType').attr('data-translation'));
            window.EQTR.restaurantBooking.updatePeopleDropDown(data.MaxCovers, $('select#Form_NumberOfCovers'), $('select#Form_NumberOfCovers').attr('data-translationsingular'), $('select#Form_NumberOfCovers').attr('data-translationplural'));
			if (data.StartingDateString) {
				$('#datepicker-table').val(data.StartingDateString);
				$('#datepicker-table').data('startingdate',data.StartingDateString);
			}
			else
			{
				//$('#datepicker-table').val($.datepicker.formatDate( "dd/MM/yyyy", new Date()));
				$('#datepicker-table').val(window.EQTR.restaurantBooking.getDefaultDate());
				$('#datepicker-table').data('startingdate',window.EQTR.restaurantBooking.getDefaultDate());
			}
		})).done(window.EQTR.bookingBar.triggerDropdown('.meals-drp'));
    });
    $('.selectpicker.restuarents-drp-mob').on('change', function (e) {
        var language = $('html')[0].lang,
            $restaurantIdSelect = $(this),
            restaurantId = $(this).val();
        $.when($.get('/api/restaurant/getrestaurantconfiguration/?lang=' + language + '&restaurantReference=' + restaurantId, function (data) {
            window.EQTR.restaurantBooking.updateTimeDropDown(data.MealTypes, $('select#Form_MealTypemob'), $('select#Form_MealTypemob').attr('data-translation'));
            window.EQTR.restaurantBooking.updatePeopleDropDown(data.MaxCovers, $('select#Form_NumberOfCoversmob'), $('select#Form_NumberOfCoversmob').attr('data-translationsingular'), $('select#Form_NumberOfCoversmob').attr('data-translationplural'));
			if (data.StartingDateString) {
				$('#datepicker-table-mob').val(data.StartingDateString);
				$('#datepicker-table-mob').data('startingdate',data.StartingDateString);
			}
			else
			{
				//$('#datepicker-table').val($.datepicker.formatDate( "dd/MM/yyyy", new Date()));
				$('#datepicker-table-mob').val(window.EQTR.restaurantBooking.getDefaultDate());
				$('#datepicker-table-mob').data('startingdate',window.EQTR.restaurantBooking.getDefaultDate());
			}
		})).done(window.EQTR.bookingBar.triggerDropdown('.meals-drp-mob'));
    });
	//room
    $('.selectpicker.hotels-drp').on('change', function (e) {
        hotelId = $(this).val();
		if(hotelId)
		{
			$.get('/api/hotelroomsandsuites/en/gethotelconfiguration/?id=' + hotelId, function (data) {

		   if (data.StartingDateString) {
				
				$('#datepicker-room').val(data.StartingDateString);
				$('#datepicker-room').data('startingdate',data.StartingDateString);
			}
			else
			{
				//$('#datepicker-table').val($.datepicker.formatDate( "dd/MM/yyyy", new Date()));
				$('#datepicker-room').val(window.EQTR.restaurantBooking.getDefaultDate());
				$('#datepicker-room').data('startingdate',window.EQTR.restaurantBooking.getDefaultDate());
			}
			var adults = $('#numberofadults');
			var childrens = $('#numberofchildren');
			if (hotelId == "58527") {
				$('.rooms-drp-wrapper').css('display', 'none');
				$('.bedroomsuite-drp-wrapper').css('display', 'block');
				$('.selectpicker.bedroomsuite-drp').selectpicker('val', 1).selectpicker('refresh');
				window.EQTR.bookingBar.updateBedRoomSuiteAdultDropDown("1", adults, hotelId);
				window.EQTR.bookingBar.updateBedRoomSuiteChildrenDropDown("1", childrens, "2", hotelId);
			}
			else
			{
				$('.bedroomsuite-drp-wrapper').css('display', 'none');
				$('.rooms-drp-wrapper').css('display', 'block');
				$('.selectpicker.rooms-drp').selectpicker('val', 1).selectpicker('refresh');
				window.EQTR.bookingBar.updateAdultDropDown("1", adults);
				window.EQTR.bookingBar.updateChildrenDropDown("1", childrens);
				
			}
			$('.selectpicker.adults-drp').selectpicker('val', 2);
			$('.selectpicker.adults-drp').selectpicker('refresh');
			
			var childNumber = $('.selectpicker.childrens-drp').val();
			window.EQTR.bookingBar.showChildAgePanel(childNumber, $(this));
		});
		}
    });
    $('.selectpicker.hotels-drp-mob').on('change', function (e) {
        hotelId = $(this).val();
		if(hotelId)
		{
			$.get('/api/hotelroomsandsuites/en/gethotelconfiguration/?id=' + hotelId, function (data) {

		   if (data.StartingDateString) {
				
				$('#datepicker-room-mob').val(data.StartingDateString);
				$('#datepicker-room-mob').data('startingdate',data.StartingDateString);
			}
			else
			{
				//$('#datepicker-table').val($.datepicker.formatDate( "dd/MM/yyyy", new Date()));
				$('#datepicker-room-mob').val(window.EQTR.restaurantBooking.getDefaultDate());
				$('#datepicker-room-mob').data('startingdate',window.EQTR.restaurantBooking.getDefaultDate());
			}
			var adults = $('#numberofadultsmob');
			var childrens = $('#numberofchildrenmob');
			if (hotelId == "58527") {
				$('.rooms-drp-mob-wrapper').css('display', 'none');
				$('.bedroomsuite-drp-mob-wrapper').css('display', 'block');
				$('.selectpicker.bedroomsuite-drp-mob').selectpicker('val', 1).selectpicker('refresh');
				window.EQTR.bookingBar.updateBedRoomSuiteAdultDropDown("1", adults, hotelId);
				window.EQTR.bookingBar.updateBedRoomSuiteChildrenDropDown("1", childrens, "2", hotelId);
			}
			else {
				$('.bedroomsuite-drp-mob-wrapper').css('display', 'none');
				$('.rooms-drp-mob-wrapper').css('display', 'block');
				$('.selectpicker.rooms-drp-mob').selectpicker('val', 1).selectpicker('refresh');
				window.EQTR.bookingBar.updateAdultDropDown("1", adults);
				window.EQTR.bookingBar.updateChildrenDropDown("1", childrens);
			}
			
			$('.selectpicker.adults-drp-mob').selectpicker('val', 2);
			$('.selectpicker.adults-drp-mob').selectpicker('refresh');
			
			var childNumber = $('.selectpicker.childrens-drp-mob').val();
			window.EQTR.bookingBar.showChildAgePanel(childNumber, $(this));
		});
		}
    });
    $(".meals-drp .dropdown-menu").on("click", "li", function (event) {
        var myDatepicker = $("#datepicker-table").datepicker().data('datepicker');
        myDatepicker.show();
    });
    $(".meals-drp-mob .dropdown-menu").on("click", "li", function (event) {
        var myDatepicker = $("#datepicker-table-mob").datepicker().data('datepicker');
        myDatepicker.show();
    });
    if ($(window).width() <= 360) {
        $('.selectpicker.hotels-drp-mob').on('change', function (e) {
            $('#mob_footer_conteiner_2').scrollTop(100);
        });
        $('.selectpicker.restuarents-drp-mob').on('change', function (e) {
            $('#mob_footer_conteiner_2').scrollTop(100);
        });
    }

    $('body').find(".datepicker-here").each(function () {
        var dp = $(this).datepicker().data('datepicker');

        if (isMobile) {
            $('#mob_footer_conteiner_2').on('scroll', function () {
                dp.update();
            });
        }
    });
	$('.selectpicker.FormHotelId').on('change', function (e) {
        hotelId = $(this).val();
		if(hotelId)
		{
			$.get('/api/hotelroomsandsuites/en/gethotelconfiguration/?id=' + hotelId, function (data) {
			var defaultDate=window.EQTR.restaurantBooking.getDefaultDate();
			if($('.preload-wrapper').hasClass('loaded'))	
			{
				if (data.StartingDateString) {
				$('#Form_SelectedDateTime').val(data.StartingDateString);
				}
				else
				{
					$('#Form_SelectedDateTime').val(defaultDate);
				}
			}
			window.EQTR.roomBooking.updateRoomDropDown(data.RoomsList,$('select#Form_SelectedRooms'));
		});
		}
        
    });
}
function TabletScondLineMenuHeight()
{
    var nav_container_fluid = $('.header-middle .navbar .container-fluid');
    var header_height = 150;
    if (window_width >= 768 && window_width < 992) {
        header_height = 116 + nav_container_fluid.outerHeight();
    }
    var wrapper_sticky = $('.wrapper-sticky');
    var wrapper_sticky_height = wrapper_sticky.height();

    if (window_width >= 768 && window_width < 992) {
        if (wrapper_sticky_height != header_height)
            wrapper_sticky.height(header_height);
    }
}
function PromotionFilterDropdownTrigger()
{
	$('.packages-filter-nav .dropdown').on("show.bs.dropdown", function () {
		$('.packages-filter-nav').css('margin-bottom',283);
		$('.packages-filter-nav .dropdown').not(this).find('.dropdown-menu').css('display','none');
	});
	$('.packages-filter-nav .dropdown').on("hide.bs.dropdown", function () {
		$('.packages-filter-nav').css('margin-bottom',0);
		$(this).find('.dropdown-menu').css('display','none');
	});
	$(".packages-filter-nav .delete-filter-content").on("click", function (event) {
		
		$.ajax({
			type: "get",
			url: "/promotions/Filter",
			data: {},
			traditional:true,
			success: function(response){
				$('.filter-content').html($(response).find('.filter-content'));
				$(".responsive-cover-background-image").responsiveInlineBackgroundImage();
				SetSimiliarHeightBlocks();
			}, beforeSend: function () {
			$('.preload-wrapper').removeClass('loaded');
			
        },
        complete: function (jqXHR, textStatus) {
            $('.preload-wrapper').addClass('loaded');
			$('.packages-filter-nav').css('margin-bottom',0);
		$('.packages-filter-nav .dropdown').find('.dropdown-menu').css('display','none');
		$('.results-arrow').css('display','none');
		$('.destination-filter-drp').removeClass('open');
		$('.category-filter-drp').removeClass('open');
		$('.packages-filter-nav .dropdown .dropdown-toggle').removeClass('selected-item');
		$('.packages-filter-nav .dropdown-menu li').removeClass('selected-item');
		$(".packages-filter-nav .delete-filter-content .filter-span").removeClass('selected-item');
        }
		});
        return false;
	});
	$(".packages-filter-nav .dropdown-menu").on("click", "li", function (event) {
		$(this).addClass('selected-item');
		$(this).parents('.dropdown').find('.dropdown-toggle').addClass('selected-item');
		
		
		hotels = [];
		var hotelscount=0;
		$('.destination-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
			if ($(this).attr('id').indexOf(',') != -1) {
				var arr = $(this).attr('id').split(',');
				$.each(arr, function(splitindex, obj){
					hotels[hotelscount]=arr[splitindex];
					hotelscount++;
				});
			}
			else{
				hotels[hotelscount]=$(this).attr('id');
				hotelscount++;
			}
            
			
        });
		
		categories = [];
		$('.category-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
            categories[index]=$(this).attr('id');
        });
		

		$.ajax({
			type: "get",
			url: "/promotions/Filter",
			data: {hotels:hotels,categories:categories},
			traditional:true,
			success: function(response){
				$('.filter-content').html($(response).find('.filter-content'));
				var packagesCount=$('.filter-content').find('.block-boot').length;
				var results_message=$('.results-arrow .filter-text').data('message');
				$('.results-arrow .filter-text').text(results_message.format(packagesCount));
				$('.results-arrow').css('display','block');
				$(".responsive-cover-background-image").responsiveInlineBackgroundImage();
				SetSimiliarHeightBlocks();
				$(".packages-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
			}, beforeSend: function () {
$('.preload-wrapper').removeClass('loaded');
        },
        complete: function (jqXHR, textStatus) {
            $('.preload-wrapper').addClass('loaded');
        }
		});
        return false;
    });
	
	 jQuery('#mobile-packages-filter a.filter_toggle').click(function(){
			$('.each_filter').not($(this).parent('.each_filter')).removeClass('menu_open');
            jQuery(this).parent('.each_filter').toggleClass('menu_open');
        })

        jQuery('#mobile-packages-filter .filter_head').click(function(){
    
            jQuery(this).parent('#mobile-packages-filter').removeClass('open');
			
			$('.each_filter').removeClass('menu_open');
			jQuery('html body').css('overflow', 'inherit');
			jQuery('html body').css('position', 'relative');
			var scrollTop = jQuery('#mobile-packages-filter').data( "scrollTop");
			$(window).scrollTop(parseInt(scrollTop));
        })

        jQuery('#mobile-packages-filter .each_filter .filter_items li').click(function(){
    
            jQuery(this).toggleClass('menu_act');
			
			hotels = [];
		var hotelscount=0;
		$('#mobile-packages-filter .hotel-filter-mob-drp').find('li.menu_act').each(function (index) {
			if ($(this).attr('id').indexOf(',') != -1) {
				var arr = $(this).attr('id').split(',');
				$.each(arr, function(splitindex, obj){
					hotels[hotelscount]=arr[splitindex];
					hotelscount++;
				});
			}
			else{
				hotels[hotelscount]=$(this).attr('id');
				hotelscount++;
			}
            
			
        });
		
		categories = [];
		$('#mobile-packages-filter .category-filter-mob-drp').find('li.menu_act').each(function (index) {
            categories[index]=$(this).attr('id');
        });
		var element = this;

		$.ajax({
			type: "get",
			url: "/promotions/Filter",
			data: {hotels:hotels,categories:categories},
			traditional:true,
			success: function(response){
				$('.filter-content').html($(response).find('.filter-content'));
				$(".responsive-cover-background-image").responsiveInlineBackgroundImage();
				SetSimiliarHeightBlocks();
			}, beforeSend: function () {
$('.preload-wrapper-mob').removeClass('loaded');
        },
        complete: function (jqXHR, textStatus) {
            $('.preload-wrapper-mob').addClass('loaded');
			jQuery('#mobile-packages-filter').removeClass('open');
			
			$('.each_filter').removeClass('menu_open');
			jQuery('html body').css('overflow', 'inherit');
			jQuery('html body').css('position', 'relative');
			var scrollTop = jQuery('#mobile-packages-filter').data( "scrollTop");
			$(window).scrollTop(parseInt(scrollTop));
			$(element).parents('.each_filter').find('.filter_toggle').addClass('selected-item');
			$('.delete-filter-content .filter-span').addClass('selected-item');
        }
		});
        }) 

        jQuery('#mobile-packages-filter .delete-filter-content').click(function(){
    
            jQuery('#mobile-packages-filter .each_filter .filter_items li').removeClass('menu_act');
			$.ajax({
			type: "get",
			url: "/promotions/Filter",
			data: {},
			traditional:true,
			success: function(response){
				$('.filter-content').html($(response).find('.filter-content'));
				$(".responsive-cover-background-image").responsiveInlineBackgroundImage();
				SetSimiliarHeightBlocks();
			}, beforeSend: function () {
$('.preload-wrapper-mob').removeClass('loaded');
        },
        complete: function (jqXHR, textStatus) {
            $('.preload-wrapper-mob').addClass('loaded');
			jQuery('#mobile-packages-filter').removeClass('open');
			
			$('.each_filter').removeClass('menu_open');
			jQuery('html body').css('overflow', 'inherit');
			jQuery('html body').css('position', 'relative');
			var scrollTop = jQuery('#mobile-packages-filter').data( "scrollTop");
			$(window).scrollTop(parseInt(scrollTop));
			$('.each_filter .filter_toggle').removeClass('selected-item');
			$('.delete-filter-content .filter-span').removeClass('selected-item');
        }
		});
        }) 
		jQuery('.packages-filter-nav.mobile>ul>li').click(function(){
			jQuery('#mobile-packages-filter').data( "scrollTop", $(window).scrollTop() );
            jQuery('#mobile-packages-filter').addClass('open');
			jQuery('html body').css('overflow', 'hidden');
			jQuery('html body').css('position', 'fixed');
        })
		
if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        var str = this;

        function replaceByObjectProperies(obj) {
            for (var property in obj)
                if (obj.hasOwnProperty(property))
                    //replace all instances case-insensitive
                    str = str.replace(new RegExp(escapeRegExp("{" + property + "}"), 'gi'), String(obj[property]));
        }

        function escapeRegExp(string) {
            return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
        }

        function replaceByArray(arrayLike) {
            for (var i = 0, len = arrayLike.length; i < len; i++)
                str = str.replace(new RegExp(escapeRegExp("{" + i + "}"), 'gi'), String(arrayLike[i]));
        }

        if (!arguments.length || arguments[0] === null || arguments[0] === undefined)
            return str;
        else if (arguments.length == 1 && Array.isArray(arguments[0]))
            replaceByArray(arguments[0]);
        else if (arguments.length == 1 && typeof arguments[0] === "object")
            replaceByObjectProperies(arguments[0]);
        else
            replaceByArray(arguments);

        return str;
    };
}

}
function SetNotebookBlocksHeight() {
    var block_content_ht = 0;
    $('.blocks .three-inline-blocks .each_note .note_content').each(function () {

        if ($(this).outerHeight() > block_content_ht) {
            block_content_ht = $(this).outerHeight();
        }
    });
    $('.blocks .three-inline-blocks .each_note .note_content').outerHeight(block_content_ht);
    
}

function NotebookFilterDropdownTrigger() {
    $('.blog-filter-nav .dropdown').on("show.bs.dropdown", function () {
        $('.blog-filter-nav').css('margin-bottom', 283);
        $('.blog-filter-nav .dropdown').not(this).find('.dropdown-menu').css('display', 'none');
		$(this).find('.dropdown-menu').css('display', 'block');
    });
    $('.blog-filter-nav .dropdown').on("hide.bs.dropdown", function () {
        $('.blog-filter-nav').css('margin-bottom', 0);
        $(this).find('.dropdown-menu').css('display', 'none');
    });
    $('.results-arrow , .results-arrow .filter-text').on('click', function (e) {
        return false;
    });
    $(".blog-filter-nav .delete-filter-content").on("click", function (event) {

        $.ajax({
            type: "get",
            url: "/the-notebook/filter",
            data: {},
            traditional: true,
            success: function (response) {
                $('.filter-content').html($(response).find('.filter-content'));
                $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
                SetNotebookBlocksHeight();
            }, beforeSend: function () {
                $('.preload-wrapper').removeClass('loaded');

            },
            complete: function (jqXHR, textStatus) {
                $('.preload-wrapper').addClass('loaded');
                $('.blog-filter-nav').css('margin-bottom', 0);
                $('.blog-filter-nav .dropdown').find('.dropdown-menu').css('display', 'none');
                $('.results-arrow').css('display', 'none');
                $('.destination-filter-drp').removeClass('open');
                $('.category-filter-drp').removeClass('open');
                $('.blog-filter-nav .dropdown .dropdown-toggle').removeClass('selected-item');
                $('.blog-filter-nav .dropdown-menu li').removeClass('selected-item');
                $(".blog-filter-nav .delete-filter-content .filter-span").removeClass('selected-item');
				$('#notebook_search_form .search_input').val('');
            }
        });
        return false;
    });
    $(".blog-filter-nav .dropdown-menu").on("click", "li", function (event) {
        
		if($(this).hasClass('selected-item')){
			$(this).removeClass('selected-item');
		}else{
			$(this).addClass('selected-item');
		}


        hotels = [];
        var hotelscount = 0;
        $('.destination-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
            if ($(this).attr('id').indexOf(',') != -1) {
                var arr = $(this).attr('id').split(',');
                $.each(arr, function (splitindex, obj) {
                    hotels[hotelscount] = arr[splitindex];
                    hotelscount++;
                });
            }
            else {
                hotels[hotelscount] = $(this).attr('id');
                hotelscount++;
            }


        });
		
		if(hotels.length > 0){
			$(this).parents('.dropdown.destination-filter-drp').find('.dropdown-toggle').addClass('selected-item');
		}else{
			$(this).parents('.dropdown.destination-filter-drp').find('.dropdown-toggle').removeClass('selected-item');
		}

        categories = [];
        $('.category-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
            categories[index] = $(this).attr('id');
        });
		
		if(categories.length > 0){
			$(this).parents('.dropdown.category-filter-drp').find('.dropdown-toggle').addClass('selected-item');
		}else{
			$(this).parents('.dropdown.category-filter-drp').find('.dropdown-toggle').removeClass('selected-item');
		}

		searchText = $('.search_input').val();
        $.ajax({
            type: "get",
            url: "/the-notebook/filter",
            data: { cities: hotels, categories: categories, searchText:searchText, page:$('note_pagination').data('page') },
            traditional: true,
            success: function (response) {
                $('.filter-content').html($(response).find('.filter-content'));
                $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
                SetNotebookBlocksHeight();
                // $(".blog-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
				if(hotels.length > 0 || categories.length > 0){
					$(".blog-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
				}else{
					$(".blog-filter-nav .delete-filter-content .filter-span").removeClass('selected-item');
				}
            }, beforeSend: function () {
                $('.preload-wrapper').removeClass('loaded');
            },
            complete: function (jqXHR, textStatus) {
                $('.preload-wrapper').addClass('loaded');
            }
        });
        return false;
    });
	$('form#notebook_search_form').submit(function () {
        hotels = [];
        var hotelscount = 0;
        $('.destination-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
            if ($(this).attr('id').indexOf(',') != -1) {
                var arr = $(this).attr('id').split(',');
                $.each(arr, function (splitindex, obj) {
                    hotels[hotelscount] = arr[splitindex];
                    hotelscount++;
                });
            }
            else {
                hotels[hotelscount] = $(this).attr('id');
                hotelscount++;
            }


        });

        categories = [];
        $('.category-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
            categories[index] = $(this).attr('id');
        });
        searchText = $('.search_input').val();
        $.ajax({
            url: "/the-notebook/filter",
            type: 'POST',
            data: { cities: hotels, categories: categories, searchText:searchText,page:$('note_pagination').data('page') },
            traditional: true,
            success: function (response) {
                $('.filter-content').html($(response).find('.filter-content'));
                $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
                SetNotebookBlocksHeight();
                // $(".blog-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
				if(hotels.length > 0 || categories.length > 0){
					$(".blog-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
				}else{
					$(".blog-filter-nav .delete-filter-content .filter-span").removeClass('selected-item');
				}
            }, beforeSend: function () {
                $('.preload-wrapper').removeClass('loaded');
            },
            complete: function (jqXHR, textStatus) {
                $('.preload-wrapper').addClass('loaded');
            }
        });
        return false;
    });
	$('.notebook').on("click",'.button-next', function (event) {
		$('html, body').animate({scrollTop:0}, 'slow');
        hotels = [];
        var hotelscount = 0;
        $('.destination-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
            if ($(this).attr('id').indexOf(',') != -1) {
                var arr = $(this).attr('id').split(',');
                $.each(arr, function (splitindex, obj) {
                    hotels[hotelscount] = arr[splitindex];
                    hotelscount++;
                });
            }
            else {
                hotels[hotelscount] = $(this).attr('id');
                hotelscount++;
            }


        });

        categories = [];
        $('.category-filter-drp .dropdown-menu').find('li.selected-item').each(function (index) {
            categories[index] = $(this).attr('id');
        });
        searchText = $('.search_input').val();
        $.ajax({
            url: "/the-notebook/filter",
            type: 'get',
            data: { cities: hotels, categories: categories, searchText:searchText,page:$(this).data('page') },
            traditional: true,
            success: function (response) {
                $('.filter-content').html($(response).find('.filter-content'));
                $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
                SetNotebookBlocksHeight();
                // $(".blog-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
				if(hotels.length > 0 || categories.length > 0){
					$(".blog-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
				}else{
					$(".blog-filter-nav .delete-filter-content .filter-span").removeClass('selected-item');
				}
            }, beforeSend: function () {
                $('.preload-wrapper').removeClass('loaded');
            },
            complete: function (jqXHR, textStatus) {
                $('.preload-wrapper').addClass('loaded');
            }
        });
        return false;
    });
	
	$('.notebook').on("click",'.button-next-mobile', function (event) {
		$('html, body').animate({scrollTop:0}, 'slow');
        hotels = [];
        var hotelscount = 0;
        $('#mobile-blog-filter .hotel-filter-mob-drp').find('li.menu_act').each(function (index) {
            if ($(this).attr('id').indexOf(',') != -1) {
                var arr = $(this).attr('id').split(',');
                $.each(arr, function (splitindex, obj) {
                    hotels[hotelscount] = arr[splitindex];
                    hotelscount++;
                });
            }
            else {
                hotels[hotelscount] = $(this).attr('id');
                hotelscount++;
            }


        });

        categories = [];
        $('#mobile-blog-filter .category-filter-mob-drp').find('li.menu_act').each(function (index) {
            categories[index] = $(this).attr('id');
        });
        searchText = $('.search_input').val();
        $.ajax({
            url: "/the-notebook/filter",
            type: 'get',
            data: { cities: hotels, categories: categories, searchText:searchText,page:$(this).data('page') },
            traditional: true,
            success: function (response) {
                $('.filter-content').html($(response).find('.filter-content'));
                $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
                SetNotebookBlocksHeight();
                // $(".blog-filter-nav .delete-filter-content .filter-span").addClass('selected-item');
				if(hotels.length > 0 || categories.length > 0){
					$(".delete-filter-content .filter-span").addClass('selected-item');
				}else{
					$(".delete-filter-content .filter-span").removeClass('selected-item');
				}
            }, beforeSend: function () {
                $('.preload-wrapper').removeClass('loaded');
            },
            complete: function (jqXHR, textStatus) {
                $('.preload-wrapper').addClass('loaded');
            }
        });
        return false;
    });
	
    jQuery('#mobile-blog-filter a.filter_toggle').click(function () {
        $('.each_filter').not($(this).parent('.each_filter')).removeClass('menu_open');
        jQuery(this).parent('.each_filter').toggleClass('menu_open');
    })

    jQuery('#mobile-blog-filter .filter_head').click(function () {

        jQuery(this).parent('#mobile-blog-filter').removeClass('open');

        $('.each_filter').removeClass('menu_open');
        jQuery('html body').css('overflow', 'inherit');
        jQuery('html body').css('position', 'relative');
        var scrollTop = jQuery('#mobile-blog-filter').data("scrollTop");
        $(window).scrollTop(parseInt(scrollTop));
    })

    jQuery('#mobile-blog-filter .each_filter .filter_items li').click(function () {

        jQuery(this).toggleClass('menu_act');


        hotels = [];
        var hotelscount = 0;
        $('#mobile-blog-filter .hotel-filter-mob-drp').find('li.menu_act').each(function (index) {
            if ($(this).attr('id').indexOf(',') != -1) {
                var arr = $(this).attr('id').split(',');
                $.each(arr, function (splitindex, obj) {
                    hotels[hotelscount] = arr[splitindex];
                    hotelscount++;
                });
            }
            else {
                hotels[hotelscount] = $(this).attr('id');
                hotelscount++;
            }


        });
		
		if(hotels.length > 0){
			$(this).parents('.each_filter.hotel-filter-mob-drp').find('.filter_toggle').addClass('selected-item');
		}else{
			$(this).parents('.each_filter.hotel-filter-mob-drp').find('.filter_toggle').removeClass('selected-item');
		}

        categories = [];
        $('#mobile-blog-filter .category-filter-mob-drp').find('li.menu_act').each(function (index) {
            categories[index] = $(this).attr('id');
        });
		
		if(categories.length > 0){
			$(this).parents('.each_filter.category-filter-mob-drp').find('.filter_toggle').addClass('selected-item');
		}else{
			$(this).parents('.each_filter.category-filter-mob-drp').find('.filter_toggle').removeClass('selected-item');
		}
		
        var element = this;
		
		searchText = $('.search_input').val();
		
        $.ajax({
            type: "get",
            url: "/the-notebook/filter",
            data: { cities: hotels, categories: categories, searchText:searchText,page:$(this).data('page') },
            traditional: true,
            success: function (response) {
                $('.filter-content').html($(response).find('.filter-content'));
                $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
                SetSimiliarHeightBlocks();
            }, beforeSend: function () {
                $('.preload-wrapper-mob').removeClass('loaded');
            },
            complete: function (jqXHR, textStatus) {
                $('.preload-wrapper-mob').addClass('loaded');
                jQuery('#mobile-blog-filter').removeClass('open');

                $('.each_filter').removeClass('menu_open');
                jQuery('html body').css('overflow', 'inherit');
                jQuery('html body').css('position', 'relative');
                var scrollTop = jQuery('#mobile-blog-filter').data("scrollTop");
                $(window).scrollTop(parseInt(scrollTop));
                // $(element).parents('.each_filter').find('.filter_toggle').addClass('selected-item');
                // $('.delete-filter-content .filter-span').addClass('selected-item');
				if(hotels.length > 0 || categories.length > 0){
					$('.delete-filter-content .filter-span').addClass('selected-item');
				}else{
					$('.delete-filter-content .filter-span').removeClass('selected-item');
				}
			}
        });
    })

    jQuery('#mobile-blog-filter .delete-filter-content').click(function () {

        jQuery('#mobile-blog-filter .each_filter .filter_items li').removeClass('menu_act');
        $.ajax({
            type: "get",
            url: "/the-notebook/filter",
            data: {},
            traditional: true,
            success: function (response) {
                $('.filter-content').html($(response).find('.filter-content'));
                $(".responsive-cover-background-image").responsiveInlineBackgroundImage();
                SetSimiliarHeightBlocks();
            }, beforeSend: function () {
                $('.preload-wrapper-mob').removeClass('loaded');
            },
            complete: function (jqXHR, textStatus) {
                $('.preload-wrapper-mob').addClass('loaded');
                jQuery('#mobile-blog-filter').removeClass('open');

                $('.each_filter').removeClass('menu_open');
                jQuery('html body').css('overflow', 'inherit');
                jQuery('html body').css('position', 'relative');
                var scrollTop = jQuery('#mobile-blog-filter').data("scrollTop");
                $(window).scrollTop(parseInt(scrollTop));
                $('.each_filter .filter_toggle').removeClass('selected-item');
                $('.delete-filter-content .filter-span').removeClass('selected-item');
            }
        });
    })
    jQuery('.blog-filter-nav.mobile>ul>li').click(function () {
		jQuery('#mobile-blog-filter').data("scrollTop", $(window).scrollTop());
        jQuery('#mobile-blog-filter').addClass('open');
        jQuery('html body').css('overflow', 'hidden');
        jQuery('html body').css('position', 'fixed');
    })

    if (!String.prototype.format) {
        String.prototype.format = function () {
            var args = arguments;
            var str = this;

            function replaceByObjectProperies(obj) {
                for (var property in obj)
                    if (obj.hasOwnProperty(property))
                        //replace all instances case-insensitive
                        str = str.replace(new RegExp(escapeRegExp("{" + property + "}"), 'gi'), String(obj[property]));
            }

            function escapeRegExp(string) {
                return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
            }

            function replaceByArray(arrayLike) {
                for (var i = 0, len = arrayLike.length; i < len; i++)
                    str = str.replace(new RegExp(escapeRegExp("{" + i + "}"), 'gi'), String(arrayLike[i]));
            }

            if (!arguments.length || arguments[0] === null || arguments[0] === undefined)
                return str;
            else if (arguments.length == 1 && Array.isArray(arguments[0]))
                replaceByArray(arguments[0]);
            else if (arguments.length == 1 && typeof arguments[0] === "object")
                replaceByObjectProperies(arguments[0]);
            else
                replaceByArray(arguments);

            return str;
        };
    }

}

function SetformInputLabelHeight() {
    $(".input-container.last").each(function (e) {
        var labelHeight = $(this).find('label').outerHeight();
        var leftContainer = $(this).prev();
        if (leftContainer.find('label').outerHeight() > labelHeight) {
            labelHeight = leftContainer.find('label').outerHeight();
        }
        $(this).parent('.input-row').find('label').outerHeight(labelHeight);
    });
}

$(".single-hotel-page a.img_pop_btn").click(function (e) {
    e.preventDefault();
    var imgUrl = $(this).attr('href');
    $('#floorplan-modal .modal-image-wrap img').attr('src', imgUrl);
    $('.wrapper-sticky').css({ visibility: 'hidden' });
    $('#floorplan-modal').modal({
        backdrop: false
    });
})

$('#floorplan-modal').on('hidden.bs.modal', function () {
    $('.wrapper-sticky').css({ visibility: 'visible' });
});

$(window).load(function(){
	if (isMobile) {
		$('.GenericSubPageTemplate .gen-subpage-new-carousel.panel-scroll').height('auto');
		$('.GenericSubPageTemplate .gen-subpage-new-carousel.panel-scroll .scroll-nav.left').css('visibility','visible');
		$('.GenericSubPageTemplate .gen-subpage-new-carousel.panel-scroll .scroll-nav.down').css('visibility','visible');
		$('.GenericSubPageTemplate .gen-subpage-new-carousel.panel-scroll .scroll-nav.right').css('visibility','visible');
	}
	
	/*villas redesign page update*/
	if ($(window).width()<992) {
		
		jQuery('.facility_acc_wrap .each_fac_col .fa_acc_title').click(function () {
            jQuery(this).closest('.each_fac_col').find('.fa_acc_content').slideToggle('slow', function () {
                if (jQuery(this).closest('.each_fac_col').find('.fa_acc_content').is(':hidden')) {
                    jQuery(this).closest('.each_fac_col').removeClass('acc_act');
                }
                else {
                    jQuery(this).closest('.each_fac_col').addClass('acc_act');
                }
            });
        });

        jQuery('.hv_extra_content_wrap .hv_read_btn span').click(function () {
            jQuery(this).closest('.hv_extra_content_wrap').find('.hv_extra_content').slideToggle('slow', function () {
                if (jQuery(this).closest('.hv_extra_content_wrap').find('.hv_extra_content').is(':hidden')) {
                    jQuery(this).closest('.hv_extra_content_wrap').removeClass('acc_act');
                }
                else {
                    jQuery(this).closest('.hv_extra_content_wrap').addClass('acc_act');
                }
            });
        });
	}
})
;
/*! Magnific Popup - v1.1.0 - 2016-02-20
* http://dimsemenov.com/plugins/magnific-popup/
* Copyright (c) 2016 Dmitry Semenov; */
;(function (factory) { 
if (typeof define === 'function' && define.amd) { 
 // AMD. Register as an anonymous module. 
 define(['jquery'], factory); 
 } else if (typeof exports === 'object') { 
 // Node/CommonJS 
 factory(require('jquery')); 
 } else { 
 // Browser globals 
 factory(window.jQuery || window.Zepto); 
 } 
 }(function($) { 

/*>>core*/
/**
 * 
 * Magnific Popup Core JS file
 * 
 */


/**
 * Private static constants
 */
var CLOSE_EVENT = 'Close',
	BEFORE_CLOSE_EVENT = 'BeforeClose',
	AFTER_CLOSE_EVENT = 'AfterClose',
	BEFORE_APPEND_EVENT = 'BeforeAppend',
	MARKUP_PARSE_EVENT = 'MarkupParse',
	OPEN_EVENT = 'Open',
	CHANGE_EVENT = 'Change',
	NS = 'mfp',
	EVENT_NS = '.' + NS,
	READY_CLASS = 'mfp-ready',
	REMOVING_CLASS = 'mfp-removing',
	PREVENT_CLOSE_CLASS = 'mfp-prevent-close';


/**
 * Private vars 
 */
/*jshint -W079 */
var mfp, // As we have only one instance of MagnificPopup object, we define it locally to not to use 'this'
	MagnificPopup = function(){},
	_isJQ = !!(window.jQuery),
	_prevStatus,
	_window = $(window),
	_document,
	_prevContentType,
	_wrapClasses,
	_currPopupType;


/**
 * Private functions
 */
var _mfpOn = function(name, f) {
		mfp.ev.on(NS + name + EVENT_NS, f);
	},
	_getEl = function(className, appendTo, html, raw) {
		var el = document.createElement('div');
		el.className = 'mfp-'+className;
		if(html) {
			el.innerHTML = html;
		}
		if(!raw) {
			el = $(el);
			if(appendTo) {
				el.appendTo(appendTo);
			}
		} else if(appendTo) {
			appendTo.appendChild(el);
		}
		return el;
	},
	_mfpTrigger = function(e, data) {
		mfp.ev.triggerHandler(NS + e, data);

		if(mfp.st.callbacks) {
			// converts "mfpEventName" to "eventName" callback and triggers it if it's present
			e = e.charAt(0).toLowerCase() + e.slice(1);
			if(mfp.st.callbacks[e]) {
				mfp.st.callbacks[e].apply(mfp, $.isArray(data) ? data : [data]);
			}
		}
	},
	_getCloseBtn = function(type) {
		if(type !== _currPopupType || !mfp.currTemplate.closeBtn) {
			mfp.currTemplate.closeBtn = $( mfp.st.closeMarkup.replace('%title%', mfp.st.tClose ) );
			_currPopupType = type;
		}
		return mfp.currTemplate.closeBtn;
	},
	// Initialize Magnific Popup only when called at least once
	_checkInstance = function() {
		if(!$.magnificPopup.instance) {
			/*jshint -W020 */
			mfp = new MagnificPopup();
			mfp.init();
			$.magnificPopup.instance = mfp;
		}
	},
	// CSS transition detection, http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
	supportsTransitions = function() {
		var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist
			v = ['ms','O','Moz','Webkit']; // 'v' for vendor

		if( s['transition'] !== undefined ) {
			return true; 
		}
			
		while( v.length ) {
			if( v.pop() + 'Transition' in s ) {
				return true;
			}
		}
				
		return false;
	};



/**
 * Public functions
 */
MagnificPopup.prototype = {

	constructor: MagnificPopup,

	/**
	 * Initializes Magnific Popup plugin. 
	 * This function is triggered only once when $.fn.magnificPopup or $.magnificPopup is executed
	 */
	init: function() {
		var appVersion = navigator.appVersion;
		mfp.isLowIE = mfp.isIE8 = document.all && !document.addEventListener;
		mfp.isAndroid = (/android/gi).test(appVersion);
		mfp.isIOS = (/iphone|ipad|ipod/gi).test(appVersion);
		mfp.supportsTransition = supportsTransitions();

		// We disable fixed positioned lightbox on devices that don't handle it nicely.
		// If you know a better way of detecting this - let me know.
		mfp.probablyMobile = (mfp.isAndroid || mfp.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent) );
		_document = $(document);

		mfp.popupsCache = {};
	},

	/**
	 * Opens popup
	 * @param  data [description]
	 */
	open: function(data) {

		var i;

		if(data.isObj === false) { 
			// convert jQuery collection to array to avoid conflicts later
			mfp.items = data.items.toArray();

			mfp.index = 0;
			var items = data.items,
				item;
			for(i = 0; i < items.length; i++) {
				item = items[i];
				if(item.parsed) {
					item = item.el[0];
				}
				if(item === data.el[0]) {
					mfp.index = i;
					break;
				}
			}
		} else {
			mfp.items = $.isArray(data.items) ? data.items : [data.items];
			mfp.index = data.index || 0;
		}

		// if popup is already opened - we just update the content
		if(mfp.isOpen) {
			mfp.updateItemHTML();
			return;
		}
		
		mfp.types = []; 
		_wrapClasses = '';
		if(data.mainEl && data.mainEl.length) {
			mfp.ev = data.mainEl.eq(0);
		} else {
			mfp.ev = _document;
		}

		if(data.key) {
			if(!mfp.popupsCache[data.key]) {
				mfp.popupsCache[data.key] = {};
			}
			mfp.currTemplate = mfp.popupsCache[data.key];
		} else {
			mfp.currTemplate = {};
		}



		mfp.st = $.extend(true, {}, $.magnificPopup.defaults, data ); 
		mfp.fixedContentPos = mfp.st.fixedContentPos === 'auto' ? !mfp.probablyMobile : mfp.st.fixedContentPos;

		if(mfp.st.modal) {
			mfp.st.closeOnContentClick = false;
			mfp.st.closeOnBgClick = false;
			mfp.st.showCloseBtn = false;
			mfp.st.enableEscapeKey = false;
		}
		

		// Building markup
		// main containers are created only once
		if(!mfp.bgOverlay) {

			// Dark overlay
			mfp.bgOverlay = _getEl('bg').on('click'+EVENT_NS, function() {
				mfp.close();
			});

			mfp.wrap = _getEl('wrap').attr('tabindex', -1).on('click'+EVENT_NS, function(e) {
				if(mfp._checkIfClose(e.target)) {
					mfp.close();
				}
			});

			mfp.container = _getEl('container', mfp.wrap);
		}

		mfp.contentContainer = _getEl('content');
		if(mfp.st.preloader) {
			mfp.preloader = _getEl('preloader', mfp.container, mfp.st.tLoading);
		}


		// Initializing modules
		var modules = $.magnificPopup.modules;
		for(i = 0; i < modules.length; i++) {
			var n = modules[i];
			n = n.charAt(0).toUpperCase() + n.slice(1);
			mfp['init'+n].call(mfp);
		}
		_mfpTrigger('BeforeOpen');


		if(mfp.st.showCloseBtn) {
			// Close button
			if(!mfp.st.closeBtnInside) {
				mfp.wrap.append( _getCloseBtn() );
			} else {
				_mfpOn(MARKUP_PARSE_EVENT, function(e, template, values, item) {
					values.close_replaceWith = _getCloseBtn(item.type);
				});
				_wrapClasses += ' mfp-close-btn-in';
			}
		}

		if(mfp.st.alignTop) {
			_wrapClasses += ' mfp-align-top';
		}

	

		if(mfp.fixedContentPos) {
			mfp.wrap.css({
				overflow: mfp.st.overflowY,
				overflowX: 'hidden',
				overflowY: mfp.st.overflowY
			});
		} else {
			mfp.wrap.css({ 
				top: _window.scrollTop(),
				position: 'absolute'
			});
		}
		if( mfp.st.fixedBgPos === false || (mfp.st.fixedBgPos === 'auto' && !mfp.fixedContentPos) ) {
			mfp.bgOverlay.css({
				height: _document.height(),
				position: 'absolute'
			});
		}

		

		if(mfp.st.enableEscapeKey) {
			// Close on ESC key
			_document.on('keyup' + EVENT_NS, function(e) {
				if(e.keyCode === 27) {
					mfp.close();
				}
			});
		}

		_window.on('resize' + EVENT_NS, function() {
			mfp.updateSize();
		});


		if(!mfp.st.closeOnContentClick) {
			_wrapClasses += ' mfp-auto-cursor';
		}
		
		if(_wrapClasses)
			mfp.wrap.addClass(_wrapClasses);


		// this triggers recalculation of layout, so we get it once to not to trigger twice
		var windowHeight = mfp.wH = _window.height();

		
		var windowStyles = {};

		if( mfp.fixedContentPos ) {
            if(mfp._hasScrollBar(windowHeight)){
                var s = mfp._getScrollbarSize();
                if(s) {
                    windowStyles.marginRight = s;
                }
            }
        }

		if(mfp.fixedContentPos) {
			if(!mfp.isIE7) {
				windowStyles.overflow = 'hidden';
			} else {
				// ie7 double-scroll bug
				$('body, html').css('overflow', 'hidden');
			}
		}

		
		
		var classesToadd = mfp.st.mainClass;
		if(mfp.isIE7) {
			classesToadd += ' mfp-ie7';
		}
		if(classesToadd) {
			mfp._addClassToMFP( classesToadd );
		}

		// add content
		mfp.updateItemHTML();

		_mfpTrigger('BuildControls');

		// remove scrollbar, add margin e.t.c
		$('html').css(windowStyles);
		
		// add everything to DOM
		mfp.bgOverlay.add(mfp.wrap).prependTo( mfp.st.prependTo || $(document.body) );

		// Save last focused element
		mfp._lastFocusedEl = document.activeElement;
		
		// Wait for next cycle to allow CSS transition
		setTimeout(function() {
			
			if(mfp.content) {
				mfp._addClassToMFP(READY_CLASS);
				mfp._setFocus();
			} else {
				// if content is not defined (not loaded e.t.c) we add class only for BG
				mfp.bgOverlay.addClass(READY_CLASS);
			}
			
			// Trap the focus in popup
			_document.on('focusin' + EVENT_NS, mfp._onFocusIn);

		}, 16);

		mfp.isOpen = true;
		mfp.updateSize(windowHeight);
		_mfpTrigger(OPEN_EVENT);

		return data;
	},

	/**
	 * Closes the popup
	 */
	close: function() {
		if(!mfp.isOpen) return;
		_mfpTrigger(BEFORE_CLOSE_EVENT);

		mfp.isOpen = false;
		// for CSS3 animation
		if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition )  {
			mfp._addClassToMFP(REMOVING_CLASS);
			setTimeout(function() {
				mfp._close();
			}, mfp.st.removalDelay);
		} else {
			mfp._close();
		}
	},

	/**
	 * Helper for close() function
	 */
	_close: function() {
		_mfpTrigger(CLOSE_EVENT);

		var classesToRemove = REMOVING_CLASS + ' ' + READY_CLASS + ' ';

		mfp.bgOverlay.detach();
		mfp.wrap.detach();
		mfp.container.empty();

		if(mfp.st.mainClass) {
			classesToRemove += mfp.st.mainClass + ' ';
		}

		mfp._removeClassFromMFP(classesToRemove);

		if(mfp.fixedContentPos) {
			var windowStyles = {marginRight: ''};
			if(mfp.isIE7) {
				$('body, html').css('overflow', '');
			} else {
				windowStyles.overflow = '';
			}
			$('html').css(windowStyles);
		}
		
		_document.off('keyup' + EVENT_NS + ' focusin' + EVENT_NS);
		mfp.ev.off(EVENT_NS);

		// clean up DOM elements that aren't removed
		mfp.wrap.attr('class', 'mfp-wrap').removeAttr('style');
		mfp.bgOverlay.attr('class', 'mfp-bg');
		mfp.container.attr('class', 'mfp-container');

		// remove close button from target element
		if(mfp.st.showCloseBtn &&
		(!mfp.st.closeBtnInside || mfp.currTemplate[mfp.currItem.type] === true)) {
			if(mfp.currTemplate.closeBtn)
				mfp.currTemplate.closeBtn.detach();
		}


		if(mfp.st.autoFocusLast && mfp._lastFocusedEl) {
			$(mfp._lastFocusedEl).focus(); // put tab focus back
		}
		mfp.currItem = null;	
		mfp.content = null;
		mfp.currTemplate = null;
		mfp.prevHeight = 0;

		_mfpTrigger(AFTER_CLOSE_EVENT);
	},
	
	updateSize: function(winHeight) {

		if(mfp.isIOS) {
			// fixes iOS nav bars https://github.com/dimsemenov/Magnific-Popup/issues/2
			var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
			var height = window.innerHeight * zoomLevel;
			mfp.wrap.css('height', height);
			mfp.wH = height;
		} else {
			mfp.wH = winHeight || _window.height();
		}
		// Fixes #84: popup incorrectly positioned with position:relative on body
		if(!mfp.fixedContentPos) {
			mfp.wrap.css('height', mfp.wH);
		}

		_mfpTrigger('Resize');

	},

	/**
	 * Set content of popup based on current index
	 */
	updateItemHTML: function() {
		var item = mfp.items[mfp.index];

		// Detach and perform modifications
		mfp.contentContainer.detach();

		if(mfp.content)
			mfp.content.detach();

		if(!item.parsed) {
			item = mfp.parseEl( mfp.index );
		}

		var type = item.type;

		_mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]);
		// BeforeChange event works like so:
		// _mfpOn('BeforeChange', function(e, prevType, newType) { });

		mfp.currItem = item;

		if(!mfp.currTemplate[type]) {
			var markup = mfp.st[type] ? mfp.st[type].markup : false;

			// allows to modify markup
			_mfpTrigger('FirstMarkupParse', markup);

			if(markup) {
				mfp.currTemplate[type] = $(markup);
			} else {
				// if there is no markup found we just define that template is parsed
				mfp.currTemplate[type] = true;
			}
		}

		if(_prevContentType && _prevContentType !== item.type) {
			mfp.container.removeClass('mfp-'+_prevContentType+'-holder');
		}

		var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]);
		mfp.appendContent(newContent, type);

		item.preloaded = true;

		_mfpTrigger(CHANGE_EVENT, item);
		_prevContentType = item.type;

		// Append container back after its content changed
		mfp.container.prepend(mfp.contentContainer);

		_mfpTrigger('AfterChange');
	},


	/**
	 * Set HTML content of popup
	 */
	appendContent: function(newContent, type) {
		mfp.content = newContent;

		if(newContent) {
			if(mfp.st.showCloseBtn && mfp.st.closeBtnInside &&
				mfp.currTemplate[type] === true) {
				// if there is no markup, we just append close button element inside
				if(!mfp.content.find('.mfp-close').length) {
					mfp.content.append(_getCloseBtn());
				}
			} else {
				mfp.content = newContent;
			}
		} else {
			mfp.content = '';
		}

		_mfpTrigger(BEFORE_APPEND_EVENT);
		mfp.container.addClass('mfp-'+type+'-holder');

		mfp.contentContainer.append(mfp.content);
	},


	/**
	 * Creates Magnific Popup data object based on given data
	 * @param  {int} index Index of item to parse
	 */
	parseEl: function(index) {
		var item = mfp.items[index],
			type;

		if(item.tagName) {
			item = { el: $(item) };
		} else {
			type = item.type;
			item = { data: item, src: item.src };
		}

		if(item.el) {
			var types = mfp.types;

			// check for 'mfp-TYPE' class
			for(var i = 0; i < types.length; i++) {
				if( item.el.hasClass('mfp-'+types[i]) ) {
					type = types[i];
					break;
				}
			}

			item.src = item.el.attr('data-mfp-src');
			if(!item.src) {
				item.src = item.el.attr('href');
			}
		}

		item.type = type || mfp.st.type || 'inline';
		item.index = index;
		item.parsed = true;
		mfp.items[index] = item;
		_mfpTrigger('ElementParse', item);

		return mfp.items[index];
	},


	/**
	 * Initializes single popup or a group of popups
	 */
	addGroup: function(el, options) {
		var eHandler = function(e) {
			e.mfpEl = this;
			mfp._openClick(e, el, options);
		};

		if(!options) {
			options = {};
		}

		var eName = 'click.magnificPopup';
		options.mainEl = el;

		if(options.items) {
			options.isObj = true;
			el.off(eName).on(eName, eHandler);
		} else {
			options.isObj = false;
			if(options.delegate) {
				el.off(eName).on(eName, options.delegate , eHandler);
			} else {
				options.items = el;
				el.off(eName).on(eName, eHandler);
			}
		}
	},
	_openClick: function(e, el, options) {
		var midClick = options.midClick !== undefined ? options.midClick : $.magnificPopup.defaults.midClick;


		if(!midClick && ( e.which === 2 || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey ) ) {
			return;
		}

		var disableOn = options.disableOn !== undefined ? options.disableOn : $.magnificPopup.defaults.disableOn;

		if(disableOn) {
			if($.isFunction(disableOn)) {
				if( !disableOn.call(mfp) ) {
					return true;
				}
			} else { // else it's number
				if( _window.width() < disableOn ) {
					return true;
				}
			}
		}

		if(e.type) {
			e.preventDefault();

			// This will prevent popup from closing if element is inside and popup is already opened
			if(mfp.isOpen) {
				e.stopPropagation();
			}
		}

		options.el = $(e.mfpEl);
		if(options.delegate) {
			options.items = el.find(options.delegate);
		}
		mfp.open(options);
	},


	/**
	 * Updates text on preloader
	 */
	updateStatus: function(status, text) {

		if(mfp.preloader) {
			if(_prevStatus !== status) {
				mfp.container.removeClass('mfp-s-'+_prevStatus);
			}

			if(!text && status === 'loading') {
				text = mfp.st.tLoading;
			}

			var data = {
				status: status,
				text: text
			};
			// allows to modify status
			_mfpTrigger('UpdateStatus', data);

			status = data.status;
			text = data.text;

			mfp.preloader.html(text);

			mfp.preloader.find('a').on('click', function(e) {
				e.stopImmediatePropagation();
			});

			mfp.container.addClass('mfp-s-'+status);
			_prevStatus = status;
		}
	},


	/*
		"Private" helpers that aren't private at all
	 */
	// Check to close popup or not
	// "target" is an element that was clicked
	_checkIfClose: function(target) {

		if($(target).hasClass(PREVENT_CLOSE_CLASS)) {
			return;
		}

		var closeOnContent = mfp.st.closeOnContentClick;
		var closeOnBg = mfp.st.closeOnBgClick;

		if(closeOnContent && closeOnBg) {
			return true;
		} else {

			// We close the popup if click is on close button or on preloader. Or if there is no content.
			if(!mfp.content || $(target).hasClass('mfp-close') || (mfp.preloader && target === mfp.preloader[0]) ) {
				return true;
			}

			// if click is outside the content
			if(  (target !== mfp.content[0] && !$.contains(mfp.content[0], target))  ) {
				if(closeOnBg) {
					// last check, if the clicked element is in DOM, (in case it's removed onclick)
					if( $.contains(document, target) ) {
						return true;
					}
				}
			} else if(closeOnContent) {
				return true;
			}

		}
		return false;
	},
	_addClassToMFP: function(cName) {
		mfp.bgOverlay.addClass(cName);
		mfp.wrap.addClass(cName);
	},
	_removeClassFromMFP: function(cName) {
		this.bgOverlay.removeClass(cName);
		mfp.wrap.removeClass(cName);
	},
	_hasScrollBar: function(winHeight) {
		return (  (mfp.isIE7 ? _document.height() : document.body.scrollHeight) > (winHeight || _window.height()) );
	},
	_setFocus: function() {
		(mfp.st.focus ? mfp.content.find(mfp.st.focus).eq(0) : mfp.wrap).focus();
	},
	_onFocusIn: function(e) {
		if( e.target !== mfp.wrap[0] && !$.contains(mfp.wrap[0], e.target) ) {
			mfp._setFocus();
			return false;
		}
	},
	_parseMarkup: function(template, values, item) {
		var arr;
		if(item.data) {
			values = $.extend(item.data, values);
		}
		_mfpTrigger(MARKUP_PARSE_EVENT, [template, values, item] );

		$.each(values, function(key, value) {
			if(value === undefined || value === false) {
				return true;
			}
			arr = key.split('_');
			if(arr.length > 1) {
				var el = template.find(EVENT_NS + '-'+arr[0]);

				if(el.length > 0) {
					var attr = arr[1];
					if(attr === 'replaceWith') {
						if(el[0] !== value[0]) {
							el.replaceWith(value);
						}
					} else if(attr === 'img') {
						if(el.is('img')) {
							el.attr('src', value);
						} else {
							el.replaceWith( $('<img>').attr('src', value).attr('class', el.attr('class')) );
						}
					} else {
						el.attr(arr[1], value);
					}
				}

			} else {
				template.find(EVENT_NS + '-'+key).html(value);
			}
		});
	},

	_getScrollbarSize: function() {
		// thx David
		if(mfp.scrollbarSize === undefined) {
			var scrollDiv = document.createElement("div");
			scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
			document.body.appendChild(scrollDiv);
			mfp.scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;
			document.body.removeChild(scrollDiv);
		}
		return mfp.scrollbarSize;
	}

}; /* MagnificPopup core prototype end */




/**
 * Public static functions
 */
$.magnificPopup = {
	instance: null,
	proto: MagnificPopup.prototype,
	modules: [],

	open: function(options, index) {
		_checkInstance();

		if(!options) {
			options = {};
		} else {
			options = $.extend(true, {}, options);
		}

		options.isObj = true;
		options.index = index || 0;
		return this.instance.open(options);
	},

	close: function() {
		return $.magnificPopup.instance && $.magnificPopup.instance.close();
	},

	registerModule: function(name, module) {
		if(module.options) {
			$.magnificPopup.defaults[name] = module.options;
		}
		$.extend(this.proto, module.proto);
		this.modules.push(name);
	},

	defaults: {

		// Info about options is in docs:
		// http://dimsemenov.com/plugins/magnific-popup/documentation.html#options

		disableOn: 0,

		key: null,

		midClick: false,

		mainClass: '',

		preloader: true,

		focus: '', // CSS selector of input to focus after popup is opened

		closeOnContentClick: false,

		closeOnBgClick: true,

		closeBtnInside: true,

		showCloseBtn: true,

		enableEscapeKey: true,

		modal: false,

		alignTop: false,

		removalDelay: 0,

		prependTo: null,

		fixedContentPos: 'auto',

		fixedBgPos: 'auto',

		overflowY: 'auto',

		closeMarkup: '<button title="%title%" type="button" class="mfp-close">&#215;</button>',

		tClose: 'Close (Esc)',

		tLoading: 'Loading...',

		autoFocusLast: true

	}
};



$.fn.magnificPopup = function(options) {
	_checkInstance();

	var jqEl = $(this);

	// We call some API method of first param is a string
	if (typeof options === "string" ) {

		if(options === 'open') {
			var items,
				itemOpts = _isJQ ? jqEl.data('magnificPopup') : jqEl[0].magnificPopup,
				index = parseInt(arguments[1], 10) || 0;

			if(itemOpts.items) {
				items = itemOpts.items[index];
			} else {
				items = jqEl;
				if(itemOpts.delegate) {
					items = items.find(itemOpts.delegate);
				}
				items = items.eq( index );
			}
			mfp._openClick({mfpEl:items}, jqEl, itemOpts);
		} else {
			if(mfp.isOpen)
				mfp[options].apply(mfp, Array.prototype.slice.call(arguments, 1));
		}

	} else {
		// clone options obj
		options = $.extend(true, {}, options);

		/*
		 * As Zepto doesn't support .data() method for objects
		 * and it works only in normal browsers
		 * we assign "options" object directly to the DOM element. FTW!
		 */
		if(_isJQ) {
			jqEl.data('magnificPopup', options);
		} else {
			jqEl[0].magnificPopup = options;
		}

		mfp.addGroup(jqEl, options);

	}
	return jqEl;
};

/*>>core*/

/*>>inline*/

var INLINE_NS = 'inline',
	_hiddenClass,
	_inlinePlaceholder,
	_lastInlineElement,
	_putInlineElementsBack = function() {
		if(_lastInlineElement) {
			_inlinePlaceholder.after( _lastInlineElement.addClass(_hiddenClass) ).detach();
			_lastInlineElement = null;
		}
	};

$.magnificPopup.registerModule(INLINE_NS, {
	options: {
		hiddenClass: 'hide', // will be appended with `mfp-` prefix
		markup: '',
		tNotFound: 'Content not found'
	},
	proto: {

		initInline: function() {
			mfp.types.push(INLINE_NS);

			_mfpOn(CLOSE_EVENT+'.'+INLINE_NS, function() {
				_putInlineElementsBack();
			});
		},

		getInline: function(item, template) {

			_putInlineElementsBack();

			if(item.src) {
				var inlineSt = mfp.st.inline,
					el = $(item.src);

				if(el.length) {

					// If target element has parent - we replace it with placeholder and put it back after popup is closed
					var parent = el[0].parentNode;
					if(parent && parent.tagName) {
						if(!_inlinePlaceholder) {
							_hiddenClass = inlineSt.hiddenClass;
							_inlinePlaceholder = _getEl(_hiddenClass);
							_hiddenClass = 'mfp-'+_hiddenClass;
						}
						// replace target inline element with placeholder
						_lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass);
					}

					mfp.updateStatus('ready');
				} else {
					mfp.updateStatus('error', inlineSt.tNotFound);
					el = $('<div>');
				}

				item.inlineElement = el;
				return el;
			}

			mfp.updateStatus('ready');
			mfp._parseMarkup(template, {}, item);
			return template;
		}
	}
});

/*>>inline*/

/*>>ajax*/
var AJAX_NS = 'ajax',
	_ajaxCur,
	_removeAjaxCursor = function() {
		if(_ajaxCur) {
			$(document.body).removeClass(_ajaxCur);
		}
	},
	_destroyAjaxRequest = function() {
		_removeAjaxCursor();
		if(mfp.req) {
			mfp.req.abort();
		}
	};

$.magnificPopup.registerModule(AJAX_NS, {

	options: {
		settings: null,
		cursor: 'mfp-ajax-cur',
		tError: '<a href="%url%">The content</a> could not be loaded.'
	},

	proto: {
		initAjax: function() {
			mfp.types.push(AJAX_NS);
			_ajaxCur = mfp.st.ajax.cursor;

			_mfpOn(CLOSE_EVENT+'.'+AJAX_NS, _destroyAjaxRequest);
			_mfpOn('BeforeChange.' + AJAX_NS, _destroyAjaxRequest);
		},
		getAjax: function(item) {

			if(_ajaxCur) {
				$(document.body).addClass(_ajaxCur);
			}

			mfp.updateStatus('loading');

			var opts = $.extend({
				url: item.src,
				success: function(data, textStatus, jqXHR) {
					var temp = {
						data:data,
						xhr:jqXHR
					};

					_mfpTrigger('ParseAjax', temp);

					mfp.appendContent( $(temp.data), AJAX_NS );

					item.finished = true;

					_removeAjaxCursor();

					mfp._setFocus();

					setTimeout(function() {
						mfp.wrap.addClass(READY_CLASS);
					}, 16);

					mfp.updateStatus('ready');

					_mfpTrigger('AjaxContentAdded');
				},
				error: function() {
					_removeAjaxCursor();
					item.finished = item.loadError = true;
					mfp.updateStatus('error', mfp.st.ajax.tError.replace('%url%', item.src));
				}
			}, mfp.st.ajax.settings);

			mfp.req = $.ajax(opts);

			return '';
		}
	}
});

/*>>ajax*/

/*>>image*/
var _imgInterval,
	_getTitle = function(item) {
		if(item.data && item.data.title !== undefined)
			return item.data.title;

		var src = mfp.st.image.titleSrc;

		if(src) {
			if($.isFunction(src)) {
				return src.call(mfp, item);
			} else if(item.el) {
				return item.el.attr(src) || '';
			}
		}
		return '';
	};

$.magnificPopup.registerModule('image', {

	options: {
		markup: '<div class="mfp-figure">'+
					'<div class="mfp-close"></div>'+
					'<figure>'+
						'<div class="mfp-img"></div>'+
						'<figcaption>'+
							'<div class="mfp-bottom-bar">'+
								'<div class="mfp-title"></div>'+
								'<div class="mfp-counter"></div>'+
							'</div>'+
						'</figcaption>'+
					'</figure>'+
				'</div>',
		cursor: 'mfp-zoom-out-cur',
		titleSrc: 'title',
		verticalFit: true,
		tError: '<a href="%url%">The image</a> could not be loaded.'
	},

	proto: {
		initImage: function() {
			var imgSt = mfp.st.image,
				ns = '.image';

			mfp.types.push('image');

			_mfpOn(OPEN_EVENT+ns, function() {
				if(mfp.currItem.type === 'image' && imgSt.cursor) {
					$(document.body).addClass(imgSt.cursor);
				}
			});

			_mfpOn(CLOSE_EVENT+ns, function() {
				if(imgSt.cursor) {
					$(document.body).removeClass(imgSt.cursor);
				}
				_window.off('resize' + EVENT_NS);
			});

			_mfpOn('Resize'+ns, mfp.resizeImage);
			if(mfp.isLowIE) {
				_mfpOn('AfterChange', mfp.resizeImage);
			}
		},
		resizeImage: function() {
			var item = mfp.currItem;
			if(!item || !item.img) return;

			if(mfp.st.image.verticalFit) {
				var decr = 0;
				// fix box-sizing in ie7/8
				if(mfp.isLowIE) {
					decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'),10);
				}
				item.img.css('max-height', mfp.wH-decr);
			}
		},
		_onImageHasSize: function(item) {
			if(item.img) {

				item.hasSize = true;

				if(_imgInterval) {
					clearInterval(_imgInterval);
				}

				item.isCheckingImgSize = false;

				_mfpTrigger('ImageHasSize', item);

				if(item.imgHidden) {
					if(mfp.content)
						mfp.content.removeClass('mfp-loading');

					item.imgHidden = false;
				}

			}
		},

		/**
		 * Function that loops until the image has size to display elements that rely on it asap
		 */
		findImageSize: function(item) {

			var counter = 0,
				img = item.img[0],
				mfpSetInterval = function(delay) {

					if(_imgInterval) {
						clearInterval(_imgInterval);
					}
					// decelerating interval that checks for size of an image
					_imgInterval = setInterval(function() {
						if(img.naturalWidth > 0) {
							mfp._onImageHasSize(item);
							return;
						}

						if(counter > 200) {
							clearInterval(_imgInterval);
						}

						counter++;
						if(counter === 3) {
							mfpSetInterval(10);
						} else if(counter === 40) {
							mfpSetInterval(50);
						} else if(counter === 100) {
							mfpSetInterval(500);
						}
					}, delay);
				};

			mfpSetInterval(1);
		},

		getImage: function(item, template) {

			var guard = 0,

				// image load complete handler
				onLoadComplete = function() {
					if(item) {
						if (item.img[0].complete) {
							item.img.off('.mfploader');

							if(item === mfp.currItem){
								mfp._onImageHasSize(item);

								mfp.updateStatus('ready');
							}

							item.hasSize = true;
							item.loaded = true;

							_mfpTrigger('ImageLoadComplete');

						}
						else {
							// if image complete check fails 200 times (20 sec), we assume that there was an error.
							guard++;
							if(guard < 200) {
								setTimeout(onLoadComplete,100);
							} else {
								onLoadError();
							}
						}
					}
				},

				// image error handler
				onLoadError = function() {
					if(item) {
						item.img.off('.mfploader');
						if(item === mfp.currItem){
							mfp._onImageHasSize(item);
							mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) );
						}

						item.hasSize = true;
						item.loaded = true;
						item.loadError = true;
					}
				},
				imgSt = mfp.st.image;


			var el = template.find('.mfp-img');
			if(el.length) {
				var img = document.createElement('img');
				img.className = 'mfp-img';
				if(item.el && item.el.find('img').length) {
					img.alt = item.el.find('img').attr('alt');
				}
				item.img = $(img).on('load.mfploader', onLoadComplete).on('error.mfploader', onLoadError);
				img.src = item.src;

				// without clone() "error" event is not firing when IMG is replaced by new IMG
				// TODO: find a way to avoid such cloning
				if(el.is('img')) {
					item.img = item.img.clone();
				}

				img = item.img[0];
				if(img.naturalWidth > 0) {
					item.hasSize = true;
				} else if(!img.width) {
					item.hasSize = false;
				}
			}

			mfp._parseMarkup(template, {
				title: _getTitle(item),
				img_replaceWith: item.img
			}, item);

			mfp.resizeImage();

			if(item.hasSize) {
				if(_imgInterval) clearInterval(_imgInterval);

				if(item.loadError) {
					template.addClass('mfp-loading');
					mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) );
				} else {
					template.removeClass('mfp-loading');
					mfp.updateStatus('ready');
				}
				return template;
			}

			mfp.updateStatus('loading');
			item.loading = true;

			if(!item.hasSize) {
				item.imgHidden = true;
				template.addClass('mfp-loading');
				mfp.findImageSize(item);
			}

			return template;
		}
	}
});

/*>>image*/

/*>>zoom*/
var hasMozTransform,
	getHasMozTransform = function() {
		if(hasMozTransform === undefined) {
			hasMozTransform = document.createElement('p').style.MozTransform !== undefined;
		}
		return hasMozTransform;
	};

$.magnificPopup.registerModule('zoom', {

	options: {
		enabled: false,
		easing: 'ease-in-out',
		duration: 300,
		opener: function(element) {
			return element.is('img') ? element : element.find('img');
		}
	},

	proto: {

		initZoom: function() {
			var zoomSt = mfp.st.zoom,
				ns = '.zoom',
				image;

			if(!zoomSt.enabled || !mfp.supportsTransition) {
				return;
			}

			var duration = zoomSt.duration,
				getElToAnimate = function(image) {
					var newImg = image.clone().removeAttr('style').removeAttr('class').addClass('mfp-animated-image'),
						transition = 'all '+(zoomSt.duration/1000)+'s ' + zoomSt.easing,
						cssObj = {
							position: 'fixed',
							zIndex: 9999,
							left: 0,
							top: 0,
							'-webkit-backface-visibility': 'hidden'
						},
						t = 'transition';

					cssObj['-webkit-'+t] = cssObj['-moz-'+t] = cssObj['-o-'+t] = cssObj[t] = transition;

					newImg.css(cssObj);
					return newImg;
				},
				showMainContent = function() {
					mfp.content.css('visibility', 'visible');
				},
				openTimeout,
				animatedImg;

			_mfpOn('BuildControls'+ns, function() {
				if(mfp._allowZoom()) {

					clearTimeout(openTimeout);
					mfp.content.css('visibility', 'hidden');

					// Basically, all code below does is clones existing image, puts in on top of the current one and animated it

					image = mfp._getItemToZoom();

					if(!image) {
						showMainContent();
						return;
					}

					animatedImg = getElToAnimate(image);

					animatedImg.css( mfp._getOffset() );

					mfp.wrap.append(animatedImg);

					openTimeout = setTimeout(function() {
						animatedImg.css( mfp._getOffset( true ) );
						openTimeout = setTimeout(function() {

							showMainContent();

							setTimeout(function() {
								animatedImg.remove();
								image = animatedImg = null;
								_mfpTrigger('ZoomAnimationEnded');
							}, 16); // avoid blink when switching images

						}, duration); // this timeout equals animation duration

					}, 16); // by adding this timeout we avoid short glitch at the beginning of animation


					// Lots of timeouts...
				}
			});
			_mfpOn(BEFORE_CLOSE_EVENT+ns, function() {
				if(mfp._allowZoom()) {

					clearTimeout(openTimeout);

					mfp.st.removalDelay = duration;

					if(!image) {
						image = mfp._getItemToZoom();
						if(!image) {
							return;
						}
						animatedImg = getElToAnimate(image);
					}

					animatedImg.css( mfp._getOffset(true) );
					mfp.wrap.append(animatedImg);
					mfp.content.css('visibility', 'hidden');

					setTimeout(function() {
						animatedImg.css( mfp._getOffset() );
					}, 16);
				}

			});

			_mfpOn(CLOSE_EVENT+ns, function() {
				if(mfp._allowZoom()) {
					showMainContent();
					if(animatedImg) {
						animatedImg.remove();
					}
					image = null;
				}
			});
		},

		_allowZoom: function() {
			return mfp.currItem.type === 'image';
		},

		_getItemToZoom: function() {
			if(mfp.currItem.hasSize) {
				return mfp.currItem.img;
			} else {
				return false;
			}
		},

		// Get element postion relative to viewport
		_getOffset: function(isLarge) {
			var el;
			if(isLarge) {
				el = mfp.currItem.img;
			} else {
				el = mfp.st.zoom.opener(mfp.currItem.el || mfp.currItem);
			}

			var offset = el.offset();
			var paddingTop = parseInt(el.css('padding-top'),10);
			var paddingBottom = parseInt(el.css('padding-bottom'),10);
			offset.top -= ( $(window).scrollTop() - paddingTop );


			/*

			Animating left + top + width/height looks glitchy in Firefox, but perfect in Chrome. And vice-versa.

			 */
			var obj = {
				width: el.width(),
				// fix Zepto height+padding issue
				height: (_isJQ ? el.innerHeight() : el[0].offsetHeight) - paddingBottom - paddingTop
			};

			// I hate to do this, but there is no another option
			if( getHasMozTransform() ) {
				obj['-moz-transform'] = obj['transform'] = 'translate(' + offset.left + 'px,' + offset.top + 'px)';
			} else {
				obj.left = offset.left;
				obj.top = offset.top;
			}
			return obj;
		}

	}
});



/*>>zoom*/

/*>>iframe*/

var IFRAME_NS = 'iframe',
	_emptyPage = '//about:blank',

	_fixIframeBugs = function(isShowing) {
		if(mfp.currTemplate[IFRAME_NS]) {
			var el = mfp.currTemplate[IFRAME_NS].find('iframe');
			if(el.length) {
				// reset src after the popup is closed to avoid "video keeps playing after popup is closed" bug
				if(!isShowing) {
					el[0].src = _emptyPage;
				}

				// IE8 black screen bug fix
				if(mfp.isIE8) {
					el.css('display', isShowing ? 'block' : 'none');
				}
			}
		}
	};

$.magnificPopup.registerModule(IFRAME_NS, {

	options: {
		markup: '<div class="mfp-iframe-scaler">'+
					'<div class="mfp-close"></div>'+
					'<iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe>'+
				'</div>',

		srcAction: 'iframe_src',

		// we don't care and support only one default type of URL by default
		patterns: {
			youtube: {
				index: 'youtube.com',
				id: 'v=',
				src: '//www.youtube.com/embed/%id%?autoplay=1'
			},
			vimeo: {
				index: 'vimeo.com/',
				id: '/',
				src: '//player.vimeo.com/video/%id%?autoplay=1'
			},
			gmaps: {
				index: '//maps.google.',
				src: '%id%&output=embed'
			}
		}
	},

	proto: {
		initIframe: function() {
			mfp.types.push(IFRAME_NS);

			_mfpOn('BeforeChange', function(e, prevType, newType) {
				if(prevType !== newType) {
					if(prevType === IFRAME_NS) {
						_fixIframeBugs(); // iframe if removed
					} else if(newType === IFRAME_NS) {
						_fixIframeBugs(true); // iframe is showing
					}
				}// else {
					// iframe source is switched, don't do anything
				//}
			});

			_mfpOn(CLOSE_EVENT + '.' + IFRAME_NS, function() {
				_fixIframeBugs();
			});
		},

		getIframe: function(item, template) {
			var embedSrc = item.src;
			var iframeSt = mfp.st.iframe;

			$.each(iframeSt.patterns, function() {
				if(embedSrc.indexOf( this.index ) > -1) {
					if(this.id) {
						if(typeof this.id === 'string') {
							embedSrc = embedSrc.substr(embedSrc.lastIndexOf(this.id)+this.id.length, embedSrc.length);
						} else {
							embedSrc = this.id.call( this, embedSrc );
						}
					}
					embedSrc = this.src.replace('%id%', embedSrc );
					return false; // break;
				}
			});

			var dataObj = {};
			if(iframeSt.srcAction) {
				dataObj[iframeSt.srcAction] = embedSrc;
			}
			mfp._parseMarkup(template, dataObj, item);

			mfp.updateStatus('ready');

			return template;
		}
	}
});



/*>>iframe*/

/*>>gallery*/
/**
 * Get looped index depending on number of slides
 */
var _getLoopedId = function(index) {
		var numSlides = mfp.items.length;
		if(index > numSlides - 1) {
			return index - numSlides;
		} else  if(index < 0) {
			return numSlides + index;
		}
		return index;
	},
	_replaceCurrTotal = function(text, curr, total) {
		return text.replace(/%curr%/gi, curr + 1).replace(/%total%/gi, total);
	};

$.magnificPopup.registerModule('gallery', {

	options: {
		enabled: false,
		arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',
		preload: [0,2],
		navigateByImgClick: true,
		arrows: true,

		tPrev: 'Previous (Left arrow key)',
		tNext: 'Next (Right arrow key)',
		tCounter: '%curr% of %total%'
	},

	proto: {
		initGallery: function() {

			var gSt = mfp.st.gallery,
				ns = '.mfp-gallery';

			mfp.direction = true; // true - next, false - prev

			if(!gSt || !gSt.enabled ) return false;

			_wrapClasses += ' mfp-gallery';

			_mfpOn(OPEN_EVENT+ns, function() {

				if(gSt.navigateByImgClick) {
					mfp.wrap.on('click'+ns, '.mfp-img', function() {
						if(mfp.items.length > 1) {
							mfp.next();
							return false;
						}
					});
				}

				_document.on('keydown'+ns, function(e) {
					if (e.keyCode === 37) {
						mfp.prev();
					} else if (e.keyCode === 39) {
						mfp.next();
					}
				});
			});

			_mfpOn('UpdateStatus'+ns, function(e, data) {
				if(data.text) {
					data.text = _replaceCurrTotal(data.text, mfp.currItem.index, mfp.items.length);
				}
			});

			_mfpOn(MARKUP_PARSE_EVENT+ns, function(e, element, values, item) {
				var l = mfp.items.length;
				values.counter = l > 1 ? _replaceCurrTotal(gSt.tCounter, item.index, l) : '';
			});

			_mfpOn('BuildControls' + ns, function() {
				if(mfp.items.length > 1 && gSt.arrows && !mfp.arrowLeft) {
					var markup = gSt.arrowMarkup,
						arrowLeft = mfp.arrowLeft = $( markup.replace(/%title%/gi, gSt.tPrev).replace(/%dir%/gi, 'left') ).addClass(PREVENT_CLOSE_CLASS),
						arrowRight = mfp.arrowRight = $( markup.replace(/%title%/gi, gSt.tNext).replace(/%dir%/gi, 'right') ).addClass(PREVENT_CLOSE_CLASS);

					arrowLeft.click(function() {
						mfp.prev();
					});
					arrowRight.click(function() {
						mfp.next();
					});

					mfp.container.append(arrowLeft.add(arrowRight));
				}
			});

			_mfpOn(CHANGE_EVENT+ns, function() {
				if(mfp._preloadTimeout) clearTimeout(mfp._preloadTimeout);

				mfp._preloadTimeout = setTimeout(function() {
					mfp.preloadNearbyImages();
					mfp._preloadTimeout = null;
				}, 16);
			});


			_mfpOn(CLOSE_EVENT+ns, function() {
				_document.off(ns);
				mfp.wrap.off('click'+ns);
				mfp.arrowRight = mfp.arrowLeft = null;
			});

		},
		next: function() {
			mfp.direction = true;
			mfp.index = _getLoopedId(mfp.index + 1);
			mfp.updateItemHTML();
		},
		prev: function() {
			mfp.direction = false;
			mfp.index = _getLoopedId(mfp.index - 1);
			mfp.updateItemHTML();
		},
		goTo: function(newIndex) {
			mfp.direction = (newIndex >= mfp.index);
			mfp.index = newIndex;
			mfp.updateItemHTML();
		},
		preloadNearbyImages: function() {
			var p = mfp.st.gallery.preload,
				preloadBefore = Math.min(p[0], mfp.items.length),
				preloadAfter = Math.min(p[1], mfp.items.length),
				i;

			for(i = 1; i <= (mfp.direction ? preloadAfter : preloadBefore); i++) {
				mfp._preloadItem(mfp.index+i);
			}
			for(i = 1; i <= (mfp.direction ? preloadBefore : preloadAfter); i++) {
				mfp._preloadItem(mfp.index-i);
			}
		},
		_preloadItem: function(index) {
			index = _getLoopedId(index);

			if(mfp.items[index].preloaded) {
				return;
			}

			var item = mfp.items[index];
			if(!item.parsed) {
				item = mfp.parseEl( index );
			}

			_mfpTrigger('LazyLoad', item);

			if(item.type === 'image') {
				item.img = $('<img class="mfp-img" />').on('load.mfploader', function() {
					item.hasSize = true;
				}).on('error.mfploader', function() {
					item.hasSize = true;
					item.loadError = true;
					_mfpTrigger('LazyLoadError', item);
				}).attr('src', item.src);
			}


			item.preloaded = true;
		}
	}
});

/*>>gallery*/

/*>>retina*/

var RETINA_NS = 'retina';

$.magnificPopup.registerModule(RETINA_NS, {
	options: {
		replaceSrc: function(item) {
			return item.src.replace(/\.\w+$/, function(m) { return '@2x' + m; });
		},
		ratio: 1 // Function or number.  Set to 1 to disable.
	},
	proto: {
		initRetina: function() {
			if(window.devicePixelRatio > 1) {

				var st = mfp.st.retina,
					ratio = st.ratio;

				ratio = !isNaN(ratio) ? ratio : ratio();

				if(ratio > 1) {
					_mfpOn('ImageHasSize' + '.' + RETINA_NS, function(e, item) {
						item.img.css({
							'max-width': item.img[0].naturalWidth / ratio,
							'width': '100%'
						});
					});
					_mfpOn('ElementParse' + '.' + RETINA_NS, function(e, item) {
						item.src = st.replaceSrc(item, ratio);
					});
				}
			}

		}
	}
});

/*>>retina*/
 _checkInstance(); }));;
/* jquery.nicescroll v3.7.6 InuYaksa - MIT - https://nicescroll.areaaperta.com */
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?module.exports=e(require("jquery")):e(jQuery)}(function(e){"use strict";var o=!1,t=!1,r=0,i=2e3,s=0,n=e,l=document,a=window,c=n(a),d=[],u=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||!1,h=a.cancelAnimationFrame||a.webkitCancelAnimationFrame||a.mozCancelAnimationFrame||!1;if(u)a.cancelAnimationFrame||(h=function(e){});else{var p=0;u=function(e,o){var t=(new Date).getTime(),r=Math.max(0,16-(t-p)),i=a.setTimeout(function(){e(t+r)},r);return p=t+r,i},h=function(e){a.clearTimeout(e)}}var m=a.MutationObserver||a.WebKitMutationObserver||!1,f=Date.now||function(){return(new Date).getTime()},g={zindex:"auto",cursoropacitymin:0,cursoropacitymax:1,cursorcolor:"#424242",cursorwidth:"6px",cursorborder:"1px solid #fff",cursorborderradius:"5px",scrollspeed:40,mousescrollstep:27,touchbehavior:!1,emulatetouch:!1,hwacceleration:!0,usetransition:!0,boxzoom:!1,dblclickzoom:!0,gesturezoom:!0,grabcursorenabled:!0,autohidemode:!0,background:"",iframeautoresize:!0,cursorminheight:32,preservenativescrolling:!0,railoffset:!1,railhoffset:!1,bouncescroll:!0,spacebarenabled:!0,railpadding:{top:0,right:0,left:0,bottom:0},disableoutline:!0,horizrailenabled:!0,railalign:"right",railvalign:"bottom",enabletranslate3d:!0,enablemousewheel:!0,enablekeyboard:!0,smoothscroll:!0,sensitiverail:!0,enablemouselockapi:!0,cursorfixedheight:!1,directionlockdeadzone:6,hidecursordelay:400,nativeparentscrolling:!0,enablescrollonselection:!0,overflowx:!0,overflowy:!0,cursordragspeed:.3,rtlmode:"auto",cursordragontouch:!1,oneaxismousemode:"auto",scriptpath:function(){var e=l.currentScript||function(){var e=l.getElementsByTagName("script");return!!e.length&&e[e.length-1]}(),o=e?e.src.split("?")[0]:"";return o.split("/").length>0?o.split("/").slice(0,-1).join("/")+"/":""}(),preventmultitouchscrolling:!0,disablemutationobserver:!1,enableobserver:!0,scrollbarid:!1},v=!1,w=function(){if(v)return v;var e=l.createElement("DIV"),o=e.style,t=navigator.userAgent,r=navigator.platform,i={};return i.haspointerlock="pointerLockElement"in l||"webkitPointerLockElement"in l||"mozPointerLockElement"in l,i.isopera="opera"in a,i.isopera12=i.isopera&&"getUserMedia"in navigator,i.isoperamini="[object OperaMini]"===Object.prototype.toString.call(a.operamini),i.isie="all"in l&&"attachEvent"in e&&!i.isopera,i.isieold=i.isie&&!("msInterpolationMode"in o),i.isie7=i.isie&&!i.isieold&&(!("documentMode"in l)||7===l.documentMode),i.isie8=i.isie&&"documentMode"in l&&8===l.documentMode,i.isie9=i.isie&&"performance"in a&&9===l.documentMode,i.isie10=i.isie&&"performance"in a&&10===l.documentMode,i.isie11="msRequestFullscreen"in e&&l.documentMode>=11,i.ismsedge="msCredentials"in a,i.ismozilla="MozAppearance"in o,i.iswebkit=!i.ismsedge&&"WebkitAppearance"in o,i.ischrome=i.iswebkit&&"chrome"in a,i.ischrome38=i.ischrome&&"touchAction"in o,i.ischrome22=!i.ischrome38&&i.ischrome&&i.haspointerlock,i.ischrome26=!i.ischrome38&&i.ischrome&&"transition"in o,i.cantouch="ontouchstart"in l.documentElement||"ontouchstart"in a,i.hasw3ctouch=(a.PointerEvent||!1)&&(navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0),i.hasmstouch=!i.hasw3ctouch&&(a.MSPointerEvent||!1),i.ismac=/^mac$/i.test(r),i.isios=i.cantouch&&/iphone|ipad|ipod/i.test(r),i.isios4=i.isios&&!("seal"in Object),i.isios7=i.isios&&"webkitHidden"in l,i.isios8=i.isios&&"hidden"in l,i.isios10=i.isios&&a.Proxy,i.isandroid=/android/i.test(t),i.haseventlistener="addEventListener"in e,i.trstyle=!1,i.hastransform=!1,i.hastranslate3d=!1,i.transitionstyle=!1,i.hastransition=!1,i.transitionend=!1,i.trstyle="transform",i.hastransform="transform"in o||function(){for(var e=["msTransform","webkitTransform","MozTransform","OTransform"],t=0,r=e.length;t<r;t++)if(void 0!==o[e[t]]){i.trstyle=e[t];break}i.hastransform=!!i.trstyle}(),i.hastransform&&(o[i.trstyle]="translate3d(1px,2px,3px)",i.hastranslate3d=/translate3d/.test(o[i.trstyle])),i.transitionstyle="transition",i.prefixstyle="",i.transitionend="transitionend",i.hastransition="transition"in o||function(){i.transitionend=!1;for(var e=["webkitTransition","msTransition","MozTransition","OTransition","OTransition","KhtmlTransition"],t=["-webkit-","-ms-","-moz-","-o-","-o","-khtml-"],r=["webkitTransitionEnd","msTransitionEnd","transitionend","otransitionend","oTransitionEnd","KhtmlTransitionEnd"],s=0,n=e.length;s<n;s++)if(e[s]in o){i.transitionstyle=e[s],i.prefixstyle=t[s],i.transitionend=r[s];break}i.ischrome26&&(i.prefixstyle=t[1]),i.hastransition=i.transitionstyle}(),i.cursorgrabvalue=function(){var e=["grab","-webkit-grab","-moz-grab"];(i.ischrome&&!i.ischrome38||i.isie)&&(e=[]);for(var t=0,r=e.length;t<r;t++){var s=e[t];if(o.cursor=s,o.cursor==s)return s}return"url(https://cdnjs.cloudflare.com/ajax/libs/slider-pro/1.3.0/css/images/openhand.cur),n-resize"}(),i.hasmousecapture="setCapture"in e,i.hasMutationObserver=!1!==m,e=null,v=i,i},b=function(e,p){function v(){var e=T.doc.css(P.trstyle);return!(!e||"matrix"!=e.substr(0,6))&&e.replace(/^.*\((.*)\)$/g,"$1").replace(/px/g,"").split(/, +/)}function b(){var e=T.win;if("zIndex"in e)return e.zIndex();for(;e.length>0;){if(9==e[0].nodeType)return!1;var o=e.css("zIndex");if(!isNaN(o)&&0!==o)return parseInt(o);e=e.parent()}return!1}function x(e,o,t){var r=e.css(o),i=parseFloat(r);if(isNaN(i)){var s=3==(i=I[r]||0)?t?T.win.outerHeight()-T.win.innerHeight():T.win.outerWidth()-T.win.innerWidth():1;return T.isie8&&i&&(i+=1),s?i:0}return i}function S(e,o,t,r){T._bind(e,o,function(r){var i={original:r=r||a.event,target:r.target||r.srcElement,type:"wheel",deltaMode:"MozMousePixelScroll"==r.type?0:1,deltaX:0,deltaZ:0,preventDefault:function(){return r.preventDefault?r.preventDefault():r.returnValue=!1,!1},stopImmediatePropagation:function(){r.stopImmediatePropagation?r.stopImmediatePropagation():r.cancelBubble=!0}};return"mousewheel"==o?(r.wheelDeltaX&&(i.deltaX=-.025*r.wheelDeltaX),r.wheelDeltaY&&(i.deltaY=-.025*r.wheelDeltaY),!i.deltaY&&!i.deltaX&&(i.deltaY=-.025*r.wheelDelta)):i.deltaY=r.detail,t.call(e,i)},r)}function z(e,o,t,r){T.scrollrunning||(T.newscrolly=T.getScrollTop(),T.newscrollx=T.getScrollLeft(),D=f());var i=f()-D;if(D=f(),i>350?A=1:A+=(2-A)/10,e=e*A|0,o=o*A|0,e){if(r)if(e<0){if(T.getScrollLeft()>=T.page.maxw)return!0}else if(T.getScrollLeft()<=0)return!0;var s=e>0?1:-1;X!==s&&(T.scrollmom&&T.scrollmom.stop(),T.newscrollx=T.getScrollLeft(),X=s),T.lastdeltax-=e}if(o){if(function(){var e=T.getScrollTop();if(o<0){if(e>=T.page.maxh)return!0}else if(e<=0)return!0}()){if(M.nativeparentscrolling&&t&&!T.ispage&&!T.zoomactive)return!0;var n=T.view.h>>1;T.newscrolly<-n?(T.newscrolly=-n,o=-1):T.newscrolly>T.page.maxh+n?(T.newscrolly=T.page.maxh+n,o=1):o=0}var l=o>0?1:-1;B!==l&&(T.scrollmom&&T.scrollmom.stop(),T.newscrolly=T.getScrollTop(),B=l),T.lastdeltay-=o}(o||e)&&T.synched("relativexy",function(){var e=T.lastdeltay+T.newscrolly;T.lastdeltay=0;var o=T.lastdeltax+T.newscrollx;T.lastdeltax=0,T.rail.drag||T.doScrollPos(o,e)})}function k(e,o,t){var r,i;return!(t||!q)||(0===e.deltaMode?(r=-e.deltaX*(M.mousescrollstep/54)|0,i=-e.deltaY*(M.mousescrollstep/54)|0):1===e.deltaMode&&(r=-e.deltaX*M.mousescrollstep*50/80|0,i=-e.deltaY*M.mousescrollstep*50/80|0),o&&M.oneaxismousemode&&0===r&&i&&(r=i,i=0,t&&(r<0?T.getScrollLeft()>=T.page.maxw:T.getScrollLeft()<=0)&&(i=r,r=0)),T.isrtlmode&&(r=-r),z(r,i,t,!0)?void(t&&(q=!0)):(q=!1,e.stopImmediatePropagation(),e.preventDefault()))}var T=this;this.version="3.7.6",this.name="nicescroll",this.me=p;var E=n("body"),M=this.opt={doc:E,win:!1};if(n.extend(M,g),M.snapbackspeed=80,e)for(var L in M)void 0!==e[L]&&(M[L]=e[L]);if(M.disablemutationobserver&&(m=!1),this.doc=M.doc,this.iddoc=this.doc&&this.doc[0]?this.doc[0].id||"":"",this.ispage=/^BODY|HTML/.test(M.win?M.win[0].nodeName:this.doc[0].nodeName),this.haswrapper=!1!==M.win,this.win=M.win||(this.ispage?c:this.doc),this.docscroll=this.ispage&&!this.haswrapper?c:this.win,this.body=E,this.viewport=!1,this.isfixed=!1,this.iframe=!1,this.isiframe="IFRAME"==this.doc[0].nodeName&&"IFRAME"==this.win[0].nodeName,this.istextarea="TEXTAREA"==this.win[0].nodeName,this.forcescreen=!1,this.canshowonmouseevent="scroll"!=M.autohidemode,this.onmousedown=!1,this.onmouseup=!1,this.onmousemove=!1,this.onmousewheel=!1,this.onkeypress=!1,this.ongesturezoom=!1,this.onclick=!1,this.onscrollstart=!1,this.onscrollend=!1,this.onscrollcancel=!1,this.onzoomin=!1,this.onzoomout=!1,this.view=!1,this.page=!1,this.scroll={x:0,y:0},this.scrollratio={x:0,y:0},this.cursorheight=20,this.scrollvaluemax=0,"auto"==M.rtlmode){var C=this.win[0]==a?this.body:this.win,N=C.css("writing-mode")||C.css("-webkit-writing-mode")||C.css("-ms-writing-mode")||C.css("-moz-writing-mode");"horizontal-tb"==N||"lr-tb"==N||""===N?(this.isrtlmode="rtl"==C.css("direction"),this.isvertical=!1):(this.isrtlmode="vertical-rl"==N||"tb"==N||"tb-rl"==N||"rl-tb"==N,this.isvertical="vertical-rl"==N||"tb"==N||"tb-rl"==N)}else this.isrtlmode=!0===M.rtlmode,this.isvertical=!1;if(this.scrollrunning=!1,this.scrollmom=!1,this.observer=!1,this.observerremover=!1,this.observerbody=!1,!1!==M.scrollbarid)this.id=M.scrollbarid;else do{this.id="ascrail"+i++}while(l.getElementById(this.id));this.rail=!1,this.cursor=!1,this.cursorfreezed=!1,this.selectiondrag=!1,this.zoom=!1,this.zoomactive=!1,this.hasfocus=!1,this.hasmousefocus=!1,this.railslocked=!1,this.locked=!1,this.hidden=!1,this.cursoractive=!0,this.wheelprevented=!1,this.overflowx=M.overflowx,this.overflowy=M.overflowy,this.nativescrollingarea=!1,this.checkarea=0,this.events=[],this.saved={},this.delaylist={},this.synclist={},this.lastdeltax=0,this.lastdeltay=0,this.detected=w();var P=n.extend({},this.detected);this.canhwscroll=P.hastransform&&M.hwacceleration,this.ishwscroll=this.canhwscroll&&T.haswrapper,this.isrtlmode?this.isvertical?this.hasreversehr=!(P.iswebkit||P.isie||P.isie11):this.hasreversehr=!(P.iswebkit||P.isie&&!P.isie10&&!P.isie11):this.hasreversehr=!1,this.istouchcapable=!1,P.cantouch||!P.hasw3ctouch&&!P.hasmstouch?!P.cantouch||P.isios||P.isandroid||!P.iswebkit&&!P.ismozilla||(this.istouchcapable=!0):this.istouchcapable=!0,M.enablemouselockapi||(P.hasmousecapture=!1,P.haspointerlock=!1),this.debounced=function(e,o,t){T&&(T.delaylist[e]||!1||(T.delaylist[e]={h:u(function(){T.delaylist[e].fn.call(T),T.delaylist[e]=!1},t)},o.call(T)),T.delaylist[e].fn=o)},this.synched=function(e,o){T.synclist[e]?T.synclist[e]=o:(T.synclist[e]=o,u(function(){T&&(T.synclist[e]&&T.synclist[e].call(T),T.synclist[e]=null)}))},this.unsynched=function(e){T.synclist[e]&&(T.synclist[e]=!1)},this.css=function(e,o){for(var t in o)T.saved.css.push([e,t,e.css(t)]),e.css(t,o[t])},this.scrollTop=function(e){return void 0===e?T.getScrollTop():T.setScrollTop(e)},this.scrollLeft=function(e){return void 0===e?T.getScrollLeft():T.setScrollLeft(e)};var R=function(e,o,t,r,i,s,n){this.st=e,this.ed=o,this.spd=t,this.p1=r||0,this.p2=i||1,this.p3=s||0,this.p4=n||1,this.ts=f(),this.df=o-e};if(R.prototype={B2:function(e){return 3*(1-e)*(1-e)*e},B3:function(e){return 3*(1-e)*e*e},B4:function(e){return e*e*e},getPos:function(){return(f()-this.ts)/this.spd},getNow:function(){var e=(f()-this.ts)/this.spd,o=this.B2(e)+this.B3(e)+this.B4(e);return e>=1?this.ed:this.st+this.df*o|0},update:function(e,o){return this.st=this.getNow(),this.ed=e,this.spd=o,this.ts=f(),this.df=this.ed-this.st,this}},this.ishwscroll){this.doc.translate={x:0,y:0,tx:"0px",ty:"0px"},P.hastranslate3d&&P.isios&&this.doc.css("-webkit-backface-visibility","hidden"),this.getScrollTop=function(e){if(!e){var o=v();if(o)return 16==o.length?-o[13]:-o[5];if(T.timerscroll&&T.timerscroll.bz)return T.timerscroll.bz.getNow()}return T.doc.translate.y},this.getScrollLeft=function(e){if(!e){var o=v();if(o)return 16==o.length?-o[12]:-o[4];if(T.timerscroll&&T.timerscroll.bh)return T.timerscroll.bh.getNow()}return T.doc.translate.x},this.notifyScrollEvent=function(e){var o=l.createEvent("UIEvents");o.initUIEvent("scroll",!1,!1,a,1),o.niceevent=!0,e.dispatchEvent(o)};var _=this.isrtlmode?1:-1;P.hastranslate3d&&M.enabletranslate3d?(this.setScrollTop=function(e,o){T.doc.translate.y=e,T.doc.translate.ty=-1*e+"px",T.doc.css(P.trstyle,"translate3d("+T.doc.translate.tx+","+T.doc.translate.ty+",0)"),o||T.notifyScrollEvent(T.win[0])},this.setScrollLeft=function(e,o){T.doc.translate.x=e,T.doc.translate.tx=e*_+"px",T.doc.css(P.trstyle,"translate3d("+T.doc.translate.tx+","+T.doc.translate.ty+",0)"),o||T.notifyScrollEvent(T.win[0])}):(this.setScrollTop=function(e,o){T.doc.translate.y=e,T.doc.translate.ty=-1*e+"px",T.doc.css(P.trstyle,"translate("+T.doc.translate.tx+","+T.doc.translate.ty+")"),o||T.notifyScrollEvent(T.win[0])},this.setScrollLeft=function(e,o){T.doc.translate.x=e,T.doc.translate.tx=e*_+"px",T.doc.css(P.trstyle,"translate("+T.doc.translate.tx+","+T.doc.translate.ty+")"),o||T.notifyScrollEvent(T.win[0])})}else this.getScrollTop=function(){return T.docscroll.scrollTop()},this.setScrollTop=function(e){T.docscroll.scrollTop(e)},this.getScrollLeft=function(){return T.hasreversehr?T.detected.ismozilla?T.page.maxw-Math.abs(T.docscroll.scrollLeft()):T.page.maxw-T.docscroll.scrollLeft():T.docscroll.scrollLeft()},this.setScrollLeft=function(e){return setTimeout(function(){if(T)return T.hasreversehr&&(e=T.detected.ismozilla?-(T.page.maxw-e):T.page.maxw-e),T.docscroll.scrollLeft(e)},1)};this.getTarget=function(e){return!!e&&(e.target?e.target:!!e.srcElement&&e.srcElement)},this.hasParent=function(e,o){if(!e)return!1;for(var t=e.target||e.srcElement||e||!1;t&&t.id!=o;)t=t.parentNode||!1;return!1!==t};var I={thin:1,medium:3,thick:5};this.getDocumentScrollOffset=function(){return{top:a.pageYOffset||l.documentElement.scrollTop,left:a.pageXOffset||l.documentElement.scrollLeft}},this.getOffset=function(){if(T.isfixed){var e=T.win.offset(),o=T.getDocumentScrollOffset();return e.top-=o.top,e.left-=o.left,e}var t=T.win.offset();if(!T.viewport)return t;var r=T.viewport.offset();return{top:t.top-r.top,left:t.left-r.left}},this.updateScrollBar=function(e){var o,t;if(T.ishwscroll)T.rail.css({height:T.win.innerHeight()-(M.railpadding.top+M.railpadding.bottom)}),T.railh&&T.railh.css({width:T.win.innerWidth()-(M.railpadding.left+M.railpadding.right)});else{var r=T.getOffset();if(o={top:r.top,left:r.left-(M.railpadding.left+M.railpadding.right)},o.top+=x(T.win,"border-top-width",!0),o.left+=T.rail.align?T.win.outerWidth()-x(T.win,"border-right-width")-T.rail.width:x(T.win,"border-left-width"),(t=M.railoffset)&&(t.top&&(o.top+=t.top),t.left&&(o.left+=t.left)),T.railslocked||T.rail.css({top:o.top,left:o.left,height:(e?e.h:T.win.innerHeight())-(M.railpadding.top+M.railpadding.bottom)}),T.zoom&&T.zoom.css({top:o.top+1,left:1==T.rail.align?o.left-20:o.left+T.rail.width+4}),T.railh&&!T.railslocked){o={top:r.top,left:r.left},(t=M.railhoffset)&&(t.top&&(o.top+=t.top),t.left&&(o.left+=t.left));var i=T.railh.align?o.top+x(T.win,"border-top-width",!0)+T.win.innerHeight()-T.railh.height:o.top+x(T.win,"border-top-width",!0),s=o.left+x(T.win,"border-left-width");T.railh.css({top:i-(M.railpadding.top+M.railpadding.bottom),left:s,width:T.railh.width})}}},this.doRailClick=function(e,o,t){var r,i,s,n;T.railslocked||(T.cancelEvent(e),"pageY"in e||(e.pageX=e.clientX+l.documentElement.scrollLeft,e.pageY=e.clientY+l.documentElement.scrollTop),o?(r=t?T.doScrollLeft:T.doScrollTop,s=t?(e.pageX-T.railh.offset().left-T.cursorwidth/2)*T.scrollratio.x:(e.pageY-T.rail.offset().top-T.cursorheight/2)*T.scrollratio.y,T.unsynched("relativexy"),r(0|s)):(r=t?T.doScrollLeftBy:T.doScrollBy,s=t?T.scroll.x:T.scroll.y,n=t?e.pageX-T.railh.offset().left:e.pageY-T.rail.offset().top,i=t?T.view.w:T.view.h,r(s>=n?i:-i)))},T.newscrolly=T.newscrollx=0,T.hasanimationframe="requestAnimationFrame"in a,T.hascancelanimationframe="cancelAnimationFrame"in a,T.hasborderbox=!1,this.init=function(){if(T.saved.css=[],P.isoperamini)return!0;if(P.isandroid&&!("hidden"in l))return!0;M.emulatetouch=M.emulatetouch||M.touchbehavior,T.hasborderbox=a.getComputedStyle&&"border-box"===a.getComputedStyle(l.body)["box-sizing"];var e={"overflow-y":"hidden"};if((P.isie11||P.isie10)&&(e["-ms-overflow-style"]="none"),T.ishwscroll&&(this.doc.css(P.transitionstyle,P.prefixstyle+"transform 0ms ease-out"),P.transitionend&&T.bind(T.doc,P.transitionend,T.onScrollTransitionEnd,!1)),T.zindex="auto",T.ispage||"auto"!=M.zindex?T.zindex=M.zindex:T.zindex=b()||"auto",!T.ispage&&"auto"!=T.zindex&&T.zindex>s&&(s=T.zindex),T.isie&&0===T.zindex&&"auto"==M.zindex&&(T.zindex="auto"),!T.ispage||!P.isieold){var i=T.docscroll;T.ispage&&(i=T.haswrapper?T.win:T.doc),T.css(i,e),T.ispage&&(P.isie11||P.isie)&&T.css(n("html"),e),!P.isios||T.ispage||T.haswrapper||T.css(E,{"-webkit-overflow-scrolling":"touch"});var d=n(l.createElement("div"));d.css({position:"relative",top:0,float:"right",width:M.cursorwidth,height:0,"background-color":M.cursorcolor,border:M.cursorborder,"background-clip":"padding-box","-webkit-border-radius":M.cursorborderradius,"-moz-border-radius":M.cursorborderradius,"border-radius":M.cursorborderradius}),d.addClass("nicescroll-cursors"),T.cursor=d;var u=n(l.createElement("div"));u.attr("id",T.id),u.addClass("nicescroll-rails nicescroll-rails-vr");var h,p,f=["left","right","top","bottom"];for(var g in f)p=f[g],(h=M.railpadding[p]||0)&&u.css("padding-"+p,h+"px");u.append(d),u.width=Math.max(parseFloat(M.cursorwidth),d.outerWidth()),u.css({width:u.width+"px",zIndex:T.zindex,background:M.background,cursor:"default"}),u.visibility=!0,u.scrollable=!0,u.align="left"==M.railalign?0:1,T.rail=u,T.rail.drag=!1;var v=!1;!M.boxzoom||T.ispage||P.isieold||(v=l.createElement("div"),T.bind(v,"click",T.doZoom),T.bind(v,"mouseenter",function(){T.zoom.css("opacity",M.cursoropacitymax)}),T.bind(v,"mouseleave",function(){T.zoom.css("opacity",M.cursoropacitymin)}),T.zoom=n(v),T.zoom.css({cursor:"pointer",zIndex:T.zindex,backgroundImage:"url("+M.scriptpath+"zoomico.png)",height:18,width:18,backgroundPosition:"0 0"}),M.dblclickzoom&&T.bind(T.win,"dblclick",T.doZoom),P.cantouch&&M.gesturezoom&&(T.ongesturezoom=function(e){return e.scale>1.5&&T.doZoomIn(e),e.scale<.8&&T.doZoomOut(e),T.cancelEvent(e)},T.bind(T.win,"gestureend",T.ongesturezoom))),T.railh=!1;var w;if(M.horizrailenabled&&(T.css(i,{overflowX:"hidden"}),(d=n(l.createElement("div"))).css({position:"absolute",top:0,height:M.cursorwidth,width:0,backgroundColor:M.cursorcolor,border:M.cursorborder,backgroundClip:"padding-box","-webkit-border-radius":M.cursorborderradius,"-moz-border-radius":M.cursorborderradius,"border-radius":M.cursorborderradius}),P.isieold&&d.css("overflow","hidden"),d.addClass("nicescroll-cursors"),T.cursorh=d,(w=n(l.createElement("div"))).attr("id",T.id+"-hr"),w.addClass("nicescroll-rails nicescroll-rails-hr"),w.height=Math.max(parseFloat(M.cursorwidth),d.outerHeight()),w.css({height:w.height+"px",zIndex:T.zindex,background:M.background}),w.append(d),w.visibility=!0,w.scrollable=!0,w.align="top"==M.railvalign?0:1,T.railh=w,T.railh.drag=!1),T.ispage)u.css({position:"fixed",top:0,height:"100%"}),u.css(u.align?{right:0}:{left:0}),T.body.append(u),T.railh&&(w.css({position:"fixed",left:0,width:"100%"}),w.css(w.align?{bottom:0}:{top:0}),T.body.append(w));else{if(T.ishwscroll){"static"==T.win.css("position")&&T.css(T.win,{position:"relative"});var x="HTML"==T.win[0].nodeName?T.body:T.win;n(x).scrollTop(0).scrollLeft(0),T.zoom&&(T.zoom.css({position:"absolute",top:1,right:0,"margin-right":u.width+4}),x.append(T.zoom)),u.css({position:"absolute",top:0}),u.css(u.align?{right:0}:{left:0}),x.append(u),w&&(w.css({position:"absolute",left:0,bottom:0}),w.css(w.align?{bottom:0}:{top:0}),x.append(w))}else{T.isfixed="fixed"==T.win.css("position");var S=T.isfixed?"fixed":"absolute";T.isfixed||(T.viewport=T.getViewport(T.win[0])),T.viewport&&(T.body=T.viewport,/fixed|absolute/.test(T.viewport.css("position"))||T.css(T.viewport,{position:"relative"})),u.css({position:S}),T.zoom&&T.zoom.css({position:S}),T.updateScrollBar(),T.body.append(u),T.zoom&&T.body.append(T.zoom),T.railh&&(w.css({position:S}),T.body.append(w))}P.isios&&T.css(T.win,{"-webkit-tap-highlight-color":"rgba(0,0,0,0)","-webkit-touch-callout":"none"}),M.disableoutline&&(P.isie&&T.win.attr("hideFocus","true"),P.iswebkit&&T.win.css("outline","none"))}if(!1===M.autohidemode?(T.autohidedom=!1,T.rail.css({opacity:M.cursoropacitymax}),T.railh&&T.railh.css({opacity:M.cursoropacitymax})):!0===M.autohidemode||"leave"===M.autohidemode?(T.autohidedom=n().add(T.rail),P.isie8&&(T.autohidedom=T.autohidedom.add(T.cursor)),T.railh&&(T.autohidedom=T.autohidedom.add(T.railh)),T.railh&&P.isie8&&(T.autohidedom=T.autohidedom.add(T.cursorh))):"scroll"==M.autohidemode?(T.autohidedom=n().add(T.rail),T.railh&&(T.autohidedom=T.autohidedom.add(T.railh))):"cursor"==M.autohidemode?(T.autohidedom=n().add(T.cursor),T.railh&&(T.autohidedom=T.autohidedom.add(T.cursorh))):"hidden"==M.autohidemode&&(T.autohidedom=!1,T.hide(),T.railslocked=!1),P.cantouch||T.istouchcapable||M.emulatetouch||P.hasmstouch){T.scrollmom=new y(T);T.ontouchstart=function(e){if(T.locked)return!1;if(e.pointerType&&("mouse"===e.pointerType||e.pointerType===e.MSPOINTER_TYPE_MOUSE))return!1;if(T.hasmoving=!1,T.scrollmom.timer&&(T.triggerScrollEnd(),T.scrollmom.stop()),!T.railslocked){var o=T.getTarget(e);if(o&&/INPUT/i.test(o.nodeName)&&/range/i.test(o.type))return T.stopPropagation(e);var t="mousedown"===e.type;if(!("clientX"in e)&&"changedTouches"in e&&(e.clientX=e.changedTouches[0].clientX,e.clientY=e.changedTouches[0].clientY),T.forcescreen){var r=e;(e={original:e.original?e.original:e}).clientX=r.screenX,e.clientY=r.screenY}if(T.rail.drag={x:e.clientX,y:e.clientY,sx:T.scroll.x,sy:T.scroll.y,st:T.getScrollTop(),sl:T.getScrollLeft(),pt:2,dl:!1,tg:o},T.ispage||!M.directionlockdeadzone)T.rail.drag.dl="f";else{var i={w:c.width(),h:c.height()},s=T.getContentSize(),l=s.h-i.h,a=s.w-i.w;T.rail.scrollable&&!T.railh.scrollable?T.rail.drag.ck=l>0&&"v":!T.rail.scrollable&&T.railh.scrollable?T.rail.drag.ck=a>0&&"h":T.rail.drag.ck=!1}if(M.emulatetouch&&T.isiframe&&P.isie){var d=T.win.position();T.rail.drag.x+=d.left,T.rail.drag.y+=d.top}if(T.hasmoving=!1,T.lastmouseup=!1,T.scrollmom.reset(e.clientX,e.clientY),o&&t){if(!/INPUT|SELECT|BUTTON|TEXTAREA/i.test(o.nodeName))return P.hasmousecapture&&o.setCapture(),M.emulatetouch?(o.onclick&&!o._onclick&&(o._onclick=o.onclick,o.onclick=function(e){if(T.hasmoving)return!1;o._onclick.call(this,e)}),T.cancelEvent(e)):T.stopPropagation(e);/SUBMIT|CANCEL|BUTTON/i.test(n(o).attr("type"))&&(T.preventclick={tg:o,click:!1})}}},T.ontouchend=function(e){if(!T.rail.drag)return!0;if(2==T.rail.drag.pt){if(e.pointerType&&("mouse"===e.pointerType||e.pointerType===e.MSPOINTER_TYPE_MOUSE))return!1;T.rail.drag=!1;var o="mouseup"===e.type;if(T.hasmoving&&(T.scrollmom.doMomentum(),T.lastmouseup=!0,T.hideCursor(),P.hasmousecapture&&l.releaseCapture(),o))return T.cancelEvent(e)}else if(1==T.rail.drag.pt)return T.onmouseup(e)};var z=M.emulatetouch&&T.isiframe&&!P.hasmousecapture,k=.3*M.directionlockdeadzone|0;T.ontouchmove=function(e,o){if(!T.rail.drag)return!0;if(e.targetTouches&&M.preventmultitouchscrolling&&e.targetTouches.length>1)return!0;if(e.pointerType&&("mouse"===e.pointerType||e.pointerType===e.MSPOINTER_TYPE_MOUSE))return!0;if(2==T.rail.drag.pt){"changedTouches"in e&&(e.clientX=e.changedTouches[0].clientX,e.clientY=e.changedTouches[0].clientY);var t,r;if(r=t=0,z&&!o){var i=T.win.position();r=-i.left,t=-i.top}var s=e.clientY+t,n=s-T.rail.drag.y,a=e.clientX+r,c=a-T.rail.drag.x,d=T.rail.drag.st-n;if(T.ishwscroll&&M.bouncescroll)d<0?d=Math.round(d/2):d>T.page.maxh&&(d=T.page.maxh+Math.round((d-T.page.maxh)/2));else if(d<0?(d=0,s=0):d>T.page.maxh&&(d=T.page.maxh,s=0),0===s&&!T.hasmoving)return T.ispage||(T.rail.drag=!1),!0;var u=T.getScrollLeft();if(T.railh&&T.railh.scrollable&&(u=T.isrtlmode?c-T.rail.drag.sl:T.rail.drag.sl-c,T.ishwscroll&&M.bouncescroll?u<0?u=Math.round(u/2):u>T.page.maxw&&(u=T.page.maxw+Math.round((u-T.page.maxw)/2)):(u<0&&(u=0,a=0),u>T.page.maxw&&(u=T.page.maxw,a=0))),!T.hasmoving){if(T.rail.drag.y===e.clientY&&T.rail.drag.x===e.clientX)return T.cancelEvent(e);var h=Math.abs(n),p=Math.abs(c),m=M.directionlockdeadzone;if(T.rail.drag.ck?"v"==T.rail.drag.ck?p>m&&h<=k?T.rail.drag=!1:h>m&&(T.rail.drag.dl="v"):"h"==T.rail.drag.ck&&(h>m&&p<=k?T.rail.drag=!1:p>m&&(T.rail.drag.dl="h")):h>m&&p>m?T.rail.drag.dl="f":h>m?T.rail.drag.dl=p>k?"f":"v":p>m&&(T.rail.drag.dl=h>k?"f":"h"),!T.rail.drag.dl)return T.cancelEvent(e);T.triggerScrollStart(e.clientX,e.clientY,0,0,0),T.hasmoving=!0}return T.preventclick&&!T.preventclick.click&&(T.preventclick.click=T.preventclick.tg.onclick||!1,T.preventclick.tg.onclick=T.onpreventclick),T.rail.drag.dl&&("v"==T.rail.drag.dl?u=T.rail.drag.sl:"h"==T.rail.drag.dl&&(d=T.rail.drag.st)),T.synched("touchmove",function(){T.rail.drag&&2==T.rail.drag.pt&&(T.prepareTransition&&T.resetTransition(),T.rail.scrollable&&T.setScrollTop(d),T.scrollmom.update(a,s),T.railh&&T.railh.scrollable?(T.setScrollLeft(u),T.showCursor(d,u)):T.showCursor(d),P.isie10&&l.selection.clear())}),T.cancelEvent(e)}return 1==T.rail.drag.pt?T.onmousemove(e):void 0},T.ontouchstartCursor=function(e,o){if(!T.rail.drag||3==T.rail.drag.pt){if(T.locked)return T.cancelEvent(e);T.cancelScroll(),T.rail.drag={x:e.touches[0].clientX,y:e.touches[0].clientY,sx:T.scroll.x,sy:T.scroll.y,pt:3,hr:!!o};var t=T.getTarget(e);return!T.ispage&&P.hasmousecapture&&t.setCapture(),T.isiframe&&!P.hasmousecapture&&(T.saved.csspointerevents=T.doc.css("pointer-events"),T.css(T.doc,{"pointer-events":"none"})),T.cancelEvent(e)}},T.ontouchendCursor=function(e){if(T.rail.drag){if(P.hasmousecapture&&l.releaseCapture(),T.isiframe&&!P.hasmousecapture&&T.doc.css("pointer-events",T.saved.csspointerevents),3!=T.rail.drag.pt)return;return T.rail.drag=!1,T.cancelEvent(e)}},T.ontouchmoveCursor=function(e){if(T.rail.drag){if(3!=T.rail.drag.pt)return;if(T.cursorfreezed=!0,T.rail.drag.hr){T.scroll.x=T.rail.drag.sx+(e.touches[0].clientX-T.rail.drag.x),T.scroll.x<0&&(T.scroll.x=0);var o=T.scrollvaluemaxw;T.scroll.x>o&&(T.scroll.x=o)}else{T.scroll.y=T.rail.drag.sy+(e.touches[0].clientY-T.rail.drag.y),T.scroll.y<0&&(T.scroll.y=0);var t=T.scrollvaluemax;T.scroll.y>t&&(T.scroll.y=t)}return T.synched("touchmove",function(){T.rail.drag&&3==T.rail.drag.pt&&(T.showCursor(),T.rail.drag.hr?T.doScrollLeft(Math.round(T.scroll.x*T.scrollratio.x),M.cursordragspeed):T.doScrollTop(Math.round(T.scroll.y*T.scrollratio.y),M.cursordragspeed))}),T.cancelEvent(e)}}}if(T.onmousedown=function(e,o){if(!T.rail.drag||1==T.rail.drag.pt){if(T.railslocked)return T.cancelEvent(e);T.cancelScroll(),T.rail.drag={x:e.clientX,y:e.clientY,sx:T.scroll.x,sy:T.scroll.y,pt:1,hr:o||!1};var t=T.getTarget(e);return P.hasmousecapture&&t.setCapture(),T.isiframe&&!P.hasmousecapture&&(T.saved.csspointerevents=T.doc.css("pointer-events"),T.css(T.doc,{"pointer-events":"none"})),T.hasmoving=!1,T.cancelEvent(e)}},T.onmouseup=function(e){if(T.rail.drag)return 1!=T.rail.drag.pt||(P.hasmousecapture&&l.releaseCapture(),T.isiframe&&!P.hasmousecapture&&T.doc.css("pointer-events",T.saved.csspointerevents),T.rail.drag=!1,T.cursorfreezed=!1,T.hasmoving&&T.triggerScrollEnd(),T.cancelEvent(e))},T.onmousemove=function(e){if(T.rail.drag){if(1!==T.rail.drag.pt)return;if(P.ischrome&&0===e.which)return T.onmouseup(e);if(T.cursorfreezed=!0,T.hasmoving||T.triggerScrollStart(e.clientX,e.clientY,0,0,0),T.hasmoving=!0,T.rail.drag.hr){T.scroll.x=T.rail.drag.sx+(e.clientX-T.rail.drag.x),T.scroll.x<0&&(T.scroll.x=0);var o=T.scrollvaluemaxw;T.scroll.x>o&&(T.scroll.x=o)}else{T.scroll.y=T.rail.drag.sy+(e.clientY-T.rail.drag.y),T.scroll.y<0&&(T.scroll.y=0);var t=T.scrollvaluemax;T.scroll.y>t&&(T.scroll.y=t)}return T.synched("mousemove",function(){T.cursorfreezed&&(T.showCursor(),T.rail.drag.hr?T.scrollLeft(Math.round(T.scroll.x*T.scrollratio.x)):T.scrollTop(Math.round(T.scroll.y*T.scrollratio.y)))}),T.cancelEvent(e)}T.checkarea=0},P.cantouch||M.emulatetouch)T.onpreventclick=function(e){if(T.preventclick)return T.preventclick.tg.onclick=T.preventclick.click,T.preventclick=!1,T.cancelEvent(e)},T.onclick=!P.isios&&function(e){return!T.lastmouseup||(T.lastmouseup=!1,T.cancelEvent(e))},M.grabcursorenabled&&P.cursorgrabvalue&&(T.css(T.ispage?T.doc:T.win,{cursor:P.cursorgrabvalue}),T.css(T.rail,{cursor:P.cursorgrabvalue}));else{var L=function(e){if(T.selectiondrag){if(e){var o=T.win.outerHeight(),t=e.pageY-T.selectiondrag.top;t>0&&t<o&&(t=0),t>=o&&(t-=o),T.selectiondrag.df=t}if(0!==T.selectiondrag.df){var r=-2*T.selectiondrag.df/6|0;T.doScrollBy(r),T.debounced("doselectionscroll",function(){L()},50)}}};T.hasTextSelected="getSelection"in l?function(){return l.getSelection().rangeCount>0}:"selection"in l?function(){return"None"!=l.selection.type}:function(){return!1},T.onselectionstart=function(e){T.ispage||(T.selectiondrag=T.win.offset())},T.onselectionend=function(e){T.selectiondrag=!1},T.onselectiondrag=function(e){T.selectiondrag&&T.hasTextSelected()&&T.debounced("selectionscroll",function(){L(e)},250)}}if(P.hasw3ctouch?(T.css(T.ispage?n("html"):T.win,{"touch-action":"none"}),T.css(T.rail,{"touch-action":"none"}),T.css(T.cursor,{"touch-action":"none"}),T.bind(T.win,"pointerdown",T.ontouchstart),T.bind(l,"pointerup",T.ontouchend),T.delegate(l,"pointermove",T.ontouchmove)):P.hasmstouch?(T.css(T.ispage?n("html"):T.win,{"-ms-touch-action":"none"}),T.css(T.rail,{"-ms-touch-action":"none"}),T.css(T.cursor,{"-ms-touch-action":"none"}),T.bind(T.win,"MSPointerDown",T.ontouchstart),T.bind(l,"MSPointerUp",T.ontouchend),T.delegate(l,"MSPointerMove",T.ontouchmove),T.bind(T.cursor,"MSGestureHold",function(e){e.preventDefault()}),T.bind(T.cursor,"contextmenu",function(e){e.preventDefault()})):P.cantouch&&(T.bind(T.win,"touchstart",T.ontouchstart,!1,!0),T.bind(l,"touchend",T.ontouchend,!1,!0),T.bind(l,"touchcancel",T.ontouchend,!1,!0),T.delegate(l,"touchmove",T.ontouchmove,!1,!0)),M.emulatetouch&&(T.bind(T.win,"mousedown",T.ontouchstart,!1,!0),T.bind(l,"mouseup",T.ontouchend,!1,!0),T.bind(l,"mousemove",T.ontouchmove,!1,!0)),(M.cursordragontouch||!P.cantouch&&!M.emulatetouch)&&(T.rail.css({cursor:"default"}),T.railh&&T.railh.css({cursor:"default"}),T.jqbind(T.rail,"mouseenter",function(){if(!T.ispage&&!T.win.is(":visible"))return!1;T.canshowonmouseevent&&T.showCursor(),T.rail.active=!0}),T.jqbind(T.rail,"mouseleave",function(){T.rail.active=!1,T.rail.drag||T.hideCursor()}),M.sensitiverail&&(T.bind(T.rail,"click",function(e){T.doRailClick(e,!1,!1)}),T.bind(T.rail,"dblclick",function(e){T.doRailClick(e,!0,!1)}),T.bind(T.cursor,"click",function(e){T.cancelEvent(e)}),T.bind(T.cursor,"dblclick",function(e){T.cancelEvent(e)})),T.railh&&(T.jqbind(T.railh,"mouseenter",function(){if(!T.ispage&&!T.win.is(":visible"))return!1;T.canshowonmouseevent&&T.showCursor(),T.rail.active=!0}),T.jqbind(T.railh,"mouseleave",function(){T.rail.active=!1,T.rail.drag||T.hideCursor()}),M.sensitiverail&&(T.bind(T.railh,"click",function(e){T.doRailClick(e,!1,!0)}),T.bind(T.railh,"dblclick",function(e){T.doRailClick(e,!0,!0)}),T.bind(T.cursorh,"click",function(e){T.cancelEvent(e)}),T.bind(T.cursorh,"dblclick",function(e){T.cancelEvent(e)})))),M.cursordragontouch&&(this.istouchcapable||P.cantouch)&&(T.bind(T.cursor,"touchstart",T.ontouchstartCursor),T.bind(T.cursor,"touchmove",T.ontouchmoveCursor),T.bind(T.cursor,"touchend",T.ontouchendCursor),T.cursorh&&T.bind(T.cursorh,"touchstart",function(e){T.ontouchstartCursor(e,!0)}),T.cursorh&&T.bind(T.cursorh,"touchmove",T.ontouchmoveCursor),T.cursorh&&T.bind(T.cursorh,"touchend",T.ontouchendCursor)),M.emulatetouch||P.isandroid||P.isios?(T.bind(P.hasmousecapture?T.win:l,"mouseup",T.ontouchend),T.onclick&&T.bind(l,"click",T.onclick),M.cursordragontouch?(T.bind(T.cursor,"mousedown",T.onmousedown),T.bind(T.cursor,"mouseup",T.onmouseup),T.cursorh&&T.bind(T.cursorh,"mousedown",function(e){T.onmousedown(e,!0)}),T.cursorh&&T.bind(T.cursorh,"mouseup",T.onmouseup)):(T.bind(T.rail,"mousedown",function(e){e.preventDefault()}),T.railh&&T.bind(T.railh,"mousedown",function(e){e.preventDefault()}))):(T.bind(P.hasmousecapture?T.win:l,"mouseup",T.onmouseup),T.bind(l,"mousemove",T.onmousemove),T.onclick&&T.bind(l,"click",T.onclick),T.bind(T.cursor,"mousedown",T.onmousedown),T.bind(T.cursor,"mouseup",T.onmouseup),T.railh&&(T.bind(T.cursorh,"mousedown",function(e){T.onmousedown(e,!0)}),T.bind(T.cursorh,"mouseup",T.onmouseup)),!T.ispage&&M.enablescrollonselection&&(T.bind(T.win[0],"mousedown",T.onselectionstart),T.bind(l,"mouseup",T.onselectionend),T.bind(T.cursor,"mouseup",T.onselectionend),T.cursorh&&T.bind(T.cursorh,"mouseup",T.onselectionend),T.bind(l,"mousemove",T.onselectiondrag)),T.zoom&&(T.jqbind(T.zoom,"mouseenter",function(){T.canshowonmouseevent&&T.showCursor(),T.rail.active=!0}),T.jqbind(T.zoom,"mouseleave",function(){T.rail.active=!1,T.rail.drag||T.hideCursor()}))),M.enablemousewheel&&(T.isiframe||T.mousewheel(P.isie&&T.ispage?l:T.win,T.onmousewheel),T.mousewheel(T.rail,T.onmousewheel),T.railh&&T.mousewheel(T.railh,T.onmousewheelhr)),T.ispage||P.cantouch||/HTML|^BODY/.test(T.win[0].nodeName)||(T.win.attr("tabindex")||T.win.attr({tabindex:++r}),T.bind(T.win,"focus",function(e){o=T.getTarget(e).id||T.getTarget(e)||!1,T.hasfocus=!0,T.canshowonmouseevent&&T.noticeCursor()}),T.bind(T.win,"blur",function(e){o=!1,T.hasfocus=!1}),T.bind(T.win,"mouseenter",function(e){t=T.getTarget(e).id||T.getTarget(e)||!1,T.hasmousefocus=!0,T.canshowonmouseevent&&T.noticeCursor()}),T.bind(T.win,"mouseleave",function(e){t=!1,T.hasmousefocus=!1,T.rail.drag||T.hideCursor()})),T.onkeypress=function(e){if(T.railslocked&&0===T.page.maxh)return!0;e=e||a.event;var r=T.getTarget(e);if(r&&/INPUT|TEXTAREA|SELECT|OPTION/.test(r.nodeName)&&(!(r.getAttribute("type")||r.type||!1)||!/submit|button|cancel/i.tp))return!0;if(n(r).attr("contenteditable"))return!0;if(T.hasfocus||T.hasmousefocus&&!o||T.ispage&&!o&&!t){var i=e.keyCode;if(T.railslocked&&27!=i)return T.cancelEvent(e);var s=e.ctrlKey||!1,l=e.shiftKey||!1,c=!1;switch(i){case 38:case 63233:T.doScrollBy(72),c=!0;break;case 40:case 63235:T.doScrollBy(-72),c=!0;break;case 37:case 63232:T.railh&&(s?T.doScrollLeft(0):T.doScrollLeftBy(72),c=!0);break;case 39:case 63234:T.railh&&(s?T.doScrollLeft(T.page.maxw):T.doScrollLeftBy(-72),c=!0);break;case 33:case 63276:T.doScrollBy(T.view.h),c=!0;break;case 34:case 63277:T.doScrollBy(-T.view.h),c=!0;break;case 36:case 63273:T.railh&&s?T.doScrollPos(0,0):T.doScrollTo(0),c=!0;break;case 35:case 63275:T.railh&&s?T.doScrollPos(T.page.maxw,T.page.maxh):T.doScrollTo(T.page.maxh),c=!0;break;case 32:M.spacebarenabled&&(l?T.doScrollBy(T.view.h):T.doScrollBy(-T.view.h),c=!0);break;case 27:T.zoomactive&&(T.doZoom(),c=!0)}if(c)return T.cancelEvent(e)}},M.enablekeyboard&&T.bind(l,P.isopera&&!P.isopera12?"keypress":"keydown",T.onkeypress),T.bind(l,"keydown",function(e){(e.ctrlKey||!1)&&(T.wheelprevented=!0)}),T.bind(l,"keyup",function(e){e.ctrlKey||!1||(T.wheelprevented=!1)}),T.bind(a,"blur",function(e){T.wheelprevented=!1}),T.bind(a,"resize",T.onscreenresize),T.bind(a,"orientationchange",T.onscreenresize),T.bind(a,"load",T.lazyResize),P.ischrome&&!T.ispage&&!T.haswrapper){var C=T.win.attr("style"),N=parseFloat(T.win.css("width"))+1;T.win.css("width",N),T.synched("chromefix",function(){T.win.attr("style",C)})}if(T.onAttributeChange=function(e){T.lazyResize(T.isieold?250:30)},M.enableobserver&&(T.isie11||!1===m||(T.observerbody=new m(function(e){if(e.forEach(function(e){if("attributes"==e.type)return E.hasClass("modal-open")&&E.hasClass("modal-dialog")&&!n.contains(n(".modal-dialog")[0],T.doc[0])?T.hide():T.show()}),T.me.clientWidth!=T.page.width||T.me.clientHeight!=T.page.height)return T.lazyResize(30)}),T.observerbody.observe(l.body,{childList:!0,subtree:!0,characterData:!1,attributes:!0,attributeFilter:["class"]})),!T.ispage&&!T.haswrapper)){var R=T.win[0];!1!==m?(T.observer=new m(function(e){e.forEach(T.onAttributeChange)}),T.observer.observe(R,{childList:!0,characterData:!1,attributes:!0,subtree:!1}),T.observerremover=new m(function(e){e.forEach(function(e){if(e.removedNodes.length>0)for(var o in e.removedNodes)if(T&&e.removedNodes[o]===R)return T.remove()})}),T.observerremover.observe(R.parentNode,{childList:!0,characterData:!1,attributes:!1,subtree:!1})):(T.bind(R,P.isie&&!P.isie9?"propertychange":"DOMAttrModified",T.onAttributeChange),P.isie9&&R.attachEvent("onpropertychange",T.onAttributeChange),T.bind(R,"DOMNodeRemoved",function(e){e.target===R&&T.remove()}))}!T.ispage&&M.boxzoom&&T.bind(a,"resize",T.resizeZoom),T.istextarea&&(T.bind(T.win,"keydown",T.lazyResize),T.bind(T.win,"mouseup",T.lazyResize)),T.lazyResize(30)}if("IFRAME"==this.doc[0].nodeName){var _=function(){T.iframexd=!1;var o;try{(o="contentDocument"in this?this.contentDocument:this.contentWindow._doc).domain}catch(e){T.iframexd=!0,o=!1}if(T.iframexd)return"console"in a&&console.log("NiceScroll error: policy restriced iframe"),!0;if(T.forcescreen=!0,T.isiframe&&(T.iframe={doc:n(o),html:T.doc.contents().find("html")[0],body:T.doc.contents().find("body")[0]},T.getContentSize=function(){return{w:Math.max(T.iframe.html.scrollWidth,T.iframe.body.scrollWidth),h:Math.max(T.iframe.html.scrollHeight,T.iframe.body.scrollHeight)}},T.docscroll=n(T.iframe.body)),!P.isios&&M.iframeautoresize&&!T.isiframe){T.win.scrollTop(0),T.doc.height("");var t=Math.max(o.getElementsByTagName("html")[0].scrollHeight,o.body.scrollHeight);T.doc.height(t)}T.lazyResize(30),T.css(n(T.iframe.body),e),P.isios&&T.haswrapper&&T.css(n(o.body),{"-webkit-transform":"translate3d(0,0,0)"}),"contentWindow"in this?T.bind(this.contentWindow,"scroll",T.onscroll):T.bind(o,"scroll",T.onscroll),M.enablemousewheel&&T.mousewheel(o,T.onmousewheel),M.enablekeyboard&&T.bind(o,P.isopera?"keypress":"keydown",T.onkeypress),P.cantouch?(T.bind(o,"touchstart",T.ontouchstart),T.bind(o,"touchmove",T.ontouchmove)):M.emulatetouch&&(T.bind(o,"mousedown",T.ontouchstart),T.bind(o,"mousemove",function(e){return T.ontouchmove(e,!0)}),M.grabcursorenabled&&P.cursorgrabvalue&&T.css(n(o.body),{cursor:P.cursorgrabvalue})),T.bind(o,"mouseup",T.ontouchend),T.zoom&&(M.dblclickzoom&&T.bind(o,"dblclick",T.doZoom),T.ongesturezoom&&T.bind(o,"gestureend",T.ongesturezoom))};this.doc[0].readyState&&"complete"===this.doc[0].readyState&&setTimeout(function(){_.call(T.doc[0],!1)},500),T.bind(this.doc,"load",_)}},this.showCursor=function(e,o){if(T.cursortimeout&&(clearTimeout(T.cursortimeout),T.cursortimeout=0),T.rail){if(T.autohidedom&&(T.autohidedom.stop().css({opacity:M.cursoropacitymax}),T.cursoractive=!0),T.rail.drag&&1==T.rail.drag.pt||(void 0!==e&&!1!==e&&(T.scroll.y=e/T.scrollratio.y|0),void 0!==o&&(T.scroll.x=o/T.scrollratio.x|0)),T.cursor.css({height:T.cursorheight,top:T.scroll.y}),T.cursorh){var t=T.hasreversehr?T.scrollvaluemaxw-T.scroll.x:T.scroll.x;T.cursorh.css({width:T.cursorwidth,left:!T.rail.align&&T.rail.visibility?t+T.rail.width:t}),T.cursoractive=!0}T.zoom&&T.zoom.stop().css({opacity:M.cursoropacitymax})}},this.hideCursor=function(e){T.cursortimeout||T.rail&&T.autohidedom&&(T.hasmousefocus&&"leave"===M.autohidemode||(T.cursortimeout=setTimeout(function(){T.rail.active&&T.showonmouseevent||(T.autohidedom.stop().animate({opacity:M.cursoropacitymin}),T.zoom&&T.zoom.stop().animate({opacity:M.cursoropacitymin}),T.cursoractive=!1),T.cursortimeout=0},e||M.hidecursordelay)))},this.noticeCursor=function(e,o,t){T.showCursor(o,t),T.rail.active||T.hideCursor(e)},this.getContentSize=T.ispage?function(){return{w:Math.max(l.body.scrollWidth,l.documentElement.scrollWidth),h:Math.max(l.body.scrollHeight,l.documentElement.scrollHeight)}}:T.haswrapper?function(){return{w:T.doc[0].offsetWidth,h:T.doc[0].offsetHeight}}:function(){return{w:T.docscroll[0].scrollWidth,h:T.docscroll[0].scrollHeight}},this.onResize=function(e,o){if(!T||!T.win)return!1;var t=T.page.maxh,r=T.page.maxw,i=T.view.h,s=T.view.w;if(T.view={w:T.ispage?T.win.width():T.win[0].clientWidth,h:T.ispage?T.win.height():T.win[0].clientHeight},T.page=o||T.getContentSize(),T.page.maxh=Math.max(0,T.page.h-T.view.h),T.page.maxw=Math.max(0,T.page.w-T.view.w),T.page.maxh==t&&T.page.maxw==r&&T.view.w==s&&T.view.h==i){if(T.ispage)return T;var n=T.win.offset();if(T.lastposition){var l=T.lastposition;if(l.top==n.top&&l.left==n.left)return T}T.lastposition=n}return 0===T.page.maxh?(T.hideRail(),T.scrollvaluemax=0,T.scroll.y=0,T.scrollratio.y=0,T.cursorheight=0,T.setScrollTop(0),T.rail&&(T.rail.scrollable=!1)):(T.page.maxh-=M.railpadding.top+M.railpadding.bottom,T.rail.scrollable=!0),0===T.page.maxw?(T.hideRailHr(),T.scrollvaluemaxw=0,T.scroll.x=0,T.scrollratio.x=0,T.cursorwidth=0,T.setScrollLeft(0),T.railh&&(T.railh.scrollable=!1)):(T.page.maxw-=M.railpadding.left+M.railpadding.right,T.railh&&(T.railh.scrollable=M.horizrailenabled)),T.railslocked=T.locked||0===T.page.maxh&&0===T.page.maxw,T.railslocked?(T.ispage||T.updateScrollBar(T.view),!1):(T.hidden||(T.rail.visibility||T.showRail(),T.railh&&!T.railh.visibility&&T.showRailHr()),T.istextarea&&T.win.css("resize")&&"none"!=T.win.css("resize")&&(T.view.h-=20),T.cursorheight=Math.min(T.view.h,Math.round(T.view.h*(T.view.h/T.page.h))),T.cursorheight=M.cursorfixedheight?M.cursorfixedheight:Math.max(M.cursorminheight,T.cursorheight),T.cursorwidth=Math.min(T.view.w,Math.round(T.view.w*(T.view.w/T.page.w))),T.cursorwidth=M.cursorfixedheight?M.cursorfixedheight:Math.max(M.cursorminheight,T.cursorwidth),T.scrollvaluemax=T.view.h-T.cursorheight-(M.railpadding.top+M.railpadding.bottom),T.hasborderbox||(T.scrollvaluemax-=T.cursor[0].offsetHeight-T.cursor[0].clientHeight),T.railh&&(T.railh.width=T.page.maxh>0?T.view.w-T.rail.width:T.view.w,T.scrollvaluemaxw=T.railh.width-T.cursorwidth-(M.railpadding.left+M.railpadding.right)),T.ispage||T.updateScrollBar(T.view),T.scrollratio={x:T.page.maxw/T.scrollvaluemaxw,y:T.page.maxh/T.scrollvaluemax},T.getScrollTop()>T.page.maxh?T.doScrollTop(T.page.maxh):(T.scroll.y=T.getScrollTop()/T.scrollratio.y|0,T.scroll.x=T.getScrollLeft()/T.scrollratio.x|0,T.cursoractive&&T.noticeCursor()),T.scroll.y&&0===T.getScrollTop()&&T.doScrollTo(T.scroll.y*T.scrollratio.y|0),T)},this.resize=T.onResize;var O=0;this.onscreenresize=function(e){clearTimeout(O);var o=!T.ispage&&!T.haswrapper;o&&T.hideRails(),O=setTimeout(function(){T&&(o&&T.showRails(),T.resize()),O=0},120)},this.lazyResize=function(e){return clearTimeout(O),e=isNaN(e)?240:e,O=setTimeout(function(){T&&T.resize(),O=0},e),T},this.jqbind=function(e,o,t){T.events.push({e:e,n:o,f:t,q:!0}),n(e).on(o,t)},this.mousewheel=function(e,o,t){var r="jquery"in e?e[0]:e;if("onwheel"in l.createElement("div"))T._bind(r,"wheel",o,t||!1);else{var i=void 0!==l.onmousewheel?"mousewheel":"DOMMouseScroll";S(r,i,o,t||!1),"DOMMouseScroll"==i&&S(r,"MozMousePixelScroll",o,t||!1)}};var Y=!1;if(P.haseventlistener){try{var H=Object.defineProperty({},"passive",{get:function(){Y=!0}});a.addEventListener("test",null,H)}catch(e){}this.stopPropagation=function(e){return!!e&&((e=e.original?e.original:e).stopPropagation(),!1)},this.cancelEvent=function(e){return e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),e.preventManipulation&&e.preventManipulation(),!1}}else Event.prototype.preventDefault=function(){this.returnValue=!1},Event.prototype.stopPropagation=function(){this.cancelBubble=!0},a.constructor.prototype.addEventListener=l.constructor.prototype.addEventListener=Element.prototype.addEventListener=function(e,o,t){this.attachEvent("on"+e,o)},a.constructor.prototype.removeEventListener=l.constructor.prototype.removeEventListener=Element.prototype.removeEventListener=function(e,o,t){this.detachEvent("on"+e,o)},this.cancelEvent=function(e){return(e=e||a.event)&&(e.cancelBubble=!0,e.cancel=!0,e.returnValue=!1),!1},this.stopPropagation=function(e){return(e=e||a.event)&&(e.cancelBubble=!0),!1};this.delegate=function(e,o,t,r,i){var s=d[o]||!1;s||(s={a:[],l:[],f:function(e){for(var o=s.l,t=!1,r=o.length-1;r>=0;r--)if(!1===(t=o[r].call(e.target,e)))return!1;return t}},T.bind(e,o,s.f,r,i),d[o]=s),T.ispage?(s.a=[T.id].concat(s.a),s.l=[t].concat(s.l)):(s.a.push(T.id),s.l.push(t))},this.undelegate=function(e,o,t,r,i){var s=d[o]||!1;if(s&&s.l)for(var n=0,l=s.l.length;n<l;n++)s.a[n]===T.id&&(s.a.splice(n),s.l.splice(n),0===s.a.length&&(T._unbind(e,o,s.l.f),d[o]=null))},this.bind=function(e,o,t,r,i){var s="jquery"in e?e[0]:e;T._bind(s,o,t,r||!1,i||!1)},this._bind=function(e,o,t,r,i){T.events.push({e:e,n:o,f:t,b:r,q:!1}),Y&&i?e.addEventListener(o,t,{passive:!1,capture:r}):e.addEventListener(o,t,r||!1)},this._unbind=function(e,o,t,r){d[o]?T.undelegate(e,o,t,r):e.removeEventListener(o,t,r)},this.unbindAll=function(){for(var e=0;e<T.events.length;e++){var o=T.events[e];o.q?o.e.unbind(o.n,o.f):T._unbind(o.e,o.n,o.f,o.b)}},this.showRails=function(){return T.showRail().showRailHr()},this.showRail=function(){return 0===T.page.maxh||!T.ispage&&"none"==T.win.css("display")||(T.rail.visibility=!0,T.rail.css("display","block")),T},this.showRailHr=function(){return T.railh&&(0===T.page.maxw||!T.ispage&&"none"==T.win.css("display")||(T.railh.visibility=!0,T.railh.css("display","block"))),T},this.hideRails=function(){return T.hideRail().hideRailHr()},this.hideRail=function(){return T.rail.visibility=!1,T.rail.css("display","none"),T},this.hideRailHr=function(){return T.railh&&(T.railh.visibility=!1,T.railh.css("display","none")),T},this.show=function(){return T.hidden=!1,T.railslocked=!1,T.showRails()},this.hide=function(){return T.hidden=!0,T.railslocked=!0,T.hideRails()},this.toggle=function(){return T.hidden?T.show():T.hide()},this.remove=function(){T.stop(),T.cursortimeout&&clearTimeout(T.cursortimeout);for(var e in T.delaylist)T.delaylist[e]&&h(T.delaylist[e].h);T.doZoomOut(),T.unbindAll(),P.isie9&&T.win[0].detachEvent("onpropertychange",T.onAttributeChange),!1!==T.observer&&T.observer.disconnect(),!1!==T.observerremover&&T.observerremover.disconnect(),!1!==T.observerbody&&T.observerbody.disconnect(),T.events=null,T.cursor&&T.cursor.remove(),T.cursorh&&T.cursorh.remove(),T.rail&&T.rail.remove(),T.railh&&T.railh.remove(),T.zoom&&T.zoom.remove();for(var o=0;o<T.saved.css.length;o++){var t=T.saved.css[o];t[0].css(t[1],void 0===t[2]?"":t[2])}T.saved=!1,T.me.data("__nicescroll","");var r=n.nicescroll;r.each(function(e){if(this&&this.id===T.id){delete r[e];for(var o=++e;o<r.length;o++,e++)r[e]=r[o];--r.length&&delete r[r.length]}});for(var i in T)T[i]=null,delete T[i];T=null},this.scrollstart=function(e){return this.onscrollstart=e,T},this.scrollend=function(e){return this.onscrollend=e,T},this.scrollcancel=function(e){return this.onscrollcancel=e,T},this.zoomin=function(e){return this.onzoomin=e,T},this.zoomout=function(e){return this.onzoomout=e,T},this.isScrollable=function(e){var o=e.target?e.target:e;if("OPTION"==o.nodeName)return!0;for(;o&&1==o.nodeType&&o!==this.me[0]&&!/^BODY|HTML/.test(o.nodeName);){var t=n(o),r=t.css("overflowY")||t.css("overflowX")||t.css("overflow")||"";if(/scroll|auto/.test(r))return o.clientHeight!=o.scrollHeight;o=!!o.parentNode&&o.parentNode}return!1},this.getViewport=function(e){for(var o=!(!e||!e.parentNode)&&e.parentNode;o&&1==o.nodeType&&!/^BODY|HTML/.test(o.nodeName);){var t=n(o);if(/fixed|absolute/.test(t.css("position")))return t;var r=t.css("overflowY")||t.css("overflowX")||t.css("overflow")||"";if(/scroll|auto/.test(r)&&o.clientHeight!=o.scrollHeight)return t;if(t.getNiceScroll().length>0)return t;o=!!o.parentNode&&o.parentNode}return!1},this.triggerScrollStart=function(e,o,t,r,i){if(T.onscrollstart){var s={type:"scrollstart",current:{x:e,y:o},request:{x:t,y:r},end:{x:T.newscrollx,y:T.newscrolly},speed:i};T.onscrollstart.call(T,s)}},this.triggerScrollEnd=function(){if(T.onscrollend){var e=T.getScrollLeft(),o=T.getScrollTop(),t={type:"scrollend",current:{x:e,y:o},end:{x:e,y:o}};T.onscrollend.call(T,t)}};var B=0,X=0,D=0,A=1,q=!1;if(this.onmousewheel=function(e){if(T.wheelprevented||T.locked)return!1;if(T.railslocked)return T.debounced("checkunlock",T.resize,250),!1;if(T.rail.drag)return T.cancelEvent(e);if("auto"===M.oneaxismousemode&&0!==e.deltaX&&(M.oneaxismousemode=!1),M.oneaxismousemode&&0===e.deltaX&&!T.rail.scrollable)return!T.railh||!T.railh.scrollable||T.onmousewheelhr(e);var o=f(),t=!1;if(M.preservenativescrolling&&T.checkarea+600<o&&(T.nativescrollingarea=T.isScrollable(e),t=!0),T.checkarea=o,T.nativescrollingarea)return!0;var r=k(e,!1,t);return r&&(T.checkarea=0),r},this.onmousewheelhr=function(e){if(!T.wheelprevented){if(T.railslocked||!T.railh.scrollable)return!0;if(T.rail.drag)return T.cancelEvent(e);var o=f(),t=!1;return M.preservenativescrolling&&T.checkarea+600<o&&(T.nativescrollingarea=T.isScrollable(e),t=!0),T.checkarea=o,!!T.nativescrollingarea||(T.railslocked?T.cancelEvent(e):k(e,!0,t))}},this.stop=function(){return T.cancelScroll(),T.scrollmon&&T.scrollmon.stop(),T.cursorfreezed=!1,T.scroll.y=Math.round(T.getScrollTop()*(1/T.scrollratio.y)),T.noticeCursor(),T},this.getTransitionSpeed=function(e){return 80+e/72*M.scrollspeed|0},M.smoothscroll)if(T.ishwscroll&&P.hastransition&&M.usetransition&&M.smoothscroll){var j="";this.resetTransition=function(){j="",T.doc.css(P.prefixstyle+"transition-duration","0ms")},this.prepareTransition=function(e,o){var t=o?e:T.getTransitionSpeed(e),r=t+"ms";return j!==r&&(j=r,T.doc.css(P.prefixstyle+"transition-duration",r)),t},this.doScrollLeft=function(e,o){var t=T.scrollrunning?T.newscrolly:T.getScrollTop();T.doScrollPos(e,t,o)},this.doScrollTop=function(e,o){var t=T.scrollrunning?T.newscrollx:T.getScrollLeft();T.doScrollPos(t,e,o)},this.cursorupdate={running:!1,start:function(){var e=this;if(!e.running){e.running=!0;var o=function(){e.running&&u(o),T.showCursor(T.getScrollTop(),T.getScrollLeft()),T.notifyScrollEvent(T.win[0])};u(o)}},stop:function(){this.running=!1}},this.doScrollPos=function(e,o,t){var r=T.getScrollTop(),i=T.getScrollLeft();if(((T.newscrolly-r)*(o-r)<0||(T.newscrollx-i)*(e-i)<0)&&T.cancelScroll(),M.bouncescroll?(o<0?o=o/2|0:o>T.page.maxh&&(o=T.page.maxh+(o-T.page.maxh)/2|0),e<0?e=e/2|0:e>T.page.maxw&&(e=T.page.maxw+(e-T.page.maxw)/2|0)):(o<0?o=0:o>T.page.maxh&&(o=T.page.maxh),e<0?e=0:e>T.page.maxw&&(e=T.page.maxw)),T.scrollrunning&&e==T.newscrollx&&o==T.newscrolly)return!1;T.newscrolly=o,T.newscrollx=e;var s=T.getScrollTop(),n=T.getScrollLeft(),l={};l.x=e-n,l.y=o-s;var a=0|Math.sqrt(l.x*l.x+l.y*l.y),c=T.prepareTransition(a);T.scrollrunning||(T.scrollrunning=!0,T.triggerScrollStart(n,s,e,o,c),T.cursorupdate.start()),T.scrollendtrapped=!0,P.transitionend||(T.scrollendtrapped&&clearTimeout(T.scrollendtrapped),T.scrollendtrapped=setTimeout(T.onScrollTransitionEnd,c)),T.setScrollTop(T.newscrolly),T.setScrollLeft(T.newscrollx)},this.cancelScroll=function(){if(!T.scrollendtrapped)return!0;var e=T.getScrollTop(),o=T.getScrollLeft();return T.scrollrunning=!1,P.transitionend||clearTimeout(P.transitionend),T.scrollendtrapped=!1,T.resetTransition(),T.setScrollTop(e),T.railh&&T.setScrollLeft(o),T.timerscroll&&T.timerscroll.tm&&clearInterval(T.timerscroll.tm),T.timerscroll=!1,T.cursorfreezed=!1,T.cursorupdate.stop(),T.showCursor(e,o),T},this.onScrollTransitionEnd=function(){if(T.scrollendtrapped){var e=T.getScrollTop(),o=T.getScrollLeft();if(e<0?e=0:e>T.page.maxh&&(e=T.page.maxh),o<0?o=0:o>T.page.maxw&&(o=T.page.maxw),e!=T.newscrolly||o!=T.newscrollx)return T.doScrollPos(o,e,M.snapbackspeed);T.scrollrunning&&T.triggerScrollEnd(),T.scrollrunning=!1,T.scrollendtrapped=!1,T.resetTransition(),T.timerscroll=!1,T.setScrollTop(e),T.railh&&T.setScrollLeft(o),T.cursorupdate.stop(),T.noticeCursor(!1,e,o),T.cursorfreezed=!1}}}else this.doScrollLeft=function(e,o){var t=T.scrollrunning?T.newscrolly:T.getScrollTop();T.doScrollPos(e,t,o)},this.doScrollTop=function(e,o){var t=T.scrollrunning?T.newscrollx:T.getScrollLeft();T.doScrollPos(t,e,o)},this.doScrollPos=function(e,o,t){var r=T.getScrollTop(),i=T.getScrollLeft();((T.newscrolly-r)*(o-r)<0||(T.newscrollx-i)*(e-i)<0)&&T.cancelScroll();var s=!1;if(T.bouncescroll&&T.rail.visibility||(o<0?(o=0,s=!0):o>T.page.maxh&&(o=T.page.maxh,s=!0)),T.bouncescroll&&T.railh.visibility||(e<0?(e=0,s=!0):e>T.page.maxw&&(e=T.page.maxw,s=!0)),T.scrollrunning&&T.newscrolly===o&&T.newscrollx===e)return!0;T.newscrolly=o,T.newscrollx=e,T.dst={},T.dst.x=e-i,T.dst.y=o-r,T.dst.px=i,T.dst.py=r;var n=0|Math.sqrt(T.dst.x*T.dst.x+T.dst.y*T.dst.y),l=T.getTransitionSpeed(n);T.bzscroll={};var a=s?1:.58;T.bzscroll.x=new R(i,T.newscrollx,l,0,0,a,1),T.bzscroll.y=new R(r,T.newscrolly,l,0,0,a,1);f();var c=function(){if(T.scrollrunning){var e=T.bzscroll.y.getPos();T.setScrollLeft(T.bzscroll.x.getNow()),T.setScrollTop(T.bzscroll.y.getNow()),e<=1?T.timer=u(c):(T.scrollrunning=!1,T.timer=0,T.triggerScrollEnd())}};T.scrollrunning||(T.triggerScrollStart(i,r,e,o,l),T.scrollrunning=!0,T.timer=u(c))},this.cancelScroll=function(){return T.timer&&h(T.timer),T.timer=0,T.bzscroll=!1,T.scrollrunning=!1,T};else this.doScrollLeft=function(e,o){var t=T.getScrollTop();T.doScrollPos(e,t,o)},this.doScrollTop=function(e,o){var t=T.getScrollLeft();T.doScrollPos(t,e,o)},this.doScrollPos=function(e,o,t){var r=e>T.page.maxw?T.page.maxw:e;r<0&&(r=0);var i=o>T.page.maxh?T.page.maxh:o;i<0&&(i=0),T.synched("scroll",function(){T.setScrollTop(i),T.setScrollLeft(r)})},this.cancelScroll=function(){};this.doScrollBy=function(e,o){z(0,e)},this.doScrollLeftBy=function(e,o){z(e,0)},this.doScrollTo=function(e,o){var t=o?Math.round(e*T.scrollratio.y):e;t<0?t=0:t>T.page.maxh&&(t=T.page.maxh),T.cursorfreezed=!1,T.doScrollTop(e)},this.checkContentSize=function(){var e=T.getContentSize();e.h==T.page.h&&e.w==T.page.w||T.resize(!1,e)},T.onscroll=function(e){T.rail.drag||T.cursorfreezed||T.synched("scroll",function(){T.scroll.y=Math.round(T.getScrollTop()/T.scrollratio.y),T.railh&&(T.scroll.x=Math.round(T.getScrollLeft()/T.scrollratio.x)),T.noticeCursor()})},T.bind(T.docscroll,"scroll",T.onscroll),this.doZoomIn=function(e){if(!T.zoomactive){T.zoomactive=!0,T.zoomrestore={style:{}};var o=["position","top","left","zIndex","backgroundColor","marginTop","marginBottom","marginLeft","marginRight"],t=T.win[0].style;for(var r in o){var i=o[r];T.zoomrestore.style[i]=void 0!==t[i]?t[i]:""}T.zoomrestore.style.width=T.win.css("width"),T.zoomrestore.style.height=T.win.css("height"),T.zoomrestore.padding={w:T.win.outerWidth()-T.win.width(),h:T.win.outerHeight()-T.win.height()},P.isios4&&(T.zoomrestore.scrollTop=c.scrollTop(),c.scrollTop(0)),T.win.css({position:P.isios4?"absolute":"fixed",top:0,left:0,zIndex:s+100,margin:0});var n=T.win.css("backgroundColor");return(""===n||/transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(n))&&T.win.css("backgroundColor","#fff"),T.rail.css({zIndex:s+101}),T.zoom.css({zIndex:s+102}),T.zoom.css("backgroundPosition","0 -18px"),T.resizeZoom(),T.onzoomin&&T.onzoomin.call(T),T.cancelEvent(e)}},this.doZoomOut=function(e){if(T.zoomactive)return T.zoomactive=!1,T.win.css("margin",""),T.win.css(T.zoomrestore.style),P.isios4&&c.scrollTop(T.zoomrestore.scrollTop),T.rail.css({"z-index":T.zindex}),T.zoom.css({"z-index":T.zindex}),T.zoomrestore=!1,T.zoom.css("backgroundPosition","0 0"),T.onResize(),T.onzoomout&&T.onzoomout.call(T),T.cancelEvent(e)},this.doZoom=function(e){return T.zoomactive?T.doZoomOut(e):T.doZoomIn(e)},this.resizeZoom=function(){if(T.zoomactive){var e=T.getScrollTop();T.win.css({width:c.width()-T.zoomrestore.padding.w+"px",height:c.height()-T.zoomrestore.padding.h+"px"}),T.onResize(),T.setScrollTop(Math.min(T.page.maxh,e))}},this.init(),n.nicescroll.push(this)},y=function(e){var o=this;this.nc=e,this.lastx=0,this.lasty=0,this.speedx=0,this.speedy=0,this.lasttime=0,this.steptime=0,this.snapx=!1,this.snapy=!1,this.demulx=0,this.demuly=0,this.lastscrollx=-1,this.lastscrolly=-1,this.chkx=0,this.chky=0,this.timer=0,this.reset=function(e,t){o.stop(),o.steptime=0,o.lasttime=f(),o.speedx=0,o.speedy=0,o.lastx=e,o.lasty=t,o.lastscrollx=-1,o.lastscrolly=-1},this.update=function(e,t){var r=f();o.steptime=r-o.lasttime,o.lasttime=r;var i=t-o.lasty,s=e-o.lastx,n=o.nc.getScrollTop()+i,l=o.nc.getScrollLeft()+s;o.snapx=l<0||l>o.nc.page.maxw,o.snapy=n<0||n>o.nc.page.maxh,o.speedx=s,o.speedy=i,o.lastx=e,o.lasty=t},this.stop=function(){o.nc.unsynched("domomentum2d"),o.timer&&clearTimeout(o.timer),o.timer=0,o.lastscrollx=-1,o.lastscrolly=-1},this.doSnapy=function(e,t){var r=!1;t<0?(t=0,r=!0):t>o.nc.page.maxh&&(t=o.nc.page.maxh,r=!0),e<0?(e=0,r=!0):e>o.nc.page.maxw&&(e=o.nc.page.maxw,r=!0),r?o.nc.doScrollPos(e,t,o.nc.opt.snapbackspeed):o.nc.triggerScrollEnd()},this.doMomentum=function(e){var t=f(),r=e?t+e:o.lasttime,i=o.nc.getScrollLeft(),s=o.nc.getScrollTop(),n=o.nc.page.maxh,l=o.nc.page.maxw;o.speedx=l>0?Math.min(60,o.speedx):0,o.speedy=n>0?Math.min(60,o.speedy):0;var a=r&&t-r<=60;(s<0||s>n||i<0||i>l)&&(a=!1);var c=!(!o.speedy||!a)&&o.speedy,d=!(!o.speedx||!a)&&o.speedx;if(c||d){var u=Math.max(16,o.steptime);if(u>50){var h=u/50;o.speedx*=h,o.speedy*=h,u=50}o.demulxy=0,o.lastscrollx=o.nc.getScrollLeft(),o.chkx=o.lastscrollx,o.lastscrolly=o.nc.getScrollTop(),o.chky=o.lastscrolly;var p=o.lastscrollx,m=o.lastscrolly,g=function(){var e=f()-t>600?.04:.02;o.speedx&&(p=Math.floor(o.lastscrollx-o.speedx*(1-o.demulxy)),o.lastscrollx=p,(p<0||p>l)&&(e=.1)),o.speedy&&(m=Math.floor(o.lastscrolly-o.speedy*(1-o.demulxy)),o.lastscrolly=m,(m<0||m>n)&&(e=.1)),o.demulxy=Math.min(1,o.demulxy+e),o.nc.synched("domomentum2d",function(){if(o.speedx){o.nc.getScrollLeft();o.chkx=p,o.nc.setScrollLeft(p)}if(o.speedy){o.nc.getScrollTop();o.chky=m,o.nc.setScrollTop(m)}o.timer||(o.nc.hideCursor(),o.doSnapy(p,m))}),o.demulxy<1?o.timer=setTimeout(g,u):(o.stop(),o.nc.hideCursor(),o.doSnapy(p,m))};g()}else o.doSnapy(o.nc.getScrollLeft(),o.nc.getScrollTop())}},x=e.fn.scrollTop;e.cssHooks.pageYOffset={get:function(e,o,t){var r=n.data(e,"__nicescroll")||!1;return r&&r.ishwscroll?r.getScrollTop():x.call(e)},set:function(e,o){var t=n.data(e,"__nicescroll")||!1;return t&&t.ishwscroll?t.setScrollTop(parseInt(o)):x.call(e,o),this}},e.fn.scrollTop=function(e){if(void 0===e){var o=!!this[0]&&(n.data(this[0],"__nicescroll")||!1);return o&&o.ishwscroll?o.getScrollTop():x.call(this)}return this.each(function(){var o=n.data(this,"__nicescroll")||!1;o&&o.ishwscroll?o.setScrollTop(parseInt(e)):x.call(n(this),e)})};var S=e.fn.scrollLeft;n.cssHooks.pageXOffset={get:function(e,o,t){var r=n.data(e,"__nicescroll")||!1;return r&&r.ishwscroll?r.getScrollLeft():S.call(e)},set:function(e,o){var t=n.data(e,"__nicescroll")||!1;return t&&t.ishwscroll?t.setScrollLeft(parseInt(o)):S.call(e,o),this}},e.fn.scrollLeft=function(e){if(void 0===e){var o=!!this[0]&&(n.data(this[0],"__nicescroll")||!1);return o&&o.ishwscroll?o.getScrollLeft():S.call(this)}return this.each(function(){var o=n.data(this,"__nicescroll")||!1;o&&o.ishwscroll?o.setScrollLeft(parseInt(e)):S.call(n(this),e)})};var z=function(e){var o=this;if(this.length=0,this.name="nicescrollarray",this.each=function(e){return n.each(o,e),o},this.push=function(e){o[o.length]=e,o.length++},this.eq=function(e){return o[e]},e)for(var t=0;t<e.length;t++){var r=n.data(e[t],"__nicescroll")||!1;r&&(this[this.length]=r,this.length++)}return this};!function(e,o,t){for(var r=0,i=o.length;r<i;r++)t(e,o[r])}(z.prototype,["show","hide","toggle","onResize","resize","remove","stop","doScrollPos"],function(e,o){e[o]=function(){var e=arguments;return this.each(function(){this[o].apply(this,e)})}}),e.fn.getNiceScroll=function(e){return void 0===e?new z(this):this[e]&&n.data(this[e],"__nicescroll")||!1},(e.expr.pseudos||e.expr[":"]).nicescroll=function(e){return void 0!==n.data(e,"__nicescroll")},n.fn.niceScroll=function(e,o){void 0!==o||"object"!=typeof e||"jquery"in e||(o=e,e=!1);var t=new z;return this.each(function(){var r=n(this),i=n.extend({},o);if(e){var s=n(e);i.doc=s.length>1?n(e,r):s,i.win=r}!("doc"in i)||"win"in i||(i.win=r);var l=r.data("__nicescroll")||!1;l||(i.doc=i.doc||r,l=new b(i,r),r.data("__nicescroll",l)),t.push(l)}),1===t.length?t[0]:t},a.NiceScroll={getjQuery:function(){return e}},n.nicescroll||(n.nicescroll=new z,n.nicescroll.options=g)});;
