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

    // Only continue if we're on IE8/IE9 with jQuery 1.5+ (contains the ajaxTransport function)
    if ($.support.cors || !$.ajaxTransport || !window.XDomainRequest) {
        return $;
    }

    var httpRegEx = /^(https?:)?\/\//i;
    var getOrPostRegEx = /^get|post$/i;
    var sameSchemeRegEx = new RegExp('^(\/\/|' + location.protocol + ')', 'i');

    // ajaxTransport exists in jQuery 1.5+
    $.ajaxTransport('* text html xml json', function (options, userOptions, jqXHR) {

        // Only continue if the request is: asynchronous, uses GET or POST method, has HTTP or HTTPS protocol, and has the same scheme as the calling page
        if (!options.crossDomain || !options.async || !getOrPostRegEx.test(options.type) || !httpRegEx.test(options.url) || !sameSchemeRegEx.test(options.url)) {
            return;
        }

        var xdr = null;

        return {
            send: function (headers, complete) {
                var postData = '';
                var userType = (userOptions.dataType || '').toLowerCase();

                xdr = new XDomainRequest();
                if (/^\d+$/.test(userOptions.timeout)) {
                    xdr.timeout = userOptions.timeout;
                }

                xdr.ontimeout = function () {
                    complete(500, 'timeout');
                };

                xdr.onload = function () {
                    var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
                    var status = {
                        code: 200,
                        message: 'success'
                    };
                    var responses = {
                        text: xdr.responseText
                    };
                    try {
                        if (userType === 'html' || /text\/html/i.test(xdr.contentType)) {
                            responses.html = xdr.responseText;
                        } else if (userType === 'json' || (userType !== 'text' && /\/json/i.test(xdr.contentType))) {
                            try {
                                responses.json = $.parseJSON(xdr.responseText);
                            } catch (e) {
                                status.code = 500;
                                status.message = 'parseerror';
                                //throw 'Invalid JSON: ' + xdr.responseText;
                            }
                        } else if (userType === 'xml' || (userType !== 'text' && /\/xml/i.test(xdr.contentType))) {
                            var doc = new ActiveXObject('Microsoft.XMLDOM');
                            doc.async = false;
                            try {
                                doc.loadXML(xdr.responseText);
                            } catch (e) {
                                doc = undefined;
                            }
                            if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
                                status.code = 500;
                                status.message = 'parseerror';
                                throw 'Invalid XML: ' + xdr.responseText;
                            }
                            responses.xml = doc;
                        }
                    } catch (parseMessage) {
                        throw parseMessage;
                    } finally {
                        complete(status.code, status.message, responses, allResponseHeaders);
                    }
                };

                // set an empty handler for 'onprogress' so requests don't get aborted
                xdr.onprogress = function () { };
                xdr.onerror = function () {
                    complete(500, 'error', {
                        text: xdr.responseText
                    });
                };

                if (userOptions.data) {
                    postData = ($.type(userOptions.data) === 'string') ? userOptions.data : $.param(userOptions.data);
                }
                xdr.open(options.type, options.url);
                xdr.send(postData);
            },
            abort: function () {
                if (xdr) {
                    xdr.abort();
                }
            }
        };
    });

    return $;

}));
/*! UIkit 2.27.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function (t) { if ("function" == typeof define && define.amd && define("uikit", function () { var i = window.UIkit || t(window, window.jQuery, window.document); return i.load = function (t, e, n, o) { var s, a = t.split(","), r = [], l = (o.config && o.config.uikit && o.config.uikit.base ? o.config.uikit.base : "").replace(/\/+$/g, ""); if (!l) throw new Error("Please define base path to UIkit in the requirejs config."); for (s = 0; s < a.length; s += 1) { var c = a[s].replace(/\./g, "/"); r.push(l + "/components/" + c) } e(r, function () { n(i) }) }, i }), !window.jQuery) throw new Error("UIkit requires jQuery"); window && window.jQuery && t(window, window.jQuery, window.document) }(function (t, i, e) { "use strict"; var n = {}, o = t.UIkit ? Object.create(t.UIkit) : void 0; if (n.version = "2.27.2", n.noConflict = function () { return o && (t.UIkit = o, i.UIkit = o, i.fn.uk = o.fn), n }, n.prefix = function (t) { return t }, n.$ = i, n.$doc = n.$(document), n.$win = n.$(window), n.$html = n.$("html"), n.support = {}, n.support.transition = function () { var t = function () { var t, i = e.body || e.documentElement, n = { WebkitTransition: "webkitTransitionEnd", MozTransition: "transitionend", OTransition: "oTransitionEnd otransitionend", transition: "transitionend" }; for (t in n) if (void 0 !== i.style[t]) return n[t] }(); return t && { end: t } }(), n.support.animation = function () { var t = function () { var t, i = e.body || e.documentElement, n = { WebkitAnimation: "webkitAnimationEnd", MozAnimation: "animationend", OAnimation: "oAnimationEnd oanimationend", animation: "animationend" }; for (t in n) if (void 0 !== i.style[t]) return n[t] }(); return t && { end: t } }(), function () { Date.now = Date.now || function () { return (new Date).getTime() }; for (var t = ["webkit", "moz"], i = 0; i < t.length && !window.requestAnimationFrame; ++i) { var e = t[i]; window.requestAnimationFrame = window[e + "RequestAnimationFrame"], window.cancelAnimationFrame = window[e + "CancelAnimationFrame"] || window[e + "CancelRequestAnimationFrame"] } if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) || !window.requestAnimationFrame || !window.cancelAnimationFrame) { var n = 0; window.requestAnimationFrame = function (t) { var i = Date.now(), e = Math.max(n + 16, i); return setTimeout(function () { t(n = e) }, e - i) }, window.cancelAnimationFrame = clearTimeout } }(), n.support.touch = "ontouchstart" in document || t.DocumentTouch && document instanceof t.DocumentTouch || t.navigator.msPointerEnabled && t.navigator.msMaxTouchPoints > 0 || t.navigator.pointerEnabled && t.navigator.maxTouchPoints > 0 || !1, n.support.mutationobserver = t.MutationObserver || t.WebKitMutationObserver || null, n.Utils = {}, n.Utils.isFullscreen = function () { return document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || document.fullscreenElement || !1 }, n.Utils.str2json = function (t, i) { try { return i ? JSON.parse(t.replace(/([\$\w]+)\s*:/g, function (t, i) { return '"' + i + '":' }).replace(/'([^']+)'/g, function (t, i) { return '"' + i + '"' })) : new Function("", "var json = " + t + "; return JSON.parse(JSON.stringify(json));")() } catch (e) { return !1 } }, n.Utils.debounce = function (t, i, e) { var n; return function () { var o = this, s = arguments, a = function () { n = null, e || t.apply(o, s) }, r = e && !n; clearTimeout(n), n = setTimeout(a, i), r && t.apply(o, s) } }, n.Utils.throttle = function (t, i) { var e = !1; return function () { e || (t.call(), e = !0, setTimeout(function () { e = !1 }, i)) } }, n.Utils.removeCssRules = function (t) { var i, e, n, o, s, a, r, l, c, u; t && setTimeout(function () { try { for (u = document.styleSheets, o = 0, r = u.length; r > o; o++) { for (n = u[o], e = [], n.cssRules = n.cssRules, i = s = 0, l = n.cssRules.length; l > s; i = ++s) n.cssRules[i].type === CSSRule.STYLE_RULE && t.test(n.cssRules[i].selectorText) && e.unshift(i); for (a = 0, c = e.length; c > a; a++) n.deleteRule(e[a]) } } catch (d) { } }, 0) }, n.Utils.isInView = function (t, e) { var o = i(t); if (!o.is(":visible")) return !1; var s = n.$win.scrollLeft(), a = n.$win.scrollTop(), r = o.offset(), l = r.left, c = r.top; return e = i.extend({ topoffset: 0, leftoffset: 0 }, e), c + o.height() >= a && c - e.topoffset <= a + n.$win.height() && l + o.width() >= s && l - e.leftoffset <= s + n.$win.width() ? !0 : !1 }, n.Utils.checkDisplay = function (t, e) { var o = n.$("[data-uk-margin], [data-uk-grid-match], [data-uk-grid-margin], [data-uk-check-display]", t || document); return t && !o.length && (o = i(t)), o.trigger("display.uk.check"), e && ("string" != typeof e && (e = '[class*="uk-animation-"]'), o.find(e).each(function () { var t = n.$(this), i = t.attr("class"), e = i.match(/uk-animation-(.+)/); t.removeClass(e[0]).width(), t.addClass(e[0]) })), o }, n.Utils.options = function (t) { if ("string" != i.type(t)) return t; -1 != t.indexOf(":") && "}" != t.trim().substr(-1) && (t = "{" + t + "}"); var e = t ? t.indexOf("{") : -1, o = {}; if (-1 != e) try { o = n.Utils.str2json(t.substr(e)) } catch (s) { } return o }, n.Utils.animate = function (t, e) { var o = i.Deferred(); return t = n.$(t), t.css("display", "none").addClass(e).one(n.support.animation.end, function () { t.removeClass(e), o.resolve() }), t.css("display", ""), o.promise() }, n.Utils.uid = function (t) { return (t || "id") + (new Date).getTime() + "RAND" + Math.ceil(1e5 * Math.random()) }, n.Utils.template = function (t, i) { for (var e, n, o, s, a = t.replace(/\n/g, "\\n").replace(/\{\{\{\s*(.+?)\s*\}\}\}/g, "{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g), r = 0, l = [], c = 0; r < a.length;) { if (e = a[r], e.match(/\{\{\s*(.+?)\s*\}\}/)) switch (r += 1, e = a[r], n = e[0], o = e.substring(e.match(/^(\^|\#|\!|\~|\:)/) ? 1 : 0), n) { case "~": l.push("for(var $i=0;$i<" + o + ".length;$i++) { var $item = " + o + "[$i];"), c++; break; case ":": l.push("for(var $key in " + o + ") { var $val = " + o + "[$key];"), c++; break; case "#": l.push("if(" + o + ") {"), c++; break; case "^": l.push("if(!" + o + ") {"), c++; break; case "/": l.push("}"), c--; break; case "!": l.push("__ret.push(" + o + ");"); break; default: l.push("__ret.push(escape(" + o + "));") } else l.push("__ret.push('" + e.replace(/\'/g, "\\'") + "');"); r += 1 } return s = new Function("$data", ["var __ret = [];", "try {", "with($data){", c ? '__ret = ["Not all blocks are closed correctly."]' : l.join(""), "};", "}catch(e){__ret = [e.message];}", 'return __ret.join("").replace(/\\n\\n/g, "\\n");', "function escape(html) { return String(html).replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');}"].join("\n")), i ? s(i) : s }, n.Utils.focus = function (t, e) { if (t = i(t), !t.length) return t; var n, o = t.find("[autofocus]:first"); return o.length ? o.focus() : (o = t.find(":input" + (e && "," + e || "")).first(), o.length ? o.focus() : (t.attr("tabindex") || (n = 1e3, t.attr("tabindex", n)), t[0].focus(), n && t.attr("tabindex", ""), t)) }, n.Utils.events = {}, n.Utils.events.click = n.support.touch ? "tap" : "click", t.UIkit = n, n.fn = function (t, e) { var o = arguments, s = t.match(/^([a-z\-]+)(?:\.([a-z]+))?/i), a = s[1], r = s[2]; return n[a] ? this.each(function () { var t = i(this), s = t.data(a); s || t.data(a, s = n[a](this, r ? void 0 : e)), r && s[r].apply(s, Array.prototype.slice.call(o, 1)) }) : (i.error("UIkit component [" + a + "] does not exist."), this) }, i.UIkit = n, i.fn.uk = n.fn, n.langdirection = "rtl" == n.$html.attr("dir") ? "right" : "left", n.components = {}, n.component = function (t, e) { var o = function (e, s) { var a = this; return this.UIkit = n, this.element = e ? n.$(e) : null, this.options = i.extend(!0, {}, this.defaults, s), this.plugins = {}, this.element && this.element.data(t, this), this.init(), (this.options.plugins.length ? this.options.plugins : Object.keys(o.plugins)).forEach(function (t) { o.plugins[t].init && (o.plugins[t].init(a), a.plugins[t] = !0) }), this.trigger("init.uk.component", [t, this]), this }; return o.plugins = {}, i.extend(!0, o.prototype, { defaults: { plugins: [] }, boot: function () { }, init: function () { }, on: function (t, i, e) { return n.$(this.element || this).on(t, i, e) }, one: function (t, i, e) { return n.$(this.element || this).one(t, i, e) }, off: function (t) { return n.$(this.element || this).off(t) }, trigger: function (t, i) { return n.$(this.element || this).trigger(t, i) }, find: function (t) { return n.$(this.element ? this.element : []).find(t) }, proxy: function (t, i) { var e = this; i.split(" ").forEach(function (i) { e[i] || (e[i] = function () { return t[i].apply(t, arguments) }) }) }, mixin: function (t, i) { var e = this; i.split(" ").forEach(function (i) { e[i] || (e[i] = t[i].bind(e)) }) }, option: function () { return 1 == arguments.length ? this.options[arguments[0]] || void 0 : (2 == arguments.length && (this.options[arguments[0]] = arguments[1]), void 0) } }, e), this.components[t] = o, this[t] = function () { var e, o; if (arguments.length) switch (arguments.length) { case 1: "string" == typeof arguments[0] || arguments[0].nodeType || arguments[0] instanceof jQuery ? e = i(arguments[0]) : o = arguments[0]; break; case 2: e = i(arguments[0]), o = arguments[1] } return e && e.data(t) ? e.data(t) : new n.components[t](e, o) }, n.domready && n.component.boot(t), o }, n.plugin = function (t, i, e) { this.components[t].plugins[i] = e }, n.component.boot = function (t) { n.components[t].prototype && n.components[t].prototype.boot && !n.components[t].booted && (n.components[t].prototype.boot.apply(n, []), n.components[t].booted = !0) }, n.component.bootComponents = function () { for (var t in n.components) n.component.boot(t) }, n.domObservers = [], n.domready = !1, n.ready = function (t) { n.domObservers.push(t), n.domready && t(document) }, n.on = function (t, i, e) { return t && t.indexOf("ready.uk.dom") > -1 && n.domready && i.apply(n.$doc), n.$doc.on(t, i, e) }, n.one = function (t, i, e) { return t && t.indexOf("ready.uk.dom") > -1 && n.domready ? (i.apply(n.$doc), n.$doc) : n.$doc.one(t, i, e) }, n.trigger = function (t, i) { return n.$doc.trigger(t, i) }, n.domObserve = function (t, i) { n.support.mutationobserver && (i = i || function () { }, n.$(t).each(function () { var t = this, e = n.$(t); if (!e.data("observer")) try { var o = new n.support.mutationobserver(n.Utils.debounce(function () { i.apply(t, [e]), e.trigger("changed.uk.dom") }, 50), { childList: !0, subtree: !0 }); o.observe(t, { childList: !0, subtree: !0 }), e.data("observer", o) } catch (s) { } })) }, n.init = function (t) { t = t || document, n.domObservers.forEach(function (i) { i(t) }) }, n.on("domready.uk.dom", function () { n.init(), n.domready && n.Utils.checkDisplay() }), document.addEventListener("DOMContentLoaded", function () { var t = function () { n.$body = n.$("body"), n.trigger("beforeready.uk.dom"), n.component.bootComponents(); var t = requestAnimationFrame(function () { var i = { dir: { x: 0, y: 0 }, x: window.pageXOffset, y: window.pageYOffset }, e = function () { var o = window.pageXOffset, s = window.pageYOffset; (i.x != o || i.y != s) && (i.dir.x = o != i.x ? o > i.x ? 1 : -1 : 0, i.dir.y = s != i.y ? s > i.y ? 1 : -1 : 0, i.x = o, i.y = s, n.$doc.trigger("scrolling.uk.document", [{ dir: { x: i.dir.x, y: i.dir.y }, x: o, y: s }])), cancelAnimationFrame(t), t = requestAnimationFrame(e) }; return n.support.touch && n.$html.on("touchmove touchend MSPointerMove MSPointerUp pointermove pointerup", e), (i.x || i.y) && e(), e }()); if (n.trigger("domready.uk.dom"), n.support.touch && navigator.userAgent.match(/(iPad|iPhone|iPod)/g) && n.$win.on("load orientationchange resize", n.Utils.debounce(function () { var t = function () { return i(".uk-height-viewport").css("height", window.innerHeight), t }; return t() }(), 100)), n.trigger("afterready.uk.dom"), n.domready = !0, n.support.mutationobserver) { var e = n.Utils.debounce(function () { requestAnimationFrame(function () { n.init(document.body) }) }, 10); new n.support.mutationobserver(function (t) { var i = !1; t.every(function (t) { if ("childList" != t.type) return !0; for (var e, n = 0; n < t.addedNodes.length; ++n) if (e = t.addedNodes[n], e.outerHTML && -1 !== e.outerHTML.indexOf("data-uk-")) return (i = !0) && !1; return !0 }), i && e() }).observe(document.body, { childList: !0, subtree: !0 }) } }; return ("complete" == document.readyState || "interactive" == document.readyState) && setTimeout(t), t }()), n.$html.addClass(n.support.touch ? "uk-touch" : "uk-notouch"), n.support.touch) { var s, a = !1, r = "uk-hover", l = ".uk-overlay, .uk-overlay-hover, .uk-overlay-toggle, .uk-animation-hover, .uk-has-hover"; n.$html.on("mouseenter touchstart MSPointerDown pointerdown", l, function () { a && i("." + r).removeClass(r), a = i(this).addClass(r) }).on("mouseleave touchend MSPointerUp pointerup", function (t) { s = i(t.target).parents(l), a && a.not(s).removeClass(r) }) } return n }), function (t) { function i(t, i, e, n) { return Math.abs(t - i) >= Math.abs(e - n) ? t - i > 0 ? "Left" : "Right" : e - n > 0 ? "Up" : "Down" } function e() { c = null, d.last && (void 0 !== d.el && d.el.trigger("longTap"), d = {}) } function n() { c && clearTimeout(c), c = null } function o() { a && clearTimeout(a), r && clearTimeout(r), l && clearTimeout(l), c && clearTimeout(c), a = r = l = c = null, d = {} } function s(t) { return t.pointerType == t.MSPOINTER_TYPE_TOUCH && t.isPrimary } if (!t.fn.swipeLeft) { var a, r, l, c, u, d = {}, h = 750; t(function () { var p, f, m, g = 0, v = 0; "MSGesture" in window && (u = new MSGesture, u.target = document.body), t(document).on("MSGestureEnd gestureend", function (t) { var i = t.originalEvent.velocityX > 1 ? "Right" : t.originalEvent.velocityX < -1 ? "Left" : t.originalEvent.velocityY > 1 ? "Down" : t.originalEvent.velocityY < -1 ? "Up" : null; i && void 0 !== d.el && (d.el.trigger("swipe"), d.el.trigger("swipe" + i)) }).on("touchstart MSPointerDown pointerdown", function (i) { ("MSPointerDown" != i.type || s(i.originalEvent)) && (m = "MSPointerDown" == i.type || "pointerdown" == i.type ? i : i.originalEvent.touches[0], p = Date.now(), f = p - (d.last || p), d.el = t("tagName" in m.target ? m.target : m.target.parentNode), a && clearTimeout(a), d.x1 = m.pageX, d.y1 = m.pageY, f > 0 && 250 >= f && (d.isDoubleTap = !0), d.last = p, c = setTimeout(e, h), i.originalEvent && i.originalEvent.pointerId && u && ("MSPointerDown" == i.type || "pointerdown" == i.type || "touchstart" == i.type) && u.addPointer(i.originalEvent.pointerId)) }).on("touchmove MSPointerMove pointermove", function (t) { ("MSPointerMove" != t.type || s(t.originalEvent)) && (m = "MSPointerMove" == t.type || "pointermove" == t.type ? t : t.originalEvent.touches[0], n(), d.x2 = m.pageX, d.y2 = m.pageY, g += Math.abs(d.x1 - d.x2), v += Math.abs(d.y1 - d.y2)) }).on("touchend MSPointerUp pointerup", function (e) { ("MSPointerUp" != e.type || s(e.originalEvent)) && (n(), d.x2 && Math.abs(d.x1 - d.x2) > 30 || d.y2 && Math.abs(d.y1 - d.y2) > 30 ? l = setTimeout(function () { void 0 !== d.el && (d.el.trigger("swipe"), d.el.trigger("swipe" + i(d.x1, d.x2, d.y1, d.y2))), d = {} }, 0) : "last" in d && (isNaN(g) || 30 > g && 30 > v ? r = setTimeout(function () { var i = t.Event("tap"); i.cancelTouch = o, void 0 !== d.el && d.el.trigger(i), d.isDoubleTap ? (void 0 !== d.el && d.el.trigger("doubleTap"), d = {}) : a = setTimeout(function () { a = null, void 0 !== d.el && d.el.trigger("singleTap"), d = {} }, 250) }, 0) : d = {}, g = v = 0)) }).on("touchcancel MSPointerCancel pointercancel", o), t(window).on("scroll", o) }), ["swipe", "swipeLeft", "swipeRight", "swipeUp", "swipeDown", "doubleTap", "tap", "singleTap", "longTap"].forEach(function (i) { t.fn[i] = function (e) { return t(this).on(i, e) } }) } }(jQuery), function (t) { "use strict"; var i = []; t.component("stackMargin", { defaults: { cls: "uk-margin-small-top", rowfirst: !1, observe: !1 }, boot: function () { t.ready(function (i) { t.$("[data-uk-margin]", i).each(function () { var i = t.$(this); i.data("stackMargin") || t.stackMargin(i, t.Utils.options(i.attr("data-uk-margin"))) }) }) }, init: function () { var e = this; t.$win.on("resize orientationchange", function () { var i = function () { e.process() }; return t.$(function () { i(), t.$win.on("load", i) }), t.Utils.debounce(i, 20) }()), this.on("display.uk.check", function () { this.element.is(":visible") && this.process() }.bind(this)), this.options.observe && t.domObserve(this.element, function () { e.element.is(":visible") && e.process() }), i.push(this) }, process: function () { var i = this.element.children(); if (t.Utils.stackMargin(i, this.options), !this.options.rowfirst || !i.length) return this; var e = {}, n = !1; return i.removeClass(this.options.rowfirst).each(function (i, o) { o = t.$(this), "none" != this.style.display && (i = o.offset().left, ((e[i] = e[i] || []) && e[i]).push(this), n = n === !1 ? i : Math.min(n, i)) }), t.$(e[n]).addClass(this.options.rowfirst), this } }), function () { var i = [], e = function (t) { if (t.is(":visible")) { var i = t.parent().width(), e = t.data("width"), n = i / e, o = Math.floor(n * t.data("height")); t.css({ height: e > i ? o : t.data("height") }) } }; t.component("responsiveElement", { defaults: {}, boot: function () { t.ready(function (i) { t.$("iframe.uk-responsive-width, [data-uk-responsive]", i).each(function () { var i, e = t.$(this); e.data("responsiveElement") || (i = t.responsiveElement(e, {})) }) }) }, init: function () { var t = this.element; t.attr("width") && t.attr("height") && (t.data({ width: t.attr("width"), height: t.attr("height") }).on("display.uk.check", function () { e(t) }), e(t), i.push(t)) } }), t.$win.on("resize load", t.Utils.debounce(function () { i.forEach(function (t) { e(t) }) }, 15)) }(), t.Utils.stackMargin = function (i, e) { e = t.$.extend({ cls: "uk-margin-small-top" }, e), i = t.$(i).removeClass(e.cls); var n = !1; i.each(function (i, e, o, s) { s = t.$(this), "none" != s.css("display") && (i = s.offset(), e = s.outerHeight(), o = i.top + e, s.data({ ukMarginPos: o, ukMarginTop: i.top }), (n === !1 || i.top < n.top) && (n = { top: i.top, left: i.left, pos: o })) }).each(function (i) { i = t.$(this), "none" != i.css("display") && i.data("ukMarginTop") > n.top && i.data("ukMarginPos") > n.pos && i.addClass(e.cls) }) }, t.Utils.matchHeights = function (i, e) { i = t.$(i).css("min-height", ""), e = t.$.extend({ row: !0 }, e); var n = function (i) { if (!(i.length < 2)) { var e = 0; i.each(function () { e = Math.max(e, t.$(this).outerHeight()) }).each(function () { var i = t.$(this), n = e - ("border-box" == i.css("box-sizing") ? 0 : i.outerHeight() - i.height()); i.css("min-height", n + "px") }) } }; e.row ? (i.first().width(), setTimeout(function () { var e = !1, o = []; i.each(function () { var i = t.$(this), s = i.offset().top; s != e && o.length && (n(t.$(o)), o = [], s = i.offset().top), o.push(i), e = s }), o.length && n(t.$(o)) }, 0)) : n(i) }, function (i) { t.Utils.inlineSvg = function (e, n) { t.$(e || 'img[src$=".svg"]', n || document).each(function () { var e = t.$(this), n = e.attr("src"); if (!i[n]) { var o = t.$.Deferred(); t.$.get(n, { nc: Math.random() }, function (i) { o.resolve(t.$(i).find("svg")) }), i[n] = o.promise() } i[n].then(function (i) { var n = t.$(i).clone(); e.attr("id") && n.attr("id", e.attr("id")), e.attr("class") && n.attr("class", e.attr("class")), e.attr("style") && n.attr("style", e.attr("style")), e.attr("width") && (n.attr("width", e.attr("width")), e.attr("height") || n.removeAttr("height")), e.attr("height") && (n.attr("height", e.attr("height")), e.attr("width") || n.removeAttr("width")), e.replaceWith(n) }) }) }, t.ready(function (i) { t.Utils.inlineSvg("[data-uk-svg]", i) }) }({}), t.Utils.getCssVar = function (t) { var i, e = document.documentElement, n = e.appendChild(document.createElement("div")); n.classList.add("var-" + t); try { i = JSON.parse(i = getComputedStyle(n, ":before").content.replace(/^["'](.*)["']$/, "$1")) } catch (o) { i = void 0 } return e.removeChild(n), i } }(UIkit), function (t) { "use strict"; function i(i, e) { e = t.$.extend({ duration: 1e3, transition: "easeOutExpo", offset: 0, complete: function () { } }, e); var n = i.offset().top - e.offset, o = t.$doc.height(), s = window.innerHeight; n + s > o && (n = o - s), t.$("html,body").stop().animate({ scrollTop: n }, e.duration, e.transition).promise().done(e.complete) } t.component("smoothScroll", { boot: function () { t.$html.on("click.smooth-scroll.uikit", "[data-uk-smooth-scroll]", function () { var i = t.$(this); if (!i.data("smoothScroll")) { { t.smoothScroll(i, t.Utils.options(i.attr("data-uk-smooth-scroll"))) } i.trigger("click") } return !1 }) }, init: function () { var e = this; this.on("click", function (n) { n.preventDefault(), i(t.$(this.hash).length ? t.$(this.hash) : t.$("body"), e.options) }) } }), t.Utils.scrollToElement = i, t.$.easing.easeOutExpo || (t.$.easing.easeOutExpo = function (t, i, e, n, o) { return i == o ? e + n : n * (-Math.pow(2, -10 * i / o) + 1) + e }) }(UIkit), function (t) { "use strict"; var i = t.$win, e = t.$doc, n = [], o = function () { for (var t = 0; t < n.length; t++) window.requestAnimationFrame.apply(window, [n[t].check]) }; t.component("scrollspy", { defaults: { target: !1, cls: "uk-scrollspy-inview", initcls: "uk-scrollspy-init-inview", topoffset: 0, leftoffset: 0, repeat: !1, delay: 0 }, boot: function () { e.on("scrolling.uk.document", o), i.on("load resize orientationchange", t.Utils.debounce(o, 50)), t.ready(function (i) { t.$("[data-uk-scrollspy]", i).each(function () { var i = t.$(this); if (!i.data("scrollspy")) { t.scrollspy(i, t.Utils.options(i.attr("data-uk-scrollspy"))) } }) }) }, init: function () { var i, e = this, o = this.options.cls.split(/,/), s = function () { var n = e.options.target ? e.element.find(e.options.target) : e.element, s = 1 === n.length ? 1 : 0, a = 0; n.each(function () { var n = t.$(this), r = n.data("inviewstate"), l = t.Utils.isInView(n, e.options), c = n.data("ukScrollspyCls") || o[a].trim(); !l || r || n.data("scrollspy-idle") || (i || (n.addClass(e.options.initcls), e.offset = n.offset(), i = !0, n.trigger("init.uk.scrollspy")), n.data("scrollspy-idle", setTimeout(function () { n.addClass("uk-scrollspy-inview").toggleClass(c).width(), n.trigger("inview.uk.scrollspy"), n.data("scrollspy-idle", !1), n.data("inviewstate", !0) }, e.options.delay * s)), s++), !l && r && e.options.repeat && (n.data("scrollspy-idle") && (clearTimeout(n.data("scrollspy-idle")), n.data("scrollspy-idle", !1)), n.removeClass("uk-scrollspy-inview").toggleClass(c), n.data("inviewstate", !1), n.trigger("outview.uk.scrollspy")), a = o[a + 1] ? a + 1 : 0 }) }; s(), this.check = s, n.push(this) } }); var s = [], a = function () { for (var t = 0; t < s.length; t++) window.requestAnimationFrame.apply(window, [s[t].check]) }; t.component("scrollspynav", { defaults: { cls: "uk-active", closest: !1, topoffset: 0, leftoffset: 0, smoothscroll: !1 }, boot: function () { e.on("scrolling.uk.document", a), i.on("resize orientationchange", t.Utils.debounce(a, 50)), t.ready(function (i) { t.$("[data-uk-scrollspy-nav]", i).each(function () { var i = t.$(this); if (!i.data("scrollspynav")) { t.scrollspynav(i, t.Utils.options(i.attr("data-uk-scrollspy-nav"))) } }) }) }, init: function () { var e, n = [], o = this.find("a[href^='#']").each(function () { "#" !== this.getAttribute("href").trim() && n.push(this.getAttribute("href")) }), a = t.$(n.join(",")), r = this.options.cls, l = this.options.closest || this.options.closest, c = this, u = function () { e = []; for (var n = 0; n < a.length; n++) t.Utils.isInView(a.eq(n), c.options) && e.push(a.eq(n)); if (e.length) { var s, u = i.scrollTop(), d = function () { for (var t = 0; t < e.length; t++) if (e[t].offset().top - c.options.topoffset >= u) return e[t] }(); if (!d) return; c.options.closest ? (o.blur().closest(l).removeClass(r), s = o.filter("a[href='#" + d.attr("id") + "']").closest(l).addClass(r)) : s = o.removeClass(r).filter("a[href='#" + d.attr("id") + "']").addClass(r), c.element.trigger("inview.uk.scrollspynav", [d, s]) } }; this.options.smoothscroll && t.smoothScroll && o.each(function () { t.smoothScroll(this, c.options.smoothscroll) }), u(), this.element.data("scrollspynav", this), this.check = u, s.push(this) } }) }(UIkit), function (t) { "use strict"; var i = []; t.component("toggle", { defaults: { target: !1, cls: "uk-hidden", animation: !1, duration: 200 }, boot: function () { t.ready(function (e) { t.$("[data-uk-toggle]", e).each(function () { var i = t.$(this); if (!i.data("toggle")) { t.toggle(i, t.Utils.options(i.attr("data-uk-toggle"))) } }), setTimeout(function () { i.forEach(function (t) { t.getToggles() }) }, 0) }) }, init: function () { var t = this; this.aria = -1 !== this.options.cls.indexOf("uk-hidden"), this.on("click", function (i) { t.element.is('a[href="#"]') && i.preventDefault(), t.toggle() }), i.push(this) }, toggle: function () { if (this.getToggles(), this.totoggle.length) { if (this.options.animation && t.support.animation) { var i = this, e = this.options.animation.split(","); 1 == e.length && (e[1] = e[0]), e[0] = e[0].trim(), e[1] = e[1].trim(), this.totoggle.css("animation-duration", this.options.duration + "ms"), this.totoggle.each(function () { var n = t.$(this); n.hasClass(i.options.cls) ? (n.toggleClass(i.options.cls), t.Utils.animate(n, e[0]).then(function () { n.css("animation-duration", ""), t.Utils.checkDisplay(n) })) : t.Utils.animate(this, e[1] + " uk-animation-reverse").then(function () { n.toggleClass(i.options.cls).css("animation-duration", ""), t.Utils.checkDisplay(n) }) }) } else this.totoggle.toggleClass(this.options.cls), t.Utils.checkDisplay(this.totoggle); this.updateAria() } }, getToggles: function () { this.totoggle = this.options.target ? t.$(this.options.target) : [], this.updateAria() }, updateAria: function () { this.aria && this.totoggle.length && this.totoggle.not("[aria-hidden]").each(function () { t.$(this).attr("aria-hidden", t.$(this).hasClass("uk-hidden")) }) } }) }(UIkit), function (t) { "use strict"; t.component("alert", { defaults: { fade: !0, duration: 200, trigger: ".uk-alert-close" }, boot: function () { t.$html.on("click.alert.uikit", "[data-uk-alert]", function (i) { var e = t.$(this); if (!e.data("alert")) { var n = t.alert(e, t.Utils.options(e.attr("data-uk-alert"))); t.$(i.target).is(n.options.trigger) && (i.preventDefault(), n.close()) } }) }, init: function () { var t = this; this.on("click", this.options.trigger, function (i) { i.preventDefault(), t.close() }) }, close: function () { var t = this.trigger("close.uk.alert"), i = function () { this.trigger("closed.uk.alert").remove() }.bind(this); this.options.fade ? t.css("overflow", "hidden").css("max-height", t.height()).animate({ height: 0, opacity: 0, paddingTop: 0, paddingBottom: 0, marginTop: 0, marginBottom: 0 }, this.options.duration, i) : i() } }) }(UIkit), function (t) { "use strict"; t.component("buttonRadio", { defaults: { activeClass: "uk-active", target: ".uk-button" }, boot: function () { t.$html.on("click.buttonradio.uikit", "[data-uk-button-radio]", function (i) { var e = t.$(this); if (!e.data("buttonRadio")) { var n = t.buttonRadio(e, t.Utils.options(e.attr("data-uk-button-radio"))), o = t.$(i.target); o.is(n.options.target) && o.trigger("click") } }) }, init: function () { var i = this; this.find(i.options.target).attr("aria-checked", "false").filter("." + i.options.activeClass).attr("aria-checked", "true"), this.on("click", this.options.target, function (e) { var n = t.$(this); n.is('a[href="#"]') && e.preventDefault(), i.find(i.options.target).not(n).removeClass(i.options.activeClass).blur(), n.addClass(i.options.activeClass), i.find(i.options.target).not(n).attr("aria-checked", "false"), n.attr("aria-checked", "true"), i.trigger("change.uk.button", [n]) }) }, getSelected: function () { return this.find("." + this.options.activeClass) } }), t.component("buttonCheckbox", { defaults: { activeClass: "uk-active", target: ".uk-button" }, boot: function () { t.$html.on("click.buttoncheckbox.uikit", "[data-uk-button-checkbox]", function (i) { var e = t.$(this); if (!e.data("buttonCheckbox")) { var n = t.buttonCheckbox(e, t.Utils.options(e.attr("data-uk-button-checkbox"))), o = t.$(i.target); o.is(n.options.target) && o.trigger("click") } }) }, init: function () { var i = this; this.find(i.options.target).attr("aria-checked", "false").filter("." + i.options.activeClass).attr("aria-checked", "true"), this.on("click", this.options.target, function (e) { var n = t.$(this); n.is('a[href="#"]') && e.preventDefault(), n.toggleClass(i.options.activeClass).blur(), n.attr("aria-checked", n.hasClass(i.options.activeClass)), i.trigger("change.uk.button", [n]) }) }, getSelected: function () { return this.find("." + this.options.activeClass) } }), t.component("button", { defaults: {}, boot: function () { t.$html.on("click.button.uikit", "[data-uk-button]", function () { var i = t.$(this); if (!i.data("button")) { { t.button(i, t.Utils.options(i.attr("data-uk-button"))) } i.trigger("click") } }) }, init: function () { var t = this; this.element.attr("aria-pressed", this.element.hasClass("uk-active")), this.on("click", function (i) { t.element.is('a[href="#"]') && i.preventDefault(), t.toggle(), t.trigger("change.uk.button", [t.element.blur().hasClass("uk-active")]) }) }, toggle: function () { this.element.toggleClass("uk-active"), this.element.attr("aria-pressed", this.element.hasClass("uk-active")) } }) }(UIkit), function (t) {
    "use strict"; function i(i, e, n, o) { if (i = t.$(i), e = t.$(e), n = n || window.innerWidth, o = o || i.offset(), e.length) { var s = e.outerWidth(); if (i.css("min-width", s), "right" == t.langdirection) { var a = n - (e.offset().left + s), r = n - (i.offset().left + i.outerWidth()); i.css("margin-right", a - r) } else i.css("margin-left", e.offset().left - o.left) } } var e, n = !1, o = { x: { "bottom-left": "bottom-right", "bottom-right": "bottom-left", "bottom-center": "bottom-center", "top-left": "top-right", "top-right": "top-left", "top-center": "top-center", "left-top": "right-top", "left-bottom": "right-bottom", "left-center": "right-center", "right-top": "left-top", "right-bottom": "left-bottom", "right-center": "left-center" }, y: { "bottom-left": "top-left", "bottom-right": "top-right", "bottom-center": "top-center", "top-left": "bottom-left", "top-right": "bottom-right", "top-center": "bottom-center", "left-top": "left-bottom", "left-bottom": "left-top", "left-center": "left-center", "right-top": "right-bottom", "right-bottom": "right-top", "right-center": "right-center" }, xy: { "bottom-left": "top-right", "bottom-right": "top-left", "bottom-center": "top-center", "top-left": "bottom-right", "top-right": "bottom-left", "top-center": "bottom-center", "left-top": "right-bottom", "left-bottom": "right-top", "left-center": "right-center", "right-top": "left-bottom", "right-bottom": "left-top", "right-center": "left-center" } }; t.component("dropdown", {
        defaults: { mode: "hover", pos: "bottom-left", offset: 0, remaintime: 800, justify: !1, boundary: t.$win, delay: 0, dropdownSelector: ".uk-dropdown,.uk-dropdown-blank", hoverDelayIdle: 250, preventflip: !1 }, remainIdle: !1, boot: function () { var i = t.support.touch ? "click" : "mouseenter"; t.$html.on(i + ".dropdown.uikit focus pointerdown", "[data-uk-dropdown]", function (e) { var n = t.$(this); if (!n.data("dropdown")) { var o = t.dropdown(n, t.Utils.options(n.attr("data-uk-dropdown"))); ("click" == e.type || "mouseenter" == e.type && "hover" == o.options.mode) && o.element.trigger(i), o.dropdown.length && e.preventDefault() } }) }, init: function () { var i = this; this.dropdown = this.find(this.options.dropdownSelector), this.offsetParent = this.dropdown.parents().filter(function () { return -1 !== t.$.inArray(t.$(this).css("position"), ["relative", "fixed", "absolute"]) }).slice(0, 1), this.offsetParent.length || (this.offsetParent = this.element), this.centered = this.dropdown.hasClass("uk-dropdown-center"), this.justified = this.options.justify ? t.$(this.options.justify) : !1, this.boundary = t.$(this.options.boundary), this.boundary.length || (this.boundary = t.$win), this.dropdown.hasClass("uk-dropdown-up") && (this.options.pos = "top-left"), this.dropdown.hasClass("uk-dropdown-flip") && (this.options.pos = this.options.pos.replace("left", "right")), this.dropdown.hasClass("uk-dropdown-center") && (this.options.pos = this.options.pos.replace(/(left|right)/, "center")), this.element.attr("aria-haspopup", "true"), this.element.attr("aria-expanded", this.element.hasClass("uk-open")), this.dropdown.attr("aria-hidden", "true"), "click" == this.options.mode || t.support.touch ? this.on("click.uk.dropdown", function (e) { var n = t.$(e.target); n.parents(i.options.dropdownSelector).length || ((n.is("a[href='#']") || n.parent().is("a[href='#']") || i.dropdown.length && !i.dropdown.is(":visible")) && e.preventDefault(), n.blur()), i.element.hasClass("uk-open") ? (!i.dropdown.find(e.target).length || n.is(".uk-dropdown-close") || n.parents(".uk-dropdown-close").length) && i.hide() : i.show() }) : this.on("mouseenter", function () { i.trigger("pointerenter.uk.dropdown", [i]), i.remainIdle && clearTimeout(i.remainIdle), e && clearTimeout(e), n && n == i || (e = n && n != i ? setTimeout(function () { e = setTimeout(i.show.bind(i), i.options.delay) }, i.options.hoverDelayIdle) : setTimeout(i.show.bind(i), i.options.delay)) }).on("mouseleave", function () { e && clearTimeout(e), i.remainIdle = setTimeout(function () { n && n == i && i.hide() }, i.options.remaintime), i.trigger("pointerleave.uk.dropdown", [i]) }).on("click", function (e) { var o = t.$(e.target); return i.remainIdle && clearTimeout(i.remainIdle), n && n == i ? ((!i.dropdown.find(e.target).length || o.is(".uk-dropdown-close") || o.parents(".uk-dropdown-close").length) && i.hide(), void 0) : ((o.is("a[href='#']") || o.parent().is("a[href='#']")) && e.preventDefault(), i.show(), void 0) }) }, show: function () { t.$html.off("click.outer.dropdown"), n && n != this && n.hide(!0), e && clearTimeout(e), this.trigger("beforeshow.uk.dropdown", [this]), this.checkDimensions(), this.element.addClass("uk-open"), this.element.attr("aria-expanded", "true"), this.dropdown.attr("aria-hidden", "false"), this.trigger("show.uk.dropdown", [this]), t.Utils.checkDisplay(this.dropdown, !0), t.Utils.focus(this.dropdown), n = this, this.registerOuterClick() }, hide: function (t) { this.trigger("beforehide.uk.dropdown", [this, t]), this.element.removeClass("uk-open"), this.remainIdle && clearTimeout(this.remainIdle), this.remainIdle = !1, this.element.attr("aria-expanded", "false"), this.dropdown.attr("aria-hidden", "true"), this.trigger("hide.uk.dropdown", [this, t]), n == this && (n = !1) }, registerOuterClick: function () { var i = this; t.$html.off("click.outer.dropdown"), setTimeout(function () { t.$html.on("click.outer.dropdown", function (o) { e && clearTimeout(e); t.$(o.target); n != i || i.element.find(o.target).length || (i.hide(!0), t.$html.off("click.outer.dropdown")) }) }, 10) }, checkDimensions: function () {
            if (this.dropdown.length) {
                this.dropdown.removeClass("uk-dropdown-top uk-dropdown-bottom uk-dropdown-left uk-dropdown-right uk-dropdown-stack uk-dropdown-autoflip").css({ topLeft: "", left: "", marginLeft: "", marginRight: "" }), this.justified && this.justified.length && this.dropdown.css("min-width", ""); var e, n = t.$.extend({}, this.offsetParent.offset(), { width: this.offsetParent[0].offsetWidth, height: this.offsetParent[0].offsetHeight }), s = this.options.offset, a = this.dropdown, r = (a.show().offset() || { left: 0, top: 0 }, a.outerWidth()), l = a.outerHeight(), c = this.boundary.width(), u = (this.boundary[0] !== window && this.boundary.offset() ? this.boundary.offset() : { top: 0, left: 0 }, this.options.pos), d = { "bottom-left": { top: 0 + n.height + s, left: 0 }, "bottom-right": { top: 0 + n.height + s, left: 0 + n.width - r }, "bottom-center": { top: 0 + n.height + s, left: 0 + n.width / 2 - r / 2 }, "top-left": { top: 0 - l - s, left: 0 }, "top-right": { top: 0 - l - s, left: 0 + n.width - r }, "top-center": { top: 0 - l - s, left: 0 + n.width / 2 - r / 2 }, "left-top": { top: 0, left: 0 - r - s }, "left-bottom": { top: 0 + n.height - l, left: 0 - r - s }, "left-center": { top: 0 + n.height / 2 - l / 2, left: 0 - r - s }, "right-top": { top: 0, left: 0 + n.width + s }, "right-bottom": { top: 0 + n.height - l, left: 0 + n.width + s }, "right-center": { top: 0 + n.height / 2 - l / 2, left: 0 + n.width + s } }, h = {};
                if (e = u.split("-"), h = d[u] ? d[u] : d["bottom-left"], this.justified && this.justified.length) i(a.css({ left: 0 }), this.justified, c); else if (this.options.preventflip !== !0) { var p; switch (this.checkBoundary(n.left + h.left, n.top + h.top, r, l, c)) { case "x": "x" !== this.options.preventflip && (p = o.x[u] || "right-top"); break; case "y": "y" !== this.options.preventflip && (p = o.y[u] || "top-left"); break; case "xy": this.options.preventflip || (p = o.xy[u] || "right-bottom") } p && (e = p.split("-"), h = d[p] ? d[p] : d["bottom-left"], a.addClass("uk-dropdown-autoflip"), this.checkBoundary(n.left + h.left, n.top + h.top, r, l, c) && (e = u.split("-"), h = d[u] ? d[u] : d["bottom-left"])) } r > c && (a.addClass("uk-dropdown-stack"), this.trigger("stack.uk.dropdown", [this])), a.css(h).css("display", "").addClass("uk-dropdown-" + e[0])
            }
        }, checkBoundary: function (i, e, n, o, s) { var a = ""; return (0 > i || i - t.$win.scrollLeft() + n > s) && (a += "x"), (e - t.$win.scrollTop() < 0 || e - t.$win.scrollTop() + o > window.innerHeight) && (a += "y"), a }
    }), t.component("dropdownOverlay", { defaults: { justify: !1, cls: "", duration: 200 }, boot: function () { t.ready(function (i) { t.$("[data-uk-dropdown-overlay]", i).each(function () { var i = t.$(this); i.data("dropdownOverlay") || t.dropdownOverlay(i, t.Utils.options(i.attr("data-uk-dropdown-overlay"))) }) }) }, init: function () { var e = this; this.justified = this.options.justify ? t.$(this.options.justify) : !1, this.overlay = this.element.find("uk-dropdown-overlay"), this.overlay.length || (this.overlay = t.$('<div class="uk-dropdown-overlay"></div>').appendTo(this.element)), this.overlay.addClass(this.options.cls), this.on({ "beforeshow.uk.dropdown": function (t, n) { e.dropdown = n, e.justified && e.justified.length && i(e.overlay.css({ display: "block", marginLeft: "", marginRight: "" }), e.justified, e.justified.outerWidth()) }, "show.uk.dropdown": function () { var i = e.dropdown.dropdown.outerHeight(!0); e.dropdown.element.removeClass("uk-open"), e.overlay.stop().css("display", "block").animate({ height: i }, e.options.duration, function () { e.dropdown.dropdown.css("visibility", ""), e.dropdown.element.addClass("uk-open"), t.Utils.checkDisplay(e.dropdown.dropdown, !0) }), e.pointerleave = !1 }, "hide.uk.dropdown": function () { e.overlay.stop().animate({ height: 0 }, e.options.duration) }, "pointerenter.uk.dropdown": function () { clearTimeout(e.remainIdle) }, "pointerleave.uk.dropdown": function () { e.pointerleave = !0 } }), this.overlay.on({ mouseenter: function () { e.remainIdle && (clearTimeout(e.dropdown.remainIdle), clearTimeout(e.remainIdle)) }, mouseleave: function () { e.pointerleave && n && (e.remainIdle = setTimeout(function () { n && n.hide() }, n.options.remaintime)) } }) } })
}(UIkit), function (t) { "use strict"; var i = []; t.component("gridMatchHeight", { defaults: { target: !1, row: !0, ignorestacked: !1, observe: !1 }, boot: function () { t.ready(function (i) { t.$("[data-uk-grid-match]", i).each(function () { var i, e = t.$(this); e.data("gridMatchHeight") || (i = t.gridMatchHeight(e, t.Utils.options(e.attr("data-uk-grid-match")))) }) }) }, init: function () { var e = this; this.columns = this.element.children(), this.elements = this.options.target ? this.find(this.options.target) : this.columns, this.columns.length && (t.$win.on("load resize orientationchange", function () { var i = function () { e.element.is(":visible") && e.match() }; return t.$(function () { i() }), t.Utils.debounce(i, 50) }()), this.options.observe && t.domObserve(this.element, function () { e.element.is(":visible") && e.match() }), this.on("display.uk.check", function () { this.element.is(":visible") && this.match() }.bind(this)), i.push(this)) }, match: function () { var i = this.columns.filter(":visible:first"); if (i.length) { var e = Math.ceil(100 * parseFloat(i.css("width")) / parseFloat(i.parent().css("width"))) >= 100; return e && !this.options.ignorestacked ? this.revert() : t.Utils.matchHeights(this.elements, this.options), this } }, revert: function () { return this.elements.css("min-height", ""), this } }), t.component("gridMargin", { defaults: { cls: "uk-grid-margin", rowfirst: "uk-row-first" }, boot: function () { t.ready(function (i) { t.$("[data-uk-grid-margin]", i).each(function () { var i, e = t.$(this); e.data("gridMargin") || (i = t.gridMargin(e, t.Utils.options(e.attr("data-uk-grid-margin")))) }) }) }, init: function () { t.stackMargin(this.element, this.options) } }) }(UIkit), function (t) { "use strict"; function i(i, e) { return e ? ("object" == typeof i ? (i = i instanceof jQuery ? i : t.$(i), i.parent().length && (e.persist = i, e.persist.data("modalPersistParent", i.parent()))) : i = "string" == typeof i || "number" == typeof i ? t.$("<div></div>").html(i) : t.$("<div></div>").html("UIkit.modal Error: Unsupported data type: " + typeof i), i.appendTo(e.element.find(".uk-modal-dialog")), e) : void 0 } var e, n = !1, o = 0, s = t.$html; t.$win.on("resize orientationchange", t.Utils.debounce(function () { t.$(".uk-modal.uk-open").each(function () { return t.$(this).data("modal") && t.$(this).data("modal").resize() }) }, 150)), t.component("modal", { defaults: { keyboard: !0, bgclose: !0, minScrollHeight: 150, center: !1, modal: !0 }, scrollable: !1, transition: !1, hasTransitioned: !0, init: function () { if (e || (e = t.$("body")), this.element.length) { var i = this; this.paddingdir = "padding-" + ("left" == t.langdirection ? "right" : "left"), this.dialog = this.find(".uk-modal-dialog"), this.active = !1, this.element.attr("aria-hidden", this.element.hasClass("uk-open")), this.on("click", ".uk-modal-close", function (t) { t.preventDefault(), i.hide() }).on("click", function (e) { var n = t.$(e.target); n[0] == i.element[0] && i.options.bgclose && i.hide() }), t.domObserve(this.element, function () { i.resize() }) } }, toggle: function () { return this[this.isActive() ? "hide" : "show"]() }, show: function () { if (this.element.length) { var i = this; if (!this.isActive()) return this.options.modal && n && n.hide(!0), this.element.removeClass("uk-open").show(), this.resize(!0), this.options.modal && (n = this), this.active = !0, o++, t.support.transition ? (this.hasTransitioned = !1, this.element.one(t.support.transition.end, function () { i.hasTransitioned = !0, t.Utils.focus(i.dialog, "a[href]") }).addClass("uk-open")) : (this.element.addClass("uk-open"), t.Utils.focus(this.dialog, "a[href]")), s.addClass("uk-modal-page").height(), this.element.attr("aria-hidden", "false"), this.element.trigger("show.uk.modal"), t.Utils.checkDisplay(this.dialog, !0), this } }, hide: function (i) { if (!i && t.support.transition && this.hasTransitioned) { var e = this; this.one(t.support.transition.end, function () { e._hide() }).removeClass("uk-open") } else this._hide(); return this }, resize: function (t) { if (this.isActive() || t) { var i = e.width(); if (this.scrollbarwidth = window.innerWidth - i, e.css(this.paddingdir, this.scrollbarwidth), this.element.css("overflow-y", this.scrollbarwidth ? "scroll" : "auto"), !this.updateScrollable() && this.options.center) { var n = this.dialog.outerHeight(), o = parseInt(this.dialog.css("margin-top"), 10) + parseInt(this.dialog.css("margin-bottom"), 10); n + o < window.innerHeight ? this.dialog.css({ top: window.innerHeight / 2 - n / 2 - o }) : this.dialog.css({ top: "" }) } } }, updateScrollable: function () { var t = this.dialog.find(".uk-overflow-container:visible:first"); if (t.length) { t.css("height", 0); var i = Math.abs(parseInt(this.dialog.css("margin-top"), 10)), e = this.dialog.outerHeight(), n = window.innerHeight, o = n - 2 * (20 > i ? 20 : i) - e; return t.css({ maxHeight: o < this.options.minScrollHeight ? "" : o, height: "" }), !0 } return !1 }, _hide: function () { this.active = !1, o > 0 ? o-- : o = 0, this.element.hide().removeClass("uk-open"), this.element.attr("aria-hidden", "true"), o || (s.removeClass("uk-modal-page"), e.css(this.paddingdir, "")), n === this && (n = !1), this.trigger("hide.uk.modal") }, isActive: function () { return this.element.hasClass("uk-open") } }), t.component("modalTrigger", { boot: function () { t.$html.on("click.modal.uikit", "[data-uk-modal]", function (i) { var e = t.$(this); if (e.is("a") && i.preventDefault(), !e.data("modalTrigger")) { var n = t.modalTrigger(e, t.Utils.options(e.attr("data-uk-modal"))); n.show() } }), t.$html.on("keydown.modal.uikit", function (t) { n && 27 === t.keyCode && n.options.keyboard && (t.preventDefault(), n.hide()) }) }, init: function () { var i = this; this.options = t.$.extend({ target: i.element.is("a") ? i.element.attr("href") : !1 }, this.options), this.modal = t.modal(this.options.target, this.options), this.on("click", function (t) { t.preventDefault(), i.show() }), this.proxy(this.modal, "show hide isActive") } }), t.modal.dialog = function (e, n) { var o = t.modal(t.$(t.modal.dialog.template).appendTo("body"), n); return o.on("hide.uk.modal", function () { o.persist && (o.persist.appendTo(o.persist.data("modalPersistParent")), o.persist = !1), o.element.remove() }), i(e, o), o }, t.modal.dialog.template = '<div class="uk-modal"><div class="uk-modal-dialog" style="min-height:0;"></div></div>', t.modal.alert = function (i, e) { e = t.$.extend(!0, { bgclose: !1, keyboard: !1, modal: !1, labels: t.modal.labels }, e); var n = t.modal.dialog(['<div class="uk-margin uk-modal-content">' + String(i) + "</div>", '<div class="uk-modal-footer uk-text-right"><button class="uk-button uk-button-primary uk-modal-close">' + e.labels.Ok + "</button></div>"].join(""), e); return n.on("show.uk.modal", function () { setTimeout(function () { n.element.find("button:first").focus() }, 50) }), n.show() }, t.modal.confirm = function (i, e, n) { var o = arguments.length > 1 && arguments[arguments.length - 1] ? arguments[arguments.length - 1] : {}; e = t.$.isFunction(e) ? e : function () { }, n = t.$.isFunction(n) ? n : function () { }, o = t.$.extend(!0, { bgclose: !1, keyboard: !1, modal: !1, labels: t.modal.labels }, t.$.isFunction(o) ? {} : o); var s = t.modal.dialog(['<div class="uk-margin uk-modal-content">' + String(i) + "</div>", '<div class="uk-modal-footer uk-text-right"><button class="uk-button js-modal-confirm-cancel">' + o.labels.Cancel + '</button> <button class="uk-button uk-button-primary js-modal-confirm">' + o.labels.Ok + "</button></div>"].join(""), o); return s.element.find(".js-modal-confirm, .js-modal-confirm-cancel").on("click", function () { t.$(this).is(".js-modal-confirm") ? e() : n(), s.hide() }), s.on("show.uk.modal", function () { setTimeout(function () { s.element.find(".js-modal-confirm").focus() }, 50) }), s.show() }, t.modal.prompt = function (i, e, n, o) { n = t.$.isFunction(n) ? n : function () { }, o = t.$.extend(!0, { bgclose: !1, keyboard: !1, modal: !1, labels: t.modal.labels }, o); var s = t.modal.dialog([i ? '<div class="uk-modal-content uk-form">' + String(i) + "</div>" : "", '<div class="uk-margin-small-top uk-modal-content uk-form"><p><input type="text" class="uk-width-1-1"></p></div>', '<div class="uk-modal-footer uk-text-right"><button class="uk-button uk-modal-close">' + o.labels.Cancel + '</button> <button class="uk-button uk-button-primary js-modal-ok">' + o.labels.Ok + "</button></div>"].join(""), o), a = s.element.find("input[type='text']").val(e || "").on("keyup", function (t) { 13 == t.keyCode && s.element.find(".js-modal-ok").trigger("click") }); return s.element.find(".js-modal-ok").on("click", function () { n(a.val()) !== !1 && s.hide() }), s.show() }, t.modal.blockUI = function (i, e) { var n = t.modal.dialog(['<div class="uk-margin uk-modal-content">' + String(i || '<div class="uk-text-center">...</div>') + "</div>"].join(""), t.$.extend({ bgclose: !1, keyboard: !1, modal: !1 }, e)); return n.content = n.element.find(".uk-modal-content:first"), n.show() }, t.modal.labels = { Ok: "Ok", Cancel: "Cancel" } }(UIkit), function (t) { "use strict"; function i(i) { var e = t.$(i), n = "auto"; if (e.is(":visible")) n = e.outerHeight(); else { var o = { position: e.css("position"), visibility: e.css("visibility"), display: e.css("display") }; n = e.css({ position: "absolute", visibility: "hidden", display: "block" }).outerHeight(), e.css(o) } return n } t.component("nav", { defaults: { toggle: '>li.uk-parent > a[href="#"]', lists: ">li.uk-parent > ul", multiple: !1 }, boot: function () { t.ready(function (i) { t.$("[data-uk-nav]", i).each(function () { var i = t.$(this); if (!i.data("nav")) { t.nav(i, t.Utils.options(i.attr("data-uk-nav"))) } }) }) }, init: function () { var i = this; this.on("click.uk.nav", this.options.toggle, function (e) { e.preventDefault(); var n = t.$(this); i.open(n.parent()[0] == i.element[0] ? n : n.parent("li")) }), this.update(), t.domObserve(this.element, function () { i.element.find(i.options.lists).not("[role]").length && i.update() }) }, update: function () { var i = this; this.find(this.options.lists).each(function () { var e = t.$(this).attr("role", "menu"), n = e.closest("li"), o = n.hasClass("uk-active"); n.data("list-container") || (e.wrap('<div style="overflow:hidden;height:0;position:relative;"></div>'), n.data("list-container", e.parent()[o ? "removeClass" : "addClass"]("uk-hidden"))), n.attr("aria-expanded", n.hasClass("uk-open")), o && i.open(n, !0) }) }, open: function (e, n) { var o = this, s = this.element, a = t.$(e), r = a.data("list-container"); this.options.multiple || s.children(".uk-open").not(e).each(function () { var i = t.$(this); i.data("list-container") && i.data("list-container").stop().animate({ height: 0 }, function () { t.$(this).parent().removeClass("uk-open").end().addClass("uk-hidden") }) }), a.toggleClass("uk-open"), a.attr("aria-expanded", a.hasClass("uk-open")), r && (a.hasClass("uk-open") && r.removeClass("uk-hidden"), n ? (r.stop().height(a.hasClass("uk-open") ? "auto" : 0), a.hasClass("uk-open") || r.addClass("uk-hidden"), this.trigger("display.uk.check")) : r.stop().animate({ height: a.hasClass("uk-open") ? i(r.find("ul:first")) : 0 }, function () { a.hasClass("uk-open") ? r.css("height", "") : r.addClass("uk-hidden"), o.trigger("display.uk.check") })) } }) }(UIkit), function (t) { "use strict"; var i = { x: window.scrollX, y: window.scrollY }, e = (t.$win, t.$doc, t.$html), n = { show: function (n, o) { if (n = t.$(n), n.length) { o = t.$.extend({ mode: "push" }, o); var s = t.$("body"), a = n.find(".uk-offcanvas-bar:first"), r = "right" == t.langdirection, l = a.hasClass("uk-offcanvas-bar-flip") ? -1 : 1, c = l * (r ? -1 : 1), u = window.innerWidth - s.width(); i = { x: window.pageXOffset, y: window.pageYOffset }, a.attr("mode", o.mode), n.addClass("uk-active"), s.css({ width: window.innerWidth - u, height: window.innerHeight }).addClass("uk-offcanvas-page"), ("push" == o.mode || "reveal" == o.mode) && s.css(r ? "margin-right" : "margin-left", (r ? -1 : 1) * a.outerWidth() * c), "reveal" == o.mode && a.css("clip", "rect(0, " + a.outerWidth() + "px, 100vh, 0)"), e.css("margin-top", -1 * i.y).width(), a.addClass("uk-offcanvas-bar-show"), this._initElement(n), a.trigger("show.uk.offcanvas", [n, a]), n.attr("aria-hidden", "false") } }, hide: function (n) { var o = t.$("body"), s = t.$(".uk-offcanvas.uk-active"), a = "right" == t.langdirection, r = s.find(".uk-offcanvas-bar:first"), l = function () { o.removeClass("uk-offcanvas-page").css({ width: "", height: "", marginLeft: "", marginRight: "" }), s.removeClass("uk-active"), r.removeClass("uk-offcanvas-bar-show"), e.css("margin-top", ""), window.scrollTo(i.x, i.y), r.trigger("hide.uk.offcanvas", [s, r]), s.attr("aria-hidden", "true") }; s.length && ("none" == r.attr("mode") && (n = !0), t.support.transition && !n ? (o.one(t.support.transition.end, function () { l() }).css(a ? "margin-right" : "margin-left", ""), "reveal" == r.attr("mode") && r.css("clip", ""), setTimeout(function () { r.removeClass("uk-offcanvas-bar-show") }, 0)) : l()) }, _initElement: function (i) { i.data("OffcanvasInit") || (i.on("click.uk.offcanvas swipeRight.uk.offcanvas swipeLeft.uk.offcanvas", function (i) { var e = t.$(i.target); if (!i.type.match(/swipe/) && !e.hasClass("uk-offcanvas-close")) { if (e.hasClass("uk-offcanvas-bar")) return; if (e.parents(".uk-offcanvas-bar:first").length) return } i.stopImmediatePropagation(), n.hide() }), i.on("click", 'a[href*="#"]', function () { var i = t.$(this), e = i.attr("href"); "#" != e && (t.$doc.one("hide.uk.offcanvas", function () { var n; try { n = t.$(i[0].hash) } catch (o) { n = "" } n.length || (n = t.$('[name="' + i[0].hash.replace("#", "") + '"]')), n.length && t.Utils.scrollToElement ? t.Utils.scrollToElement(n, t.Utils.options(i.attr("data-uk-smooth-scroll") || "{}")) : window.location.href = e }), n.hide()) }), i.data("OffcanvasInit", !0)) } }; t.component("offcanvasTrigger", { boot: function () { e.on("click.offcanvas.uikit", "[data-uk-offcanvas]", function (i) { i.preventDefault(); var e = t.$(this); if (!e.data("offcanvasTrigger")) { { t.offcanvasTrigger(e, t.Utils.options(e.attr("data-uk-offcanvas"))) } e.trigger("click") } }), e.on("keydown.uk.offcanvas", function (t) { 27 === t.keyCode && n.hide() }) }, init: function () { var i = this; this.options = t.$.extend({ target: i.element.is("a") ? i.element.attr("href") : !1, mode: "push" }, this.options), this.on("click", function (t) { t.preventDefault(), n.show(i.options.target, i.options) }) } }), t.offcanvas = n }(UIkit), function (t) { "use strict"; function i(i, e, n) { var o, s = t.$.Deferred(), a = i, r = i; return n[0] === e[0] ? (s.resolve(), s.promise()) : ("object" == typeof i && (a = i[0], r = i[1] || i[0]), t.$body.css("overflow-x", "hidden"), o = function () { e && e.hide().removeClass("uk-active " + r + " uk-animation-reverse"), n.addClass(a).one(t.support.animation.end, function () { setTimeout(function () { n.removeClass("" + a).css({ opacity: "", display: "" }) }, 0), s.resolve(), t.$body.css("overflow-x", ""), e && e.css({ opacity: "", display: "" }) }.bind(this)).show() }, n.css("animation-duration", this.options.duration + "ms"), e && e.length ? (e.css("animation-duration", this.options.duration + "ms"), e.css("display", "none").addClass(r + " uk-animation-reverse").one(t.support.animation.end, function () { o() }.bind(this)).css("display", "")) : (n.addClass("uk-active"), o()), s.promise()) } var e; t.component("switcher", { defaults: { connect: !1, toggle: ">*", active: 0, animation: !1, duration: 200, swiping: !0 }, animating: !1, boot: function () { t.ready(function (i) { t.$("[data-uk-switcher]", i).each(function () { var i = t.$(this); if (!i.data("switcher")) { t.switcher(i, t.Utils.options(i.attr("data-uk-switcher"))) } }) }) }, init: function () { var i = this; this.on("click.uk.switcher", this.options.toggle, function (t) { t.preventDefault(), i.show(this) }), this.options.connect && (this.connect = t.$(this.options.connect), this.connect.length && (this.connect.on("click.uk.switcher", "[data-uk-switcher-item]", function (e) { e.preventDefault(); var n = t.$(this).attr("data-uk-switcher-item"); if (i.index != n) switch (n) { case "next": case "previous": i.show(i.index + ("next" == n ? 1 : -1)); break; default: i.show(parseInt(n, 10)) } }), this.options.swiping && this.connect.on("swipeRight swipeLeft", function (t) { t.preventDefault(), window.getSelection().toString() || i.show(i.index + ("swipeLeft" == t.type ? 1 : -1)) }), this.update())) }, update: function () { this.connect.children().removeClass("uk-active").attr("aria-hidden", "true"); var t = this.find(this.options.toggle), i = t.filter(".uk-active"); if (i.length) this.show(i, !1); else { if (this.options.active === !1) return; i = t.eq(this.options.active), this.show(i.length ? i : t.eq(0), !1) } t.not(i).attr("aria-expanded", "false"), i.attr("aria-expanded", "true") }, show: function (n, o) { if (!this.animating) { var s = this.find(this.options.toggle); isNaN(n) ? n = t.$(n) : (n = 0 > n ? s.length - 1 : n, n = s.eq(s[n] ? n : 0)); var a = this, r = t.$(n), l = e[this.options.animation] || function (t, n) { if (!a.options.animation) return e.none.apply(a); var o = a.options.animation.split(","); return 1 == o.length && (o[1] = o[0]), o[0] = o[0].trim(), o[1] = o[1].trim(), i.apply(a, [o, t, n]) }; o !== !1 && t.support.animation || (l = e.none), r.hasClass("uk-disabled") || (s.attr("aria-expanded", "false"), r.attr("aria-expanded", "true"), s.filter(".uk-active").removeClass("uk-active"), r.addClass("uk-active"), this.options.connect && this.connect.length && (this.index = this.find(this.options.toggle).index(r), -1 == this.index && (this.index = 0), this.connect.each(function () { var i = t.$(this), e = t.$(i.children()), n = t.$(e.filter(".uk-active")), o = t.$(e.eq(a.index)); a.animating = !0, l.apply(a, [n, o]).then(function () { n.removeClass("uk-active"), o.addClass("uk-active"), n.attr("aria-hidden", "true"), o.attr("aria-hidden", "false"), t.Utils.checkDisplay(o, !0), a.animating = !1 }) })), this.trigger("show.uk.switcher", [r])) } } }), e = { none: function () { var i = t.$.Deferred(); return i.resolve(), i.promise() }, fade: function (t, e) { return i.apply(this, ["uk-animation-fade", t, e]) }, "slide-bottom": function (t, e) { return i.apply(this, ["uk-animation-slide-bottom", t, e]) }, "slide-top": function (t, e) { return i.apply(this, ["uk-animation-slide-top", t, e]) }, "slide-vertical": function (t, e) { var n = ["uk-animation-slide-top", "uk-animation-slide-bottom"]; return t && t.index() > e.index() && n.reverse(), i.apply(this, [n, t, e]) }, "slide-left": function (t, e) { return i.apply(this, ["uk-animation-slide-left", t, e]) }, "slide-right": function (t, e) { return i.apply(this, ["uk-animation-slide-right", t, e]) }, "slide-horizontal": function (t, e) { var n = ["uk-animation-slide-right", "uk-animation-slide-left"]; return t && t.index() > e.index() && n.reverse(), i.apply(this, [n, t, e]) }, scale: function (t, e) { return i.apply(this, ["uk-animation-scale-up", t, e]) } }, t.switcher.animations = e }(UIkit), function (t) { "use strict"; t.component("tab", { defaults: { target: ">li:not(.uk-tab-responsive, .uk-disabled)", connect: !1, active: 0, animation: !1, duration: 200, swiping: !0 }, boot: function () { t.ready(function (i) { t.$("[data-uk-tab]", i).each(function () { var i = t.$(this); if (!i.data("tab")) { t.tab(i, t.Utils.options(i.attr("data-uk-tab"))) } }) }) }, init: function () { var i = this; this.current = !1, this.on("click.uk.tab", this.options.target, function (e) { if (e.preventDefault(), !i.switcher || !i.switcher.animating) { var n = i.find(i.options.target).not(this); n.removeClass("uk-active").blur(), i.trigger("change.uk.tab", [t.$(this).addClass("uk-active"), i.current]), i.current = t.$(this), i.options.connect || (n.attr("aria-expanded", "false"), t.$(this).attr("aria-expanded", "true")) } }), this.options.connect && (this.connect = t.$(this.options.connect)), this.responsivetab = t.$('<li class="uk-tab-responsive uk-active"><a></a></li>').append('<div class="uk-dropdown uk-dropdown-small"><ul class="uk-nav uk-nav-dropdown"></ul><div>'), this.responsivetab.dropdown = this.responsivetab.find(".uk-dropdown"), this.responsivetab.lst = this.responsivetab.dropdown.find("ul"), this.responsivetab.caption = this.responsivetab.find("a:first"), this.element.hasClass("uk-tab-bottom") && this.responsivetab.dropdown.addClass("uk-dropdown-up"), this.responsivetab.lst.on("click.uk.tab", "a", function (e) { e.preventDefault(), e.stopPropagation(); var n = t.$(this); i.element.children("li:not(.uk-tab-responsive)").eq(n.data("index")).trigger("click") }), this.on("show.uk.switcher change.uk.tab", function (t, e) { i.responsivetab.caption.html(e.text()) }), this.element.append(this.responsivetab), this.options.connect && (this.switcher = t.switcher(this.element, { toggle: ">li:not(.uk-tab-responsive)", connect: this.options.connect, active: this.options.active, animation: this.options.animation, duration: this.options.duration, swiping: this.options.swiping })), t.dropdown(this.responsivetab, { mode: "click", preventflip: "y" }), i.trigger("change.uk.tab", [this.element.find(this.options.target).not(".uk-tab-responsive").filter(".uk-active")]), this.check(), t.$win.on("resize orientationchange", t.Utils.debounce(function () { i.element.is(":visible") && i.check() }, 100)), this.on("display.uk.check", function () { i.element.is(":visible") && i.check() }) }, check: function () { var i = this.element.children("li:not(.uk-tab-responsive)").removeClass("uk-hidden"); if (!i.length) return this.responsivetab.addClass("uk-hidden"), void 0; var e, n, o, s = i.eq(0).offset().top + Math.ceil(i.eq(0).height() / 2), a = !1; if (this.responsivetab.lst.empty(), i.each(function () { t.$(this).offset().top > s && (a = !0) }), a) for (var r = 0; r < i.length; r++) e = t.$(i.eq(r)), n = e.find("a"), "none" == e.css("float") || e.attr("uk-dropdown") || (e.hasClass("uk-disabled") || (o = t.$(e[0].outerHTML), o.find("a").data("index", r), this.responsivetab.lst.append(o)), e.addClass("uk-hidden")); this.responsivetab[this.responsivetab.lst.children("li").length ? "removeClass" : "addClass"]("uk-hidden") } }) }(UIkit), function (t) { "use strict"; t.component("cover", { defaults: { automute: !0 }, boot: function () { t.ready(function (i) { t.$("[data-uk-cover]", i).each(function () { var i = t.$(this); if (!i.data("cover")) { t.cover(i, t.Utils.options(i.attr("data-uk-cover"))) } }) }) }, init: function () { if (this.parent = this.element.parent(), t.$win.on("load resize orientationchange", t.Utils.debounce(function () { this.check() }.bind(this), 100)), this.on("display.uk.check", function () { this.element.is(":visible") && this.check() }.bind(this)), this.check(), this.element.is("iframe") && this.options.automute) { var i = this.element.attr("src"); this.element.attr("src", "").on("load", function () { this.contentWindow.postMessage('{ "event": "command", "func": "mute", "method":"setVolume", "value":0}', "*") }).attr("src", [i, i.indexOf("?") > -1 ? "&" : "?", "enablejsapi=1&api=1"].join("")) } }, check: function () { this.element.css({ width: "", height: "" }), this.dimension = { w: this.element.width(), h: this.element.height() }, this.element.attr("width") && !isNaN(this.element.attr("width")) && (this.dimension.w = this.element.attr("width")), this.element.attr("height") && !isNaN(this.element.attr("height")) && (this.dimension.h = this.element.attr("height")), this.ratio = this.dimension.w / this.dimension.h; var t, i, e = this.parent.width(), n = this.parent.height(); e / this.ratio < n ? (t = Math.ceil(n * this.ratio), i = n) : (t = e, i = Math.ceil(e / this.ratio)), this.element.css({ width: t, height: i }) } }) }(UIkit);
;(function($) {
  $.fn.unveil = function(threshold, callback) {

    var $w = $(window),
        th = 100000,
        retina = window.devicePixelRatio > 1,
        attrib = retina? "data-src-retina" : "data-srcload",
        images = this,
        loaded;

    this.one("unveil", function () {
        var source = this.getAttribute(attrib);
      source = source || this.getAttribute("data-srcload");
      if (source) {
          this.setAttribute("src", source);

          if (typeof callback === "function") {
              callback(this);
          };
      }
    });

    function unveil() {
        $(document).ready(function() {
            var inview = images.filter(function () {
                var $e = $(this);
                $e.attr("data-srcload", $e.attr("data-srcload").replace("cdn2", "cdn" + Math.floor((Math.random() * 3) + 1)));
                if ($e.is(":hidden")) return;

                var wt = $w.scrollTop(),
                    wb = wt + $w.height(),
                    et = $e.offset().top,
                    eb = et + $e.height();
         
                return eb >= wt - th && et <= wb + th;
            });

            loaded = inview.trigger("unveil");
            images = images.not(loaded);
        });
    }
    $w.on("scroll.unveil resize.unveil lookup.unveil", unveil);
    unveil();
    return this;
  };

})(window.jQuery || window.Zepto);

(function(addon) {
    var component;

    if (window.UIkit) {
        component = addon(UIkit);
    }

    if (typeof define == "function" && define.amd) {
        define("uikit-tooltip", ["uikit"], function(){
            return component || addon(UIkit);
        });
    }

})(function(UI){

    "use strict";

    var $tooltip,   // tooltip container
        tooltipdelay, checkdelay;

    UI.component('tooltip', {

        defaults: {
            "offset": 5,
            "pos": "top",
            "animation": false,
            "delay": 0, // in miliseconds
            "cls": "",
            "activeClass": "uk-active",
            "src": function(ele) {
                var title = ele.attr('title');

                if (title !== undefined) {
                    ele.data('cached-title', title).removeAttr('title');
                }

                return ele.data("cached-title");
            }
        },

        tip: "",

        boot: function() {

            // init code
            UI.$html.on("mouseenter.tooltip.uikit focus.tooltip.uikit", "[data-uk-tooltip]", function(e) {
                var ele = UI.$(this);

                if (!ele.data("tooltip")) {
                    UI.tooltip(ele, UI.Utils.options(ele.attr("data-uk-tooltip")));
                    ele.trigger("mouseenter");
                }
            });
        },

        init: function() {

            var $this = this;

            if (!$tooltip) {
                $tooltip = UI.$('<div class="uk-tooltip"></div>').appendTo("body");
            }

            this.on({
                focus      : function(e) { $this.show(); },
                blur       : function(e) { $this.hide(); },
                mouseenter : function(e) { $this.show(); },
                mouseleave : function(e) { $this.hide(); }
            });
        },

        show: function() {

            this.tip = typeof(this.options.src) === "function" ? this.options.src(this.element) : this.options.src;

            if (tooltipdelay)     clearTimeout(tooltipdelay);
            if (checkdelay)       clearTimeout(checkdelay);

            if (typeof(this.tip) === 'string' ? !this.tip.length:true) return;

            $tooltip.stop().css({"top": -2000, "visibility": "hidden"}).removeClass(this.options.activeClass).show();
            $tooltip.html('<div class="uk-tooltip-inner">' + this.tip + '</div>');

            var $this      = this,
                pos        = UI.$.extend({}, this.element.offset(), {width: this.element[0].offsetWidth, height: this.element[0].offsetHeight}),
                width      = $tooltip[0].offsetWidth,
                height     = $tooltip[0].offsetHeight,
                offset     = typeof(this.options.offset) === "function" ? this.options.offset.call(this.element) : this.options.offset,
                position   = typeof(this.options.pos) === "function" ? this.options.pos.call(this.element) : this.options.pos,
                tmppos     = position.split("-"),
                tcss       = {
                    "display"    : "none",
                    "visibility" : "visible",
                    "top"        : (pos.top + pos.height + height),
                    "left"       : pos.left
                };


            // prevent strange position
            // when tooltip is in offcanvas etc.
            if (UI.$html.css('position')=='fixed' || UI.$body.css('position')=='fixed'){
                var bodyoffset = UI.$('body').offset(),
                    htmloffset = UI.$('html').offset(),
                    docoffset  = {'top': (htmloffset.top + bodyoffset.top), 'left': (htmloffset.left + bodyoffset.left)};

                pos.left -= docoffset.left;
                pos.top  -= docoffset.top;
            }


            if ((tmppos[0] == "left" || tmppos[0] == "right") && UI.langdirection == 'right') {
                tmppos[0] = tmppos[0] == "left" ? "right" : "left";
            }

            var variants =  {
                "bottom"  : {top: pos.top + pos.height + offset, left: pos.left + pos.width / 2 - width / 2},
                "top"     : {top: pos.top - height - offset, left: pos.left + pos.width / 2 - width / 2},
                "left"    : {top: pos.top + pos.height / 2 - height / 2, left: pos.left - width - offset},
                "right"   : {top: pos.top + pos.height / 2 - height / 2, left: pos.left + pos.width + offset}
            };

            UI.$.extend(tcss, variants[tmppos[0]]);

            if (tmppos.length == 2) tcss.left = (tmppos[1] == 'left') ? (pos.left) : ((pos.left + pos.width) - width);

            var boundary = this.checkBoundary(tcss.left, tcss.top, width, height);

            if(boundary) {

                switch(boundary) {
                    case "x":

                        if (tmppos.length == 2) {
                            position = tmppos[0]+"-"+(tcss.left < 0 ? "left": "right");
                        } else {
                            position = tcss.left < 0 ? "right": "left";
                        }

                        break;

                    case "y":
                        if (tmppos.length == 2) {
                            position = (tcss.top < 0 ? "bottom": "top")+"-"+tmppos[1];
                        } else {
                            position = (tcss.top < 0 ? "bottom": "top");
                        }

                        break;

                    case "xy":
                        if (tmppos.length == 2) {
                            position = (tcss.top < 0 ? "bottom": "top")+"-"+(tcss.left < 0 ? "left": "right");
                        } else {
                            position = tcss.left < 0 ? "right": "left";
                        }

                        break;

                }

                tmppos = position.split("-");

                UI.$.extend(tcss, variants[tmppos[0]]);

                if (tmppos.length == 2) tcss.left = (tmppos[1] == 'left') ? (pos.left) : ((pos.left + pos.width) - width);
            }


            tcss.left -= UI.$body.position().left;

            tooltipdelay = setTimeout(function(){

                $tooltip.css(tcss).attr("class", ["uk-tooltip", "uk-tooltip-"+position, $this.options.cls].join(' '));

                if ($this.options.animation) {
                    $tooltip.css({opacity: 0, display: 'block'}).addClass($this.options.activeClass).animate({opacity: 1}, parseInt($this.options.animation, 10) || 400);
                } else {
                    $tooltip.show().addClass($this.options.activeClass);
                }

                tooltipdelay = false;

                // close tooltip if element was removed or hidden
                checkdelay = setInterval(function(){
                    if(!$this.element.is(':visible')) $this.hide();
                }, 150);

            }, parseInt(this.options.delay, 10) || 0);
        },

        hide: function() {
            if(this.element.is("input") && this.element[0]===document.activeElement) return;

            if(tooltipdelay) clearTimeout(tooltipdelay);
            if (checkdelay)  clearTimeout(checkdelay);

            $tooltip.stop();

            if (this.options.animation) {

                var $this = this;

                $tooltip.fadeOut(parseInt(this.options.animation, 10) || 400, function(){
                    $tooltip.removeClass($this.options.activeClass)
                });

            } else {
                $tooltip.hide().removeClass(this.options.activeClass);
            }
        },

        content: function() {
            return this.tip;
        },

        checkBoundary: function(left, top, width, height) {

            var axis = "";

            if(left < 0 || ((left - UI.$win.scrollLeft())+width) > window.innerWidth) {
               axis += "x";
            }

            if(top < 0 || ((top - UI.$win.scrollTop())+height) > window.innerHeight) {
               axis += "y";
            }

            return axis;
        }
    });

    return UI.tooltip;
});

/*
 * Tempo Template Engine 2.0
 *
 * http://tempojs.com/
 */
function TempoEvent(type, item, element) {
    'use strict';
    this.type = type;
    this.item = item;
    this.element = element;

    return this;
}

TempoEvent.Types = {
    RENDER_STARTING: 'render_starting',
    ITEM_RENDER_STARTING: 'item_render_starting',
    ITEM_RENDER_COMPLETE: 'item_render_complete',
    RENDER_COMPLETE: 'render_complete',
    BEFORE_CLEAR: 'before_clear',
    AFTER_CLEAR: 'after_clear'
};


var Tempo = (function (tempo) {
    'use strict';

    /*
     * Constants
     */
    var NUMBER_FORMAT_REGEX = /(\d+)(\d{3})/;


    var _window;


    /*
     * Helpers
     */
    var utils = {
        memberRegex: function (obj) {
            var member_regex = '(';
            for (var member in obj) {
                if (obj.hasOwnProperty(member)) {
                    if (member_regex.length > 1) {
                        member_regex += '|';
                    }
                    member_regex += member;
                }
            }
            return member_regex + ')[\\.]?' + '(?!\\w)';
        },

        pad: function (val, pad, size) {
            while (val.length < size) {
                val = pad + val;
            }
            return val;
        },

        trim: function (str) {
            return str.replace(/^\s*([\S\s]*?)\s*$/, '$1');
        },

        startsWith: function (str, prefix) {
            return (str.indexOf(prefix) === 0);
        },

        clearContainer: function (el) {
            if (el !== null && el !== undefined && el.childNodes !== undefined) {
                for (var i = el.childNodes.length - 1; i >= 0; i--) {
                    if (el.childNodes[i] !== undefined && el.childNodes[i].getAttribute !== undefined && (el.childNodes[i].getAttribute('data-template') !== null || el.childNodes[i].getAttribute('data-template-for') !== null)) {
                        el.childNodes[i].parentNode.removeChild(el.childNodes[i]);
                    }
                }
            }
        },

        isNested: function (el) {
            var p = el.parentNode;
            while (p) {
                if (this.hasAttr(p, 'data-template') || this.hasAttr(p, 'data-template-for')) {
                    return true;
                }
                p = p.parentNode;
            }
            return false;
        },

        equalsIgnoreCase: function (str1, str2) {
            return str1.toLowerCase() === str2.toLowerCase();
        },

        getElement: function (template, html) {
            if (navigator.appVersion.indexOf("MSIE") > -1 && utils.equalsIgnoreCase(template.tagName, 'tr')) {
                // Wrapping to get around read-only innerHTML
                var el = _window.document.createElement('div');
                el.innerHTML = '<table><tbody>' + html + '</tbody></table>';
                var depth = 3;
                while (depth--) {
                    el = el.lastChild;
                }
                el.setAttribute('data-template', '');
                return el;
            } else {
                // No need to wrap
                template.innerHTML = html;
                return template;
            }
        },

        typeOf: function (obj) {
            if (typeof(obj) === "object") {
                if (obj === null) {
                    return "null";
                }
                if (obj.constructor === ([]).constructor) {
                    return "array";
                }
                if (obj.constructor === (new Date()).constructor) {
                    return "date";
                }
                if (obj.constructor === (new RegExp()).constructor) {
                    return "regex";
                }
                if (typeof HTMLElement === "object" ? obj instanceof HTMLElement : obj && typeof obj === "object" && obj.nodeType === 1 && typeof obj.nodeName === "string") {
                    return 'element';
                }
                if (typeof jQuery !== 'undefined' && obj instanceof jQuery) {
                    return 'jquery';
                }
                return "object";
            }
            return typeof(obj);
        },

        hasAttr: function (el, name) {
            if (el !== undefined) {
                if (el.hasAttribute !== undefined) {
                    return el.hasAttribute(name);
                } else if (el.getAttribute !== undefined) {
                    return el.getAttribute(name) !== null;
                }
            }

            return false;
        },

        removeAttr: function (el, name) {
            if (el !== undefined) {
                el.setAttribute(name, '');
                if (el.removeAttribute) {
                    el.removeAttribute(name);
                }
            }
        },

        merge: function (obj1, obj2) {
            var obj3 = {};

            for (var attr1 in obj1) {
                if (obj1.hasOwnProperty(attr1)) {
                    obj3[attr1] = obj1[attr1];
                }
            }

            for (var attr2 in obj2) {
                if (obj2.hasOwnProperty(attr2)) {
                    obj3[attr2] = obj2[attr2];
                }
            }
            return obj3;
        },
        notify: function (listener, event) {
			
            if (listener !== undefined && listener.length > 0) {
                for (var i = 0; i < listener.length; i++) {
                    if (event.type === listener[i].type) {
						if((listener.length - 1) === i){					
							listener[i].listener(event);
						}
                    }
                }
            }
        },
        container: function (container) {
            if (utils.typeOf(container) === 'string') {
                if (container === '*') {
                    container = _window.document.getElementsByTagName('html')[0];
                } else {
                    container = _window.document.getElementById(container);
                }
            } else if (utils.typeOf(container) === 'jquery' && container.length > 0) {
                container = container[0];
            }

            return container;
        },
        arrayContains: function (array, obj) {
            if (!Array.prototype.indexOf) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] === obj) {
                        return true;
                    }
                }
                return false;
            } else {
                return array.indexOf(obj) > -1;
            }
        }
    };

    function Templates(params, nestedItem) {
        this.params = params;
        this.defaultTemplate = null;
        this.namedTemplates = {};
        this.container = null;

        this.nestedItem = nestedItem !== undefined ? nestedItem : null;

        this.escape = true;
        this.var_brace_left = '\\{\\{';
        this.var_brace_right = '\\}\\}';
        this.tag_brace_left = '\\{\\[';
        this.tag_brace_right = '\\]\\}';

        this.dataIsMap = false;

        this.attributes = {};

        if (typeof params !== 'undefined') {
            for (var prop in params) {
                if (prop === 'var_braces') {
                    this.var_brace_left = params[prop].substring(0, params[prop].length / 2);
                    this.var_brace_right = params[prop].substring(params[prop].length / 2);
                } else if (prop === 'tag_braces') {
                    this.tag_brace_left = params[prop].substring(0, params[prop].length / 2);
                    this.tag_brace_right = params[prop].substring(params[prop].length / 2);
                } else if (typeof this[prop] !== 'undefined') {
                    this[prop] = params[prop];
                }
            }
        }

        return this;
    }

    Templates.prototype = {
        load: function (file, callback) {
            function contents(iframe) {
                return iframe.contentWindow ? iframe.contentWindow.document.documentElement.innerHTML : iframe.contentDocument ? iframe.contentDocument.body.innerHTML : iframe.document.body.innerHTML;
            }

            if (_window.document.getElementById(file) !== null) {
                callback(contents(_window.document.getElementById(file)));
            } else {
                var el = _window.document.createElement('iframe');
                el.id = file;
                el.name = file;
                el.style.height = 0;
                el.style.width = 0;
                el.src = file;

                if (el.attachEvent) {
                    el.attachEvent('onload', function () {
                        callback(contents(el));
                    });
                } else {
                    el.onload = function () {
                        callback(contents(el));
                    };
                }

                _window.document.body.appendChild(el);
            }
        },
        _insertTemplate: function (child, templates, container, callback) {
            return function (el) {
                utils.removeAttr(child, 'data-template-file');
                child.innerHTML = el;
                templates.parse(container, callback);
            };
        },

        parse: function (container, callback) {

            //-----------------------------------------------------------------------------------
            //THIS WAS ADDED TO NOT THROW A LAME EXCEPTION SAYING THAT THE CONAINER DOESN'T EXIST
            if (container == null) return;
            //-----------------------------------------------------------------------------------

            this.container = container;

            var children = container.getElementsByTagName('*');

            var ready = true;

            // Preprocessing for referenced templates
            for (var i = 0; i < children.length; i++) {
                if (ready === true && callback !== undefined && utils.hasAttr(children[i], 'data-template-file')) {
                    var child = children[i];
                    if (child.getAttribute('data-template-file').length > 0) {
                        var templates = this;
                        ready = false;

                        this.load(child.getAttribute('data-template-file'), this._insertTemplate(child, templates, container, callback));
                    }
                } else if (utils.hasAttr(children[i], 'data-template-fallback')) {
                    // Hiding the fallback template
                    children[i].style.display = 'none';
                }
            }

            // Parsing
            if (ready) {
                var foundTemplates = {};
                for (var s = 0; s < children.length; s++) {
                    if (children[s].getAttribute !== undefined) {
                        if (utils.hasAttr(children[s], 'data-template-for') && children[s].getAttribute('data-template-for').length > 0 && this.nestedItem === children[s].getAttribute('data-template-for') && !foundTemplates[this.nestedItem]) {
                            // Nested template
                            this.createTemplate(children[s]);
                            // Guards against recursion when child template has same name!
                            foundTemplates[this.nestedItem] = true;
                        } else if (utils.hasAttr(children[s], 'data-template') && !utils.isNested(children[s])) {
                            // Normal template
                            this.createTemplate(children[s]);
                        }
                    }
                }

                // If there is no default template (data-template) then create one from container
                if (this.defaultTemplate === null) {
                    this.createTemplate(container);
                }

                utils.clearContainer(this.container);
                if (callback !== undefined) {
                    callback(this);
                }
            }
        },

        createTemplate: function (node) {
            var element = node.cloneNode(true);

            // Clear display: none;
            if (element.style.removeAttribute) {
                element.style.removeAttribute('display');
            } else if (element.style.removeProperty) {
                element.style.removeProperty('display');
            } else {
                element.style.display = 'block';
            }

            // Remapping container element in case template
            // is deep in container
            this.container = node.parentNode;

            // Element is a template
            var nonDefault = false;
            for (var a = 0; a < element.attributes.length; a++) {
                var attr = element.attributes[a];
                // If attribute
                if (utils.startsWith(attr.name, 'data-if-')) {
                    var val;
                    if (attr.value === '') {
                        val = true;
                    } else {
                        val = '\'' + attr.value + '\'';
                    }
                    this.namedTemplates[attr.name.substring(8, attr.name.length) + '==' + val] = element;
                    utils.removeAttr(element, attr.name);
                    nonDefault = true;
                } else if (attr.name === 'data-has') {
                    this.namedTemplates[attr.value + '!==undefined'] = element;
                    utils.removeAttr(element, attr.name);
                    nonDefault = true;
                } else if (attr.name === 'data-from-map') {
                    this.dataIsMap = true;
                } else if (!utils.startsWith(attr.name, 'data-template') && utils.startsWith(attr.name, 'data-')) {
                    // Treat as an attribute for template
                    this.attributes[attr.name.substring(5, attr.name.length)] = attr.value;
                }
            }
            // Setting as default template, last one wins
            if (!nonDefault) {
                this.defaultTemplate = element;
            }
        },

        templateFor: function (i) {
            for (var templateName in this.namedTemplates) {
                if (eval('i.' + templateName)) {
                    return this.namedTemplates[templateName].cloneNode(true);
                }
            }
            if (this.defaultTemplate) {
                return this.defaultTemplate.cloneNode(true);
            }
        }
    };


    /*
     * Renderer for populating containers with data using templates.
     */
    function Renderer(templates) {
        this.templates = templates;
        this.listener = [];
        this.started = false;
        this.varRegex = new RegExp(this.templates.var_brace_left + '[ ]?([A-Za-z0-9$\\._\\[\\]]*?)([ ]?\\|[ ]?.*?)?[ ]?' + this.templates.var_brace_right, 'g');
        this.tagRegex = new RegExp(this.templates.tag_brace_left + '[ ]?([\\s\\S]*?)( [\\s\\S]*?)?[ ]?' + this.templates.tag_brace_right + '(([\\s\\S]*?)(?=' + this.templates.tag_brace_left + '[ ]?end\\1[ ]?' + this.templates.tag_brace_right + '))?', 'g');
        this.filterSplitter = new RegExp('\\|[ ]?(?=' + utils.memberRegex(this.filters) + ')', 'g');
        this.errorHandler = null;
        return this;
    }

    Renderer.prototype = {
        when: function (type, listener) {	
            this.listener.push({'type': type, 'listener': listener});
            return this;
        },

        _getValue: function (renderer, variable, i, t) {
            var val = null;
            // Handling tempo_info variable
            if (utils.startsWith(variable, '_tempo.')) {
                return eval('t.' + variable.substring(7, variable.length));
            }

            if (variable === '.') {
                val = eval('i');
            } else if (variable === 'this' || variable.match(/this[\\[\\.]/) !== null) {
                val = eval('i' + variable.substring(4, variable.length));
            } else if (utils.typeOf(i) === 'array') {
                val = eval('i' + variable);
            } else {
                val = eval('i.' + variable);
            }

            return val;
        },

        _replaceVariables: function (renderer, _tempo, i, str) {
            var self = this;
            return str.replace(this.varRegex, function (match, variable, args) {

                try {
                    var val = renderer._getValue(renderer, variable, i, _tempo);
                    // Handle filters
                    if (args !== undefined && args !== '') {
                        var filters = utils.trim(utils.trim(args).substring(1)).split(self.filterSplitter);
                        for (var p = 0; p < filters.length; p++) {
                            var filter = utils.trim(filters[p]);
                            var filter_args = [];
                            // If there is a space, there must be arguments
                            if (filter.indexOf(' ') > -1) {
                                var f = filter.substring(filter.indexOf(' ')).replace(/^[ ']*|[ ']*$/g, '');
                                filter_args = f.split(/(?:[\'"])[ ]?,[ ]?(?:[\'"])/);
                                filter = filter.substring(0, filter.indexOf(' '));
                            }
                            val = renderer.filters[filter](val, filter_args);
                        }
                    }

                    if (val !== undefined) {
                        if (self.templates.escape) {
                            val = self.filters.escape(val, {});
                        }
                        return val;
                    }
                } catch (err) {
                    self._onError.call(self, err);
                }

                return '';
            });
        },

        _replaceObjects: function (renderer, _tempo, i, str, regex) {
            return str.replace(regex, function (match, variable, args) {
                try {
                    var val = renderer._getValue(renderer, variable, i, _tempo);

                    if (val !== undefined) {
                        if (utils.typeOf(val) === 'string') {
                            return '\'' + val + '\'';
                        } else {
                            return val;
                        }
                    }
                } catch (err) {
                    self._onError.call(self, err);
                }

                return undefined;
            });
        },

        _applyAttributeSetters: function (renderer, item, str) {
            // Adding a space in front of first part to make sure I don't get partial matches
            return str.replace(/(\b[A-z0-9]+?)(?:="[^"']*?"[^>]*?)data-\1="(.*?)"/g, function (match, attr, data_value) {
                if (data_value !== '') {
                    return attr + '="' + data_value + '"';
                }
                return match;
            });
        },

        _applyTags: function (renderer, item, str) {
            return str.replace(this.tagRegex, function (match, tag, args, body) {
                if (renderer.tags.hasOwnProperty(tag)) {
                    args = args.substring(args.indexOf(' ')).replace(/^[ ]*|[ ]*$/g, '');
                    var filter_args = args.split(/(?:['"])[ ]?,[ ]?(?:['"])/);
                    return renderer.tags[tag](renderer, item, match, filter_args, body);
                } else {
                    return '';
                }
            });
        },

        starting: function (event) {
            // Use this to manually fire the RENDER_STARTING event e.g. just before you issue an AJAX request
            // Useful if you're not calling prepare immediately before render
            this.started = true;
            if (event === undefined) {
                event = new TempoEvent(TempoEvent.Types.RENDER_STARTING, undefined, undefined);
            }
            utils.notify(this.listener, event);

            return this;
        },

        _renderNestedItem: function (i, nested) {
            var self = this;
            return function (templates) {
                var r = new Renderer(templates);
                var data = null;
                if (i.hasOwnProperty(nested.split('.')[0])) {
                    data = eval('i.' + nested);
                    if (data) {
                        try {
                            if (utils.typeOf(data) === 'array') {
                                for (var s = 0; s < data.length; s++) {
                                    data[s]._parent = function () {
                                        return i;
                                    }()
                                }
                            } else {
                                data._parent = function () {
                                    return i;
                                }();
                            }
                        } catch (err) {
                            self._onError.call(self, err);
                        }
                    }
                }
                r.render(data);
            };
        },

        renderItem: function (renderer, _tempo_info, i, fragment) {
            var memberRegex = new RegExp('(?:__[\\.]?)((_tempo|\\[|' + utils.memberRegex(i) + '|this)([A-Za-z0-9$\\._\\[\\]]+)?)', 'g');
            var template = renderer.templates.templateFor(i);
            var tempo_info = utils.merge(_tempo_info, renderer.templates.attributes);

            // Clear attributes in case of recursive nesting (TODO: Probably need to clear more)
            if (utils.hasAttr(template, 'data-template-for')) {
                utils.removeAttr(template, 'data-template-for');
            }
            if (utils.hasAttr(template, 'data-template-file')) {
                utils.removeAttr(template, 'data-template-file');
            }

            if (template && i) {
                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.ITEM_RENDER_STARTING, i, template));
                var nestedDeclaration = template.innerHTML.match(/data-template-for="([^"]+?)"/g);
                if (nestedDeclaration) {
                    for (var p = 0; p < nestedDeclaration.length; p++) {
                        var nested = nestedDeclaration[p].match(/data-template-for="([^"]+?)"/);
                        if (nested && nested[1]) {
                            var t = new Templates(renderer.templates.params, nested[1]);
                            try {
                                t.parse(template, this._renderNestedItem(i, nested[1]));
                            } catch (err) {
                                this._onError.call(this, err);
                            }
                        }
                    }
                }

                // Processing template element attributes
                for (var a = 0; a < template.attributes.length; a++) {
                    var attr = template.attributes[a];
                    if (attr !== null && attr.specified && attr.value !== null && attr.value.length > 0 && attr.name.match(/style|data-template.*/) === null) {
                        attr.value = this._applyTags(this, i, attr.value);
                        attr.value = this._replaceVariables(this, tempo_info, i, attr.value);
                    }
                }

                // Dealing with HTML as a String from now on (to be reviewed)
                // Attribute values are escaped in FireFox so making sure there are no escaped tags
                var html = template.innerHTML.replace(/%7B%7B/g, '{{').replace(/%7D%7D/g, '}}');

                // Tags
                html = this._applyTags(this, i, html);

                // Content
                html = this._replaceVariables(this, tempo_info, i, html);

                // JavaScript objects
                html = this._replaceObjects(this, tempo_info, i, html, memberRegex);

                html = this._applyAttributeSetters(this, i, html);

                fragment.appendChild(utils.getElement(template, html));

                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.ITEM_RENDER_COMPLETE, i, template));
            }
        },

        _createFragment: function (data) {
            if (data) {
                var tempo_info = {};
                var fragment = _window.document.createDocumentFragment();

                // If object then wrapping in an array
                if (utils.typeOf(data) === 'object') {
                    if (this.templates.dataIsMap) {
                        var mapped = [];
                        for (var member in data) {
                            if (data.hasOwnProperty(member) && member !== '_parent') {
                                var pair = {};
                                pair.key = member;
                                pair.value = data[member];
                                mapped.push(pair);
                            }
                        }
                        data = mapped;
                    } else {
                        data = [data];
                    }
                }

                for (var i = 0; i < data.length; i++) {
                    tempo_info.index = i;
                    tempo_info.first = i < 1;
                    tempo_info.last = i == data.length - 1;
                    this.renderItem(this, tempo_info, data[i], fragment);
                }

                return fragment;
            }

            return null;
        },

        into: function (target) {
            if (target !== undefined) {
                this.templates.container = utils.container(target);
            }

            return this;
        },

        render: function (data) {
            // Check if starting event was manually fired
            if (!this.started) {
                this.starting(new TempoEvent(TempoEvent.Types.RENDER_STARTING, data, this.templates.container));
            }

            this.clear();
            this.append(data);

            return this;
        },

        append: function (data) {
            // Check if starting event was manually fired
            if (!this.started) {
                this.starting(new TempoEvent(TempoEvent.Types.RENDER_STARTING, data, this.templates.container));
            }

            var fragment = this._createFragment(data);
            if (fragment !== null && this.templates.container !== null) {
                if (fragment !== null) {
                    var ref = null;
                    for (var i = this.templates.container.childNodes.length; i >= 0; i--) {

                        if (this.templates.container.childNodes[i] !== undefined && this.templates.container.childNodes[i].getAttribute !== undefined && this.templates.container.childNodes[i].getAttribute('data-after-template') !== null) {
                            ref = this.templates.container.childNodes[i];
                        }
                    }
                    if (ref === null) {
                        ref = this.templates.container.lastChild;
                    }
                    if (ref !== null) {
                        this.templates.container.insertBefore(fragment, ref);
                    } else {
                        this.templates.container.appendChild(fragment);
                    }
                }
            }

            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_COMPLETE, data, this.templates.container));

            return this;
        },

        prepend: function (data) {
            // Check if starting event was manually fired
            if (!this.started) {
                this.starting(new TempoEvent(TempoEvent.Types.RENDER_STARTING, data, this.templates.container));
            }

            var fragment = this._createFragment(data);
            if (fragment !== null) {
                var ref = null;
                for (var i = 0; i < this.templates.container.childNodes.length; i++) {
                    if (this.templates.container.childNodes[i] !== undefined && this.templates.container.childNodes[i].getAttribute !== undefined && this.templates.container.childNodes[i].getAttribute('data-before-template') !== null) {
                        ref = this.templates.container.childNodes[i];
                    }
                }
                if (ref === null) {
                    ref = this.templates.container.firstChild;
                }
                if (ref !== null) {
                    if (ref.nextSibling !== null && ref.getAttribute && ref.getAttribute('data-before-template') !== null) {
                        ref = ref.nextSibling;
                    }
                    this.templates.container.insertBefore(fragment, ref);
                } else {
                    this.templates.container.appendChild(fragment);
                }
            }

            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_COMPLETE, data, this.templates.container));

            return this;
        },

        errors: function(errorHandler) {
            this.errorHandler = errorHandler;
            return this;
        },

        _onError: function(err) {
            if (this.errorHandler !== null) {
                this.errorHandler.call(this, err);
            }
        },

        clear: function () {
            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.BEFORE_CLEAR, {}, this.templates.container));
            utils.clearContainer(this.templates.container);
            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.AFTER_CLEAR, {}, this.templates.container));
        },

        tags: {
            'if': function (renderer, i, match, args, body) {
                var member_regex = utils.memberRegex(i);

                var expr = args[0].replace(/&amp;/g, '&').replace(/&gt;/g, '>').replace(/&lt;/g, '<');
                expr = expr.replace(new RegExp(member_regex, 'gi'), function (match) {
                    return 'i.' + match;
                });

                var blockRegex = new RegExp(renderer.templates.tag_brace_left + '[ ]?else[ ]?' + renderer.templates.tag_brace_right, 'g');
                var blocks = body.split(blockRegex);

                if (eval(expr)) {
                    return blocks[0];
                } else if (blocks.length > 1) {
                    return blocks[1];
                }

                return '';
            }
        },

        filters: {
            'escape': function (value, args) {
                return value.toString().replace(/[&<>]/g, function (c) {
                    return {
                        '&': '&amp;',
                        '<': '&lt;',
                        '>': '&gt;'
                    }[c] || c;
                });
            },
            'encodeURI': function (value, args) {
                return encodeURI(value.toString());
            },
            'decodeURI': function (value, args) {
                return decodeURI(value.toString());
            },
            'truncate': function (value, args) {
                if (value !== undefined) {
                    var len = 0;
                    var rep = '...';
                    if (args.length > 0) {
                        len = parseInt(args[0], 10);
                    }
                    if (args.length > 1) {
                        rep = args[1];
                    }
                    if (value.length > len - 3) {
                        return value.substr(0, len - 3) + rep;
                    }
                    return value;
                }
            },
            'format': function (value, args) {
                if (value !== undefined) {
                    if (args.length === 1) {
                        value = parseFloat(value + '').toFixed(parseInt(args[0], 10));
                    }
                    var x = (value + '').split('.');
                    var x1 = x[0];
                    var x2 = x.length > 1 ? '.' + x[1] : '';

                    while (NUMBER_FORMAT_REGEX.test(x1)) {
                        x1 = x1.replace(NUMBER_FORMAT_REGEX, '$1' + ',' + '$2');
                    }

                    return x1 + x2;
                }
            },
            'upper': function (value, args) {
                return value.toUpperCase();
            },
            'lower': function (value, args) {
                return value.toLowerCase();
            },
            'titlecase': function (value, args) {
                var blacklist = [];
                if (args !== undefined && args.length == 1) {
                    blacklist = args[0].split(' ');
                }
                return value.replace(/\w[a-z]\S*/g, function (m, i) {
                    if (blacklist.length === 0 || !(utils.arrayContains(blacklist, m) && i > 0)) {
                        return m.charAt(0).toUpperCase() + m.substr(1).toLowerCase();
                    }
                    return m;
                });
            },
            'trim': function (value, args) {
                return utils.trim(value);
            },
            'replace': function (value, args) {
                if (value !== undefined && args.length === 2) {
                    return value.replace(new RegExp(args[0], 'g'), args[1]);
                }
                return value;
            },
            'append': function (value, args) {
                if (value !== undefined && args.length === 1) {
                    return value + '' + args[0];
                }
                return value;
            },
            'prepend': function (value, args) {
                if (value !== undefined && args.length === 1) {
                    return args[0] + '' + value;
                }
                return value;
            },
            'join': function (value, args) {
                if (args.length === 1 && value !== undefined && utils.typeOf(value) === 'array') {
                    return value.join(args[0]);
                }
                return value;
            },
            'default': function (value, args) {
                if (value !== undefined && value !== null) {
                    return value;
                }
                if (args.length === 1) {
                    return args[0];
                }
                return value;
            },
            'date': function (value, args) {
                if (value !== undefined && args.length >= 1 && args.length <= 2) {
                    var date = new Date(value);
                    var format = args[0];
                    var isUTC = (args.length === 2 && args[1] === 'UTC');
                    if (format === 'localedate') {
                        return date.toLocaleDateString();
                    } else if (format === 'localetime') {
                        return date.toLocaleTimeString();
                    } else if (format === 'date') {
                        return date.toDateString();
                    } else if (format === 'time') {
                        return date.toTimeString();
                    } else {
                        var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                        var DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
                        var DATE_PATTERNS = {
                            'YYYY': function (date) {
                                return (isUTC ? date.getUTCFullYear() : date.getFullYear());
                            },
                            'YY': function (date) {
                                return (isUTC ? date.getUTCFullYear() : date.getFullYear()).toFixed().substring(2);
                            },
                            'MMMM': function (date) {
                                return MONTHS[(isUTC ? date.getUTCMonth() : date.getMonth())];
                            },
                            'MMM': function (date) {
                                return MONTHS[(isUTC ? date.getUTCMonth() : date.getMonth())].substring(0, 3);
                            },
                            'MM': function (date) {
                                return utils.pad(((isUTC ? date.getUTCMonth() : date.getMonth()) + 1).toFixed(), '0', 2);
                            },
                            'M': function (date) {
                                return (isUTC ? date.getUTCMonth() : date.getMonth()) + 1;
                            },
                            'DD': function (date) {
                                return utils.pad((isUTC ? date.getUTCDate() : date.getDate()).toFixed(), '0', 2);
                            },
                            'D': function (date) {
                                return (isUTC ? date.getUTCDate() : date.getDate());
                            },
                            'EEEE': function (date) {
                                return DAYS[(isUTC ? date.getUTCDay() : date.getDay())];
                            },
                            'EEE': function (date) {
                                return DAYS[(isUTC ? date.getUTCDay() : date.getDay())].substring(0, 3);
                            },
                            'E': function (date) {
                                return (isUTC ? date.getUTCDay() : date.getDay());
                            },
                            'HH': function (date) {
                                return utils.pad((isUTC ? date.getUTCHours() : date.getHours()).toFixed(), '0', 2);
                            },
                            'H': function (date) {
                                return (isUTC ? date.getUTCHours() : date.getHours());
                            },
                            'h': function (date) {
                                var hours = (isUTC ? date.getUTCHours() : date.getHours());
                                return hours < 13 ? (hours === 0 ? 12 : hours) : hours - 12;
                            },
                            'mm': function (date) {
                                return utils.pad((isUTC ? date.getUTCMinutes() : date.getMinutes()).toFixed(), '0', 2);
                            },
                            'm': function (date) {
                                return (isUTC ? date.getUTCMinutes() : date.getMinutes());
                            },
                            'ss': function (date) {
                                return utils.pad((isUTC ? date.getUTCSeconds() : date.getSeconds()).toFixed(), '0', 2);
                            },
                            's': function (date) {
                                return (isUTC ? date.getUTCSeconds() : date.getSeconds());
                            },
                            'SSS': function (date) {
                                return utils.pad((isUTC ? date.getUTCMilliseconds() : date.getMilliseconds()).toFixed(), '0', 3);
                            },
                            'S': function (date) {
                                return (isUTC ? date.getUTCMilliseconds() : date.getMilliseconds());
                            },
                            'a': function (date) {
                                return (isUTC ? date.getUTCHours() : date.getHours()) < 12 ? 'AM' : 'PM';
                            }
                        };
                        format = format.replace(/(\\)?(Y{2,4}|M{1,4}|D{1,2}|E{1,4}|H{1,2}|h|m{1,2}|s{1,2}|S{1,3}|a)/g,
                            function (match, escape, pattern) {
                                if (!escape) {
                                    if (DATE_PATTERNS.hasOwnProperty(pattern)) {
                                        return DATE_PATTERNS[pattern](date);
                                    }
                                }
                                return pattern;
                            });

                        return format;
                    }
                }

                return '';
            }
        }
    };

    /*
     * Initialising Tempo with a Window object in case running inside Node.
     */
    tempo.init = function (window) {
        _window = window;

        return this;
    };

    /*
     * Prepare a container for rendering, gathering templates and
     * clearing afterwards.
     */
    tempo.prepare = function (container, params, callback) {
        container = utils.container(container);

        var templates = new Templates(params);
        if (callback !== undefined) {
            templates.parse(container, function (templates) {
                callback(new Renderer(templates));
            });
        } else {
            templates.parse(container);
            return new Renderer(templates);
        }
    };

    tempo.exports = {
        'templates': Templates,
        'utils': utils
    };

    tempo.test = {
        'utils': utils,
        'templates': new Templates({}),
        'renderer': new Renderer(new Templates({}))
    };


    // Default initialisation
    try {
        tempo.init(window);
    } catch (e) {
        exports.tempo = tempo;
    }

    return tempo;

})(Tempo || {});

/*************************************************************************************************
 The MIT License (MIT)

 Copyright (c) 2015 THOMAS FORD

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

 AUTHOR: Thomas Ford
 DATE:   3/21/2015

 ------------------------------------------------------------------------------------------
 DATE:     3/23/15
 VERSION:  .1.1
 NOTE:     Added leftJoin(), avg(), and predicate for on().

 DATE:     3/26/15
 VERSION:  .1.2
 NOTE:     Minor corrections

 DATE:     3/30/15
 VERSION   .1.3
 NOTE:     Added ability to sort asc/desc on plain arrays
 concat() and union()

 DATE:     4/1/15
 VERSION:   .1.4
 NOTE:     Added support for positional for orderBy and Select on {field: #} objects

 DATE:     4/2/15
 VERSION:  .1.5
 NOTE:      Added ability to join() on() collections with simple arrays

 DATE:     4/3/15
 VESION:   .1.6
 NOTE:      Added index as 2nd parameter for .where() and .select()
 Added .not(), .in()

 DATE:     4/4/15
 VERSION   1.00
 NOTE:     Added ability to do .distinct(), .max(),. min(), .avg() on simple arrays.
 Added ability to union simple arrays.
 .in() can except multiple columns to compare to.
 If .orderBy() uses positional, then all fields ordered must be positional
 Added support for .identity() on simple arrays. When on simple arrays the value gets set to a "Value" column by default.
 Included unit tests

 DATE:     4/11/15
 VERSION   1.13
 NOTE:     Made various performance improvements.
 Added new ability to perform Full Joins using .fullJoin() <-- Only String columns, no expressions
 Added new function .skip().
 Added support for strong type comparison === and !== in .where() when using expressions.
 Fixed an issue with the .not().in() function not properly working when using multiple columns.

 DATE:     4/13/15
 VERSION   1.2a
 NOTE:     Added new function jinqJs.addPlugin() to allow extensibility. See API documentation.

 DATE:     4/13/15
 VERSION   1.3
 NOTE:     Added module jinqJs to support node.js.
 *************************************************************************************************/

var jinqJs = function (settings) {
    'use strict';

    /* Private Variables */
    var collections = [],
        result = [],
        groups = [],
        notted = false,
        identityUsed = false,
        operators = {
            LessThen: 0,
            LessThenEqual: 1,
            GreaterThen: 2,
            GreaterThenEqual: 3,
            Equal: 4,
            EqualEqualType: 5,
            NotEqual: 6,
            NotEqualEqualType: 7,
            Contains: 8
        },
        storage = {};

    jinqJs.settings = jinqJs.settings || {};

    /* Constructor Code */
    if (typeof settings !== 'undefined') {
        jinqJs.settings = settings;
    }
    else {
        jinqJs.settings = {
            includeIdentity: jinqJs.settings.includeIdentity || false
        };
    }

    /* Private Methods (no prefix) */
    var isEmpty = function (array) {
            return (typeof array === 'undefined' ||
            array.length === 0);
        },

        isArray = function (array) {
            return (hasProperty(array, 'length') && !isString(array) && !isFunction(array));
        },

        isObject = function (obj) {
            return (obj !== null && obj.constructor === Object);
        },

        isString = function (str) {
            return (str !== null && str.constructor === String);
        },

        hasProperty = function (obj, property) {
            return obj[property] !== undefined; //(typeof obj[property] !== 'undefined'); //((obj[property] || null) !== null);
        },

        isFunction = function (func) {
            return (typeof func === 'function'); //(func !== null && func.constructor === Function);
        },

        isNumber = function (value) {
            return typeof value === 'number';
        },

        arrayItemFieldValueExists = function (collection, field, value) {
            for (var index = 0; index < collection.length; index++) {
                if (collection[index][field] === value)
                    return true;
            }

            return false;
        },

        arrayFindFirstItem = function (collection, obj) {
            return arrayFindItem(collection, obj, true);
        },

        arrayFindItem = function (collection, obj, findFirst) {
            var row = null;
            var isMatch = false;
            var ret = [];
            var isObj = false;

            findFirst = findFirst || false;
            for (var index = 0; index < collection.length; index++) {

                isMatch = false;
                for (var field in obj) {

                    row = collection[index];
                    isObj = isObject(row);
                    if ((!isObj && row != obj[field]) || (isObj && row[field] != obj[field])) {
                        isMatch = false;
                        break;
                    }

                    isMatch = true;
                }

                if (isMatch) {
                    if (findFirst)
                        return row;
                    else
                        ret.push(row);
                }
            }

            return (ret.length === 0 ? null : ret);
        },

        condenseToFields = function (obj, fields) {
            var newObj = {};
            var field = null;

            for (var index = 0; index < fields.length; index++) {
                field = fields[index];

                if (hasProperty(obj, field))
                    newObj[field] = obj[field];
                else
                    newObj[field] = 0;
            }

            return newObj;
        },

        aggregator = function (args, predicate) {
            var collection = [];
            var keys = null;
            var values = null;
            var row = null;

            for (var index = 0; index < result.length; index++) {
                keys = condenseToFields(result[index], groups);
                values = condenseToFields(result[index], args);

                row = arrayFindFirstItem(collection, keys);
                if (row === null) {
                    row = {};
                    for (var keyField in keys)
                        row[keyField] = keys[keyField];

                    for (var valField in values)
                        row[valField] = predicate(row[valField], values[valField], JSON.stringify(keys) + valField);


                    collection.push(row);
                }
                else {
                    for (var vField in values) {
                        row[vField] = predicate(row[vField], result[index][vField], JSON.stringify(keys) + vField);
                    }
                }
            }

            groups = [];
            return collection;
        },

        orderByComplex = function (complexFields) {
            var complex = null;
            var prior = null;
            var field = null;
            var firstField = null;
            var secondField = null;
            var priorFirstField = null;
            var priorSecondField = null;
            var order = 1;
            var lValue = null;
            var rValue = null;
            var isNumField = false;

            for (var index = 0; index < complexFields.length; index++) {
                prior = (index > 0 ? complexFields[index - 1] : null);
                complex = complexFields[index];
                field = (hasProperty(complex, 'field') ? complex.field : null);
                order = (hasProperty(complex, 'sort') && complex.sort === 'desc' ? -1 : 1);
                isNumField = (field !== null && !isNaN(field) ? true : false);

                result.sort(function (first, second) {
                        if (isNumField) {
                            firstField = Object.keys(first)[field];
                            secondField = Object.keys(second)[field];

                            if (prior !== null) {
                                priorFirstField = Object.keys(first)[prior.field];
                                priorSecondField = Object.keys(second)[prior.field];
                            }
                        }
                        else {
                            firstField = secondField = field;

                            if (prior !== null)
                                priorFirstField = priorSecondField = prior.field;
                        }

                        lValue = (field === null ? first : (isNaN(first[firstField]) ? first[firstField] : Number(first[firstField])));
                        rValue = (field === null ? second : (isNaN(second[secondField]) ? second[secondField] : Number(second[secondField])));

                        if (lValue < rValue && (prior === null || (field === null || first[priorFirstField] == second[priorSecondField])))
                            return -1 * order;

                        if (lValue > rValue && (prior === null || (field === null || first[priorFirstField] == second[priorSecondField])))
                            return 1 * order;

                        return 0;
                    }
                );
            }
        },

        flattenCollection = function (collection) {
            //This is done for optimal performance
            switch (collection.length) {
                case 1:
                    return collection[0].concat();
                case 2:
                    return [].concat(collection[0], collection[1]);
                case 3:
                    return [].concat(collection[0], collection[1], collection[2]);
                case 4:
                    return [].concat(collection[0], collection[1], collection[2], collection[3]);
                case 5:
                    return [].concat(collection[0], collection[1], collection[2], collection[3], collection[4]);
                default:
                    var flatCollection = [];

                    for (var index = 0; index < collection.length; index++)
                        flatCollection = flatCollection.concat(collection[index]);

                    return flatCollection;
            }
        },

    /* Possible future use */
        pluckRowByMissingField = function (collection, args) {
            var ret = [];
            var bIsMissing = false;

            if (args.length === 0)
                return collection;

            for (var index = 0; index < collection.length; index++) {
                bIsMissing = false;
                for (var iArg = 0; iArg < args.length; iArg++) {
                    if (!hasProperty(collection[index], args[iArg])) {
                        bIsMissing = true;
                        break;
                    }
                }

                if (!bIsMissing)
                    ret.push(collection[index]);
            }

            return ret;
        },

        mergeObjectsFields = function (objects) {
            var obj = {};

            for (var index = 0; index < objects.length; index++) {
                for (var prop in objects[index]) {
                    obj[prop] = objects[index][prop];
                }
            }

            return obj;
        },

        convertToEmptyObject = function (obj) {
            var o = {};

            for (var field in obj)
                o[field] = '';

            return o;
        },

        convertToOperatorEnum = function (operator) {
            switch (operator) {
                case '<':
                    return operators.LessThen;
                case '>':
                    return operators.GreaterThen;
                case '!=':
                    return operators.NotEqual;
                case '!==':
                    return operators.NotEqualEqualType;
                case '=':
                case '==':
                    return operators.Equal;
                case '===':
                    return operators.EqualEqualType;
                case '<=':
                    return operators.LessThenEqual;
                case '>=':
                    return operators.GreaterThenEqual;
                case '*':
                    return operators.Contains;
                default:
                    throw 'Invalid Expression!';
            }
        },

        convertToFieldArray = function (obj) {
            var array = [];

            for (var field in obj) {
                array.push({
                    field: field
                });
            }

            return array;
        },

        isNode = function() {
            return (typeof module !== 'undefined' && typeof module.exports !== 'undefined');
        },

        onFromJoin = function (joinType, comparers) {
            var row = null;
            var ret = [];
            var matches = null;
            var collection = [];
            var startIndex = 1;

            if (!isArray(comparers) || comparers.length === 0 || collections.length === 0) return;

            switch (joinType) {
                case 'from':
                    //If we have just one pending collection then just return it, there is nothing to join it with
                    if (collections.length === 1) {
                        result = collections[0];
                        return;
                    }

                    collection = collections[0];
                    break;

                case 'full':
                case 'inner':
                case 'left':
                    collection = result;
                    startIndex = 0;
                    break;

                default:
                    return;
            }

            for (var index = startIndex; index < collections.length; index++) {
                ret = [];

                collection.forEach(function (lItem) {

                    if (isFunction(comparers[0])) {
                        matches = [];
                        collections[index].forEach(function (item) {
                                if (comparers[0](lItem, item))
                                    matches.push(item);
                            }
                        );

                        //This condition is used to handle left joins with a predicate
                        if (matches.length === 0) {
                            matches = null;
                        }
                    }
                    else {
                        row = condenseToFields(lItem, comparers);
                        matches = arrayFindItem(collections[index], row);
                    }

                    if (matches !== null) {
                        if (isString(matches[0]))
                            ret.push(lItem);
                        else {
                            matches.forEach(function (rItem) {
                                ret.push(mergeObjectsFields([rItem, lItem]));
                            });
                        }
                    }
                    else {
                        if (joinType === 'left' || joinType === 'full') {
                            if (collections[index].length > 0) {
                                //The order of merging objects is important here, right -> left
                                row = convertToEmptyObject(collections[index][0]);
                                row = mergeObjectsFields([row, lItem]);
                            }
                            ret.push(mergeObjectsFields([lItem, row]));
                        }
                    }
                });

                //Next get the elements on the right that are not in the result
                if (joinType === 'full') {
                    var z = new jinqJs().from(collections[index]).not().in(ret, comparers).select(convertToFieldArray(ret[0]));
                    ret = ret.concat(z);
                }

                collection = ret;
            }

            collections = [];
            result = ret;
        },

        joinIt = function (joinType, args) {
            if (args.length === 0) return this;

            collections = [];
            collections.func = joinType;
            for (var index = 0; index < args.length; index++) {
                if (args[index].length > 0)             //Could be a url string here or an array here. Length is ok to use either way
                    collections.push(args[index]);
            }
        },

        nodeServiceCall = function(self, url, callback){
            var http = require("http");

            http.get(url, function(response){
                var content = '';

                response.on('data', function(data){ content += data; });
                response.on('end', function() {
                    var data = JSON.parse(content);
                    var collection = null;

                    if (isArray(data))
                        collection = data;
                    else
                        collection = new Array(data);

                    collections.push(collection);
                    result = collection;

                    if (isFunction(callback))
                        callback(self);
                });
            });
        },

        browserServiceCall = function(self, url, callback){
            var xmlhttp = new XMLHttpRequest();
            var collection = null;

            if (isFunction(callback)) {
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.response.length === 0)
                        return;

                    var response = JSON.parse(xmlhttp.response);

                    if (isArray(response))
                        collection = response;
                    else
                        collection = new Array(response);

                    collections.push(collection);
                    result = collection;

                    callback(self);
                };
            }


            xmlhttp.open("GET", url, isFunction(callback));
            xmlhttp.send();

            if (!isFunction(callback)) {

                var response = JSON.parse(xmlhttp.response);

                if (isArray(response))
                    collection = response;
                else
                    collection = new Array(response);

                collections.push(collection);
            }
        };

    /* Exposed Methods (prefixed with _) */
    var _from = function () {
            var collection = null;
            var callback = null;


            if (arguments.length === 0) return this;

            result = [];
            for (var index = 0; index < arguments.length; index++) {
                if (arguments[index] === null || arguments[index].length === 0)
                    continue;

                if (arguments.length == 2 && isFunction(arguments[1])) {
                    collection = arguments[0];
                    callback = arguments[1];
                    index = arguments.length;
                }
                else {
                    collection = arguments[index];

                    //Check for a callback function we dont support asyn callbacks with multiple tables
                    if (isFunction(collection))
                        continue;
                }

                if (isString(collection)) {
                    if (!isNode())
                        browserServiceCall(this, collection, callback);
                    else
                        nodeServiceCall(this, collection, callback);
                }
                else {
                    collections.push(collection);
                }
            }

            collections.func = 'from';
            result = flattenCollection(collections);

            return (isFunction(callback) ? callback : this);
        },

        _select = function () {
            var fields = null;
            var fieldIsObject = false;
            var fieldIsPredicate = false;
            var collection = null;


            if (isEmpty(result))
                return [];

            var obj = null;
            var srcFieldName = null;
            var dstFieldName = null;
            var isSimple = false;
            var fieldDefs = null;

            if (jinqJs.settings.includeIdentity && !identityUsed) {
                _identity();
            }

            if (isEmpty(arguments)) {
                return result;
            }

            collection = new Array(result.length);

            //Check if an Array of objects is passed in as first parameter
            if (isArray(arguments[0])) {
                fields = arguments[0];
                fieldIsObject = true;
                fieldDefs = new Array(fields.length);

                for (var fIndex = 0; fIndex < fields.length; fIndex++) {
                    fieldDefs[fIndex] = {
                        hasField: hasProperty(fields[fIndex], 'field'),
                        hasText: hasProperty(fields[fIndex], 'text'),
                        hasValue: hasProperty(fields[fIndex], 'value'),
                    };
                }
            }
            else if (isFunction(arguments[0])) {
                fields = arguments[0];
                fieldIsPredicate = true;
            }
            else {
                fields = arguments;
            }

            isSimple = !isObject(result[0]);    //It cant be empty if I got here
            for (var index = 0; index < result.length; index++) {
                if (fieldIsPredicate) {
                    collection[index] = fields(result[index], index);
                }
                else {
                    obj = {};

                    for (var field = 0; field < fields.length; field++) {
                        if (fieldIsObject) {
                            if (fieldDefs[field].hasField) {
                                if (!isNumber(fields[field].field))
                                    srcFieldName = fields[field].field;
                                else
                                    srcFieldName = Object.keys(result[index])[fields[field].field];
                            }

                            dstFieldName = (fieldDefs[field].hasText ? fields[field].text : fields[field].field);
                        } else {
                            dstFieldName = srcFieldName = fields[field];
                        }

                        if (fieldIsObject && fieldDefs[field].hasValue) {
                            if (isFunction(fields[field].value))
                                obj[dstFieldName] = fields[field].value(result[index]);
                            else
                                obj[dstFieldName] = fields[field].value;
                        } else {
                            obj[dstFieldName] = (isSimple ? result[index] : (result[index][srcFieldName] || null) );
                        }
                    }

                    collection[index] = obj;
                }
            }

            return collection;
        },

        _concat = function () {
            collections.func = null;

            for (var index = 0; index < arguments.length; index++)
                result = result.concat(arguments[index]);

            return this;
        },

        _top = function (amount) {
            var totalRows = 0;

            //Check for a percentage
            if (amount > -1 && amount < 1) {
                totalRows = result.length * amount;
            }
            else
                totalRows = amount;

            if (amount < 0) {
                result = result.slice(totalRows, (result.length - Math.abs(totalRows) * -1));
            }
            else
                result = result.slice(0, totalRows);

            return this;
        },

        _bottom = function (amount) {
            _top(amount * -1);

            return this;
        },

        _where = function (predicate) {
            var collection = [];
            var isPredicateFunc = false;
            var isTruthy = false;
            var argLen = arguments.length;
            var resLen = result.length;
            var expr = new Array(argLen);
            var row = null;

            if (typeof predicate === 'undefined')
                return this;

            isPredicateFunc = isFunction(predicate);

            if (!isPredicateFunc) {
                for (var eIndex = 0; eIndex < argLen; eIndex++) {
                    var matches = arguments[eIndex].split(' ');

                    if (matches.length !== 3)
                        throw ('Invalid expression!');

                    expr[eIndex] = {
                        lField: matches[0],
                        operator: convertToOperatorEnum(matches[1]),
                        rValue: matches[2]
                    };
                }
            }

            for (var index = 0; index < resLen; index++) {
                row = result[index];

                if (isPredicateFunc) {
                    if (predicate(row, index))
                        collection.push(row);
                }
                else {
                    for (var arg = 0; arg < argLen; arg++) {
                        switch (expr[arg].operator) {
                            case operators.EqualEqualType:
                                isTruthy = (row[expr[arg].lField] === expr[arg].rValue);
                                break;

                            case operators.NotEqualEqualType:
                                isTruthy = (row[expr[arg].lField] !== expr[arg].rValue);
                                break;

                            case operators.LessThen:
                                isTruthy = (row[expr[arg].lField] < expr[arg].rValue);
                                break;

                            case operators.GreaterThen:
                                isTruthy = (row[expr[arg].lField] > expr[arg].rValue);
                                break;

                            case operators.NotEqual:
                                isTruthy = (row[expr[arg].lField] != expr[arg].rValue);
                                break;

                            case operators.Equal:
                                isTruthy = (row[expr[arg].lField] == expr[arg].rValue);
                                break;

                            case operators.LessThenEqual:
                                isTruthy = (row[expr[arg].lField] <= expr[arg].rValue);
                                break;

                            case operators.GreaterThenEqual:
                                isTruthy = (row[expr[arg].lField] >= expr[arg].rValue);
                                break;

                            case operators.Contains:
                                isTruthy = (row[expr[arg].lField].indexOf(expr[arg].rValue) > -1);
                                break;

                            default:
                                isTruthy = false;
                        }

                        if (!isTruthy)
                            break;
                    }

                    if (isTruthy)
                        collection.push(row);

                }
            }

            result = collection;

            return this;
        },

        _distinct = function () {
            var collection = [];
            var row = null;
            var field = null;
            var index = 0;
            var len = result.length;
            var collSize = 0;
            var dupp = false;

            if (arguments.length === 0) {
                if (isObject(result[0])) {
                    for (index = 0; index < len; index++) {
                        dupp = false;
                        for (var i = 0; i < collSize; i++) {
                            if (result[index] !== collection[i])
                                continue;

                            dupp = true;
                            break;
                        }

                        if (!dupp)
                            collection[collSize++] = result[index];
                    }
                }
                else {
                    var obj = {};
                    for (index = 0; index !== len; index++) {
                        row = result[index];
                        if (obj[row] !== 1) {
                            obj[row] = 1;
                            collection[collection.length] = row;
                        }
                    }
                }
            }
            else {
                for (index = 0; index < len; index++) {
                    row = condenseToFields(result[index], arguments);
                    for (var fieldIndex = 0; fieldIndex < arguments.length; fieldIndex++) {

                        field = arguments[fieldIndex];
                        if (!arrayItemFieldValueExists(collection, field, row[field])) {
                            collection.push(row);
                            break;
                        }
                    }
                }
            }

            result = collection;

            return this;
        },

        _groupBy = function () {
            groups = arguments;

            return this;
        },

        _sum = function () {
            var sum = {};

            if (groups.length === 0) {
                sum = 0;
                for (var index = 0; index < result.length; index++)
                    sum += (arguments.length === 0 ? result[index] : result[index][arguments[0]]);

                result = [sum];
            }
            else {
                result = aggregator(arguments, function (lValue, rValue, keys) {
                    var key = keys;//JSON.stringify(keys);

                    if (!hasProperty(sum, key))
                        sum[key] = 0;

                    return sum[key] += rValue;
                });
            }

            return this;
        },

        _avg = function () {
            var avg = {};

            if (groups.length === 0) {
                avg = 0;
                for (var index = 0; index < result.length; index++)
                    avg += (arguments.length === 0 ? result[index] : result[index][arguments[0]]);

                result = [avg / result.length];
            }
            else {
                result = aggregator(arguments, function (lValue, rValue, keys) {
                    var key = JSON.stringify(keys);

                    if (!hasProperty(avg, key))
                        avg[key] = { count: 0, sum: 0 };

                    avg[key].count++;
                    avg[key].sum += rValue;

                    return avg[key].sum / avg[key].count;
                });
            }

            return this;
        },

        _count = function () {
            var total = {};

            result = aggregator(arguments, function (lValue, rValue, keys) {
                var key = JSON.stringify(keys);

                if (!hasProperty(total, key))
                    total[key] = 0;

                return ++total[key];
            });

            return this;
        },

        _min = function () {
            var minValue = {};
            var value = 0;

            if (groups.length === 0) {
                minValue = -1;
                for (var index = 0; index < result.length; index++) {
                    value = (arguments.length === 0 ? Number(result[index]) : Number(result[index][arguments[0]]));
                    minValue = (value < minValue || minValue === -1 ? value : minValue);
                }

                result = [minValue];
            } else {
                result = aggregator(arguments, function (lValue, rValue, keys) {
                    var key = JSON.stringify(keys);
                    if (!hasProperty(minValue, key))
                        minValue[key] = 0;

                    if (minValue[key] === 0 || rValue < minValue[key])
                        minValue[key] = rValue;

                    return minValue[key];
                });
            }

            return this;
        },

        _max = function () {
            var maxValue = {};
            var value = 0;

            if (groups.length === 0) {
                maxValue = -1;
                for (var index = 0; index < result.length; index++) {
                    value = (arguments.length === 0 ? Number(result[index]) : Number(result[index][arguments[0]]));
                    maxValue = (value > maxValue || maxValue === -1 ? value : maxValue);
                }

                result = [maxValue];
            } else {
                result = aggregator(arguments, function (lValue, rValue, keys) {
                    var key = JSON.stringify(keys);
                    if (!hasProperty(maxValue, key))
                        maxValue[key] = 0;

                    if (rValue > maxValue[key])
                        maxValue[key] = rValue;

                    return maxValue[key];
                });
            }

            return this;
        },

        _identity = function () {
            var id = 1;
            var label = (arguments.length === 0 ? 'ID' : arguments[0]);
            var isSimple = (result.length > 0 && !isObject(result[0]));
            var ret = [];
            var obj = null;

            identityUsed = true;
            for (var index = 0; index < result.length; index++) {
                if (isSimple) {
                    obj = {};
                    obj[label] = id++;
                    obj.Value = result[index];

                    ret.push(obj);
                }
                else
                    result[index][label] = id++;
            }

            if (isSimple)
                result = ret;

            return this;
        },

        _orderBy = function () {
            var fields = arguments;

            if (arguments.length > 0 && isArray(arguments[0])) {
                orderByComplex(arguments[0]);
                return this;
            }

            result.sort(function (first, second) {
                var firstFields = JSON.stringify(condenseToFields(first, fields));
                var secondFields = JSON.stringify(condenseToFields(second, fields));

                if (firstFields < secondFields)
                    return -1;

                if (firstFields > secondFields)
                    return 1;

                return 0;   //Egual
            });

            return this;
        },

        _union = function () {
            if (arguments.length === 0 || !isArray(arguments[0]) || arguments[0].length === 0) return this;

            if (!isObject(arguments[0][0])) {
                for (var index = 0; index < arguments.length; index++)
                    _concat(arguments[index]);

                _distinct();
            }
            else {
                var collection = flattenCollection(arguments);

                _concat(collection);
                groups = [];
                for (var field in arguments[0][0])
                    groups.push(field);

                _count();
            }

            return this;
        },

        _on = function () {
            if (arguments.length === 0 || !hasProperty(collections, 'func')) return this;

            onFromJoin(collections.func, arguments);
            collections.func = null;

            return this;
        },

        _in = function () {
            var ret = [];
            var outerField = null;
            var innerField = null;
            var match = false;
            var fields = [];
            var collection = null;

            if (arguments.length === 0)
                return this;

            collection = arguments[0];
            if (collection.length === 0 || result.length === 0)
                return this;

            var isInnerSimple = !isObject(collection[0]);
            var isOuterSimple = !isObject(result[0]);

            if ((!isInnerSimple || !isOuterSimple) && arguments.length < 2)
                throw 'Invalid field or missing field!';

            if (arguments.length < 2)
                fields = [0]; //Just a dummy position holder
            else {
                if (isArray(arguments[1]))
                    fields = arguments[1];
                else {
                    for (var i = 1; i < arguments.length; i++) fields.push(arguments[i]);
                }
            }

            var matches = 0;
            for (var outer = 0; outer < result.length; outer++) {
                for (var inner = 0; inner < collection.length; inner++) {
                    matches = 0;
                    for (var index = 0; index < fields.length; index++) {
                        outerField = (isOuterSimple ? result[outer] : result[outer][fields[index]]);
                        innerField = (isInnerSimple ? collection[inner] : collection[inner][fields[index]]);

                        match = (outerField === innerField);

                        if (match)
                            matches++;
                    }

                    if (matches === fields.length)
                        break;
                }

                if ((inner < collection.length && !notted) || (inner === collection.length && notted))
                    ret.push(result[outer]);
            }

            notted = false;
            result = ret;
            return this;
        },

        _join = function () {
            joinIt('inner', arguments);

            return this;
        },

        _leftJoin = function () {
            joinIt('left', arguments);

            return this;
        },

        _fullJoin = function () {
            joinIt('full', arguments);

            return this;
        },

        _not = function () {
            notted = true;

            return this;
        },

        _skip = function () {
            var totalRows = 0;

            if (arguments.length === 0 || !isNumber(arguments[0]))
                return this;

            //Check for a percentage
            var amount = arguments[0];
            if (amount > -1 && arguments[0] < 1) {
                totalRows = result.length * amount;
            }
            else
                totalRows = amount;

            result = result.slice(totalRows);

            return this;
        };

    //Globals
    this.from = _from;
    this.select = _select;
    this.top = _top;
    this.bottom = _bottom;
    this.where = _where;
    this.distinct = _distinct;
    this.groupBy = _groupBy;
    this.sum = _sum;
    this.count = _count;
    this.min = _min;
    this.max = _max;
    this.avg = _avg;
    this.identity = _identity;
    this.orderBy = _orderBy;
    this.on = _on;
    this.join = _join;
    this.leftJoin = _leftJoin;
    this.fullJoin = _fullJoin;
    this.concat = _concat;
    this.union = _union;
    this.not = _not;
    this.in = _in;
    this.skip = _skip;
    this._x = function(name, args, plugin){
        storage[name] = storage[name] || {};
        return plugin.call(this, result, args, storage[name]);
    };
};

(function() {
    'use strict';

    jinqJs.addPlugin = function(name, plugin) {
        jinqJs.prototype[name] = function() {return this._x(name, arguments, plugin);};
    };

    //node.js
    if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
        module.exports = jinqJs;
})();
/* == jquery mousewheel plugin == Version: 3.1.12, License: MIT License (MIT) */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});
/* == malihu jquery custom scrollbar plugin == Version: 3.0.9, License: MIT License (MIT) */
!function(e){"undefined"!=typeof module&&module.exports?module.exports=e:e(jQuery,window,document)}(function(e){!function(t){var o="function"==typeof define&&define.amd,a="undefined"!=typeof module&&module.exports,n="https:"==document.location.protocol?"https:":"http:",i="cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.12/jquery.mousewheel.min.js";o||(a?require("jquery-mousewheel")(e):e.event.special.mousewheel||e("head").append(decodeURI("%3Cscript src="+n+"//"+i+"%3E%3C/script%3E"))),t()}(function(){var t,o="mCustomScrollbar",a="mCS",n=".mCustomScrollbar",i={setTop:0,setLeft:0,axis:"y",scrollbarPosition:"inside",scrollInertia:950,autoDraggerLength:!0,alwaysShowScrollbar:0,snapOffset:0,mouseWheel:{enable:!0,scrollAmount:"auto",axis:"y",deltaFactor:"auto",disableOver:["select","option","keygen","datalist","textarea"]},scrollButtons:{scrollType:"stepless",scrollAmount:"auto"},keyboard:{enable:!0,scrollType:"stepless",scrollAmount:"auto"},contentTouchScroll:25,advanced:{autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",updateOnContentResize:!0,updateOnImageLoad:!0,autoUpdateTimeout:60},theme:"light",callbacks:{onTotalScrollOffset:0,onTotalScrollBackOffset:0,alwaysTriggerOffsets:!0}},r=0,l={},s=window.attachEvent&&!window.addEventListener?1:0,c=!1,d=["mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar","mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer","mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight"],u={init:function(t){var t=e.extend(!0,{},i,t),o=f.call(this);if(t.live){var s=t.liveSelector||this.selector||n,c=e(s);if("off"===t.live)return void m(s);l[s]=setTimeout(function(){c.mCustomScrollbar(t),"once"===t.live&&c.length&&m(s)},500)}else m(s);return t.setWidth=t.set_width?t.set_width:t.setWidth,t.setHeight=t.set_height?t.set_height:t.setHeight,t.axis=t.horizontalScroll?"x":p(t.axis),t.scrollInertia=t.scrollInertia>0&&t.scrollInertia<17?17:t.scrollInertia,"object"!=typeof t.mouseWheel&&1==t.mouseWheel&&(t.mouseWheel={enable:!0,scrollAmount:"auto",axis:"y",preventDefault:!1,deltaFactor:"auto",normalizeDelta:!1,invert:!1}),t.mouseWheel.scrollAmount=t.mouseWheelPixels?t.mouseWheelPixels:t.mouseWheel.scrollAmount,t.mouseWheel.normalizeDelta=t.advanced.normalizeMouseWheelDelta?t.advanced.normalizeMouseWheelDelta:t.mouseWheel.normalizeDelta,t.scrollButtons.scrollType=g(t.scrollButtons.scrollType),h(t),e(o).each(function(){var o=e(this);if(!o.data(a)){o.data(a,{idx:++r,opt:t,scrollRatio:{y:null,x:null},overflowed:null,contentReset:{y:null,x:null},bindEvents:!1,tweenRunning:!1,sequential:{},langDir:o.css("direction"),cbOffsets:null,trigger:null});var n=o.data(a),i=n.opt,l=o.data("mcs-axis"),s=o.data("mcs-scrollbar-position"),c=o.data("mcs-theme");l&&(i.axis=l),s&&(i.scrollbarPosition=s),c&&(i.theme=c,h(i)),v.call(this),e("#mCSB_"+n.idx+"_container img:not(."+d[2]+")").addClass(d[2]),u.update.call(null,o)}})},update:function(t,o){var n=t||f.call(this);return e(n).each(function(){var t=e(this);if(t.data(a)){var n=t.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container"),l=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];if(!r.length)return;n.tweenRunning&&V(t),t.hasClass(d[3])&&t.removeClass(d[3]),t.hasClass(d[4])&&t.removeClass(d[4]),S.call(this),_.call(this),"y"===i.axis||i.advanced.autoExpandHorizontalScroll||r.css("width",x(r.children())),n.overflowed=B.call(this),O.call(this),i.autoDraggerLength&&b.call(this),C.call(this),k.call(this);var s=[Math.abs(r[0].offsetTop),Math.abs(r[0].offsetLeft)];"x"!==i.axis&&(n.overflowed[0]?l[0].height()>l[0].parent().height()?T.call(this):(Q(t,s[0].toString(),{dir:"y",dur:0,overwrite:"none"}),n.contentReset.y=null):(T.call(this),"y"===i.axis?M.call(this):"yx"===i.axis&&n.overflowed[1]&&Q(t,s[1].toString(),{dir:"x",dur:0,overwrite:"none"}))),"y"!==i.axis&&(n.overflowed[1]?l[1].width()>l[1].parent().width()?T.call(this):(Q(t,s[1].toString(),{dir:"x",dur:0,overwrite:"none"}),n.contentReset.x=null):(T.call(this),"x"===i.axis?M.call(this):"yx"===i.axis&&n.overflowed[0]&&Q(t,s[0].toString(),{dir:"y",dur:0,overwrite:"none"}))),o&&n&&(2===o&&i.callbacks.onImageLoad&&"function"==typeof i.callbacks.onImageLoad?i.callbacks.onImageLoad.call(this):3===o&&i.callbacks.onSelectorChange&&"function"==typeof i.callbacks.onSelectorChange?i.callbacks.onSelectorChange.call(this):i.callbacks.onUpdate&&"function"==typeof i.callbacks.onUpdate&&i.callbacks.onUpdate.call(this)),X.call(this)}})},scrollTo:function(t,o){if("undefined"!=typeof t&&null!=t){var n=f.call(this);return e(n).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l={trigger:"external",scrollInertia:r.scrollInertia,scrollEasing:"mcsEaseInOut",moveDragger:!1,timeout:60,callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},s=e.extend(!0,{},l,o),c=Y.call(this,t),d=s.scrollInertia>0&&s.scrollInertia<17?17:s.scrollInertia;c[0]=j.call(this,c[0],"y"),c[1]=j.call(this,c[1],"x"),s.moveDragger&&(c[0]*=i.scrollRatio.y,c[1]*=i.scrollRatio.x),s.dur=d,setTimeout(function(){null!==c[0]&&"undefined"!=typeof c[0]&&"x"!==r.axis&&i.overflowed[0]&&(s.dir="y",s.overwrite="all",Q(n,c[0].toString(),s)),null!==c[1]&&"undefined"!=typeof c[1]&&"y"!==r.axis&&i.overflowed[1]&&(s.dir="x",s.overwrite="none",Q(n,c[1].toString(),s))},s.timeout)}})}},stop:function(){var t=f.call(this);return e(t).each(function(){var t=e(this);t.data(a)&&V(t)})},disable:function(t){var o=f.call(this);return e(o).each(function(){var o=e(this);if(o.data(a)){{o.data(a)}X.call(this,"remove"),M.call(this),t&&T.call(this),O.call(this,!0),o.addClass(d[3])}})},destroy:function(){var t=f.call(this);return e(t).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx),s=e("#mCSB_"+i.idx+"_container"),c=e(".mCSB_"+i.idx+"_scrollbar");r.live&&m(r.liveSelector||e(t).selector),X.call(this,"remove"),M.call(this),T.call(this),n.removeData(a),Z(this,"mcs"),c.remove(),s.find("img."+d[2]).removeClass(d[2]),l.replaceWith(s.contents()),n.removeClass(o+" _"+a+"_"+i.idx+" "+d[6]+" "+d[7]+" "+d[5]+" "+d[3]).addClass(d[4])}})}},f=function(){return"object"!=typeof e(this)||e(this).length<1?n:this},h=function(t){var o=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"],a=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"],n=["minimal","minimal-dark"],i=["minimal","minimal-dark"],r=["minimal","minimal-dark"];t.autoDraggerLength=e.inArray(t.theme,o)>-1?!1:t.autoDraggerLength,t.autoExpandScrollbar=e.inArray(t.theme,a)>-1?!1:t.autoExpandScrollbar,t.scrollButtons.enable=e.inArray(t.theme,n)>-1?!1:t.scrollButtons.enable,t.autoHideScrollbar=e.inArray(t.theme,i)>-1?!0:t.autoHideScrollbar,t.scrollbarPosition=e.inArray(t.theme,r)>-1?"outside":t.scrollbarPosition},m=function(e){l[e]&&(clearTimeout(l[e]),Z(l,e))},p=function(e){return"yx"===e||"xy"===e||"auto"===e?"yx":"x"===e||"horizontal"===e?"x":"y"},g=function(e){return"stepped"===e||"pixels"===e||"step"===e||"click"===e?"stepped":"stepless"},v=function(){var t=e(this),n=t.data(a),i=n.opt,r=i.autoExpandScrollbar?" "+d[1]+"_expand":"",l=["<div id='mCSB_"+n.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+n.idx+"_scrollbar mCS-"+i.theme+" mCSB_scrollTools_vertical"+r+"'><div class='"+d[12]+"'><div id='mCSB_"+n.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>","<div id='mCSB_"+n.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+n.idx+"_scrollbar mCS-"+i.theme+" mCSB_scrollTools_horizontal"+r+"'><div class='"+d[12]+"'><div id='mCSB_"+n.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"],s="yx"===i.axis?"mCSB_vertical_horizontal":"x"===i.axis?"mCSB_horizontal":"mCSB_vertical",c="yx"===i.axis?l[0]+l[1]:"x"===i.axis?l[1]:l[0],u="yx"===i.axis?"<div id='mCSB_"+n.idx+"_container_wrapper' class='mCSB_container_wrapper' />":"",f=i.autoHideScrollbar?" "+d[6]:"",h="x"!==i.axis&&"rtl"===n.langDir?" "+d[7]:"";i.setWidth&&t.css("width",i.setWidth),i.setHeight&&t.css("height",i.setHeight),i.setLeft="y"!==i.axis&&"rtl"===n.langDir?"989999px":i.setLeft,t.addClass(o+" _"+a+"_"+n.idx+f+h).wrapInner("<div id='mCSB_"+n.idx+"' class='mCustomScrollBox mCS-"+i.theme+" "+s+"'><div id='mCSB_"+n.idx+"_container' class='mCSB_container' style='position:relative; top:"+i.setTop+"; left:"+i.setLeft+";' dir="+n.langDir+" /></div>");var m=e("#mCSB_"+n.idx),p=e("#mCSB_"+n.idx+"_container");"y"===i.axis||i.advanced.autoExpandHorizontalScroll||p.css("width",x(p.children())),"outside"===i.scrollbarPosition?("static"===t.css("position")&&t.css("position","relative"),t.css("overflow","visible"),m.addClass("mCSB_outside").after(c)):(m.addClass("mCSB_inside").append(c),p.wrap(u)),w.call(this);var g=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];g[0].css("min-height",g[0].height()),g[1].css("min-width",g[1].width())},x=function(t){return Math.max.apply(Math,t.map(function(){return e(this).outerWidth(!0)}).get())},_=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx+"_container");n.advanced.autoExpandHorizontalScroll&&"y"!==n.axis&&i.css({position:"absolute",width:"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:Math.ceil(i[0].getBoundingClientRect().right+.4)-Math.floor(i[0].getBoundingClientRect().left),position:"relative"}).unwrap()},w=function(){var t=e(this),o=t.data(a),n=o.opt,i=e(".mCSB_"+o.idx+"_scrollbar:first"),r=te(n.scrollButtons.tabindex)?"tabindex='"+n.scrollButtons.tabindex+"'":"",l=["<a href='#' class='"+d[13]+"' oncontextmenu='return false;' "+r+" />","<a href='#' class='"+d[14]+"' oncontextmenu='return false;' "+r+" />","<a href='#' class='"+d[15]+"' oncontextmenu='return false;' "+r+" />","<a href='#' class='"+d[16]+"' oncontextmenu='return false;' "+r+" />"],s=["x"===n.axis?l[2]:l[0],"x"===n.axis?l[3]:l[1],l[2],l[3]];n.scrollButtons.enable&&i.prepend(s[0]).append(s[1]).next(".mCSB_scrollTools").prepend(s[2]).append(s[3])},S=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=t.css("max-height")||"none",r=-1!==i.indexOf("%"),l=t.css("box-sizing");if("none"!==i){var s=r?t.parent().height()*parseInt(i)/100:parseInt(i);"border-box"===l&&(s-=t.innerHeight()-t.height()+(t.outerHeight()-t.innerHeight())),n.css("max-height",Math.round(s))}},b=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[n.height()/i.outerHeight(!1),n.width()/i.outerWidth(!1)],c=[parseInt(r[0].css("min-height")),Math.round(l[0]*r[0].parent().height()),parseInt(r[1].css("min-width")),Math.round(l[1]*r[1].parent().width())],d=s&&c[1]<c[0]?c[0]:c[1],u=s&&c[3]<c[2]?c[2]:c[3];r[0].css({height:d,"max-height":r[0].parent().height()-10}).find(".mCSB_dragger_bar").css({"line-height":c[0]+"px"}),r[1].css({width:u,"max-width":r[1].parent().width()-10})},C=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[i.outerHeight(!1)-n.height(),i.outerWidth(!1)-n.width()],s=[l[0]/(r[0].parent().height()-r[0].height()),l[1]/(r[1].parent().width()-r[1].width())];o.scrollRatio={y:s[0],x:s[1]}},y=function(e,t,o){var a=o?d[0]+"_expanded":"",n=e.closest(".mCSB_scrollTools");"active"===t?(e.toggleClass(d[0]+" "+a),n.toggleClass(d[1]),e[0]._draggable=e[0]._draggable?0:1):e[0]._draggable||("hide"===t?(e.removeClass(d[0]),n.removeClass(d[1])):(e.addClass(d[0]),n.addClass(d[1])))},B=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=null==o.overflowed?i.height():i.outerHeight(!1),l=null==o.overflowed?i.width():i.outerWidth(!1);return[r>n.height(),l>n.width()]},T=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx),r=e("#mCSB_"+o.idx+"_container"),l=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")];if(V(t),("x"!==n.axis&&!o.overflowed[0]||"y"===n.axis&&o.overflowed[0])&&(l[0].add(r).css("top",0),Q(t,"_resetY")),"y"!==n.axis&&!o.overflowed[1]||"x"===n.axis&&o.overflowed[1]){var s=dx=0;"rtl"===o.langDir&&(s=i.width()-r.outerWidth(!1),dx=Math.abs(s/o.scrollRatio.x)),r.css("left",s),l[1].css("left",dx),Q(t,"_resetX")}},k=function(){function t(){r=setTimeout(function(){e.event.special.mousewheel?(clearTimeout(r),W.call(o[0])):t()},100)}var o=e(this),n=o.data(a),i=n.opt;if(!n.bindEvents){if(R.call(this),i.contentTouchScroll&&D.call(this),E.call(this),i.mouseWheel.enable){var r;t()}P.call(this),H.call(this),i.advanced.autoScrollOnFocus&&z.call(this),i.scrollButtons.enable&&U.call(this),i.keyboard.enable&&F.call(this),n.bindEvents=!0}},M=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=".mCSB_"+o.idx+"_scrollbar",l=e("#mCSB_"+o.idx+",#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,"+r+" ."+d[12]+",#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal,"+r+">a"),s=e("#mCSB_"+o.idx+"_container");n.advanced.releaseDraggableSelectors&&l.add(e(n.advanced.releaseDraggableSelectors)),o.bindEvents&&(e(document).unbind("."+i),l.each(function(){e(this).unbind("."+i)}),clearTimeout(t[0]._focusTimeout),Z(t[0],"_focusTimeout"),clearTimeout(o.sequential.step),Z(o.sequential,"step"),clearTimeout(s[0].onCompleteTimeout),Z(s[0],"onCompleteTimeout"),o.bindEvents=!1)},O=function(t){var o=e(this),n=o.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container_wrapper"),l=r.length?r:e("#mCSB_"+n.idx+"_container"),s=[e("#mCSB_"+n.idx+"_scrollbar_vertical"),e("#mCSB_"+n.idx+"_scrollbar_horizontal")],c=[s[0].find(".mCSB_dragger"),s[1].find(".mCSB_dragger")];"x"!==i.axis&&(n.overflowed[0]&&!t?(s[0].add(c[0]).add(s[0].children("a")).css("display","block"),l.removeClass(d[8]+" "+d[10])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[0].css("display","none"),l.removeClass(d[10])):(s[0].css("display","none"),l.addClass(d[10])),l.addClass(d[8]))),"y"!==i.axis&&(n.overflowed[1]&&!t?(s[1].add(c[1]).add(s[1].children("a")).css("display","block"),l.removeClass(d[9]+" "+d[11])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[1].css("display","none"),l.removeClass(d[11])):(s[1].css("display","none"),l.addClass(d[11])),l.addClass(d[9]))),n.overflowed[0]||n.overflowed[1]?o.removeClass(d[5]):o.addClass(d[5])},I=function(e){var t=e.type;switch(t){case"pointerdown":case"MSPointerDown":case"pointermove":case"MSPointerMove":case"pointerup":case"MSPointerUp":return e.target.ownerDocument!==document?[e.originalEvent.screenY,e.originalEvent.screenX,!1]:[e.originalEvent.pageY,e.originalEvent.pageX,!1];case"touchstart":case"touchmove":case"touchend":var o=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0],a=e.originalEvent.touches.length||e.originalEvent.changedTouches.length;return e.target.ownerDocument!==document?[o.screenY,o.screenX,a>1]:[o.pageY,o.pageX,a>1];default:return[e.pageY,e.pageX,!1]}},R=function(){function t(e){var t=m.find("iframe");if(t.length){var o=e?"auto":"none";t.css("pointer-events",o)}}function o(e,t,o,a){if(m[0].idleTimer=u.scrollInertia<233?250:0,n.attr("id")===h[1])var i="x",r=(n[0].offsetLeft-t+a)*d.scrollRatio.x;else var i="y",r=(n[0].offsetTop-e+o)*d.scrollRatio.y;Q(l,r.toString(),{dir:i,drag:!0})}var n,i,r,l=e(this),d=l.data(a),u=d.opt,f=a+"_"+d.idx,h=["mCSB_"+d.idx+"_dragger_vertical","mCSB_"+d.idx+"_dragger_horizontal"],m=e("#mCSB_"+d.idx+"_container"),p=e("#"+h[0]+",#"+h[1]),g=u.advanced.releaseDraggableSelectors?p.add(e(u.advanced.releaseDraggableSelectors)):p;p.bind("mousedown."+f+" touchstart."+f+" pointerdown."+f+" MSPointerDown."+f,function(o){if(o.stopImmediatePropagation(),o.preventDefault(),$(o)){c=!0,s&&(document.onselectstart=function(){return!1}),t(!1),V(l),n=e(this);var a=n.offset(),d=I(o)[0]-a.top,f=I(o)[1]-a.left,h=n.height()+a.top,m=n.width()+a.left;h>d&&d>0&&m>f&&f>0&&(i=d,r=f),y(n,"active",u.autoExpandScrollbar)}}).bind("touchmove."+f,function(e){e.stopImmediatePropagation(),e.preventDefault();var t=n.offset(),a=I(e)[0]-t.top,l=I(e)[1]-t.left;o(i,r,a,l)}),e(document).bind("mousemove."+f+" pointermove."+f+" MSPointerMove."+f,function(e){if(n){var t=n.offset(),a=I(e)[0]-t.top,l=I(e)[1]-t.left;if(i===a)return;o(i,r,a,l)}}).add(g).bind("mouseup."+f+" touchend."+f+" pointerup."+f+" MSPointerUp."+f,function(e){n&&(y(n,"active",u.autoExpandScrollbar),n=null),c=!1,s&&(document.onselectstart=null),t(!0)})},D=function(){function o(e){if(!ee(e)||c||I(e)[2])return void(t=0);t=1,S=0,b=0,C.removeClass("mCS_touch_action");var o=M.offset();d=I(e)[0]-o.top,u=I(e)[1]-o.left,A=[I(e)[0],I(e)[1]]}function n(e){if(ee(e)&&!c&&!I(e)[2]&&(e.stopImmediatePropagation(),!b||S)){p=J();var t=k.offset(),o=I(e)[0]-t.top,a=I(e)[1]-t.left,n="mcsLinearOut";if(R.push(o),D.push(a),A[2]=Math.abs(I(e)[0]-A[0]),A[3]=Math.abs(I(e)[1]-A[1]),y.overflowed[0])var i=O[0].parent().height()-O[0].height(),r=d-o>0&&o-d>-(i*y.scrollRatio.y)&&(2*A[3]<A[2]||"yx"===B.axis);if(y.overflowed[1])var l=O[1].parent().width()-O[1].width(),f=u-a>0&&a-u>-(l*y.scrollRatio.x)&&(2*A[2]<A[3]||"yx"===B.axis);r||f?(e.preventDefault(),S=1):(b=1,C.addClass("mCS_touch_action")),_="yx"===B.axis?[d-o,u-a]:"x"===B.axis?[null,u-a]:[d-o,null],M[0].idleTimer=250,y.overflowed[0]&&s(_[0],E,n,"y","all",!0),y.overflowed[1]&&s(_[1],E,n,"x",W,!0)}}function i(e){if(!ee(e)||c||I(e)[2])return void(t=0);t=1,e.stopImmediatePropagation(),V(C),m=J();var o=k.offset();f=I(e)[0]-o.top,h=I(e)[1]-o.left,R=[],D=[]}function r(e){if(ee(e)&&!c&&!I(e)[2]){e.stopImmediatePropagation(),S=0,b=0,g=J();var t=k.offset(),o=I(e)[0]-t.top,a=I(e)[1]-t.left;if(!(g-p>30)){x=1e3/(g-m);var n="mcsEaseOut",i=2.5>x,r=i?[R[R.length-2],D[D.length-2]]:[0,0];v=i?[o-r[0],a-r[1]]:[o-f,a-h];var d=[Math.abs(v[0]),Math.abs(v[1])];x=i?[Math.abs(v[0]/4),Math.abs(v[1]/4)]:[x,x];var u=[Math.abs(M[0].offsetTop)-v[0]*l(d[0]/x[0],x[0]),Math.abs(M[0].offsetLeft)-v[1]*l(d[1]/x[1],x[1])];_="yx"===B.axis?[u[0],u[1]]:"x"===B.axis?[null,u[1]]:[u[0],null],w=[4*d[0]+B.scrollInertia,4*d[1]+B.scrollInertia];var C=parseInt(B.contentTouchScroll)||0;_[0]=d[0]>C?_[0]:0,_[1]=d[1]>C?_[1]:0,y.overflowed[0]&&s(_[0],w[0],n,"y",W,!1),y.overflowed[1]&&s(_[1],w[1],n,"x",W,!1)}}}function l(e,t){var o=[1.5*t,2*t,t/1.5,t/2];return e>90?t>4?o[0]:o[3]:e>60?t>3?o[3]:o[2]:e>30?t>8?o[1]:t>6?o[0]:t>4?t:o[2]:t>8?t:o[3]}function s(e,t,o,a,n,i){e&&Q(C,e.toString(),{dur:t,scrollEasing:o,dir:a,overwrite:n,drag:i})}var d,u,f,h,m,p,g,v,x,_,w,S,b,C=e(this),y=C.data(a),B=y.opt,T=a+"_"+y.idx,k=e("#mCSB_"+y.idx),M=e("#mCSB_"+y.idx+"_container"),O=[e("#mCSB_"+y.idx+"_dragger_vertical"),e("#mCSB_"+y.idx+"_dragger_horizontal")],R=[],D=[],E=0,W="yx"===B.axis?"none":"all",A=[],P=M.find("iframe"),z=["touchstart."+T+" pointerdown."+T+" MSPointerDown."+T,"touchmove."+T+" pointermove."+T+" MSPointerMove."+T,"touchend."+T+" pointerup."+T+" MSPointerUp."+T];M.bind(z[0],function(e){o(e)}).bind(z[1],function(e){n(e)}),k.bind(z[0],function(e){i(e)}).bind(z[2],function(e){r(e)}),P.length&&P.each(function(){e(this).load(function(){L(this)&&e(this.contentDocument||this.contentWindow.document).bind(z[0],function(e){o(e),i(e)}).bind(z[1],function(e){n(e)}).bind(z[2],function(e){r(e)})})})},E=function(){function o(){return window.getSelection?window.getSelection().toString():document.selection&&"Control"!=document.selection.type?document.selection.createRange().text:0}function n(e,t,o){d.type=o&&i?"stepped":"stepless",d.scrollAmount=10,q(r,e,t,"mcsLinearOut",o?60:null)}var i,r=e(this),l=r.data(a),s=l.opt,d=l.sequential,u=a+"_"+l.idx,f=e("#mCSB_"+l.idx+"_container"),h=f.parent();f.bind("mousedown."+u,function(e){t||i||(i=1,c=!0)}).add(document).bind("mousemove."+u,function(e){if(!t&&i&&o()){var a=f.offset(),r=I(e)[0]-a.top+f[0].offsetTop,c=I(e)[1]-a.left+f[0].offsetLeft;r>0&&r<h.height()&&c>0&&c<h.width()?d.step&&n("off",null,"stepped"):("x"!==s.axis&&l.overflowed[0]&&(0>r?n("on",38):r>h.height()&&n("on",40)),"y"!==s.axis&&l.overflowed[1]&&(0>c?n("on",37):c>h.width()&&n("on",39)))}}).bind("mouseup."+u,function(e){t||(i&&(i=0,n("off",null)),c=!1)})},W=function(){function t(t,a){if(V(o),!A(o,t.target)){var r="auto"!==i.mouseWheel.deltaFactor?parseInt(i.mouseWheel.deltaFactor):s&&t.deltaFactor<100?100:t.deltaFactor||100;if("x"===i.axis||"x"===i.mouseWheel.axis)var d="x",u=[Math.round(r*n.scrollRatio.x),parseInt(i.mouseWheel.scrollAmount)],f="auto"!==i.mouseWheel.scrollAmount?u[1]:u[0]>=l.width()?.9*l.width():u[0],h=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetLeft),m=c[1][0].offsetLeft,p=c[1].parent().width()-c[1].width(),g=t.deltaX||t.deltaY||a;else var d="y",u=[Math.round(r*n.scrollRatio.y),parseInt(i.mouseWheel.scrollAmount)],f="auto"!==i.mouseWheel.scrollAmount?u[1]:u[0]>=l.height()?.9*l.height():u[0],h=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetTop),m=c[0][0].offsetTop,p=c[0].parent().height()-c[0].height(),g=t.deltaY||a;"y"===d&&!n.overflowed[0]||"x"===d&&!n.overflowed[1]||((i.mouseWheel.invert||t.webkitDirectionInvertedFromDevice)&&(g=-g),i.mouseWheel.normalizeDelta&&(g=0>g?-1:1),(g>0&&0!==m||0>g&&m!==p||i.mouseWheel.preventDefault)&&(t.stopImmediatePropagation(),t.preventDefault()),Q(o,(h-g*f).toString(),{dir:d}))}}if(e(this).data(a)){var o=e(this),n=o.data(a),i=n.opt,r=a+"_"+n.idx,l=e("#mCSB_"+n.idx),c=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")],d=e("#mCSB_"+n.idx+"_container").find("iframe");d.length&&d.each(function(){e(this).load(function(){L(this)&&e(this.contentDocument||this.contentWindow.document).bind("mousewheel."+r,function(e,o){t(e,o)})})}),l.bind("mousewheel."+r,function(e,o){t(e,o)})}},L=function(e){var t=null;try{var o=e.contentDocument||e.contentWindow.document;t=o.body.innerHTML}catch(a){}return null!==t},A=function(t,o){var n=o.nodeName.toLowerCase(),i=t.data(a).opt.mouseWheel.disableOver,r=["select","textarea"];return e.inArray(n,i)>-1&&!(e.inArray(n,r)>-1&&!e(o).is(":focus"))},P=function(){var t=e(this),o=t.data(a),n=a+"_"+o.idx,i=e("#mCSB_"+o.idx+"_container"),r=i.parent(),l=e(".mCSB_"+o.idx+"_scrollbar ."+d[12]);l.bind("touchstart."+n+" pointerdown."+n+" MSPointerDown."+n,function(e){c=!0}).bind("touchend."+n+" pointerup."+n+" MSPointerUp."+n,function(e){c=!1}).bind("click."+n,function(a){if(e(a.target).hasClass(d[12])||e(a.target).hasClass("mCSB_draggerRail")){V(t);var n=e(this),l=n.find(".mCSB_dragger");if(n.parent(".mCSB_scrollTools_horizontal").length>0){if(!o.overflowed[1])return;var s="x",c=a.pageX>l.offset().left?-1:1,u=Math.abs(i[0].offsetLeft)-.9*c*r.width()}else{if(!o.overflowed[0])return;var s="y",c=a.pageY>l.offset().top?-1:1,u=Math.abs(i[0].offsetTop)-.9*c*r.height()}Q(t,u.toString(),{dir:s,scrollEasing:"mcsEaseInOut"})}})},z=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=e("#mCSB_"+o.idx+"_container"),l=r.parent();r.bind("focusin."+i,function(o){var a=e(document.activeElement),i=r.find(".mCustomScrollBox").length,s=0;a.is(n.advanced.autoScrollOnFocus)&&(V(t),clearTimeout(t[0]._focusTimeout),t[0]._focusTimer=i?(s+17)*i:0,t[0]._focusTimeout=setTimeout(function(){var e=[oe(a)[0],oe(a)[1]],o=[r[0].offsetTop,r[0].offsetLeft],i=[o[0]+e[0]>=0&&o[0]+e[0]<l.height()-a.outerHeight(!1),o[1]+e[1]>=0&&o[0]+e[1]<l.width()-a.outerWidth(!1)],c="yx"!==n.axis||i[0]||i[1]?"all":"none";"x"===n.axis||i[0]||Q(t,e[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:c,dur:s}),"y"===n.axis||i[1]||Q(t,e[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:c,dur:s})},t[0]._focusTimer))})},H=function(){var t=e(this),o=t.data(a),n=a+"_"+o.idx,i=e("#mCSB_"+o.idx+"_container").parent();i.bind("scroll."+n,function(t){(0!==i.scrollTop()||0!==i.scrollLeft())&&e(".mCSB_"+o.idx+"_scrollbar").css("visibility","hidden")})},U=function(){var t=e(this),o=t.data(a),n=o.opt,i=o.sequential,r=a+"_"+o.idx,l=".mCSB_"+o.idx+"_scrollbar",s=e(l+">a");s.bind("mousedown."+r+" touchstart."+r+" pointerdown."+r+" MSPointerDown."+r+" mouseup."+r+" touchend."+r+" pointerup."+r+" MSPointerUp."+r+" mouseout."+r+" pointerout."+r+" MSPointerOut."+r+" click."+r,function(a){function r(e,o){i.scrollAmount=n.snapAmount||n.scrollButtons.scrollAmount,q(t,e,o)}if(a.preventDefault(),$(a)){var l=e(this).attr("class");switch(i.type=n.scrollButtons.scrollType,a.type){case"mousedown":case"touchstart":case"pointerdown":case"MSPointerDown":if("stepped"===i.type)return;c=!0,o.tweenRunning=!1,r("on",l);break;case"mouseup":case"touchend":case"pointerup":case"MSPointerUp":case"mouseout":case"pointerout":case"MSPointerOut":if("stepped"===i.type)return;c=!1,i.dir&&r("off",l);break;case"click":if("stepped"!==i.type||o.tweenRunning)return;r("on",l)}}})},F=function(){function t(t){function a(e,t){r.type=i.keyboard.scrollType,r.scrollAmount=i.snapAmount||i.keyboard.scrollAmount,"stepped"===r.type&&n.tweenRunning||q(o,e,t)}switch(t.type){case"blur":n.tweenRunning&&r.dir&&a("off",null);break;case"keydown":case"keyup":var l=t.keyCode?t.keyCode:t.which,s="on";if("x"!==i.axis&&(38===l||40===l)||"y"!==i.axis&&(37===l||39===l)){if((38===l||40===l)&&!n.overflowed[0]||(37===l||39===l)&&!n.overflowed[1])return;"keyup"===t.type&&(s="off"),e(document.activeElement).is(u)||(t.preventDefault(),t.stopImmediatePropagation(),a(s,l))}else if(33===l||34===l){if((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type){V(o);var f=34===l?-1:1;if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=Math.abs(c[0].offsetLeft)-.9*f*d.width();else var h="y",m=Math.abs(c[0].offsetTop)-.9*f*d.height();Q(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}else if((35===l||36===l)&&!e(document.activeElement).is(u)&&((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type)){if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=35===l?Math.abs(d.width()-c.outerWidth(!1)):0;else var h="y",m=35===l?Math.abs(d.height()-c.outerHeight(!1)):0;Q(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}}var o=e(this),n=o.data(a),i=n.opt,r=n.sequential,l=a+"_"+n.idx,s=e("#mCSB_"+n.idx),c=e("#mCSB_"+n.idx+"_container"),d=c.parent(),u="input,textarea,select,datalist,keygen,[contenteditable='true']",f=c.find("iframe"),h=["blur."+l+" keydown."+l+" keyup."+l];f.length&&f.each(function(){e(this).load(function(){L(this)&&e(this.contentDocument||this.contentWindow.document).bind(h[0],function(e){t(e)})})}),s.attr("tabindex","0").bind(h[0],function(e){t(e)})},q=function(t,o,n,i,r){function l(e){var o="stepped"!==f.type,a=r?r:e?o?p/1.5:g:1e3/60,n=e?o?7.5:40:2.5,s=[Math.abs(h[0].offsetTop),Math.abs(h[0].offsetLeft)],d=[c.scrollRatio.y>10?10:c.scrollRatio.y,c.scrollRatio.x>10?10:c.scrollRatio.x],u="x"===f.dir[0]?s[1]+f.dir[1]*d[1]*n:s[0]+f.dir[1]*d[0]*n,m="x"===f.dir[0]?s[1]+f.dir[1]*parseInt(f.scrollAmount):s[0]+f.dir[1]*parseInt(f.scrollAmount),v="auto"!==f.scrollAmount?m:u,x=i?i:e?o?"mcsLinearOut":"mcsEaseInOut":"mcsLinear",_=e?!0:!1;return e&&17>a&&(v="x"===f.dir[0]?s[1]:s[0]),Q(t,v.toString(),{dir:f.dir[0],scrollEasing:x,dur:a,onComplete:_}),e?void(f.dir=!1):(clearTimeout(f.step),void(f.step=setTimeout(function(){l()},a)))}function s(){clearTimeout(f.step),Z(f,"step"),V(t)}var c=t.data(a),u=c.opt,f=c.sequential,h=e("#mCSB_"+c.idx+"_container"),m="stepped"===f.type?!0:!1,p=u.scrollInertia<26?26:u.scrollInertia,g=u.scrollInertia<1?17:u.scrollInertia;switch(o){case"on":if(f.dir=[n===d[16]||n===d[15]||39===n||37===n?"x":"y",n===d[13]||n===d[15]||38===n||37===n?-1:1],V(t),te(n)&&"stepped"===f.type)return;l(m);break;case"off":s(),(m||c.tweenRunning&&f.dir)&&l(!0)}},Y=function(t){var o=e(this).data(a).opt,n=[];return"function"==typeof t&&(t=t()),t instanceof Array?n=t.length>1?[t[0],t[1]]:"x"===o.axis?[null,t[0]]:[t[0],null]:(n[0]=t.y?t.y:t.x||"x"===o.axis?null:t,n[1]=t.x?t.x:t.y||"y"===o.axis?null:t),"function"==typeof n[0]&&(n[0]=n[0]()),"function"==typeof n[1]&&(n[1]=n[1]()),n},j=function(t,o){if(null!=t&&"undefined"!=typeof t){var n=e(this),i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx+"_container"),s=l.parent(),c=typeof t;o||(o="x"===r.axis?"x":"y");var d="x"===o?l.outerWidth(!1):l.outerHeight(!1),f="x"===o?l[0].offsetLeft:l[0].offsetTop,h="x"===o?"left":"top";switch(c){case"function":return t();case"object":var m=t.jquery?t:e(t);if(!m.length)return;return"x"===o?oe(m)[1]:oe(m)[0];case"string":case"number":if(te(t))return Math.abs(t);if(-1!==t.indexOf("%"))return Math.abs(d*parseInt(t)/100);if(-1!==t.indexOf("-="))return Math.abs(f-parseInt(t.split("-=")[1]));if(-1!==t.indexOf("+=")){var p=f+parseInt(t.split("+=")[1]);return p>=0?0:Math.abs(p)}if(-1!==t.indexOf("px")&&te(t.split("px")[0]))return Math.abs(t.split("px")[0]);if("top"===t||"left"===t)return 0;if("bottom"===t)return Math.abs(s.height()-l.outerHeight(!1));if("right"===t)return Math.abs(s.width()-l.outerWidth(!1));if("first"===t||"last"===t){var m=l.find(":"+t);return"x"===o?oe(m)[1]:oe(m)[0]}return e(t).length?"x"===o?oe(e(t))[1]:oe(e(t))[0]:(l.css(h,t),void u.update.call(null,n[0]))}}},X=function(t){function o(){return clearTimeout(h[0].autoUpdate),0===s.parents("html").length?void(s=null):void(h[0].autoUpdate=setTimeout(function(){return f.advanced.updateOnSelectorChange&&(m=r(),m!==w)?(l(3),void(w=m)):(f.advanced.updateOnContentResize&&(p=[h.outerHeight(!1),h.outerWidth(!1),v.height(),v.width(),_()[0],_()[1]],(p[0]!==S[0]||p[1]!==S[1]||p[2]!==S[2]||p[3]!==S[3]||p[4]!==S[4]||p[5]!==S[5])&&(l(p[0]!==S[0]||p[1]!==S[1]),S=p)),f.advanced.updateOnImageLoad&&(g=n(),g!==b&&(h.find("img").each(function(){i(this)}),b=g)),void((f.advanced.updateOnSelectorChange||f.advanced.updateOnContentResize||f.advanced.updateOnImageLoad)&&o()))},f.advanced.autoUpdateTimeout))}function n(){var e=0;return f.advanced.updateOnImageLoad&&(e=h.find("img").length),e}function i(t){function o(e,t){return function(){return t.apply(e,arguments)}}function a(){this.onload=null,e(t).addClass(d[2]),l(2)}if(e(t).hasClass(d[2]))return void l();var n=new Image;n.onload=o(n,a),n.src=t.src}function r(){f.advanced.updateOnSelectorChange===!0&&(f.advanced.updateOnSelectorChange="*");var t=0,o=h.find(f.advanced.updateOnSelectorChange);return f.advanced.updateOnSelectorChange&&o.length>0&&o.each(function(){t+=e(this).height()+e(this).width()}),t}function l(e){clearTimeout(h[0].autoUpdate),u.update.call(null,s[0],e)}var s=e(this),c=s.data(a),f=c.opt,h=e("#mCSB_"+c.idx+"_container");if(t)return clearTimeout(h[0].autoUpdate),void Z(h[0],"autoUpdate");var m,p,g,v=h.parent(),x=[e("#mCSB_"+c.idx+"_scrollbar_vertical"),e("#mCSB_"+c.idx+"_scrollbar_horizontal")],_=function(){return[x[0].is(":visible")?x[0].outerHeight(!0):0,x[1].is(":visible")?x[1].outerWidth(!0):0]},w=r(),S=[h.outerHeight(!1),h.outerWidth(!1),v.height(),v.width(),_()[0],_()[1]],b=n();o()},N=function(e,t,o){return Math.round(e/t)*t-o},V=function(t){var o=t.data(a),n=e("#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal");n.each(function(){K.call(this)})},Q=function(t,o,n){function i(e){return s&&c.callbacks[e]&&"function"==typeof c.callbacks[e]}function r(){return[c.callbacks.alwaysTriggerOffsets||_>=w[0]+b,c.callbacks.alwaysTriggerOffsets||-C>=_]}function l(){var e=[h[0].offsetTop,h[0].offsetLeft],o=[v[0].offsetTop,v[0].offsetLeft],a=[h.outerHeight(!1),h.outerWidth(!1)],i=[f.height(),f.width()];t[0].mcs={content:h,top:e[0],left:e[1],draggerTop:o[0],draggerLeft:o[1],topPct:Math.round(100*Math.abs(e[0])/(Math.abs(a[0])-i[0])),leftPct:Math.round(100*Math.abs(e[1])/(Math.abs(a[1])-i[1])),direction:n.dir}}var s=t.data(a),c=s.opt,d={trigger:"internal",dir:"y",scrollEasing:"mcsEaseOut",drag:!1,dur:c.scrollInertia,overwrite:"all",
callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},n=e.extend(d,n),u=[n.dur,n.drag?0:n.dur],f=e("#mCSB_"+s.idx),h=e("#mCSB_"+s.idx+"_container"),m=h.parent(),p=c.callbacks.onTotalScrollOffset?Y.call(t,c.callbacks.onTotalScrollOffset):[0,0],g=c.callbacks.onTotalScrollBackOffset?Y.call(t,c.callbacks.onTotalScrollBackOffset):[0,0];if(s.trigger=n.trigger,(0!==m.scrollTop()||0!==m.scrollLeft())&&(e(".mCSB_"+s.idx+"_scrollbar").css("visibility","visible"),m.scrollTop(0).scrollLeft(0)),"_resetY"!==o||s.contentReset.y||(i("onOverflowYNone")&&c.callbacks.onOverflowYNone.call(t[0]),s.contentReset.y=1),"_resetX"!==o||s.contentReset.x||(i("onOverflowXNone")&&c.callbacks.onOverflowXNone.call(t[0]),s.contentReset.x=1),"_resetY"!==o&&"_resetX"!==o){switch(!s.contentReset.y&&t[0].mcs||!s.overflowed[0]||(i("onOverflowY")&&c.callbacks.onOverflowY.call(t[0]),s.contentReset.x=null),!s.contentReset.x&&t[0].mcs||!s.overflowed[1]||(i("onOverflowX")&&c.callbacks.onOverflowX.call(t[0]),s.contentReset.x=null),c.snapAmount&&(o=N(o,c.snapAmount,c.snapOffset)),n.dir){case"x":var v=e("#mCSB_"+s.idx+"_dragger_horizontal"),x="left",_=h[0].offsetLeft,w=[f.width()-h.outerWidth(!1),v.parent().width()-v.width()],S=[o,0===o?0:o/s.scrollRatio.x],b=p[1],C=g[1],B=b>0?b/s.scrollRatio.x:0,T=C>0?C/s.scrollRatio.x:0;break;case"y":var v=e("#mCSB_"+s.idx+"_dragger_vertical"),x="top",_=h[0].offsetTop,w=[f.height()-h.outerHeight(!1),v.parent().height()-v.height()],S=[o,0===o?0:o/s.scrollRatio.y],b=p[0],C=g[0],B=b>0?b/s.scrollRatio.y:0,T=C>0?C/s.scrollRatio.y:0}S[1]<0||0===S[0]&&0===S[1]?S=[0,0]:S[1]>=w[1]?S=[w[0],w[1]]:S[0]=-S[0],t[0].mcs||(l(),i("onInit")&&c.callbacks.onInit.call(t[0])),clearTimeout(h[0].onCompleteTimeout),(s.tweenRunning||!(0===_&&S[0]>=0||_===w[0]&&S[0]<=w[0]))&&(G(v[0],x,Math.round(S[1]),u[1],n.scrollEasing),G(h[0],x,Math.round(S[0]),u[0],n.scrollEasing,n.overwrite,{onStart:function(){n.callbacks&&n.onStart&&!s.tweenRunning&&(i("onScrollStart")&&(l(),c.callbacks.onScrollStart.call(t[0])),s.tweenRunning=!0,y(v),s.cbOffsets=r())},onUpdate:function(){n.callbacks&&n.onUpdate&&i("whileScrolling")&&(l(),c.callbacks.whileScrolling.call(t[0]))},onComplete:function(){if(n.callbacks&&n.onComplete){"yx"===c.axis&&clearTimeout(h[0].onCompleteTimeout);var e=h[0].idleTimer||0;h[0].onCompleteTimeout=setTimeout(function(){i("onScroll")&&(l(),c.callbacks.onScroll.call(t[0])),i("onTotalScroll")&&S[1]>=w[1]-B&&s.cbOffsets[0]&&(l(),c.callbacks.onTotalScroll.call(t[0])),i("onTotalScrollBack")&&S[1]<=T&&s.cbOffsets[1]&&(l(),c.callbacks.onTotalScrollBack.call(t[0])),s.tweenRunning=!1,h[0].idleTimer=0,y(v,"hide")},e)}}}))}},G=function(e,t,o,a,n,i,r){function l(){S.stop||(x||m.call(),x=J()-v,s(),x>=S.time&&(S.time=x>S.time?x+f-(x-S.time):x+f-1,S.time<x+1&&(S.time=x+1)),S.time<a?S.id=h(l):g.call())}function s(){a>0?(S.currVal=u(S.time,_,b,a,n),w[t]=Math.round(S.currVal)+"px"):w[t]=o+"px",p.call()}function c(){f=1e3/60,S.time=x+f,h=window.requestAnimationFrame?window.requestAnimationFrame:function(e){return s(),setTimeout(e,.01)},S.id=h(l)}function d(){null!=S.id&&(window.requestAnimationFrame?window.cancelAnimationFrame(S.id):clearTimeout(S.id),S.id=null)}function u(e,t,o,a,n){switch(n){case"linear":case"mcsLinear":return o*e/a+t;case"mcsLinearOut":return e/=a,e--,o*Math.sqrt(1-e*e)+t;case"easeInOutSmooth":return e/=a/2,1>e?o/2*e*e+t:(e--,-o/2*(e*(e-2)-1)+t);case"easeInOutStrong":return e/=a/2,1>e?o/2*Math.pow(2,10*(e-1))+t:(e--,o/2*(-Math.pow(2,-10*e)+2)+t);case"easeInOut":case"mcsEaseInOut":return e/=a/2,1>e?o/2*e*e*e+t:(e-=2,o/2*(e*e*e+2)+t);case"easeOutSmooth":return e/=a,e--,-o*(e*e*e*e-1)+t;case"easeOutStrong":return o*(-Math.pow(2,-10*e/a)+1)+t;case"easeOut":case"mcsEaseOut":default:var i=(e/=a)*e,r=i*e;return t+o*(.499999999999997*r*i+-2.5*i*i+5.5*r+-6.5*i+4*e)}}e._mTween||(e._mTween={top:{},left:{}});var f,h,r=r||{},m=r.onStart||function(){},p=r.onUpdate||function(){},g=r.onComplete||function(){},v=J(),x=0,_=e.offsetTop,w=e.style,S=e._mTween[t];"left"===t&&(_=e.offsetLeft);var b=o-_;S.stop=0,"none"!==i&&d(),c()},J=function(){return window.performance&&window.performance.now?window.performance.now():window.performance&&window.performance.webkitNow?window.performance.webkitNow():Date.now?Date.now():(new Date).getTime()},K=function(){var e=this;e._mTween||(e._mTween={top:{},left:{}});for(var t=["top","left"],o=0;o<t.length;o++){var a=t[o];e._mTween[a].id&&(window.requestAnimationFrame?window.cancelAnimationFrame(e._mTween[a].id):clearTimeout(e._mTween[a].id),e._mTween[a].id=null,e._mTween[a].stop=1)}},Z=function(e,t){try{delete e[t]}catch(o){e[t]=null}},$=function(e){return!(e.which&&1!==e.which)},ee=function(e){var t=e.originalEvent.pointerType;return!(t&&"touch"!==t&&2!==t)},te=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},oe=function(e){var t=e.parents(".mCSB_container");return[e.offset().top-t.offset().top,e.offset().left-t.offset().left]};e.fn[o]=function(t){return u[t]?u[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):u.init.apply(this,arguments)},e[o]=function(t){return u[t]?u[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):u.init.apply(this,arguments)},e[o].defaults=i,window[o]=!0,e(window).load(function(){e(n)[o](),e.extend(e.expr[":"],{mcsInView:e.expr[":"].mcsInView||function(t){var o,a,n=e(t),i=n.parents(".mCSB_container");if(i.length)return o=i.parent(),a=[i[0].offsetTop,i[0].offsetLeft],a[0]+oe(n)[0]>=0&&a[0]+oe(n)[0]<o.height()-n.outerHeight(!1)&&a[1]+oe(n)[1]>=0&&a[1]+oe(n)[1]<o.width()-n.outerWidth(!1)},mcsOverflow:e.expr[":"].mcsOverflow||function(t){var o=e(t).data(a);if(o)return o.overflowed[0]||o.overflowed[1]}})})})});
/*
 * Swipe 2.0
 *
 * Brad Birdsall
 * Copyright 2013, MIT License
 *
*/

function Swipe(container, options)
{

	"use strict";

	// utilities
	var noop = function () { }; // simple no operation function
	var offloadFn = function (fn) { setTimeout(fn || noop, 0) }; // offload a functions execution

	// check browser capabilities
	var browser = {
		addEventListener: !!window.addEventListener,
		touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
		transitions: (function (temp)
		{
			var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
			for (var i in props) if (temp.style[props[i]] !== undefined) return true;
			return false;
		})(document.createElement('swipe'))
	};

	// quit if no root element
	if (!container) return;
	var element = container.children[0];
	var slides, slidePos, width, length;
	options = options || {};
	var index = parseInt(options.startSlide, 10) || 0;
	var speed = options.speed || 300;
	options.continuous = options.continuous !== undefined ? options.continuous : true;

	function setup()
	{

		// cache slides
		slides = element.children;
		length = slides.length;

		// set continuous to false if only one slide
		if (slides.length < 2) options.continuous = false;

		//special case if two slides
		if (browser.transitions && options.continuous && slides.length < 3)
		{
			element.appendChild(slides[0].cloneNode(true));
			element.appendChild(element.children[1].cloneNode(true));
			slides = element.children;
		}

		// create an array to store current positions of each slide
		slidePos = new Array(slides.length);

		// determine width of each slide
		width = container.getBoundingClientRect().width || container.offsetWidth;

		element.style.width = (slides.length * width) + 'px';

		// stack elements
		var pos = slides.length;
		while (pos--)
		{

			var slide = slides[pos];

			slide.style.width = width + 'px';
			slide.setAttribute('data-index', pos);

			if (browser.transitions)
			{
				slide.style.left = (pos * -width) + 'px';
				move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
			}

		}

		// reposition elements before and after index
		if (options.continuous && browser.transitions)
		{
			move(circle(index - 1), -width, 0);
			move(circle(index + 1), width, 0);
		}

		if (!browser.transitions) element.style.left = (index * -width) + 'px';

		container.style.visibility = 'visible';

	}

	function prev()
	{

		if (options.continuous) slide(index - 1);
		else if (index) slide(index - 1);

	}

	function next()
	{

		if (options.continuous) slide(index + 1);
		else if (index < slides.length - 1) slide(index + 1);

	}

	function circle(index)
	{

		// a simple positive modulo using slides.length
		return (slides.length + (index % slides.length)) % slides.length;

	}

	function slide(to, slideSpeed)
	{

		// do nothing if already on requested slide
		if (index == to) return;

		if (browser.transitions)
		{

			var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward

			// get the actual position of the slide
			if (options.continuous)
			{
				var natural_direction = direction;
				direction = -slidePos[circle(to)] / width;

				// if going forward but to < index, use to = slides.length + to
				// if going backward but to > index, use to = -slides.length + to
				if (direction !== natural_direction) to = -direction * slides.length + to;

			}

			var diff = Math.abs(index - to) - 1;

			// move all the slides between index and to in the right direction
			while (diff--) move(circle((to > index ? to : index) - diff - 1), width * direction, 0);

			to = circle(to);

			move(index, width * direction, slideSpeed || speed);
			move(to, 0, slideSpeed || speed);

			if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place

		} else
		{

			to = circle(to);
			animate(index * -width, to * -width, slideSpeed || speed);
			//no fallback for a circular continuous if the browser does not accept transitions
		}

		index = to;
		offloadFn(options.callback && options.callback(index, slides[index]));
	}

	function move(index, dist, speed)
	{

		translate(index, dist, speed);
		slidePos[index] = dist;

	}

	function translate(index, dist, speed)
	{

		var slide = slides[index];
		var style = slide && slide.style;

		if (!style) return;

		style.webkitTransitionDuration =
		style.MozTransitionDuration =
		style.msTransitionDuration =
		style.OTransitionDuration =
		style.transitionDuration = speed + 'ms';

		style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
		style.msTransform =
		style.MozTransform =
		style.OTransform = 'translateX(' + dist + 'px)';

	}

	function animate(from, to, speed)
	{

		// if not an animation, just reposition
		if (!speed)
		{

			element.style.left = to + 'px';
			return;

		}

		var start = +new Date;

		var timer = setInterval(function ()
		{

			var timeElap = +new Date - start;

			if (timeElap > speed)
			{

				element.style.left = to + 'px';

				if (delay) begin();

				options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

				clearInterval(timer);
				return;

			}

			element.style.left = (((to - from) * (Math.floor((timeElap / speed) * 100) / 100)) + from) + 'px';

		}, 4);

	}

	// setup auto slideshow
	var delay = options.auto || 0;
	var interval;

	function begin()
	{

		interval = setTimeout(next, delay);

	}

	function stop()
	{

		delay = 0;
		clearTimeout(interval);

	}


	// setup initial vars
	var start = {};
	var delta = {};
	var isScrolling;

	// setup event capturing
	var events = {

		handleEvent: function (event)
		{

			switch (event.type)
			{
				case 'touchstart': this.start(event); break;
				case 'touchmove': this.move(event); break;
				case 'touchend': offloadFn(this.end(event)); break;
				case 'webkitTransitionEnd':
				case 'msTransitionEnd':
				case 'oTransitionEnd':
				case 'otransitionend':
				case 'transitionend': offloadFn(this.transitionEnd(event)); break;
				case 'resize': offloadFn(setup); break;
			}

			if (options.stopPropagation) event.stopPropagation();

		},
		start: function (event)
		{

			var touches = event.touches[0];

			// measure start values
			start = {

				// get initial touch coords
				x: touches.pageX,
				y: touches.pageY,

				// store time to determine touch duration
				time: +new Date

			};

			// used for testing first move event
			isScrolling = undefined;

			// reset delta and end measurements
			delta = {};

			// attach touchmove and touchend listeners
			element.addEventListener('touchmove', this, true);
			element.addEventListener('touchend', this, true);

		},
		move: function (event)
		{

			// ensure swiping with one touch and not pinching
			if (event.touches.length > 1 || event.scale && event.scale !== 1) return

			if (options.disableScroll) event.preventDefault();

			var touches = event.touches[0];

			// measure change in x and y
			delta = {
				x: touches.pageX - start.x,
				y: touches.pageY - start.y
			}

			// determine if scrolling test has run - one time test
			if (typeof isScrolling == 'undefined')
			{
				isScrolling = !!(isScrolling || Math.abs(delta.x) < Math.abs(delta.y));
			}

			// if user is not trying to scroll vertically
			if (!isScrolling)
			{

				// prevent native scrolling
				event.preventDefault();

				// stop slideshow
				stop();

				// increase resistance if first or last slide
				if (options.continuous)
				{ // we don't add resistance at the end

					translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
					translate(index, delta.x + slidePos[index], 0);
					translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);

				} else
				{

					delta.x =
					  delta.x /
						((!index && delta.x > 0               // if first slide and sliding left
						  || index == slides.length - 1        // or if last slide and sliding right
						  && delta.x < 0                       // and if sliding at all
						) ?
						(Math.abs(delta.x) / width + 1)      // determine resistance level
						: 1);                                 // no resistance if false

					// translate 1:1
					translate(index - 1, delta.x + slidePos[index - 1], 0);
					translate(index, delta.x + slidePos[index], 0);
					translate(index + 1, delta.x + slidePos[index + 1], 0);
				}

			}

		},
		end: function (event)
		{

			// measure duration
			var duration = +new Date - start.time;

			// determine if slide attempt triggers next/prev slide
			var isValidSlide =
				  Number(duration) < 250               // if slide duration is less than 250ms
				  && Math.abs(delta.x) > 20            // and if slide amt is greater than 20px
				  || Math.abs(delta.x) > width / 2;      // or if slide amt is greater than half the width

			// determine if slide attempt is past start and end
			var isPastBounds =
				  !index && delta.x > 0                            // if first slide and slide amt is greater than 0
				  || index == slides.length - 1 && delta.x < 0;    // or if last slide and slide amt is less than 0

			if (options.continuous) isPastBounds = false;

			// determine direction of swipe (true:right, false:left)
			var direction = delta.x < 0;

			// if not scrolling vertically
			if (!isScrolling)
			{

				if (isValidSlide && !isPastBounds)
				{

					if (direction)
					{

						if (options.continuous)
						{ // we need to get the next in this direction in place

							move(circle(index - 1), -width, 0);
							move(circle(index + 2), width, 0);

						} else
						{
							move(index - 1, -width, 0);
						}

						move(index, slidePos[index] - width, speed);
						move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
						index = circle(index + 1);

					} else
					{
						if (options.continuous)
						{ // we need to get the next in this direction in place

							move(circle(index + 1), width, 0);
							move(circle(index - 2), -width, 0);

						} else
						{
							move(index + 1, width, 0);
						}

						move(index, slidePos[index] + width, speed);
						move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
						index = circle(index - 1);

					}

					options.callback && options.callback(index, slides[index]);

				} else
				{

					if (options.continuous)
					{

						move(circle(index - 1), -width, speed);
						move(index, 0, speed);
						move(circle(index + 1), width, speed);

					} else
					{

						move(index - 1, -width, speed);
						move(index, 0, speed);
						move(index + 1, width, speed);
					}

				}

			}

			// kill touchmove and touchend event listeners until touchstart called again
			element.removeEventListener('touchmove', events, false)
			element.removeEventListener('touchend', events, false)

		},
		transitionEnd: function (event)
		{

			if (parseInt(event.target.getAttribute('data-index'), 10) == index)
			{

				if (delay) begin();

				options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

			}

		}

	}

	// trigger setup
	setup();

	// start auto slideshow if applicable
	if (delay) begin();


	// add event listeners
	if (browser.addEventListener)
	{

		// set touchstart event on element
		if (browser.touch) element.addEventListener('touchstart', events, true);

		if (browser.transitions)
		{
			element.addEventListener('webkitTransitionEnd', events, true);
			element.addEventListener('msTransitionEnd', events, true);
			element.addEventListener('oTransitionEnd', events, true);
			element.addEventListener('otransitionend', events, true);
			element.addEventListener('transitionend', events, true);
		}

		// set resize event on window
		window.addEventListener('resize', events, true);

	} else
	{

		window.onresize = function () { setup() }; // to play nice with old IE

	}

	// expose the Swipe API
	return {
		setup: function ()
		{

			setup();

		},
		slide: function (to, speed)
		{

			// cancel slideshow
			stop();

			slide(to, speed);

		},
		prev: function ()
		{

			// cancel slideshow
			stop();

			prev();

		},
		next: function ()
		{

			// cancel slideshow
			stop();

			next();

		},
		stop: function ()
		{

			// cancel slideshow
			stop();

		},
		begin: function ()
		{
			// cancel slideshow
			//setTimeout(function () { begin(); }, options.auto);
			//begin();
		},
		getPos: function ()
		{

			// return current index position
			return index;

		},
		getNumSlides: function ()
		{

			// return total number of slides
			return length;
		},
		kill: function ()
		{

			// cancel slideshow
			stop();

			// reset element
			element.style.width = '';
			element.style.left = '';

			// reset slides
			var pos = slides.length;
			while (pos--)
			{

				var slide = slides[pos];
				slide.style.width = '';
				slide.style.left = '';

				if (browser.transitions) translate(pos, 0, 0);

			}

			// removed event listeners
			if (browser.addEventListener)
			{
				// remove current event listeners
				element.removeEventListener('touchstart', events, true);
				element.removeEventListener('webkitTransitionEnd', events, true);
				element.removeEventListener('msTransitionEnd', events, true);
				element.removeEventListener('oTransitionEnd', events, true);
				element.removeEventListener('otransitionend', events, true);
				element.removeEventListener('transitionend', events, true);
				window.removeEventListener('resize', events, true);
			}
			else
			{
				window.onresize = null;
			}

		}
	}

}


if (window.jQuery || window.Zepto)
{
	(function ($)
	{
		$.fn.Swipe = function (params)
		{
			return this.each(function ()
			{
				$(this).data('Swipe', new Swipe($(this)[0], params));
			});
		}
	})(window.jQuery || window.Zepto)
}

function browserStorage(disallowCookieStore) {
    var cookieName = "LDS";

    var storageAvailable = function (type) {
        try {
            var storage = window[type],
				x = "__storage_test__";
            storage.setItem(x, x);
            storage.removeItem(x);
            return true;
        }
        catch (e) {
            return false;
        }
    };

    var localStorageStore = {

        storeItem: function (name, value) {
            localStorage.setItem(name, value);
        },

        getItem: function (name) {
            return localStorage.getItem(name);
        },

        removeItem: function (name) {
            localStorage.removeItem(name);
        },

        removeAllItems: function () {
            for (var i = 0; i < localStorage.length; i++) {
                localStorage.removeItem(localStorage.key(i));
            }
        }
    };

    var cookieStorageHelper = function (name, value) {
        var dataToStore = {};
        var cookieStore = ReadCookie(name);
        if (!cookieStore) {
            dataToStore[name] = value;
        } else {
            cookieStore[name] = value;
        }
        return JSON.stringify(dataToStore);
    };

    var cookieStore = {

        storeItem: function (name, value) {
            try {
                CreateCookie(cookieName, cookieStorageHelper(name, value), 365);
            } catch (e) {
                console.log(e);
            }
        },

        getItem: function (name) {
            var dataValue = "";
            try {
                var cookieStore = ReadCookie(name);
                if (cookieStore) {
                    var jsonCookieStore = JSON.parse(cookieStore);
                    if (jsonCookieStore.hasOwnProperty(name)) {
                        dataValue = jsonCookieStore[name];
                        if (!dataValue) {
                            dataValue = "";
                        }
                    }
                }
            } catch (e) {
                console.log(e);
            }
            return dataValue;
        },

        removeItem: function (name) {
            try {
                var cookieStore = ReadCookie(name);
                if (cookieStore) {
                    var jsonCookieStore = JSON.parse(cookieStore);
                    if (jsonCookieStore.hasOwnProperty(name)) {
                        var dataValue = jsonCookieStore[name];
                        if (dataValue) {
                            jsonCookieStore[name] = "";
                        }
                    }
                }
                CreateCookie(cookieName, JSON.stringify(cookieStore), 365);
            } catch (e) {
                console.log(e);
            }
        },

        removeAllItems: function () {
            EraseCookie(cookieName);
        }

    };

    return {
		
        storeItem: function (name, value) {
            if (storageAvailable("localStorage")) {
                localStorageStore.storeItem(name, value);
            }
            else {
                if (!disallowCookieStore) {
                    cookieStore.storeItem(name, value);
                }
            }
        },
		
        getItem: function (name) {
            if (storageAvailable("localStorage")) {
                return localStorageStore.getItem(name);
            } else {
                if (!disallowCookieStore) {
                    return cookieStore.getItem(name);
                }
            }
        },
		
        removeItem: function (name) {
            if (storageAvailable("localStorage")) {
                localStorageStore.removeItem(name);
            } else {
                if (!disallowCookieStore) {
                    cookieStore.removeItem(name);
                }
            }
        },
		
        removeAllItems: function () {
            if (storageAvailable("localStorage")) {
                localStorageStore.removeAllItems();
            } else {
                if (!disallowCookieStore) {
                    cookieStore.removeAllItems();
                }
            }
        }
		
    };

}
function _TranslationHelper() {

    try {
        var currentLanguage = window.casinoGlobals.CasinoMetadata.RequestMetadata.languageCode.toLowerCase();
        var customErrors = {
            en: {
                DIDYOUMEAN: "Did you mean:",
                NORESULTS: "No results found",
                KEEPTYPING: "Keep typing your address to display more results",
                RETRIEVEERROR: "Sorry, we could not retrieve this address",
                SERVICEERROR: "Service Error:",
                COUNTRYSELECT: "Change Country",
                NOLOCATION: "Sorry, we could not get your location",
                NOCOUNTRY: "Sorry, we could not find this country",
                MANUALENTRY: "I cannot find my address. Let me type it in",
                RESULTCOUNT: "<b>{count}</b> matching results",
                CanadianPostalCodeError: "Your Zip/Postal Code should be 6 characters long and only include letters and/or numbers (A-Z/a-z and 0-9)",
                STATE: "State / Province"
            },
            it: {
                DIDYOUMEAN: "Intendevi:",
                NORESULTS: "nessun risultato trovato",
                KEEPTYPING: "Continuare a digitare il tuo indirizzo per visualizzare altri risultati",
                RETRIEVEERROR: "Spiacenti, non è possibile recuperare questo indirizzo",
                SERVICEERROR: "Errore di servizio:",
                COUNTRYSELECT: "Cambia Paese",
                NOLOCATION: "Spiacenti, non abbiamo potuto ottenere la tua posizione",
                NOCOUNTRY: "Spiacenti, non abbiamo trovato questo paese",
                MANUALENTRY: "Non riesco a trovare il mio indirizzo. Lasciatemi digitarlo",
                RESULTCOUNT: "<b>{count}</b> risultati corrispondenti",
                CanadianPostalCodeError: "Il codice postale deve essere di 6 caratteri e include solo lettere e / o numeri (A-Z / a-z e 0-9)",
                STATE: "Stato / provincia"
            },
            nl: {
                DIDYOUMEAN: "Did you mean:",
                NORESULTS: "No results found",
                KEEPTYPING: "Keep typing your address to display more results",
                RETRIEVEERROR: "Sorry, we could not retrieve this address",
                SERVICEERROR: "Service Error:",
                COUNTRYSELECT: "Change Country",
                NOLOCATION: "Sorry, we could not get your location",
                NOCOUNTRY: "Sorry, we could not find this country",
                MANUALENTRY: "I cannot find my address. Let me type it in",
                RESULTCOUNT: "<b>{count}</b> matching results",
                CanadianPostalCodeError: "Your Zip/Postal Code should be 6 characters long and only include letters and/or numbers (A-Z/a-z and 0-9)",
                STATE: "State / Province"
            },
            cy: {
                DIDYOUMEAN: "A oeddech yn meddwl:",
                NORESULTS: "Dim canlyniadau ar ganlyniadau",
                KEEPTYPING: "Cadwch teipio eich cyfeiriad i arddangos mwy o ganlyniadau",
                RETRIEVEERROR: "Mae'n ddrwg gennym, ni allem adfer y cyfeiriad hwn",
                SERVICEERROR: "Gwall gwasanaeth:",
                COUNTRYSELECT: "Dewiswch gwlad",
                NOLOCATION: "Mae'n ddrwg gennym, nid oeddem yn gallu cael eich lleoliad",
                NOCOUNTRY: "Mae'n ddrwg gennym, ni allem ddod o hyd y wlad hon",
                MANUALENTRY: "Ni allaf ddod o hyd i fy nghyfeiriad. Gadewch i mi deipio mewn",
                RESULTCOUNT: "<b>{count}</b> Canlyniadau paru",
                CanadianPostalCodeError: "",
                STATE: "Gwladol / Talaith"
            },
            fr: {
                DIDYOUMEAN: "Vouliez-vous dire:",
                NORESULTS: "Aucun résultat n'a été trouvé",
                KEEPTYPING: "Continuer à taper votre adresse pour afficher plus de résultats",
                RETRIEVEERROR: "Désolé , nous ne pouvions pas récupérer cette adresse",
                SERVICEERROR: "Erreur de service:",
                COUNTRYSELECT: "Changer de pays",
                NOLOCATION: "Désolé, nous n'avons pas pu obtenir votre emplacement",
                NOCOUNTRY: "Désolé, nous n'avons pas trouvé ce pays",
                MANUALENTRY: "Je ne peux pas trouver mon adresse. Permettez-moi de taper dans",
                RESULTCOUNT: "<b>{count}</b> résultats correspondants",
                STATE: "Etat / Province",
                CanadianPostalCodeError: "Votre code postal doit être long de 6 caractères au moins et comporter uniquement des lettres et/ou des chiffres (A-Z/a-z et 0-9)"
            },
            de: {
                DIDYOUMEAN: "Meinten Sie:",
                NORESULTS: "Keine Adressen gefunden",
                KEEPTYPING: "Halten Sie Ihre Adresse eingeben, um weitere Ergebnisse anzuzeigen",
                RETRIEVEERROR: "Leider haben wir diese Adresse nicht abrufen",
                SERVICEERROR: "Service-Fehler:",
                COUNTRYSELECT: "Land wechseln",
                NOLOCATION: "Leider konnten wir nicht bekommen, Ihren Standort",
                NOCOUNTRY: "Leider konnten wir nicht finden, dieses Land",
                MANUALENTRY: "Ich kann meine Adresse nicht finden. Lassen Sie mich geben Sie es in",
                RESULTCOUNT: "<b>{count}</b> passenden Ergebnisse",
                STATE: "Bundesland",
                CanadianPostalCodeError: "Ihre Postleitzahl darf nur 6 Zeichen lang sein und nur Buchstaben und/oder Zahlen enthalten (A-Z/a-z und 0-9)"
            },
            fi: {
                DIDYOUMEAN: "Tarkoititko:",
                NORESULTS: "Ei hakutuloksia",
                KEEPTYPING: "Ennakoiva tekstinsyöttö auttaa osoitekentän täyttämisen kanssa",
                RETRIEVEERROR: "Valitettavasti osoitetta ei löytynyt tietokannasta",
                SERVICEERROR: "Palveluvirhe:",
                COUNTRYSELECT: "Vaihda maa",
                NOLOCATION: "Valitettavasti sijaintia ei löytynyt",
                NOCOUNTRY: "Valitettavasti maata ei löytynyt",
                MANUALENTRY: "En löydä osoitettani. Haluan kirjoittaa sen itse.",
                RESULTCOUNT: "<b>{count}</b> hakutulosta",
                STATE: "Osavaltio / Provinssi",
                CanadianPostalCodeError: "Postinumeron tulee olla 6 merkkiä pitkä ja se saa sisältää vain kirjaimia ja/tai numeroita (A–Z/a–z ja 0–9)"
            },
            el: {
                DIDYOUMEAN: "Μήπως εννοείτε:",
                NORESULTS: "Δεν βρέθηκαν αποτελέσματα",
                KEEPTYPING: "Συνεχίστε να πληκτρολογείτε τη διεύθυνσή σας για να εμφανίζετε σε περισσότερα αποτελέσματα",
                RETRIEVEERROR: "Δυστυχώς, δεν μπορέσαμε να ανακτήσουμε αυτή τη διεύθυνση",
                SERVICEERROR: "Σφάλμα υπηρεσίας:",
                COUNTRYSELECT: "Αλλαγή χώρας",
                NOLOCATION: "Δυστυχώς, δεν μπορέσαμε να βρούμετη θέση σας",
                NOCOUNTRY: "Δυστυχώς, δεν μπορέσαμε να βρούμε αυτή τη χώρα",
                MANUALENTRY: "Δεν μπορώ να βρω τη διεύθυνση μου. Επιτρέψτε μου να την πληκτρολογήσω",
                RESULTCOUNT: "Περίπου <b>{count}</b> Αποτελέσματα",
                STATE: "Πόλη / Νομός",
                CanadianPostalCodeError: "Ο Ταχυδρομικός κώδικας σας θα πρέπει να είναι μήκους 6 χαρακτήρες και να περιλαμβάνει μόνο γράμματα ή/και αριθμούς (Α-Ω / a-z και 0-9)"
            },
            gr: {
                DIDYOUMEAN: "Μήπως εννοείτε:",
                NORESULTS: "Δεν βρέθηκαν αποτελέσματα",
                KEEPTYPING: "Συνεχίστε να πληκτρολογείτε τη διεύθυνσή σας για να εμφανίζετε σε περισσότερα αποτελέσματα",
                RETRIEVEERROR: "Δυστυχώς, δεν μπορέσαμε να ανακτήσουμε αυτή τη διεύθυνση",
                SERVICEERROR: "Σφάλμα υπηρεσίας:",
                COUNTRYSELECT: "Αλλαγή χώρας",
                NOLOCATION: "Δυστυχώς, δεν μπορέσαμε να βρούμετη θέση σας",
                NOCOUNTRY: "Δυστυχώς, δεν μπορέσαμε να βρούμε αυτή τη χώρα",
                MANUALENTRY: "Δεν μπορώ να βρω τη διεύθυνση μου. Επιτρέψτε μου να την πληκτρολογήσω",
                RESULTCOUNT: "Περίπου <b>{count}</b> Αποτελέσματα",
                STATE: "Πόλη / Νομός",
                CanadianPostalCodeError: "Ο Ταχυδρομικός κώδικας σας θα πρέπει να είναι μήκους 6 χαρακτήρες και να περιλαμβάνει μόνο γράμματα ή/και αριθμούς (Α-Ω / a-z και 0-9)"
            },
            se: {
                DIDYOUMEAN: "Menade du:",
                NORESULTS: "Vi hittade inte vad du sökte",
                KEEPTYPING: "Fortsätt att skriva din adress för att se fler resultat",
                RETRIEVEERROR: "Vi kunde tyvärr inte hitta adressen",
                SERVICEERROR: "Servicefel:",
                COUNTRYSELECT: "Ändra land",
                NOLOCATION: "Vi kunde tyvärr inte hitta din plats",
                NOCOUNTRY: "Vi kunde tyvärr inte hitta det landet",
                MANUALENTRY: "Jag kan inte hitta min adress. Låt mig skriva den",
                RESULTCOUNT: "<b>{count}</b> resultat",
                STATE: "Landskap",
                CanadianPostalCodeError: "Ditt postnummer kan enbart innehålla 6 tecken i form av bokstäver och/eller nummer (A-Ö/a-ö och 0-9)"
            },
            sv: {
                DIDYOUMEAN: "Menade du:",
                NORESULTS: "Vi hittade inte vad du sökte",
                KEEPTYPING: "Fortsätt att skriva din adress för att se fler resultat",
                RETRIEVEERROR: "Vi kunde tyvärr inte hitta adressen",
                SERVICEERROR: "Servicefel:",
                COUNTRYSELECT: "Ändra land",
                NOLOCATION: "Vi kunde tyvärr inte hitta din plats",
                NOCOUNTRY: "Vi kunde tyvärr inte hitta det landet",
                MANUALENTRY: "Jag kan inte hitta min adress. Låt mig skriva den",
                RESULTCOUNT: "<b>{count}</b> resultat",
                STATE: "Landskap",
                CanadianPostalCodeError: "Ditt postnummer kan enbart innehålla 6 tecken i form av bokstäver och/eller nummer (A-Ö/a-ö och 0-9)"
            },
            pt: {
                DIDYOUMEAN: "Queria dizer:",
                NORESULTS: "Nenhum resultado encontrado",
                KEEPTYPING: "Continue a escrever o seu endereço para mais resultados",
                RETRIEVEERROR: "Lamentamos, mas não conseguimos encontrar esse endereço",
                SERVICEERROR: "Erro de Servidor",
                COUNTRYSELECT: "Altere o seu país",
                NOLOCATION: "Lamentamos, mas não conseguimos encontrar a sua localização",
                NOCOUNTRY: "Lamentamos, mas não conseguimos encontrar o seu país",
                MANUALENTRY: "Não consigo encontrar o meu endereço. Deixem-me escrever.",
                RESULTCOUNT: "<b>{count}</b> de resultados correspondentes",
                STATE: "Estado / Província",
                CanadianPostalCodeError: "O seu código postal/CEP deve ser de até 6 caractéres e apenas incluír letras e/ou números (A-Z/a-z e 0-9)"
            },
            es: {
                DIDYOUMEAN: "¿Quiso decir:*",
                NORESULTS: "No se encontraron resultados",
                KEEPTYPING: "Siga escribiendo su dirección para ver más resultados",
                RETRIEVEERROR: "Lo sentimos, no pudimos encontrar su dirección",
                SERVICEERROR: "Error de servicio:",
                COUNTRYSELECT: "Cambiar el país",
                NOLOCATION: "Lo sentimos, no pudimos encontrar su situación",
                NOCOUNTRY: "Lo sentimos, no pudimos encontrar su país",
                MANUALENTRY: "No puedo encontrar mi dirección. Prefiero introducirla yo mismo.",
                RESULTCOUNT: "Encontrados <b>{count}</b> resultados que coinciden",
                STATE: "Estado / Provincia",
                CanadianPostalCodeError: "Su código postal debe tener 6 caracteres y solo incluir letras o números (A-Z/a-z y 0-9)"
            },
            no: {
                DIDYOUMEAN: "Mente du:",
                NORESULTS: "Ingen resultater funnet",
                KEEPTYPING: "Fortsett å skriv inn din adresse for flere resultater",
                RETRIEVEERROR: "Beklager, vi fant ikke denne adressen",
                SERVICEERROR: "Tjeneste feil:",
                COUNTRYSELECT: "Endre land",
                NOLOCATION: "Beklager, vi fant ikke denne beliggenheten",
                NOCOUNTRY: "Beklager, vi fant ikke dette landet",
                MANUALENTRY: "Jeg finner ikke min adresse. La meg skrive det inn",
                RESULTCOUNT: "Samsvarende resultater",
                STATE: "Stat / Provins",
                CanadianPostalCodeError: "Ditt postnummer må ha 6 tegn og kan kun inneholde bokstaver og/eller nummer (A-Å/a-å og 0-9)"
            },
            nn: {
                DIDYOUMEAN: "Mente du:",
                NORESULTS: "Ingen resultater funnet",
                KEEPTYPING: "Fortsett å skriv inn din adresse for flere resultater",
                RETRIEVEERROR: "Beklager, vi fant ikke denne adressen",
                SERVICEERROR: "Tjeneste feil:",
                COUNTRYSELECT: "Endre land",
                NOLOCATION: "Beklager, vi fant ikke denne beliggenheten",
                NOCOUNTRY: "Beklager, vi fant ikke dette landet",
                MANUALENTRY: "Jeg finner ikke min adresse. La meg skrive det inn",
                RESULTCOUNT: "Samsvarende resultater",
                STATE: "Stat / Provins",
                CanadianPostalCodeError: "Ditt postnummer må ha 6 tegn og kan kun inneholde bokstaver og/eller nummer (A-Å/a-å og 0-9)"
            },
            jp: {
                DIDYOUMEAN: "正しい住所をご入力下さい",
                NORESULTS: "住所が見つかりませんでした",
                KEEPTYPING: "住所をご入力下さい",
                RETRIEVEERROR: "ご入力の住所は見つかりませんでした",
                SERVICEERROR: "サービスエラー",
                COUNTRYSELECT: "国名の変更",
                NOLOCATION: "お住まいの地域を特定できませんでした",
                NOCOUNTRY: "お住まいの国を特定できませんでした",
                MANUALENTRY: "住所が一致しませんでした。正しい住所をご入力下さい：",
                RESULTCOUNT: "住所検索結果：<b>{count}</b>",
                STATE: "都道府県(ローマ字)",
                CanadianPostalCodeError: "郵便番号は6桁の半角英数字でご入力下さい。"
            },
            ja: {
                DIDYOUMEAN: "正しい住所をご入力下さい",
                NORESULTS: "住所が見つかりませんでした",
                KEEPTYPING: "住所をご入力下さい",
                RETRIEVEERROR: "ご入力の住所は見つかりませんでした",
                SERVICEERROR: "サービスエラー",
                COUNTRYSELECT: "国名の変更",
                NOLOCATION: "お住まいの地域を特定できませんでした",
                NOCOUNTRY: "お住まいの国を特定できませんでした",
                MANUALENTRY: "住所が一致しませんでした。正しい住所をご入力下さい：",
                RESULTCOUNT: "住所検索結果：<b>{count}</b>",
                STATE: "都道府県(ローマ字)",
                CanadianPostalCodeError: "郵便番号は6桁の半角英数字でご入力下さい。"
            }
        }
        window.LocationMessages = {
            DIDYOUMEAN: customErrors[currentLanguage].DIDYOUMEAN,
            NORESULTS: customErrors[currentLanguage].NORESULTS,
            KEEPTYPING: customErrors[currentLanguage].KEEPTYPING,
            RETRIEVEERROR: customErrors[currentLanguage].RETRIEVEERROR,
            SERVICEERROR: customErrors[currentLanguage].SERVICEERROR,
            COUNTRYSELECT: customErrors[currentLanguage].COUNTRYSELECT,
            NOLOCATION: customErrors[currentLanguage].NOLOCATION,
            NOCOUNTRY: customErrors[currentLanguage].NOCOUNTRY,
            MANUALENTRY: customErrors[currentLanguage].MANUALENTRY,
            RESULTCOUNT: customErrors[currentLanguage].RESULTCOUNT,
            STATE: customErrors[currentLanguage].STATE,
            CanadianPostalCodeError: customErrors[currentLanguage].CanadianPostalCodeError
        };
    } catch (ex) {
        console.log(ex);
    }
}

_DateOfBirthValues = function (currentLanguage) {

    var dateOfBirthDefaultValues = {
        en: {
            Day: "DD",
            Month: "MM",
            Year: "YYYY"
        },
        ja: {
            Day: "日",
            Month: "月",
            Year: "年"
        },
        jp: {
            Day: "日",
            Month: "月",
            Year: "年"
        },
        de: {
            Day: "DD",
            Month: "MM",
            Year: "YYYY"
        },
        pt: {
            Day: "DD",
            Month: "MM",
            Year: "AAAA"
        },
        gr: {
            Day: "HH",
            Month: "MM",
            Year: "EEEE"
        },
        el: {
            Day: "HH",
            Month: "MM",
            Year: "EEEE"
        },
        es: {
            Day: "DD",
            Month: "MM",
            Year: "AAAA"
        },
        fi: {
            Day: "PP",
            Month: "KK",
            Year: "YYYY"
        },
        fr: {
            Day: "DD",
            Month: "MM",
            Year: "YYYY"
        },
        it: {
            Day: "GG",
            Month: "MM",
            Year: "AAAA"
        },
        nl: {
            Day: "DD",
            Month: "MM",
            Year: "JJJJ"
        },
        no: {
            Day: "DD",
            Month: "MM",
            Year: "ÅÅÅÅ"
        },
        se: {
            Day: "DD",
            Month: "MM",
            Year: "ÅÅÅÅ"
        },
        sv: {
            Day: "DD",
            Month: "MM",
            Year: "ÅÅÅÅ"
        }
    };
    window.dobValues = {
        Day: dateOfBirthDefaultValues[currentLanguage.toLowerCase()].Day,
        Month: dateOfBirthDefaultValues[currentLanguage.toLowerCase()].Month,
        Year: dateOfBirthDefaultValues[currentLanguage.toLowerCase()].Year
    };


};

_DateOfBirthMonths = function (currentLanguage) {

    var dateOfBirthMonthValues = {
        en: {
            January: "January",
            February: "February ",
            March: "March ",
            April: "April",
            May: "May",
            June: "June",
            July: "July",
            August: "August",
            September: "September",
            October: "October",
            November: "November",
            December: "December"

        },
        ja: {
            January: "一月",
            February: "二月",
            March: "三月",
            April: "四月",
            May: "五月",
            June: "六月",
            July: "七月",
            August: "八月",
            September: "九月",
            October: "十月",
            November: "十一月",
            December: "十二月"
        },
        jp: {
            January: "一月",
            February: "二月",
            March: "三月",
            April: "四月",
            May: "五月",
            June: "六月",
            July: "七月",
            August: "八月",
            September: "九月",
            October: "十月",
            November: "十一月",
            December: "十二月"
        },
        de: {
            January: "Januar",
            February: "Februar",
            March: "März",
            April: "April",
            May: "Mai",
            June: "Juni",
            July: "Juli",
            August: "August",
            September: "September",
            October: "Oktober",
            November: "November",
            December: "Dezember​"
        },
        pt: {
            January: "Janeiro",
            February: "Fevereiro",
            March: "Março",
            April: "Abril",
            May: "Maio",
            June: "Junho",
            July: "Julho",
            August: "Agosto",
            September: "Setembro",
            October: "Outubro",
            November: "Novembro",
            December: "Dezembro"
        },
        gr: {
            January: "Ιανουάριος",
            February: "Φεβρουάριος",
            March: "Μάρτιος",
            April: "Απρίλιος",
            May: "Μάιος",
            June: "Ιούνιος",
            July: "Ιούλιος",
            August: "Αύγουστος",
            September: "Σεπτέμβριος",
            October: "Οκτώβριος",
            November: "Νοέμβριος",
            December: "Δεκέμβριος"
        },
        el: {
            January: "Ιανουάριος",
            February: "Φεβρουάριος",
            March: "Μάρτιος",
            April: "Απρίλιος",
            May: "Μάιος",
            June: "Ιούνιος",
            July: "Ιούλιος",
            August: "Αύγουστος",
            September: "Σεπτέμβριος",
            October: "Οκτώβριος",
            November: "Νοέμβριος",
            December: "Δεκέμβριος"
        },
        es: {
            January: "Enero",
            February: "Febrero",
            March: "Marzo",
            April: "Abril",
            May: "Mayo",
            June: "Junio",
            July: "Julio",
            August: "Agosto",
            September: "Septiembre",
            October: "Octubre",
            November: "Noviembre",
            December: "Diciembre"
        },
        fi: {
            January: "Tammikuu",
            February: "Helmikuu",
            March: "Maaliskuu",
            April: "Huhtikuu",
            May: "Toukokuu",
            June: "Kesäkuu",
            July: "Heinäkuu",
            August: "Elokuu",
            September: "Syyskuu",
            October: "Lokakuu",
            November: "Marraskuu",
            December: "Joulukuu"
        },
        fr: {
            January: "Janvier",
            February: "Février",
            March: "Mars",
            April: "Avril",
            May: "Mai",
            June: "Juin",
            July: "Juillet",
            August: "Août",
            September: "Septembre",
            October: "Octobre",
            November: "Novembre",
            December: "Décembre"
        },
        it: {
            January: "Gennaio",
            February: "Febbraio",
            March: "Marzo",
            April: "Aprile",
            May: "Maggio",
            June: "Giugno",
            July: "Luglio",
            August: "Agosto",
            September: "Settembre",
            October: "Ottobre",
            November: "Novembre",
            December: "Dicembre"
        },
        nl: {
            January: "January",
            February: "February ",
            March: "March ",
            April: "April",
            May: "May",
            June: "June",
            July: "July",
            August: "August",
            September: "September",
            October: "October",
            November: "November",
            December: "December"
        },
        no: {
            January: "Januar",
            February: "Februar",
            March: "Mars",
            April: "April",
            May: "Mai",
            June: "Juni",
            July: "Juli",
            August: "August",
            September: "September",
            October: "Oktober",
            November: "November",
            December: "Desember"
        },
        se: {
            January: "Januari",
            February: "Februari",
            March: "Mars",
            April: "April",
            May: "Maj",
            June: "Juni",
            July: "Juli",
            August: "Augusti",
            September: "September",
            October: "Oktober",
            November: "November",
            December: "December"
        },
        sv: {
            January: "Januari",
            February: "Februari",
            March: "Mars",
            April: "April",
            May: "Maj",
            June: "Juni",
            July: "Juli",
            August: "Augusti",
            September: "September",
            October: "Oktober",
            November: "November",
            December: "December"
        }
    };
    window.dobMonthValues = {
        _1: dateOfBirthMonthValues[currentLanguage.toLowerCase()].January,
        _2: dateOfBirthMonthValues[currentLanguage.toLowerCase()].February,
        _3: dateOfBirthMonthValues[currentLanguage.toLowerCase()].March,
        _4: dateOfBirthMonthValues[currentLanguage.toLowerCase()].April,
        _5: dateOfBirthMonthValues[currentLanguage.toLowerCase()].May,
        _6: dateOfBirthMonthValues[currentLanguage.toLowerCase()].June,
        _7: dateOfBirthMonthValues[currentLanguage.toLowerCase()].July,
        _8: dateOfBirthMonthValues[currentLanguage.toLowerCase()].August,
        _9: dateOfBirthMonthValues[currentLanguage.toLowerCase()].September,
        _10: dateOfBirthMonthValues[currentLanguage.toLowerCase()].October,
        _11: dateOfBirthMonthValues[currentLanguage.toLowerCase()].November,
        _12: dateOfBirthMonthValues[currentLanguage.toLowerCase()].December
    };
};


_DisplayGeneralError = function (currentLanguage) {

    var customErrors = {
        en: "An error occurred with your request, please contact the casino helpdesk if this problem persists.",
        de: "Während der Bearbeitung Ihrer Anfrage ist ein Fehler aufgetreten, bitte kontaktieren Sie den Kundenservice, falls das Problem weiterhin bestehen bleibt.",
        el: "Παρουσιάστηκε σφάλμα με το αίτημά σας , παρακαλούμε επικοινωνήστε με το γραφείο υποστήριξης του καζίνο , εάν αυτό το πρόβλημα εξακολουθεί να υφίσταται.",
        es: "Se ha producido un error con su pedido , por favor, póngase en contacto con el servicio de asistencia casino si este problema persiste .",
        fi: "Tapahtui virhe pyynnön, ota yhteyttä kasinon helpdesk jos ongelma jatkuu .",
        fr: "Une erreur s’est produite lors de votre demande, veuillez contacter l’assistance du casino si le problème persiste.",
        it: "È verificato un errore con la vostra richiesta , si prega di contattare l'helpdesk casino se il problema persiste .",
        ja: "ログイン中にエラーが発生しました。問題が続くようであれば、日本語サポートまでお問合せ下さい。",
        jp: "ログイン中にエラーが発生しました。問題が続くようであれば、日本語サポートまでお問合せ下さい。",
        nl: "Er is een fout opgetreden tijdens inloggen. De klantenservice staat klaar voor assistentie als het probleem zich voor blijft doen",
        nn: "Det oppstod en feil med din forespørsel , vennligst kontakt casino kundestøtte hvis problemet vedvarer .",
        no: "Det oppstod en feil med din forespørsel , vennligst kontakt casino kundestøtte hvis problemet vedvarer .",
        pt: "Ocorreu um erro com seu pedido , entre em contato com o helpdesk casino se o problema persistir .",
        sv: "Ett fel uppstod när vi bearbetade din förfrågan, vänligen kontakta vår kundsupport om felet kvarstår.",
        se: "Ett fel uppstod när vi bearbetade din förfrågan, vänligen kontakta vår kundsupport om felet kvarstår."
    }
    var response = customErrors[currentLanguage.toLowerCase()];
    if (!response) {
        response = customErrors.en;
    }
    return response;
};

_DisplayLoginError = function (currentLanguage) {

    var customErrors = {
        en: "The account name or password is incorrect.",
        de: "Der Kontoname oder das Kennwort sind falsch.",
        el: "Το όνομα λογαριασμού ή ο κωδικός πρόσβασης είναι εσφαλμένα.",
        es: "El nombre de cuenta o la contraseña no son correctos.",
        fi: "Tilinimi tai salasana ei kelpaa.",
        fr: "Le nom de compte ou le mot de passe est incorrect.",
        it: "The account name or password is incorrect.",
        ja: "アカウント名またはパスワードが間違っています。",
        jp: "アカウント名またはパスワードが間違っています。",
        nl: "The account name or password is incorrect.",
        nn: "Kontonavnet eller passordet er ugyldig.",
        no: "Kontonavnet eller passordet er ugyldig.",
        pt: "O nome da conta ou a palavra-passe está incorrecta.",
        sv: "Felaktigt kontonamn eller lösenord.",
        se: "Felaktigt kontonamn eller lösenord."
    }
    var response = customErrors[currentLanguage.toLowerCase()];
    if (!response) {
        response = customErrors.en;
    }
    return response;
};

_DisplayCountryNotFound = function (currentLanguage) {

    var customErrors = {
        en: "Sorry, we could not find this country",//
        de: "Leider konnten wir nicht finden, dieses Land",//
        el: "Δυστυχώς, δεν μπορέσαμε να βρούμε αυτή τη χώρα",//
        es: "Lo sentimos, no pudimos encontrar su país",//
        fi: "Valitettavasti maata ei löytynyt",//
        fr: "Désolé, nous n'avons pas trouvé ce pays",//
        it: "Sorry, we could not find this country",//
        ja: "Sorry, we could not find this country",//
        jp: "Sorry, we could not find this country",//
        nl: "Sorry, we could not find this country",//
        nn: "Beklager, vi fant ikke dette landet",//
        no: "Beklager, vi fant ikke dette landet",//
        pt: "Lamentamos, mas não conseguimos encontrar o seu país",//
        sv: "Vi kunde tyvärr inte hitta det landet",//
        se: "Vi kunde tyvärr inte hitta det landet"//
    }
    var response = customErrors[currentLanguage.toLowerCase()];
    if (!response) {
        response = customErrors.en;
    }
    return response;
};

function mergeDataHelper(mergeString, data, tolower) {
	
	if(!mergeString){
		return null;
	}	
	var str = mergeString;
	
	if(tolower){
		var str = str.toLowerCase();
	}	
	
	for (var key in data) {
		if (data.hasOwnProperty(key)) {
			if(data[key] == null){
				data[key] = "";
			}
		
			if(tolower){			
				str = replaceAll(str, "${" + key.toLowerCase() + "}", data[key]);				
			} else {			
				str = replaceAll(str, "${" + key + "}", data[key]);				
			}
		}
	}
	
	return str;
}

function escapeRegExp(string) {
	return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function replaceAll(string, find, replace) {
	return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function CreateCookie(name, value, days, wildcard) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }

    var domain;

    if (wildcard) {
        domain = "; domain=" + GetWildcardDomain(window.location.hostname);
    } else {
        domain = "";
    }

    document.cookie = name + "=" + value + expires + domain + "; path=/";
};

function CreateCookieByDate(name, value, date, wildcard) {
    var expires;
    if (date) {
        date = new Date(date);
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }

    var domain;

    if (wildcard) {
        domain = "; domain=" + GetWildcardDomain(window.location.hostname);
    } else {
        domain = "";
    }

    document.cookie = name + "=" + value + expires + domain + "; 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 EraseCookie(name, wildcard) {
    CreateCookie(name, "", -1, wildcard);
}

function GetWildcardDomain(host) {
    var hostSections = host.split('.');

    var domain;

    if (hostSections.length == 2) {
        domain = "." + hostSections[0] + "." + hostSections[1];
    } else if (hostSections.length >= 3) {
        domain = "";

        for (var index = 1; index < hostSections.length; index++) {
            domain += "." + hostSections[index];
        }
    } else {
        domain = host;
    }

    return domain;
}
function PageScroll() {

    function toTopScrolling() {
        $("html, body").animate({ scrollTop: 0 }, 0);
    }
    
    function toPositionScrolling(heightPos) {
        $("html, body").animate({ scrollTop: heightPos }, 300);
    }

    function disableScrolling() {
        $("body, html").css({
            "height": "100%",
            "overflow": "hidden"
        });
    }

    function enableScrolling() {
        $("body, html").attr("style", "");
        $("body, html").unbind("touchmove");
    }

    return {
        toTopScrolling: function () {
            return toTopScrolling();
        },
        disableScrolling: function () {
            return disableScrolling();
        },
        enableScrolling: function () {
            return enableScrolling();
        },
        toPositionScrolling: function (heightPos) {
            return toPositionScrolling(heightPos);
        }
    };
}
function XmlToJson(xml) {
    var obj = {};
    if (xml.nodeType == 1) {
        if (xml.attributes.length > 0) {
            obj["NodeAttributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["NodeAttributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) {
        obj = xml.nodeValue;
    }

    if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {

            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;

            if (typeof (obj[nodeName]) == "undefined") {
                obj[nodeName] = XmlToJson(item);
            } else {
                if (typeof (obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(XmlToJson(item));
            }

        }
    }
    return obj;
}
function UriLookup() {

    var url = window.location.href;

    parsed_url = {}

    if (url == null || url.length == 0)
        return parsed_url;

    protocol_i = url.indexOf('://');
    parsed_url.protocol = url.substr(0, protocol_i);

    remaining_url = url.substr(protocol_i + 3, url.length);
    domain_i = remaining_url.indexOf('/');
    domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i;
    parsed_url.domain = remaining_url.substr(0, domain_i);
    parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length);

    domain_parts = parsed_url.domain.split('.');
    switch (domain_parts.length) {
        case 2:
            parsed_url.subdomain = null;
            parsed_url.host = domain_parts[0];
            parsed_url.tld = domain_parts[1];
            break;
        case 3:
            parsed_url.subdomain = domain_parts[0];
            parsed_url.host = domain_parts[1];
            parsed_url.tld = domain_parts[2];
            break;
        case 4:
            parsed_url.subdomain = domain_parts[0];
            parsed_url.host = domain_parts[1];
            parsed_url.tld = domain_parts[2] + '.' + domain_parts[3];
            break;
    }

    parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld;

    return parsed_url;

}

function stripTrailingSlash(str) {
	if(str.substr(-1) === '/') {
		return str.substr(0, str.length - 1);
	}
	return str;
}

var queryStringLookup = (function(a) {
	if (a == "") return {};
	var b = {};
	for (var i = 0; i < a.length; ++i)
	{
		var p=a[i].split('=', 2);
		if (p.length == 1)
			b[p[0]] = "";
		else
			b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
	}
	return b;
})(window.location.search.substr(1).split('&'));

function getQueryStringParameterByName(name, url) {
	if (!url) url = window.location.href;
	name = name.replace(/[\[\]]/g, "\\$&");
	var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
		results = regex.exec(url);
	if (!results) return null;
	if (!results[2]) return '';
	return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
/* v.. - Copyright 2011 - 2014, Microgaming - http://www.microgaming.com */
var PTRMF = PTRMF || {}; PTRMF.namespace = function (b) { var d = b.split("."), c = PTRMF, a; if (d[0] === "PTRMF") { d = d.slice(1) } for (a = 0; a < d.length; a++) { if (typeof c[d[a]] === "undefined") { c[d[a]] = {} } c = c[d[a]] } return c }; PTRMF.namespace("forms"); PTRMF.namespace("forms.utils").getUTCDate = function (a) { return Date.UTC(a.getFullYear(), a.getMonth(), a.getDay(), a.getHours(), a.getMinutes(), a.getSeconds(), a.getMilliseconds()) }; PTRMF.namespace("metrics"); PTRMF.metrics = (function (f, h) { var a = {}; var c = []; var b = {}; var d = {}; var m = 5000; var n; var p = function (q) { var s = []; for (var r in q) { s.push({ Key: r, Value: q[r] }) } return s }; var l = function () { if ($.isEmptyObject(a) && c.length === 0 && $.isEmptyObject(b)) { n(); return } var q = { Counts: p(a), Latencies: c, Gauges: p(b) }; var r = PTRMF.services.values.sessionBag.serviceUrl + "/tracking/ClientMetrics?sid=" + (PTRMF.services.values.sessionResponseInfo ? PTRMF.services.values.sessionResponseInfo.SessionId : ""); $.ajax({ url: r, data: { metrics: JSON.stringify(q) }, type: "POST", dataType: "json", complete: function () { n() } }); a = {}; c = []; b = {} }; n = function () { setTimeout(function () { l() }, m) }; var i = function (r, q) { q = q || 1; if (a[r]) { a[r] += q } else { a[r] = q } }; var k = function (r, q) { c.push({ Key: r, Value: q }) }; var j = function (q, r) { b[q] = r }; var o = function (q) { d[q] = new Date() }; var e = function (r) { if (d[r]) { var q = new Date() - d[r]; k(r, q); delete d[r] } }; var g = function (q) { return d.hasOwnProperty(q) }; n(); return { logCount: i, logLatency: k, logGauge: j, startTimer: o, endTimer: e, hasTimer: g } })(); PTRMF.namespace("forms.templates").checkbox = '<fieldset fsIid="${IId}" fsVal="${AdditionalData["default"] ? true : false}" class="checkbox">   <div class="wrapper wrapper-checkbox">     <input type="checkbox"id="${IId}" mode="${Mode}" readonly="readonly" tabindex="${PTRMF.services.values.getNextTabIndex}"     ${AdditionalData["default"]}     {{if (Mand)}}            required      {{/if}}        />   </div>   {{html HtmlStr}} </fieldset> '; PTRMF.namespace("forms.templates").confirmationmessage = '<section class="${Mode} confirmationMessage">   <section class="nobg" id="${Name}">     <span class="icon ${Mode}Icon" />     <p class="${Mode}">${Disp}</p>   </section> </section> '; PTRMF.namespace("forms.templates").date = '<fieldset fsIid="${IId}" fsVal="${Value}" fsType="date" mode="${Mode}" {{if Mode == "cardexpiry"}}           class="monthyear"> {{else}}           max="${Max}"     {{if Mode == "monthyear"}}       class="monthyear">     {{else}}       class="dateofbirth">     {{/if}} {{/if}}   <legend>     ${Disp}   </legend>   <div class="wrapper">     {{if Mode !== "cardexpiry"}}     {{if Mode !== "monthyear"}}     <select fsType="date_day" tabindex="${PTRMF.services.values.getNextTabIndex}">       <option value=""></option>       {{each(i, lookup) LookUps}}        {{if LookUps[i].Val.match(/^[0-9]*$/)}}       <option value="${lookup.Val}">${lookup.Name}</option>       {{/if}}       {{/each}}     </select>     {{/if}}     <select fsType="date_month" tabindex="${PTRMF.services.values.getNextTabIndex}">       <option value=""></option>       {{each(i, lookup) LookUps}}        {{if !LookUps[i].Val.match(/^[0-9]*$/)}}       <option value="${i-31}">${lookup.Name}</option>       {{/if}}       {{/each}}     </select>     {{else}}     <select fsType="date_month" tabindex="${PTRMF.services.values.getNextTabIndex}">       <option value=""></option>       {{each(i, lookup) Months}}        <option value="${Months[i]}">${Months[i]}</option>       {{/each}}     </select>     {{/if}}     <select fsType="date_year" tabindex="${PTRMF.services.values.getNextTabIndex}">       <option value=""></option>       {{each(i, lookup) Years}}        <option value="${Years[i]}">${Years[i]}</option>       {{/each}}     </select>   </div>   <span>${Err}</span>   <span class="serverError"></span> </fieldset> '; PTRMF.namespace("forms.templates").displaybox = '<section class="displayBox">   <p>${Disp}</p><br/>   <p class="displayBoxOutput">${Value}</p> </section>'; PTRMF.namespace("forms.templates").header = '<header fsiid="${IId}">${Disp}</header>'; PTRMF.namespace("forms.templates").hidden = '<input type="hidden" fsIid="${IId}" fsVal="${Value}"/>'; PTRMF.namespace("forms.templates").hiddentracker = '<div style="display: none;">   <form id="${IId}_form" action="${LookupUrl}" method="${Disp}" target="${IId}_iframe">     {{each(i, lookup) LookUps}}       <input type="hidden" name="${lookup.Name}" value="${lookup.Val}" />     {{/each}}     <input type="submit" value="submit" />   </form>   <iframe name="${IId}_iframe" src="about:blank">   </iframe> </div>'; PTRMF.namespace("forms.templates").inputbox = '{{if (Mode == "password")}} <div> {{/if}}   <fieldset fsIid="${IId}" fsVal="${Value}" fsType="${Type}" mode="${Mode}" min="${Min}" max="${Max}" regex="${RX}" valUrl="${ValUrl}"   {{if Mode == "address"}}     class="address"   {{/if}}     >     <legend>${Disp}</legend>     <div class="wrapper{{if ((Max) && (Max >= 20)) }} fullwidth{{/if}}">       <input id="${IId}" value="${PTRMF.controls.controlFactory.formatFormInputValue(Mode, Value)}" line="1" tabindex="${PTRMF.services.values.getNextTabIndex}" maxlength="${Max}"              autocomplete="off" autocorrect="off" autocapitalization="off"        {{if (Max < 20) }}         size="${Max}"       {{/if}}              {{if (Mode == "password")}}              type="password"       {{else}}            {{if (Mode == "email")}}                 type="email"           {{else}}                  type="text"               {{/if}}       {{/if}}         {{if (Mand)}}               required="required"        {{/if}}         {{if ImgUrl}}         placeholder="${ImgUrl}"       {{/if}}              />       {{if Mode == "address"}}         <input type="text" line="2" maxlength="${Max}" value="${PTRMF.controls.controlFactory.formatFormInputValue(Mode, Value, 2)}" tabindex="${PTRMF.services.values.getNextTabIndex}" class="fullwidth" autocomplete="off" autocorrect="off" autocapitalization="off" {{if (Mand)}} required="required" {{/if}} />       {{/if}}       <p class="valicon"></p>     </div>      <span>${Err}</span>     <span class="serverError"></span>   </fieldset>   {{if (Mode == "password")}}   <fieldset class="checkbox" fsMode="${Mode}">     <div class="wrapper">       <input type="checkbox" id="chkShowPassword" inputId="${IId}" tabindex="-1"/>     </div>     <label for="chkShowPassword">${PTRMF.i18n.getString("ShowPassword")}</label>   </fieldset> </div> {{/if}}'; PTRMF.namespace("forms.templates").label = '{{if Mode && Mode.length > 0 && Mode !== "info"}}   <section class="nobg" {{if IId && IId.length > 0}}id="${IId}"{{/if}} >     <span class="icon ${Mode}Icon"></span>     <p class="${Mode}">${Disp}</p>   </section> {{else}}   {{if ((PId) && (PId.length > 0))}} <div>   {{if includeImgSpacer }}     {{if ImgUrl && ImgUrl.length > 0}}       <span class="icon" style="background-image:url(${PTRMF.services.values.sessionBag.serviceUrl}${ImgUrl})"></span>     {{else}}       <span class="spacer"></span>     {{/if}}   {{/if}}   <p>${Disp}</p> </div>   {{else}}   <section class="${Mode}">     <p>${Disp}</p>   </section>   {{/if}} {{/if}}'; PTRMF.namespace("forms.templates").linkbutton = '{{if ((PId) && (PId.length > 0))}}   <li formName="${FormName}" formParameters="${FormParameters}" >     {{if ImgUrl.length > 0}}     <p style="background-image:url(${PTRMF.services.values.sessionBag.serviceUrl}${ImgUrl})"></p>     {{/if}}     <span>${Disp}</span>   </li> {{else}} <section   {{if Mode == "nav" }}     callback="${Value}" {{else}}     {{if Mode != "href" }}       formName="${FormName}" formParameters="${FormParameters}"     {{/if}} {{/if}}   mode="${Mode}" class="info arrow">   {{if ImgUrl.length > 0}}     <span class="icon" style="background-image:url(${PTRMF.services.values.sessionBag.serviceUrl}${ImgUrl})"></span>   {{/if}}   <p>   {{if Mode == "href" }}     <a href="${Value}" target="_blank">${Disp}</a>   {{else}}     ${Disp}   {{/if}}   </p> </section> {{/if}} '; PTRMF.namespace("forms.templates").list = '{{if Value == "1"}} {{if Mode == "menu"}} <div>   {{if Disp.length > 0 }}   <h1>${Disp}</h1>   {{/if}} <ul>   {{html PTRMF.controls.controlFactory.getChildrenHtml(Children)}} </ul> </div> {{else}} {{if Disp.length > 0 }}   <h1>${Disp}</h1>   {{/if}} <section class="${Mode} ${IId}">   {{if Mode == "info" }}     {{html PTRMF.controls.controlFactory.getChildrenHtml(Children, "true")}}   {{else}}     {{html PTRMF.controls.controlFactory.getChildrenHtml(Children)}}   {{/if}} </section> {{/if}} {{else Mode == "radiogroup"}} <fieldset fsiid="${IId}" fsval="${Value}" class="radiogroup">     <legend>${Disp}</legend>     <ul>         {{html PTRMF.controls.controlFactory.getChildrenHtml(Children)}}     </ul> </fieldset> {{else}} <footer>   {{if Children.length > 0}}   {{html PTRMF.controls.controlFactory.getChildrenHtml(Children)}}   {{/if}} </footer> {{/if}} '; PTRMF.namespace("forms.templates").multifieldvalidator = '<section class="failure" style="display: none;">   <span class="icon failureIcon"></span>   <p class="failure"></p>   <div style="display: none;" fsIid="${IId}" mode="${Mode}" id="${IId}" class="multiFieldValidator" data-targets="${Value}" data-state="ready" data-global-error-target="${DepIId}"/> </section>'; PTRMF.namespace("forms.templates").navbutton = '<span value="${Value}" mode="${Mode}" pageID="${GId}" tabindex="-1" class="button">${Disp}</span>  '; PTRMF.namespace("forms.templates").numeric = '<fieldset fsIid="${IId}" fsVal="${CentsValue}" valUrl="${ValUrl}" regex="${RX}" mode="${Mode}" min="${Min}" max="${Max}" mandatory="${Mand}"     {{if Mode == "creditcard"}}         class="${LookUps[0].Val}"     {{/if}}     {{if Mode == "creditcard" && LookUps.length == 3}}       data-pci-enabled="true"       data-pci-url="${LookUps[1].Val}"       data-pci-token="${LookUps[2].Val}"     {{/if}}     {{if Mode == "creditcard" && LookUps.length == 1}}       data-pci-enabled="false"     {{/if}} >   <legend>${Disp}</legend>   <div class="wrapper{{if ((Max) && (Max >= 20)) }} fullwidth{{/if}}">     <input id="${IId}" fsType="number" value="${Value}" tabindex="${PTRMF.services.values.getNextTabIndex}" mode="${Mode}"             autocomplete="off" autocorrect="off" autocapitalization="off"      {{if (Mode == "amount") }}        type="number" step="0.1"     {{else}}        type="tel" step="1"     {{/if}}     {{if (Max < 20) }}       size="${parseInt(Max) + 2}"       maxlength="${Max}"     {{/if}}     {{if ImgUrl}}       placeholder="${ImgUrl}"     {{/if}}     {{if Mand}}     required      {{/if}}      />     <p class="valicon"></p>   </div>   {{if (Mode == "creditcard" || Mode == "cvv") }}     <p class="outericon"></p>   {{/if}}   <span>${Err}</span>   <span class="serverError"></span> </fieldset>'; PTRMF.namespace("forms.templates").phonenumber = '<div>   <fieldset fsIid="${IId}" fsVal="${Value}" fsType="${Type}" mode="${Mode}" min="${Min}" max="${Max}" regex="${RX}" valUrl="${ValUrl}" class="phonenumber">     <legend>${Disp}</legend>       <div  id="${IId}IntDialingCodeContainer" class="wrapper">           <input id="${IId}IntDialingCode" type="text" maxlength="4" disabled="true" type="tel"/>           <input id="${IId}" value="${Value}" line="1" tabindex="${PTRMF.services.values.getNextTabIndex}" maxlength="${Max}"                  autocomplete="off" autocorrect="off" autocapitalization="off"  type="tel"           {{if (Mand)}}                  required="required"            {{/if}}/>            <p class="valicon"></p></div>     <span>${Err}</span>     <span class="serverError"></span>   </fieldset> </div> '; PTRMF.namespace("forms.templates").radiobutton = '{{if ((PId) && (PId.length > 0))}} <li {{if (Mode.length > 0)}} class="selected" {{/if}}>   <span>{{html PTRMF.controls.controlFactory.ParseOrCreateFromValueJson(Disp).Text}}</span>   {{if PTRMF.controls.controlFactory.ParseOrCreateFromValueJson(Disp).SubText}}   <div>{{html PTRMF.controls.controlFactory.ParseOrCreateFromValueJson(Disp).SubText}}</div>   {{/if}}   <input type="radio" name="${PId}" value="${Value}" class="check" {{if (Mode.length > 0)}} checked="checked" {{/if}}/> </li> {{/if}}   '; PTRMF.namespace("forms.templates").select = '<fieldset fsIid="${IId}"  {{if ((Value.length == 0) && (LookUps.length > 0))}}     fsVal="${LookUps[0].Val}"     {{if LookUps[0].Val.length > 0}}         class="valid"     {{/if}} {{else}}   fsVal="${Value}" {{/if}} {{if LookUps.length <= 0}}     class="disabled" {{/if}}   >   <legend>${Disp}</legend>   <div class="wrapper select">   <select id="${IId}" fsType="select" tabindex="${PTRMF.services.values.getNextTabIndex}"   {{if Dependants.length > 0}}     dependants="${Dependants.join(",")}"     {{else}}     {{if LookUps.length > 0}}     fsVal="${LookUps[0].Val}"     value="${LookUps[0].Name}"     {{/if}}     {{/if}}     {{if LookUps.length <= 0}}     disabled="disabled"     {{/if}}     {{if (Mand)}}     required      {{/if}}      >     {{if LookUps.length > 0}}     {{each(i, lookup) LookUps}}      <option value="${lookup.Val}"      {{if (Value.length > 0) && (Value == lookup.Val)}}       selected       {{/if}}       >${lookup.Name}     </option>     {{/each}}     {{/if}}   </select>   <p class="valicon"></p>   </div>   <span>${Err}</span> </fieldset> '; PTRMF.namespace("forms.templates").tabstrip = '<nav> {{each(i, lookup) LookUps}} 	<span formName="${lookup.formName}"  	{{if  (i + 1)==Value }}           class="active"   {{/if}} 	> 	  ${lookup.Name} 	</span> {{/each}} </nav> '; PTRMF.namespace("forms.templates").unknown = "${Type} : ${IId} "; PTRMF.namespace("forms.templates").waitcontrol = '  <section class="nobg waitcontrol" fsVal="${Value}" fsIid="${IId}" >     <span class="icon waitIcon"></span>     <p>${Disp}</p>   </section> '; $.fn.outerHTML = function (a) { return a ? this.before(a).remove() : $("<p>").append(this.eq(0).clone()).html() }; $.fn.spin = function (a) { this.each(function () { var b = $(this), c = b.data(); if (c.spinner) { c.spinner.stop(); delete c.spinner } if (a !== false) { c.spinner = new Spinner($.extend({}, a)).spin(this) } }); return this }; $.fn.stopSpin = function () { this.each(function () { var a = $(this), b = a.data(); if (b.spinner) { b.spinner.stop(); delete b.spinner } }); return this }; PTRMF.namespace("controls").controlFactory = PTRMF.controls.controlFactory || { render: function (c) { var e = [], j, m = [], a, d, k, g = "", l, f; for (j = 0; j < c.FormControls.length; j++) { a = c.FormControls[j]; f = this.getGroup(a.GId, e); if (f.length == 0) { d = { GId: a.GId, SectionMU: "", NonSectionMU: "" }; e.push(d) } else { d = f[0] } if (m.indexOf(a.IId) == -1) { k = this.getControlModel(a); if (this.isSectionControl(a)) { k = this.addChildrenToModel(k, c.FormControls, m) } if (a.Type === "select") { k = this.addDependantsIds(k, c.FormControls) } l = this.getControl(k).outerHTML(); if (a.Type == "hiddentracker") { l += '<script type="text/javascript">$("#' + a.IId + '_form").submit();</script>' } if (this.isSectionControl(a)) { d.SectionMU += l } else { d.NonSectionMU += l } m.push(a.IId) } } if (e.length == 1) { g += "<view>"; g += e[0].NonSectionMU; g += "<article>" + e[0].SectionMU + "</article>"; g += "</view>" } else { for (j = 0; j < e.length; j++) { (j == 0) ? g += "<view>" : g += '<view style="display:none">'; g += e[j].NonSectionMU; g += "<article>" + e[j].SectionMU + "</article>"; g += "</view>" } } var h = $(g); var b = h.find("section.failure  p"); if (b.length) { b.html(h.find("section.failure  p").html().replace(/(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/gi, '<a href="mailto:$1">$1</a>')) } return h }, getChildrenHtml: function (b, d) { var c = "", a; if ((b) && (b.length > 0)) { $(b).each(function (f, e) { var g = PTRMF.controls.controlFactory.getControlModel(e); if (d && d === "true") { if ((g.ImgUrl && g.ImgUrl.length > 0) || (f > 0)) { g.includeImgSpacer = "true" } } a = PTRMF.controls.controlFactory.getControl(g); c += $(a).outerHTML() }) } return c }, getControl: function (a) { if (typeof a === "undefined") { return "" } if (typeof PTRMF.forms.templates[a.Type] === "undefined") { return "" } if (a.Type === "numeric" && a.Mode === "phonenumber") { return $.tmpl(PTRMF.forms.templates.phonenumber, a) } else { return $.tmpl(PTRMF.forms.templates[a.Type], a) } }, isSectionControl: function (a) { var b = a.Type.toLowerCase(); return (!((b === "header") || (b === "tabstrip"))) }, getGroup: function (a, b) { return $.grep(b, function (c, d) { return c.GId == a }) }, getControlModel: function (a) { var b; switch (a.Type.toLowerCase()) { case "date": b = this.getDateModel(a); break; case "linkbutton": b = this.getLinkButtonModel(a); break; case "tabstrip": b = this.getTabStripModel(a); break; case "checkbox": b = this.getCheckboxModel(a); break; case "numeric": b = this.getNumericModel(a); default: b = a } return b }, addChildrenToModel: function (b, c, e) { var d, a; b.Children = []; for (d = 0; d < c.length; d++) { if (c[d].PId === b.IId) { a = c[d]; b.Children.push(a); e.push(a.IId) } } return b }, addDependantsIds: function (a, c) { var d, b = []; for (d = 0; d < c.length; d++) { if (c[d].DepIId === a.IId) { b.push(c[d].IId) } } a.Dependants = b; return a }, getCheckboxModel: function (a) { var c = a.Disp; if (a.Mode === "terms") { var e = a.Disp.match(/\[%+(.*?)%\]/g); var g = a.Value.split(";"); if (e != null && e.length > 0) { if (e.length != g.length) { throw a.IId + ": Errors processing urls" } else { for (var b = 0; b < e.length; b++) { var d = e[b].substring(2, e[b].length - 2); var f = '<a href="' + g[b] + '" target="_blank" tabindex="-1">' + d + "</a>"; c = c.replace(e[b], f) } } } } a.HtmlStr = '<label for="' + a.IId + '">' + c + "</label>"; return a }, getTabStripModel: function (a) { var b; for (b = a.LookUps.length - 1; b >= 0; b--) { a.LookUps[b].formName = a.LookUps[b].Val } return a }, getLinkButtonModel: function (a) { a.FormName = a.Value; a.FormParameters = a.LookUps.length === 0 ? "" : JSON.stringify(a.LookUps); return a }, getNumericModel: function (a) { if (a.Mode == "amount") { if (a.Value) { a.CentsValue = a.Value; a.Value = (a.Value / 100).toFixed(2) } } return a }, ParseOrCreateFromValueJson: function (a) { var c; try { c = $.parseJSON(a) } catch (b) { c = { Text: a } } return c }, getDateModel: function (a) { var j = [], g = [], d, c, h, f, b; var e = a.Mode.toLowerCase(); if (e == "cardexpiry") { b = new Date(); var i = b.getFullYear(); for (h = 0; h < 100; h++) { j.push(i + h) } for (h = 1; h < 13; h++) { (h < 10) ? f = "0" + h : f = h; g.push(f) } } else { if ((a.Min && a.Min.length > 0) && (a.Max && a.Max.length > 0)) { d = a.Min.split("/")[0]; c = a.Max.split("/")[0] } else { b = new Date(); d = b.getFullYear() - 100; c = b.getFullYear() + 100 } for (h = c; h >= d; h--) { j.push(h) } } a.Years = j; a.Months = g; return a }, formatFormInputValue: function (c, d, b) { if (c.toLowerCase() === "address") { if (d.length === 0) { return "" } b = b ? b - 1 : 0; var a = d.split(/\r\n|\r|\n/g); if (typeof a[b] === "undefined") { return "" } return a[b] } return d } }; PTRMF.namespace("ui").UIManager = PTRMF.ui.UIManager || { NavigateTo: function (a, b, c) { this.ShowLoader(); PTRMF.services.operations.getForm(a, b, function (d) { PTRMF.ui.UIManager.RenderResponseToContainer(d); $.each((PTRMF.services.values.container).find("select[dependants]"), function (g, f) { PTRMF.events.eventManager.PopulateDependantDropDowns($(f)) }); PTRMF.events.eventManager.WireUpForm(c); PTRMF.services.values.formRenderedCallback(); PTRMF.ui.UIManager.HideLoader() }) }, MoveToNextView: function (b) { var d = $(b).parents("view:first"), a = $(d).next("view"); var c = function () { PTRMF.ui.UIManager.MoveToNextView(b) }; if (PTRMF.ui.UIManager.IsBusy(c, d)) { return } if (PTRMF.validation.validator.validateView(d)) { this.ShowFalseLoader(500); d.hide(); a.show(); PTRMF.services.values.pageViewChanged() } else { if (PTRMF.ui.UIManager.IsBusy(c, d)) { return } } }, MoveToPreviousView: function (b) { var c = $(b).parents("view:first"), a = $(c).prev("view"); if (a.length > 0) { this.ShowFalseLoader(500); c.hide(); a.show(); PTRMF.services.values.pageViewChanged() } else { this.ShowLoader(); PTRMF.services.operations.getPreviousForm(function (d) { PTRMF.ui.UIManager.LoadContents(d); PTRMF.ui.UIManager.HideLoader() }) } }, Submit: function (b) { var d = $(b).parents("view:first"); $(d).find("section.confirmationMessage").remove(); var c = function () { PTRMF.ui.UIManager.Submit(b) }; if (PTRMF.ui.UIManager.IsBusy(c, d)) { return } var a = true; if (PTRMF.validation.validator.validateView(d, a)) { if (PTRMF.ui.UIManager.IsBusy(c, d)) { return } this.ShowLoader(); PTRMF.services.operations.processForm($(b).attr("value"), function (e) { PTRMF.ui.UIManager.HideLoader() }) } else { $(".formsService section.validation-summary").css("display", "block") } }, IsBusy: function (a, b) { if (PTRMF.validation.validator.isViewBusyValidating(b)) { PTRMF.services.values.pendingSubmitCall = function () { PTRMF.services.values.pendingSubmitCall = null; a() }; return true } else { return false } }, OpenPopup: function (g) { var j = $(g).parents("view:first"); if (!PTRMF.validation.validator.validateView(j)) { return } var h = JSON.parse($(g).attr("value")); var k = h.url; if (h.parameters && h.parameters.length > 0) { k = k + "?"; for (var b = 0; b < h.parameters.length; b++) { k = k + h.parameters[b][0] + "=" + h.parameters[b][1]; if (b < h.parameters.length - 1) { k += "&" } } } if (h.submitForm === true) { var f = function () { PTRMF.ui.UIManager.ShowLoader(); PTRMF.services.operations.processForm("submit", function () { PTRMF.ui.UIManager.HideLoader() }) }; if (window.hasOwnProperty("onpageshow")) { var e = window.onpageshow; window.onpageshow = function () { window.onpageshow = e; f(); if (e) { e() } } } else { var c = setInterval(function () { clearInterval(c); f() }, 3000) } } if (!h.openInOwnWindow && window.navigator.standalone) { window.location.href = k } else { var d = document.createElement("a"); d.setAttribute("href", k); if (h.openInOwnWindow) { d.setAttribute("target", "_blank") } else { d.setAttribute("target", "_self") } if (d.click) { d.click() } else { var a = document.createEvent("HTMLEvents"); a.initEvent("click", true, true); d.dispatchEvent(a) } } }, LoadContents: function (a) { if (!$(PTRMF.services.values.container).hasClass("formsService")) { $(PTRMF.services.values.container).addClass("formsService") } PTRMF.ui.UIManager.RenderResponseToContainer(a); $.each((PTRMF.services.values.container).find("select[dependants]"), function (c, b) { PTRMF.events.eventManager.PopulateDependantDropDowns($(b)) }); PTRMF.events.eventManager.WireUpForm(); PTRMF.services.values.formRenderedCallback() }, RenderResponseToContainer: function (b) { $(PTRMF.services.values.container).attr("data-form", b.FormName); var a = PTRMF.controls.controlFactory.render(b); PTRMF.services.values.container.html(a) }, SetControlStyle: function (a, b) { $(a).removeClass("valid invalid focus server-invalid"); if (b) { $(a).addClass(b) } }, ShowFalseLoader: function (a) { this.ShowLoader(); setTimeout(function () { PTRMF.ui.UIManager.HideLoader() }, a) }, ShowLoader: function () { if (PTRMF.services.values.hasOwnProperty("ShowLoader")) { PTRMF.services.values.ShowLoader(); return } var a = $(".formsservicemodal"); if (a.length === 0) { a = $("<div></div>").addClass("formsservicemodal").html("<span><p></p></span>"); $(PTRMF.services.values.container).after(a); a.css({ top: $(window).scrollTop() - 100, height: (window.innerHeight || window.height) + 100 }) } var b = new Spinner(this.spinnerOptions).spin(); a.find("span > p").html(b.el); a.bind("touchmove", function (c) { c.preventDefault() }); a.css({ top: $(window).scrollTop() - 100, height: (window.innerHeight || window.height) + 100 }); a.show() }, HideLoader: function () { if (PTRMF.services.values.hasOwnProperty("HideLoader")) { PTRMF.services.values.HideLoader(); return } $(".formsservicemodal").remove() }, GetFormResponseHandler: function (a) { PTRMF.ui.UIManager.LoadContents(a); PTRMF.ui.UIManager.HideLoader() }, CloseBrowserWindow: function (b) { var a = this; a.ShowLoader(); window.close(); setTimeout(function () { var d = PTRMF.i18n.getString("CantCloseWindow"); if (b && b.is(".formsService span.button")) { var c = PTRMF.controls.controlFactory.getControl({ Type: "label", Mode: "info", includeImgSpacer: true, Disp: d, PId: null }); b.hide(); b.parent().append(c) } else { alert(d) } a.HideLoader() }, 2000) }, resetAndShowLoader: function (b, a) { PTRMF.services.values.reset(); PTRMF.services.values.container = $(b); if (a) { PTRMF.services.values.setCallbacks(a) } this.ShowLoader() }, spinnerOptions: { lines: 12, length: 11, width: 4, radius: 10, color: "#C8C8C8", speed: 1, trail: 100, shadow: false } }; PTRMF.namespace("events").eventManager = PTRMF.events.eventManager || { numericChangingState: false, WireUpForm: function () { this.WireTabNavigation(); this.WireLinkButtons(); this.WireDropdowns(); this.WireDatePickers(); this.WireInputControls(); this.WireNavButtons(); this.WireWaitControls(); this.WireRadioButtons(); this.WireMultiFieldValidators(); this.WirePhoneNumberInputs() }, WireNavButtons: function () { var a = $(PTRMF.services.values.container); $(a).find('span[value="next"]').click(function () { PTRMF.ui.UIManager.MoveToNextView($(this)) }); $(a).find('span[value="prev"]').click(function () { PTRMF.ui.UIManager.MoveToPreviousView($(this)) }); $(a).find('span[mode="submit"]').click(function () { PTRMF.ui.UIManager.Submit($(this)) }); $(a).find('span[mode="popup"]').click(function () { PTRMF.ui.UIManager.OpenPopup($(this)) }); $(a).find('span[value="restart"]').click(function () { PTRMF.services.operations.getFirstForm(function (b) { PTRMF.ui.UIManager.LoadContents(b) }) }); $(a).find('span[value="close"]').click(function () { PTRMF.services.values.closeFormCallback($(this)) }); $(a).find('span[value="games"],section[callback="games"]').click(function () { PTRMF.services.values.backToGamesCallback() }); $(a).find('span[value="gameslogin"],section[callback="gameslogin"]').click(function () { PTRMF.services.values.gotoLoginCallback() }) }, WireInputControls: function () { var a = $(PTRMF.services.values.container); $(a).find('input,select[fsType="select"]').change(function () { PTRMF.events.eventManager.InputChangeEventHandler($(this)) }); $(a).find("input,select").focusin(function (b) { var c = PTRMF.validation.validator.getContainerFieldSet($(this)); if ($(c).attr("mode") === "amount" && $(this).val() === "0.00") { $(this).val(""); $(c).attr("fsval", 0); $(c).removeClass("valid") } if (!(($(c).hasClass("valid")) || ($(c).hasClass("invalid")))) { PTRMF.ui.UIManager.SetControlStyle($(c), "focus") } }); $(a).find("input,select").blur(function () { var b = PTRMF.validation.validator.getContainerFieldSet($(this)); $(b).removeClass("focus"); if ($(b).attr("mode") === "amount" && $(this).val() == "") { if (!this.validity.valid) { PTRMF.ui.UIManager.SetControlStyle($(b), "invalid") } else { if ($(b).attr("mandatory") === "true") { $(this).val("0.00").change() } else { if (b.attr("fsval") != $(this).val()) { $(this).change() } else { $(b).removeClass("validating valid invalid server-invalid") } } } } }); $(a).find('input[fsType="number"]').keydown(function (c) { if (PTRMF.validation.validator.checkNumericLengthLimit($(this))) { var b = [8, 255, 4, 46]; if (b.indexOf(c.keyCode) == -1) { c.preventDefault() } } }) }, InputChangeEventHandler: function (c) { var b = PTRMF.validation.validator.getContainerFieldSet($(c)); var a = $("div.formsService:first").attr("data-form"); PTRMF.metrics.logCount("5if." + a + "." + b.attr("fsiid")); if (b.attr("mode") == "amount") { this.HandleAmountFieldUpdate(c, b) } else { PTRMF.events.eventManager.SetInputValue($(c)) } if ($(c).attr("inputid") !== "Password") { PTRMF.validation.validator.setValid(c) } }, HandleAmountFieldUpdate: function (d, a) { if (a.attr("mandatory") === "false" && a.find("input:first").val() === "") { $(a).attr("fsVal", "") } else { var b = $(d).val(); if (b.length == 0 || b === "0") { $(d).val("0.00") } else { if (!isNaN(new Number(b))) { var c = new Number(b); c = Math.min(c, 21474836.47); $(d).val(c.toFixed(2)); $(a).attr("fsVal", Math.round(c * 100)) } } } }, ZeroFill: function (a, b) { b -= a.toString().length; if (b > 0) { return new Array(b + (/\./.test(a) ? 2 : 1)).join("0") + a } else { return a + "" } }, WireTabNavigation: function () { $(PTRMF.services.values.container).find("nav span").click(function () { PTRMF.ui.UIManager.NavigateTo($(this).attr("formName"), [], $(PTRMF.services.values.container)) }) }, WireLinkButtons: function () { $(PTRMF.services.values.container).find("li[formName],section[formName]").click(function () { PTRMF.ui.UIManager.NavigateTo($(this).attr("formName"), $(this).attr("formParameters"), $(PTRMF.services.values.container)) }) }, WireDatePickers: function () { $(PTRMF.services.values.container).find('select[fsType="date_day"]').change(function () { var a = $(this).val(); var b = $(this).next("select").val(); var c = $(this).next("select").next("select").val(); PTRMF.events.eventManager.SetDatePickerValue($(this), a, b, c) }); $(PTRMF.services.values.container).find('select[fsType="date_month"]').change(function () { var c = $(this).val(), a; ($(this).parents("fieldset").attr("mode").toLowerCase() === "cardexpiry") ? a = 1 : a = $(this).prev("select").val() || 1; var d = $(this).next("select").val(); var b = PTRMF.events.helpers.getLeapYearDaysList(c, d, a); $(this).prev("select").html(b); PTRMF.events.eventManager.SetDatePickerValue($(this), a, c, d); $(PTRMF.services.values.container).find('select[fsType="date_day"]').change() }); $(PTRMF.services.values.container).find('select[fsType="date_year"]').change(function () { var c = $(this).prev("select").val(), a; ($(this).parents("fieldset").attr("mode").toLowerCase() === "cardexpiry") ? a = 1 : a = $(this).siblings('select[fsType="date_day"]').val() || 1; var d = $(this).val(); var b = PTRMF.events.helpers.getLeapYearDaysList(c, d, a); $(this).siblings('select[fsType="date_day"]').html(b); PTRMF.events.eventManager.SetDatePickerValue($(this), a, c, d); $(PTRMF.services.values.container).find('select[fsType="date_day"]').change() }) }, SetDatePickerValue: function (f, a, d, g) { var e, b, c = $(f).parents("fieldset"); e = PTRMF.events.helpers.getEnglishMonthName(parseInt(d, 10) + 1); (c.attr("mode").toLowerCase() === "cardexpiry") ? b = d + "/" + g : b = a + " " + e + " " + g; c.attr("fsVal", b); PTRMF.validation.validator.setValid(f) }, SetInputValue: function (h) { var a = $(h).parents("fieldset"), i = $(h).attr("type"); switch (i) { case "checkbox": if (a.attr("fsMode") === "password") { var f = $('fieldset[fsIId="' + $(h).attr("inputId") + '"]').find("input:first"); var g = "text"; if ($(f).attr("type") === "text") { g = "password" } f[0].setAttribute("type", g) } else { var c = "true"; if ($(h).attr("checked") !== "checked") { c = "false" } a.attr("fsVal", c) } break; case "tel": case "number": case "text": if (a.attr("mode") === "phonenumber") { var b = $("#" + a.attr("fsiid") + "IntDialingCode").val(); a.attr("fsVal", b + h.val().replace(/^0/g, "")) } else { if (a.attr("mode") === "address") { var d, e; if ($(h).attr("line") === "2") { d = $(h).siblings('input[line="1"]:first'); e = $(h) } else { d = $(h); e = $(h).siblings('input[line="2"]:first') } a.attr("fsVal", d.val() + "\n" + e.val()) } else { a.attr("fsVal", h.val()) } } break; case "radio": if ($(h).attr("checked") === "checked") { a.attr("fsVal", h.val()) } break; default: a.attr("fsVal", h.val()); break } }, WireDropdowns: function () { $("select").change(function () { PTRMF.events.eventManager.PopulateDependantDropDowns($(this)) }) }, PopulateDependantDropDowns: function (c) { if (($(c).attr("dependants")) && ($(c).attr("dependants").length > 0)) { var a = $(c).attr("dependants").split(","); var b; for (b = 0; b < a.length; b++) { if ($('fieldset[fsIId="' + a[b] + '"][mode="phonenumber"]').length > 0) { PTRMF.events.eventManager.GetInputLookupItem(a[b], $(c).val(), a[b] + "IntDialingCode") } else { if ($("#" + a[b]).is("input")) { PTRMF.events.eventManager.GetInputLookupItem(a[b], $(c).val()) } else { PTRMF.events.eventManager.GetSelectListItems(a[b], $(c).val()) } } } } $(c).attr("fsVal", $(c).val()) }, GetSelectListItems: function (b, a) { PTRMF.ui.UIManager.ShowLoader(); PTRMF.services.operations.getLookups(PTRMF.services.values.currentForm.FormName, b, a, function (e) { var c = $('select[id="' + b + '"]'); c.html(); var f = ""; for (var g = 0; g < e.length; g++) { f = f + '<option value="' + e[g].Val + '">' + e[g].Name + "</li>" } c.html(f); var d = $('fieldset[fsIId="' + b + '"]'); if (f.length > 0) { c.removeAttr("disabled", ""); c.parents("fieldset").removeClass("disabled"); c.change() } else { c.html("<option>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>"); c.attr("disabled", "disabled"); c.parents("fieldset").addClass("disabled"); d.attr("fsVal", null); PTRMF.events.eventManager.PopulateDependantDropDowns(c) } PTRMF.ui.UIManager.HideLoader(); if (c.is(":focus")) { c.blur(); c.focus() } }) }, GetInputLookupItem: function (c, b, a) { if (!a) { a = c } PTRMF.ui.UIManager.ShowLoader(); PTRMF.services.operations.getLookups(PTRMF.services.values.currentForm.FormName, c, b, function (e) { var d = $("#" + a); if (e.length > 0) { d.val(e[0].Val); PTRMF.events.eventManager.SetInputValue(d); if ($('fieldset[fsIId="' + c + '"]').is(".valid, .invalid")) { $("#" + c).change() } } PTRMF.ui.UIManager.HideLoader(); if (d.is(":focus")) { d.blur(); d.focus() } }) }, WireWaitControls: function () { var c = $(".waitcontrol").first(); if (c.length !== 1) { return } var b = $.extend({}, PTRMF.ui.UIManager.spinnerOptions, { color: "black", length: 6, width: 2, radius: 6 }); c.find(".waitIcon").spin(b); var a = function () { var g = c.attr("fsiid"); var d = c.attr("fsval"); try { PTRMF.services.operations.serverValidate(PTRMF.services.values.currentForm.FormName, g, d, function (e) { if (!e.Valid) { setTimeout(a, 5000) } else { PTRMF.ui.UIManager.Submit(c) } }) } catch (f) { PTRMF.ui.UIManager.Submit(c) } }; setTimeout(a, 5000) }, RadioButtonClick: function (a) { $(a).siblings().removeClass("selected"); $(a).addClass("selected"); $(a).children("input[type=radio]")[0].click() }, WireRadioButtons: function () { var a = $("fieldset input[type=radio][checked=checked]"); a.each(function () { $(this).parents("fieldset").attr("fsVal", $(this).val()) }); $(".formsService fieldset.radiogroup ul li").click(function () { PTRMF.events.eventManager.RadioButtonClick($(this)) }) }, WireMultiFieldValidators: function () { $(".formsService div.multiFieldValidator").each(function (b, a) { var d = $(this).attr("Mode"); if (d == null || d !== "submit") { var h = $(this).attr("fsIid"); var g = $(a).attr("data-targets").split(","); var f = []; for (var c = 0; c < g.length; c++) { f.push($('fieldset[fsIid="' + g[c] + '"]')); f[c].attr("data-notify-post-validate", $(a).attr("id")) } $(a).bind("post-validate", function (e) { if (!$(this).is(".validating")) { PTRMF.validation.validator.doMultipleInputServerValidation(f, e.sourceInputId, h) } }) } }) }, WirePhoneNumberInputs: function () { $('fieldset[fstype="numeric"][mode="phonenumber"]').each(function (c, a) { var b = $(this).attr("fsIid"); $("#" + b + "IntDialingCodeContainer").click(function () { $("#" + b).focus() }) }) } }; PTRMF.namespace("events").helpers = PTRMF.events.helpers || { isLeapYear: function (a) { return new Date(a, 1, 29).getDate() == 29 }, getLeapYearDaysList: function (d, h, f) { var e, a, c = "", b, g; if (d == 1) { this.isLeapYear(h) ? e = 29 : e = 28 } else { if (d < 7) { (d % 2 == 0) ? e = 31 : e = 30 } else { (d % 2 == 0) ? e = 30 : e = 31 } } for (a = 1; a <= e; a++) { (parseInt(f) === a) ? b = " selected" : b = ""; (a < 10) ? g = "0" + a : g = a; c += '<option value="' + g + '"' + b + ">" + g + "</option>" } return c }, getEnglishMonthName: function (a) { switch (a) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return "" } } }; PTRMF.namespace("services").helpers = PTRMF.services.helpers || { buildServiceRequestStr: function (a, c) { if (typeof c === "undefined") { return JSON.stringify({ FormName: a, Parameters: [] }) } else { var d = [], b; for (b = 0; b < c.length; b++) { d.push({ Name: c[b].Name, Val: c[b].Val }) } return JSON.stringify({ FormName: a, Parameters: d }) } }, buildBaseRequest: function (c, b) { var a = c.toLowerCase() === "opensession" || c.toLowerCase() === "resumesession" ? "session" : "forms"; var e = PTRMF.services.values.sessionBag.serviceUrl + "/" + a + "/" + c; var d; if (c.toLowerCase() === "getform") { d = this.buildServiceRequestStr(b.formName, b.lookups) } else { d = JSON.stringify(b) } return { url: e, requestStr: d } }, buildFormsServiceUrl: function (c, b) { var a = PTRMF.services.helpers.buildBaseRequest(c, b); a.url += "?"; if (PTRMF.services.values.sessionResponseInfo) { a.url += "sid=" + PTRMF.services.values.sessionResponseInfo.SessionId + "&" } a.url += "requestStr=" + a.requestStr; return a.url }, buildFormsServicePostRequest: function (d, c) { var a; if (c && c.authToken) { a = c.authToken; delete c.authToken } var b = PTRMF.services.helpers.buildBaseRequest(d, c); var c = { requestStr: b.requestStr }; if (PTRMF.services.values.sessionResponseInfo) { c.sid = PTRMF.services.values.sessionResponseInfo.SessionId } if (a) { c.authToken = a } return { url: b.url, data: c } } }; PTRMF.namespace("services").session = PTRMF.services.session || { open: function (a) { var b = PTRMF.services.values.sessionBag; b.clientUrl = window.location.href; var c = PTRMF.services.helpers.buildFormsServicePostRequest("opensession", b); $.ajax({ type: "POST", url: c.url, data: c.data, success: function (d) { PTRMF.services.values.sessionResponseInfo = d; PTRMF.metrics.logCount("5os"); a(d) } }) }, resume: function (c, a) { var b = PTRMF.services.helpers.buildFormsServicePostRequest("resumesession", null); b.url += (b.url.indexOf("?") > -1 ? "&" : "?") + "sid=" + c; $.ajax({ type: "POST", url: b.url, data: b.data, success: function (d) { if (d.State !== "Invalid") { PTRMF.services.values.sessionResponseInfo = d; a(d) } else { PTRMF.services.session.open(a) } }, error: function () { PTRMF.services.session.open(a) } }) } }; PTRMF.namespace("services").operations = PTRMF.services.operations || { getForm: function (c, d, a) { PTRMF.metrics.startTimer("5gf." + c); if (typeof d === "string") { try { d = $.parseJSON(d) === null ? [] : $.parseJSON(d) } catch (b) { d = [] } } if (PTRMF.services.values.currentForm.FormName.length > 0) { PTRMF.services.values.pageStack.push(PTRMF.services.values.currentForm) } this.makeServiceCall("GetForm", { formName: c, lookups: d }, function (e) { PTRMF.services.values.currentTabIndex = 0; PTRMF.services.values.currentForm = { FormName: e.FormName || c, Parameters: d }; PTRMF.services.values.getFormCallback({ FormName: PTRMF.services.values.currentForm.FormName, SystemInfoRequest: e.SystemInfoRequest, Status: e.Status }); a(e); PTRMF.metrics.startTimer("5tof." + c); PTRMF.metrics.endTimer("5gf." + c) }) }, getPreviousForm: function (a) { var b = PTRMF.services.values.pageStack.pop(); this.getForm(b.FormName, b.Parameters, a) }, getFirstForm: function (a) { this.getForm(PTRMF.services.values.firstForm.FormName, PTRMF.services.values.firstForm.Parameters, a) }, processForm: function (f, a) { var d = [], c, e; PTRMF.metrics.startTimer("5pf." + PTRMF.services.values.currentForm.FormName); PTRMF.services.values.container.find("[fsIId]").each(function () { var i = $(this); var j = i.attr("fsIId"); var l = i.attr("fsVal"); if (i.data("pci-enabled")) { var h = $.Deferred(); e = h.promise(); PTRMF.metrics.startTimer("5pcit"); PTRMF.metrics.logCount("5pcir.attempt"); $.ajax({ url: i.data("pci-url"), data: { EncryptionList: [{ ClearText: i.attr("fsVal") }] }, dataType: "json", type: "POST", headers: { "Access-Token": i.data("pci-token") }, complete: function (n, m) { PTRMF.metrics.endTimer("5pcit"); PTRMF.metrics.logCount("5pcir." + m) } }).done(function k(m) { d.forEach(function (n) { if (n.IId === j) { n.Val = m[0].Token; return false } }); h.resolve() }) } d.push({ IId: j, Val: l }) }); PTRMF.services.values.currentForm.Parameters.push({ Name: "submit", Val: f }); c = { FormName: PTRMF.services.values.currentForm.FormName, FormControlValues: d, Parameters: PTRMF.services.values.currentForm.Parameters, ReturnedSystemInfo: PTRMF.services.values.formSysInfo }; PTRMF.metrics.endTimer("5tof." + PTRMF.services.values.currentForm.FormName); var b = function () { PTRMF.services.operations.makeServiceCall("ProcessForm", c, function (h) { PTRMF.services.values.currentTabIndex = 0; PTRMF.services.values.currentForm = { FormName: h.FormName || PTRMF.services.values.currentForm.FormName, Parameters: [] }; PTRMF.services.values.container.html(PTRMF.controls.controlFactory.render(h)); PTRMF.events.eventManager.WireUpForm(); if (a) { a(h) } if (PTRMF.services.values.processFormCallback) { PTRMF.services.values.processFormCallback({ FormName: PTRMF.services.values.currentForm.FormName, SystemInfoResponse: h.SystemInfoResponse, Status: h.Status }) } PTRMF.metrics.endTimer("5pf." + c.FormName) }) }; if (e) { e.done(function g() { b() }) } else { b() } }, getLookups: function (c, d, b, a) { var e = { FormName: c, ItemId: d, FilterValue: b }; this.makeServiceCall("getLookups", e, function (f) { a(f) }) }, serverValidate: function (b, c, d, a) { PTRMF.metrics.startTimer("5vi." + b + "." + c); var e = { FormName: b, RequestData: { IId: c, Value: d } }; this.makeServiceCall("ValidateItem", e, function (f) { PTRMF.metrics.endTimer("5vi." + b + "." + c); a(f) }) }, makeServiceCall: function (e, f, a) { var c = new Date(); var d = function () { var j = PTRMF.services.helpers.buildFormsServicePostRequest(e, f); $.ajax({ type: "POST", url: j.url, data: j.data, success: function (k) { a(k) } }) }; var h = PTRMF.services.values.sessionResponseInfo && PTRMF.services.values.sessionOpenedAt; var i = h && (PTRMF.forms.utils.getUTCDate(c) - PTRMF.services.values.sessionOpenedAt > PTRMF.services.values.sessionResponseInfo.SessionTimeout); var g = PTRMF.services.values.sessionBag.SessionId; var b = PTRMF.services.values.sessionBag.CasinoId; if (!h && g) { PTRMF.services.session.resume(g, function () { d() }) } else { if (!h || i) { PTRMF.services.session.open(function () { PTRMF.metrics.logCount("5ops"); if ("standalone" in navigator && navigator.standalone) { PTRMF.metrics.logCount("5ihs") } d() }) } else { d() } } PTRMF.services.values.sessionOpenedAt = PTRMF.forms.utils.getUTCDate(c) } }; PTRMF.namespace("services").values = PTRMF.services.values || { setCallbacks: function (a) { $.each(a, function (d, b) { PTRMF.services.values[b.event] = b.callBack }) }, currentTabIndex: 0, closeFormCallback: function (a) { PTRMF.ui.UIManager.CloseBrowserWindow(a) }, backToGamesCallback: function () { }, getFormCallback: function () { }, processFormCallback: function () { }, gotoLoginCallback: function () { }, pageViewChanged: function () { }, formRenderedCallback: function () { }, sessionResponseInfo: null, sessionOpenedAt: null, sessionBag: { serviceUrl: "", CasinoId: null, LanguageCode: "en", LoginName: "", Password: "", UserId: 0, ClientTypeId: 40 }, currentForm: { FormName: "", Parameters: [] }, firstForm: { FormName: "", Parameters: [] }, container: null, formSysInfo: [], pageStack: [], pendingSubmitCall: null, getNextTabIndex: function () { PTRMF.services.values.currentTabIndex++; return PTRMF.services.values.currentTabIndex }, reset: function () { this.processFormCallback = undefined; this.gotoLoginCallback = undefined; this.sessionResponseInfo = undefined; this.sessionResponseInfo = undefined; this.currentForm.FormName = ""; this.currentForm.Parameters.length = 0; this.formSysInfo.length = 0; this.pageStack.length = 0; this.pendingSubmitCall = null } }; PTRMF.namespace("validation").validator = PTRMF.validation.validator || { validateControl: function (a, c) { var d; c = c || "control"; switch ($(a).get(0).tagName.toLowerCase()) { case "input": var b = PTRMF.validation.validator.getContainerFieldSet(a); d = this.validateInputTag(a, c); if (b.attr("mode") == "amount") { PTRMF.events.eventManager.HandleAmountFieldUpdate(a, b) } else { PTRMF.events.eventManager.SetInputValue(a) } break; case "select": d = this.validateSelectTag(a, c); break; default: d = true; break } return d }, validateOnSubmitMutlifieldValidators: function () { $('.formsService div.multiFieldValidator[mode="submit"]').each(function (b, a) { var d = $(this).attr("data-state"); if (d !== "valid-data") { var h = $(this).attr("fsIid"); var g = $(a).attr("data-targets").split(","); var f = []; for (var c = 0; c < g.length; c++) { f.push($('fieldset[fsIid="' + g[c].trim() + '"]')) } PTRMF.validation.validator.doMultipleInputServerValidation(f, null, h) } }) }, validateView: function (g, d) { d = (typeof d === "undefined") ? false : d; var f = true, a = true, e; $.each($(g).find("fieldset").not(".valid,.invalid,.validating").find("input,select"), function (j, h) { if ($(h).attr("inputid") !== "Password") { a = PTRMF.validation.validator.validateControl($(h), "view"); (a) ? e = "valid" : e = "invalid"; PTRMF.ui.UIManager.SetControlStyle(PTRMF.validation.validator.getContainerFieldSet($(h)), e); f = f && a } }); f = f && !$(g).find("fieldset").is(".invalid"); var b = $("div.formsService:first").attr("data-form"); var c = "5fv." + b; if (f && d) { PTRMF.metrics.endTimer(c); PTRMF.ui.UIManager.ShowLoader(); PTRMF.validation.validator.validateOnSubmitMutlifieldValidators() } else { PTRMF.metrics.logCount("5sb." + b); if (!PTRMF.metrics.hasTimer(c)) { PTRMF.metrics.startTimer(c) } } f = f && $(g).find("div.multiFieldValidator.invalid").length === 0; return f }, isViewBusyValidating: function (a) { return $(a).find("fieldset").is(".validating") || $(a).find("div.multiFieldValidator").is(".validating") }, validateSelectTag: function (a, c) { var d = true, b = this.getContainerFieldSet(a); if ($(a).attr("required") == "required") { if ($(a).attr("disabled") !== "disabled") { if ($(a).val().length == 0) { return false } } } if (b.attr("mode") === "cardexpiry") { return this.validateCardExpiry(b, c) } else { if (b.attr("fsType") === "date") { return this.validateDateControl(b, c) } } return true }, validateCardExpiry: function (a, b) { var c = $(a).find('select[fsType="date_month"]:first').val(), e = $(a).find('select[fsType="date_year"]:first').val(), d = new Date(e, c, 0, 23, 59, 59, 0); if (c === "" || e === "") { if (b === "control") { return "insufficient-data" } else { return false } } return d >= new Date() }, validateDateControl: function (b, f) { var d = true; if (!b.attr("fsVal") || b.attr("fsVal").length === 0) { d = false } else { $(b).find("select").each(function () { if (!$(this).attr("fsVal") || $(this).attr("fsVal").length === 0) { d = "insufficient-data"; return false } }) } if (f === "view" && d === "insufficient-data") { d = false } if (d && b.attr("max")) { var a = b.attr("max").split("/"); var e = new Date(parseInt(a[0], 10), parseInt(a[1], 10) - 1, parseInt(a[2], 10)); var c = function (i) { return parseInt(b.find('[fstype="' + i + '"]').attr("fsval"), 10) }; var h = new Date(c("date_year"), c("date_month"), c("date_day")); if (h > e) { d = false } } if (d === true) { var g = this.getPostValidationCallback(b); if (g) { g(); d = "insufficient-data" } } return d }, validateInputTag: function (b) { var a = b.val(); if ((a.length > 0) && (a.trim() === "")) { return false } switch (b.attr("type")) { case "tel": case "password": case "email": case "text": if ((b.attr("mode") === "amount") || (b.attr("fsType") === "number")) { b.val($.trim(b.val())); return this.validateNumeric(b) } else { if (b.attr("required") === undefined && jQuery.trim(b.val()) === "") { return true } else { this.validateInput(b) } } case "number": return this.validateNumeric(b); case "checkbox": return this.validateCheckbox(b); default: break } return true }, validateCheckbox: function (a) { var b = true; if ($(a).attr("required") == "required") { ($(a).is(":checked")) ? b = true : b = false } return b }, checkNumericLengthLimit: function (b) { var c = this.getContainerFieldSet(b), e = c.attr("max"), d = $(b).val().length, a = false; if (c.attr("mode") !== "amount") { if (d >= e) { a = true } } return a }, validateNumeric: function (a) { var i, b = this.getContainerFieldSet(a), c = b.find("input:first"), e = b.attr("min"), d = b.attr("max"), h = b.attr("regex"), f = b.attr("mode").toLowerCase(); i = true; switch (f) { case "amount": if (e && d) { i = (i && ((c.val() * 100) >= e) && ((c.val() * 100) <= d)) } else { if (e && d.length === 0) { i = i && (c.val() * 100) >= e } else { if (d && e.length === 0) { i = i && (c.val() * 100) <= d } } } break; default: if (e && d) { i = (i && (c.val().length >= e) && (c.val().length <= d)) } break } if (h && h.length > 0) { i = i && this.validateRegex(h, c.val()) } if (b.attr("mode") === "creditcard") { i = i && PTRMF.validation.validator.validateLuhn(c.val()) } if (b.attr("mandatory") === "false" && b.find("input:first").val() === "") { i = true } if (i) { var g = this.getPostValidationCallback(b); if ((b.attr("valUrl").length > 0) && (c.val().length > 0)) { this.doInputServerValidation(c, b, function (j) { if (f == "creditcard") { if (!j.Valid) { c.next('p[class="valicon"]').attr("style", "") } else { c.next('p[class="valicon"]').attr("style", "background-image:url(" + PTRMF.services.values.sessionBag.serviceUrl + j.Text + ")") } } if (j.Valid && g) { g() } else { if (PTRMF.services.values.pendingSubmitCall) { PTRMF.services.values.pendingSubmitCall() } } }); i = false } else { if (g) { g() } } } else { if (f == "creditcard") { c.next('p[class="valicon"]').attr("style", "") } } return i }, getPostValidationCallback: function (a) { if (a.attr("data-notify-post-validate")) { return function () { var b = $(a).attr("data-notify-post-validate"); $("#" + b).trigger({ type: "post-validate", sourceInputId: a.attr("fsIid") }) } } return null }, validateInput: function (a) { var d = true, c, b = this.getContainerFieldSet(a); switch (b.attr("mode")) { case "phonenumber": c = b.find("input:last"); d = this.doBaseInputValidation(c, b); d = d && b.find("input:first").val().length > 0; break; case "address": c = b.find("input:first"); d = this.doBaseInputValidation(c, b); c = c.next("input"); d = d && (c.val().length <= b.attr("max")); break; default: c = b.find("input:first"); d = this.doBaseInputValidation(c, b); break } if (d) { if ((b.attr("valUrl").length > 0) && (c.val().length > 0)) { this.doInputServerValidation(c, b); d = false } } return d }, doBaseInputValidation: function (b, a) { var d = a.attr("min"), c = a.attr("max"), e = a.attr("regex"); valid = ((b.val().length >= d) && (b.val().length <= c)); if (e && e.length > 0) { valid = (valid && this.validateRegex(e, b.val())) } return valid }, doInputServerValidation: function (e, b, a) { var d = b.attr("fsIid"), f = "", c; b.find('div[class="suggestionBlock"]').remove(); PTRMF.ui.UIManager.SetControlStyle(b, "validating"); var g = e.val(); switch (b.attr("mode")) { case "phonenumber": g = b.find("input:first").val() + ";" + e.val(); break; case "creditcard": g = g.substring(0, 6); break; default: break } PTRMF.services.operations.serverValidate(PTRMF.services.values.currentForm.FormName, d, g, function (h) { if (!h.Valid) { if (h.Text && h.Text !== "") { PTRMF.ui.UIManager.SetControlStyle(b, "invalid server-invalid"); b.find("span.serverError").text(h.Text) } else { PTRMF.ui.UIManager.SetControlStyle(b, "invalid") } if (h.Suggestions && h.Suggestions.length > 0) { f = ""; for (c = 0; c < h.Suggestions.length; c++) { f += "<p>" + h.Suggestions[c].Val + "</p>" } if (b.find('div[class="suggestionBlock"]').length === 0) { var i = $('<div class="suggestionBlock"></div>'); b.find("span:last").after($(i).html(f)); b.find('div[class="suggestionBlock"] p').click(function () { e.val($(this).html()); PTRMF.events.eventManager.SetInputValue(e); $(this).parent().remove(); PTRMF.validation.validator.validateInput(e); $(e).select() }) } } } else { PTRMF.ui.UIManager.SetControlStyle(b, "valid") } $(b).removeClass("validating"); if (a) { a(h) } else { if (PTRMF.services.values.pendingSubmitCall) { PTRMF.services.values.pendingSubmitCall() } } }) }, doMultipleInputServerValidation: function (b, c, d) { PTRMF.ui.UIManager.SetControlStyle($("#" + d), "validating"); var a = b.map(function (f) { var e = f.attr("fsVal"); if (e !== "") { PTRMF.ui.UIManager.SetControlStyle(f, "validating") } return { IId: f.attr("fsIid"), Value: f.attr("fsVal"), IsSourceInput: f.attr("fsIid") === c } }); PTRMF.services.operations.serverValidate(PTRMF.services.values.currentForm.FormName, d, JSON.stringify(a), function (e) { b.forEach(function (h) { h.removeClass("validating") }); var g = $("#" + d); g.removeClass("validating"); g.attr("data-state", "invalid-data"); var f = JSON.parse(e.Text); if (f.IsGlobalError) { PTRMF.ui.UIManager.HideLoader(); g.addClass("invalid"); g.parent().show().find("p").text(f.GlobalErrorText); b.forEach(function (h) { h.removeClass("valid") }); g.removeClass("validating"); if (PTRMF.services.values.pendingSubmitCall) { PTRMF.services.values.pendingSubmitCall = null } } else { if (f.Errors.length > 0) { PTRMF.ui.UIManager.HideLoader(); f.Errors.forEach(function (i) { var h = $('fieldset[fsIid="' + i.IId + '"]'); PTRMF.ui.UIManager.SetControlStyle(h, "invalid server-invalid"); h.find("span.serverError").text(i.Message) }); b.forEach(function (h) { if (!h.is("invalid")) { h.addClass("valid") } }); if (PTRMF.services.values.pendingSubmitCall) { PTRMF.services.values.pendingSubmitCall = null } } else { if (f.ValidationPostponed) { b.forEach(function (h) { if (h.attr("fsIid") === c) { h.addClass("valid") } }) } else { g.attr("data-state", "valid-data"); g.addClass("valid"); if (PTRMF.services.values.pendingSubmitCall) { PTRMF.services.values.pendingSubmitCall() } b.forEach(function (h) { h.addClass("valid") }) } } } }) }, getContainerFieldSet: function (a) { return $(a).parents("fieldset") }, validateRegex: function (a, c) { var b = new RegExp(a); return b.test(c) }, validateLuhn: function (a) { var b = a.length, c = 0, d = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]], e = 0; while (b--) { e += d[c][parseInt(a.charAt(b), 10)]; c ^= 1 } return e % 10 === 0 && e > 0 }, setValid: function (d) { $(".formsService section.validation-summary").css("display", "none"); var c = this.validateControl($(d)); if (c === "insufficient-data") { this.getContainerFieldSet($(d)).removeClass("valid invalid").addClass("insufficient-data"); return } else { if (c) { this.getContainerFieldSet($(d)).removeClass("insufficient-data"); PTRMF.ui.UIManager.SetControlStyle(this.getContainerFieldSet($(d)), "valid") } else { this.getContainerFieldSet($(d)).removeClass("insufficient-data"); var a = this.getContainerFieldSet($(d)); var e = a.is(".validating") ? "validating" : "invalid"; PTRMF.ui.UIManager.SetControlStyle(this.getContainerFieldSet($(d)), e); if (e === "invalid") { var b = $("div.formsService:first").attr("data-form"); PTRMF.metrics.logCount("5ve." + b + "." + a.attr("fsiid")) } } } } }; PTRMF.namespace("jqueryplugins").fsPlugin = (function (a) { var c = { initialForm: { formName: "Olr", parameters: {} } }, b = { init: function (d) { PTRMF.services.values.container = this; if (d) { if (d.sessionBag) { a.extend(PTRMF.services.values.sessionBag, d.sessionBag); delete d.sessionBag } a.extend(c, d) } return this }, getForm: function (g, e, f, d) { PTRMF.ui.UIManager.resetAndShowLoader(this, d); PTRMF.services.values.firstForm = { FormName: e, Parameters: f }; if (g) { a.extend(PTRMF.services.values.sessionBag, g) } if (d) { PTRMF.services.values.setCallbacks(d) } PTRMF.services.operations.getForm(e, f, function (h) { PTRMF.ui.UIManager.LoadContents(h); PTRMF.ui.UIManager.HideLoader() }); return this }, setFormRequiredSystemInfoFields: function (d) { if (d) { PTRMF.services.values.formSysInfo = d } return this }, registration: function (e, d) { PTRMF.ui.UIManager.resetAndShowLoader(this, d); PTRMF.services.values.firstForm = { FormName: "Olr", Parameters: [] }; if (e) { a.extend(PTRMF.services.values.sessionBag, e) } if (d) { PTRMF.services.values.setCallbacks(d) } PTRMF.services.operations.getForm("Olr", [], function (f) { PTRMF.ui.UIManager.GetFormResponseHandler(f); PTRMF.ui.UIManager.HideLoader() }); return this }, banking: function (f, d, e) { PTRMF.ui.UIManager.resetAndShowLoader(this); PTRMF.services.values.firstForm = { FormName: "PurchaseMethods", Parameters: e || [] }; if (f) { a.extend(PTRMF.services.values.sessionBag, f) } if (d) { PTRMF.services.values.setCallbacks(d) } PTRMF.services.operations.getForm("PurchaseMethods", PTRMF.services.values.firstForm.Parameters, function (g) { PTRMF.ui.UIManager.GetFormResponseHandler(g); PTRMF.ui.UIManager.HideLoader() }); return this } }; a.fn.formsService = function (d) { if (b[d]) { return b[d].apply(this, Array.prototype.slice.call(arguments, 1)) } else { if (typeof d === "object" || !d) { return b.init.apply(this, arguments) } else { a.error("Method " + d + " does not exist on jQuery.formsService") } } } })(jQuery); PTRMF.i18n = PTRMF.i18n || { getString: function (b, c) { var a = c || PTRMF.services.values.sessionBag.LanguageCode; if (!this[a]) { a = "en" } var d = this[a][b] || this.en[b]; return d }, en: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Show password" }, da: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Vis adgangskode" }, de: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Kennwort anzeigen" }, es: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Mostrar contraseÃ±a" }, fi: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "NÃ¤ytÃ¤ Salasana" }, ja: { CantCloseWindow: "ç”³ã—è¨³ã”ã–ã„ã¾ã›ã‚“ ãŠä½¿ã„ã®ãƒ–ãƒ©ã‚¦ã‚¶ãƒ¼ã‚’é–‰ã˜ã‚‹ã“ã¨ãŒå‡ºæ¥ã¾ã›ã‚“ã§ã—ãŸ ã”ä½¿ç”¨ä¸­ã®ã‚¿ãƒ–ã‚’é–‰ã˜ã¦ãã ã•ã„", ShowPassword: "ãƒ‘ã‚¹ãƒ¯ãƒ¼ãƒ‰ã‚’è¡¨ç¤º" }, nl: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Wachtwoord weergeven" }, no: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Vis passord" }, ru: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚ÑŒ Ð¿Ð°Ñ€Ð¾Ð»ÑŒ" }, sv: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Visa lÃ¶senord" }, it: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Mostra password" }, lv: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "RÄdÄ«t paroli" }, el: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Î ÏÎ¿Î²Î¿Î»Î® ÎºÏ‰Î´Î¹ÎºÎ¿Ï Ï€ÏÏŒÏƒÎ²Î±ÏƒÎ·Ï‚" }, fr: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Afficher le mot de passe" }, pt: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "Mostrar palavra-passe" }, pl: { CantCloseWindow: "Oops! The browser won't let us close this page for you. Please close it by closing the current tab.", ShowPassword: "PokaÅ¼ HasÅ‚o" } };
(function(a) {
    var r = a.fn.domManip, d = "_tmplitem", q = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, b = {}, f = {}, e, p = { key: 0, data: {} }, h = 0, c = 0, l = [];

    function g(e, d, g, i) {
        var c = { data: i || (d ? d.data : {}), _wrap: d ? d._wrap : null, tmpl: null, parent: d || null, nodes: [], calls: u, nest: w, wrap: x, html: v, update: t };
        e && a.extend(c, e, { nodes: [], parent: d });
        if (g) {
            c.tmpl = g;
            c._ctnt = c._ctnt || c.tmpl(a, c);
            c.key = ++h;
            (l.length ? f : b)[h] = c
        }
        return c
    }

    a.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(f, d) {
        a.fn[f] = function(n) {
            var g = [], i = a(n), k, h, m, l, j = this.length === 1 && this[0].parentNode;
            e = b || {};
            if (j && j.nodeType === 11 && j.childNodes.length === 1 && i.length === 1) {
                i[d](this[0]);
                g = this
            } else {
                for (h = 0, m = i.length; h < m; h++) {
                    c = h;
                    k = (h > 0 ? this.clone(true) : this).get();
                    a.fn[d].apply(a(i[h]), k);
                    g = g.concat(k)
                }
                c = 0;
                g = this.pushStack(g, f, i.selector)
            }
            l = e;
            e = null;
            a.tmpl.complete(l);
            return g
        }
    });
    a.fn.extend({
        tmpl: function(d, c, b) { return a.tmpl(this[0], d, c, b) }, tmplItem: function() { return a.tmplItem(this[0]) }, template: function(b) { return a.template(b, this[0]) },
        domManip: function(d, l, j) {
            if (d[0] && d[0].nodeType) {
                var f = a.makeArray(arguments), g = d.length, i = 0, h;
                while (i < g && !(h = a.data(d[i++], "tmplItem")));
                if (g > 1) f[0] = [a.makeArray(d)];
                if (h && c) f[2] = function(b) { a.tmpl.afterManip(this, b, j) };
                r.apply(this, f)
            } else r.apply(this, arguments);
            c = 0;
            !e && a.tmpl.complete(b);
            return this
        }
    });
    a.extend({
        tmpl: function(d, h, e, c) {
            var j, k = !c;
            if (k) {
                c = p;
                d = a.template[d] || a.template(null, d);
                f = {}
            } else if (!d) {
                d = c.tmpl;
                b[c.key] = c;
                c.nodes = [];
                c.wrapped && n(c, c.wrapped);
                return a(i(c, null, c.tmpl(a, c)))
            }
            if (!d) return [];
            if (typeof h === "function") h = h.call(c || {});
            e && e.wrapped && n(e, e.wrapped);
            j = a.isArray(h) ? a.map(h, function(a) { return a ? g(e, c, d, a) : null }) : [g(e, c, d, h)];
            return k ? a(i(c, null, j)) : j
        },
        tmplItem: function(b) {
            var c;
            if (b instanceof a) b = b[0];
            while (b && b.nodeType === 1 && !(c = a.data(b, "tmplItem")) && (b = b.parentNode));
            return c || p
        },
        template: function(c, b) {
            if (b) {
                if (typeof b === "string") b = o(b);
                else if (b instanceof a) b = b[0] || {};
                if (b.nodeType) b = a.data(b, "tmpl") || a.data(b, "tmpl", o(b.innerHTML));
                return typeof c === "string" ? (a.template[c] = b) : b
            }
            return c ? typeof c !== "string" ? a.template(null, c) : a.template[c] || a.template(null, q.test(c) ? c : a(c)) : null
        },
        encode: function(a) { return ("" + a).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;") }
    });
    a.extend(a.tmpl, {
        tag: { tmpl: { _default: { $2: "null" }, open: "if($notnull_1){_=_.concat($item.nest($1,$2));}" }, wrap: { _default: { $2: "null" }, open: "$item.calls(_,$1,$2);_=[];", close: "call=$item.calls();_=call._.concat($item.wrap(call,_));" }, each: { _default: { $2: "$index, $value" }, open: "if($notnull_1){$.each($1a,function($2){with(this){", close: "}});}" }, "if": { open: "if(($notnull_1) && $1a){", close: "}" }, "else": { _default: { $1: "true" }, open: "}else if(($notnull_1) && $1a){" }, html: { open: "if($notnull_1){_.push($1a);}" }, "=": { _default: { $1: "$data" }, open: "if($notnull_1){_.push($.encode($1a));}" }, "!": { open: "" } }, complete: function() { b = {} },
        afterManip: function(f, b, d) {
            var e = b.nodeType === 11 ? a.makeArray(b.childNodes) : b.nodeType === 1 ? [b] : [];
            d.call(f, b);
            m(e);
            c++
        }
    });

    function i(e, g, f) {
        var b, c = f ? a.map(f, function(a) { return typeof a === "string" ? e.key ? a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + d + '="' + e.key + '" $2') : a : i(a, e, a._ctnt) }) : e;
        if (g) return c;
        c = c.join("");
        c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function(f, c, e, d) {
            b = a(e).get();
            m(b);
            if (c) b = j(c).concat(b);
            if (d) b = b.concat(j(d))
        });
        return b ? b : j(c)
    }

    function j(c) {
        var b = document.createElement("div");
        b.innerHTML = c;
        return a.makeArray(b.childNodes)
    }

    function o(b) {
        return new Function("jQuery", "$item", "var $=jQuery,call,_=[],$data=$item.data;with($data){_.push('" + a.trim(b).replace(/([\\'])/g, "\\$1").replace(/[\r\t\n]/g, " ").replace(/\$\{([^\}]*)\}/g, "{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g, function(m, l, j, d, b, c, e) {
            var i = a.tmpl.tag[j], h, f, g;
            if (!i) throw "Template command not found: " + j;
            h = i._default || [];
            if (c && !/\w$/.test(b)) {
                b += c;
                c = ""
            }
            if (b) {
                b = k(b);
                e = e ? "," + k(e) + ")" : c ? ")" : "";
                f = c ? b.indexOf(".") > -1 ? b + c : "(" + b + ").call($item" + e : b;
                g = c ? f : "(typeof(" + b + ")==='function'?(" + b + ").call($item):(" + b + "))"
            } else g = f = h.$1 || "null";
            d = k(d);
            return "');" + i[l ? "close" : "open"].split("$notnull_1").join(b ? "typeof(" + b + ")!=='undefined' && (" + b + ")!=null" : "true").split("$1a").join(g).split("$1").join(f).split("$2").join(d ? d.replace(/\s*([^\(]+)\s*(\((.*?)\))?/g, function(d, c, b, a) {
                a = a ? "," + a + ")" : b ? ")" : "";
                return a ? "(" + c + ").call($item" + a : d
            }) : h.$2 || "") + "_.push('"
        }) + "');}return _;")
    }

    function n(c, b) { c._wrap = i(c, true, a.isArray(b) ? b : [q.test(b) ? b : a(b).html()]).join("") }

    function k(a) { return a ? a.replace(/\\'/g, "'").replace(/\\\\/g, "\\") : null }

    function s(b) {
        var a = document.createElement("div");
        a.appendChild(b.cloneNode(true));
        return a.innerHTML
    }

    function m(o) {
        var n = "_" + c, k, j, l = {}, e, p, i;
        for (e = 0, p = o.length; e < p; e++) {
            if ((k = o[e]).nodeType !== 1) continue;
            j = k.getElementsByTagName("*");
            for (i = j.length - 1; i >= 0; i--) m(j[i]);
            m(k)
        }

        function m(j) {
            var p, i = j, k, e, m;
            if (m = j.getAttribute(d)) {
                while (i.parentNode && (i = i.parentNode).nodeType === 1 && !(p = i.getAttribute(d)));
                if (p !== m) {
                    i = i.parentNode ? i.nodeType === 11 ? 0 : i.getAttribute(d) || 0 : 0;
                    if (!(e = b[m])) {
                        e = f[m];
                        e = g(e, b[i] || f[i], null, true);
                        e.key = ++h;
                        b[h] = e
                    }
                    c && o(m)
                }
                j.removeAttribute(d)
            } else if (c && (e = a.data(j, "tmplItem"))) {
                o(e.key);
                b[e.key] = e;
                i = a.data(j.parentNode, "tmplItem");
                i = i ? i.key : 0
            }
            if (e) {
                k = e;
                while (k && k.key != i) {
                    k.nodes.push(j);
                    k = k.parent
                }
                delete e._ctnt;
                delete e._wrap;
                a.data(j, "tmplItem", e)
            }

            function o(a) {
                a = a + n;
                e = l[a] = l[a] || g(e, b[e.parent.key + n] || e.parent, null, true)
            }
        }
    }

    function u(a, d, c, b) {
        if (!a) return l.pop();
        l.push({ _: a, tmpl: d, item: this, data: c, options: b })
    }

    function w(d, c, b) { return a.tmpl(a.template(d), c, b, this) }

    function x(b, d) {
        var c = b.options || {};
        c.wrapped = d;
        return a.tmpl(a.template(b.tmpl), b.data, c, b.item)
    }

    function v(d, c) {
        var b = this._wrap;
        return a.map(a(a.isArray(b) ? b.join("") : b).filter(d || "*"), function(a) { return c ? a.innerText || a.textContent : a.outerHTML || s(a) })
    }

    function t() {
        var b = this.nodes;
        a.tmpl(null, null, null, this).insertBefore(b[0]);
        a(b).remove()
    }
})(jQuery);
(function (a, b, c) { function g(a, c) { var d = b.createElement(a || "div"), e; for (e in c) d[e] = c[e]; return d } function h(a) { for (var b = 1, c = arguments.length; b < c; b++) a.appendChild(arguments[b]); return a } function j(a, b, c, d) { var g = ["opacity", b, ~~(a * 100), c, d].join("-"), h = .01 + c / d * 100, j = Math.max(1 - (1 - a) / b * (100 - h), a), k = f.substring(0, f.indexOf("Animation")).toLowerCase(), l = k && "-" + k + "-" || ""; return e[g] || (i.insertRule("@" + l + "keyframes " + g + "{" + "0%{opacity:" + j + "}" + h + "%{opacity:" + a + "}" + (h + .01) + "%{opacity:1}" + (h + b) % 100 + "%{opacity:" + a + "}" + "100%{opacity:" + j + "}" + "}", 0), e[g] = 1), g } function k(a, b) { var e = a.style, f, g; if (e[b] !== c) return b; b = b.charAt(0).toUpperCase() + b.slice(1); for (g = 0; g < d.length; g++) { f = d[g] + b; if (e[f] !== c) return f } } function l(a, b) { for (var c in b) a.style[k(a, c) || c] = b[c]; return a } function m(a) { for (var b = 1; b < arguments.length; b++) { var d = arguments[b]; for (var e in d) a[e] === c && (a[e] = d[e]) } return a } function n(a) { var b = { x: a.offsetLeft, y: a.offsetTop }; while (a = a.offsetParent) b.x += a.offsetLeft, b.y += a.offsetTop; return b } var d = ["webkit", "Moz", "ms", "O"], e = {}, f, i = function () { var a = g("style"); return h(b.getElementsByTagName("head")[0], a), a.sheet || a.styleSheet }(), o = { lines: 12, length: 7, width: 5, radius: 10, rotate: 0, color: "#000", speed: 1, trail: 100, opacity: .25, fps: 20, zIndex: 2e9, className: "spinner", top: "auto", left: "auto" }, p = function q(a) { if (!this.spin) return new q(a); this.opts = m(a || {}, q.defaults, o) }; p.defaults = {}, m(p.prototype, { spin: function (a) { this.stop(); var b = this, c = b.opts, d = b.el = l(g(0, { className: c.className }), { position: "relative", zIndex: c.zIndex }), e = c.radius + c.length + c.width, h, i; a && (a.insertBefore(d, a.firstChild || null), i = n(a), h = n(d), l(d, { left: (c.left == "auto" ? i.x - h.x + (a.offsetWidth >> 1) : c.left + e) + "px", top: (c.top == "auto" ? i.y - h.y + (a.offsetHeight >> 1) : c.top + e) + "px" })), d.setAttribute("aria-role", "progressbar"), b.lines(d, b.opts); if (!f) { var j = 0, k = c.fps, m = k / c.speed, o = (1 - c.opacity) / (m * c.trail / 100), p = m / c.lines; !function q() { j++; for (var a = c.lines; a; a--) { var e = Math.max(1 - (j + a * p) % m * o, c.opacity); b.opacity(d, c.lines - a, e, c) } b.timeout = b.el && setTimeout(q, ~~(1e3 / k)) }() } return b }, stop: function () { var a = this.el; return a && (clearTimeout(this.timeout), a.parentNode && a.parentNode.removeChild(a), this.el = c), this }, lines: function (a, b) { function e(a, d) { return l(g(), { position: "absolute", width: b.length + b.width + "px", height: b.width + "px", background: a, boxShadow: d, transformOrigin: "left", transform: "rotate(" + ~~(360 / b.lines * c + b.rotate) + "deg) translate(" + b.radius + "px" + ",0)", borderRadius: (b.width >> 1) + "px" }) } var c = 0, d; for (; c < b.lines; c++) d = l(g(), { position: "absolute", top: 1 + ~(b.width / 2) + "px", transform: b.hwaccel ? "translate3d(0,0,0)" : "", opacity: b.opacity, animation: f && j(b.opacity, b.trail, c, b.lines) + " " + 1 / b.speed + "s linear infinite" }), b.shadow && h(d, l(e("#000", "0 0 4px #000"), { top: "2px" })), h(a, h(d, e(b.color, "0 0 1px rgba(0,0,0,.1)"))); return a }, opacity: function (a, b, c) { b < a.childNodes.length && (a.childNodes[b].style.opacity = c) } }), !function () { function a(a, b) { return g("<" + a + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', b) } var b = l(g("group"), { behavior: "url(#default#VML)" }); !k(b, "transform") && b.adj ? (i.addRule(".spin-vml", "behavior:url(#default#VML)"), p.prototype.lines = function (b, c) { function f() { return l(a("group", { coordsize: e + " " + e, coordorigin: -d + " " + -d }), { width: e, height: e }) } function k(b, e, g) { h(i, h(l(f(), { rotation: 360 / c.lines * b + "deg", left: ~~e }), h(l(a("roundrect", { arcsize: 1 }), { width: d, height: c.width, left: c.radius, top: -c.width >> 1, filter: g }), a("fill", { color: c.color, opacity: c.opacity }), a("stroke", { opacity: 0 })))) } var d = c.length + c.width, e = 2 * d, g = -(c.width + c.length) * 2 + "px", i = l(f(), { position: "absolute", top: g, left: g }), j; if (c.shadow) for (j = 1; j <= c.lines; j++) k(j, -2, "progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)"); for (j = 1; j <= c.lines; j++) k(j); return h(b, i) }, p.prototype.opacity = function (a, b, c, d) { var e = a.firstChild; d = d.shadow && d.lines || 0, e && b + d < e.childNodes.length && (e = e.childNodes[b + d], e = e && e.firstChild, e = e && e.firstChild, e && (e.opacity = c)) }) : f = k(b, "animation") }(), a.Spinner = p })(window, document);
//console.log = function() {}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function getQueryParams() {
    if (window.queryParams == null || window.queryParams == undefined || window.queryParams.CultureCode == null || window.queryParams.CultureCode == undefined || window.queryParams.CultureCode == "") {
        //just to check if cookie exists
        var cookieDetails = getCookie("JavaScriptDetails");
        if (cookieDetails != undefined && cookieDetails != "") {
            var cookieExploded = cookieDetails.split("&");
            if (cookieExploded.length >= 2) {
                var BrandCode = cookieExploded[0];
                var CultureCode = cookieExploded[1];

                window.queryParams = {
                    CultureCode: CultureCode.split("=")[1],
                    BrandCode: BrandCode.split("=")[1],
                    JsonToken: window.queryParams && window.queryParams.JsonToken ? window.queryParams.JsonToken : ""
                };
            }
        }
    }

    return window.queryParams;
}

function _InitGlobalVariables() {


    window.swiftObjects = [];
    window.swiftDomain = "https://webserver7-bankingswiftlivestaging.installprogram.eu";
    window.swiftOrigin = "dmgamingsystems";

    window.swiftDomObjects = {
        registeristrationObject: { name: "register" },
        bankingObject: { name: "banking" }
    };

    window.aftoken = "empty:empty";


    window.languageOverwrideParams = {
        CultureCode: window.CultureCodeOverride || getQueryParams().CultureCode,
        BrandCode: getQueryParams().BrandCode,
        JsonToken: getQueryParams().JsonToken
    };

    window.postParams = {
        CultureCode: getQueryParams().CultureCode,
        BrandCode: getQueryParams().BrandCode,
        JsonToken: getQueryParams().JsonToken
    };

    //TODO: **** REMOVE *** CANADA *** Country code override (for testing)
    //TODO: -- MIT --
    //Add the override countryCode to the query string (used on all ajax requests)
    var countryOverride = queryStringLookup["COUNTRYOVERRIDE"];
    if (countryOverride) { CreateCookie("COUNTRYOVERRIDE", countryOverride, 1, true); }

    countryOverride = ReadCookie("COUNTRYOVERRIDE");
    window.queryParams.CountryOverride = countryOverride;
    window.languageOverwrideParams.CountryOverride = countryOverride;

    delete window.queryParams.JsonToken;

    window.timer = { increment: 0, object: null };

    window.casinoGlobals = {
        mobileBankingSelector: "#mobileBankingContent",
        apiDomain: window.apiDomain,
        casinoUserData: {
            promotionSliderSettings: {
                startSlide: 0,
                speed: 500,
                auto: 5000
            }
        }
    };

    window.AjaxUrl = {
        MetaData: "/api/metadata/CasinoMetadata?" + jQuery.param(getQueryParams()),
    };
    $("[site-container]").removeClass("api-start");

    _InitAjaxCalls();
}

var _CleanQueryStringInfo = function(){

	try{
		var currentUrl = window.location.href;
		var queryStringSplit = currentUrl.split("?");	
		
		if(queryStringSplit[1]){
			//console.log("CLEAN THE QUERY STRING");
			//console.log(queryStringSplit);
			window.history.pushState('', '', location.pathname);
		}
		
	}catch(e){	
	}	
}



function _InitAjaxCalls() {
    var currentTimeInSeconds = (Date.now() / 1000 | 0) - 8.64e4;
    var maxCacheSeconds = 300;
    var cacheTime = currentTimeInSeconds + maxCacheSeconds;

    var removeStoredItems = function () {
        //console.log("--- CLEAR CLIENT CACHE ---");
        browserStorage(true).removeItem("window.casinoGlobals.CasinoMetadata");
        browserStorage(true).removeItem("window.casinoGlobals.CasinoMetadata.StoredTime");
    };

    var userAgentStore = browserStorage(true).getItem("navigator.userAgent");
    if (userAgentStore !== navigator.userAgent) {
        removeStoredItems();
        browserStorage(true).storeItem("navigator.userAgent", navigator.userAgent);
    }

    var casinoMetadata = browserStorage(true).getItem("window.casinoGlobals.CasinoMetadata");
    var casinoMetadataStored = parseInt(browserStorage(true).getItem("window.casinoGlobals.CasinoMetadata.StoredTime"));

    if (casinoMetadataStored < currentTimeInSeconds ||
        maxCacheSeconds < (casinoMetadataStored - currentTimeInSeconds)) {
        removeStoredItems();
        casinoMetadata = null;
    }

    //Remove Overlay: Check Moved here due to ajax calls taking to long to complete
    if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
        analyticsEventTracking("TEST - AFTER NEW FUNC - BEFORE AJAX LOADS");
    }

    function ajaxBeforeCalls() {
        //console.log("--- START ---");
        $("body").addClass("rendering");
    }

    var echoAjax = function () {

        if (!window.EchoRequest) {
            window.EchoRequest = $.ajax({
                url: window.casinoGlobals.apiDomain + "/api/echo/get?request=",
                type: "GET",
                dataType: "json",
                error: function (error) {
                    //console.log(error);
                }
            });
        }

        return window.EchoRequest;
    };

    function a() {
        ajaxBeforeCalls();
        //console.log("--- AJAX CALL (CasinoMetadata) ---");
        if (!casinoMetadata || window.postParams.JsonToken) {
            return $.ajax({
                url: window.AjaxUrl.MetaData,
                type: "POST",
                data: window.postParams,
                dataType: "json",
                error: function (error) {
                    //console.log(error);
                }
            });
        } else {
            return echoAjax();
        }
    }

    function b(data) {
        //console.log("--- AJAX CALL () ---");
        if (!window.postParams.JsonToken) {
            if (casinoMetadata) {
                window.casinoGlobals.CasinoMetadata = JSON.parse(casinoMetadata);
            } else {
                if (data) {
                    browserStorage(true).storeItem("window.casinoGlobals.CasinoMetadata", JSON.stringify(data));
                    browserStorage(true).storeItem("window.casinoGlobals.CasinoMetadata.StoredTime", cacheTime);
                    window.casinoGlobals.CasinoMetadata = data;
                }
            }
        } else {
            window.casinoGlobals.CasinoMetadata = data;
        }
        _TranslationHelper();
    }

    function ajaxCallsComplete(data) {

        jQuery(document).ready(function ($) {

            //console.log("--- PROCESS DATA ---");
            window.casinoGlobals.Events = {};

            //Show data on the dom
            $(".gameControlBlock, .gameControlNavBlock, .gameControlGameBlock").show();
            $(".gameControl, .offer-bg .container-fluid").css("background", "transparent");

           

            //Ajax Calls Completed - Start using the data
            _CustomSiteScripts();

            if (typeof _CustomFrontEndScripts == "function") {
                _CustomFrontEndScripts();
            }

            //Register Global Click Events
            _GlobalClickEvents().loginPopUp();
            _GlobalClickEvents().passwordShowHide();
            _GlobalClickEvents().socialMediaLinks();
            _GlobalClickEvents().playerLogout();
            _GlobalClickEvents().playerBanking();
            _GlobalClickEvents().playerRegisterBanking();
            _GlobalClickEvents().transactionHistory();
            //_GlobalClickEvents().forgotPassword();
            //_GlobalClickEvents().changePassword();
            //_GlobalClickEvents().gameHistory();
            //_GlobalClickEvents().redeemLoyalty();
            //_GlobalClickEvents().liveChat();
            //_GlobalClickEvents().playerRegister();
            _GlobalClickEvents().unsubscribe();
            //_GlobalClickEvents().accountMobile();
            _GlobalClickEvents().launchGeneralTermsPopUp();
            _GlobalClickEvents().maltaLicence();
            _GlobalClickEvents().ecograCertificate();
            _GlobalClickEvents().launchResponsibleGaming();
            _GlobalClickEvents().supportWindow();
            window.CustomEvents.MobileSeoContentClick();
            _GlobalClickEvents().displayRtpDoc();
            _GlobalClickEvents().browserSupportClose();
            _GlobalClickEvents().flashSupportClose();

            if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
                analyticsEventTracking("--- AFTER NEW FUNC - AFTER AJAX LOADS ---");
            }
           

            //if (window.postParams.JsonToken) { _MgsAccount(); }
            //if (typeof _LiveChatEvents == "function") { _LiveChatEvents(); }

            $("body").removeClass("rendering");
            $("[api-render-rendering]").remove();
            $("[api-render-completed]").removeClass("api-rendering");

        });
    }

    if (!casinoMetadata || window.postParams.JsonToken) {
        removeStoredItems();
        if (parseInt(ReadCookie("RegStep3")) === 1) {

            $("[api-reg-banking-click]", "[api-banking-click]").attr('disabled', true);
            a().then(function (data) {
                window.casinoGlobals.CasinoMetadata = data;
                EraseCookie("RegStep3");
                setInterval(function () {
                    _GlobalClickEvents().playerRegisterBanking();
                    _GlobalClickEvents().playerBanking();
                    $("[api-reg-banking-click]", "[api-banking-click]").attr('disabled', false);
                }, 1000);

                b(data).then(c, function () {
                    removeStoredItems();
                }).then(d, function () {
                    removeStoredItems();
                }).then(e, function () {
                    ajaxCallsComplete(null);
                }).then(function (data) {
                    ajaxCallsComplete(data);
                }, function () {
                    removeStoredItems();
                });
            });
        } else {

            a().then(b, function () {
                removeStoredItems();
                ajaxCallsComplete(null);
            }).then(function (data) {
                ajaxCallsComplete(data);
                //ajaxCallsComplete(null);
            }, function () {
                removeStoredItems();
            });
        }
    } else {
        ajaxBeforeCalls();
        window.casinoGlobals.CasinoMetadata = JSON.parse(casinoMetadata);
        ajaxCallsComplete();
        jQuery(document).ready(function () {
            _TranslationHelper();
        });
    }
}
var analyticsEventTracking = function () {
    //console.log("--- NOT LOADED - ANALYTICS EVENT TRACKING ---");
}
analyticsEventTracking("TEST - BEFORE NEW FUNC");
//STOP BACK AND FORTH SWIPE ACTIONS ON IPHONE
//window.history.replaceState(null, null, "#" + url)

//PLEASE ADD EXTRA FUNCTION THAT NEED TO BE CALLED IN THE [_GlobalAjaxCalls.js] FILE --> ajaxCallsComplete();
var _InitScripts = function() {
    
    _InitGlobalVariables();
    _InitFrontEndCustomScripts();

    return true;
}

//Poor man's Promise
function waitFor(itemTowaitFor, maxAttempts, intervalBetweenAttempts, onSuccess) {
    var i = 0;
    while (itemTowaitFor == null || itemTowaitFor == undefined) {
        i++;

        
        setTimeout(function () { console.log("Retry attempt " + i); }, intervalBetweenAttempts);

        if (i >= maxAttempts) {
            return itemTowaitFor;
        }
    }

    if (onSuccess) {
        return onSuccess();
    }

    return itemTowaitFor;
}

$(document).ready(function () {
    waitFor(window.queryParams, 100, 30, _InitScripts);
});

//PLEASE ADD EXTRA FUNCTION THAT NEED TO BE CALLED IN THE [_GlobalAjaxCalls.js] FILE --> ajaxCallsComplete();


analyticsEventTracking = function (data) {
    //console.log("--- ANALYTICS EVENT TRACKING - " + data + " ---");
}
function _ExternalAplicationLookup(applicationId, disableUrlEncoding) {

    var applications = window.casinoGlobals.CasinoMetadata.Metadata.BrandExternalApplications;
    var requestContext = window.casinoGlobals.CasinoMetadata.RequestMetadata;
    var domainInfo = UriLookup();
    var currentDomain = domainInfo.protocol + "://" + domainInfo.domain + "/";
    if (!disableUrlEncoding) {
        currentDomain = encodeURIComponent(currentDomain);
    }

    for (var a = 0; a < applications.length; a++) {
        if (applications[a].ExternalApplicationTypeId.toLowerCase() == applicationId.toLowerCase()) {

            return mergeDataHelper(applications[a].ExternalApplicationUrl, {
                AccountId: requestContext.AccountId,
                UserName: requestContext.Reference,
                EmailAddress: requestContext.Ereference,
                FirstName: requestContext.FirstName,
                ReturnUrl: currentDomain,
                RaptorSessionToken: requestContext.RaptorSessionToken,
                Password: requestContext.RaptorSessionToken,
                BannerTag: window.COOKIE_BTAG
            });
        }
    }
    return null;
};

function MgsH5Lobbyredirect(h5RedirectGuid) {
    var applications = window.casinoGlobals.CasinoMetadata.Metadata.BrandExternalApplications;
    var url;
    for (var a = 0; a < applications.length; a++) {
        if (applications[a].ExternalApplicationTypeId === h5RedirectGuid) {
            url = mergeDataHelper(applications[a].ExternalApplicationUrl, {
                BannerTag1: window.COOKIE_BTAG,
                BannerTag2: window.COOKIE_ST,
                BannerTag3: window.COOKIE_MT
            });
            break;
        }
    }

    if (url) {
        window.location = url;
    }
}

function _ExternalAplicationBankingLookup(applicationId, promotionId, disableUrlEncoding) {

    var applications = window.casinoGlobals.CasinoMetadata.Metadata.BrandExternalApplications;
    var requestContext = window.casinoGlobals.CasinoMetadata.RequestMetadata;
    var domainInfo = UriLookup();
    var currentDomain = domainInfo.protocol + "://" + domainInfo.domain + "/";
    if (!disableUrlEncoding) {
        currentDomain = encodeURIComponent(currentDomain);
    }

    if (!promotionId) {
        promotionId = "Default-Banking-Flash";
    }

    for (var a = 0; a < applications.length; a++) {
        if (applications[a].ExternalApplicationTypeId === applicationId) {

            return mergeDataHelper(applications[a].ExternalApplicationUrl, {
                AccountId: requestContext.AccountId,
                UserName: requestContext.Reference,
                EmailAddress: requestContext.Ereference,
                FirstName: requestContext.FirstName,
                ReturnUrl: currentDomain,
                RaptorSessionToken: requestContext.RaptorSessionToken,
                Password: requestContext.RaptorSessionToken,
                MOTD: encodeURIComponent(promotionId)
            });
        }
    }
    return null;
};

function _GlobalClickEvents() {

    var isMobile = window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile;

    var socialMediaLinks = function () {
        $("[api-social-Media-facebook-click]").unbind("click");
        $("[api-social-Media-blog-click]").unbind("click");
        $("[api-social-Media-pinterest-click]").unbind("click");
        $("[api-social-Media-googleplus-click]").unbind("click");
        $("[api-social-Media-youtube-click]").unbind("click");
        $("[api-social-Media-instagram-click]").unbind("click");
        $("[api-social-Media-twitter-click]").unbind("click");

        $("[api-social-Media-facebook-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("6f4f9245-524c-47cf-b77c-205afdcf08e6", true);
            var win = window.open(url, '_blank');
            win.focus();
        });

        $("[api-social-Media-blog-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("416aab4d-cd57-4590-8e68-6935f296c8f3", true);
            var win = window.open(url, '_blank');
            win.focus();
        });

        $("[api-social-Media-pinterest-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("8f0f10f3-afed-4d2b-9636-e059e0ded415", true);
            var win = window.open(url, '_blank');
            win.focus();
        });

        $("[api-social-Media-googleplus-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("46bd666b-38c8-4944-b97c-aa8175f25116", true);
            var win = window.open(url, '_blank');
            win.focus();
        });

        $("[api-social-Media-youtube-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("b0de30dc-a8d9-4e65-b47e-854c58ea64e1", true);
            var win = window.open(url, '_blank');
            win.focus();
        });

        $("[api-social-Media-instagram-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("381492c7-a077-478a-8c6a-0e9168dec0df", true);
            var win = window.open(url, '_blank');
            win.focus();
        });

        $("[api-social-Media-twitter-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("b1b6a8db-79a5-4e4c-8eec-5ea16c33f55f", true);
            var win = window.open(url, '_blank');
            win.focus();
        });

    };

    var playerLogout = function () {
        $("[api-logout-click]").unbind("click");
        $("[api-logout-click]").click(function (e) {
            e.preventDefault();
            _PlayerLogout();
        });
    };

    var supportWindow = function () {
        $("[api-launch-support-window]").unbind("click");
        $("[api-launch-support-window]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup('820f4131-9d70-403f-96db-27bf25165d7e', true);
            if (!url) {
                url = $(this).attr("href");
            }
            var win = window.open(url, "My Account", "width=1024, height=768, scrollbars=yes");
            win.focus();
        });
    };

    var mgsMyAccount = function () {

        $("[api-desktop-my-account-click]").unbind("click");
        $("[api-desktop-my-account-click]").click(function (e) {
            e.preventDefault();
            if (!isMobile) {
                var url = _ExternalAplicationLookup("51357257-7a5b-46cb-9168-6f733dbe48ab", true);
                if (url) {
                    window.open(url, "My Account", "width=1024, height=768");
                }
            }
        });

    };

    var playerBanking = function () {
        $("[api-banking-click]").unbind("click");
        $("[api-banking-click]").click(function (e) {
            e.preventDefault();
            if (!isMobile) {
                var url = _ExternalAplicationBankingLookup("d80af463-8e1e-4e33-b100-b29de0affd5f");
                window.open(url, "Banking", "width=1024, height=768");
            } else {
                $("[account-pop-up]").hide();
                $('#register3').remove();
                _MgsMobileBanking();

                if (typeof window.CustomEvents.MobileBankingClick === "function") {
                    window.CustomEvents.MobileBankingClick();
                }
                if (typeof window.CustomEvents.CloseMenu === "function") {
                    window.CustomEvents.CloseMenu();
                }
            }
            if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
                analyticsEventTracking("Bank Initiated");
            }
        });
    };

    var playerRegisterBanking = function () {
        $("[api-reg-banking-click]").unbind("click");
        $("[api-reg-banking-click]").click(function (e) {
            e.preventDefault();
            if (!isMobile) {
                var url = _ExternalAplicationLookup("d80af463-8e1e-4e33-b100-b29de0affd5f");
                window.open(url, "Banking", "width=1024, height=768");
                window.location.href = "/";
            } else {
                $('#casinoRegistrationComplete').remove();
                _MgsMobileBanking();
                window.CustomEvents.CloseMenu();
            }
            if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
                analyticsEventTracking("Bank Initiated");
            }
        });

    };

    var gameHistory = function () {

        $("[api-game-history-click]").unbind("click");
        $("[api-game-history-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("045a7fe6-bb94-4540-b5d9-04773f7426be");
            window.open(url, "Game History", "width=1024, height=768");
        });

    };

    var transactionHistory = function () {

        $("[api-transaction-history-click]").unbind("click");
        $("[api-transaction-history-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("8300b158-5a0a-499a-8817-7b48724d0454");
            window.open(url, "Transaction History", "width=1024, height=768");
        });

    };

    var changePassword = function () {

        $("[api-change-password-click]").unbind("click");
        $("[api-change-password-click]").click(function (e) {
            e.preventDefault();
            if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
                analyticsEventTracking("Login Forgot");
            }
            var url = _ExternalAplicationLookup("b52751b4-25f4-4172-a7fc-2432d7df7a96");
            window.open(url, "Change Password", "width=1024, height=768");
        });
    };

    var redeemLoyalty = function () {

        $("[api-redeem-loyalty-click]").unbind("click");
        $("[api-redeem-loyalty-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("471e9964-c401-4ce1-9718-8f48e065470e");
            window.open(url, "Loyalty", "width=1024, height=768");
        });

    };

    var redeemLoyaltyMobile = function (callback) {

        $("[api-redeem-loyalty-desktop-click]").unbind("click");
        $("[api-redeem-loyalty-desktop-click]").click(function (e) {
            e.preventDefault();
            if (callback) {
                var type = ($(this).attr("loyalty-type"));
                callback(type);
            }
        });
    };

    var redeemLoyaltyDesktop = function (callback) {
        $("[api-redeem-loyalty-desktop-click]").unbind("click");
        $("[api-redeem-loyalty-desktop-click]").click(function (e) {
            e.preventDefault();
            if (callback) {
                var type = ($(this).attr("loyalty-type"));
                callback(type);
            }
        });
    };

    var liveChat = function () {
        $("[api-livechat-click]").unbind("click");
        $("[api-livechat-click]").click(function (e) {
            e.preventDefault();
            $("#genesys-messgage-poll").click();
            if ($("#genesys-messgage-poll").length <= 0) {
                var url = _ExternalAplicationLookup("b9825520-ffe1-4285-ba8e-e2fbdf6c0d5a");
                window.open(url, "Live Chat", "width=480, height=420");
            }
        });
    };

    var playerRegister = function () {

        $("[api-register-click]").unbind("click");
        $("[api-register-click]").click(function (e) {
            e.preventDefault();
            $("[login-popup]").removeClass('open').fadeOut(0, function () {
                $("[login-popup] [popup-inner]").fadeOut();
            });

            var loginname = $("[api-home-page-login-username]").val();
            var password = $("[api-home-page-login-password]").val();
            if (loginname) {
                $('[name="LoginName"]').val(loginname);
                $('[name="LoginName"]').trigger("change");
            }

            if (password) {
                $('[name="Password"]').val(password);
                $('[name="Password"]').trigger("change");
            }

            if (casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {

                if (typeof displaySwiftRegistration === "function") {
                    if (window.casinoGlobals.CasinoMetadata.RequestMetadata.brandCode.toUpperCase() === "PG") {
                        displaySwiftRegistration();
                        return;
                    }
                }
                $("[api-register-mobile-content-hide]").hide();
                $("[api-register-mobile-content-show]").show();
                $("#contentWrapper").hide();
                $('#LoginButton').hide();
                $(".loginMobileBox").hide();
                if (window.casinoGlobals.CasinoMetadata.RequestMetadata.brandCode.toUpperCase() === "RV" && window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
                    $("footer").show();
                }

            } else {
                $("body").attr("style", "overflow:hidden");
            }
            $('#casinoRegistrationModalStep1').removeClass('hideOverlay');
            $("[api-show-registartion-content]").removeClass('hideOverlay');
            $("[LoginNameSuggestions],[CheckingLoginName],[usernameInUse]").hide();
            $("[name='LoginName']").removeClass("LoginNameSuggestionsLoading");
            //console.log($('#casinoRegistrationModalStep1'));

            $("body").scrollTop(0);
            _PopulateStaleRegistrationForm();

            if (typeof window.CustomEvents.ApiRegisterClickCallback !== 'undefined' &&
                typeof window.CustomEvents.ApiRegisterClickCallback === 'function') {
                window.CustomEvents.ApiRegisterClickCallback();
            }

            if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
                analyticsEventTracking("Register Initiated");
            }

            if (!casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {

                if ($("input:focus, select:focus").length < 1) {
                    $("[name='LoginName']").focus();
                }

                $("form").unbind("keyup keypress");
                $("form").on("keyup keypress", function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode === 13) {
                        e.preventDefault();

                        var element = $("input:focus");
                        if (element.length > 0) {
                            element.blur();
                        }

                        if (element.parent() && (element.parent().hasClass("loginUserBox") || (element.parent().parent() && element.parent().parent().hasClass("loginUserBox")))) {
                            $("#LoginButton").trigger("click");
                        } else {
                            if ($(".countrySelect").length > 0 && $(".countrySelect").is(":visible")) {
                                $(".countrySelect").hide();
                            }
                            if ($(".pcacountrylist").length > 0 && $(".pcacountrylist").is(":visible")) {
                                $(".pcacountrylist").hide();
                            }
                        }




                        return false;
                    }
                });



                $("#casinoRegistrationModalStep1 form ").unbind("keyup keypress");
                $("#casinoRegistrationModalStep1 form").on("keyup keypress", function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode === 13) {
                        e.preventDefault();
                        var element = $("input:focus");
                        if (element.length > 0) {
                            element.blur();
                        }
                        if (!$("#casinoRegistrationModalStep1").hasClass("hideOverlay")) {
                            $("[name='PlayerRegisterStep1']").trigger("click");
                        }
                    }
                });


                $("#casinoRegistrationModalStep2 form ").unbind("keyup keypress");
                $("#casinoRegistrationModalStep2 form").on("keyup keypress", function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode === 13) {
                        e.preventDefault();
                        var element = $("input:focus");
                        if (element.length > 0) {
                            element.blur();
                        }
                        if (!$("#casinoRegistrationModalStep2").hasClass("hideOverlay")) {
                            $("[name='PlayerRegisterStep2']").trigger("click");
                        }
                    }
                });

            }
        });
    };

    var unsubscribe = function () {

        $("[api-unsubscribe-click]").unbind("click");
        $("[api-unsubscribe-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("67b8889f-82f6-45b5-8f31-6943f08686e6");
            window.open(url, "Unsubscribe", "width=800, height=600");
        });

    };

    var maltaLicence = function () {

        $("[api-malta-licence-click]").unbind("click");
        $("[api-malta-licence-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("5de9feef-71ec-45e9-833f-d36af64141f0");
            var win = window.open(url, '_blank');
            win.focus();
        });

    };

    var ecograCertificate = function () {

        $("[api-ecogra-certificate-click]").unbind("click");
        $("[api-ecogra-certificate-click]").click(function (e) {
            e.preventDefault();
            var url = _ExternalAplicationLookup("c30a7904-760c-4413-bf3c-c1ad9df34cfc");
            var win = window.open(url, '_blank');
            win.focus();
        });

    };

    var rmmRedirectUrl = function () {
        return _ExternalAplicationLookup("3fed5250-8f41-4544-9e84-af0e815b5fd4");
    };

    var accountMobile = function () {

        $("[api-account-mobile-click]").unbind("click");
        $("[api-account-mobile-click]").click(function (e) {
            e.preventDefault();
            $("[api-mobile-account-info]").show();
            window.CustomEvents.MobileAccountAnimation();
            window.renderLoyaltyBalanceEvents.renderLoyalty();
            window.CustomEvents.CloseMenu();
        });
    };

    var launchGeneralTermsPopUp = function () {
        $("[api-general-terms-popup-click]").unbind("click");
        $("[api-general-terms-popup-click]").click(function (e) {
            e.preventDefault();
            var iframeContainer = $("[api-registration-terms-click]");
            var url = iframeContainer.attr("data-src");
            iframeContainer.attr("src", url);
            $("html, body").animate({
                scrollTop: 0
            }, "fast");
            $("[general-terms-pop-up]").removeClass("responsible-gaming-popup").removeClass("general-terms-pop-up").removeClass('hideOverlay').addClass("general-terms-pop-up").addClass("showOverlay");

            if ($("[general-terms-pop-up]").attr("hide-scroll") != undefined) {
                $("html, body").css({
                    "overflow-y": "hidden"
                });
            }

            if (typeof window.CustomEvents.TermsPopupClickCallback !== 'undefined' &&
                typeof window.CustomEvents.TermsPopupClickCallback === 'function') {
                window.CustomEvents.TermsPopupClickCallback();
            }

        });

    };
    var launchResponsibleGaming = function () {
        $("[api-Responsible-Gaming-PopUp-click]").unbind("click");
        $("[api-Responsible-Gaming-PopUp-click]").click(function () {
            var iframeContainer = $("[api-Responsible-Gaming-click]");
            var url = _ExternalAplicationLookup("5e152f88-f982-4053-8cd8-355468389cdb");
            if (!url) {
                url = iframeContainer.attr("data-src");
            }

            if (window.casinoGlobals.CasinoMetadata.RequestMetadata.languageCode.toLowerCase() === "nl" && window.postParams.JsonToken) {
                url = url.replace("en-us", "nl-nl");
            }

            iframeContainer.attr("src", url);

            $("[ResponsibleGamingPopUp]").removeClass("responsible-gaming-popup").removeClass("general-terms-pop-up").removeClass('hideOverlay').addClass("responsible-gaming-popup").addClass("showOverlay");

            $("html, body").animate({
                scrollTop: 0
            }, "fast");
            if ($("[ResponsibleGamingPopUp]").attr("hide-scroll") != undefined) {
                $("html, body").css({
                    "overflow-y": "hidden"
                });
            }

            if (typeof window.CustomEvents.ResponsibleGamingPopupClickCallback !== 'undefined' &&
                typeof window.CustomEvents.ResponsibleGamingPopupClickCallback === 'function') {
                window.CustomEvents.ResponsibleGamingPopupClickCallback();
            }
        });
    };


    var myAccountPopupClick = function () {
        $("[api-account-info-popup-click]").unbind("click");
        $("[api-account-info-popup-click]").click(function (e) {
            e.preventDefault();
            if (!window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
                $("[account-pop-up]").show();
                $("[account-balances]").trigger("click");
                PageScroll().toTopScrolling();
                PageScroll().disableScrolling();
            } else {
                $("[api-register-mobile-content-hide], [api-render-completed], #contentWrapper").hide();

                $(".account-sub-content").hide();
                $(".account-panel-container").hide();
                $("[account-sub-category-item]").hide();
                $("[account-mobile-selection-toggle]").show();
                $("[account-category-item]").show();

                if (typeof window.CustomEvents.CloseMenu !== 'undefined' &&
                    typeof window.CustomEvents.CloseMenu === 'function') {
                    window.CustomEvents.CloseMenu();
                }

                if (typeof window.CustomEvents.MobileAccountAnimation !== 'undefined' &&
                    typeof window.CustomEvents.MobileAccountAnimation === 'function') {
                    window.CustomEvents.MobileAccountAnimation();
                }

                $("[account-pop-up]").show();
                $("#mobileBankingContent").hide();

            }
        });
    };

    var displayRtpDoc = function () {
        if ($("[data-pagename='rtp']").length !== 0) {
            $("[data-pagename='rtp']").unbind("click");
            $("[data-pagename='rtp']").click(function (e) {
                e.preventDefault();
                window.open("https://content.dmgamingsystems.com/rtp.pdf");
            });
        }
    };

    var loginPopUp = function () {
        $("[login-popup-trigger]").unbind("click");
        $("[login-popup-trigger]").on("click", function (e) {
            e.preventDefault();

            //console.log($(this).parent().hasClass("sign-up"));

            if (!casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
                $("form").unbind("keyup keypress");
                $("form").on("keyup keypress", function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode === 13) {
                        e.preventDefault();

                        var element = $("input:focus");
                        if (element.length > 0) {
                            element.blur();
                        }

                        if (((element.parent() && element.parent().hasClass("loginUserBox")) || (element.parent().parent() && element.parent().parent().hasClass("loginUserBox"))) ||
                            ((element.parent() && element.parent().hasClass("loginPswdBox")) || (element.parent().parent() && element.parent().parent().hasClass("loginPswdBox")))) {
                            $("#LoginButton").trigger("click");
                        }

                        return false;
                    }
                });
            }

            $("[login-popup]").addClass('open').fadeIn(150, function () {
                $("[login-popup] [popup-inner]").delay(100).fadeIn();
            });

            if (typeof window.CustomEvents.LoginPopup === "function") {
                window.CustomEvents.LoginPopup();
            }
        });

        $("[login-popup-close]").unbind("click");
        $("[login-popup-close]").on('click', function (e) {
            e.preventDefault();
            $("[login-popup]").fadeOut().removeClass("active");
            $("[login-popup]").find("[popup-inner]").fadeOut();
        });
    };

    var passwordShowHide = function () {
        $("[password-eye]").unbind("click");
        $("[password-eye]").on("click", function (e) {
            e.preventDefault();
            var eyeClicked = $(this);
            if (eyeClicked.hasClass('clicked')) {
                eyeClicked.siblings("input").attr('type', 'password');
                eyeClicked.removeClass('clicked');
                eyeClicked.find('.open').show();
                eyeClicked.find('.closed').hide();
            } else {
                eyeClicked.siblings("input").attr('type', 'text');
                eyeClicked.addClass('clicked');
                eyeClicked.find('.open').hide();
                eyeClicked.find('.closed').show();
            }
        });
    };

    var browserSupportClose = function () {
        $("[browser-support-close]").unbind("click");
        $("[browser-support-close]").on("click", function () {

            if (ReadCookie("BS") == null) {
                var currentDate = new Date();
                var year = currentDate.getFullYear();
                var month = currentDate.getMonth();
                var day = currentDate.getDate();
                var futureDate = new Date(year + 1, month, day);

                CreateCookieByDate("BS", "viewed", futureDate);
            }
            $(".browserSupportPopup:not(.safariFlash)").removeClass("down");
            setTimeout(function () {
                $(".browserSupportPopup:not(.safariFlash)").fadeOut(100).remove();
            }, 1000);
        });
    };

    var flashSupportClose = function () {
        if (ReadCookie("FE") == null) {
            if (casinoGlobals.CasinoMetadata.RequestMetadata.isMobile != true) {
                var hasFlash = false;
                var flashEnabled = false;
                if (navigator.mimeTypes && navigator.mimeTypes['application/x-shockwave-flash'] != undefined) {
                    hasFlash = true;

                    if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
                        flashEnabled = true;
                    }
                }

                if (hasFlash == true) {
                    var currentDate = new Date();

                    var futureDate = new Date(currentDate.getTime());
                    futureDate.setDate(futureDate.getDate() + 1);

                    CreateCookieByDate("FE", "viewed", futureDate);
                } else {
                    $(".safariFlash.browserSupportPopup").fadeIn(100);

                    $("[flash-support-close]").unbind("click");
                    $("[flash-support-close]").on("click", function () {
                        var currentDate = new Date();

                        var futureDate = new Date(currentDate.getTime());
                        futureDate.setDate(futureDate.getDate() + 1);

                        CreateCookieByDate("FE", "viewed", futureDate);

                        $(this).parent().removeClass("down");
                        setTimeout(function () {
                            $(this).parent().fadeOut(100).remove();
                        }, 1000);
                    });
                }
            }
        }
    };

    return {

        socialMediaLinks: function () {
            socialMediaLinks();
        },

        playerLogout: function () {
            playerLogout();
        },

        mgsMyAccount: function () {
            mgsMyAccount();
        },

        playerBanking: function () {
            playerBanking();
        },

        playerRegisterBanking: function () {
            playerRegisterBanking();
        },

        transactionHistory: function () {
            transactionHistory();
        },

        changePassword: function () {
            changePassword();
        },

        gameHistory: function () {
            gameHistory();
        },

        liveChat: function () {
            liveChat();
        },

        redeemLoyalty: function () {
            redeemLoyalty();
        },

        redeemLoyaltyMobile: function (callback) {
            redeemLoyaltyMobile(callback);
        },

        redeemLoyaltyDesktop: function (callback) {
            redeemLoyaltyDesktop(callback);
        },
        playerRegister: function () {
            playerRegister();
        },

        unsubscribe: function () {
            unsubscribe();
        },

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

        accountMobile: function () {
            accountMobile();
        },

        launchGeneralTermsPopUp: function () {
            launchGeneralTermsPopUp();
        },

        launchResponsibleGaming: function () {
            launchResponsibleGaming();
        },

        maltaLicence: function () {
            maltaLicence();
        },

        supportWindow: function () {
            supportWindow();
        },

        ecograCertificate: function () {
            ecograCertificate();
        },

        myAccountPopupClick: function () {
            myAccountPopupClick();
        },

        displayRtpDoc: function () {
            displayRtpDoc();
        },

        loginPopUp: function () {
            loginPopUp();
        },

        passwordShowHide: function () {
            passwordShowHide();
        },

        browserSupportClose: function () {
            browserSupportClose();
        },

        flashSupportClose: function () {
            flashSupportClose();
        }
    };
}
function iframeListener(event) {
    $('#iframe-response').html(event.data);
}

if (window.addEventListener) {
    addEventListener("message", iframeListener, false);
}
else {
    attachEvent("onmessage", iframeListener);
}

function PopPlayBox() {

    if (IsAustralia() && !IsPlayRoyalVegas()) {
        ausRegisterPopup();
    }

}

function LoadLog() {
    $(document).ready(function () {
        if (IsAustralia() && !IsPlayRoyalVegas()) {
            ausRegisterPopup();
        } else if (!IsMobile()) {
            triggerLoginPop();
        } else if (window.PreconnectLoginUrl) {
            window.location.href = window.PreconnectLoginUrl;
        }
    });


    return false;
}

function triggerLoginPop() {
    $("#overlay").show();
    $("#registerIframe").removeClass("showIframe");
    $("#logonIframe").addClass("showIframe");
    $("#regBtnClose").removeClass("reg-close");
    $('.close-modal').trigger("click");

}

function LoadReg() {
    $(document).ready(function () {
        if (IsAustralia() && !IsPlayRoyalVegas()) {
            ausRegisterPopup();
        } else if (!IsMobile()) {
            triggerRegistrationPop();
        } else if (window.PreconnectRegisterUrl) {
            window.location.href = window.PreconnectRegisterUrl;
        }
    });

    return false;
}

function ValidateReg() {
    if (IsAustralia() && !IsPlayRoyalVegas()) {
        ausRegisterPopup();
        return false;
    }

    return true;
}

function triggerRegistrationPop() {
    $("#overlay").show();
    $("#logonIframe").removeClass("showIframe");
    $("#registerIframe").addClass("showIframe");
    $("#regBtnClose").addClass("reg-close");
    $('.close-modal').trigger("click");
}

function closereglog() {
    $("#overlay").hide();
}

var ausRegisterPopup = function () {
    var redirectPlayPopup = $("[redirectplaypopup]");

    redirectPlayPopup.removeClass('hideOverlay').addClass('showOverlay');

    redirectPlayPopup.find(".close").on("click", function (event) {
        redirectPlayPopup.removeClass('showOverlay').addClass('hideOverlay');
        event.preventDefault();
    });
};

function IsAustralia() {
    return waitFor(window.casinoGlobals, 100, 30, function () {
        return waitFor(window.casinoGlobals.CasinoMetadata, 100, 30, function() {
            return waitFor(window.casinoGlobals.CasinoMetadata.RequestMetadata, 100, 30, ValidateIsAustralia);
        });
    });
}

function ValidateIsAustralia() {
    //console.log("ValidateIsAustralia - " + window.casinoGlobals.CasinoMetadata.RequestMetadata.CountryCode);
    return window.casinoGlobals.CasinoMetadata.RequestMetadata.CountryCode &&
        window.casinoGlobals.CasinoMetadata.RequestMetadata.CountryCode.toLowerCase() === "au";
}

function IsPlayRoyalVegas() {
    return getQueryParams().BrandCode &&
        getQueryParams().BrandCode.toLowerCase() === "prv";
}

function IsMobile() {
    return casinoGlobals.CasinoMetadata != null &&
        casinoGlobals.CasinoMetadata.RequestMetadata != null &&
        casinoGlobals.CasinoMetadata.RequestMetadata.isMobile;
}

function _InitFrontEndCustomScripts() {
    //Play Royal Vegas Pop Params
    if (!IsPlayRoyalVegas()) {
        var params = '?s=' +
            window.AffiliateId +
            '&a=' +
            window.AdId +
            '&visitId=' +
            window.VisitId;

        $('a[href$="playroyalvegas.com"],a[href$="playroyalvegas.com/"]').each(function () {
            var $link = $(this);
            $link.attr('href', $link.attr('href') + params);
        });
    }

    if ($(".GDPRWindow").length > 0) {
        var gdprBrand = $("#privacyLinkValues").attr("data-brand").toLowerCase();
        var gdprLanguage = $("#privacyLinkValues").attr("data-lang")
    }

    if (gdprBrand == "wtc") {
        $(".GDPRWindow").text('datarequest@playersupportcentre.com');
        $(".GDPRWindow").attr('href', 'mailto:datarequest@playersupportcentre.com');
    }
    else {
        $(".GDPRWindow").text('https://www.playersupportcentre.com/' + gdprBrand + '/' + gdprLanguage + '/RemoveDataRequest')

        $(".GDPRWindow").click(function () {
            window.open('https://www.playersupportcentre.com/' + gdprBrand + '/' + gdprLanguage + '/RemoveDataRequest', 'MsgWindow', 'width=550,height=750')

            return false;
        });
    }


    //GAMES BLOCK
    $("#gamesBlock > div > div > span > span > div").click(function () {
        $('.selected').removeClass('selected');
        $(this).addClass('selected');
        $this = $.trim($(this).find('h3').html());

        $('#gamesBlock > div:not(:first-child)').hide();
        $('*[data-item-type="' + $this + '"]').show();
    })

    $('#gamesBlock > div > div > span > span > div').hover(function () {
        $(this).stop().find('h3').toggleClass('h3-hover-underline');
    });

    $("#gamesBlock > div > div > span > span:nth-of-type(1) > div").trigger('click');

    // JACKPOT TICKER
    $jpTicker = 0.00;

    $.ajax({
        method: "GET",
        url: "https://1clickapi.com/v4/SPC/en/1/games/GetProgressive/Total"
    })
        .done(function (data) {
            $jpTicker = data.Model;
            potBuild();

        });

    function potBuild() {

        $jpSplit = ("" + $jpTicker.toFixed(2)).split("");
        $b = "";

        $.each($jpSplit, function (i, v) {
            if (v != '.')
                $b += "<li>" + v + "</li>";
        });

        $('.progressive-jackpot ul').html($b);
    }

    function progression() {
        $num = parseFloat((Math.random() / 5).toFixed(2));
        $jpTicker = $jpTicker + $num;
        potBuild();
    }

    setInterval(progression, 2000);
}



function _CustomFrontEndScripts() {

    //setup login reg iframes
    (function () {
        var $container = $('.regLoginIframe');

        if (!$container.length ||
            $container.children().length ||
            !window.PreconnectLoginUrl ||
            !window.PreconnectRegisterUrl) {
            return;
        }

        var $closeButton = $('<span>',
            {
                id: 'regBtnClose',
                'class': 'close-icon'
            });
        $closeButton.text('X');

        $container.empty();
        $container.append($closeButton);

        if (!IsAustralia() || IsPlayRoyalVegas()) {
            var $regPop = createIframe('allow-top-navigation allow-scripts allow-same-origin allow-popups allow-forms', 'registerIframe',
                'regIframe logreg-iframe',
                800,
                600,
                window.PreconnectRegisterUrl);

            $container.append($regPop);
        }
        // sandbox="allow-top-navigation allow-scripts"
        var $loginPop = createIframe('allow-top-navigation allow-scripts allow-same-origin allow-popups allow-forms', 'logonIframe',
            'Ioginframe logreg-iframe',
            630,
            350,
            window.PreconnectLoginUrl);

        $container.append($loginPop);

        function createIframe(sandbox, id, className, height, width, src) {
            return $('<iframe>',
                {
                    'sandbox': sandbox,
                    id: id,
                    'class': className,
                    'frameborder': 0,
                    'height': height,
                    'width': width,
                    'src': src
                });
        }
    }());

    //load immediate login pop
    (function () {
        if (queryStringLookup["popup"] === "login") {

            if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
                analyticsEventTracking("popupLogin");
            }

            window.history.pushState('', '', location.pathname);

            LoadLog();
        }
    }());

    //load immediate register pop
    (function () {
        if (queryStringLookup["popup"] === "register") {

            if (analyticsEventTracking && typeof analyticsEventTracking === "function") {
                analyticsEventTracking("popupRegister");
            }

            window.history.pushState('', '', location.pathname);

            LoadReg();
        }
    }());
}



function _EmailMessages() {

    var getEmailMessgages = function () {
        return $.ajax({
            type: "POST",
            url: window.AjaxUrl.EmailMessages,
            data: window.postParams
        });
    };

    return {
        getEmailMessgages: function () {
            return getEmailMessgages();
        }
    };

}

window.DocumentUploadItemObjects = [];

function getDocuments(refreshData) {
    console.log("--- GET DOCUMENTS ---");

    var dataRequest = {
        CultureCode: window.postParams.CultureCode,
        BrandCode: window.postParams.BrandCode,
        JsonToken: window.postParams.JsonToken,
        RefreshData: refreshData
    };

    return $.ajax({
        type: "POST",
        url: window.AjaxUrl.DocumentVerificationGetDocuments,
        data: dataRequest,
        dataType: "json",
        error: function (data) {
            console.log(data);
        }
    });
};

function _DocumentVerification() {

    var statusId = {
        approved: "50a55dfc-ebf7-4e30-97a1-cc9a1bcc119d",
        requested: "d066a8ee-cb9f-4791-b787-b336280477b8",
        pending: "2902e92f-c308-490e-8744-27d1f03527a0",
        rejected: "f950e840-99e9-4cb4-b575-c0895bc10ae7"
    };
    
    var documentsByStatus = function (statusId) {
        var documents = [];
        var document = window.casinoGlobals.DocumentVerification.Documents;
        console.log("--- DOCUMENTS FOR : " + statusId + " ---");

        $("[show-document-being-reviewed-section]").hide();
        if (document && document.length > 0) {

            for (var d = 0; d < document.length; d++) {

                if (document[d] && document[d].DocumentStatusId) {
                    if (statusId) {
                        if (document[d].DocumentStatusId.toLowerCase() === statusId.toLowerCase()) {
                            if (document[d].DocumentStatusId.toLowerCase() === "f950e840-99e9-4cb4-b575-c0895bc10ae7") {
                                $("[display-rejected-doc-grid]").show();
                            }
                            $("[display-all-doc-grid]").show();
                            documents.push(document[d]);
                        }
                    } else {
                        $("[display-all-doc-grid]").show();
                        if (document[d].DocumentStatusId.toLowerCase() !== "f950e840-99e9-4cb4-b575-c0895bc10ae7") {
                            documents.push(document[d]);
                        }
                    }
                }
            }
            
            
            if (window.casinoGlobals.DocumentVerification.ShowGrid) {
                $("[hide-document-sections]").show();
                $("[show-document-null-section]").hide();
                $("[api-add-document-files]").show();
            } else {
                $("[hide-document-sections]").hide();
                $("[show-document-null-section]").show();
                $("[api-add-document-files]").hide();
            }

        } else {
            $("[hide-document-sections]").hide();
            $("[show-document-null-section]").show();
            $("[api-add-document-files]").hide();
        }

        if (window.casinoGlobals.DocumentVerification.IsPendingReview) {
            $("[show-document-being-reviewed-section]").show();
            $("#list-requested-document-verification-grid [show-document-null-section], [api-add-document-files]").hide();
        }

        if (window.casinoGlobals.DocumentVerification.ShowDataScreen) {
            $("[account-section-document-status] [hide-document-sections]").show();
            $("[account-section-document-status] [show-document-null-section]").hide();
        }
        //console.log(window.casinoGlobals.DocumentVerification);
        return documents;
    };

    function updateUploadLimit(documentId, operator) {
        var duio = new jinqJs()
            .from(window.DocumentUploadItemObjects)
            .where(function (row) {
                return row.DocId == documentId;
            })
            .select();

        if (duio.length > 0) {
            var usedFileSpace = $("[doc-type-id=" + duio[0].DocTypeId + "].uploadLimit .usedFileSpace");

            var duio1 = new jinqJs()
                .from(window.DocumentUploadItemObjects)
                .where(function (row) {
                    return row.DocTypeId == duio[0].DocTypeId;
                })
                .select(function (row) {
                    row.FileSize = row.file.size;
                    return row;
                });
            if (duio1.length > 0) {
                duio1 = new jinqJs()
                    .from(duio1)
                    .groupBy("DocTypeId")
                    .sum("FileSize")
                    .select([{ field: 'DocTypeId' }, { field: 'FileSize' }])[0];


                var usedSpace = (duio1.FileSize.toFixed(2) / (1000000).toFixed(2)).toFixed(2);

                if (operator == "subtract") {
                    usedSpace = ((duio1.FileSize.toFixed(2) - duio[0].file.size) / (1000000).toFixed(2)).toFixed(2);
                }

                usedFileSpace.html(usedSpace);
            }
        }

    }

    var documentUploadEvent = {
        documentUpload: function () {
            $("[api-add-document-files]").unbind("click");
            $("[api-add-document-files]").click(function (e) {
                e.preventDefault();

                if (window.DocumentUploadItemObjects.length > 0) {
                    $("[api-add-document-files]").hide();
                    $(".spinner.uploader").css({ display: "inline-block" });
                }

                setTimeout(function () {
                    function groupBy(array, f) {
                        var groups = {};
                        array.forEach(function (o) {
                            var group = JSON.stringify(f(o));
                            groups[group] = groups[group] || [];
                            groups[group].push(o);
                        });
                        return Object.keys(groups).map(function (group) {
                            return groups[group];
                        });
                    }

                    var result = groupBy(window.DocumentUploadItemObjects, function (item) {
                        return [item.DocTypeId];
                    });

                    var formData;
                    var d;

                    if (window.DocumentUploadItemObjects.length > 0) {


                        for (var r = 0; r < result.length; r++) {

                            $("[document-verification-loader]").show();
                            var documentTypeList = result[r];
                            //console.log("------------------");
                            //console.log(documentTypeList);
                            //console.log("------------------");

                            formData = new FormData();
                            formData.append("DocumentId", documentTypeList[0].DocId);
                            formData.append("DocumentTypeId", documentTypeList[0].DocTypeId);

                            formData.append("JsonToken", window.postParams.JsonToken);
                            formData.append("BrandCode", window.postParams.BrandCode);
                            formData.append("CultureCode", window.postParams.CultureCode);

                            for (d = 0; d < documentTypeList.length; d++) {
                                formData.append("FileDataByteArrayList_" + documentTypeList[d].ItemId,
                                    documentTypeList[d].file);
                                formData.append("ItemId", documentTypeList[d].ItemId);
                                formData.append("ItemName", documentTypeList[d].ItemName);
                            }
                            //console.log(documentTypeList);
                            //console.log(formData);

                            $.ajax({
                                type: "POST",
                                url: window.AjaxUrl.DocumentVerificationUpload,
                                data: formData,
                                contentType: false,
                                processData: false,
                                timeout: 1200000,
                                async: false,
                                beforeSend: function() {
                                },
                                success: function(response) {
                                    if (response) {
                                        if (response.IsPendingReview) {
                                            $("[show-document-being-reviewed-section]").show();
                                            $(
                                                    "#list-requested-document-verification-grid [show-document-null-section], [api-add-document-files]")
                                                .hide();
                                            $(".dv-upload-container").hide();
                                            return;
                                        } else {
                                            $("[api-add-document-files]").show();
                                        }

                                        //console.log(response);
                                        if (response.IsSuccess) {
                                            var removeFiles = response.FileUploadResponse;
                                            for (var re = 0; re < removeFiles.length; re++) {
                                                if (removeFiles[re].IsSuccess) {
                                                    $("#itemId_" + removeFiles[re].ItemId).remove();
                                                    var removeFromArray = removeFiles[re].ItemId;
                                                    for (var d = 0; window.DocumentUploadItemObjects.length > d; d++) {
                                                        if (window.DocumentUploadItemObjects[d].ItemId ===
                                                            removeFromArray) {
                                                            window.DocumentUploadItemObjects.splice(d, 1);
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            $("[doc-type-id='" + response.DocumentTypeId + "']").parent("div").remove();
                                            $("[api-upload-success]").show().delay(2000).slideUp(500);

                                        } else {

                                            var failedFiles = response.FileUploadResponse;
                                            for (var ff = 0; ff < failedFiles.length; ff++) {
                                                if (!failedFiles[ff].IsSuccess) {
                                                    if (failedFiles[ff].ItemId) {
                                                        $("#itemId_" + failedFiles[ff].ItemId).css({
                                                            "background": "#F00",
                                                            "color": "#FFF"
                                                        }).html(failedFiles[ff].FileName +
                                                            ' - ' +
                                                            failedFiles[ff].Error +
                                                            '<span class="dv-close-container" dv-remove-file-click="dv-remove-file-click" document-id="' +
                                                            response.DocumentId +
                                                            '" file-id="' +
                                                            failedFiles[ff].ItemId +
                                                            '"><svg version="1.1" id="Layer_4" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 460 460" enable-background="new 0 0 460 460" xml:space="preserve"><g><path d="M80.7,29.7l349.6,349.6c11.3,11.3,11.3,29.5,0,40.8l-10.2,10.2c-11.3,11.3-29.5,11.3-40.8,0L29.7,80.6c-11.3-11.3-11.3-29.5,0-40.8l10.2-10.2C51.2,18.4,69.4,18.4,80.7,29.7z"></path><path d="M29.7,379.3L379.3,29.7c11.3-11.3,29.5-11.3,40.8,0l10.2,10.2c11.3,11.3,11.3,29.5,0,40.8L80.7,430.2c-11.3,11.3-29.5,11.3-40.8,0L29.7,420C18.4,408.7,18.4,390.4,29.7,379.3z"></path></g></svg></span>');
                                                    } else {
                                                        $("#dv-upladed-docs-container-" + response.DocumentId)
                                                            .prepend('<div style="background: #F00; color: #FFF;">' +
                                                                failedFiles[ff].Error +
                                                                '</div>');
                                                    }
                                                }
                                            }
                                        }
                                    }
                                },
                                error: function(error) {
                                    $("[upload-error-message]").show();
                                    $("[api-add-document-files]").show();
                                },
                                complete: function() {
                                    $("[document-verification-loader]").hide();

                                    $("[dv-remove-file-click]").unbind("click");
                                    $("[dv-remove-file-click]").on("click",
                                        function() {
                                            var itemId = $(this).attr("file-id");
                                            var docId = $(this).attr("document-id");
                                            updateUploadLimit(docId, "subtract");
                                            for (var d = 0; window.DocumentUploadItemObjects.length > d; d++) {
                                                if (window.DocumentUploadItemObjects[d].ItemId === itemId) {
                                                    window.DocumentUploadItemObjects.splice(d, 1);
                                                    $("#itemId_" + itemId).remove();
                                                    break;
                                                }
                                            }
                                        });

                                    $(".spinner.uploader").css({ display: "none" });
                                }
                            });
                        }
                    } else {
                        $(".spinner.uploader").css({ display: "none" });
                        $("[api-add-document-files]").show();
                        $("[api-upload-no-docs]").show().delay(2000).slideUp(500);
                    }
                }, 100);
            });
        }
    }

    window.renderDocuments = {

        renderAllDocuments: function () {

            $("[document-verification-loader]").show();
            window.TempoObjects.allDocumentsObject.render(null);
            window.TempoObjects.allDocumentsObject.when(TempoEvent.Types.RENDER_COMPLETE, function (event) {
                
                $("[document-verification-loader]").hide();
                if (!window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
                    $("[upload-doc-click]").unbind("click");
                    $("[upload-doc-click]").click(function () {
                        $(".tab").removeClass("selected").removeAttr("selected");
                        $("[account-document-verificaction-sub-category-upload]").addClass("selected").attr("selected", "");;
                        $("[account-upload-docs-content]").show();
                        $("[account-requested-docs-content]").hide();
                        $("[account-doc-status-content]").hide();
                    });
                } else {
                    $("[upload-doc-click]").unbind("click");
                    $("[upload-doc-click]").click(function () {
                        $('[account-mobile-secion-child="account-section-upload-docs"]').click();
                    });
                }
            }).render(documentsByStatus());
        },

        renderApprovedDocuments: function () {
            $("[document-verification-loader]").show();
            window.TempoObjects.approvedDocumentsObject.render(null);
            window.TempoObjects.approvedDocumentsObject.when(TempoEvent.Types.RENDER_COMPLETE, function (event) {
                $("[document-verification-loader]").hide();
                if (window.errorListString) {
                    $("[api-upload-error-list]").append(window.errorListString).show();
                }
            }).render(documentsByStatus(statusId.approved));
        },

        renderRequestedDocuments: function () {
            $("[document-verification-loader]").show();
            window.TempoObjects.requestedDocumentsObject.render(null);
            window.TempoObjects.requestedDocumentsObject.when(TempoEvent.Types.RENDER_COMPLETE, function (event) {
                $("[document-verification-loader]").hide();
                $(".uploadError").hide();
                window.uploadItemScope = {};

                if (window.errorListString) {
                    $("[api-upload-error-list]").append(window.errorListString).show();
                }

                $("[dv-add-files-click]").unbind("click");
                $("[dv-add-files-click]").click(function () {

                    var currentObject = $(this);
                    window.uploadItemScope = {};
                    window.uploadItemScope.DocumentId = currentObject.attr("doc-id");
                    window.uploadItemScope.DocumentTypeId = currentObject.attr("doc-type-id");
                    $("#DvFileUploader").click();
                    $(".uploadError").hide();
                    $(".extentionError").hide();
                });


                $("[dv-drag-and-drop-area]").each(function (e, s) {
                    var dropbox = $(this);

                    dropbox.on("dragenter", function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                    });
                    dropbox.on("dragexit", function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                    });
                    dropbox.on("dragleave", function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        $(this).removeClass("dragOver");
                    });

                    dropbox.on("dragover", function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        $("[dv-drag-and-drop-area]").removeClass("dragOver");
                        $(this).addClass("dragOver");
                    });

                    dropbox.on("drop", function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        $("[dv-drag-and-drop-area]").removeClass("dragOver");

                        var currentObject = $(this);
                        window.uploadItemScope = {};
                        window.uploadItemScope.DocumentId = currentObject.attr("doc-id");
                        window.uploadItemScope.DocumentTypeId = currentObject.attr("doc-type-id");

                        var dt = e.dataTransfer || (e.originalEvent && e.originalEvent.dataTransfer);
                        var files = e.target.files || (dt && dt.files);
                        for (var i = 0 ; i < files.length; i++) {

                            var file = files[i];

                            addDocumentUploadItemObjects(file, window.uploadItemScope);
                        };

                        buildFileList(window.uploadItemScope.DocumentId);

                        removeItemClickEvent();

                    });
                });

                function addDocumentUploadItemObjects(file, uploadItemScope) {
                    var currentDocError = "[doc-id=" + uploadItemScope.DocumentId + "] .uploadError";
                    var currentDocExtError = "[doc-id=" + uploadItemScope.DocumentId + "] .extentionError";

                    $(currentDocError).hide();
                    $(currentDocExtError).hide();

                    var fileNameSplit = file.name.split(".");

                    if (fileNameSplit.length > 0) {
                        var fileExt = fileNameSplit[fileNameSplit.length - 1].toLowerCase();

                        if ($("#DvFileUploader").attr("accept").indexOf("." + fileExt) < 0) {
                            console.log('Showing Error');
                            $(currentDocExtError).show();
                        } else {
                            if (file.size > 10000000) {
                                console.log('Showing Error');
                                $(currentDocError).show();
                            } else {

                                if (window.DocumentUploadItemObjects.length > 0) {
                                    var duio = new jinqJs()
                                        .from(window.DocumentUploadItemObjects)
                                        .where(function (row) {
                                            return row.DocTypeId == uploadItemScope.DocumentTypeId;
                                        })
                                        .select(function (row) {
                                            row.FileSize = row.file.size;
                                            return row;
                                        });

                                    if (duio.length > 0) {
                                        duio = new jinqJs()
                                            .from(duio)
                                            .groupBy("DocTypeId")
                                            .sum("FileSize")
                                            .select([{ field: 'DocTypeId' }, { field: 'FileSize' }])[0];

                                        if ((duio.FileSize + file.size) > 10000000) {
                                            console.log('Showing Error');
                                            $(currentDocError).show();
                                        } else {
                                            window.DocumentUploadItemObjects.push({
                                                file: file,
                                                ItemId: guid(),
                                                ItemName: file.name,
                                                DocId: uploadItemScope.DocumentId,
                                                DocTypeId: uploadItemScope.DocumentTypeId
                                            });
                                            updateUploadLimit(uploadItemScope.DocumentId, "add");
                                        }
                                    } else {
                                        window.DocumentUploadItemObjects.push({
                                            file: file,
                                            ItemId: guid(),
                                            ItemName: file.name,
                                            DocId: uploadItemScope.DocumentId,
                                            DocTypeId: uploadItemScope.DocumentTypeId
                                        });
                                        updateUploadLimit(uploadItemScope.DocumentId, "add");
                                    }
                                } else {
                                    window.DocumentUploadItemObjects.push({
                                        file: file,
                                        ItemId: guid(),
                                        ItemName: file.name,
                                        DocId: uploadItemScope.DocumentId,
                                        DocTypeId: uploadItemScope.DocumentTypeId
                                    });
                                    updateUploadLimit(uploadItemScope.DocumentId, "add");
                                }
                            }
                        }
                    } else {
                        console.log('Showing Error');
                        $(currentDocExtError).show();
                    }
                }

                function buildFileList(documentId) {
                    var appendFileList = "";
                    for (var d = 0; window.DocumentUploadItemObjects.length > d; d++) {
                        if (window.DocumentUploadItemObjects[d].DocId === documentId) {
                            appendFileList += '<div id="itemId_' + window.DocumentUploadItemObjects[d].ItemId + '">' + window.DocumentUploadItemObjects[d].ItemName + '<span class="dv-close-container" dv-remove-file-click="dv-remove-file-click" document-id="' + window.DocumentUploadItemObjects[d].DocId + '" file-id="' + window.DocumentUploadItemObjects[d].ItemId + '"><svg version="1.1" id="Layer_4" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 460 460" enable-background="new 0 0 460 460" xml:space="preserve"><g><path d="M80.7,29.7l349.6,349.6c11.3,11.3,11.3,29.5,0,40.8l-10.2,10.2c-11.3,11.3-29.5,11.3-40.8,0L29.7,80.6c-11.3-11.3-11.3-29.5,0-40.8l10.2-10.2C51.2,18.4,69.4,18.4,80.7,29.7z"></path><path d="M29.7,379.3L379.3,29.7c11.3-11.3,29.5-11.3,40.8,0l10.2,10.2c11.3,11.3,11.3,29.5,0,40.8L80.7,430.2c-11.3,11.3-29.5,11.3-40.8,0L29.7,420C18.4,408.7,18.4,390.4,29.7,379.3z"></path></g></svg></span></div>';
                        }
                    }
                    $("#dv-upladed-docs-container-" + documentId).html(appendFileList);
                }

                function removeItemClickEvent() {

                    $("[dv-remove-file-click]").unbind("click");
                    $("[dv-remove-file-click]").click(function () {

                        $(".uploadError").hide();
                        $(".extentionError").hide();

                        var itemId = $(this).attr("file-id");
                        var docId = $(this).attr("document-id");

                        updateUploadLimit(docId, "subtract");

                        for (var d = 0; window.DocumentUploadItemObjects.length > d; d++) {
                            if (window.DocumentUploadItemObjects[d].ItemId === itemId) {
                                window.DocumentUploadItemObjects.splice(d, 1);
                                break;
                            }
                        }

                        buildFileList(docId);
                        removeItemClickEvent();
                    });
                }

                $("#DvFileUploader").unbind("change");
                $("#DvFileUploader").change(function (e) {
                    e.preventDefault();
                    
                    if (window.uploadItemScope) {
                        $(".uploader-grey-block[dv-drag-and-drop-area][doc-type-id=" + window.uploadItemScope.DocumentTypeId + "] .svg-container").hide();
                        $(".uploader-grey-block[dv-drag-and-drop-area][doc-type-id=" + window.uploadItemScope.DocumentTypeId + "] .spinner.select-uploader").show();
                        
                        for (var i = 0 ; i < $(this)[0].files.length; i++) {
                            var file = $(this)[0].files[i];

                            addDocumentUploadItemObjects(file, window.uploadItemScope);
                        };

                        //******************************************************/

                        buildFileList(window.uploadItemScope.DocumentId);

                        removeItemClickEvent();

                        //******************************************************/
                        
                        var input = $("#DvFileUploader");
                        input.replaceWith(input.val("").clone(true));
                        
                        $(".uploader-grey-block[dv-drag-and-drop-area][doc-type-id='" + window.uploadItemScope.DocumentTypeId + "'] .svg-container").show();
                        $(".uploader-grey-block[dv-drag-and-drop-area][doc-type-id='" + window.uploadItemScope.DocumentTypeId + "'] .spinner.select-uploader").hide();
                    }
                });
            }).render(documentsByStatus(statusId.requested));
        },

        renderRequiredDocuments: function () {
            $("[document-verification-loader]").show();
            window.TempoObjects.requiredDocumentsObject.render(null);
            window.TempoObjects.requiredDocumentsObject.when(TempoEvent.Types.RENDER_COMPLETE, function (event) {
                $("[document-verification-loader]").hide();

                if (!window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
                    $("[upload-doc-click]").unbind("click");
                    $("[upload-doc-click]").click(function () {
                        $(".tab").removeClass("selected").removeAttr("selected");
                        $("[account-document-verificaction-sub-category-upload]").addClass("selected").attr("selected", "");;
                        $("[account-upload-docs-content]").show();
                        $("[account-requested-docs-content]").hide();
                        $("[account-doc-status-content]").hide();
                    });
                } else {
                    $("[upload-doc-click]").unbind("click");
                    $("[upload-doc-click]").click(function () {
                        $('[account-mobile-secion-child="account-section-upload-docs"]').click();
                    });
                }

                if (window.errorListString) {
                    $("[api-upload-error-list]").append(window.errorListString).show();
                }
            }).render(documentsByStatus(statusId.requested));
        },

        renderRejectedDocuments: function () {
            $("[document-verification-loader]").show();
            window.TempoObjects.rejectedDocumentsObject.render(null);
            window.TempoObjects.rejectedDocumentsObject.when(TempoEvent.Types.RENDER_COMPLETE, function (event) {
                $("[document-verification-loader]").hide();
                if (window.errorListString) {
                    $("[api-upload-error-list]").append(window.errorListString).show();
                }
            }).render(documentsByStatus(statusId.rejected));
        },

        renderPendingDocuments: function () {
            $("[document-verification-loader]").show();
            window.TempoObjects.pendingDocumentsObject.render(null);
            window.TempoObjects.pendingDocumentsObject.when(TempoEvent.Types.RENDER_COMPLETE, function (event) {
                $("[document-verification-loader]").hide();
                if (window.errorListString) {
                    $("[api-upload-error-list]").append(window.errorListString).show();
                }
            }).render(documentsByStatus(statusId.pending));
        }
    };
    documentUploadEvent.documentUpload();

    function init() {
        $("[document-verification-loader]").show();
        getDocuments().then(function (data) {

            window.casinoGlobals.DocumentVerification = data;
            
            window.renderDocuments.renderAllDocuments();
            window.renderDocuments.renderApprovedDocuments();
            window.renderDocuments.renderRequestedDocuments();
            window.renderDocuments.renderRequiredDocuments();
            window.renderDocuments.renderPendingDocuments();
            window.renderDocuments.renderRejectedDocuments();

            $("[api-document-verification-container]").show();
            //$("[document-verification-loader]").hide();
            $("[upload-error-message]").hide();
            $("[api-upload-error-list]").html("").hide();
            window.DocumentUploadItemObjects = [];
        });
    }
    init();
}
window.casinoChatIsActive = false;
window.allowChatSend = false;


var chatwindow;
var brandCodeMapping = new Array;
brandCodeMapping.push({
    brandCode: "rv",
    mappedBrandCode: "rvg"
});
brandCodeMapping.push({
    brandCode: "7s",
    mappedBrandCode: "suc"
});
brandCodeMapping.push({
    brandCode: "pp",
    mappedBrandCode: "ppc"
});
brandCodeMapping.push({
    brandCode: "vp",
    mappedBrandCode: "vgp"
});
brandCodeMapping.push({
    brandCode: "pg",
    mappedBrandCode: "ppr"
});
brandCodeMapping.push({
    brandCode: "prv",
    mappedBrandCode: "rgf"
});
brandCodeMapping.push({
    brandCode: "fr",
    mappedBrandCode: "ftr"
});
brandCodeMapping.push({
    brandCode: "rf",
    mappedBrandCode: "red"
});
brandCodeMapping.push({
    brandCode: "aj",
    mappedBrandCode: "ajc"
});
brandCodeMapping.push({
    brandCode: "lv",
    mappedBrandCode: "clv"
});
brandCodeMapping.push({
    brandCode: "ep",
    mappedBrandCode: "eup"
});
brandCodeMapping.push({
    brandCode: "wj",
    mappedBrandCode: "wjc"
});
brandCodeMapping.push({
    brandCode: "as",
    mappedBrandCode: "asc"
});
brandCodeMapping.push({
    brandCode: "wt",
    mappedBrandCode: "wtg"
});

function _LiveChatEvents() {

    function showHideChat() {

        $("#genesys-chat-minimize, #genesys-messgage-poll").unbind("click");
        $("#genesys-chat-minimize, #genesys-messgage-poll").click(function () {
            if (chatwindow) {
                chatwindow.close();
            }
            var mappedBrandCode = "flg";
            for (var i = 0; i < brandCodeMapping.length; i++) {
                if (brandCodeMapping[i].brandCode.toLowerCase() === window.casinoGlobals.CasinoMetadata.RequestMetadata.brandCode.toLowerCase()) {
                    mappedBrandCode = brandCodeMapping[i].mappedBrandCode;
                    break;
                }
            }
            if (window.casinoGlobals.CasinoMetadata.RequestMetadata.languageCode.toLowerCase() == "en" && window.casinoGlobals.CasinoMetadata.RequestMetadata.CountryCode.toLowerCase() === "ca" && window.casinoGlobals.CasinoMetadata.RequestMetadata.brandCode.toLowerCase() !== "wt") {
                chatwindow =
                    window.open(
                        "http://smrouter.com/divert/sitemaxtraffic/" +
                        mappedBrandCode +
                        "/" +
                        window.casinoGlobals.CasinoMetadata.RequestMetadata.languageCode.toLowerCase() +
                        "-ca",
                        "",
                        "width=400,height=600");
            } else if (window.casinoGlobals.CasinoMetadata.RequestMetadata.languageCode.toLowerCase() == "en" && window.casinoGlobals.CasinoMetadata.RequestMetadata.CountryCode.toLowerCase() === "nz" && window.casinoGlobals.CasinoMetadata.RequestMetadata.brandCode.toLowerCase() !== "wt") {
                chatwindow =
                    window.open(
                        "http://smrouter.com/divert/sitemaxtraffic/" +
                        mappedBrandCode +
                        "/" +
                        window.casinoGlobals.CasinoMetadata.RequestMetadata.languageCode.toLowerCase() +
                        "-nz",
                        "",
                        "width=400,height=600");
            } else {
                chatwindow =
                    window.open(
                        "http://smrouter.com/divert/sitemaxtraffic/" +
                        mappedBrandCode +
                        "/" +
                        window.casinoGlobals.CasinoMetadata.RequestMetadata.languageCode.toLowerCase(),
                        "",
                        "width=400,height=600");
            }
        });
    }
    
    var chatHtmlContent = '<div id="genesys-messgage-poll"><div id="genesys-messgage-poll-count"></div></div>';
    function init() {
        $("body").append(chatHtmlContent);
        showHideChat();
    }
    init();
};
//console.log("--- PP ---");

function blurOnClick() {
    $("#page").addClass('blur');
    // $('body').addClass('no-scroll');
    if (!casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
        window.onscroll = function () {
            window.scrollTo(0, 0);
        };
    }
}

function mobileLoginPopup(element) {
    blurOnClick();
    $('.login').fadeIn('fast');
    $("html, body").animate({
        scrollTop: 0
    }, "fast");
    _PopulateStaleRegistrationForm();
    if (element) {
        if ($(element).hasClass("login-select")) {
            $("[name='LoginUsernameInput']").focus();
        } else {
            $("[name='FirstName']").focus();
        }
    } else {
        $("[name='LoginUsernameInput']").focus();
    }
    $("form").unbind("keyup keypress");
    $("form").on("keyup keypress", function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode === 13) {
            e.preventDefault();
            return false;
        }
    });
    $(".loginBox input").keyup(function (e) {
        e.preventDefault();
        var code = e.keyCode || e.which;
        if (code === 13) {
            $(".validation-error").hide();
            $(".validation-required-error").hide();
            $("[name='LoginSubmit']").trigger("click");
        }
    });
    $(".registerBox input").unbind("keyup");
    $(".registerBox input").keyup(function (e) {
        e.preventDefault();
        var code = e.keyCode || e.which;
        if (code === 13) {
            $(".error-message").hide();
            if ($(".countrySelect").length > 0 && $(".countrySelect").is(":visible")) {
                $(".countrySelect").hide();
            }
            if ($(".pcacountrylist").length > 0 && $(".pcacountrylist").is(":visible")) {
                $(".pcacountrylist").hide();
            }

            var element = $("input:focus");
            if (element.length > 0) {
                element.blur();
            }

            $("[name='PlayerRegisterStep1']").trigger("click");
        }
    });
}

function desktopLoginPopup(element) {
    blurOnClick();
    $('.login').fadeIn('fast');
    $("html, body").animate({
        scrollTop: 0
    }, "fast");
    _PopulateStaleRegistrationForm();
    if (element) {
        if ($(element).hasClass("login-select")) {
            $("[name='LoginUsernameInput']").focus();
        } else {
            $("[name='FirstName']").focus();
        }
    } else {
        $("[name='LoginUsernameInput']").focus();
    }
    $("form").on("keyup keypress", function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode === 13) {
            e.preventDefault();
            return false;
        }
    });
    $(".loginBox input").keyup(function (e) {
        e.preventDefault();
        var code = e.keyCode || e.which;
        if (code === 13) {
            $(".validation-error").hide();
            $(".validation-required-error").hide();
            $("[name='LoginSubmit']").trigger("click");
        }
    });
    $(".registerBox input").keyup(function (e) {
        e.preventDefault();
        var code = e.keyCode || e.which;
        if (code === 13) {
            $(".error-message").hide();
            if ($(".countrySelect").length > 0 && $(".countrySelect").is(":visible")) {
                $(".countrySelect").hide();
            }
            if ($(".pcacountrylist").length > 0 && $(".pcacountrylist").is(":visible")) {
                $(".pcacountrylist").hide();
            }

            var element = $("input:focus");
            if (element.length > 0) {
                element.blur();
            }

            $("[name='PlayerRegisterStep1']").trigger("click");
        }
    });
}

window.CustomEvents = {
    TermsPopupClickCallback: function () { },
    ResponsibleGamingPopupClickCallback: function () { },
    FavNotLoggedInClickEvent: function () {
        $('[login-select-click]').click();
    },
    ApiRegisterClickCallback: function () {
        if (casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
            $('[login-container]').hide();
        }

        $("[more-info-popup]").hide();
        $("#page").removeClass('blur');
        $('body').removeClass('no-scroll');
        blurOnClick();
    },
    ShowAccount: function () {
        //blurOnClick();
        //$('.myAccount').fadeIn('fast');
        //$("[api-account-info-popup-click]").click();
    },
    GamesCategoryChanged: function () { //Mobile accordion
        if (!$("#seo").hasClass("secondContent")) {
            $("#seo").on("click", "h2", function () {
                if ($(this).attr("class") !== "mobileSeoClicked") {
                    var isOpen = $(this).next("p");
                    $("#seo").find("h2").removeClass("MobileSeoActiveAccordion");
                    if (isOpen.is(":visible")) {
                        $("#seo").find("h2").next("p").slideUp();
                    } else {
                        $("#seo").find("h2").next("p").slideUp();
                        isOpen.slideDown();
                        $(this).toggleClass("MobileSeoActiveAccordion");
                    }
                }
            });
        } else {
            $("#seo").unbind("click");
        }
        if (casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
            $('.gameItemBox').unbind("click");
            $('.gameItemBox').click(function (e) {
                $('.gameItemHover').hide();
                $(this).find('.gameItemHover').show();
            });

            $('[login-select-click]').unbind("click");
            $('[login-select-click]').click(function (e) {
                e.preventDefault();
                mobileLoginPopup(this);
            });
        } else {

            $('[login-select-click]').unbind("click");
            $('[login-select-click]').click(function (e) {
                e.preventDefault();
                desktopLoginPopup(this);
            });
        }
    },
    MobileSeoContentClick: function () {


    },
    CloseMenu: function () {

    },
    LoginPopup: function () {
        if ($(".registerOverlay").is(":visible")) {
            $(".registerOverlay").addClass("hideOverlay");
        }
        $('body').css("overflow", "");
    },
    MobileAccountAnimation: function () {
        $("#contentWrapper").hide();
    },
    hideWelcomeBonus: function () {
        $("#casinoRegistrationComplete").addClass("hideOverlay");
    },
    GameClose: function () {
        $("#genesys-messgage-poll").show();
        window.chatVisable = false;
    },
    GameLaunch: function () {
        if (!window.casinoChatIsActive) {
            $("#genesys-messgage-poll, #genesys-chat-screen").hide();
        }
        $('[login-select-click]').unbind("click");
        $('[login-select-click]').click(function (e) {
            e.preventDefault();
            blurOnClick();
            $('.login').fadeIn('fast');

            $("html, body").animate({
                scrollTop: 0
            }, "fast");

            _PopulateStaleRegistrationForm();
        });
        $('.games-overlay .modal-content .inner h1').click(function () {
            $(this).parent().toggleClass('games-overlay-open');
        });
    },
    GameResize: function () {
        var resizeGame = function () {
            $("#gameWindow").parent().parent().removeAttr("style");

            var gameWindowParentWidth = $("#gameWindow").parent().width();
            var gameWindowParentHeight = $("#gameWindow").parent().height();

            var newGameWindowParentWidth = (16 * gameWindowParentHeight) / 9;
            var newGameWindowParentHeight = (9 * gameWindowParentWidth) / 16;

            if (gameWindowParentWidth <= gameWindowParentHeight || gameWindowParentHeight > newGameWindowParentHeight) {
                var gWnnw = (16 * newGameWindowParentHeight) / 9;
                $("#gameWindow").parent().parent().height(newGameWindowParentHeight);
                $("#gameWindow").parent().parent().width(gWnnw);
            } else {
                var gWnnh = (9 * newGameWindowParentWidth) / 16;
                $("#gameWindow").parent().parent().width(newGameWindowParentWidth);
                $("#gameWindow").parent().parent().height(gWnnh);
            }
        };
        resizeGame();
        $(window).on("resize", resizeGame);
    },
    RegistrationValidationScroll: function (requiredFields, validationFields, validationSection) {
        if (window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
            for (var k = 0; k < validationSection.length; k++) {
                if (!requiredFields[validationSection[k]] || !validationFields[validationSection[k]]) {
                    var elementCtx = $("[validation-required-error-id='" + validationSection[k] + "']");
                    if (elementCtx.length < 1)
                        elementCtx = $("[validation-error-id='" + validationSection[k] + "']");
                    if (elementCtx.length < 1)
                        elementCtx = $("[name='" + validationSection[k] + "']");

                    PageScroll().toPositionScrolling(elementCtx.parent().offset().top);

                    (function (elementCtxx) {
                        setTimeout(function () {
                            if (elementCtxx.parent().hasClass("inner")) {
                                elementCtxx.prev().find("input:not([type=hidden], [name=Country]), select").first().blur().focus();
                            } else {
                                elementCtxx.parent().find("input:not([type=hidden], [name=Country]), select").first().blur().focus();
                            }
                        }, 200);
                    })(elementCtx);

                    break;
                }
            }
        }
    },
    CategorySelectCallback: function (isChildCategory, categoryId) {

        if (!isChildCategory) {
            $("[api-game-category-click]").closest("#list-game-categories").removeClass("active");
            $(".game-category-click").closest("#list-game-categories").removeClass("active");
            $("#nav-category-" + categoryId).closest("#list-game-categories").addClass("active");
            $(".showSubNav").removeClass("showSubNav").addClass("hideSubNav");
            $("#nav-parent-" + categoryId).removeClass("hideSubNav").addClass("showSubNav");
        } else {
            $(".games-header-item").removeClass("active");
            if ($("#nav-category-" + categoryId).parent().prev().is("a")) {

                $("#nav-category-" + categoryId).parent().prev().parent().addClass("active");
            } else {
                $("#nav-category-" + categoryId).parent().prev().addClass("active");
            }

        }

        $('.games-header-container .games-header-container-inner .search-container').removeClass('open-search');
        $('.games-header-container .games-header-container-inner .search-container').removeClass('open-search-z');
    },
    MobileBankingClick: function () {
        $(".myAccount").hide();
    },
    MobileRegistrationFocusScroll: function (targetInput) {
        if (targetInput.attr("name") === "DobDay" || targetInput.attr("name") === "DobMonth" || targetInput.attr("name") === "DobYear" || targetInput.attr("name") === "Password" || targetInput.attr("name") === "LoginName") {
            //console.log("DOB");
            //console.log(targetInput.closest(".registerBox").position().top);
            PageScroll().toPositionScrolling($(".register .modal-content .reg2 .frame2").position().top - $(".modal-container .modal-content .header").height());
        } else {
            PageScroll().toPositionScrolling(targetInput.closest(".registerBox").position().top);
        }
    }
}
//Removes debris from url
if (String(document.location.href).indexOf("/#") > -1) {
    document.location.href = String(document.location.href).replace("/#", "");
}

//console.log("line 316");
function _CustomSiteScripts() {

    $(".myAccountBtn").on("click", function (e) {
        window.renderLoyaltyBalanceEvents.renderLoyalty();
    });


    if (ReadCookie("RegStep3") == 1 && window.postParams.JsonToken && window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {

        $("#contentWrapper").hide();
    }
    else if (ReadCookie("RegStep3") == 1 && window.postParams.JsonToken && !window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {

        blurOnClick();
    }


    /*Language popup*/
    $('[language-selector-click]').click(function (e) {
        e.preventDefault();
        blurOnClick();
        $('[language-selector-popup]').fadeIn('fast');
    });

    /*login popup*/
    $('[login-select-click]').click(function (e) {
        e.preventDefault();
        $("#casinoRegistrationModalStep1").addClass("hideOverlay");
        $("[more-info-popup]").hide();
        $("#page").removeClass('blur');
        $('body').removeClass('no-scroll');
        $("html, body").animate({
            scrollTop: 0
        }, "fast");
        blurOnClick();
        $('.login').fadeIn('fast');
        _PopulateStaleRegistrationForm();

        if (window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
            $("#contentWrapper").hide();
        }

    });

    $(".search-icon").click(function (e) {
        $("[api-game-search]").focus();
    });


    /*close button click*/
    $('.close-modal').click(function (e) {
        e.preventDefault();
        window.onscroll = function () { };

        $("#page").removeClass('blur');
        $('body').removeClass('no-scroll');
        $("html, body").attr("style", "");

        if ($(this).parent().parent().attr('id') === "casinoRegistrationModalStep1" || $(this).parent().parent().attr('id') === "casinoRegistrationModalStep2") {
            $("#casinoRegistrationModalStep1, #casinoRegistrationModalStep2").removeClass('showOverlay').addClass('hideOverlay');
        } else {
            $(this).parent().parent().fadeOut('fast');
        }

        //Terms popups
        if (!window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile && window.postParams.JsonToken) {
            $("#casinoRegistrationComplete").remove();
        }
        var iframeContainer = $("[api-registration-terms-click]");
        $("#ResponsibleGaminPopUp").removeClass('showOverlay').addClass('hideOverlay');
        $("html, body").attr("style", "");
        if (!iframeContainer.attr("src")) {
            $("#casinoRegistrationModalStep1, #casinoRegistrationModalStep2").removeClass('showOverlay').addClass('hideOverlay');
        } else {
            $("[general-terms-pop-up]").removeClass('showOverlay').addClass('hideOverlay');
            iframeContainer.attr("src", "");
        }

        if (casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
            $("#contentWrapper").show();
        }

        if (casinoGlobals.CasinoMetadata.RequestMetadata.isMobile && !$("#casinoRegistrationModalStep1").hasClass("hideOverlay") && $(this).parent().parent().parent().attr('id') === "GeneralTermsPopUp") {
            $("#contentWrapper").hide();
        }

    });

    var padding,
        subMenuHeight;

    $('.games-header-item').mouseenter(function () {

        if ($(window).width() > 1024) {
            padding = $('.games-header-item').index($(this)) * $('.games-header-item').width() - $('.games-header-item').width() / 5;
            subMenuHeight = '65px';
        }
        if ($(window).width() < 1024) {
            padding = $(window).width() / 100;
            subMenuHeight = '65px';
        }
        if ($(window).width() < 600) {
            subMenuHeight = '35px';
        }


        $(this).css('background-color', '#ffffff');

        $(this).find('.icon-container').addClass('hover');
        $(this).find('.title span').css('color', '#960f22');

        if ($(this).next('div').hasClass('games-header-sub-item')) {

            $(this).next('div').css('height', subMenuHeight);
            $(this).next('div').css('padding-left', padding);

        }

    });


    $(".games-header-item").each(function () {
        if ($(this).find(".games-header-sub-item").length !== 0) {
            $($(this).find(".games-header-sub-item")).insertAfter($(this));
        }

    })

    $('.games-header-item').mouseleave(function () {
        $(this).css('background-color', '#960f22');
        $(this).find('.icon-container').removeClass('hover');

        $(this).find('.title span').css('color', '#ffffff');


        if ($(this).next('div').hasClass('games-header-sub-item')) {
            $(this).next('div').css('height', '0');
        }

    });

    $('.games-header-sub-item').mouseenter(function () {
        $(this).css('height', subMenuHeight);
        $(this).prev('div').css('background-color', '#ffffff');
        $(this).prev('div').find('.icon-container').addClass('hover');
        $(this).prev('div').find('.title span').css('color', '#960f22');
    });

    $('.games-header-sub-item').mouseleave(function () {
        $(this).css('height', '0');
        $(this).prev('div').css('background-color', '#960f22');
        $(this).prev('div').find('.icon-container').removeClass('hover');
        $(this).prev('div').find('.title span').css('color', '#ffffff');
    });


    /*open search text*/
    $('.games-header-container .games-header-container-inner .search-container .search-icon').click(function () {

        $('.games-header-container .games-header-container-inner .search-container').toggleClass('open-search');


        $('.games-header-container .games-header-container-inner .search-container').toggleClass('open-search-z');


    });



    $(".logo18,.ref-94d7f8a8-4d23-49c3-8ff7-fa0f7fc5247a,.ref-2a38c1f3-97d5-4009-ba9a-6e350240ae1b,.ref-95ff32b0-52f7-4a39-b882-1499a86d1b15,.ref-ade46350-1af5-4dc6-9e23-f7105bd21c26,.ref-9c2b5249-7291-41d1-b145-7cce0ab816ee,.ref-fbe750ac-9aa3-49a3-a553-af1a12209dc5,.ref-d7981323-3034-4fa7-989b-551652675c3f,.ref-c26395f8-a838-4ef8-aac4-4f386d65e60f,.ref-c0131dcc-18d3-4ed7-92da-1a5f153c72ea,.ref-10558c12-aca4-4685-aeeb-a74db4511760").click(function (e) {
        e.preventDefault();
        var url = _ExternalAplicationLookup('5e152f88-f982-4053-8cd8-355468389cdb', true);
        var iframeContainer = $("[api-registration-terms-click]");
        iframeContainer.attr("src", url);
        $("html, body").animate({
            scrollTop: 0
        }, "fast");
        $("[general-terms-pop-up]").removeClass('hideOverlay');

    });

    window.casinoGlobals.seoContentSection = "#game-content-render";
    //console.log("line 499")
    //console.log("line 500")
    if (casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
        var currentUrlSelected;

        $("#seo h2").click(function (e) {
            e.preventDefault();
            $("#seo p").slideUp();
            $(this).next("p").slideToggle();
        });

        $("#MenuCaptionPanel, #mobilemenu").click(function (e) {
            e.preventDefault();
            if (mobileMenuClosed) {
                //active
                openMobileMenu($(this));
            } else {
                closeMobileMenu($(this));

            }
        });

        if (!window.postParams.JsonToken) {

            $(".CMSListMenuLink").click(function (e) {
                var currentSelected = $(this);
                e.preventDefault();
                //console.log(currentSelected.next(".dropdown-sub-menu-border").length)
                //console.log(currentSelected.attr("href"))
                //console.log(currentUrlSelected)
                if (currentSelected.next(".dropdown-sub-menu-border").length > 0) {

                    if (currentUrlSelected != currentSelected.attr("href")) {
                        currentUrlSelected = currentSelected.attr("href");
                        //console.log("SET: " + currentUrlSelected);
                    } else {
                        document.location.href = currentSelected.attr("href");
                    }
                }
            });
        }

        $('[api-register-click]').click(function (e) {
            $(".mainBlock").hide();

        });
    }

    /* Launch popups (TODO) */
    var qString = location.search.toLowerCase();
    var domainInfo = UriLookup();
    var currentDomain = domainInfo.protocol + "://" + domainInfo.domain + "/";
    
    $(document).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 675) {
            $('.sec').fadeIn(20);
            $('.sec').removeClass('hidden');
            $('.games').removeClass('game-margin');
            $('.games').addClass('game-margin-b');
            $('.totop').fadeIn();
            $('.totop').removeClass('hidden');
        } else {
            $('.sec').fadeOut('fast');
            $('.games').addClass('game-margin');
            $('.games').removeClass('game-margin-b');
            $('.totop').fadeOut();
            $('.totop').addClass('hidden');
        }
    });

    //DESKTOP GAME INTERACTIONS (DONE DONE)
    if (!casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {



        var body = $(' body ');

        $('#AccountBtn').click(function (e) {
            e.preventDefault();
            blurOnClick();
            $('.myAccount').fadeIn('fast');
        });

        if (body.hasClass('loggedout')) {
            //console.log('show logged out content');
            $('header .outer .inner .nav-container .selection-container .login-select').css('display', 'table');
            $('header .outer .inner .nav-container .selection-container .logout-select').css('display', 'none');
            $('header .outer .inner .nav-container .hamburger').css('display', 'block');
            $('header .outer .inner .nav-container .buttons-container').css('display', 'none');
        } else if (body.hasClass('loggedin')) {
            //console.log('show logged in content');
            $('header .outer .inner .nav-container .social-container').css('display', 'none');
            $('header .outer .inner .nav-container .selection-container .language-select').css('display', 'none');
            $('header .outer .inner .nav-container .selection-container .login-select').css('display', 'none');
            $('header .outer .inner .nav-container .selection-container .logout-select').css('display', 'table');
            $('header .outer .inner .nav-container .hamburger').css('display', 'none');
            $('header .outer .inner .nav-container .buttons-container').css('display', 'block');
        }

        $('.hamburger').click(function (e) {
            e.stopPropagation();
            //e.preventDefault();
            $('header .outer .navigation-container .nav-items-outer').fadeToggle('fast');
            $('header .outer .navigation-container .nav-items-outer .sub-nav').css('display', 'none');
            $('header .outer .navigation-container .nav-items-outer .sub-nav .sub-sub-nav').css('display', 'none');
        });


        $('.nav-item').click(function (e) {
            e.stopPropagation();
            //e.preventDefault();
            if ($(this).next('div').hasClass('sub-nav')) {
                $(this).next('div').fadeToggle('fast');
            }
        });

        $(document).click(function (e) {
            $('.nav-items-outer').css('display', 'none');
        });


        $('.nav-item').mouseenter(function () {
            //event.stopPropagation();
            $('.sub-nav').stop(true, true).css('display', 'none');
            $('.sub-sub-nav').stop(true, true).css('display', 'none');
            $(this).next('div').stop(true, true).css('display', 'block');
        });


        $('.sub-nav .sub-nav-item').mouseenter(function () {
            //e.stopPropagation();
            //e.preventDefault();
            $(this).parent().stop(true, true).css('display', 'block');
            $('.sub-sub-nav').stop(true, true).css('display', 'none');

            if ($(this).next('div').hasClass('sub-sub-nav')) {
                //e.stopPropagation();
                $(this).next('div').stop(true, true).fadeIn('fast');
            }
        });



        $('.sub-nav .sub-nav-item').mouseleave(function () {
            if ($(this).next('div').hasClass('sub-sub-nav')) {
                //console.log('in');
                $(this).next('div').stop(true, true).css('display', 'block');
            }
        });


        $('.sub-nav .sub-nav-item .sub-sub-nav-item').mouseenter(function () {
            $(this).parent().stop(true, true).css('display', 'block');
        });

    } else {

        $(".below-fold").insertAfter($(".landing-container"));


        /*open menu*/
        $('.open-mobi-menu').click(function () {
            if ($('.mobi-menu-open-container').height() > 0) {
                $('.mobi-menu-open-container').css('height', '0');
                $('html, body').removeClass('no-scroll');
            }

            if ($('.mobi-menu-open-container').height() < 1) {
                $('.mobi-menu-open-container').css('height', $(window).height() - $('.menu-items').height() + 2 + 'px');
                $('html, body').addClass('no-scroll');
            }
        });

        $('.mobi-menu-open-container > .parent').click(function () {
            $('.parent').removeClass('openSubNav').next('div').css('height', '0');
        });


        var item = $('.item');
        $('.open-item').click(function () {

            if ($(this).next().hasClass('sub-nav')) {

                var itemHeight = $(this).next('div').children(item).first().height();

                if ($(this).next('div').height() === 0) {
                    var items = ($(this).next('div').children(item).filter(":not(.sub-nav)").length),
                        subSubNavItems = $('.sub-sub-nav').children(item).filter(":not(.sub-nav)").length,
                        subSubNavHeight,
                        height;

                    subSubNavHeight = subSubNavItems * itemHeight;
                    height = items * itemHeight - subSubNavHeight;

                    $(this).parent().children().filter(".sub-nav").height(0);
                    $(this).parent().children().filter(".sub-nav").each(function () { $(this).prev('div').removeClass("openSubNav") });

                    $(this).addClass("openSubNav");
                    $(this).next('div').css('height', height);

                    if ($(this).parent().hasClass("sub-nav")) {
                        var snh = $(this).parent().children().filter(":not(.sub-nav)").length * itemHeight;
                        var snch = $(this).next('div').children().filter(":not(.sub-nav)").length * itemHeight;


                        if ($(this).parent().height() != (snh + snch))
                            $(this).parent().height((snh + snch));

                    }



                    if (($(this).parent().hasClass("sub-nav"))) {
                        var ce = $(this);
                        var subNavsubNavDiv = ce.next("div");
                        ce.parent().parent().animate({
                            scrollTop: subNavsubNavDiv.children().filter(":last-child").offset().top
                        }, 1000);
                    } else {

                        var subNavDiv = $(this);
                        $(this).parent().animate({
                            scrollTop: subNavDiv.offset().top
                        }, 1000);
                    }

                    //$(this).css('background-color', '#919294');
                } else {
                    $(this).removeClass("openSubNav");
                    $(this).next('div').css('height', '0');
                    //$(this).css('background-color', '#77797b');
                    $(this).css('border-bottom', '1px #4b4c4e solid');

                    if ($(this).parent().hasClass("sub-nav")) {
                        var snh = $(this).parent().height();
                        var snch = $(this).next('div').children().filter(":not(.sub-nav)").length * itemHeight;
                        if ($(this).parent().height() != (snh - snch))
                            $(this).parent().height((snh - snch));
                    }
                    $('.sub-sub-nav').css('height', '0');
                }
            }

            $('.language').click(function () {
                var selectedLanguage = $(this).find('p').text(),
                    currentLanguage = $('.current-language');

                currentLanguage.find('p').text(selectedLanguage);
                $(this).parent().css('height', '0');
                currentLanguage.css('background-color', '#77797b');
                currentLanguage.css('border-bottom', '1px #4b4c4e solid');
            });
        });

        /*sub sub nav click*/
        $('.sub-nav .item').click(function () {

            var itemHeight = $(window).width() > 600 ? 60 : 45;
            if ($(this).next().hasClass('sub-sub-nav')) {

                /*find the amount of menu items there are in sub sub nav*/
                var items = ($(this).next('div').find(item).length),
                    /*calculate the height of the sub sub nav*/
                    height,
                    /*find the parent of sub sub nav*/
                    parent = $(this).parent(),
                    parentHeight = $(this).parent().height();

                height = items * itemHeight;

                /*if the sub sub nav is closed*/
                if ($(this).next('div').height() === 0) {
                    /*apply height edits*/
                    $(this).next('div').css('height', height);
                    parent.css('height', parentHeight + height);

                }
                    /*if sub sub nav is open*/
                else {
                    $('.sub-sub-nav').css('height', '0');

                    parent.css('height', parentHeight - height);

                }
            }

        });
        $(window).resize(function () {
            if ($('.mobi-menu-open-container').height() > 0) {
                $('.mobi-menu-open-container').css('height', $(window).height() - $('.menu-items').height() + 2 + 'px');
                $('html, body').addClass('no-scroll');
                $(".openSubNav").removeClass("openSubNav");
                $('.sub-nav').css('height', '0');
            } else {
                $('html, body').removeClass('no-scroll');
            }
        });
    }
}

$(document).ready(function () {
    $('[more-info-click]').click(function (e) {
        e.preventDefault();
        blurOnClick();
        $('[more-info-popup]').fadeIn('fast');
        if (window.casinoGlobals.CasinoMetadata.RequestMetadata.isMobile) {
            $("#contentWrapper").hide();
        }
    });
})
