/* An error occurred during minification, see errors below - returning concatenated content unminified.
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(281,13-14): run-time error JS1010: Expected identifier: .
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(281,13-14): run-time error JS1195: Expected expression: .
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(496,13-14): run-time error JS1010: Expected identifier: .
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(496,13-14): run-time error JS1195: Expected expression: .
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(579,13-14): run-time error JS1010: Expected identifier: .
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(579,13-14): run-time error JS1195: Expected expression: .
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(1123,15-16): run-time error JS1010: Expected identifier: .
D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js(1123,15-16): run-time error JS1195: Expected expression: .
 */
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery-3.5.1.min.js
/*! jQuery v3.5.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}S.fn=S.prototype={jquery:f,constructor:S,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=S.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return S.each(this,e)},map:function(n){return this.pushStack(S.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(S.grep(this,function(e,t){return(t+1)%2}))},odd:function(){return this.pushStack(S.grep(this,function(e,t){return t%2}))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},S.extend=S.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||m(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(S.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||S.isPlainObject(n)?n:{},i=!1,a[t]=S.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},S.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=v.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t,n){b(e,{nonce:t&&t.nonce},n)},each:function(e,t){var n,r=0;if(p(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},makeArray:function(e,t){var n=t||[];return null!=e&&(p(Object(e))?S.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(p(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g(a)},guid:1,support:y}),"function"==typeof Symbol&&(S.fn[Symbol.iterator]=t[Symbol.iterator]),S.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var d=function(n){var e,d,b,o,i,h,f,g,w,u,l,T,C,a,E,v,s,c,y,S="sizzle"+1*new Date,p=n.document,k=0,r=0,m=ue(),x=ue(),A=ue(),N=ue(),D=function(e,t){return e===t&&(l=!0),0},j={}.hasOwnProperty,t=[],q=t.pop,L=t.push,H=t.push,O=t.slice,P=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",I="(?:\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",W="\\["+M+"*("+I+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+I+"))|)"+M+"*\\]",F=":("+I+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+W+")*)|.*)\\)|)",B=new RegExp(M+"+","g"),$=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=new RegExp("^"+M+"*,"+M+"*"),z=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}: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},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="<a id='"+S+"'></a><select id='"+S+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?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},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0<se(t,C,null,[e]).length},se.contains=function(e,t){return(e.ownerDocument||e)!=C&&T(e),y(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!=C&&T(e);var n=b.attrHandle[t.toLowerCase()],r=n&&j.call(b.attrHandle,t.toLowerCase())?n(e,t,!E):void 0;return void 0!==r?r:d.attributes||!E?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},se.escape=function(e){return(e+"").replace(re,ie)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],r=0,i=0;if(l=!d.detectDuplicates,u=!d.sortStable&&e.slice(0),e.sort(D),l){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return u=null,e},o=se.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 while(t=e[r++])n+=o(t);return n},(b=se.selectors={cacheLength:50,createPseudo:le,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===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]||se.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]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(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){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace(B," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(h,e,t,g,v){var y="nth"!==h.slice(0,3),m="last"!==h.slice(-4),x="of-type"===e;return 1===g&&0===v?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u,l=y!==m?"nextSibling":"previousSibling",c=e.parentNode,f=x&&e.nodeName.toLowerCase(),p=!n&&!x,d=!1;if(c){if(y){while(l){a=e;while(a=a[l])if(x?a.nodeName.toLowerCase()===f:1===a.nodeType)return!1;u=l="only"===h&&!u&&"nextSibling"}return!0}if(u=[m?c.firstChild:c.lastChild],m&&p){d=(s=(r=(i=(o=(a=c)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1])&&r[2],a=s&&c.childNodes[s];while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if(1===a.nodeType&&++d&&a===e){i[h]=[k,s,d];break}}else if(p&&(d=s=(r=(i=(o=(a=e)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1]),!1===d)while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if((x?a.nodeName.toLowerCase()===f:1===a.nodeType)&&++d&&(p&&((i=(o=a[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]=[k,d]),a===e))break;return(d-=v)===g||d%g==0&&0<=d/g}}},PSEUDO:function(e,o){var t,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return a[S]?a(o):1<a.length?(t=[e,e,"",o],b.setFilters.hasOwnProperty(e.toLowerCase())?le(function(e,t){var n,r=a(e,o),i=r.length;while(i--)e[n=P(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:le(function(e){var r=[],i=[],s=f(e.replace($,"$1"));return s[S]?le(function(e,t,n,r){var i,o=s(e,null,r,[]),a=e.length;while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:le(function(t){return function(e){return 0<se(t,e).length}}),contains:le(function(t){return t=t.replace(te,ne),function(e){return-1<(e.textContent||o(e)).indexOf(t)}}),lang:le(function(n){return V.test(n||"")||se.error("unsupported lang: "+n),n=n.replace(te,ne).toLowerCase(),function(e){var t;do{if(t=E?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===a},focus:function(e){return e===C.activeElement&&(!C.hasFocus||C.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:ge(!1),disabled:ge(!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,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!b.pseudos.empty(e)},header:function(e){return J.test(e.nodeName)},input:function(e){return Q.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"))||"text"===t.toLowerCase())},first:ve(function(){return[0]}),last:ve(function(e,t){return[t-1]}),eq:ve(function(e,t,n){return[n<0?n+t:n]}),even:ve(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:ve(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:ve(function(e,t,n){for(var r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:ve(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=b.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[e]=de(e);for(e in{submit:!0,reset:!0})b.pseudos[e]=he(e);function me(){}function xe(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function be(s,e,t){var u=e.dir,l=e.next,c=l||u,f=t&&"parentNode"===c,p=r++;return e.first?function(e,t,n){while(e=e[u])if(1===e.nodeType||f)return s(e,t,n);return!1}:function(e,t,n){var r,i,o,a=[k,p];if(n){while(e=e[u])if((1===e.nodeType||f)&&s(e,t,n))return!0}else while(e=e[u])if(1===e.nodeType||f)if(i=(o=e[S]||(e[S]={}))[e.uniqueID]||(o[e.uniqueID]={}),l&&l===e.nodeName.toLowerCase())e=e[u]||e;else{if((r=i[c])&&r[0]===k&&r[1]===p)return a[2]=r[2];if((i[c]=a)[2]=s(e,t,n))return!0}return!1}}function we(i){return 1<i.length?function(e,t,n){var r=i.length;while(r--)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Te(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Ce(d,h,g,v,y,e){return v&&!v[S]&&(v=Ce(v)),y&&!y[S]&&(y=Ce(y,e)),le(function(e,t,n,r){var i,o,a,s=[],u=[],l=t.length,c=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)se(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),f=!d||!e&&h?c:Te(c,s,d,n,r),p=g?y||(e?d:l||v)?[]:t:f;if(g&&g(f,p,n,r),v){i=Te(p,u),v(i,[],n,r),o=i.length;while(o--)(a=i[o])&&(p[u[o]]=!(f[u[o]]=a))}if(e){if(y||d){if(y){i=[],o=p.length;while(o--)(a=p[o])&&i.push(f[o]=a);y(null,p=[],i,r)}o=p.length;while(o--)(a=p[o])&&-1<(i=y?P(e,a):s[o])&&(e[i]=!(t[i]=a))}}else p=Te(p===t?p.splice(l,p.length):p),y?y(null,t,p,r):H.apply(t,p)})}function Ee(e){for(var i,t,n,r=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,u=be(function(e){return e===i},a,!0),l=be(function(e){return-1<P(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!==w)||((i=t).nodeType?u(e,t,n):l(e,t,n));return i=null,r}];s<r;s++)if(t=b.relative[e[s].type])c=[be(we(c),t)];else{if((t=b.filter[e[s].type].apply(null,e[s].matches))[S]){for(n=++s;n<r;n++)if(b.relative[e[n].type])break;return Ce(1<s&&we(c),1<s&&xe(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace($,"$1"),t,s<n&&Ee(e.slice(s,n)),n<r&&Ee(e=e.slice(n)),n<r&&xe(e))}c.push(t)}return we(c)}return me.prototype=b.filters=b.pseudos,b.setFilters=new me,h=se.tokenize=function(e,t){var n,r,i,o,a,s,u,l=x[e+" "];if(l)return t?0:l.slice(0);a=e,s=[],u=b.preFilter;while(a){for(o in n&&!(r=_.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=z.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace($," ")}),a=a.slice(n.length)),b.filter)!(r=G[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?se.error(e):x(e,s).slice(0)},f=se.compile=function(e,t){var n,v,y,m,x,r,i=[],o=[],a=A[e+" "];if(!a){t||(t=h(e)),n=t.length;while(n--)(a=Ee(t[n]))[S]?i.push(a):o.push(a);(a=A(e,(v=o,m=0<(y=i).length,x=0<v.length,r=function(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],p=w,d=e||x&&b.find.TAG("*",i),h=k+=null==p?1:Math.random()||.1,g=d.length;for(i&&(w=t==C||t||i);l!==g&&null!=(o=d[l]);l++){if(x&&o){a=0,t||o.ownerDocument==C||(T(o),n=!E);while(s=v[a++])if(s(o,t||C,n)){r.push(o);break}i&&(k=h)}m&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,m&&l!==u){a=0;while(s=y[a++])s(c,f,t,n);if(e){if(0<u)while(l--)c[l]||f[l]||(f[l]=q.call(r));f=Te(f)}H.apply(r,f),i&&!e&&0<f.length&&1<u+y.length&&se.uniqueSort(r)}return i&&(k=h,w=p),c},m?le(r):r))).selector=e}return a},g=se.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&h(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&E&&b.relative[o[1].type]){if(!(t=(b.find.ID(a.matches[0].replace(te,ne),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}i=G.needsContext.test(e)?0:o.length;while(i--){if(a=o[i],b.relative[s=a.type])break;if((u=b.find[s])&&(r=u(a.matches[0].replace(te,ne),ee.test(o[0].type)&&ye(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&xe(o)))return H.apply(n,r),n;break}}}return(l||f(e,c))(r,t,!E,n,!t||ee.test(e)&&ye(t.parentNode)||t),n},d.sortStable=S.split("").sort(D).join("")===S,d.detectDuplicates=!!l,T(),d.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(C.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),d.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||fe(R,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),se}(C);S.find=d,S.expr=d.selectors,S.expr[":"]=S.expr.pseudos,S.uniqueSort=S.unique=d.uniqueSort,S.text=d.getText,S.isXMLDoc=d.isXML,S.contains=d.contains,S.escapeSelector=d.escape;var h=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&S(e).is(n))break;r.push(e)}return r},T=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},k=S.expr.match.needsContext;function A(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var N=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function D(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1<i.call(n,e)!==r}):S.filter(n,e,r)}S.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?S.find.matchesSelector(r,e)?[r]:[]:S.find.matches(e,S.grep(t,function(e){return 1===e.nodeType}))},S.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(S(e).filter(function(){for(t=0;t<r;t++)if(S.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)S.find(e,i[t],n);return 1<r?S.uniqueSort(n):n},filter:function(e){return this.pushStack(D(this,e||[],!1))},not:function(e){return this.pushStack(D(this,e||[],!0))},is:function(e){return!!D(this,"string"==typeof e&&k.test(e)?S(e):e||[],!1).length}});var j,q=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,j=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(S.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&S(e);if(!k.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&S.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?S.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?i.call(S(e),this[0]):i.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(S.uniqueSort(S.merge(this.get(),S(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),S.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return h(e,"parentNode")},parentsUntil:function(e,t,n){return h(e,"parentNode",n)},next:function(e){return O(e,"nextSibling")},prev:function(e){return O(e,"previousSibling")},nextAll:function(e){return h(e,"nextSibling")},prevAll:function(e){return h(e,"previousSibling")},nextUntil:function(e,t,n){return h(e,"nextSibling",n)},prevUntil:function(e,t,n){return h(e,"previousSibling",n)},siblings:function(e){return T((e.parentNode||{}).firstChild,e)},children:function(e){return T(e.firstChild)},contents:function(e){return null!=e.contentDocument&&r(e.contentDocument)?e.contentDocument:(A(e,"template")&&(e=e.content||e),S.merge([],e.childNodes))}},function(r,i){S.fn[r]=function(e,t){var n=S.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=S.filter(t,n)),1<this.length&&(H[r]||S.uniqueSort(n),L.test(r)&&n.reverse()),this.pushStack(n)}});var P=/[^\x20\t\r\n\f]+/g;function R(e){return e}function M(e){throw e}function I(e,t,n,r){var i;try{e&&m(i=e.promise)?i.call(e).done(t).fail(n):e&&m(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}S.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},S.each(e.match(P)||[],function(e,t){n[t]=!0}),n):S.extend({},r);var i,t,o,a,s=[],u=[],l=-1,c=function(){for(a=a||r.once,o=i=!0;u.length;l=-1){t=u.shift();while(++l<s.length)!1===s[l].apply(t[0],t[1])&&r.stopOnFalse&&(l=s.length,t=!1)}r.memory||(t=!1),i=!1,a&&(s=t?[]:"")},f={add:function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){S.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this},remove:function(){return S.each(arguments,function(e,t){var n;while(-1<(n=S.inArray(t,s,n)))s.splice(n,1),n<=l&&l--}),this},has:function(e){return e?-1<S.inArray(e,s):0<s.length},empty:function(){return s&&(s=[]),this},disable:function(){return a=u=[],s=t="",this},disabled:function(){return!s},lock:function(){return a=u=[],t||i||(s=t=""),this},locked:function(){return!!a},fireWith:function(e,t){return a||(t=[e,(t=t||[]).slice?t.slice():t],u.push(t),i||c()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},S.extend({Deferred:function(e){var o=[["notify","progress",S.Callbacks("memory"),S.Callbacks("memory"),2],["resolve","done",S.Callbacks("once memory"),S.Callbacks("once memory"),0,"resolved"],["reject","fail",S.Callbacks("once memory"),S.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},"catch":function(e){return a.then(null,e)},pipe:function(){var i=arguments;return S.Deferred(function(r){S.each(o,function(e,t){var n=m(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&m(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,m(t)?s?t.call(e,l(u,o,R,s),l(u,o,M,s)):(u++,t.call(e,l(u,o,R,s),l(u,o,M,s),l(u,o,R,o.notifyWith))):(a!==R&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){S.Deferred.exceptionHook&&S.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==M&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(S.Deferred.getStackHook&&(t.stackTrace=S.Deferred.getStackHook()),C.setTimeout(t))}}return S.Deferred(function(e){o[0][3].add(l(0,e,m(r)?r:R,e.notifyWith)),o[1][3].add(l(0,e,m(t)?t:R)),o[2][3].add(l(0,e,m(n)?n:M))}).promise()},promise:function(e){return null!=e?S.extend(e,a):a}},s={};return S.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){var n=arguments.length,t=n,r=Array(t),i=s.call(arguments),o=S.Deferred(),a=function(t){return function(e){r[t]=this,i[t]=1<arguments.length?s.call(arguments):e,--n||o.resolveWith(r,i)}};if(n<=1&&(I(e,o.done(a(t)).resolve,o.reject,!n),"pending"===o.state()||m(i[t]&&i[t].then)))return o.then();while(t--)I(i[t],a(t),o.reject);return o.promise()}});var W=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;S.Deferred.exceptionHook=function(e,t){C.console&&C.console.warn&&e&&W.test(e.name)&&C.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},S.readyException=function(e){C.setTimeout(function(){throw e})};var F=S.Deferred();function B(){E.removeEventListener("DOMContentLoaded",B),C.removeEventListener("load",B),S.ready()}S.fn.ready=function(e){return F.then(e)["catch"](function(e){S.readyException(e)}),this},S.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--S.readyWait:S.isReady)||(S.isReady=!0)!==e&&0<--S.readyWait||F.resolveWith(E,[S])}}),S.ready.then=F.then,"complete"===E.readyState||"loading"!==E.readyState&&!E.documentElement.doScroll?C.setTimeout(S.ready):(E.addEventListener("DOMContentLoaded",B),C.addEventListener("load",B));var $=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===w(n))for(s in i=!0,n)$(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,m(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(S(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},_=/^-ms-/,z=/-([a-z])/g;function U(e,t){return t.toUpperCase()}function X(e){return e.replace(_,"ms-").replace(z,U)}var V=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function G(){this.expando=S.expando+G.uid++}G.uid=1,G.prototype={cache:function(e){var t=e[this.expando];return t||(t={},V(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[X(t)]=n;else for(r in t)i[X(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][X(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(X):(t=X(t))in r?[t]:t.match(P)||[]).length;while(n--)delete r[t[n]]}(void 0===t||S.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!S.isEmptyObject(t)}};var Y=new G,Q=new G,J=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,K=/[A-Z]/g;function Z(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(K,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+""?+i:J.test(i)?JSON.parse(i):i)}catch(e){}Q.set(e,t,n)}else n=void 0;return n}S.extend({hasData:function(e){return Q.hasData(e)||Y.hasData(e)},data:function(e,t,n){return Q.access(e,t,n)},removeData:function(e,t){Q.remove(e,t)},_data:function(e,t,n){return Y.access(e,t,n)},_removeData:function(e,t){Y.remove(e,t)}}),S.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0===n){if(this.length&&(i=Q.get(o),1===o.nodeType&&!Y.get(o,"hasDataAttrs"))){t=a.length;while(t--)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=X(r.slice(5)),Z(o,r,i[r]));Y.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof n?this.each(function(){Q.set(this,n)}):$(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=Q.get(o,n))?t:void 0!==(t=Z(o,n))?t:void 0;this.each(function(){Q.set(this,n,e)})},null,e,1<arguments.length,null,!0)},removeData:function(e){return this.each(function(){Q.remove(this,e)})}}),S.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Y.get(e,t),n&&(!r||Array.isArray(n)?r=Y.access(e,t,S.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=S.queue(e,t),r=n.length,i=n.shift(),o=S._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){S.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Y.get(e,n)||Y.access(e,n,{empty:S.Callbacks("once memory").add(function(){Y.remove(e,[t+"queue",n])})})}}),S.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?S.queue(this[0],t):void 0===n?this:this.each(function(){var e=S.queue(this,t,n);S._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&S.dequeue(this,t)})},dequeue:function(e){return this.each(function(){S.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=S.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=Y.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var ee=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,te=new RegExp("^(?:([+-])=|)("+ee+")([a-z%]*)$","i"),ne=["Top","Right","Bottom","Left"],re=E.documentElement,ie=function(e){return S.contains(e.ownerDocument,e)},oe={composed:!0};re.getRootNode&&(ie=function(e){return S.contains(e.ownerDocument,e)||e.getRootNode(oe)===e.ownerDocument});var ae=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&ie(e)&&"none"===S.css(e,"display")};function se(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return S.css(e,t,"")},u=s(),l=n&&n[3]||(S.cssNumber[t]?"":"px"),c=e.nodeType&&(S.cssNumber[t]||"px"!==l&&+u)&&te.exec(S.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)S.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,S.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var ue={};function le(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=Y.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&ae(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ue[s])||(o=a.body.appendChild(a.createElement(s)),u=S.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ue[s]=u)))):"none"!==n&&(l[c]="none",Y.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}S.fn.extend({show:function(){return le(this,!0)},hide:function(){return le(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?S(this).show():S(this).hide()})}});var ce,fe,pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="<textarea>x</textarea>",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="<option></option>",y.option=!!ce.lastChild;var ge={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n<r;n++)Y.set(e[n],"globalEval",!t||Y.get(t[n],"globalEval"))}ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td,y.option||(ge.optgroup=ge.option=[1,"<select multiple='multiple'>","</select>"]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===w(o))S.merge(p,o.nodeType?[o]:o);else if(me.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+S.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;S.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&-1<S.inArray(o,r))i&&i.push(o);else if(l=ie(o),a=ve(f.appendChild(o),"script"),l&&ye(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}var be=/^key/,we=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Te=/^([^.]*)(?:\.(.+)|)/;function Ce(){return!0}function Ee(){return!1}function Se(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function ke(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)ke(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Ee;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return S().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=S.guid++)),e.each(function(){S.event.add(this,t,i,r,n)})}function Ae(e,i,o){o?(Y.set(e,i,!1),S.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Y.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(S.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Y.set(this,i,r),t=o(this,i),this[i](),r!==(n=Y.get(this,i))||t?Y.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Y.set(this,i,{value:S.event.trigger(S.extend(r[0],S.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Y.get(e,i)&&S.event.add(e,i,Ce)}S.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Y.get(t);if(V(t)){n.handler&&(n=(o=n).handler,i=o.selector),i&&S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++),(u=v.events)||(u=v.events=Object.create(null)),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof S&&S.event.triggered!==e.type?S.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(P)||[""]).length;while(l--)d=g=(s=Te.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=S.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=S.event.special[d]||{},c=S.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&S.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),S.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Y.hasData(e)&&Y.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(P)||[""]).length;while(l--)if(d=g=(s=Te.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=S.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||S.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)S.event.remove(e,d+t[l],n,r,!0);S.isEmptyObject(u)&&Y.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=new Array(arguments.length),u=S.event.fix(e),l=(Y.get(this,"events")||Object.create(null))[u.type]||[],c=S.event.special[u.type]||{};for(s[0]=u,t=1;t<arguments.length;t++)s[t]=arguments[t];if(u.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,u)){a=S.event.handlers.call(this,u,l),t=0;while((i=a[t++])&&!u.isPropagationStopped()){u.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!u.isImmediatePropagationStopped())u.rnamespace&&!1!==o.namespace&&!u.rnamespace.test(o.namespace)||(u.handleObj=o,u.data=o.data,void 0!==(r=((S.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s))&&!1===(u.result=r)&&(u.preventDefault(),u.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,u),u.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&1<=e.button))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?-1<S(i,this).index(l):S.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(t,e){Object.defineProperty(S.Event.prototype,t,{enumerable:!0,configurable:!0,get:m(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[S.expando]?e:new S.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Ae(t,"click",Ce),!1},trigger:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Ae(t,"click"),!0},_default:function(e){var t=e.target;return pe.test(t.type)&&t.click&&A(t,"input")&&Y.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},S.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},S.Event=function(e,t){if(!(this instanceof S.Event))return new S.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?Ce:Ee,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&S.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[S.expando]=!0},S.Event.prototype={constructor:S.Event,isDefaultPrevented:Ee,isPropagationStopped:Ee,isImmediatePropagationStopped:Ee,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=Ce,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=Ce,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=Ce,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},S.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(e){var t=e.button;return null==e.which&&be.test(e.type)?null!=e.charCode?e.charCode:e.keyCode:!e.which&&void 0!==t&&we.test(e.type)?1&t?1:2&t?3:4&t?2:0:e.which}},S.event.addProp),S.each({focus:"focusin",blur:"focusout"},function(e,t){S.event.special[e]={setup:function(){return Ae(this,e,Se),!1},trigger:function(){return Ae(this,e),!0},delegateType:t}}),S.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){S.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||S.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),S.fn.extend({on:function(e,t,n,r){return ke(this,e,t,n,r)},one:function(e,t,n,r){return ke(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,S(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=Ee),this.each(function(){S.event.remove(this,e,n,t)})}});var Ne=/<script|<style|<link/i,De=/checked\s*(?:[^=]|=\s*.checked.)/i,je=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function qe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function Le(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n<r;n++)S.event.add(t,i,s[i][n]);Q.hasData(e)&&(o=Q.access(e),a=S.extend({},o),Q.set(t,a))}}function Pe(n,r,i,o){r=g(r);var e,t,a,s,u,l,c=0,f=n.length,p=f-1,d=r[0],h=m(d);if(h||1<f&&"string"==typeof d&&!y.checkClone&&De.test(d))return n.each(function(e){var t=n.eq(e);h&&(r[0]=d.call(this,e,t.html())),Pe(t,r,i,o)});if(f&&(t=(e=xe(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=S.map(ve(e,"script"),Le)).length;c<f;c++)u=e,c!==p&&(u=S.clone(u,!0,!0),s&&S.merge(a,ve(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,S.map(a,He),c=0;c<s;c++)u=a[c],he.test(u.type||"")&&!Y.access(u,"globalEval")&&S.contains(l,u)&&(u.src&&"module"!==(u.type||"").toLowerCase()?S._evalUrl&&!u.noModule&&S._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")},l):b(u.textContent.replace(je,""),u,l))}return n}function Re(e,t,n){for(var r,i=t?S.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||S.cleanData(ve(r)),r.parentNode&&(n&&ie(r)&&ye(ve(r,"script")),r.parentNode.removeChild(r));return e}S.extend({htmlPrefilter:function(e){return e},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=ie(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||S.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r<i;r++)s=o[r],u=a[r],void 0,"input"===(l=u.nodeName.toLowerCase())&&pe.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||ve(e),a=a||ve(c),r=0,i=o.length;r<i;r++)Oe(o[r],a[r]);else Oe(e,c);return 0<(a=ve(c,"script")).length&&ye(a,!f&&ve(e,"script")),c},cleanData:function(e){for(var t,n,r,i=S.event.special,o=0;void 0!==(n=e[o]);o++)if(V(n)){if(t=n[Y.expando]){if(t.events)for(r in t.events)i[r]?S.event.remove(n,r):S.removeEvent(n,r,t.handle);n[Y.expando]=void 0}n[Q.expando]&&(n[Q.expando]=void 0)}}}),S.fn.extend({detach:function(e){return Re(this,e,!0)},remove:function(e){return Re(this,e)},text:function(e){return $(this,function(e){return void 0===e?S.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Pe(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||qe(this,e).appendChild(e)})},prepend:function(){return Pe(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=qe(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Pe(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Pe(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(S.cleanData(ve(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return S.clone(this,e,t)})},html:function(e){return $(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ne.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=S.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(S.cleanData(ve(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return Pe(this,arguments,function(e){var t=this.parentNode;S.inArray(this,n)<0&&(S.cleanData(ve(this)),t&&t.replaceChild(e,this))},n)}}),S.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){S.fn[e]=function(e){for(var t,n=[],r=S(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),S(r[o])[a](t),u.apply(n,t.get());return this.pushStack(n)}});var Me=new RegExp("^("+ee+")(?!px)[a-z%]+$","i"),Ie=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=C),t.getComputedStyle(e)},We=function(e,t,n){var r,i,o={};for(i in t)o[i]=e.style[i],e.style[i]=t[i];for(i in r=n.call(e),t)e.style[i]=o[i];return r},Fe=new RegExp(ne.join("|"),"i");function Be(e,t,n){var r,i,o,a,s=e.style;return(n=n||Ie(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||ie(e)||(a=S.style(e,t)),!y.pixelBoxStyles()&&Me.test(a)&&Fe.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function $e(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}!function(){function e(){if(l){u.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",l.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",re.appendChild(u).appendChild(l);var e=C.getComputedStyle(l);n="1%"!==e.top,s=12===t(e.marginLeft),l.style.right="60%",o=36===t(e.right),r=36===t(e.width),l.style.position="absolute",i=12===t(l.offsetWidth/3),re.removeChild(u),l=null}}function t(e){return Math.round(parseFloat(e))}var n,r,i,o,a,s,u=E.createElement("div"),l=E.createElement("div");l.style&&(l.style.backgroundClip="content-box",l.cloneNode(!0).style.backgroundClip="",y.clearCloneStyle="content-box"===l.style.backgroundClip,S.extend(y,{boxSizingReliable:function(){return e(),r},pixelBoxStyles:function(){return e(),o},pixelPosition:function(){return e(),n},reliableMarginLeft:function(){return e(),s},scrollboxSize:function(){return e(),i},reliableTrDimensions:function(){var e,t,n,r;return null==a&&(e=E.createElement("table"),t=E.createElement("tr"),n=E.createElement("div"),e.style.cssText="position:absolute;left:-11111px",t.style.height="1px",n.style.height="9px",re.appendChild(e).appendChild(t).appendChild(n),r=C.getComputedStyle(t),a=3<parseInt(r.height),re.removeChild(e)),a}}))}();var _e=["Webkit","Moz","ms"],ze=E.createElement("div").style,Ue={};function Xe(e){var t=S.cssProps[e]||Ue[e];return t||(e in ze?e:Ue[e]=function(e){var t=e[0].toUpperCase()+e.slice(1),n=_e.length;while(n--)if((e=_e[n]+t)in ze)return e}(e)||e)}var Ve=/^(none|table(?!-c[ea]).+)/,Ge=/^--/,Ye={position:"absolute",visibility:"hidden",display:"block"},Qe={letterSpacing:"0",fontWeight:"400"};function Je(e,t,n){var r=te.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function Ke(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=S.css(e,n+ne[a],!0,i)),r?("content"===n&&(u-=S.css(e,"padding"+ne[a],!0,i)),"margin"!==n&&(u-=S.css(e,"border"+ne[a]+"Width",!0,i))):(u+=S.css(e,"padding"+ne[a],!0,i),"padding"!==n?u+=S.css(e,"border"+ne[a]+"Width",!0,i):s+=S.css(e,"border"+ne[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u}function Ze(e,t,n){var r=Ie(e),i=(!y.boxSizingReliable()||n)&&"border-box"===S.css(e,"boxSizing",!1,r),o=i,a=Be(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if(Me.test(a)){if(!n)return a;a="auto"}return(!y.boxSizingReliable()&&i||!y.reliableTrDimensions()&&A(e,"tr")||"auto"===a||!parseFloat(a)&&"inline"===S.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===S.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+Ke(e,t,n||(i?"border":"content"),o,r,a)+"px"}function et(e,t,n,r,i){return new et.prototype.init(e,t,n,r,i)}S.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Be(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=X(t),u=Ge.test(t),l=e.style;if(u||(t=Xe(s)),a=S.cssHooks[t]||S.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"===(o=typeof n)&&(i=te.exec(n))&&i[1]&&(n=se(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(S.cssNumber[s]?"":"px")),y.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=X(t);return Ge.test(t)||(t=Xe(s)),(a=S.cssHooks[t]||S.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Be(e,t,r)),"normal"===i&&t in Qe&&(i=Qe[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),S.each(["height","width"],function(e,u){S.cssHooks[u]={get:function(e,t,n){if(t)return!Ve.test(S.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?Ze(e,u,n):We(e,Ye,function(){return Ze(e,u,n)})},set:function(e,t,n){var r,i=Ie(e),o=!y.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===S.css(e,"boxSizing",!1,i),s=n?Ke(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-Ke(e,u,"border",!1,i)-.5)),s&&(r=te.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=S.css(e,u)),Je(0,t,s)}}}),S.cssHooks.marginLeft=$e(y.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Be(e,"marginLeft"))||e.getBoundingClientRect().left-We(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),S.each({margin:"",padding:"",border:"Width"},function(i,o){S.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+ne[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(S.cssHooks[i+o].set=Je)}),S.fn.extend({css:function(e,t){return $(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Ie(e),i=t.length;a<i;a++)o[t[a]]=S.css(e,t[a],!1,r);return o}return void 0!==n?S.style(e,t,n):S.css(e,t)},e,t,1<arguments.length)}}),((S.Tween=et).prototype={constructor:et,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||S.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(S.cssNumber[n]?"":"px")},cur:function(){var e=et.propHooks[this.prop];return e&&e.get?e.get(this):et.propHooks._default.get(this)},run:function(e){var t,n=et.propHooks[this.prop];return this.options.duration?this.pos=t=S.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=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):et.propHooks._default.set(this),this}}).init.prototype=et.prototype,(et.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=S.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){S.fx.step[e.prop]?S.fx.step[e.prop](e):1!==e.elem.nodeType||!S.cssHooks[e.prop]&&null==e.elem.style[Xe(e.prop)]?e.elem[e.prop]=e.now:S.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=et.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},S.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},S.fx=et.prototype.init,S.fx.step={};var tt,nt,rt,it,ot=/^(?:toggle|show|hide)$/,at=/queueHooks$/;function st(){nt&&(!1===E.hidden&&C.requestAnimationFrame?C.requestAnimationFrame(st):C.setTimeout(st,S.fx.interval),S.fx.tick())}function ut(){return C.setTimeout(function(){tt=void 0}),tt=Date.now()}function lt(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=ne[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function ct(e,t,n){for(var r,i=(ft.tweeners[t]||[]).concat(ft.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function ft(o,e,t){var n,a,r=0,i=ft.prefilters.length,s=S.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=tt||ut(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:S.extend({},e),opts:S.extend(!0,{specialEasing:{},easing:S.easing._default},t),originalProperties:e,originalOptions:t,startTime:tt||ut(),duration:t.duration,tweens:[],createTween:function(e,t){var n=S.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=X(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=S.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=ft.prefilters[r].call(l,o,c,l.opts))return m(n.stop)&&(S._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return S.map(c,ct,l),m(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),S.fx.timer(S.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}S.Animation=S.extend(ft,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return se(n.elem,e,te.exec(t),n),n}]},tweener:function(e,t){m(e)?(t=e,e=["*"]):e=e.match(P);for(var n,r=0,i=e.length;r<i;r++)n=e[r],ft.tweeners[n]=ft.tweeners[n]||[],ft.tweeners[n].unshift(t)},prefilters:[function(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ae(e),v=Y.get(e,"fxshow");for(r in n.queue||(null==(a=S._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,S.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],ot.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!v||void 0===v[r])continue;g=!0}d[r]=v&&v[r]||S.style(e,r)}if((u=!S.isEmptyObject(t))||!S.isEmptyObject(d))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=v&&v.display)&&(l=Y.get(e,"display")),"none"===(c=S.css(e,"display"))&&(l?c=l:(le([e],!0),l=e.style.display||l,c=S.css(e,"display"),le([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===S.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1,d)u||(v?"hidden"in v&&(g=v.hidden):v=Y.access(e,"fxshow",{display:l}),o&&(v.hidden=!g),g&&le([e],!0),p.done(function(){for(r in g||le([e]),Y.remove(e,"fxshow"),d)S.style(e,r,d[r])})),u=ct(g?v[r]:0,r,p),r in v||(v[r]=u.start,g&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?ft.prefilters.unshift(e):ft.prefilters.push(e)}}),S.speed=function(e,t,n){var r=e&&"object"==typeof e?S.extend({},e):{complete:n||!n&&t||m(e)&&e,duration:e,easing:n&&t||t&&!m(t)&&t};return S.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in S.fx.speeds?r.duration=S.fx.speeds[r.duration]:r.duration=S.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){m(r.old)&&r.old.call(this),r.queue&&S.dequeue(this,r.queue)},r},S.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){var i=S.isEmptyObject(t),o=S.speed(e,n,r),a=function(){var e=ft(this,S.extend({},t),o);(i||Y.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(i,e,o){var a=function(e){var t=e.stop;delete e.stop,t(o)};return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=S.timers,r=Y.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&at.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||S.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=Y.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=S.timers,o=n?n.length:0;for(t.finish=!0,S.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),S.each(["toggle","show","hide"],function(e,r){var i=S.fn[r];S.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(lt(r,!0),e,t,n)}}),S.each({slideDown:lt("show"),slideUp:lt("hide"),slideToggle:lt("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){S.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),S.timers=[],S.fx.tick=function(){var e,t=0,n=S.timers;for(tt=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||S.fx.stop(),tt=void 0},S.fx.timer=function(e){S.timers.push(e),S.fx.start()},S.fx.interval=13,S.fx.start=function(){nt||(nt=!0,st())},S.fx.stop=function(){nt=null},S.fx.speeds={slow:600,fast:200,_default:400},S.fn.delay=function(r,e){return r=S.fx&&S.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=C.setTimeout(e,r);t.stop=function(){C.clearTimeout(n)}})},rt=E.createElement("input"),it=E.createElement("select").appendChild(E.createElement("option")),rt.type="checkbox",y.checkOn=""!==rt.value,y.optSelected=it.selected,(rt=E.createElement("input")).value="t",rt.type="radio",y.radioValue="t"===rt.value;var pt,dt=S.expr.attrHandle;S.fn.extend({attr:function(e,t){return $(this,S.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){S.removeAttr(this,e)})}}),S.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?S.prop(e,t,n):(1===o&&S.isXMLDoc(e)||(i=S.attrHooks[t.toLowerCase()]||(S.expr.match.bool.test(t)?pt:void 0)),void 0!==n?null===n?void S.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=S.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!y.radioValue&&"radio"===t&&A(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(P);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),pt={set:function(e,t,n){return!1===t?S.removeAttr(e,n):e.setAttribute(n,n),n}},S.each(S.expr.match.bool.source.match(/\w+/g),function(e,t){var a=dt[t]||S.find.attr;dt[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=dt[o],dt[o]=r,r=null!=a(e,t,n)?o:null,dt[o]=i),r}});var ht=/^(?:input|select|textarea|button)$/i,gt=/^(?:a|area)$/i;function vt(e){return(e.match(P)||[]).join(" ")}function yt(e){return e.getAttribute&&e.getAttribute("class")||""}function mt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(P)||[]}S.fn.extend({prop:function(e,t){return $(this,S.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[S.propFix[e]||e]})}}),S.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&S.isXMLDoc(e)||(t=S.propFix[t]||t,i=S.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=S.find.attr(e,"tabindex");return t?parseInt(t,10):ht.test(e.nodeName)||gt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),y.optSelected||(S.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),S.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){S.propFix[this.toLowerCase()]=this}),S.fn.extend({addClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){S(this).addClass(t.call(this,e,yt(this)))});if((e=mt(t)).length)while(n=this[u++])if(i=yt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=e[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){S(this).removeClass(t.call(this,e,yt(this)))});if(!arguments.length)return this.attr("class","");if((e=mt(t)).length)while(n=this[u++])if(i=yt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=e[a++])while(-1<r.indexOf(" "+o+" "))r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(i,t){var o=typeof i,a="string"===o||Array.isArray(i);return"boolean"==typeof t&&a?t?this.addClass(i):this.removeClass(i):m(i)?this.each(function(e){S(this).toggleClass(i.call(this,e,yt(this),t),t)}):this.each(function(){var e,t,n,r;if(a){t=0,n=S(this),r=mt(i);while(e=r[t++])n.hasClass(e)?n.removeClass(e):n.addClass(e)}else void 0!==i&&"boolean"!==o||((e=yt(this))&&Y.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",e||!1===i?"":Y.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&-1<(" "+vt(yt(n))+" ").indexOf(t))return!0;return!1}});var xt=/\r/g;S.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=m(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,S(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=S.map(t,function(e){return null==e?"":e+""})),(r=S.valHooks[this.type]||S.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=S.valHooks[t.type]||S.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(xt,""):null==e?"":e:void 0}}),S.extend({valHooks:{option:{get:function(e){var t=S.find.attr(e,"value");return null!=t?t:vt(S.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!A(n.parentNode,"optgroup"))){if(t=S(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=S.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=-1<S.inArray(S.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),S.each(["radio","checkbox"],function(){S.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<S.inArray(S(e).val(),t)}},y.checkOn||(S.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),y.focusin="onfocusin"in C;var bt=/^(?:focusinfocus|focusoutblur)$/,wt=function(e){e.stopPropagation()};S.extend(S.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,p=[n||E],d=v.call(e,"type")?e.type:e,h=v.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||E,3!==n.nodeType&&8!==n.nodeType&&!bt.test(d+S.event.triggered)&&(-1<d.indexOf(".")&&(d=(h=d.split(".")).shift(),h.sort()),u=d.indexOf(":")<0&&"on"+d,(e=e[S.expando]?e:new S.Event(d,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:S.makeArray(t,[e]),c=S.event.special[d]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!x(n)){for(s=c.delegateType||d,bt.test(s+d)||(o=o.parentNode);o;o=o.parentNode)p.push(o),a=o;a===(n.ownerDocument||E)&&p.push(a.defaultView||a.parentWindow||C)}i=0;while((o=p[i++])&&!e.isPropagationStopped())f=o,e.type=1<i?s:c.bindType||d,(l=(Y.get(o,"events")||Object.create(null))[e.type]&&Y.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&V(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=d,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(p.pop(),t)||!V(n)||u&&m(n[d])&&!x(n)&&((a=n[u])&&(n[u]=null),S.event.triggered=d,e.isPropagationStopped()&&f.addEventListener(d,wt),n[d](),e.isPropagationStopped()&&f.removeEventListener(d,wt),S.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=S.extend(new S.Event,n,{type:e,isSimulated:!0});S.event.trigger(r,null,t)}}),S.fn.extend({trigger:function(e,t){return this.each(function(){S.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return S.event.trigger(e,t,n,!0)}}),y.focusin||S.each({focus:"focusin",blur:"focusout"},function(n,r){var i=function(e){S.event.simulate(r,e.target,S.event.fix(e))};S.event.special[r]={setup:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r);t||e.addEventListener(n,i,!0),Y.access(e,r,(t||0)+1)},teardown:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r)-1;t?Y.access(e,r,t):(e.removeEventListener(n,i,!0),Y.remove(e,r))}}});var Tt=C.location,Ct={guid:Date.now()},Et=/\?/;S.parseXML=function(e){var t;if(!e||"string"!=typeof e)return null;try{t=(new C.DOMParser).parseFromString(e,"text/xml")}catch(e){t=void 0}return t&&!t.getElementsByTagName("parsererror").length||S.error("Invalid XML: "+e),t};var St=/\[\]$/,kt=/\r?\n/g,At=/^(?:submit|button|image|reset|file)$/i,Nt=/^(?:input|select|textarea|keygen)/i;function Dt(n,e,r,i){var t;if(Array.isArray(e))S.each(e,function(e,t){r||St.test(n)?i(n,t):Dt(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i)});else if(r||"object"!==w(e))i(n,e);else for(t in e)Dt(n+"["+t+"]",e[t],r,i)}S.param=function(e,t){var n,r=[],i=function(e,t){var n=m(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!S.isPlainObject(e))S.each(e,function(){i(this.name,this.value)});else for(n in e)Dt(n,e[n],t,i);return r.join("&")},S.fn.extend({serialize:function(){return S.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=S.prop(this,"elements");return e?S.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!S(this).is(":disabled")&&Nt.test(this.nodeName)&&!At.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=S(this).val();return null==n?null:Array.isArray(n)?S.map(n,function(e){return{name:t.name,value:e.replace(kt,"\r\n")}}):{name:t.name,value:n.replace(kt,"\r\n")}}).get()}});var jt=/%20/g,qt=/#.*$/,Lt=/([?&])_=[^&]*/,Ht=/^(.*?):[ \t]*([^\r\n]*)$/gm,Ot=/^(?:GET|HEAD)$/,Pt=/^\/\//,Rt={},Mt={},It="*/".concat("*"),Wt=E.createElement("a");function Ft(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(P)||[];if(m(t))while(n=i[r++])"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function Bt(t,i,o,a){var s={},u=t===Mt;function l(e){var r;return s[e]=!0,S.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function $t(e,t){var n,r,i=S.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&S.extend(!0,e,r),e}Wt.href=Tt.href,S.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Tt.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Tt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":It,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":S.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?$t($t(e,S.ajaxSettings),t):$t(S.ajaxSettings,e)},ajaxPrefilter:Ft(Rt),ajaxTransport:Ft(Mt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,p,n,d,r,h,g,i,o,v=S.ajaxSetup({},t),y=v.context||v,m=v.context&&(y.nodeType||y.jquery)?S(y):S.event,x=S.Deferred(),b=S.Callbacks("once memory"),w=v.statusCode||{},a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n){n={};while(t=Ht.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?p:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(v.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(x.promise(T),v.url=((e||v.url||Tt.href)+"").replace(Pt,Tt.protocol+"//"),v.type=t.method||t.type||v.method||v.type,v.dataTypes=(v.dataType||"*").toLowerCase().match(P)||[""],null==v.crossDomain){r=E.createElement("a");try{r.href=v.url,r.href=r.href,v.crossDomain=Wt.protocol+"//"+Wt.host!=r.protocol+"//"+r.host}catch(e){v.crossDomain=!0}}if(v.data&&v.processData&&"string"!=typeof v.data&&(v.data=S.param(v.data,v.traditional)),Bt(Rt,v,t,T),h)return T;for(i in(g=S.event&&v.global)&&0==S.active++&&S.event.trigger("ajaxStart"),v.type=v.type.toUpperCase(),v.hasContent=!Ot.test(v.type),f=v.url.replace(qt,""),v.hasContent?v.data&&v.processData&&0===(v.contentType||"").indexOf("application/x-www-form-urlencoded")&&(v.data=v.data.replace(jt,"+")):(o=v.url.slice(f.length),v.data&&(v.processData||"string"==typeof v.data)&&(f+=(Et.test(f)?"&":"?")+v.data,delete v.data),!1===v.cache&&(f=f.replace(Lt,"$1"),o=(Et.test(f)?"&":"?")+"_="+Ct.guid+++o),v.url=f+o),v.ifModified&&(S.lastModified[f]&&T.setRequestHeader("If-Modified-Since",S.lastModified[f]),S.etag[f]&&T.setRequestHeader("If-None-Match",S.etag[f])),(v.data&&v.hasContent&&!1!==v.contentType||t.contentType)&&T.setRequestHeader("Content-Type",v.contentType),T.setRequestHeader("Accept",v.dataTypes[0]&&v.accepts[v.dataTypes[0]]?v.accepts[v.dataTypes[0]]+("*"!==v.dataTypes[0]?", "+It+"; q=0.01":""):v.accepts["*"]),v.headers)T.setRequestHeader(i,v.headers[i]);if(v.beforeSend&&(!1===v.beforeSend.call(y,T,v)||h))return T.abort();if(u="abort",b.add(v.complete),T.done(v.success),T.fail(v.error),c=Bt(Mt,v,t,T)){if(T.readyState=1,g&&m.trigger("ajaxSend",[T,v]),h)return T;v.async&&0<v.timeout&&(d=C.setTimeout(function(){T.abort("timeout")},v.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,d&&C.clearTimeout(d),c=void 0,p=r||"",T.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}(v,T,n)),!i&&-1<S.inArray("script",v.dataTypes)&&(v.converters["text script"]=function(){}),s=function(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}(v,s,T,i),i?(v.ifModified&&((u=T.getResponseHeader("Last-Modified"))&&(S.lastModified[f]=u),(u=T.getResponseHeader("etag"))&&(S.etag[f]=u)),204===e||"HEAD"===v.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),T.status=e,T.statusText=(t||l)+"",i?x.resolveWith(y,[o,l,T]):x.rejectWith(y,[T,l,a]),T.statusCode(w),w=void 0,g&&m.trigger(i?"ajaxSuccess":"ajaxError",[T,v,i?o:a]),b.fireWith(y,[T,l]),g&&(m.trigger("ajaxComplete",[T,v]),--S.active||S.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return S.get(e,t,n,"json")},getScript:function(e,t){return S.get(e,void 0,t,"script")}}),S.each(["get","post"],function(e,i){S[i]=function(e,t,n,r){return m(t)&&(r=r||n,n=t,t=void 0),S.ajax(S.extend({url:e,type:i,dataType:r,data:t,success:n},S.isPlainObject(e)&&e))}}),S.ajaxPrefilter(function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||"")}),S._evalUrl=function(e,t,n){return S.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){S.globalEval(e,t,n)}})},S.fn.extend({wrapAll:function(e){var t;return this[0]&&(m(e)&&(e=e.call(this[0])),t=S(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(n){return m(n)?this.each(function(e){S(this).wrapInner(n.call(this,e))}):this.each(function(){var e=S(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=m(t);return this.each(function(e){S(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){S(this).replaceWith(this.childNodes)}),this}}),S.expr.pseudos.hidden=function(e){return!S.expr.pseudos.visible(e)},S.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},S.ajaxSettings.xhr=function(){try{return new C.XMLHttpRequest}catch(e){}};var _t={0:200,1223:204},zt=S.ajaxSettings.xhr();y.cors=!!zt&&"withCredentials"in zt,y.ajax=zt=!!zt,S.ajaxTransport(function(i){var o,a;if(y.cors||zt&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(_t[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&C.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),S.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),S.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return S.globalEval(e),e}}}),S.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),S.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=S("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=vt(e.slice(s)),e=e.slice(0,s)),m(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&S.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?S("<div>").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=$e(y.pixelPosition,function(e,t){if(t)return t=Be(e,n),Me.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({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)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}});var Gt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;S.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),m(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||S.guid++,i},S.holdReady=function(e){e?S.readyWait++:S.ready(!0)},S.isArray=Array.isArray,S.parseJSON=JSON.parse,S.nodeName=A,S.isFunction=m,S.isWindow=x,S.camelCase=X,S.type=w,S.now=Date.now,S.isNumeric=function(e){var t=S.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},S.trim=function(e){return null==e?"":(e+"").replace(Gt,"")},"function"==typeof define&&define.amd&&define("jquery",[],function(){return S});var Yt=C.jQuery,Qt=C.$;return S.noConflict=function(e){return C.$===S&&(C.$=Qt),e&&C.jQuery===S&&(C.jQuery=Yt),S},"undefined"==typeof e&&(C.jQuery=C.$=S),S});
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery-ui-1.10.4.custom.js
/*! jQuery UI - v1.10.4 - 2019-11-07
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.autocomplete.js, jquery.ui.menu.js, jquery.ui.slider.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

//JQuery v3.0 Compatible

(function ($, undefined) {

    var uuid = 0,
        runiqueId = /^ui-id-\d+$/;

    // $.ui might exist from components with no dependencies, e.g., $.ui.position
    $.ui = $.ui || {};

    $.extend($.ui, {
        version: "1.10.4",

        keyCode: {
            BACKSPACE: 8,
            COMMA: 188,
            DELETE: 46,
            DOWN: 40,
            END: 35,
            ENTER: 13,
            ESCAPE: 27,
            HOME: 36,
            LEFT: 37,
            NUMPAD_ADD: 107,
            NUMPAD_DECIMAL: 110,
            NUMPAD_DIVIDE: 111,
            NUMPAD_ENTER: 108,
            NUMPAD_MULTIPLY: 106,
            NUMPAD_SUBTRACT: 109,
            PAGE_DOWN: 34,
            PAGE_UP: 33,
            PERIOD: 190,
            RIGHT: 39,
            SPACE: 32,
            TAB: 9,
            UP: 38
        }
    });

    // plugins
    $.fn.extend({
        focus: (function (orig) {
            return function (delay, fn) {
                return typeof delay === "number" ?
                    this.each(function () {
                        var elem = this;
                        setTimeout(function () {
                            $(elem).trigger("focus");
                            if (fn) {
                                fn.call(elem);
                            }
                        }, delay);
                    }) :
                    orig.apply(this, arguments);
            };
        })($.fn.focus),

        scrollParent: function () {
            var scrollParent;
            if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
                scrollParent = this.parents().filter(function () {
                    return (/(relative|absolute|fixed)/).test($.css(this, "position")) && (/(auto|scroll)/).test($.css(this, "overflow") + $.css(this, "overflow-y") + $.css(this, "overflow-x"));
                }).eq(0);
            } else {
                scrollParent = this.parents().filter(function () {
                    return (/(auto|scroll)/).test($.css(this, "overflow") + $.css(this, "overflow-y") + $.css(this, "overflow-x"));
                }).eq(0);
            }

            return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
        },

        zIndex: function (zIndex) {
            if (zIndex !== undefined) {
                return this.css("zIndex", zIndex);
            }

            if (this.length) {
                var elem = $(this[0]), position, value;
                while (elem.length && elem[0] !== document) {
                    // Ignore z-index if position is set to a value where z-index is ignored by the browser
                    // This makes behavior of this function consistent across browsers
                    // WebKit always returns auto if the element is positioned
                    position = elem.css("position");
                    if (position === "absolute" || position === "relative" || position === "fixed") {
                        // IE returns 0 when zIndex is not specified
                        // other browsers return a string
                        // we ignore the case of nested elements with an explicit value of 0
                        // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
                        value = parseInt(elem.css("zIndex"), 10);
                        if (!isNaN(value) && value !== 0) {
                            return value;
                        }
                    }
                    elem = elem.parent();
                }
            }

            return 0;
        },

        uniqueId: function () {
            return this.each(function () {
                if (!this.id) {
                    this.id = "ui-id-" + (++uuid);
                }
            });
        },

        removeUniqueId: function () {
            return this.each(function () {
                if (runiqueId.test(this.id)) {
                    $(this).removeAttr("id");
                }
            });
        }
    });

    // selectors
    function focusable(element, isTabIndexNotNaN) {
        var map, mapName, img,
            nodeName = element.nodeName.toLowerCase();
        if ("area" === nodeName) {
            map = element.parentNode;
            mapName = map.name;
            if (!element.href || !mapName || map.nodeName.toLowerCase() !== "map") {
                return false;
            }
            img = $("img[usemap=\"#" + mapName + "\"]")[0];
            return !!img && visible(img);
        }
        return (/input|select|textarea|button|object/.test(nodeName) ?
            !element.disabled :
            "a" === nodeName ?
                element.href || isTabIndexNotNaN :
                isTabIndexNotNaN) &&
            // the element and all of its ancestors must be visible
            visible(element);
    }

    function visible(element) {
        return $.expr.pseudos.visible(element) &&
            !$(element).parents().addBack().filter(function () {
                return $.css(this, "visibility") === "hidden";
            }).length;
    }

    $.extend($.expr.pseudos, {
        data: $.expr.createPseudo ?
            $.expr.createPseudo(function (dataName) {
                return function (elem) {
                    return !!$.data(elem, dataName);
                };
            }) :
            // support: jQuery <1.8
            function (elem, i, match) {
                return !!$.data(elem, match[3]);
            },

        focusable: function (element) {
            return focusable(element, !isNaN($.attr(element, "tabindex")));
        },

        tabbable: function (element) {
            var tabIndex = $.attr(element, "tabindex"),
                isTabIndexNaN = isNaN(tabIndex);
            return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN);
        }
    });

    // support: jQuery <1.8
    if (!$("<a>").outerWidth(1).jquery) {
        $.each(["Width", "Height"], function (i, name) {
            var side = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"],
                type = name.toLowerCase(),
                orig = {
                    innerWidth: $.fn.innerWidth,
                    innerHeight: $.fn.innerHeight,
                    outerWidth: $.fn.outerWidth,
                    outerHeight: $.fn.outerHeight
                };

            function reduce(elem, size, border, margin) {
                $.each(side, function () {
                    size -= parseFloat($.css(elem, "padding" + this)) || 0;
                    if (border) {
                        size -= parseFloat($.css(elem, "border" + this + "Width")) || 0;
                    }
                    if (margin) {
                        size -= parseFloat($.css(elem, "margin" + this)) || 0;
                    }
                });
                return size;
            }

            $.fn["inner" + name] = function (size) {
                if (size === undefined) {
                    return orig["inner" + name].call(this);
                }

                return this.each(function () {
                    $(this).css(type, reduce(this, size) + "px");
                });
            };

            $.fn["outer" + name] = function (size, margin) {
                if (typeof size !== "number") {
                    return orig["outer" + name].call(this, size);
                }

                return this.each(function () {
                    $(this).css(type, reduce(this, size, true, margin) + "px");
                });
            };
        });
    }

    // support: jQuery <1.8
    if (!$.fn.addBack) {
        $.fn.addBack = function (selector) {
            return this.add(selector == null ?
                this.prevObject : this.prevObject.filter(selector)
            );
        };
    }

    // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
    if ($("<a>").data("a-b", "a").removeData("a-b").data("a-b")) {
        $.fn.removeData = (function (removeData) {
            return function (key) {
                if (arguments.length) {
                    return removeData.call(this, $.camelCase(key));
                } else {
                    return removeData.call(this);
                }
            };
        })($.fn.removeData);
    }





    // deprecated
    $.ui.ie = !!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());

    $.support.selectstart = "onselectstart" in document.createElement("div");
    $.fn.extend({
        disableSelection: function () {
            return this.on(($.support.selectstart ? "selectstart" : "mousedown") +
                ".ui-disableSelection", function (event) {
                    event.preventDefault();
                });
        },

        enableSelection: function () {
            return this.off(".ui-disableSelection");
        }
    });

    $.extend($.ui, {
        // $.ui.plugin is deprecated. Use $.widget() extensions instead.
        plugin: {
            add: function (module, option, set) {
                var i,
                    proto = $.ui[module].prototype;
                for (i in set) {
                    proto.plugins[i] = proto.plugins[i] || [];
                    proto.plugins[i].push([option, set[i]]);
                }
            },
            call: function (instance, name, args) {
                var i,
                    set = instance.plugins[name];
                if (!set || !instance.element[0].parentNode || instance.element[0].parentNode.nodeType === 11) {
                    return;
                }

                for (i = 0; i < set.length; i++) {
                    if (instance.options[set[i][0]]) {
                        set[i][1].apply(instance.element, args);
                    }
                }
            }
        },

        // only used by resizable
        hasScroll: function (el, a) {

            //If overflow is hidden, the element might have extra content, but the user wants to hide it
            if ($(el).css("overflow") === "hidden") {
                return false;
            }

            var scroll = (a && a === "left") ? "scrollLeft" : "scrollTop",
                has = false;

            if (el[scroll] > 0) {
                return true;
            }

            // TODO: determine which cases actually cause this to happen
            // if the element doesn't have the scroll set, see if it's possible to
            // set the scroll
            el[scroll] = 1;
            has = (el[scroll] > 0);
            el[scroll] = 0;
            return has;
        }
    });

})(jQuery);
(function ($, undefined) {

    var uuid = 0,
        slice = Array.prototype.slice,
        _cleanData = $.cleanData;
    $.cleanData = function (elems) {
        for (var i = 0, elem; (elem = elems[i]) != null; i++) {
            try {
                $(elem).triggerHandler("remove");
                // http://bugs.jquery.com/ticket/8235
            } catch (e) { }
        }
        _cleanData(elems);
    };

    $.widget = function (name, base, prototype) {
        var fullName, existingConstructor, constructor, basePrototype,
            // proxiedPrototype allows the provided prototype to remain unmodified
            // so that it can be used as a mixin for multiple widgets (#8876)
            proxiedPrototype = {},
            namespace = name.split(".")[0];

        name = name.split(".")[1];
        fullName = namespace + "-" + name;

        if (!prototype) {
            prototype = base;
            base = $.Widget;
        }

        // create selector for plugin
        $.expr.pseudos[fullName.toLowerCase()] = function (elem) {
            return !!$.data(elem, fullName);
        };

        $[namespace] = $[namespace] || {};
        existingConstructor = $[namespace][name];
        constructor = $[namespace][name] = function (options, element) {
            // allow instantiation without "new" keyword
            if (!this._createWidget) {
                return new constructor(options, element);
            }

            // allow instantiation without initializing for simple inheritance
            // must use "new" keyword (the code above always passes args)
            if (arguments.length) {
                this._createWidget(options, element);
            }
        };
        // extend with the existing constructor to carry over any static properties
        $.extend(constructor, existingConstructor, {
            version: prototype.version,
            // copy the object used to create the prototype in case we need to
            // redefine the widget later
            _proto: $.extend({}, prototype),
            // track widgets that inherit from this widget in case this widget is
            // redefined after a widget inherits from it
            _childConstructors: []
        });

        basePrototype = new base();
        // we need to make the options hash a property directly on the new instance
        // otherwise we'll modify the options hash on the prototype that we're
        // inheriting from
        basePrototype.options = $.widget.extend({}, basePrototype.options);
        $.each(prototype, function (prop, value) {
            if (typeof value !== "function") {
                proxiedPrototype[prop] = value;
                return;
            }
            proxiedPrototype[prop] = (function () {
                var _super = function () {
                    return base.prototype[prop].apply(this, arguments);
                },
                    _superApply = function (args) {
                        return base.prototype[prop].apply(this, args);
                    };
                return function () {
                    var __super = this._super,
                        __superApply = this._superApply,
                        returnValue;

                    this._super = _super;
                    this._superApply = _superApply;

                    returnValue = value.apply(this, arguments);

                    this._super = __super;
                    this._superApply = __superApply;

                    return returnValue;
                };
            })();
        });
        constructor.prototype = $.widget.extend(basePrototype, {
            // TODO: remove support for widgetEventPrefix
            // always use the name + a colon as the prefix, e.g., draggable:start
            // don't prefix for widgets that aren't DOM-based
            widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
        }, proxiedPrototype, {
                constructor: constructor,
                namespace: namespace,
                widgetName: name,
                widgetFullName: fullName
            });

        // If this widget is being redefined then we need to find all widgets that
        // are inheriting from it and redefine all of them so that they inherit from
        // the new version of this widget. We're essentially trying to replace one
        // level in the prototype chain.
        if (existingConstructor) {
            $.each(existingConstructor._childConstructors, function (i, child) {
                var childPrototype = child.prototype;

                // redefine the child widget using the same prototype that was
                // originally used, but inherit from the new version of the base
                $.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto);
            });
            // remove the list of existing child constructors from the old constructor
            // so the old child constructors can be garbage collected
            delete existingConstructor._childConstructors;
        } else {
            base._childConstructors.push(constructor);
        }

        $.widget.bridge(name, constructor);
    };

    $.widget.extend = function (target) {
        var input = slice.call(arguments, 1),
            inputIndex = 0,
            inputLength = input.length,
            key,
            value;
        for (; inputIndex < inputLength; inputIndex++) {
            for (key in input[inputIndex]) {
                value = input[inputIndex][key];
                if (input[inputIndex].hasOwnProperty(key) && value !== undefined) {
                    // Clone objects
                    if ($.isPlainObject(value)) {
                        target[key] = $.isPlainObject(target[key]) ?
                            $.widget.extend({}, target[key], value) :
                            // Don't extend strings, arrays, etc. with objects
                            $.widget.extend({}, value);
                        // Copy everything else by reference
                    } else {
                        target[key] = value;
                    }
                }
            }
        }
        return target;
    };

    $.widget.bridge = function (name, object) {
        var fullName = object.prototype.widgetFullName || name;
        $.fn[name] = function (options) {
            var isMethodCall = typeof options === "string",
                args = slice.call(arguments, 1),
                returnValue = this;

            // allow multiple hashes to be passed on init
            options = !isMethodCall && args.length ?
                $.widget.extend.apply(null, [options].concat(args)) :
                options;

            if (isMethodCall) {
                this.each(function () {
                    var methodValue,
                        instance = $.data(this, fullName);
                    if (!instance) {
                        return $.error("cannot call methods on " + name + " prior to initialization; " +
                            "attempted to call method '" + options + "'");
                    }
                    if (typeof instance[options] !== "function" || options.charAt(0) === "_") {
                        return $.error("no such method '" + options + "' for " + name + " widget instance");
                    }
                    methodValue = instance[options].apply(instance, args);
                    if (methodValue !== instance && methodValue !== undefined) {
                        returnValue = methodValue && methodValue.jquery ?
                            returnValue.pushStack(methodValue.get()) :
                            methodValue;
                        return false;
                    }
                });
            } else {
                this.each(function () {
                    var instance = $.data(this, fullName);
                    if (instance) {
                        instance.option(options || {})._init();
                    } else {
                        $.data(this, fullName, new object(options, this));
                    }
                });
            }

            return returnValue;
        };
    };

    $.Widget = function ( /* options, element */) { };
    $.Widget._childConstructors = [];

    $.Widget.prototype = {
        widgetName: "widget",
        widgetEventPrefix: "",
        defaultElement: "<div>",
        options: {
            disabled: false,

            // callbacks
            create: null
        },
        _createWidget: function (options, element) {
            element = $(element || this.defaultElement || this)[0];
            this.element = $(element);
            this.uuid = uuid++;
            this.eventNamespace = "." + this.widgetName + this.uuid;
            this.options = $.widget.extend({},
                this.options,
                this._getCreateOptions(),
                options);

            this.bindings = $();
            this.hoverable = $();
            this.focusable = $();

            if (element !== this) {
                $.data(element, this.widgetFullName, this);
                this._on(true, this.element, {
                    remove: function (event) {
                        if (event.target === element) {
                            this.destroy();
                        }
                    }
                });
                this.document = $(element.style ?
                    // element within the document
                    element.ownerDocument :
                    // element is window or document
                    element.document || element);
                this.window = $(this.document[0].defaultView || this.document[0].parentWindow);
            }

            this._create();
            this._trigger("create", null, this._getCreateEventData());
            this._init();
        },
        _getCreateOptions: $.noop,
        _getCreateEventData: $.noop,
        _create: $.noop,
        _init: $.noop,

        destroy: function () {
            this._destroy();
            // we can probably remove the unbind calls in 2.0
            // all event bindings should go through this._on()
            this.element
                .off(this.eventNamespace)
                // 1.9 BC for #7810
                // TODO remove dual storage
                .removeData(this.widgetName)
                .removeData(this.widgetFullName)
                // support: jquery <1.6.3
                // http://bugs.jquery.com/ticket/9413
                .removeData($.camelCase(this.widgetFullName));
            this.widget()
                .off(this.eventNamespace)
                .removeAttr("aria-disabled")
                .removeClass(
                    this.widgetFullName + "-disabled " +
                    "ui-state-disabled");

            // clean up events and states
            this.bindings.off(this.eventNamespace);
            this.hoverable.removeClass("ui-state-hover");
            this.focusable.removeClass("ui-state-focus");
        },
        _destroy: $.noop,

        widget: function () {
            return this.element;
        },

        option: function (key, value) {
            var options = key,
                parts,
                curOption,
                i;

            if (arguments.length === 0) {
                // don't return a reference to the internal hash
                return $.widget.extend({}, this.options);
            }

            if (typeof key === "string") {
                // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
                options = {};
                parts = key.split(".");
                key = parts.shift();
                if (parts.length) {
                    curOption = options[key] = $.widget.extend({}, this.options[key]);
                    for (i = 0; i < parts.length - 1; i++) {
                        curOption[parts[i]] = curOption[parts[i]] || {};
                        curOption = curOption[parts[i]];
                    }
                    key = parts.pop();
                    if (arguments.length === 1) {
                        return curOption[key] === undefined ? null : curOption[key];
                    }
                    curOption[key] = value;
                } else {
                    if (arguments.length === 1) {
                        return this.options[key] === undefined ? null : this.options[key];
                    }
                    options[key] = value;
                }
            }

            this._setOptions(options);

            return this;
        },
        _setOptions: function (options) {
            var key;

            for (key in options) {
                this._setOption(key, options[key]);
            }

            return this;
        },
        _setOption: function (key, value) {
            this.options[key] = value;

            if (key === "disabled") {
                this.widget()
                    .toggleClass(this.widgetFullName + "-disabled ui-state-disabled", !!value)
                    .attr("aria-disabled", value);
                this.hoverable.removeClass("ui-state-hover");
                this.focusable.removeClass("ui-state-focus");
            }

            return this;
        },

        enable: function () {
            return this._setOption("disabled", false);
        },
        disable: function () {
            return this._setOption("disabled", true);
        },

        _on: function (suppressDisabledCheck, element, handlers) {
            var delegateElement,
                instance = this;

            // no suppressDisabledCheck flag, shuffle arguments
            if (typeof suppressDisabledCheck !== "boolean") {
                handlers = element;
                element = suppressDisabledCheck;
                suppressDisabledCheck = false;
            }

            // no element argument, shuffle and use this.element
            if (!handlers) {
                handlers = element;
                element = this.element;
                delegateElement = this.widget();
            } else {
                // accept selectors, DOM elements
                element = delegateElement = $(element);
                this.bindings = this.bindings.add(element);
            }

            $.each(handlers, function (event, handler) {
                function handlerProxy() {
                    // allow widgets to customize the disabled handling
                    // - disabled as an array instead of boolean
                    // - disabled class as method for disabling individual parts
                    if (!suppressDisabledCheck &&
                        (instance.options.disabled === true ||
                            $(this).hasClass("ui-state-disabled"))) {
                        return;
                    }
                    return (typeof handler === "string" ? instance[handler] : handler)
                        .apply(instance, arguments);
                }

                // copy the guid so direct unbinding works
                if (typeof handler !== "string") {
                    handlerProxy.guid = handler.guid =
                        handler.guid || handlerProxy.guid || $.guid++;
                }

                var match = event.match(/^(\w+)\s*(.*)$/),
                    eventName = match[1] + instance.eventNamespace,
                    selector = match[2];
                if (selector) {
                    delegateElement.on(eventName, selector, handlerProxy);
                } else {
                    element.on(eventName, handlerProxy);
                }
            });
        },

        _off: function (element, eventName) {
            eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace;
            element.off(eventName);
        },

        _delay: function (handler, delay) {
            function handlerProxy() {
                return (typeof handler === "string" ? instance[handler] : handler)
                    .apply(instance, arguments);
            }
            var instance = this;
            return setTimeout(handlerProxy, delay || 0);
        },

        _hoverable: function (element) {
            this.hoverable = this.hoverable.add(element);
            this._on(element, {
                mouseenter: function (event) {
                    $(event.currentTarget).addClass("ui-state-hover");
                },
                mouseleave: function (event) {
                    $(event.currentTarget).removeClass("ui-state-hover");
                }
            });
        },

        _focusable: function (element) {
            this.focusable = this.focusable.add(element);
            this._on(element, {
                focusin: function (event) {
                    $(event.currentTarget).addClass("ui-state-focus");
                },
                focusout: function (event) {
                    $(event.currentTarget).removeClass("ui-state-focus");
                }
            });
        },

        _trigger: function (type, event, data) {
            var prop, orig,
                callback = this.options[type];

            data = data || {};
            event = $.Event(event);
            event.type = (type === this.widgetEventPrefix ?
                type :
                this.widgetEventPrefix + type).toLowerCase();
            // the original event may come from any element
            // so we need to reset the target on the new event
            event.target = this.element[0];

            // copy original event properties over to the new event
            orig = event.originalEvent;
            if (orig) {
                for (prop in orig) {
                    if (!(prop in event)) {
                        event[prop] = orig[prop];
                    }
                }
            }

            this.element.trigger(event, data);
            return !(typeof callback === "function" &&
                callback.apply(this.element[0], [event].concat(data)) === false ||
                event.isDefaultPrevented());
        }
    };

    $.each({ show: "fadeIn", hide: "fadeOut" }, function (method, defaultEffect) {
        $.Widget.prototype["_" + method] = function (element, options, callback) {
            if (typeof options === "string") {
                options = { effect: options };
            }
            var hasOptions,
                effectName = !options ?
                    method :
                    options === true || typeof options === "number" ?
                        defaultEffect :
                        options.effect || defaultEffect;
            options = options || {};
            if (typeof options === "number") {
                options = { duration: options };
            }
            hasOptions = !$.isEmptyObject(options);
            options.complete = callback;
            if (options.delay) {
                element.delay(options.delay);
            }
            if (hasOptions && $.effects && $.effects.effect[effectName]) {
                element[method](options);
            } else if (effectName !== method && element[effectName]) {
                element[effectName](options.duration, options.easing, callback);
            } else {
                element.queue(function (next) {
                    $(this)[method]();
                    if (callback) {
                        callback.call(element[0]);
                    }
                    next();
                });
            }
        };
    });

})(jQuery);
(function ($, undefined) {

    var mouseHandled = false;
    $(document).on("mouseup", function () {
        mouseHandled = false;
    });

    $.widget("ui.mouse", {
        version: "1.10.4",
        options: {
            cancel: "input,textarea,button,select,option",
            distance: 1,
            delay: 0
        },
        _mouseInit: function () {
            var that = this;

            this.element
                .on("mousedown." + this.widgetName, function (event) {
                    return that._mouseDown(event);
                })
                .on("click." + this.widgetName, function (event) {
                    if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
                        $.removeData(event.target, that.widgetName + ".preventClickEvent");
                        event.stopImmediatePropagation();
                        return false;
                    }
                });

            this.started = false;
        },

        // TODO: make sure destroying one instance of mouse doesn't mess with
        // other instances of mouse
        _mouseDestroy: function () {
            this.element.off("." + this.widgetName);
            if (this._mouseMoveDelegate) {
                $(document)
                    .off("mousemove." + this.widgetName, this._mouseMoveDelegate)
                    .off("mouseup." + this.widgetName, this._mouseUpDelegate);
            }
        },

        _mouseDown: function (event) {
            // don't let more than one widget handle mouseStart
            if (mouseHandled) { return; }

            // we may have missed mouseup (out of window)
            (this._mouseStarted && this._mouseUp(event));

            this._mouseDownEvent = event;

            var that = this,
                btnIsLeft = (event.which === 1),
                // event.target.nodeName works around a bug in IE 8 with
                // disabled inputs (#7620)
                elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
            if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
                return true;
            }

            this.mouseDelayMet = !this.options.delay;
            if (!this.mouseDelayMet) {
                this._mouseDelayTimer = setTimeout(function () {
                    that.mouseDelayMet = true;
                }, this.options.delay);
            }

            if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
                this._mouseStarted = (this._mouseStart(event) !== false);
                if (!this._mouseStarted) {
                    event.preventDefault();
                    return true;
                }
            }

            // Click event may never have fired (Gecko & Opera)
            if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
                $.removeData(event.target, this.widgetName + ".preventClickEvent");
            }

            // these delegates are required to keep context
            this._mouseMoveDelegate = function (event) {
                return that._mouseMove(event);
            };
            this._mouseUpDelegate = function (event) {
                return that._mouseUp(event);
            };
            $(document)
                .on("mousemove." + this.widgetName, this._mouseMoveDelegate)
                .on("mouseup." + this.widgetName, this._mouseUpDelegate);

            event.preventDefault();

            mouseHandled = true;
            return true;
        },

        _mouseMove: function (event) {
            // IE mouseup check - mouseup happened when mouse was out of window
            if ($.ui.ie && (!document.documentMode || document.documentMode < 9) && !event.button) {
                return this._mouseUp(event);
            }

            if (this._mouseStarted) {
                this._mouseDrag(event);
                return event.preventDefault();
            }

            if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
                this._mouseStarted =
                    (this._mouseStart(this._mouseDownEvent, event) !== false);
                (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
            }

            return !this._mouseStarted;
        },

        _mouseUp: function (event) {
            $(document)
                .off("mousemove." + this.widgetName, this._mouseMoveDelegate)
                .off("mouseup." + this.widgetName, this._mouseUpDelegate);

            if (this._mouseStarted) {
                this._mouseStarted = false;

                if (event.target === this._mouseDownEvent.target) {
                    $.data(event.target, this.widgetName + ".preventClickEvent", true);
                }

                this._mouseStop(event);
            }

            return false;
        },

        _mouseDistanceMet: function (event) {
            return (Math.max(
                Math.abs(this._mouseDownEvent.pageX - event.pageX),
                Math.abs(this._mouseDownEvent.pageY - event.pageY)
            ) >= this.options.distance
            );
        },

        _mouseDelayMet: function (/* event */) {
            return this.mouseDelayMet;
        },

        // These are placeholder methods, to be overriden by extending plugin
        _mouseStart: function (/* event */) { },
        _mouseDrag: function (/* event */) { },
        _mouseStop: function (/* event */) { },
        _mouseCapture: function (/* event */) { return true; }
    });

})(jQuery);
(function ($, undefined) {

    $.ui = $.ui || {};

    var cachedScrollbarWidth,
        max = Math.max,
        abs = Math.abs,
        round = Math.round,
        rhorizontal = /left|center|right/,
        rvertical = /top|center|bottom/,
        roffset = /[\+\-]\d+(\.[\d]+)?%?/,
        rposition = /^\w+/,
        rpercent = /%$/,
        _position = $.fn.position;

    function getOffsets(offsets, width, height) {
        return [
            parseFloat(offsets[0]) * (rpercent.test(offsets[0]) ? width / 100 : 1),
            parseFloat(offsets[1]) * (rpercent.test(offsets[1]) ? height / 100 : 1)
        ];
    }

    function parseCss(element, property) {
        return parseInt($.css(element, property), 10) || 0;
    }

    function getDimensions(elem) {
        var raw = elem[0];
        if (raw.nodeType === 9) {
            return {
                width: elem.width(),
                height: elem.height(),
                offset: { top: 0, left: 0 }
            };
        }
        if (raw != null && raw === raw.window) {
            return {
                width: elem.width(),
                height: elem.height(),
                offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
            };
        }
        if (raw.preventDefault) {
            return {
                width: 0,
                height: 0,
                offset: { top: raw.pageY, left: raw.pageX }
            };
        }
        return {
            width: elem.outerWidth(),
            height: elem.outerHeight(),
            offset: elem.offset()
        };
    }

    $.position = {
        scrollbarWidth: function () {
            if (cachedScrollbarWidth !== undefined) {
                return cachedScrollbarWidth;
            }
            var w1, w2,
                div = $("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),
                innerDiv = div.children()[0];

            $("body").append(div);
            w1 = innerDiv.offsetWidth;
            div.css("overflow", "scroll");

            w2 = innerDiv.offsetWidth;

            if (w1 === w2) {
                w2 = div[0].clientWidth;
            }

            div.remove();

            return (cachedScrollbarWidth = w1 - w2);
        },
        getScrollInfo: function (within) {
            var overflowX = within.isWindow || within.isDocument ? "" :
                within.element.css("overflow-x"),
                overflowY = within.isWindow || within.isDocument ? "" :
                    within.element.css("overflow-y"),
                hasOverflowX = overflowX === "scroll" ||
                    (overflowX === "auto" && within.width < within.element[0].scrollWidth),
                hasOverflowY = overflowY === "scroll" ||
                    (overflowY === "auto" && within.height < within.element[0].scrollHeight);
            return {
                width: hasOverflowY ? $.position.scrollbarWidth() : 0,
                height: hasOverflowX ? $.position.scrollbarWidth() : 0
            };
        },
        getWithinInfo: function (element) {
            var withinElement = $(element || window),
                isWindow = (withinElement[0] != null && withinElement[0] === withinElement[0].window) ? withinElement[0] : null,
                isDocument = !!withinElement[0] && withinElement[0].nodeType === 9;
            var hasOffset = withinElement.length ? withinElement.offset() : { left: 0, top: 0 };
            return {
                element: withinElement,
                isWindow: isWindow,
                isDocument: isDocument,
                offset: hasOffset,
                scrollLeft: withinElement.scrollLeft(),
                scrollTop: withinElement.scrollTop(),
                width: isWindow ? withinElement.width() : withinElement.outerWidth(),
                height: isWindow ? withinElement.height() : withinElement.outerHeight()
            };
        }
    };

    $.fn.position = function (options) {
        if (!options || !options.of) {
            return _position.apply(this, arguments);
        }

        // make a copy, we don't want to modify arguments
        options = $.extend({}, options);

        var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
            target = $(options.of),
            within = $.position.getWithinInfo(options.within),
            scrollInfo = $.position.getScrollInfo(within),
            collision = (options.collision || "flip").split(" "),
            offsets = {};

        dimensions = getDimensions(target);
        if (target[0].preventDefault) {
            // force left top to allow flipping
            options.at = "left top";
        }
        targetWidth = dimensions.width;
        targetHeight = dimensions.height;
        targetOffset = dimensions.offset;
        // clone to reuse original targetOffset later
        basePosition = $.extend({}, targetOffset);

        // force my and at to have valid horizontal and vertical positions
        // if a value is missing or invalid, it will be converted to center
        $.each(["my", "at"], function () {
            var pos = (options[this] || "").split(" "),
                horizontalOffset,
                verticalOffset;

            if (pos.length === 1) {
                pos = rhorizontal.test(pos[0]) ?
                    pos.concat(["center"]) :
                    rvertical.test(pos[0]) ?
                        ["center"].concat(pos) :
                        ["center", "center"];
            }
            pos[0] = rhorizontal.test(pos[0]) ? pos[0] : "center";
            pos[1] = rvertical.test(pos[1]) ? pos[1] : "center";

            // calculate offsets
            horizontalOffset = roffset.exec(pos[0]);
            verticalOffset = roffset.exec(pos[1]);
            offsets[this] = [
                horizontalOffset ? horizontalOffset[0] : 0,
                verticalOffset ? verticalOffset[0] : 0
            ];

            // reduce to just the positions without the offsets
            options[this] = [
                rposition.exec(pos[0])[0],
                rposition.exec(pos[1])[0]
            ];
        });

        // normalize collision option
        if (collision.length === 1) {
            collision[1] = collision[0];
        }

        if (options.at[0] === "right") {
            basePosition.left += targetWidth;
        } else if (options.at[0] === "center") {
            basePosition.left += targetWidth / 2;
        }

        if (options.at[1] === "bottom") {
            basePosition.top += targetHeight;
        } else if (options.at[1] === "center") {
            basePosition.top += targetHeight / 2;
        }

        atOffset = getOffsets(offsets.at, targetWidth, targetHeight);
        basePosition.left += atOffset[0];
        basePosition.top += atOffset[1];

        return this.each(function () {
            var collisionPosition, using,
                elem = $(this),
                elemWidth = elem.outerWidth(),
                elemHeight = elem.outerHeight(),
                marginLeft = parseCss(this, "marginLeft"),
                marginTop = parseCss(this, "marginTop"),
                collisionWidth = elemWidth + marginLeft + parseCss(this, "marginRight") + scrollInfo.width,
                collisionHeight = elemHeight + marginTop + parseCss(this, "marginBottom") + scrollInfo.height,
                position = $.extend({}, basePosition),
                myOffset = getOffsets(offsets.my, elem.outerWidth(), elem.outerHeight());

            if (options.my[0] === "right") {
                position.left -= elemWidth;
            } else if (options.my[0] === "center") {
                position.left -= elemWidth / 2;
            }

            if (options.my[1] === "bottom") {
                position.top -= elemHeight;
            } else if (options.my[1] === "center") {
                position.top -= elemHeight / 2;
            }

            position.left += myOffset[0];
            position.top += myOffset[1];

            // if the browser doesn't support fractions, then round for consistent results
            if (!$.support.offsetFractions) {
                position.left = round(position.left);
                position.top = round(position.top);
            }

            collisionPosition = {
                marginLeft: marginLeft,
                marginTop: marginTop
            };

            $.each(["left", "top"], function (i, dir) {
                if ($.ui.position[collision[i]]) {
                    $.ui.position[collision[i]][dir](position, {
                        targetWidth: targetWidth,
                        targetHeight: targetHeight,
                        elemWidth: elemWidth,
                        elemHeight: elemHeight,
                        collisionPosition: collisionPosition,
                        collisionWidth: collisionWidth,
                        collisionHeight: collisionHeight,
                        offset: [atOffset[0] + myOffset[0], atOffset[1] + myOffset[1]],
                        my: options.my,
                        at: options.at,
                        within: within,
                        elem: elem
                    });
                }
            });

            if (options.using) {
                // adds feedback as second argument to using callback, if present
                using = function (props) {
                    var left = targetOffset.left - position.left,
                        right = left + targetWidth - elemWidth,
                        top = targetOffset.top - position.top,
                        bottom = top + targetHeight - elemHeight,
                        feedback = {
                            target: {
                                element: target,
                                left: targetOffset.left,
                                top: targetOffset.top,
                                width: targetWidth,
                                height: targetHeight
                            },
                            element: {
                                element: elem,
                                left: position.left,
                                top: position.top,
                                width: elemWidth,
                                height: elemHeight
                            },
                            horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
                            vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
                        };
                    if (targetWidth < elemWidth && abs(left + right) < targetWidth) {
                        feedback.horizontal = "center";
                    }
                    if (targetHeight < elemHeight && abs(top + bottom) < targetHeight) {
                        feedback.vertical = "middle";
                    }
                    if (max(abs(left), abs(right)) > max(abs(top), abs(bottom))) {
                        feedback.important = "horizontal";
                    } else {
                        feedback.important = "vertical";
                    }
                    options.using.call(this, props, feedback);
                };
            }

            elem.offset($.extend(position, { using: using }));
        });
    };

    $.ui.position = {
        fit: {
            left: function (position, data) {
                var within = data.within,
                    withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
                    outerWidth = within.width,
                    collisionPosLeft = position.left - data.collisionPosition.marginLeft,
                    overLeft = withinOffset - collisionPosLeft,
                    overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
                    newOverRight;

                // element is wider than within
                if (data.collisionWidth > outerWidth) {
                    // element is initially over the left side of within
                    if (overLeft > 0 && overRight <= 0) {
                        newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
                        position.left += overLeft - newOverRight;
                        // element is initially over right side of within
                    } else if (overRight > 0 && overLeft <= 0) {
                        position.left = withinOffset;
                        // element is initially over both left and right sides of within
                    } else {
                        if (overLeft > overRight) {
                            position.left = withinOffset + outerWidth - data.collisionWidth;
                        } else {
                            position.left = withinOffset;
                        }
                    }
                    // too far left -> align with left edge
                } else if (overLeft > 0) {
                    position.left += overLeft;
                    // too far right -> align with right edge
                } else if (overRight > 0) {
                    position.left -= overRight;
                    // adjust based on position and margin
                } else {
                    position.left = max(position.left - collisionPosLeft, position.left);
                }
            },
            top: function (position, data) {
                var within = data.within,
                    withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
                    outerHeight = data.within.height,
                    collisionPosTop = position.top - data.collisionPosition.marginTop,
                    overTop = withinOffset - collisionPosTop,
                    overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
                    newOverBottom;

                // element is taller than within
                if (data.collisionHeight > outerHeight) {
                    // element is initially over the top of within
                    if (overTop > 0 && overBottom <= 0) {
                        newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
                        position.top += overTop - newOverBottom;
                        // element is initially over bottom of within
                    } else if (overBottom > 0 && overTop <= 0) {
                        position.top = withinOffset;
                        // element is initially over both top and bottom of within
                    } else {
                        if (overTop > overBottom) {
                            position.top = withinOffset + outerHeight - data.collisionHeight;
                        } else {
                            position.top = withinOffset;
                        }
                    }
                    // too far up -> align with top
                } else if (overTop > 0) {
                    position.top += overTop;
                    // too far down -> align with bottom edge
                } else if (overBottom > 0) {
                    position.top -= overBottom;
                    // adjust based on position and margin
                } else {
                    position.top = max(position.top - collisionPosTop, position.top);
                }
            }
        },
        flip: {
            left: function (position, data) {
                var within = data.within,
                    withinOffset = within.offset.left + within.scrollLeft,
                    outerWidth = within.width,
                    offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
                    collisionPosLeft = position.left - data.collisionPosition.marginLeft,
                    overLeft = collisionPosLeft - offsetLeft,
                    overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
                    myOffset = data.my[0] === "left" ?
                        -data.elemWidth :
                        data.my[0] === "right" ?
                            data.elemWidth :
                            0,
                    atOffset = data.at[0] === "left" ?
                        data.targetWidth :
                        data.at[0] === "right" ?
                            -data.targetWidth :
                            0,
                    offset = -2 * data.offset[0],
                    newOverRight,
                    newOverLeft;

                if (overLeft < 0) {
                    newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
                    if (newOverRight < 0 || newOverRight < abs(overLeft)) {
                        position.left += myOffset + atOffset + offset;
                    }
                }
                else if (overRight > 0) {
                    newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
                    if (newOverLeft > 0 || abs(newOverLeft) < overRight) {
                        position.left += myOffset + atOffset + offset;
                    }
                }
            },
            top: function (position, data) {
                var within = data.within,
                    withinOffset = within.offset.top + within.scrollTop,
                    outerHeight = within.height,
                    offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
                    collisionPosTop = position.top - data.collisionPosition.marginTop,
                    overTop = collisionPosTop - offsetTop,
                    overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
                    top = data.my[1] === "top",
                    myOffset = top ?
                        -data.elemHeight :
                        data.my[1] === "bottom" ?
                            data.elemHeight :
                            0,
                    atOffset = data.at[1] === "top" ?
                        data.targetHeight :
                        data.at[1] === "bottom" ?
                            -data.targetHeight :
                            0,
                    offset = -2 * data.offset[1],
                    newOverTop,
                    newOverBottom;
                if (overTop < 0) {
                    newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
                    if ((position.top + myOffset + atOffset + offset) > overTop && (newOverBottom < 0 || newOverBottom < abs(overTop))) {
                        position.top += myOffset + atOffset + offset;
                    }
                }
                else if (overBottom > 0) {
                    newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
                    if ((position.top + myOffset + atOffset + offset) > overBottom && (newOverTop > 0 || abs(newOverTop) < overBottom)) {
                        position.top += myOffset + atOffset + offset;
                    }
                }
            }
        },
        flipfit: {
            left: function () {
                $.ui.position.flip.left.apply(this, arguments);
                $.ui.position.fit.left.apply(this, arguments);
            },
            top: function () {
                $.ui.position.flip.top.apply(this, arguments);
                $.ui.position.fit.top.apply(this, arguments);
            }
        }
    };

    // fraction support test
    (function () {
        var testElement, testElementParent, testElementStyle, offsetLeft, i,
            body = document.getElementsByTagName("body")[0],
            div = document.createElement("div");

        //Create a "fake body" for testing based on method used in jQuery.support
        testElement = document.createElement(body ? "div" : "body");
        testElementStyle = {
            visibility: "hidden",
            width: 0,
            height: 0,
            border: 0,
            margin: 0,
            background: "none"
        };
        if (body) {
            $.extend(testElementStyle, {
                position: "absolute",
                left: "-1000px",
                top: "-1000px"
            });
        }
        for (i in testElementStyle) {
            testElement.style[i] = testElementStyle[i];
        }
        testElement.appendChild(div);
        testElementParent = body || document.documentElement;
        testElementParent.insertBefore(testElement, testElementParent.firstChild);

        div.style.cssText = "position: absolute; left: 10.7432222px;";

        offsetLeft = $(div).offset().left;
        $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;

        testElement.innerHTML = "";
        testElementParent.removeChild(testElement);
    })();

}(jQuery));
(function ($, undefined) {

    $.widget("ui.draggable", $.ui.mouse, {
        version: "1.10.4",
        widgetEventPrefix: "drag",
        options: {
            addClasses: true,
            appendTo: "parent",
            axis: false,
            connectToSortable: false,
            containment: false,
            cursor: "auto",
            cursorAt: false,
            grid: false,
            handle: false,
            helper: "original",
            iframeFix: false,
            opacity: false,
            refreshPositions: false,
            revert: false,
            revertDuration: 500,
            scope: "default",
            scroll: true,
            scrollSensitivity: 20,
            scrollSpeed: 20,
            snap: false,
            snapMode: "both",
            snapTolerance: 20,
            stack: false,
            zIndex: false,

            // callbacks
            drag: null,
            start: null,
            stop: null
        },
        _create: function () {

            if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
                this.element[0].style.position = "relative";
            }
            if (this.options.addClasses) {
                this.element.addClass("ui-draggable");
            }
            if (this.options.disabled) {
                this.element.addClass("ui-draggable-disabled");
            }

            this._mouseInit();

        },

        _destroy: function () {
            this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");
            this._mouseDestroy();
        },

        _mouseCapture: function (event) {

            var o = this.options;

            // among others, prevent a drag on a resizable-handle
            if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
                return false;
            }

            //Quit if we're not on a valid handle
            this.handle = this._getHandle(event);
            if (!this.handle) {
                return false;
            }

            $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function () {
                $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
                    .css({
                        width: this.offsetWidth + "px", height: this.offsetHeight + "px",
                        position: "absolute", opacity: "0.001", zIndex: 1000
                    })
                    .css($(this).offset())
                    .appendTo("body");
            });

            return true;

        },

        _mouseStart: function (event) {

            var o = this.options;

            //Create and append the visible helper
            this.helper = this._createHelper(event);

            this.helper.addClass("ui-draggable-dragging");

            //Cache the helper size
            this._cacheHelperProportions();

            //If ddmanager is used for droppables, set the global draggable
            if ($.ui.ddmanager) {
                $.ui.ddmanager.current = this;
            }

            /*
             * - Position generation -
             * This block generates everything position related - it's the core of draggables.
             */

            //Cache the margins of the original element
            this._cacheMargins();

            //Store the helper's css position
            this.cssPosition = this.helper.css("position");
            this.scrollParent = this.helper.scrollParent();
            this.offsetParent = this.helper.offsetParent();
            this.offsetParentCssPosition = this.offsetParent.css("position");

            //The element's absolute position on the page minus margins
            this.offset = this.positionAbs = this.element.offset();
            this.offset = {
                top: this.offset.top - this.margins.top,
                left: this.offset.left - this.margins.left
            };

            //Reset scroll cache
            this.offset.scroll = false;

            $.extend(this.offset, {
                click: { //Where the click happened, relative to the element
                    left: event.pageX - this.offset.left,
                    top: event.pageY - this.offset.top
                },
                parent: this._getParentOffset(),
                relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
            });

            //Generate the original position
            this.originalPosition = this.position = this._generatePosition(event);
            this.originalPageX = event.pageX;
            this.originalPageY = event.pageY;

            //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
            (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

            //Set a containment if given in the options
            this._setContainment();

            //Trigger event + callbacks
            if (this._trigger("start", event) === false) {
                this._clear();
                return false;
            }

            //Recache the helper size
            this._cacheHelperProportions();

            //Prepare the droppable offsets
            if ($.ui.ddmanager && !o.dropBehaviour) {
                $.ui.ddmanager.prepareOffsets(this, event);
            }


            this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

            //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
            if ($.ui.ddmanager) {
                $.ui.ddmanager.dragStart(this, event);
            }

            return true;
        },

        _mouseDrag: function (event, noPropagation) {
            // reset any necessary cached properties (see #5009)
            if (this.offsetParentCssPosition === "fixed") {
                this.offset.parent = this._getParentOffset();
            }

            //Compute the helpers position
            this.position = this._generatePosition(event);
            this.positionAbs = this._convertPositionTo("absolute");

            //Call plugins and callbacks and use the resulting position if something is returned
            if (!noPropagation) {
                var ui = this._uiHash();
                if (this._trigger("drag", event, ui) === false) {
                    this._mouseUp({});
                    return false;
                }
                this.position = ui.position;
            }

            if (!this.options.axis || this.options.axis !== "y") {
                this.helper[0].style.left = this.position.left + "px";
            }
            if (!this.options.axis || this.options.axis !== "x") {
                this.helper[0].style.top = this.position.top + "px";
            }
            if ($.ui.ddmanager) {
                $.ui.ddmanager.drag(this, event);
            }

            return false;
        },

        _mouseStop: function (event) {

            //If we are using droppables, inform the manager about the drop
            var that = this,
                dropped = false;
            if ($.ui.ddmanager && !this.options.dropBehaviour) {
                dropped = $.ui.ddmanager.drop(this, event);
            }

            //if a drop comes from outside (a sortable)
            if (this.dropped) {
                dropped = this.dropped;
                this.dropped = false;
            }

            //if the original element is no longer in the DOM don't bother to continue (see #8269)
            if (this.options.helper === "original" && !$.contains(this.element[0].ownerDocument, this.element[0])) {
                return false;
            }

            if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || (typeof this.options.revert === "function" && this.options.revert.call(this.element, dropped))) {
                $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function () {
                    if (that._trigger("stop", event) !== false) {
                        that._clear();
                    }
                });
            } else {
                if (this._trigger("stop", event) !== false) {
                    this._clear();
                }
            }

            return false;
        },

        _mouseUp: function (event) {
            //Remove frame helpers
            $("div.ui-draggable-iframeFix").each(function () {
                this.parentNode.removeChild(this);
            });

            //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
            if ($.ui.ddmanager) {
                $.ui.ddmanager.dragStop(this, event);
            }

            return $.ui.mouse.prototype._mouseUp.call(this, event);
        },

        cancel: function () {

            if (this.helper.is(".ui-draggable-dragging")) {
                this._mouseUp({});
            } else {
                this._clear();
            }

            return this;

        },

        _getHandle: function (event) {
            return this.options.handle ?
                !!$(event.target).closest(this.element.find(this.options.handle)).length :
                true;
        },

        _createHelper: function (event) {

            var o = this.options,
                helper = typeof o.helper === "function" ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);

            if (!helper.parents("body").length) {
                helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
            }

            if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
                helper.css("position", "absolute");
            }

            return helper;

        },

        _adjustOffsetFromHelper: function (obj) {
            if (typeof obj === "string") {
                obj = obj.split(" ");
            }
            if (Array.isArray(obj)) {
                obj = { left: +obj[0], top: +obj[1] || 0 };
            }
            if ("left" in obj) {
                this.offset.click.left = obj.left + this.margins.left;
            }
            if ("right" in obj) {
                this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
            }
            if ("top" in obj) {
                this.offset.click.top = obj.top + this.margins.top;
            }
            if ("bottom" in obj) {
                this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
            }
        },

        _getParentOffset: function () {

            //Get the offsetParent and cache its position
            var po = this.offsetParent.offset();

            // This is a special case where we need to modify a offset calculated on start, since the following happened:
            // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
            // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
            //    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
            if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
                po.left += this.scrollParent.scrollLeft();
                po.top += this.scrollParent.scrollTop();
            }

            //This needs to be actually done for all browsers, since pageX/pageY includes this information
            //Ugly IE fix
            if ((this.offsetParent[0] === document.body) ||
                (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
                po = { top: 0, left: 0 };
            }

            return {
                top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
                left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
            };

        },

        _getRelativeOffset: function () {

            if (this.cssPosition === "relative") {
                var p = this.element.position();
                return {
                    top: p.top - (parseInt(this.helper.css("top"), 10) || 0) + this.scrollParent.scrollTop(),
                    left: p.left - (parseInt(this.helper.css("left"), 10) || 0) + this.scrollParent.scrollLeft()
                };
            } else {
                return { top: 0, left: 0 };
            }

        },

        _cacheMargins: function () {
            this.margins = {
                left: (parseInt(this.element.css("marginLeft"), 10) || 0),
                top: (parseInt(this.element.css("marginTop"), 10) || 0),
                right: (parseInt(this.element.css("marginRight"), 10) || 0),
                bottom: (parseInt(this.element.css("marginBottom"), 10) || 0)
            };
        },

        _cacheHelperProportions: function () {
            this.helperProportions = {
                width: this.helper.outerWidth(),
                height: this.helper.outerHeight()
            };
        },

        _setContainment: function () {

            var over, c, ce,
                o = this.options;

            if (!o.containment) {
                this.containment = null;
                return;
            }

            if (o.containment === "window") {
                this.containment = [
                    $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
                    $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top,
                    $(window).scrollLeft() + $(window).width() - this.helperProportions.width - this.margins.left,
                    $(window).scrollTop() + ($(window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
                ];
                return;
            }

            if (o.containment === "document") {
                this.containment = [
                    0,
                    0,
                    $(document).width() - this.helperProportions.width - this.margins.left,
                    ($(document).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
                ];
                return;
            }

            if (o.containment.constructor === Array) {
                this.containment = o.containment;
                return;
            }

            if (o.containment === "parent") {
                o.containment = this.helper[0].parentNode;
            }

            c = $(o.containment);
            ce = c[0];

            if (!ce) {
                return;
            }

            over = c.css("overflow") !== "hidden";

            this.containment = [
                (parseInt(c.css("borderLeftWidth"), 10) || 0) + (parseInt(c.css("paddingLeft"), 10) || 0),
                (parseInt(c.css("borderTopWidth"), 10) || 0) + (parseInt(c.css("paddingTop"), 10) || 0),
                (over ? Math.max(ce.scrollWidth, ce.offsetWidth) : ce.offsetWidth) - (parseInt(c.css("borderRightWidth"), 10) || 0) - (parseInt(c.css("paddingRight"), 10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right,
                (over ? Math.max(ce.scrollHeight, ce.offsetHeight) : ce.offsetHeight) - (parseInt(c.css("borderBottomWidth"), 10) || 0) - (parseInt(c.css("paddingBottom"), 10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom
            ];
            this.relative_container = c;
        },

        _convertPositionTo: function (d, pos) {

            if (!pos) {
                pos = this.position;
            }

            var mod = d === "absolute" ? 1 : -1,
                scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent;

            //Cache the scroll
            if (!this.offset.scroll) {
                this.offset.scroll = { top: scroll.scrollTop(), left: scroll.scrollLeft() };
            }

            return {
                top: (
                    pos.top +																// The absolute mouse position
                    this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.parent.top * mod -										// The offsetParent's offset without borders (offset + border)
                    ((this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top) * mod)
                ),
                left: (
                    pos.left +																// The absolute mouse position
                    this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.parent.left * mod -										// The offsetParent's offset without borders (offset + border)
                    ((this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left) * mod)
                )
            };

        },

        _generatePosition: function (event) {

            var containment, co, top, left,
                o = this.options,
                scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
                pageX = event.pageX,
                pageY = event.pageY;

            //Cache the scroll
            if (!this.offset.scroll) {
                this.offset.scroll = { top: scroll.scrollTop(), left: scroll.scrollLeft() };
            }

            /*
             * - Position constraining -
             * Constrain the position to a mix of grid, containment.
             */

            // If we are not dragging yet, we won't check for options
            if (this.originalPosition) {
                if (this.containment) {
                    if (this.relative_container) {
                        co = this.relative_container.offset();
                        containment = [
                            this.containment[0] + co.left,
                            this.containment[1] + co.top,
                            this.containment[2] + co.left,
                            this.containment[3] + co.top
                        ];
                    }
                    else {
                        containment = this.containment;
                    }

                    if (event.pageX - this.offset.click.left < containment[0]) {
                        pageX = containment[0] + this.offset.click.left;
                    }
                    if (event.pageY - this.offset.click.top < containment[1]) {
                        pageY = containment[1] + this.offset.click.top;
                    }
                    if (event.pageX - this.offset.click.left > containment[2]) {
                        pageX = containment[2] + this.offset.click.left;
                    }
                    if (event.pageY - this.offset.click.top > containment[3]) {
                        pageY = containment[3] + this.offset.click.top;
                    }
                }

                if (o.grid) {
                    //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
                    top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
                    pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

                    left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
                    pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
                }

            }

            return {
                top: (
                    pageY -																	// The absolute mouse position
                    this.offset.click.top -												// Click offset (relative to the element)
                    this.offset.relative.top -												// Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
                    (this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top)
                ),
                left: (
                    pageX -																	// The absolute mouse position
                    this.offset.click.left -												// Click offset (relative to the element)
                    this.offset.relative.left -												// Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
                    (this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left)
                )
            };

        },

        _clear: function () {
            this.helper.removeClass("ui-draggable-dragging");
            if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
                this.helper.remove();
            }
            this.helper = null;
            this.cancelHelperRemoval = false;
        },

        // From now on bulk stuff - mainly helpers

        _trigger: function (type, event, ui) {
            ui = ui || this._uiHash();
            $.ui.plugin.call(this, type, [event, ui]);
            //The absolute position has to be recalculated after plugins
            if (type === "drag") {
                this.positionAbs = this._convertPositionTo("absolute");
            }
            return $.Widget.prototype._trigger.call(this, type, event, ui);
        },

        plugins: {},

        _uiHash: function () {
            return {
                helper: this.helper,
                position: this.position,
                originalPosition: this.originalPosition,
                offset: this.positionAbs
            };
        }

    });

    $.ui.plugin.add("draggable", "connectToSortable", {
        start: function (event, ui) {

            var inst = $(this).data("ui-draggable"), o = inst.options,
                uiSortable = $.extend({}, ui, { item: inst.element });
            inst.sortables = [];
            $(o.connectToSortable).each(function () {
                var sortable = $.data(this, "ui-sortable");
                if (sortable && !sortable.options.disabled) {
                    inst.sortables.push({
                        instance: sortable,
                        shouldRevert: sortable.options.revert
                    });
                    sortable.refreshPositions();	// Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
                    sortable._trigger("activate", event, uiSortable);
                }
            });

        },
        stop: function (event, ui) {

            //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
            var inst = $(this).data("ui-draggable"),
                uiSortable = $.extend({}, ui, { item: inst.element });

            $.each(inst.sortables, function () {
                if (this.instance.isOver) {

                    this.instance.isOver = 0;

                    inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
                    this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

                    //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
                    if (this.shouldRevert) {
                        this.instance.options.revert = this.shouldRevert;
                    }

                    //Trigger the stop of the sortable
                    this.instance._mouseStop(event);

                    this.instance.options.helper = this.instance.options._helper;

                    //If the helper has been the original item, restore properties in the sortable
                    if (inst.options.helper === "original") {
                        this.instance.currentItem.css({ top: "auto", left: "auto" });
                    }

                } else {
                    this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
                    this.instance._trigger("deactivate", event, uiSortable);
                }

            });

        },
        drag: function (event, ui) {

            var inst = $(this).data("ui-draggable"), that = this;

            $.each(inst.sortables, function () {

                var innermostIntersecting = false,
                    thisSortable = this;

                //Copy over some variables to allow calling the sortable's native _intersectsWith
                this.instance.positionAbs = inst.positionAbs;
                this.instance.helperProportions = inst.helperProportions;
                this.instance.offset.click = inst.offset.click;

                if (this.instance._intersectsWith(this.instance.containerCache)) {
                    innermostIntersecting = true;
                    $.each(inst.sortables, function () {
                        this.instance.positionAbs = inst.positionAbs;
                        this.instance.helperProportions = inst.helperProportions;
                        this.instance.offset.click = inst.offset.click;
                        if (this !== thisSortable &&
                            this.instance._intersectsWith(this.instance.containerCache) &&
                            $.contains(thisSortable.instance.element[0], this.instance.element[0])
                        ) {
                            innermostIntersecting = false;
                        }
                        return innermostIntersecting;
                    });
                }


                if (innermostIntersecting) {
                    //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
                    if (!this.instance.isOver) {

                        this.instance.isOver = 1;
                        //Now we fake the start of dragging for the sortable instance,
                        //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
                        //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
                        this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
                        this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
                        this.instance.options.helper = function () { return ui.helper[0]; };

                        event.target = this.instance.currentItem[0];
                        this.instance._mouseCapture(event, true);
                        this.instance._mouseStart(event, true, true);

                        //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
                        this.instance.offset.click.top = inst.offset.click.top;
                        this.instance.offset.click.left = inst.offset.click.left;
                        this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
                        this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

                        inst._trigger("toSortable", event);
                        inst.dropped = this.instance.element; //draggable revert needs that
                        //hack so receive/update callbacks work (mostly)
                        inst.currentItem = inst.element;
                        this.instance.fromOutside = inst;

                    }

                    //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
                    if (this.instance.currentItem) {
                        this.instance._mouseDrag(event);
                    }

                } else {

                    //If it doesn't intersect with the sortable, and it intersected before,
                    //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
                    if (this.instance.isOver) {

                        this.instance.isOver = 0;
                        this.instance.cancelHelperRemoval = true;

                        //Prevent reverting on this forced stop
                        this.instance.options.revert = false;

                        // The out event needs to be triggered independently
                        this.instance._trigger("out", event, this.instance._uiHash(this.instance));

                        this.instance._mouseStop(event, true);
                        this.instance.options.helper = this.instance.options._helper;

                        //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
                        this.instance.currentItem.remove();
                        if (this.instance.placeholder) {
                            this.instance.placeholder.remove();
                        }

                        inst._trigger("fromSortable", event);
                        inst.dropped = false; //draggable revert needs that
                    }

                }

            });

        }
    });

    $.ui.plugin.add("draggable", "cursor", {
        start: function () {
            var t = $("body"), o = $(this).data("ui-draggable").options;
            if (t.css("cursor")) {
                o._cursor = t.css("cursor");
            }
            t.css("cursor", o.cursor);
        },
        stop: function () {
            var o = $(this).data("ui-draggable").options;
            if (o._cursor) {
                $("body").css("cursor", o._cursor);
            }
        }
    });

    $.ui.plugin.add("draggable", "opacity", {
        start: function (event, ui) {
            var t = $(ui.helper), o = $(this).data("ui-draggable").options;
            if (t.css("opacity")) {
                o._opacity = t.css("opacity");
            }
            t.css("opacity", o.opacity);
        },
        stop: function (event, ui) {
            var o = $(this).data("ui-draggable").options;
            if (o._opacity) {
                $(ui.helper).css("opacity", o._opacity);
            }
        }
    });

    $.ui.plugin.add("draggable", "scroll", {
        start: function () {
            var i = $(this).data("ui-draggable");
            if (i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
                i.overflowOffset = i.scrollParent.offset();
            }
        },
        drag: function (event) {

            var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;

            if (i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {

                if (!o.axis || o.axis !== "x") {
                    if ((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
                        i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
                    } else if (event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
                        i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
                    }
                }

                if (!o.axis || o.axis !== "y") {
                    if ((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
                        i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
                    } else if (event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
                        i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
                    }
                }

            } else {

                if (!o.axis || o.axis !== "x") {
                    if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
                        scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
                    } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
                        scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
                    }
                }

                if (!o.axis || o.axis !== "y") {
                    if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
                        scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
                    } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
                        scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
                    }
                }

            }

            if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
                $.ui.ddmanager.prepareOffsets(i, event);
            }

        }
    });

    $.ui.plugin.add("draggable", "snap", {
        start: function () {

            var i = $(this).data("ui-draggable"),
                o = i.options;

            i.snapElements = [];

            $(o.snap.constructor !== String ? (o.snap.items || ":data(ui-draggable)") : o.snap).each(function () {
                var $t = $(this),
                    $o = $t.offset();
                if (this !== i.element[0]) {
                    i.snapElements.push({
                        item: this,
                        width: $t.outerWidth(), height: $t.outerHeight(),
                        top: $o.top, left: $o.left
                    });
                }
            });

        },
        drag: function (event, ui) {

            var ts, bs, ls, rs, l, r, t, b, i, first,
                inst = $(this).data("ui-draggable"),
                o = inst.options,
                d = o.snapTolerance,
                x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
                y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

            for (i = inst.snapElements.length - 1; i >= 0; i--) {

                l = inst.snapElements[i].left;
                r = l + inst.snapElements[i].width;
                t = inst.snapElements[i].top;
                b = t + inst.snapElements[i].height;

                if (x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains(inst.snapElements[i].item.ownerDocument, inst.snapElements[i].item)) {
                    if (inst.snapElements[i].snapping) {
                        (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
                    }
                    inst.snapElements[i].snapping = false;
                    continue;
                }

                if (o.snapMode !== "inner") {
                    ts = Math.abs(t - y2) <= d;
                    bs = Math.abs(b - y1) <= d;
                    ls = Math.abs(l - x2) <= d;
                    rs = Math.abs(r - x1) <= d;
                    if (ts) {
                        ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
                    }
                    if (bs) {
                        ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
                    }
                    if (ls) {
                        ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
                    }
                    if (rs) {
                        ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
                    }
                }

                first = (ts || bs || ls || rs);

                if (o.snapMode !== "outer") {
                    ts = Math.abs(t - y1) <= d;
                    bs = Math.abs(b - y2) <= d;
                    ls = Math.abs(l - x1) <= d;
                    rs = Math.abs(r - x2) <= d;
                    if (ts) {
                        ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
                    }
                    if (bs) {
                        ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
                    }
                    if (ls) {
                        ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
                    }
                    if (rs) {
                        ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
                    }
                }

                if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
                    (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
                }
                inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

            }

        }
    });

    $.ui.plugin.add("draggable", "stack", {
        start: function () {
            var min,
                o = this.data("ui-draggable").options,
                group = $.makeArray($(o.stack)).sort(function (a, b) {
                    return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0);
                });

            if (!group.length) { return; }

            min = parseInt($(group[0]).css("zIndex"), 10) || 0;
            $(group).each(function (i) {
                $(this).css("zIndex", min + i);
            });
            this.css("zIndex", (min + group.length));
        }
    });

    $.ui.plugin.add("draggable", "zIndex", {
        start: function (event, ui) {
            var t = $(ui.helper), o = $(this).data("ui-draggable").options;
            if (t.css("zIndex")) {
                o._zIndex = t.css("zIndex");
            }
            t.css("zIndex", o.zIndex);
        },
        stop: function (event, ui) {
            var o = $(this).data("ui-draggable").options;
            if (o._zIndex) {
                $(ui.helper).css("zIndex", o._zIndex);
            }
        }
    });

})(jQuery);
(function ($, undefined) {

    $.widget("ui.autocomplete", {
        version: "1.10.4",
        defaultElement: "<input>",
        options: {
            appendTo: null,
            autoFocus: false,
            delay: 300,
            minLength: 1,
            position: {
                my: "left top",
                at: "left bottom",
                collision: "none"
            },
            source: null,

            // callbacks
            change: null,
            close: null,
            focus: null,
            open: null,
            response: null,
            search: null,
            select: null
        },

        requestIndex: 0,
        pending: 0,

        _create: function () {
            // Some browsers only repeat keydown events, not keypress events,
            // so we use the suppressKeyPress flag to determine if we've already
            // handled the keydown event. #7269
            // Unfortunately the code for & in keypress is the same as the up arrow,
            // so we use the suppressKeyPressRepeat flag to avoid handling keypress
            // events when we know the keydown event was used to modify the
            // search term. #7799
            var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
                nodeName = this.element[0].nodeName.toLowerCase(),
                isTextarea = nodeName === "textarea",
                isInput = nodeName === "input";

            this.isMultiLine =
                // Textareas are always multi-line
                isTextarea ? true :
                    // Inputs are always single-line, even if inside a contentEditable element
                    // IE also treats inputs as contentEditable
                    isInput ? false :
                        // All other element types are determined by whether or not they're contentEditable
                        this.element.prop("isContentEditable");

            this.valueMethod = this.element[isTextarea || isInput ? "val" : "text"];
            this.isNewMenu = true;

            this.element
                .addClass("ui-autocomplete-input")
                .attr("autocomplete", "off");

            this._on(this.element, {
                keydown: function (event) {
                    if (this.element.prop("readOnly")) {
                        suppressKeyPress = true;
                        suppressInput = true;
                        suppressKeyPressRepeat = true;
                        return;
                    }

                    suppressKeyPress = false;
                    suppressInput = false;
                    suppressKeyPressRepeat = false;
                    var keyCode = $.ui.keyCode;
                    switch (event.keyCode) {
                        case keyCode.PAGE_UP:
                            suppressKeyPress = true;
                            this._move("previousPage", event);
                            break;
                        case keyCode.PAGE_DOWN:
                            suppressKeyPress = true;
                            this._move("nextPage", event);
                            break;
                        case keyCode.UP:
                            suppressKeyPress = true;
                            this._keyEvent("previous", event);
                            break;
                        case keyCode.DOWN:
                            suppressKeyPress = true;
                            this._keyEvent("next", event);
                            break;
                        case keyCode.ENTER:
                        case keyCode.NUMPAD_ENTER:
                            // when menu is open and has focus
                            if (this.menu.active) {
                                // #6055 - Opera still allows the keypress to occur
                                // which causes forms to submit
                                suppressKeyPress = true;
                                event.preventDefault();
                                this.menu.select(event);
                            }
                            break;
                        case keyCode.TAB:
                            if (this.menu.active) {
                                this.menu.select(event);
                            }
                            break;
                        case keyCode.ESCAPE:
                            if (this.menu.element.is(":visible")) {
                                this._value(this.term);
                                this.close(event);
                                // Different browsers have different default behavior for escape
                                // Single press can mean undo or clear
                                // Double press in IE means clear the whole form
                                event.preventDefault();
                            }
                            break;
                        default:
                            suppressKeyPressRepeat = true;
                            // search timeout should be triggered before the input value is changed
                            this._searchTimeout(event);
                            break;
                    }
                },
                keypress: function (event) {
                    if (suppressKeyPress) {
                        suppressKeyPress = false;
                        if (!this.isMultiLine || this.menu.element.is(":visible")) {
                            event.preventDefault();
                        }
                        return;
                    }
                    if (suppressKeyPressRepeat) {
                        return;
                    }

                    // replicate some key handlers to allow them to repeat in Firefox and Opera
                    var keyCode = $.ui.keyCode;
                    switch (event.keyCode) {
                        case keyCode.PAGE_UP:
                            this._move("previousPage", event);
                            break;
                        case keyCode.PAGE_DOWN:
                            this._move("nextPage", event);
                            break;
                        case keyCode.UP:
                            this._keyEvent("previous", event);
                            break;
                        case keyCode.DOWN:
                            this._keyEvent("next", event);
                            break;
                    }
                },
                input: function (event) {
                    if (suppressInput) {
                        suppressInput = false;
                        event.preventDefault();
                        return;
                    }
                    this._searchTimeout(event);
                },
                focus: function () {
                    this.selectedItem = null;
                    this.previous = this._value();
                },
                blur: function (event) {
                    if (this.cancelBlur) {
                        delete this.cancelBlur;
                        return;
                    }

                    clearTimeout(this.searching);
                    this.close(event);
                    this._change(event);
                }
            });

            this._initSource();
            this.menu = $("<ul>")
                .addClass("ui-autocomplete ui-front")
                .appendTo(this._appendTo())
                .menu({
                    // disable ARIA support, the live region takes care of that
                    role: null
                })
                .hide()
                .data("ui-menu");

            this._on(this.menu.element, {
                mousedown: function (event) {
                    // prevent moving focus out of the text field
                    event.preventDefault();

                    // IE doesn't prevent moving focus even with event.preventDefault()
                    // so we set a flag to know when we should ignore the blur event
                    this.cancelBlur = true;
                    this._delay(function () {
                        delete this.cancelBlur;
                    });

                    // clicking on the scrollbar causes focus to shift to the body
                    // but we can't detect a mouseup or a click immediately afterward
                    // so we have to track the next mousedown and close the menu if
                    // the user clicks somewhere outside of the autocomplete
                    var menuElement = this.menu.element[0];
                    if (!$(event.target).closest(".ui-menu-item").length) {
                        this._delay(function () {
                            var that = this;
                            this.document.one("mousedown", function (event) {
                                if (event.target !== that.element[0] &&
                                    event.target !== menuElement &&
                                    !$.contains(menuElement, event.target)) {
                                    that.close();
                                }
                            });
                        });
                    }
                },
                menufocus: function (event, ui) {
                    // support: Firefox
                    // Prevent accidental activation of menu items in Firefox (#7024 #9118)
                    if (this.isNewMenu) {
                        this.isNewMenu = false;
                        if (event.originalEvent && /^mouse/.test(event.originalEvent.type)) {
                            this.menu.blur();

                            this.document.one("mousemove", function () {
                                $(event.target).trigger(event.originalEvent);
                            });

                            return;
                        }
                    }

                    var item = ui.item.data("ui-autocomplete-item");
                    if (false !== this._trigger("focus", event, { item: item })) {
                        // use value to match what will end up in the input, if it was a key event
                        if (event.originalEvent && /^key/.test(event.originalEvent.type)) {
                            this._value(item.value);
                        }
                    } else {
                        // Normally the input is populated with the item's value as the
                        // menu is navigated, causing screen readers to notice a change and
                        // announce the item. Since the focus event was canceled, this doesn't
                        // happen, so we update the live region so that screen readers can
                        // still notice the change and announce it.
                        this.liveRegion.text(item.value);
                    }
                },
                menuselect: function (event, ui) {
                    var item = ui.item.data("ui-autocomplete-item"),
                        previous = this.previous;

                    // only trigger when focus was lost (click on menu)
                    if (this.element[0] !== this.document[0].activeElement) {
                        this.element.focus();
                        this.previous = previous;
                        // #6109 - IE triggers two focus events and the second
                        // is asynchronous, so we need to reset the previous
                        // term synchronously and asynchronously :-(
                        this._delay(function () {
                            this.previous = previous;
                            this.selectedItem = item;
                        });
                    }

                    if (false !== this._trigger("select", event, { item: item })) {
                        this._value(item.value);
                    }
                    // reset the term after the select event
                    // this allows custom select handling to work properly
                    this.term = this._value();

                    this.close(event);
                    this.selectedItem = item;
                }
            });

            this.liveRegion = $("<span>", {
                role: "status",
                "aria-live": "polite"
            })
                .addClass("ui-helper-hidden-accessible")
                .insertBefore(this.element);

            // turning off autocomplete prevents the browser from remembering the
            // value when navigating through history, so we re-enable autocomplete
            // if the page is unloaded before the widget is destroyed. #7790
            this._on(this.window, {
                beforeunload: function () {
                    this.element.removeAttr("autocomplete");
                }
            });
        },

        _destroy: function () {
            clearTimeout(this.searching);
            this.element
                .removeClass("ui-autocomplete-input")
                .removeAttr("autocomplete");
            this.menu.element.remove();
            this.liveRegion.remove();
        },

        _setOption: function (key, value) {
            this._super(key, value);
            if (key === "source") {
                this._initSource();
            }
            if (key === "appendTo") {
                this.menu.element.appendTo(this._appendTo());
            }
            if (key === "disabled" && value && this.xhr) {
                this.xhr.abort();
            }
        },

        _appendTo: function () {
            var element = this.options.appendTo;

            if (element) {
                element = element.jquery || element.nodeType ?
                    $(element) :
                    this.document.find(element).eq(0);
            }

            if (!element) {
                element = this.element.closest(".ui-front");
            }

            if (!element.length) {
                element = this.document[0].body;
            }

            return element;
        },

        _initSource: function () {
            var array, url,
                that = this;
            if (Array.isArray(this.options.source)) {
                array = this.options.source;
                this.source = function (request, response) {
                    response($.ui.autocomplete.filter(array, request.term));
                };
            } else if (typeof this.options.source === "string") {
                url = this.options.source;
                this.source = function (request, response) {
                    if (that.xhr) {
                        that.xhr.abort();
                    }
                    that.xhr = $.ajax({
                        url: url,
                        data: request,
                        dataType: "json",
                        success: function (data) {
                            response(data);
                        },
                        error: function () {
                            response([]);
                        }
                    });
                };
            } else {
                this.source = this.options.source;
            }
        },

        _searchTimeout: function (event) {
            clearTimeout(this.searching);
            this.searching = this._delay(function () {
                // only search if the value has changed
                if (this.term !== this._value()) {
                    this.selectedItem = null;
                    this.search(null, event);
                }
            }, this.options.delay);
        },

        search: function (value, event) {
            value = value != null ? value : this._value();

            // always save the actual value, not the one passed as an argument
            this.term = this._value();

            if (value.length < this.options.minLength) {
                return this.close(event);
            }

            if (this._trigger("search", event) === false) {
                return;
            }

            return this._search(value);
        },

        _search: function (value) {
            this.pending++;
            this.element.addClass("ui-autocomplete-loading");
            this.cancelSearch = false;

            this.source({ term: value }, this._response());
        },

        _response: function () {
            var index = ++this.requestIndex;

            return $.proxy(function (content) {
                if (index === this.requestIndex) {
                    this.__response(content);
                }

                this.pending--;
                if (!this.pending) {
                    this.element.removeClass("ui-autocomplete-loading");
                }
            }, this);
        },

        __response: function (content) {
            if (content) {
                content = this._normalize(content);
            }
            this._trigger("response", null, { content: content });
            if (!this.options.disabled && content && content.length && !this.cancelSearch) {
                this._suggest(content);
                this._trigger("open");
            } else {
                // use ._close() instead of .close() so we don't cancel future searches
                this._close();
            }
        },

        close: function (event) {
            this.cancelSearch = true;
            this._close(event);
        },

        _close: function (event) {
            if (this.menu.element.is(":visible")) {
                this.menu.element.hide();
                this.menu.blur();
                this.isNewMenu = true;
                this._trigger("close", event);
            }
        },

        _change: function (event) {
            if (this.previous !== this._value()) {
                this._trigger("change", event, { item: this.selectedItem });
            }
        },

        _normalize: function (items) {
            // assume all items have the right format when the first item is complete
            if (items.length && items[0].label && items[0].value) {
                return items;
            }
            return $.map(items, function (item) {
                if (typeof item === "string") {
                    return {
                        label: item,
                        value: item
                    };
                }
                return $.extend({
                    label: item.label || item.value,
                    value: item.value || item.label
                }, item);
            });
        },

        _suggest: function (items) {
            var ul = this.menu.element.empty();
            this._renderMenu(ul, items);
            this.isNewMenu = true;
            this.menu.refresh();

            // size and position menu
            ul.show();
            this._resizeMenu();
            ul.position($.extend({
                of: this.element
            }, this.options.position));

            if (this.options.autoFocus) {
                this.menu.next();
            }
        },

        _resizeMenu: function () {
            var ul = this.menu.element;
            ul.outerWidth(Math.max(
                // Firefox wraps long text (possibly a rounding bug)
                // so we add 1px to avoid the wrapping (#7513)
                ul.width("").outerWidth() + 1,
                this.element.outerWidth()
            ));
        },

        _renderMenu: function (ul, items) {
            var that = this;
            $.each(items, function (index, item) {
                that._renderItemData(ul, item);
            });
        },

        _renderItemData: function (ul, item) {
            return this._renderItem(ul, item).data("ui-autocomplete-item", item);
        },

        _renderItem: function (ul, item) {
            return $("<li>")
                .append($("<a>").text(item.label))
                .appendTo(ul);
        },

        _move: function (direction, event) {
            if (!this.menu.element.is(":visible")) {
                this.search(null, event);
                return;
            }
            if (this.menu.isFirstItem() && /^previous/.test(direction) ||
                this.menu.isLastItem() && /^next/.test(direction)) {
                this._value(this.term);
                this.menu.blur();
                return;
            }
            this.menu[direction](event);
        },

        widget: function () {
            return this.menu.element;
        },

        _value: function () {
            return this.valueMethod.apply(this.element, arguments);
        },

        _keyEvent: function (keyEvent, event) {
            if (!this.isMultiLine || this.menu.element.is(":visible")) {
                this._move(keyEvent, event);

                // prevents moving cursor to beginning/end of the text field in some browsers
                event.preventDefault();
            }
        }
    });

    $.extend($.ui.autocomplete, {
        escapeRegex: function (value) {
            return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
        },
        filter: function (array, term) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
            return $.grep(array, function (value) {
                return matcher.test(value.label || value.value || value);
            });
        }
    });


    // live region extension, adding a `messages` option
    // NOTE: This is an experimental API. We are still investigating
    // a full solution for string manipulation and internationalization.
    $.widget("ui.autocomplete", $.ui.autocomplete, {
        options: {
            messages: {
                noResults: "No search results.",
                results: function (amount) {
                    return amount + (amount > 1 ? " results are" : " result is") +
                        " available, use up and down arrow keys to navigate.";
                }
            }
        },

        __response: function (content) {
            var message;
            this._superApply(arguments);
            if (this.options.disabled || this.cancelSearch) {
                return;
            }
            if (content && content.length) {
                message = this.options.messages.results(content.length);
            } else {
                message = this.options.messages.noResults;
            }
            this.liveRegion.text(message);
        }
    });

}(jQuery));
(function ($, undefined) {

    $.widget("ui.menu", {
        version: "1.10.4",
        defaultElement: "<ul>",
        delay: 300,
        options: {
            icons: {
                submenu: "ui-icon-carat-1-e"
            },
            menus: "ul",
            position: {
                my: "left top",
                at: "right top"
            },
            role: "menu",

            // callbacks
            blur: null,
            focus: null,
            select: null
        },

        _create: function () {
            this.activeMenu = this.element;
            // flag used to prevent firing of the click handler
            // as the event bubbles up through nested menus
            this.mouseHandled = false;
            this.element
                .uniqueId()
                .addClass("ui-menu ui-widget ui-widget-content ui-corner-all")
                .toggleClass("ui-menu-icons", !!this.element.find(".ui-icon").length)
                .attr({
                    role: this.options.role,
                    tabIndex: 0
                })
                // need to catch all clicks on disabled menu
                // not possible through _on
                .on("click" + this.eventNamespace, $.proxy(function (event) {
                    if (this.options.disabled) {
                        event.preventDefault();
                    }
                }, this));

            if (this.options.disabled) {
                this.element
                    .addClass("ui-state-disabled")
                    .attr("aria-disabled", "true");
            }

            this._on({
                // Prevent focus from sticking to links inside menu after clicking
                // them (focus should always stay on UL during navigation).
                "mousedown .ui-menu-item > a": function (event) {
                    event.preventDefault();
                },
                "click .ui-state-disabled > a": function (event) {
                    event.preventDefault();
                },
                "click .ui-menu-item:has(a)": function (event) {
                    var target = $(event.target).closest(".ui-menu-item");
                    if (!this.mouseHandled && target.not(".ui-state-disabled").length) {
                        this.select(event);

                        // Only set the mouseHandled flag if the event will bubble, see #9469.
                        if (!event.isPropagationStopped()) {
                            this.mouseHandled = true;
                        }

                        // Open submenu on click
                        if (target.has(".ui-menu").length) {
                            this.expand(event);
                        } else if (!this.element.is(":focus") && $(this.document[0].activeElement).closest(".ui-menu").length) {

                            // Redirect focus to the menu
                            this.element.trigger("focus", [true]);

                            // If the active item is on the top level, let it stay active.
                            // Otherwise, blur the active item since it is no longer visible.
                            if (this.active && this.active.parents(".ui-menu").length === 1) {
                                clearTimeout(this.timer);
                            }
                        }
                    }
                },
                "mouseenter .ui-menu-item": function (event) {
                    var target = $(event.currentTarget);
                    // Remove ui-state-active class from siblings of the newly focused menu item
                    // to avoid a jump caused by adjacent elements both having a class with a border
                    target.siblings().children(".ui-state-active").removeClass("ui-state-active");
                    this.focus(event, target);
                },
                mouseleave: "collapseAll",
                "mouseleave .ui-menu": "collapseAll",
                focus: function (event, keepActiveItem) {
                    // If there's already an active item, keep it active
                    // If not, activate the first item
                    var item = this.active || this.element.children(".ui-menu-item").eq(0);

                    if (!keepActiveItem) {
                        this.focus(event, item);
                    }
                },
                blur: function (event) {
                    this._delay(function () {
                        if (!$.contains(this.element[0], this.document[0].activeElement)) {
                            this.collapseAll(event);
                        }
                    });
                },
                keydown: "_keydown"
            });

            this.refresh();

            // Clicks outside of a menu collapse any open menus
            this._on(this.document, {
                click: function (event) {
                    if (!$(event.target).closest(".ui-menu").length) {
                        this.collapseAll(event);
                    }

                    // Reset the mouseHandled flag
                    this.mouseHandled = false;
                }
            });
        },

        _destroy: function () {
            // Destroy (sub)menus
            this.element
                .removeAttr("aria-activedescendant")
                .find(".ui-menu").addBack()
                .removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons")
                .removeAttr("role")
                .removeAttr("tabIndex")
                .removeAttr("aria-labelledby")
                .removeAttr("aria-expanded")
                .removeAttr("aria-hidden")
                .removeAttr("aria-disabled")
                .removeUniqueId()
                .show();

            // Destroy menu items
            this.element.find(".ui-menu-item")
                .removeClass("ui-menu-item")
                .removeAttr("role")
                .removeAttr("aria-disabled")
                .children("a")
                .removeUniqueId()
                .removeClass("ui-corner-all ui-state-hover")
                .removeAttr("tabIndex")
                .removeAttr("role")
                .removeAttr("aria-haspopup")
                .children().each(function () {
                    var elem = $(this);
                    if (elem.data("ui-menu-submenu-carat")) {
                        elem.remove();
                    }
                });

            // Destroy menu dividers
            this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content");
        },

        _keydown: function (event) {
            var match, prev, character, skip, regex,
                preventDefault = true;

            function escape(value) {
                return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
            }

            switch (event.keyCode) {
                case $.ui.keyCode.PAGE_UP:
                    this.previousPage(event);
                    break;
                case $.ui.keyCode.PAGE_DOWN:
                    this.nextPage(event);
                    break;
                case $.ui.keyCode.HOME:
                    this._move("first", "first", event);
                    break;
                case $.ui.keyCode.END:
                    this._move("last", "last", event);
                    break;
                case $.ui.keyCode.UP:
                    this.previous(event);
                    break;
                case $.ui.keyCode.DOWN:
                    this.next(event);
                    break;
                case $.ui.keyCode.LEFT:
                    this.collapse(event);
                    break;
                case $.ui.keyCode.RIGHT:
                    if (this.active && !this.active.is(".ui-state-disabled")) {
                        this.expand(event);
                    }
                    break;
                case $.ui.keyCode.ENTER:
                case $.ui.keyCode.SPACE:
                    this._activate(event);
                    break;
                case $.ui.keyCode.ESCAPE:
                    this.collapse(event);
                    break;
                default:
                    preventDefault = false;
                    prev = this.previousFilter || "";
                    character = String.fromCharCode(event.keyCode);
                    skip = false;

                    clearTimeout(this.filterTimer);

                    if (character === prev) {
                        skip = true;
                    } else {
                        character = prev + character;
                    }

                    regex = new RegExp("^" + escape(character), "i");
                    match = this.activeMenu.children(".ui-menu-item").filter(function () {
                        return regex.test($(this).children("a").text());
                    });
                    match = skip && match.index(this.active.next()) !== -1 ?
                        this.active.nextAll(".ui-menu-item") :
                        match;

                    // If no matches on the current filter, reset to the last character pressed
                    // to move down the menu to the first item that starts with that character
                    if (!match.length) {
                        character = String.fromCharCode(event.keyCode);
                        regex = new RegExp("^" + escape(character), "i");
                        match = this.activeMenu.children(".ui-menu-item").filter(function () {
                            return regex.test($(this).children("a").text());
                        });
                    }

                    if (match.length) {
                        this.focus(event, match);
                        if (match.length > 1) {
                            this.previousFilter = character;
                            this.filterTimer = this._delay(function () {
                                delete this.previousFilter;
                            }, 1000);
                        } else {
                            delete this.previousFilter;
                        }
                    } else {
                        delete this.previousFilter;
                    }
            }

            if (preventDefault) {
                event.preventDefault();
            }
        },

        _activate: function (event) {
            if (!this.active.is(".ui-state-disabled")) {
                if (this.active.children("a[aria-haspopup='true']").length) {
                    this.expand(event);
                } else {
                    this.select(event);
                }
            }
        },

        refresh: function () {
            var menus,
                icon = this.options.icons.submenu,
                submenus = this.element.find(this.options.menus);

            this.element.toggleClass("ui-menu-icons", !!this.element.find(".ui-icon").length);

            // Initialize nested menus
            submenus.filter(":not(.ui-menu)")
                .addClass("ui-menu ui-widget ui-widget-content ui-corner-all")
                .hide()
                .attr({
                    role: this.options.role,
                    "aria-hidden": "true",
                    "aria-expanded": "false"
                })
                .each(function () {
                    var menu = $(this),
                        item = menu.prev("a"),
                        submenuCarat = $("<span>")
                            .addClass("ui-menu-icon ui-icon " + icon)
                            .data("ui-menu-submenu-carat", true);

                    item
                        .attr("aria-haspopup", "true")
                        .prepend(submenuCarat);
                    menu.attr("aria-labelledby", item.attr("id"));
                });

            menus = submenus.add(this.element);

            // Don't refresh list items that are already adapted
            menus.children(":not(.ui-menu-item):has(a)")
                .addClass("ui-menu-item")
                .attr("role", "presentation")
                .children("a")
                .uniqueId()
                .addClass("ui-corner-all")
                .attr({
                    tabIndex: -1,
                    role: this._itemRole()
                });

            // Initialize unlinked menu-items containing spaces and/or dashes only as dividers
            menus.children(":not(.ui-menu-item)").each(function () {
                var item = $(this);
                // hyphen, em dash, en dash
                if (!/[^\-\u2014\u2013\s]/.test(item.text())) {
                    item.addClass("ui-widget-content ui-menu-divider");
                }
            });

            // Add aria-disabled attribute to any disabled menu item
            menus.children(".ui-state-disabled").attr("aria-disabled", "true");

            // If the active item has been removed, blur the menu
            if (this.active && !$.contains(this.element[0], this.active[0])) {
                this.blur();
            }
        },

        _itemRole: function () {
            return {
                menu: "menuitem",
                listbox: "option"
            }[this.options.role];
        },

        _setOption: function (key, value) {
            if (key === "icons") {
                this.element.find(".ui-menu-icon")
                    .removeClass(this.options.icons.submenu)
                    .addClass(value.submenu);
            }
            this._super(key, value);
        },

        focus: function (event, item) {
            var nested, focused;
            this.blur(event, event && event.type === "focus");

            this._scrollIntoView(item);

            this.active = item.first();
            focused = this.active.children("a").addClass("ui-state-focus");
            // Only update aria-activedescendant if there's a role
            // otherwise we assume focus is managed elsewhere
            if (this.options.role) {
                this.element.attr("aria-activedescendant", focused.attr("id"));
            }

            // Highlight active parent menu item, if any
            this.active
                .parent()
                .closest(".ui-menu-item")
                .children("a").first()
                .addClass("ui-state-active");

            if (event && event.type === "keydown") {
                this._close();
            } else {
                this.timer = this._delay(function () {
                    this._close();
                }, this.delay);
            }

            nested = item.children(".ui-menu");
            if (nested.length && event && (/^mouse/.test(event.type))) {
                this._startOpening(nested);
            }
            this.activeMenu = item.parent();

            this._trigger("focus", event, { item: item });
        },

        _scrollIntoView: function (item) {
            var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
            if (this._hasScroll()) {
                borderTop = parseFloat($.css(this.activeMenu[0], "borderTopWidth")) || 0;
                paddingTop = parseFloat($.css(this.activeMenu[0], "paddingTop")) || 0;
                offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
                scroll = this.activeMenu.scrollTop();
                elementHeight = this.activeMenu.height();
                itemHeight = item.height();

                if (offset < 0) {
                    this.activeMenu.scrollTop(scroll + offset);
                } else if (offset + itemHeight > elementHeight) {
                    this.activeMenu.scrollTop(scroll + offset - elementHeight + itemHeight);
                }
            }
        },

        blur: function (event, fromFocus) {
            if (!fromFocus) {
                clearTimeout(this.timer);
            }

            if (!this.active) {
                return;
            }

            this.active.children("a").removeClass("ui-state-focus");
            this.active = null;

            this._trigger("blur", event, { item: this.active });
        },

        _startOpening: function (submenu) {
            clearTimeout(this.timer);

            // Don't open if already open fixes a Firefox bug that caused a .5 pixel
            // shift in the submenu position when mousing over the carat icon
            if (submenu.attr("aria-hidden") !== "true") {
                return;
            }

            this.timer = this._delay(function () {
                this._close();
                this._open(submenu);
            }, this.delay);
        },

        _open: function (submenu) {
            var position = $.extend({
                of: this.active
            }, this.options.position);

            clearTimeout(this.timer);
            this.element.find(".ui-menu").not(submenu.parents(".ui-menu"))
                .hide()
                .attr("aria-hidden", "true");

            submenu
                .show()
                .removeAttr("aria-hidden")
                .attr("aria-expanded", "true")
                .position(position);
        },

        collapseAll: function (event, all) {
            clearTimeout(this.timer);
            this.timer = this._delay(function () {
                // If we were passed an event, look for the submenu that contains the event
                var currentMenu = all ? this.element :
                    $(event && event.target).closest(this.element.find(".ui-menu"));

                // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
                if (!currentMenu.length) {
                    currentMenu = this.element;
                }

                this._close(currentMenu);

                this.blur(event);
                this.activeMenu = currentMenu;
            }, this.delay);
        },

        // With no arguments, closes the currently active menu - if nothing is active
        // it closes all menus.  If passed an argument, it will search for menus BELOW
        _close: function (startMenu) {
            if (!startMenu) {
                startMenu = this.active ? this.active.parent() : this.element;
            }

            startMenu
                .find(".ui-menu")
                .hide()
                .attr("aria-hidden", "true")
                .attr("aria-expanded", "false")
                .end()
                .find("a.ui-state-active")
                .removeClass("ui-state-active");
        },

        collapse: function (event) {
            var newItem = this.active &&
                this.active.parent().closest(".ui-menu-item", this.element);
            if (newItem && newItem.length) {
                this._close();
                this.focus(event, newItem);
            }
        },

        expand: function (event) {
            var newItem = this.active &&
                this.active
                    .children(".ui-menu ")
                    .children(".ui-menu-item")
                    .first();

            if (newItem && newItem.length) {
                this._open(newItem.parent());

                // Delay so Firefox will not hide activedescendant change in expanding submenu from AT
                this._delay(function () {
                    this.focus(event, newItem);
                });
            }
        },

        next: function (event) {
            this._move("next", "first", event);
        },

        previous: function (event) {
            this._move("prev", "last", event);
        },

        isFirstItem: function () {
            return this.active && !this.active.prevAll(".ui-menu-item").length;
        },

        isLastItem: function () {
            return this.active && !this.active.nextAll(".ui-menu-item").length;
        },

        _move: function (direction, filter, event) {
            var next;
            if (this.active) {
                if (direction === "first" || direction === "last") {
                    next = this.active
                    [direction === "first" ? "prevAll" : "nextAll"](".ui-menu-item")
                        .eq(-1);
                } else {
                    next = this.active
                    [direction + "All"](".ui-menu-item")
                        .eq(0);
                }
            }
            if (!next || !next.length || !this.active) {
                next = this.activeMenu.children(".ui-menu-item")[filter]();
            }

            this.focus(event, next);
        },

        nextPage: function (event) {
            var item, base, height;

            if (!this.active) {
                this.next(event);
                return;
            }
            if (this.isLastItem()) {
                return;
            }
            if (this._hasScroll()) {
                base = this.active.offset().top;
                height = this.element.height();
                this.active.nextAll(".ui-menu-item").each(function () {
                    item = $(this);
                    return item.offset().top - base - height < 0;
                });

                this.focus(event, item);
            } else {
                this.focus(event, this.activeMenu.children(".ui-menu-item")
                [!this.active ? "first" : "last"]());
            }
        },

        previousPage: function (event) {
            var item, base, height;
            if (!this.active) {
                this.next(event);
                return;
            }
            if (this.isFirstItem()) {
                return;
            }
            if (this._hasScroll()) {
                base = this.active.offset().top;
                height = this.element.height();
                this.active.prevAll(".ui-menu-item").each(function () {
                    item = $(this);
                    return item.offset().top - base + height > 0;
                });

                this.focus(event, item);
            } else {
                this.focus(event, this.activeMenu.children(".ui-menu-item").first());
            }
        },

        _hasScroll: function () {
            return this.element.outerHeight() < this.element.prop("scrollHeight");
        },

        select: function (event) {
            // TODO: It should never be possible to not have an active item at this
            // point, but the tests don't trigger mouseenter before click.
            this.active = this.active || $(event.target).closest(".ui-menu-item");
            var ui = { item: this.active };
            if (!this.active.has(".ui-menu").length) {
                this.collapseAll(event, true);
            }
            this._trigger("select", event, ui);
        }
    });

}(jQuery));
(function ($, undefined) {

    // number of pages in a slider
    // (how many times can you page up/down to go through the whole range)
    var numPages = 5;

    $.widget("ui.slider", $.ui.mouse, {
        version: "1.10.4",
        widgetEventPrefix: "slide",

        options: {
            animate: false,
            distance: 0,
            max: 100,
            min: 0,
            orientation: "horizontal",
            range: false,
            step: 1,
            value: 0,
            values: null,

            // callbacks
            change: null,
            slide: null,
            start: null,
            stop: null
        },

        _create: function () {
            this._keySliding = false;
            this._mouseSliding = false;
            this._animateOff = true;
            this._handleIndex = null;
            this._detectOrientation();
            this._mouseInit();

            this.element
                .addClass("ui-slider" +
                    " ui-slider-" + this.orientation +
                    " ui-widget" +
                    " ui-widget-content" +
                    " ui-corner-all");

            this._refresh();
            this._setOption("disabled", this.options.disabled);

            this._animateOff = false;
        },

        _refresh: function () {
            this._createRange();
            this._createHandles();
            this._setupEvents();
            this._refreshValue();
        },

        _createHandles: function () {
            var i, handleCount,
                options = this.options,
                existingHandles = this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),
                handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
                handles = [];

            handleCount = (options.values && options.values.length) || 1;

            if (existingHandles.length > handleCount) {
                existingHandles.slice(handleCount).remove();
                existingHandles = existingHandles.slice(0, handleCount);
            }

            for (i = existingHandles.length; i < handleCount; i++) {
                handles.push(handle);
            }

            this.handles = existingHandles.add($(handles.join("")).appendTo(this.element));

            this.handle = this.handles.eq(0);

            this.handles.each(function (i) {
                $(this).data("ui-slider-handle-index", i);
            });
        },

        _createRange: function () {
            var options = this.options,
                classes = "";

            if (options.range) {
                if (options.range === true) {
                    if (!options.values) {
                        options.values = [this._valueMin(), this._valueMin()];
                    } else if (options.values.length && options.values.length !== 2) {
                        options.values = [options.values[0], options.values[0]];
                    } else if (Array.isArray(options.values)) {
                        options.values = options.values.slice(0);
                    }
                }

                if (!this.range || !this.range.length) {
                    this.range = $("<div></div>")
                        .appendTo(this.element);

                    classes = "ui-slider-range" +
                        // note: this isn't the most fittingly semantic framework class for this element,
                        // but worked best visually with a variety of themes
                        " ui-widget-header ui-corner-all";
                } else {
                    this.range.removeClass("ui-slider-range-min ui-slider-range-max")
                        // Handle range switching from true to min/max
                        .css({
                            "left": "",
                            "bottom": ""
                        });
                }

                this.range.addClass(classes +
                    ((options.range === "min" || options.range === "max") ? " ui-slider-range-" + options.range : ""));
            } else {
                if (this.range) {
                    this.range.remove();
                }
                this.range = null;
            }
        },

        _setupEvents: function () {
            var elements = this.handles.add(this.range).filter("a");
            this._off(elements);
            this._on(elements, this._handleEvents);
            this._hoverable(elements);
            this._focusable(elements);
        },

        _destroy: function () {
            this.handles.remove();
            if (this.range) {
                this.range.remove();
            }

            this.element
                .removeClass("ui-slider" +
                    " ui-slider-horizontal" +
                    " ui-slider-vertical" +
                    " ui-widget" +
                    " ui-widget-content" +
                    " ui-corner-all");

            this._mouseDestroy();
        },

        _mouseCapture: function (event) {
            var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
                that = this,
                o = this.options;

            if (o.disabled) {
                return false;
            }

            this.elementSize = {
                width: this.element.outerWidth(),
                height: this.element.outerHeight()
            };
            this.elementOffset = this.element.offset();

            position = { x: event.pageX, y: event.pageY };
            normValue = this._normValueFromMouse(position);
            distance = this._valueMax() - this._valueMin() + 1;
            this.handles.each(function (i) {
                var thisDistance = Math.abs(normValue - that.values(i));
                if ((distance > thisDistance) ||
                    (distance === thisDistance &&
                        (i === that._lastChangedValue || that.values(i) === o.min))) {
                    distance = thisDistance;
                    closestHandle = $(this);
                    index = i;
                }
            });

            allowed = this._start(event, index);
            if (allowed === false) {
                return false;
            }
            this._mouseSliding = true;

            this._handleIndex = index;

            closestHandle
                .addClass("ui-state-active")
                .trigger("focus");

            offset = closestHandle.offset();
            mouseOverHandle = !$(event.target).parents().addBack().is(".ui-slider-handle");
            this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
                left: event.pageX - offset.left - (closestHandle.width() / 2),
                top: event.pageY - offset.top -
                    (closestHandle.height() / 2) -
                    (parseInt(closestHandle.css("borderTopWidth"), 10) || 0) -
                    (parseInt(closestHandle.css("borderBottomWidth"), 10) || 0) +
                    (parseInt(closestHandle.css("marginTop"), 10) || 0)
            };

            if (!this.handles.hasClass("ui-state-hover")) {
                this._slide(event, index, normValue);
            }
            this._animateOff = true;
            return true;
        },

        _mouseStart: function () {
            return true;
        },

        _mouseDrag: function (event) {
            var position = { x: event.pageX, y: event.pageY },
                normValue = this._normValueFromMouse(position);

            this._slide(event, this._handleIndex, normValue);

            return false;
        },

        _mouseStop: function (event) {
            this.handles.removeClass("ui-state-active");
            this._mouseSliding = false;

            this._stop(event, this._handleIndex);
            this._change(event, this._handleIndex);

            this._handleIndex = null;
            this._clickOffset = null;
            this._animateOff = false;

            return false;
        },

        _detectOrientation: function () {
            this.orientation = (this.options.orientation === "vertical") ? "vertical" : "horizontal";
        },

        _normValueFromMouse: function (position) {
            var pixelTotal,
                pixelMouse,
                percentMouse,
                valueTotal,
                valueMouse;

            if (this.orientation === "horizontal") {
                pixelTotal = this.elementSize.width;
                pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0);
            } else {
                pixelTotal = this.elementSize.height;
                pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0);
            }

            percentMouse = (pixelMouse / pixelTotal);
            if (percentMouse > 1) {
                percentMouse = 1;
            }
            if (percentMouse < 0) {
                percentMouse = 0;
            }
            if (this.orientation === "vertical") {
                percentMouse = 1 - percentMouse;
            }

            valueTotal = this._valueMax() - this._valueMin();
            valueMouse = this._valueMin() + percentMouse * valueTotal;

            return this._trimAlignValue(valueMouse);
        },

        _start: function (event, index) {
            var uiHash = {
                handle: this.handles[index],
                value: this.value()
            };
            if (this.options.values && this.options.values.length) {
                uiHash.value = this.values(index);
                uiHash.values = this.values();
            }
            return this._trigger("start", event, uiHash);
        },

        _slide: function (event, index, newVal) {
            var otherVal,
                newValues,
                allowed;

            if (this.options.values && this.options.values.length) {
                otherVal = this.values(index ? 0 : 1);

                if ((this.options.values.length === 2 && this.options.range === true) &&
                    ((index === 0 && newVal > otherVal) || (index === 1 && newVal < otherVal))
                ) {
                    newVal = otherVal;
                }

                if (newVal !== this.values(index)) {
                    newValues = this.values();
                    newValues[index] = newVal;
                    // A slide can be canceled by returning false from the slide callback
                    allowed = this._trigger("slide", event, {
                        handle: this.handles[index],
                        value: newVal,
                        values: newValues
                    });
                    otherVal = this.values(index ? 0 : 1);
                    if (allowed !== false) {
                        this.values(index, newVal);
                    }
                }
            } else {
                if (newVal !== this.value()) {
                    // A slide can be canceled by returning false from the slide callback
                    allowed = this._trigger("slide", event, {
                        handle: this.handles[index],
                        value: newVal
                    });
                    if (allowed !== false) {
                        this.value(newVal);
                    }
                }
            }
        },

        _stop: function (event, index) {
            var uiHash = {
                handle: this.handles[index],
                value: this.value()
            };
            if (this.options.values && this.options.values.length) {
                uiHash.value = this.values(index);
                uiHash.values = this.values();
            }

            this._trigger("stop", event, uiHash);
        },

        _change: function (event, index) {
            if (!this._keySliding && !this._mouseSliding) {
                var uiHash = {
                    handle: this.handles[index],
                    value: this.value()
                };
                if (this.options.values && this.options.values.length) {
                    uiHash.value = this.values(index);
                    uiHash.values = this.values();
                }

                //store the last changed value index for reference when handles overlap
                this._lastChangedValue = index;

                this._trigger("change", event, uiHash);
            }
        },

        value: function (newValue) {
            if (arguments.length) {
                this.options.value = this._trimAlignValue(newValue);
                this._refreshValue();
                this._change(null, 0);
                return;
            }

            return this._value();
        },

        values: function (index, newValue) {
            var vals,
                newValues,
                i;

            if (arguments.length > 1) {
                this.options.values[index] = this._trimAlignValue(newValue);
                this._refreshValue();
                this._change(null, index);
                return;
            }

            if (arguments.length) {
                if (Array.isArray(arguments[0])) {
                    vals = this.options.values;
                    newValues = arguments[0];
                    for (i = 0; i < vals.length; i += 1) {
                        vals[i] = this._trimAlignValue(newValues[i]);
                        this._change(null, i);
                    }
                    this._refreshValue();
                } else {
                    if (this.options.values && this.options.values.length) {
                        return this._values(index);
                    } else {
                        return this.value();
                    }
                }
            } else {
                return this._values();
            }
        },

        _setOption: function (key, value) {
            var i,
                valsLength = 0;

            if (key === "range" && this.options.range === true) {
                if (value === "min") {
                    this.options.value = this._values(0);
                    this.options.values = null;
                } else if (value === "max") {
                    this.options.value = this._values(this.options.values.length - 1);
                    this.options.values = null;
                }
            }

            if (Array.isArray(this.options.values)) {
                valsLength = this.options.values.length;
            }

            $.Widget.prototype._setOption.apply(this, arguments);

            switch (key) {
                case "orientation":
                    this._detectOrientation();
                    this.element
                        .removeClass("ui-slider-horizontal ui-slider-vertical")
                        .addClass("ui-slider-" + this.orientation);
                    this._refreshValue();
                    break;
                case "value":
                    this._animateOff = true;
                    this._refreshValue();
                    this._change(null, 0);
                    this._animateOff = false;
                    break;
                case "values":
                    this._animateOff = true;
                    this._refreshValue();
                    for (i = 0; i < valsLength; i += 1) {
                        this._change(null, i);
                    }
                    this._animateOff = false;
                    break;
                case "min":
                case "max":
                    this._animateOff = true;
                    this._refreshValue();
                    this._animateOff = false;
                    break;
                case "range":
                    this._animateOff = true;
                    this._refresh();
                    this._animateOff = false;
                    break;
            }
        },

        //internal value getter
        // _value() returns value trimmed by min and max, aligned by step
        _value: function () {
            var val = this.options.value;
            val = this._trimAlignValue(val);

            return val;
        },

        //internal values getter
        // _values() returns array of values trimmed by min and max, aligned by step
        // _values( index ) returns single value trimmed by min and max, aligned by step
        _values: function (index) {
            var val,
                vals,
                i;

            if (arguments.length) {
                val = this.options.values[index];
                val = this._trimAlignValue(val);

                return val;
            } else if (this.options.values && this.options.values.length) {
                // .slice() creates a copy of the array
                // this copy gets trimmed by min and max and then returned
                vals = this.options.values.slice();
                for (i = 0; i < vals.length; i += 1) {
                    vals[i] = this._trimAlignValue(vals[i]);
                }

                return vals;
            } else {
                return [];
            }
        },

        // returns the step-aligned value that val is closest to, between (inclusive) min and max
        _trimAlignValue: function (val) {
            if (val <= this._valueMin()) {
                return this._valueMin();
            }
            if (val >= this._valueMax()) {
                return this._valueMax();
            }
            var step = (this.options.step > 0) ? this.options.step : 1,
                valModStep = (val - this._valueMin()) % step,
                alignValue = val - valModStep;

            if (Math.abs(valModStep) * 2 >= step) {
                alignValue += (valModStep > 0) ? step : (-step);
            }

            // Since JavaScript has problems with large floats, round
            // the final value to 5 digits after the decimal point (see #4124)
            return parseFloat(alignValue.toFixed(5));
        },

        _valueMin: function () {
            return this.options.min;
        },

        _valueMax: function () {
            return this.options.max;
        },

        _refreshValue: function () {
            var lastValPercent, valPercent, value, valueMin, valueMax,
                oRange = this.options.range,
                o = this.options,
                that = this,
                animate = (!this._animateOff) ? o.animate : false,
                _set = {};

            if (this.options.values && this.options.values.length) {
                this.handles.each(function (i) {
                    valPercent = (that.values(i) - that._valueMin()) / (that._valueMax() - that._valueMin()) * 100;
                    _set[that.orientation === "horizontal" ? "left" : "bottom"] = valPercent + "%";
                    $(this).stop(1, 1)[animate ? "animate" : "css"](_set, o.animate);
                    if (that.options.range === true) {
                        if (that.orientation === "horizontal") {
                            if (i === 0) {
                                that.range.stop(1, 1)[animate ? "animate" : "css"]({ left: valPercent + "%" }, o.animate);
                            }
                            if (i === 1) {
                                that.range[animate ? "animate" : "css"]({ width: (valPercent - lastValPercent) + "%" }, { queue: false, duration: o.animate });
                            }
                        } else {
                            if (i === 0) {
                                that.range.stop(1, 1)[animate ? "animate" : "css"]({ bottom: (valPercent) + "%" }, o.animate);
                            }
                            if (i === 1) {
                                that.range[animate ? "animate" : "css"]({ height: (valPercent - lastValPercent) + "%" }, { queue: false, duration: o.animate });
                            }
                        }
                    }
                    lastValPercent = valPercent;
                });
            } else {
                value = this.value();
                valueMin = this._valueMin();
                valueMax = this._valueMax();
                valPercent = (valueMax !== valueMin) ?
                    (value - valueMin) / (valueMax - valueMin) * 100 :
                    0;
                _set[this.orientation === "horizontal" ? "left" : "bottom"] = valPercent + "%";
                this.handle.stop(1, 1)[animate ? "animate" : "css"](_set, o.animate);

                if (oRange === "min" && this.orientation === "horizontal") {
                    this.range.stop(1, 1)[animate ? "animate" : "css"]({ width: valPercent + "%" }, o.animate);
                }
                if (oRange === "max" && this.orientation === "horizontal") {
                    this.range[animate ? "animate" : "css"]({ width: (100 - valPercent) + "%" }, { queue: false, duration: o.animate });
                }
                if (oRange === "min" && this.orientation === "vertical") {
                    this.range.stop(1, 1)[animate ? "animate" : "css"]({ height: valPercent + "%" }, o.animate);
                }
                if (oRange === "max" && this.orientation === "vertical") {
                    this.range[animate ? "animate" : "css"]({ height: (100 - valPercent) + "%" }, { queue: false, duration: o.animate });
                }
            }
        },

        _handleEvents: {
            keydown: function (event) {
                var allowed, curVal, newVal, step,
                    index = $(event.target).data("ui-slider-handle-index");

                switch (event.keyCode) {
                    case $.ui.keyCode.HOME:
                    case $.ui.keyCode.END:
                    case $.ui.keyCode.PAGE_UP:
                    case $.ui.keyCode.PAGE_DOWN:
                    case $.ui.keyCode.UP:
                    case $.ui.keyCode.RIGHT:
                    case $.ui.keyCode.DOWN:
                    case $.ui.keyCode.LEFT:
                        event.preventDefault();
                        if (!this._keySliding) {
                            this._keySliding = true;
                            $(event.target).addClass("ui-state-active");
                            allowed = this._start(event, index);
                            if (allowed === false) {
                                return;
                            }
                        }
                        break;
                }

                step = this.options.step;
                if (this.options.values && this.options.values.length) {
                    curVal = newVal = this.values(index);
                } else {
                    curVal = newVal = this.value();
                }

                switch (event.keyCode) {
                    case $.ui.keyCode.HOME:
                        newVal = this._valueMin();
                        break;
                    case $.ui.keyCode.END:
                        newVal = this._valueMax();
                        break;
                    case $.ui.keyCode.PAGE_UP:
                        newVal = this._trimAlignValue(curVal + ((this._valueMax() - this._valueMin()) / numPages));
                        break;
                    case $.ui.keyCode.PAGE_DOWN:
                        newVal = this._trimAlignValue(curVal - ((this._valueMax() - this._valueMin()) / numPages));
                        break;
                    case $.ui.keyCode.UP:
                    case $.ui.keyCode.RIGHT:
                        if (curVal === this._valueMax()) {
                            return;
                        }
                        newVal = this._trimAlignValue(curVal + step);
                        break;
                    case $.ui.keyCode.DOWN:
                    case $.ui.keyCode.LEFT:
                        if (curVal === this._valueMin()) {
                            return;
                        }
                        newVal = this._trimAlignValue(curVal - step);
                        break;
                }

                this._slide(event, index, newVal);
            },
            click: function (event) {
                event.preventDefault();
            },
            keyup: function (event) {
                var index = $(event.target).data("ui-slider-handle-index");

                if (this._keySliding) {
                    this._keySliding = false;
                    this._stop(event, index);
                    this._change(event, index);
                    $(event.target).removeClass("ui-state-active");
                }
            }
        }

    });

}(jQuery));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.maskedinput.min.js
/* Version ="2" */

/*
jQuery Masked Input Plugin
Copyright (c) 2007 - 2014 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
Version: 1.4.0
 */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}
(function(a){var b,c=navigator.userAgent,d=/iphone/i.test(c),e=/chrome/i.test(c),f=/android/i.test(c);a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},autoclear:!0,dataName:"rawMaskFn",placeholder:"_"},a.fn.extend({caret:function(a,b){var c;if(0!==this.length&&!this.is(":hidden"))
return"number"==typeof a?(b="number"==typeof b?b:a,this.each(function(){this.setSelectionRange?this.setSelectionRange(a,b):this.createTextRange&&(c=this.createTextRange(),c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.trigger("select"))})):(this[0].setSelectionRange?(a=this[0].selectionStart,b=this[0].selectionEnd):document.selection&&document.selection.createRange&&(c=document.selection.createRange(),a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length),{begin:a,end:b})},unmask:function(){return this.trigger("unmask")},mask:function(c,g){var h,i,j,k,l,m,n,o;if(!c&&this.length>0){h=a(this[0]);var p=h.data(a.mask.dataName);return p?p():void 0}
return g=a.extend({autoclear:a.mask.autoclear,placeholder:a.mask.placeholder,completed:null},g),i=a.mask.definitions,j=[],k=n=c.length,l=null,a.each(c.split(""),function(a,b){"?"==b?(n--,k=a):i[b]?(j.push(new RegExp(i[b])),null===l&&(l=j.length-1),k>a&&(m=j.length-1)):j.push(null)}),this.trigger("unmask").each(function(){function h(){if(g.completed){for(var a=l;m>=a;a++)
if(j[a]&&C[a]===p(a))
return;g.completed.call(B)}}
function p(a){return g.placeholder.charAt(a<g.placeholder.length?a:0)}
function q(a){for(;++a<n&&!j[a];);return a}
function r(a){for(;--a>=0&&!j[a];);return a}
function s(a,b){var c,d;if(!(0>a)){for(c=a,d=q(b);n>c;c++)
if(j[c]){if(!(n>d&&j[c].test(C[d])))
break;C[c]=C[d],C[d]=p(d),d=q(d)}
z(),B.caret(Math.max(l,a))}}
function t(a){var b,c,d,e;for(b=a,c=p(a);n>b;b++)
if(j[b]){if(d=q(b),e=C[b],C[b]=c,!(n>d&&j[d].test(e)))
break;c=e}}
function u(){var a=B.val(),b=B.caret();if(a.length<o.length){for(A(!0);b.begin>0&&!j[b.begin-1];)
b.begin--;if(0===b.begin)
for(;b.begin<l&&!j[b.begin];)
b.begin++;B.caret(b.begin,b.begin)}else{for(A(!0);b.begin<n&&!j[b.begin];)
b.begin++;B.caret(b.begin,b.begin)}
h()}
function v(){A(),B.val()!=E&&B.trigger("change")}
function w(a){if(!B.prop("readonly")){var b,c,e,f=a.which||a.keyCode;o=B.val(),8===f||46===f||d&&127===f?(b=B.caret(),c=b.begin,e=b.end,e-c===0&&(c=46!==f?r(c):e=q(c-1),e=46===f?q(e):e),y(c,e),s(c,e-1),a.preventDefault()):13===f?v.call(this,a):27===f&&(B.val(E),B.caret(0,A()),a.preventDefault())}}
function x(b){if(!B.prop("readonly")){var c,d,e,g=b.which||b.keyCode,i=B.caret();if(!(b.ctrlKey||b.altKey||b.metaKey||32>g)&&g&&13!==g){if(i.end-i.begin!==0&&(y(i.begin,i.end),s(i.begin,i.end-1)),c=q(i.begin-1),n>c&&(d=String.fromCharCode(g),j[c].test(d))){if(t(c),C[c]=d,z(),e=q(c),f){var k=function(){a.proxy(a.fn.caret,B,e)()};setTimeout(k,0)}else
B.caret(e);i.begin<=m&&h()}
b.preventDefault()}}}
function y(a,b){var c;for(c=a;b>c&&n>c;c++)
j[c]&&(C[c]=p(c))}
function z(){B.val(C.join(""))}
function A(a){var b,c,d,e=B.val(),f=-1;for(b=0,d=0;n>b;b++)
if(j[b]){for(C[b]=p(b);d++<e.length;)
if(c=e.charAt(d-1),j[b].test(c)){C[b]=c,f=b;break}
if(d>e.length){y(b+1,n);break}}else
C[b]===e.charAt(d)&&d++,k>b&&(f=b);return a?z():k>f+1?g.autoclear||C.join("")===D?(B.val()&&B.val(""),y(0,n)):z():(z(),B.val(B.val().substring(0,f+1))),k?b:l}
var B=a(this),C=a.map(c.split(""),function(a,b){return"?"!=a?i[a]?p(b):a:void 0}),D=C.join(""),E=B.val();B.data(a.mask.dataName,function(){return a.map(C,function(a,b){return j[b]&&a!=p(b)?a:null}).join("")}),B.one("unmask",function(){B.off(".mask").removeData(a.mask.dataName)}).on("focus.mask",function(){if(!B.prop("readonly")){clearTimeout(b);var a;E=B.val(),a=A(),b=setTimeout(function(){z(),a==c.replace("?","").length?B.caret(0,a):B.caret(a)},10)}}).on("blur.mask",v).on("keydown.mask",w).on("keypress.mask",x).on("input.mask paste.mask",function(){B.prop("readonly")||setTimeout(function(){var a=A(!0);B.caret(a),h()},0)}),e&&f&&B.off("input.mask").on("input.mask",u),A()})}})});
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.placeholder.js
/* version = "2" */

/*! http://mths.be/placeholder v2.0.8 by @mathias */
;(function(window, document, $) {

	// Opera Mini v7 doesn’t support placeholder although its DOM seems to indicate so
	var isOperaMini = Object.prototype.toString.call(window.operamini) == '[object OperaMini]';
	var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini;
	var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini;
	var prototype = $.fn;
	var valHooks = $.valHooks;
	var propHooks = $.propHooks;
	var hooks;
	var placeholder;

	if (isInputSupported && isTextareaSupported) {

		placeholder = prototype.placeholder = function() {
			return this;
		};

		placeholder.input = placeholder.textarea = true;

	} else {

		placeholder = prototype.placeholder = function() {
			var $this = this;
			$this
				.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
				.not('.placeholder')
				.on({
					'focus.placeholder': clearPlaceholder,
					'blur.placeholder': setPlaceholder
				})
				.data('placeholder-enabled', true)
				.trigger('blur.placeholder');
			return $this;
		};

		placeholder.input = isInputSupported;
		placeholder.textarea = isTextareaSupported;

		hooks = {
			'get': function(element) {
				var $element = $(element);

				var $passwordInput = $element.data('placeholder-password');
				if ($passwordInput) {
					return $passwordInput[0].value;
				}

				return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
			},
			'set': function(element, value) {
				var $element = $(element);

				var $passwordInput = $element.data('placeholder-password');
				if ($passwordInput) {
					return $passwordInput[0].value = value;
				}

				if (!$element.data('placeholder-enabled')) {
					return element.value = value;
				}
				if (value == '') {
					element.value = value;
					// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
					if (element != safeActiveElement()) {
						// We can't use `triggerHandler` here because of dummy text/password inputs :(
						setPlaceholder.call(element);
					}
				} else if ($element.hasClass('placeholder')) {
					clearPlaceholder.call(element, true, value) || (element.value = value);
				} else {
					element.value = value;
				}
				// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
				return $element;
			}
		};

		if (!isInputSupported) {
			valHooks.input = hooks;
			propHooks.value = hooks;
		}
		if (!isTextareaSupported) {
			valHooks.textarea = hooks;
			propHooks.value = hooks;
		}

		$(function() {
			// Look for forms
			$(document).on('form', 'submit.placeholder', function() {
				// Clear the placeholder values so they don't get submitted
				var $inputs = $('.placeholder', this).each(clearPlaceholder);
				setTimeout(function() {
					$inputs.each(setPlaceholder);
				}, 10);
			});
		});

		// Clear placeholder values upon page reload
		$(window).on('beforeunload.placeholder', function() {
			$('.placeholder').each(function() {
				this.value = '';
			});
		});

	}

	function args(elem) {
		// Return an object of element attributes
		var newAttrs = {};
		var rinlinejQuery = /^jQuery\d+$/;
		$.each(elem.attributes, function(i, attr) {
			if (attr.specified && !rinlinejQuery.test(attr.name)) {
				newAttrs[attr.name] = attr.value;
			}
		});
		return newAttrs;
	}

	function clearPlaceholder(event, value) {
		var input = this;
		var $input = $(input);
		if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
			if ($input.data('placeholder-password')) {
				$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
				// If `clearPlaceholder` was called from `$.valHooks.input.set`
				if (event === true) {
					return $input[0].value = value;
				}
				$input.trigger("focus");
			} else {
				input.value = '';
				$input.removeClass('placeholder');
				input == safeActiveElement() && input.trigger("select");
			}
		}
	}

	function setPlaceholder() {
		var $replacement;
		var input = this;
		var $input = $(input);
		var id = this.id;
		if (input.value == '') {
			if (input.type == 'password') {
				if (!$input.data('placeholder-textinput')) {
					try {
						$replacement = $input.clone().attr({ 'type': 'text' });
					} catch(e) {
						$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
					}
					$replacement
						.removeAttr('name')
						.data({
							'placeholder-password': $input,
							'placeholder-id': id
						})
						.on('focus.placeholder', clearPlaceholder);
					$input
						.data({
							'placeholder-textinput': $replacement,
							'placeholder-id': id
						})
						.before($replacement);
				}
				$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
				// Note: `$input[0] != input` now!
			}
			$input.addClass('placeholder');
			$input[0].value = $input.attr('placeholder');
		} else {
			$input.removeClass('placeholder');
		}
	}

	function safeActiveElement() {
		// Avoid IE9 `document.activeElement` of death
		// https://github.com/mathiasbynens/jquery-placeholder/pull/99
		try {
			return document.activeElement;
		} catch (exception) {}
	}

}(this, document, jQuery));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\jquery.cookie.js
/*!version = "3"
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    };

    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }; 

    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }; 

    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape...
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }

        try {
            // Replace server-side written pluses with spaces.
            // If we can't decode the cookie, ignore it, it's unusable.
            // If we can't parse the cookie, ignore it, it's unusable.
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch (e) { }
    };

    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return typeof (converter) === "function" ? converter(value) : value;
    };

    var config = $.cookie = function (key, value, options) {

        // Write

        if (value !== undefined && typeof value !== "function") {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setTime(+t + days * 864e+5);
            }

            return (document.cookie = [
                encode(key), '=', stringifyCookieValue(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // Read

        var result = key ? undefined : {};

        // To prevent the for loop in the first place assign an empty array
        // in case there are no cookies at all. Also prevents odd result when
        // calling $.cookie().
        var cookies = document.cookie ? document.cookie.split('; ') : [];

        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = parts.join('=');

            if (key && key === name) {
                // If second argument (value) is a function it's a converter...
                result = read(cookie, value);
                break;
            }

            // Prevent storing a cookie that we couldn't decode.
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) === undefined) {
            return false;
        }

        // Must not alter options, thus extending a fresh object...
        $.cookie(key, '', $.extend({}, options, { expires: -1 }));
        return !$.cookie(key);
    };

}));

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\modernizr.custom.08842.js
/* Modernizr 2.8.3 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-cssanimations-csstransforms-localstorage-shiv-cssclasses-prefixed-testprop-testallprops-domprefixes-load
 */
; window.Modernizr = function (a, b, c) { function x(a) { j.cssText = a } function y(a, b) { return x(prefixes.join(a + ";") + (b || "")) } function z(a, b) { return typeof a === b } function A(a, b) { return !!~("" + a).indexOf(b) } function B(a, b) { for (var d in a) { var e = a[d]; if (!A(e, "-") && j[e] !== c) return b == "pfx" ? e : !0 } return !1 } function C(a, b, d) { for (var e in a) { var f = b[a[e]]; if (f !== c) return d === !1 ? a[e] : z(f, "function") ? f.bind(d || b) : f } return !1 } function D(a, b, c) { var d = a.charAt(0).toUpperCase() + a.slice(1), e = (a + " " + n.join(d + " ") + d).split(" "); return z(b, "string") || z(b, "undefined") ? B(e, b) : (e = (a + " " + o.join(d + " ") + d).split(" "), C(e, b, c)) } var d = "2.8.3", e = {}, f = !0, g = b.documentElement, h = "modernizr", i = b.createElement(h), j = i.style, k, l = {}.toString, m = "Webkit Moz O ms", n = m.split(" "), o = m.toLowerCase().split(" "), p = {}, q = {}, r = {}, s = [], t = s.slice, u, v = {}.hasOwnProperty, w; !z(v, "undefined") && !z(v.call, "undefined") ? w = function (a, b) { return v.call(a, b) } : w = function (a, b) { return b in a && z(a.constructor.prototype[b], "undefined") }, Function.prototype.bind || (Function.prototype.bind = function (b) { var c = this; if (typeof c != "function") throw new TypeError; var d = t.call(arguments, 1), e = function () { if (this instanceof e) { var a = function () { }; a.prototype = c.prototype; var f = new a, g = c.apply(f, d.concat(t.call(arguments))); return Object(g) === g ? g : f } return c.apply(b, d.concat(t.call(arguments))) }; return e }), p.cssanimations = function () { return D("animationName") }, p.csstransforms = function () { return !!D("transform") }, p.localstorage = function () { try { return localStorage.setItem(h, h), localStorage.removeItem(h), !0 } catch (a) { return !1 } }; for (var E in p) w(p, E) && (u = E.toLowerCase(), e[u] = p[E](), s.push((e[u] ? "" : "no-") + u)); return e.addTest = function (a, b) { if (typeof a == "object") for (var d in a) w(a, d) && e.addTest(d, a[d]); else { a = a.toLowerCase(); if (e[a] !== c) return e; b = typeof b == "function" ? b() : b, typeof f != "undefined" && f && (g.className += " " + (b ? "" : "no-") + a), e[a] = b } return e }, x(""), i = k = null, function (a, b) { function l(a, b) { var c = a.createElement("p"), d = a.getElementsByTagName("head")[0] || a.documentElement; return c.innerHTML = "x<style>" + b + "</style>", d.insertBefore(c.lastChild, d.firstChild) } function m() { var a = s.elements; return typeof a == "string" ? a.split(" ") : a } function n(a) { var b = j[a[h]]; return b || (b = {}, i++ , a[h] = i, j[i] = b), b } function o(a, c, d) { c || (c = b); if (k) return c.createElement(a); d || (d = n(c)); var g; return d.cache[a] ? g = d.cache[a].cloneNode() : f.test(a) ? g = (d.cache[a] = d.createElem(a)).cloneNode() : g = d.createElem(a), g.canHaveChildren && !e.test(a) && !g.tagUrn ? d.frag.appendChild(g) : g } function p(a, c) { a || (a = b); if (k) return a.createDocumentFragment(); c = c || n(a); var d = c.frag.cloneNode(), e = 0, f = m(), g = f.length; for (; e < g; e++)d.createElement(f[e]); return d } function q(a, b) { b.cache || (b.cache = {}, b.createElem = a.createElement, b.createFrag = a.createDocumentFragment, b.frag = b.createFrag()), a.createElement = function (c) { return s.shivMethods ? o(c, a, b) : b.createElem(c) }, a.createDocumentFragment = Function("h,f", "return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&(" + m().join().replace(/[\w\-]+/g, function (a) { return b.createElem(a), b.frag.createElement(a), 'c("' + a + '")' }) + ");return n}")(s, b.frag) } function r(a) { a || (a = b); var c = n(a); return s.shivCSS && !g && !c.hasCSS && (c.hasCSS = !!l(a, "article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")), k || q(a, c), a } var c = "3.7.0", d = a.html5 || {}, e = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i, f = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i, g, h = "_html5shiv", i = 0, j = {}, k; (function () { try { var a = b.createElement("a"); a.innerHTML = "<xyz></xyz>", g = "hidden" in a, k = a.childNodes.length == 1 || function () { b.createElement("a"); var a = b.createDocumentFragment(); return typeof a.cloneNode == "undefined" || typeof a.createDocumentFragment == "undefined" || typeof a.createElement == "undefined" }() } catch (c) { g = !0, k = !0 } })(); var s = { elements: d.elements || "abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video", version: c, shivCSS: d.shivCSS !== !1, supportsUnknownElements: k, shivMethods: d.shivMethods !== !1, type: "default", shivDocument: r, createElement: o, createDocumentFragment: p }; a.html5 = s, r(b) }(this, b), e._version = d, e._domPrefixes = o, e._cssomPrefixes = n, e.testProp = function (a) { return B([a]) }, e.testAllProps = D, e.prefixed = function (a, b, c) { return b ? D(a, b, c) : D(a, "pfx") }, g.className = g.className.replace(/(^|\s)no-js(\s|$)/, "$1$2") + (f ? " js " + s.join(" ") : ""), e }(this, this.document), function (a, b, c) { function d(a) { return "[object Function]" == o.call(a) } function e(a) { return "string" == typeof a } function f() { } function g(a) { return !a || "loaded" == a || "complete" == a || "uninitialized" == a } function h() { var a = p.shift(); q = 1, a ? a.t ? m(function () { ("c" == a.t ? B.injectCss : B.injectJs)(a.s, 0, a.a, a.x, a.e, 1) }, 0) : (a(), h()) : q = 0 } function i(a, c, d, e, f, i, j) { function k(b) { if (!o && g(l.readyState) && (u.r = o = 1, !q && h(), l.onload = l.onreadystatechange = null, b)) { "img" != a && m(function () { t.removeChild(l) }, 50); for (var d in y[c]) y[c].hasOwnProperty(d) && y[c][d].onload() } } var j = j || B.errorTimeout, l = b.createElement(a), o = 0, r = 0, u = { t: d, s: c, e: f, a: i, x: j }; 1 === y[c] && (r = 1, y[c] = []), "object" == a ? l.data = c : (l.src = c, l.type = a), l.width = l.height = "0", l.onerror = l.onload = l.onreadystatechange = function () { k.call(this, r) }, p.splice(e, 0, u), "img" != a && (r || 2 === y[c] ? (t.insertBefore(l, s ? null : n), m(k, j)) : y[c].push(l)) } function j(a, b, c, d, f) { return q = 0, b = b || "j", e(a) ? i("c" == b ? v : u, a, b, this.i++, c, d, f) : (p.splice(this.i++, 0, a), 1 == p.length && h()), this } function k() { var a = B; return a.loader = { load: j, i: 0 }, a } var l = b.documentElement, m = a.setTimeout, n = b.getElementsByTagName("script")[0], o = {}.toString, p = [], q = 0, r = "MozAppearance" in l.style, s = r && !!b.createRange().compareNode, t = s ? l : n.parentNode, l = a.opera && "[object Opera]" == o.call(a.opera), l = !!b.attachEvent && !l, u = r ? "object" : l ? "script" : "img", v = l ? "script" : u, w = Array.isArray || function (a) { return "[object Array]" == o.call(a) }, x = [], y = {}, z = { timeout: function (a, b) { return b.length && (a.timeout = b[0]), a } }, A, B; B = function (a) { function b(a) { var a = a.split("!"), b = x.length, c = a.pop(), d = a.length, c = { url: c, origUrl: c, prefixes: a }, e, f, g; for (f = 0; f < d; f++)g = a[f].split("="), (e = z[g.shift()]) && (c = e(c, g)); for (f = 0; f < b; f++)c = x[f](c); return c } function g(a, e, f, g, h) { var i = b(a), j = i.autoCallback; i.url.split(".").pop().split("?").shift(), i.bypass || (e && (e = d(e) ? e : e[a] || e[g] || e[a.split("/").pop().split("?")[0]]), i.instead ? i.instead(a, e, f, g, h) : (y[i.url] ? i.noexec = !0 : y[i.url] = 1, f.load(i.url, i.forceCSS || !i.forceJS && "css" == i.url.split(".").pop().split("?").shift() ? "c" : c, i.noexec, i.attrs, i.timeout), (d(e) || d(j)) && f.load(function () { k(), e && e(i.origUrl, h, g), j && j(i.origUrl, h, g), y[i.url] = 2 }))) } function h(a, b) { function c(a, c) { if (a) { if (e(a)) c || (j = function () { var a = [].slice.call(arguments); k.apply(this, a), l() }), g(a, j, b, 0, h); else if (Object(a) === a) for (n in m = function () { var b = 0, c; for (c in a) a.hasOwnProperty(c) && b++; return b }(), a) a.hasOwnProperty(n) && (!c && !--m && (d(j) ? j = function () { var a = [].slice.call(arguments); k.apply(this, a), l() } : j[n] = function (a) { return function () { var b = [].slice.call(arguments); a && a.apply(this, b), l() } }(k[n])), g(a[n], j, b, n, h)) } else !c && l() } var h = !!a.test, i = a.load || a.both, j = a.callback || f, k = j, l = a.complete || f, m, n; c(h ? a.yep : a.nope, !!i), i && c(i) } var i, j, l = this.yepnope.loader; if (e(a)) g(a, 0, l, 0); else if (w(a)) for (i = 0; i < a.length; i++)j = a[i], e(j) ? g(j, 0, l, 0) : w(j) ? B(j) : Object(j) === j && h(j, l); else Object(a) === a && h(a, l) }, B.addPrefix = function (a, b) { z[a] = b }, B.addFilter = function (a) { x.push(a) }, B.errorTimeout = 1e4, null == b.readyState && b.addEventListener && (b.readyState = "loading", b.addEventListener("DOMContentLoaded", A = function () { b.removeEventListener("DOMContentLoaded", A, 0), b.readyState = "complete" }, 0)), a.yepnope = k(), a.yepnope.executeStack = h, a.yepnope.injectJs = function (a, c, d, e, i, j) { var k = b.createElement("script"), l, o, e = e || B.errorTimeout; k.src = a; for (o in d) k.setAttribute(o, d[o]); c = j ? h : c || f, k.onreadystatechange = k.onload = function () { !l && g(k.readyState) && (l = 1, c(), k.onload = k.onreadystatechange = null) }, m(function () { l || (l = 1, c(1)) }, e), i ? k.onload() : n.parentNode.insertBefore(k, n) }, a.yepnope.injectCss = function (a, c, d, e, g, i) { var e = b.createElement("link"), j, c = i ? h : c || f; e.href = a, e.rel = "stylesheet", e.type = "text/css"; for (j in d) e.setAttribute(j, d[j]); g || (n.parentNode.insertBefore(e, n), m(c, 0)) } }(this, document), Modernizr.load = function () { yepnope.apply(window, [].slice.call(arguments, 0)) };
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\clientLogin.js
/* version="30" */

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

$(function () {
    processJobPortalLinks();
    processSignOutLandingPageLinks();
    popoverInitialize();

    if (!window.console) {
        window.console = {
            log: function () { }
        };
    }

    if (window.addEventListener) {
        window.addEventListener("message", redirectToLandingPage);
        window.addEventListener("message", redirectToForgotPasswordPage);
        window.addEventListener("message", redirectGetTranslations);
        window.addEventListener("message", redirectGetPageStyles);
    }
    else {
        window.attachEvent("onmessage", redirectToLandingPage);
        window.attachEvent("onmessage", redirectToForgotPasswordPage);
        window.attachEvent("onmessage", redirectGetTranslations);
        window.attachEvent("onmessage", redirectGetPageStyles);
    }

    if ($('#loginPopoverContent').length) {
        $('#sign-in-link').on("click", function () {
            var signInPopOver = $('#SignInLinksPopOver');
            var signInLink = $('#sign-in-link');
            var signInClose = $('#signInClose');
            //var sectionSignInPopupContainer = $('#LoginPopoverTriggerContainer')
            //    .find('section.form-section.col-sm-12.careersSignInContainer');

            PopOverContent();

            $('.popover-content').attr('tabindex', 0);

            $('#signInClose').on("keypress", function (e) {
                var SignInLink = $('#sign-in-link');
                if (e.which == 13) {
                    SignInLink.trigger("click");
                    e.preventDefault();
                    SignInLink.trigger("focus");
                }
            });

            $('#linkedinButton').on('keydown', function (e) {
                if (e.which == 9 && ($('.popover.fade.bottom').hasClass('in'))) {
                    e.preventDefault();
                    if ($(this).is(":focus")) {
                        $('.popover-content').trigger("focus");
                    }
                }
            });

            //if (sectionSignInPopupContainer.find('iframe:first').length == 0) {
            //    sectionSignInPopupContainer.append('<iframe src="/Authentication/LogOnModal" scrolling="no"></iframe>');
            //}

            if ($('#sectionSignInPage').find('iframe').first().length == 0) {
                $('#sectionSignInPage').append('<iframe id="ADFSLogOnModal" src="/Authentication/LogOnModal" title="Login credentials" scrolling="no"></iframe>');
            }
            // Prevent page from scrolling when sign in overlay is open
            if ($('.modal-open').length > 0 || $('body').hasClass('sign-in-open')) {
                $('body').removeClass('modal-open').removeClass('sign-in-open');
            }
            else {
                if (!$('body').hasClass('sign-in-open')) {
                    $('body').addClass('modal-open').addClass('sign-in-open');
                }
            }
            DisableCurrentLoginPopoverItem();

            signInPopOver.on('keydown', function (e) {
                if (e.which == 27) {
                    signInClose.trigger("click");
                    signInLink.trigger("focus");
                }
            });
        });

        $('#sign-in-link').on("keypress", function (e) {
            if (e.which == 13) {
                $(this).trigger("click");
            }
        });

        $('.language-icon').on("keypress", function (e) {
            if (e.which == 13) {
                $('.language-icon').trigger("click");
            }
        });

        $('#btnMainMenu').on('keydown', function (e) {
            if (e.which == 9 && ($('.popover.fade.bottom').hasClass('in'))) {
                e.preventDefault();
                if ($(this).is(":focus")) {
                    $('#signInClose').trigger("focus");
                }
            }
        });
    }

    triggerSignInPopup();

    if ($("#sign-in-data").data("is-onboarding") === "True") {
        $('span[id^="footer-contacts"]').remove();
        $('.social').remove();
        //$('.mobile-footer-contacts').remove();
    }


    var isBrowserIe = window.navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./);
    var isBrowserSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;

    if (document.referrer.indexOf("linkedin.com") > -1 || document.referrer.indexOf("xing.com") > -1 || ($('#navUserDisplayUserName').text()) && (isBrowserIe || isBrowserSafari)) {
        dropSocialAnalyticsCookie();
        dropOmnitureCookie();
    }

    else {
        dropOmnitureCookie();

    }

});

$(window).on("resize", function () {
    PopOverContent();
    adjustClientLoginPopoverPosition();
});

function PopOverContent() {
    var popOverContent = $('#LoginPopoverTriggerContainer .popover-content');
    var windowHeight = $(window).height();

    //moved the variable and initialization below - isMobile
    //var popoverOffset = popOverContent.offset().top - $(window).scrollTop();

    if (popOverContent && popOverContent.length > 0) {
        // Bug # 405464
        if ($('.popover-content div').hasClass('authenticated')) {
            $('#LoginPopoverTriggerContainer .popover-content').css({
                'height': 'auto',
                'left': 'auto !important',
                'right': '3%'
            }
            );

            if (isMobile()) {
                $('#popover-bg').removeClass("removeOverlay");
            } else {
                $('#popover-bg').addClass("removeOverlay");
            }

            var popOverTop = 52;
            var popOverWidth = '270px';
            var popOverRight = -10;
            var popOverLeft = 'auto';
            var popOverMarginRight = 0;
            var popOverMarginLeft = 0;
            var popOverPosition = 'absolute'

            if (isTablet()) {
                popOverTop = 46;
            }

            if (isMobile()) {
                popOverWidth = '95%';
                popOverRight = 0;
                popOverLeft = 0;
                popOverMarginRight = '2.5%';
                popOverMarginLeft = '2.5%';
                popOverPosition = 'fixed';
            }


            $('#LoginPopoverTriggerContainer .popover.fade.bottom.in').css({
                'top': popOverTop + 'px',
                //'float': 'right',
                'right': popOverRight + 'px',
                'position': popOverPosition,
                'width': popOverWidth,
                'left': popOverLeft,
                'margin-left': popOverMarginLeft,
                'margin-right': popOverMarginRight
            });
        }
        else {
            if (isMobile()) {
                var popoverOffset = popOverContent.offset().top - $(window).scrollTop();
                var popOverHeight = windowHeight - popoverOffset;

                if (popOverHeight >= 600) {
                    popOverHeight = 600;
                }

                popOverContent.css({ 'height': popOverHeight + 'px' });
            }
            else {
                popOverContent.css({ 'height': '600px' });

                if ($('.cookie-nav').length > 0) {
                    var popOverContentTop = $('.cookie-nav').height() + 71;

                    if (isTablet()) {
                        popOverContentTop = $('.cookie-nav').height() + 57;
                    }

                    $('#LoginPopoverTriggerContainer .popover.fade.bottom.in').css({
                        'top': popOverContentTop + 'px'
                    });
                }
                else {
                    if (isTablet()) {
                        $('#LoginPopoverTriggerContainer .popover.fade.bottom.in').css({
                            'top': '57px'
                        });
                    }
                }
            }
        }

        // [JDE - 434543/434578] Position the popover arrow at the middle of the sign-in-link
        var arrowRightPosition = ($('#LoginPopoverTriggerContainer .popover').offset().left + $('#LoginPopoverTriggerContainer .popover').outerWidth()) - ($('#sign-in-link').offset().left + $('#sign-in-link').outerWidth()) + ($('#sign-in-link').width() / 2);
        $("#LoginPopoverTriggerContainer .popover .arrow").css('right', arrowRightPosition + 'px');
    }
}

function processSignOutLandingPageLinks() {
    try {
        var lnk = $(".signout-append").attr("href");

        if (lnk != typeof undefined) {
            if (lnk != undefined) {
                if (lnk.indexOf("?") == -1) {
                    lnk = lnk + "?ReturnUrl=" + encodeURIComponent($("#signInPopupData").attr("data-signout-landingpage"));
                } else {
                    lnk = lnk + "&ReturnUrl=" + encodeURIComponent($("#signInPopupData").attr("data-signout-landingpage"));
                }
                $(".signout-append").attr("href", lnk);
            }
        }
    } catch (ex) {
        console.log("Error occurred : " + ex.message);
    }
}

function processJobPortalLinks() {
    try {
        var lnk = $(".joburl-append").attr("href");

        if (lnk != typeof undefined) {
            if (lnk != undefined) {
                if (lnk.indexOf("?") == -1) {
                    lnk = lnk + "?ReturnUrl=" + encodeURIComponent($("#sign-in-data").attr("data-return-url"));
                } else {
                    lnk = lnk + "&ReturnUrl=" + encodeURIComponent($("#sign-in-data").attr("data-return-url"));
                }
                $(".joburl-append").attr("href", lnk);
            }
        }
    } catch (ex) {
        console.log("Error occurred : " + ex.message);
    }
}

function redirectToLandingPage(e) {
    if (e.data == "reload") {
        var ru = $("#sign-in-data").attr("data-return-url");
        if (ru != null) {
            //if (ru == "" && (navigator.appVersion.indexOf("Trident") != -1)) {
            //    ru = window.location;
            //}
            //window.location.assign(ru);

            //BUG 426001
            if ((document.getElementById('SignInLinksPopOver') == undefined) || (document.getElementById('SignInLinksPopOver') == null)) {
                //Page
                if (ru == "") {
                    ru = window.location.protocol + "//" + window.location.host;
                }
            }
            else {
                // PopOver
                if (ru == "" && (navigator.appVersion.indexOf("Trident") != -1)) {
                    ru = window.location;
                }
            }

            var urlHostname = document.getElementById("login-return-url");
            if (typeof urlHostname !== 'undefined' && urlHostname != null) {
                if (urlHostname.hostname != window.location.hostname.toLowerCase()) {
                    var countrySite = window.location.pathname.split("/")[1];
                    if (countrySite == null) {
                        countrySite = "us-en";
                    }
                    ru = window.location.protocol + "//" + window.location.host + "/" + countrySite;
                }
            }
            dropOmnitureCookie();
            jQuery("body").trigger("analytics-form-success");
            window.location.assign(ru);
        }
        else {
            //var restOfUrl = window.location.href.substr(5);
            //window.location = "https" + restOfUrl;

            var signInDiv = $("div.component.col-sm-12.careersSignInContainer.signin-border");
            if (!!signInDiv.attr("data-landingPageLink")) {
                window.location.assign(signInDiv.attr("data-landingPageLink"));
            }
            else {
                //alert("No Landing Page URL was specified. Please set the Landing Page URL.");
                console.log("No Landing Page URL was specified. Please set the Landing Page URL.");
            }
        }
    }
}

function redirectToForgotPasswordPage(e) {
    if (e.data == "forgotPassword") {
        // PopOver and Sign In Page should not exist at the same time.
        // If PopOver Exist then the sign in page does not

        // Check SignInLinksPopOver
        if ((document.getElementById('SignInLinksPopOver') == undefined) || (document.getElementById('SignInLinksPopOver') == null)) {
            //Page Check
            //Check sectionSignInPage SignInLinksPage
            if ((document.getElementById('SignInLinksPage') == undefined) || (document.getElementById('SignInLinksPage') == null)) {
                console.log("No Forgot Password Page URL was specified. Please set the Forgot Password Page URL.");
            }
            else {
                // Page Exist
                var ForgetPage = $("#SignInLinksPage");
                if (!!ForgetPage.attr("data-forgotPasswordLink")) {
                    window.location.assign(ForgetPage.attr("data-forgotPasswordLink"));
                }
                else {
                    console.log("No Forgot Password Page URL was specified. Please set the Forgot Password Page URL.");
                }
            }
        }
        else {
            // PopOver Exist
            var ForgetPopUp = $("#SignInLinksPopOver");
            if (!!ForgetPopUp.attr("data-forgotPasswordLink")) {
                window.location.assign(ForgetPopUp.attr("data-forgotPasswordLink"));
            }
            else {
                console.log("No Forgot Password Page URL was specified. Please set the Forgot Password Page URL.");
            }
        }
    }
}

function redirectGetTranslations(e) {
    if (e.data == "getPageTranslations") {
        //setting default values
        var message = {};
        message.eventType = 'ReceiveTranslations';
        message.emailAddress = 'e-mail address';
        message.password = 'password';
        message.submit = 'SIGN IN';
        message.rememberEmail = 'Remember password';
        message.forgotPassword = 'Forgot Password';
        //for bug 361855
        message.emptyloginemailaddress = 'Empty Login EmailAddress';
        message.emptyloginpassword = 'Empty Login Password';
        message.invaliduserlogin = 'Invalid User Login';
        message.incorrectemailformat = 'Incorrect Email Format';
        message.accountlockout = 'Your account has been temporarily disabled. Please wait 30 minutes before attempting to login or reset your password.';

        // Check SignInLinksPopOver
        if ((document.getElementById('SignInLinksPopOver') == undefined) || (document.getElementById('SignInLinksPopOver') == null)) {
            //Page Check
            //Check sectionSignInPage SignInLinksPage
            if ((document.getElementById('SignInLinksPage') == undefined) || (document.getElementById('SignInLinksPage') == null)) {
                console.log("No Translations Specified for Sign-in.");
            }
            else {
                // Page Exist
                var TranslationPage = $("#SignInLinksPage");
                if (!!TranslationPage.attr("data-emailAddress-string")) {
                    message.emailAddress = TranslationPage.attr("data-emailAddress-string");
                }
                if (!!TranslationPage.attr("data-password-string")) {
                    message.password = TranslationPage.attr("data-password-string");
                }
                if (!!TranslationPage.attr("data-submit-string")) {
                    message.submit = TranslationPage.attr("data-submit-string");
                }
                if (!!TranslationPage.attr("data-rememberEmail-string")) {
                    message.rememberEmail = TranslationPage.attr("data-rememberEmail-string");
                }
                if (!!TranslationPage.attr("data-forgotPassword-string")) {
                    message.forgotPassword = TranslationPage.attr("data-forgotPassword-string");
                }
                if (!!TranslationPage.attr("data-IncorrectEmailFormat-string")) {
                    message.incorrectemailformat = TranslationPage.attr("data-IncorrectEmailFormat-string");
                }
                if (!!TranslationPage.attr("data-EmptyLoginEmailAddress-string")) {
                    message.emptyloginemailaddress = TranslationPage.attr("data-EmptyLoginEmailAddress-string");
                }
                if (!!TranslationPage.attr("data-EmptyLoginPassword-string")) {
                    message.emptyloginpassword = TranslationPage.attr("data-EmptyLoginPassword-string");
                }
                if (!!TranslationPage.attr("data-InvalidClientUserLogin-string")) {
                    message.invaliduserlogin = TranslationPage.attr("data-InvalidClientUserLogin-string");
                }
                if (!!TranslationPage.attr("data-AccountLockout-string")) {
                    message.accountlockout = TranslationPage.attr("data-AccountLockout-string");
                }

                /*WEB ACCESSIBILITY ERROR VALIDATION */
                var iframeAd = $('#ADFSLogOnModal').attr("src");               
                var doesExist = iframeAd.indexOf("onb");

                if (!(doesExist) >= 0) {
                    var $ADFSLogOnModal = $('#ADFSLogOnModal');
                    var UsernameErrorMessage = $ADFSLogOnModal.contents().find("#ContentPlaceHolder1_UsernameTextBox");
                    var PasswordErrorMessage = $ADFSLogOnModal.contents().find("#ContentPlaceHolder1_PasswordTextBox");
                    var ErrorIncorrectEmailFormat = $ADFSLogOnModal.contents().find('#ContentPlaceHolder1_ErrorIncorrectEmailFormat');
                    var ErrorEmptyUser = $ADFSLogOnModal.contents().find('#ContentPlaceHolder1_ErrorEmptyUser');
                    var ErrorEmptyPassword = $ADFSLogOnModal.contents().find('#ContentPlaceHolder1_ErrorEmptyPassword');
                    var ErrorInvalidUserLogin = $ADFSLogOnModal.contents().find('#ContentPlaceHolder1_ErrorInvalidUserLogin');
                    var ErrorAccountLockout = $ADFSLogOnModal.contents().find('#ContentPlaceHolder1_ErrorAccountLockout');

                    if ((ErrorIncorrectEmailFormat).length > 0) {
                        UsernameErrorMessage.attr("aria-describedby", "ContentPlaceHolder1_ErrorIncorrectEmailFormat");
                    }
                    if ((ErrorEmptyUser).length > 0) {
                        UsernameErrorMessage.attr("aria-describedby", "ContentPlaceHolder1_ErrorEmptyUser");
                    }
                    if ((ErrorEmptyPassword).length > 0) {
                        PasswordErrorMessage.attr("aria-describedby", "ContentPlaceHolder1_ErrorEmptyPassword");
                    }
                    if ((ErrorInvalidUserLogin).length > 0) {
                        PasswordErrorMessage.attr("aria-describedby", "ContentPlaceHolder1_ErrorInvalidUserLogin");
                    }
                    if ((ErrorAccountLockout).length > 0) {
                        UsernameErrorMessage.attr("aria-describedby", "ContentPlaceHolder1_ErrorAccountLockout");
                    }

                    if (((ErrorEmptyUser).length > 0) || ((ErrorIncorrectEmailFormat).length > 0) || ((ErrorAccountLockout).length > 0)) {
                        window.setTimeout(function () {
                            UsernameErrorMessage.trigger("focus");
                        }, 500);
                        $ADFSLogOnModal.addClass('withErrorMessage');
                    }

                    else if (((ErrorEmptyPassword).length > 0) || ((ErrorInvalidUserLogin).length > 0)) {
                        window.setTimeout(function () {
                            PasswordErrorMessage.trigger("focus");
                        }, 500);
                        $ADFSLogOnModal.addClass('withErrorMessage');
                    }
                }  
            }
        }
        else {
            // PopOver Exist
            var TranslationPage = $("#SignInLinksPopOver");
            if (!!TranslationPage.attr("data-emailAddress-string")) {
                message.emailAddress = TranslationPage.attr("data-emailAddress-string");
            }
            if (!!TranslationPage.attr("data-password-string")) {
                message.password = TranslationPage.attr("data-password-string");
            }
            if (!!TranslationPage.attr("data-submit-string")) {
                message.submit = TranslationPage.attr("data-submit-string");
            }
            if (!!TranslationPage.attr("data-rememberEmail-string")) {
                message.rememberEmail = TranslationPage.attr("data-rememberEmail-string");
            }
            if (!!TranslationPage.attr("data-forgotPassword-string")) {
                message.forgotPassword = TranslationPage.attr("data-forgotPassword-string");
            }
            if (!!TranslationPage.attr("data-IncorrectEmailFormat-string")) {
                message.incorrectemailformat = TranslationPage.attr("data-IncorrectEmailFormat-string");
            }
            if (!!TranslationPage.attr("data-EmptyLoginEmailAddress-string")) {
                message.emptyloginemailaddress = TranslationPage.attr("data-EmptyLoginEmailAddress-string");
            }
            if (!!TranslationPage.attr("data-EmptyLoginPassword-string")) {
                message.emptyloginpassword = TranslationPage.attr("data-EmptyLoginPassword-string");
            }
            if (!!TranslationPage.attr("data-InvalidClientUserLogin-string")) {
                message.invaliduserlogin = TranslationPage.attr("data-InvalidClientUserLogin-string");
            }
            if (!!TranslationPage.attr("data-AccountLockout-string")) {
                message.accountlockout = TranslationPage.attr("data-AccountLockout-string");
            }
        }

        //window.frames[0].postMessage
        if (IsIE8()) {
            e.source.postMessage(JSON.stringify(message), "*");
        }
        else {
            e.source.window.postMessage(JSON.stringify(message), "*");
        }
    }
}

function redirectGetPageStyles(e) {
    if (e.data == "getPageStyles") {
        var message = {}
        message.eventType = 'ReceiveStyles';
        message.fontFamily = $("body").css('font-family');

        //window.setTimeout(function () {
        if (IsIE8()) {
            e.source.postMessage(JSON.stringify(message), "*");
        }
        else {
            e.source.window.postMessage(JSON.stringify(message), "*");
        }

        //}, 0);
    }
}

function dropSocialAnalyticsCookie() {
    //Social Omni Cookie
    if (typeof acncm !== 'undefined') {
        $.ajax({
            url: "/api/sitecore/SiteAnalytics/GetSocialProfileOmniData",
            type: "POST",
            async: false,
            success: function (data) {
                var userOmniData = data;

                if (userOmniData !== null) {
                    //LinkedIn Profile ID
                    if (userOmniData.ProfileID != null && userOmniData.ProfileID != '') {
                        acncm.Visitor.detectedRegisteredUser(userOmniData.ProfileID);
                    }
                    //Social Industry
                    if (userOmniData.SocialIndustry != null && userOmniData.SocialIndustry != '') {
                        acncm.Visitor.detectedSocialConnectUserIndustry(userOmniData.SocialIndustry);
                    }

                    //Social Skills
                    if (userOmniData.SocialSkills != null && userOmniData.SocialSkills != '') {
                        acncm.Visitor.detectedSocialConnectUserCareerSkill(userOmniData.SocialSkills);
                    }

                    //Social Flag
                    if (userOmniData.SocialFlag != null && userOmniData.SocialFlag != '') {
                        acncm.Visitor.detectedSocialFlag(userOmniData.SocialFlag);
                    }

                }
            }
        });
    }
}

function dropOmnitureCookie() {
    // OMNI DROP COOKIE
    if (typeof acncm !== 'undefined') {
        $.ajax({
            url: "/api/sitecore/SiteAnalytics/GetUserProfileOmniData",
            type: "POST",
            async: false,
            success: function (data) {
                var userOmniData = data;

                if (userOmniData !== null) {
                    // Login Form - Complete (e27)
                    acncm.Forms.detectedLoginFormComplete();

                    // Visitor Groups
                    if (userOmniData.VisitorGroup != null && userOmniData.VisitorGroup != '') {
                        acncm.Visitor.detectedVisitorGroup(userOmniData.VisitorGroup * 1);
                    }

                    // User GUID ID
                    if (userOmniData.UserProfileId != null && userOmniData.UserProfileId != '') {
                        acncm.Visitor.detectedRegisteredUser(userOmniData.UserProfileId);
                    }

                    // Career Seeker Industry
                    if (userOmniData.IndustryText != null && userOmniData.IndustryText != '') {
                        acncm.Visitor.detectedRegisteredUserIndustry(userOmniData.IndustryText);
                    }

                    // Career Seeker Skill
                    if (userOmniData.SkillText != null && userOmniData.SkillText != '') {
                        acncm.Visitor.detectedRegisteredUserSkill(userOmniData.SkillText);
                    }

                    // Authentication Type
                    if (userOmniData.AuthType != null && userOmniData.AuthType != '') {
                        acncm.Visitor.detectedAuthType(userOmniData.AuthType);
                    }

                    //Authentication Flag
                    if (userOmniData.AuthFlag != null && userOmniData.AuthFlag != '') {
                        acncm.Visitor.detectedAuthFlag(userOmniData.AuthFlag);
                    }

                    //Client Type
                    if (userOmniData.ClientType != null && userOmniData.ClientType != '') {
                        acncm.Visitor.detectedClientType(userOmniData.ClientType);
                    }
                }
            }
        });
    }
}

function triggerSignInPopup() {
    //popoverInitialize();

    $('#sign-in-link').on('shown.bs.popover', function () { $("#popover-bg").fadeIn(); });
    $('#sign-in-link').on('hidden.bs.popover', function () { $("#popover-bg").fadeOut(); });
}

function validateFields() {
    var isvalid = true;

    $(".validation-container").hide();
    $(".validation-container .error-list").empty();

    var email = $("#email-input").val();
    var pass = $("#Password").val();

    if (email.trim() == "" || email.trim() == null) {
        $(".validation-container .error-list").append("<li>Email is required</li>");
        $(".validation-container").show();
        isvalid = false;
    }
    if (pass.trim() == "" || pass.trim() == null) {
        $(".validation-container .error-list").append("<li>Password is required</li>");
        $(".validation-container").show();
        isvalid = false;
    }

    $.ajax({ async: false });
    $.getJSON('/api/sitecore/CareersSignInModule/ValidateCredentials',
        {
            email: $("#Email").val(),
            password: $("#Password").val()
        }, function (res) {
            if (!res) {
                $(".validation-container .error-list").append("<li>Invalid username/password</li>");
                $(".validation-container").show();
                isvalid = false;
            }
            $.ajax({ async: true });
        });

    return isvalid;
}

function DisableCurrentLoginPopoverItem() {
    var loginPopOverItems = $("#LoginPopoverTriggerContainer .popover-content .authenticated ul");
    var currentPageAddress = window.location.href.toLowerCase();

    if (loginPopOverItems.length > 0) {
        loginPopOverItems.find("li a").each(function () {
            var loginPopOverCurrentItem = $(this);
            if (currentPageAddress.indexOf(loginPopOverCurrentItem.attr("href").toLowerCase()) > -1) {
                loginPopOverCurrentItem.replaceWith("<span class='color-primary'>" + loginPopOverCurrentItem.text() + "</span>")
            }
        });
    }
}

function popoverInitialize() {
    $(".careersSignInContainer .login-btn").off();
    $(".careersSignInContainer .login-btn").on("click", function (event) {
        if (!validateFields()) {
            event.preventDefault();
        }
        else {
            var isDropdownSignIn = $(".login-btn").parent().parent().parent().parent().hasClass('loginpanel'); //means it is from the dropdown sign in link

            if (isDropdownSignIn) {
                window.location.assign(window.location.href);
            }
            else {
                window.location.assign(clientLoginLandingPage);
            }
        }
    });

    $("#sign-in-link").popover({
        title: 'testing',
        content: function () {
            return $("#loginPopoverContent").html();
        },
        placement: 'bottom',
        html: true
    });

    $("#sign-in-link").on('shown.bs.popover', function () {
        // Bug # 365656

        var right_screen = $(window).width() - ($('#sign-in-link').offset().left + $('#sign-in-link').width());

        $("#LoginPopoverTriggerContainer .popover .arrow").css('right', right_screen + 'px');

        // Fix for 371966
        var menubarcollapse = $('#ui-menu-nav-collapse');
        var menubarexpand = $('#ui-menu-nav-expand');
        var signmoveleft = $('#LoginPopoverTriggerContainer .popover');
        var screenWidth = $(window).width();
        var desktopWidth = 1200;
        var mobileWidth = 767;
        var isAuthenticated = ($('#LoginPopoverTriggerContainer').find('.authenticated').length == 0) ? true : false;

        if (isAuthenticated) {
            if (screenWidth >= desktopWidth) {
                if (menubarexpand.length == 1) {
                    signmoveleft.attr('style', 'left: 0% !important');
                    signmoveleft.css("right", "20.5%");
                    signmoveleft.css("display", "block");

                    // Bug # 365656
                    var final_screen = $('#main-menu').width() - $('#LoginPopoverTriggerContainer').width();

                    $("#LoginPopoverTriggerContainer .popover .arrow").css('right', final_screen + 'px');
                }
                else if (menubarcollapse.length == 1) {
                    signmoveleft.attr('style', 'display:block');
                    signmoveleft.css("left", "");
                    signmoveleft.css("right", "");
                }
            }
            else if (screenWidth <= mobileWidth) {
                $('#LoginPopoverTriggerContainer .popover.fade.bottom.in').css({
                    'left': '0',
                    'width': '90%',
                    'margin-left': '5%',
                    'margin-right': '5%'
                });
            }
            else {
                $('#LoginPopoverTriggerContainer .popover.fade.bottom.in').css({
                    'left': '15%',
                    'width': '85%',
                });
            }
        }

        var loginPopOver = $('#LoginPopoverTriggerContainer');

        if (typeof loginPopOver !== 'undefined') {
            var recommendedForYouLink = $('#navigation-settings-content').data('recommendedforyoulink');

            if (recommendedForYouLink != '' && recommendedForYouLink != null) {
                $('#LoginPopoverTriggerContainer .authenticated ul li:first-child a').attr('href', recommendedForYouLink);
            }
        }

        // [JDE - 434543/434578] Remove code that hides popover arrow
        //else {
        //    $('.arrow').addClass('hidden');
        //}
        //end
    });
}

//RMT 9622 - Career Sign In Page Analytics Issues

window.addEventListener("message", setIframeSatTrackCookie);

function setIframeSatTrackCookie(e) {
    if (e.data == "getTopSatTrackCookie") {
        function getCookie(name) {
            var value = "; " + document.cookie;
            var parts = value.split("; " + name + "=");
            if (parts.length == 2) return parts.pop().split(";").shift();
        }

        var checkSatTrack = getCookie('sat_track');

        if (checkSatTrack == 'true') {
            var pageIframe = $("iframe[id=ADFSLogOnModal]");
            if (pageIframe.length != 0) {
                pageIframe.get(0).contentWindow.postMessage("EnableSatTrack", "*")
            }
        }
        else if (checkSatTrack == 'false') {
            var pageIframe = $("iframe[id=ADFSLogOnModal]");
            if (pageIframe.length != 0) {
                pageIframe.get(0).contentWindow.postMessage("DisableSatTrack", "*")
            }
        }
    }
}

function adjustClientLoginPopoverPosition() {
    var popOverUnauthenticated = $('#LoginPopoverTriggerContainer .popover .popover-content .loginpanel');
    var popOverAuthenticated = $('#LoginPopoverTriggerContainer .popover .popover-content .authenticated');
    var popOverTriggerContainer = $('#LoginPopoverTriggerContainer .popover');
    var cookieStatement = $('div.cookie-nav');
    var popoverTopValue = $('#header-topnav').height();

    if (popOverUnauthenticated.is(":visible")) {
        if (cookieStatement.is(":visible")) {
            popoverTopValue += cookieStatement.height();
        }
        popOverTriggerContainer.css({ 'top': popoverTopValue + 12 });
    }
    else if (popOverAuthenticated.is(":visible")) {
        if (isDesktop()) {
            popOverTriggerContainer.css({ 'top': popoverTopValue - 7 });
        }
        else if (isTablet()) {
            popOverTriggerContainer.css({ 'top': popoverTopValue + 2 });
        }
    }
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\AcnCacheManager.js
/* version="9" */
var acncm = {};

////////////////////
///  VISITOR     ///
///////////////////
acncm.Visitor = {

    /* 
     * Used by modules to store values to localStorage or cookie -- START 
     */
    /* Visitor Group */
    detectedVisitorGroup: function (num) {
        switch (num) {
            case 1: /* Career Seekers */
                acncm.CacheManager.write(acncm.CacheManager.Authentication.VisitorGroups.key, acncm.CacheManager.Authentication.VisitorGroups.value.RegisteredUsers);
                break;

            case 2: /* Client-Microsite Access */
                acncm.CacheManager.write(acncm.CacheManager.Authentication.VisitorGroups.key, acncm.CacheManager.Authentication.VisitorGroups.value.Client);
                break;

            case 3: /* Salesforce Contact */
                acncm.CacheManager.write(acncm.CacheManager.Authentication.VisitorGroups.key, acncm.CacheManager.Authentication.VisitorGroups.value.Salesforce);
                break;

            case 4: /* Social Sign On Users  */
                acncm.CacheManager.write(acncm.CacheManager.Authentication.VisitorGroups.key, acncm.CacheManager.Authentication.VisitorGroups.value.SocialSignOnUsers);
                break;
        }
    },

    /* Client Type */
    detectedClientType: function (clientType) {
        acncm.CacheManager.write(acncm.CacheManager.Authentication.ClientType.key, clientType);  
    },

    /* Registered User ID */
    detectedRegisteredUser: function (userProfileID) {
        if (typeof OneTrustCookieHelper !== "undefined" && OneTrustCookieHelper.activeCookieCategories.FirstPartyAnalytics) {
            acncm.CacheManager.write(acncm.CacheManager.Authentication.RegisteredUser.ID.key, userProfileID);
        }
    },

    /* Registered User Industry */
    detectedRegisteredUserIndustry: function (industries) {
        if (typeof OneTrustCookieHelper !== "undefined" && OneTrustCookieHelper.activeCookieCategories.FirstPartyAnalytics) {
            acncm.CacheManager.write(acncm.CacheManager.Authentication.RegisteredUser.Industry.key, industries);
        }
    },

    /* Registered User Skill */
    detectedRegisteredUserSkill: function (skill) {
        if (typeof OneTrustCookieHelper !== "undefined" && OneTrustCookieHelper.activeCookieCategories.FirstPartyAnalytics) {
            acncm.CacheManager.write(acncm.CacheManager.Authentication.RegisteredUser.Skill.key, skill);
        }
    },

    /* Authentication Type */
    detectedAuthType: function (loginType) {
        acncm.CacheManager.write(acncm.CacheManager.Authentication.Type.key, loginType);
    },

    /*Authentication Flag*/
    detectedAuthFlag: function (authFlag) {
        acncm.CacheManager.writeFlagCookie(acncm.CacheManager.Authentication.RegisteredUser.AuthFlag.key, authFlag);
    },

    /* Social Career Skill */
    detectedSocialConnectUserCareerSkill: function (socialCareerSkill) {
        if (typeof OneTrustCookieHelper !== "undefined" && OneTrustCookieHelper.activeCookieCategories.FirstPartyAnalytics) {
            acncm.CacheManager.write(acncm.CacheManager.Authentication.SocialConnectUser.SocialCareerSkill.key, socialCareerSkill);
        }
    },

    /* Social Industry */
    detectedSocialConnectUserIndustry: function (socialIndustry) {
        if (typeof OneTrustCookieHelper !== "undefined" && OneTrustCookieHelper.activeCookieCategories.FirstPartyAnalytics) {
            acncm.CacheManager.write(acncm.CacheManager.Authentication.SocialConnectUser.SocialIndustry.key, socialIndustry);
        }
    },

    /*Social Flag*/
    detectedSocialFlag: function (socialFlag) {
        acncm.CacheManager.writeFlagCookie(acncm.CacheManager.Authentication.SocialConnectUser.SocialFlag.key, socialFlag);
    }

    /* Used by modules to store values to localStorage or cookie -- END */
};

////////////////////
///EMAIL ALERT///
///////////////////

acncm.EA = {
    detectedSignUp: function () {
        acncm.CacheManager.write(acncm.CacheManager.EmailAlerts.key, acncm.CacheManager.EmailAlerts.value.Complete);
    }
};

////////////////////
///FORM ANALYSIS////
///////////////////
acncm.Forms = {

    /* 
    * Used by modules to store values to localStorage or cookie -- START 
    */
    /* Forms */
    detectedFormStart: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.Start);
    },
    detectedFormComplete: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.Complete);
    },
    detectedFormError: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.Error);
    },

    /* Login Form */
    detectedLoginFormStart: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.LoginStart);
    },
    detectedLoginFormComplete: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.LoginComplete);
    },
    detectedLoginFormError: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.LoginError);
    },

    /* Registration Form */
    detectedRegistrationFormStart: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.RegistrationStart);
    },
    detectedRegistrationFormComplete: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.RegistrationComplete);
    },
    detectedRegistrationFormError: function () {
        acncm.CacheManager.append(acncm.CacheManager.Forms.key, acncm.CacheManager.Forms.value.RegistrationError);
    }

    /* Used by modules to store values to localStorage or cookie -- END */

};


////////////////////
///CACHE MANAGER///
///////////////////

acncm.CacheManager = {
    LinkAnalysis: {
        key: "_ss_LINKS"
    },

    Authentication: {
        VisitorGroups: {
            key: "_ss_vg",
            value: {
                RegisteredUsers: "G1",
                Client: "G2",
                Salesforce: "G3",
                SocialSignOnUsers: "G4"
            }
        },
        ClientType: {
            key: "_ss_ct"
        },
        RegisteredUser: {
            ID: {
                key: "_ss_uid"
            },
            Industry: {
                key: "_ss_ui"
            },
            Skill: {
                key: "_ss_cs"
            },
            AuthFlag: {
                key: "_ss_af"
            }
        },
        SocialConnectUser: {
            SocialCareerSkill: {
                key: "_ss_scs"
            },
            SocialIndustry: {
                key: "_ss_sin"
            },
            SocialFlag: {
                key: "_ss_sf"
            }
        },
        Type: {
            key: "_ss_acn",
            value: {
                FederatedLogin: "fed",
                SiteLogin: "site",
                SocialLogin: "soc"
            }
        }

    },
    Forms: {
        key: "_ss_fa",
        value: {
            Start: "s",
            Complete: "c",
            Error: "e",

            LoginStart: "sl",
            LoginComplete: "cl",
            LoginError: "el",

            RegistrationStart: "sr",
            RegistrationComplete: "cr",
            RegistrationError: "er"
        }
    },
    EmailAlerts: {
        key: "_ss_ea",
        value: {
            Complete: "c",
            Edit: "e",
            Unsubscribe: "u"
        }
    },
    Jobs: {
        key: "_ss_js",
        value: {
            JobSave: "c"
        }
    },

    /* Utilities */
    isLocalStorageSupported: function () {
        var isSupported = false;
        if (typeof Modernizr != 'undefined' && typeof Modernizr.localstorage != 'undefined') {
            isSupported = Modernizr.localstorage;
        };

        return isSupported;
    },
    isSessionStorageSupported: function () {
        var isSupported = false;
        if (typeof (Storage) != 'undefined') {
            isSupported = true;
        };

        return isSupported;
    },
    isCookieSupported: function () {
        return typeof $.cookie != 'undefined';
    },
    writeFlagCookie: function (key, value, expdate) {
        if (this.isCookieSupported()) {
            //write cookie
            var domainName = window.location.hostname === "www.accenture.cn" ? ".accenture.cn" : ".accenture.com";
            $.cookie(key, value, { secure: true, path: "/", expires: expdate, domain: domainName });
        }
    },
    write: function (key, value, secure) {
        var isSuccessful = false;
        if (typeof key != 'undefined' && typeof value != 'undefined' && key.length > 0) {
            if (this.isLocalStorageSupported()) {
                //write to local storage
                localStorage.setItem(key, value);
                isSuccessful = true;
            } else if (this.isCookieSupported()) {
                //write to cookie
                if (typeof secure != 'undefined') {
                    $.cookie(key, value, { secure: secure });
                } else {
                    $.cookie(key, value, { secure: true });
                }

                isSuccessful = true;
            }
        }

        return isSuccessful;
    },
    read: function (key) {
        var value = key;
        if (typeof key != 'undefined' && key.length > 0) {
            if (this.isLocalStorageSupported()) {
                //get from local storage
                value = localStorage.getItem(key)
            }

            if (this.isCookieSupported() && (value == key || value == null)) {
                //get from cookie
                value = $.cookie(key);
            }
        }

        return value;
    },
    writeSession: function (key, value, secure) {
        var isSuccessful = false;
        if (typeof key != 'undefined' && typeof value != 'undefined' && key.length > 0) {
            if (this.isSessionStorageSupported()) {
                //write to session storage
                sessionStorage.setItem(key, value);
                isSuccessful = true;
            } else if (this.isCookieSupported()) {
                //write to cookie
                writeFlagCookie();
                isSuccessful = true;
            }
        }

        return isSuccessful;
    },
    readSession: function (key) {
        var value = key;
        if (typeof key != 'undefined' && key.length > 0) {
            if (this.isSessionStorageSupported()) {
                //get from session storage
                value = sessionStorage.getItem(key);
            }

            if (this.isCookieSupported() && (value == key || value == null)) {
                //get from cookie
                value = $.cookie(key);
            }
        }

        return value;
    },
    append: function (key, value) {
        var readValue = this.read(key);
        if (readValue && readValue.length > 0 && readValue.indexOf(value) < 0) {
            value = readValue + "," + value;
        }

        return this.write(key, value);

    },
    writeUrl: function (key, value) {
        var isSuccessful = false;
        if (typeof key != 'undefined' && typeof value != 'undefined' && key.length > 0 && value.length > 0) {
            var LastUrl = [];
            if (this.read(key) != undefined) {
                LastUrl = JSON.parse(this.read(key));
                if (LastUrl == null) {
                    LastUrl = [''];
                }
            }
            else {
                LastUrl = [''];
            }

            LastUrl.unshift(value);
            if (LastUrl.length >= 7) {
                LastUrl.pop();
            }

            this.write(key, JSON.stringify(LastUrl));
            isSuccessful = true;
        }
        return isSuccessful;
    },
    readUrl: function (key) {
        var value = [];
        if (typeof key != 'undefined' && key.length > 0) {
            value = this.read(key);
            if ((value == undefined) || (value == null)) {
                value = [];
            }
        }
        return value;
    },

    getKeyStorageLocation: function (key) {

        var value = key;
        if (this.isLocalStorageSupported()) {
            //get from local storage
            value = localStorage.getItem(key)

            if (value !== null) {
                return "localstorage";
            }
        }

        if (this.isCookieSupported()) {
            //get from cookie
            value = $.cookie(key);

            if (value) {
                return "cookie";
            }
        }

        return "Cached key location not found.";

    },
    remove: function (key, path, domain) {
        var keyLocation = this.getKeyStorageLocation(key);

        if (keyLocation == "localstorage") {
            //remove from local storage
            localStorage.removeItem(key);
        }
        else if (keyLocation == "cookie") {
            //remove from cookie
            var removeCookie = key + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

            if (domain) {
                removeCookie += 'domain=' + domain + ';';
            }
            if (path) {
                removeCookie += 'path=' + path + ';';
            }

            document.cookie = removeCookie;

        }

    }
};
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\bootstrap.js
/* version="1" */
/**
* bootstrap.js v3.0.0 by @fat and @mdo
* Copyright 2013 Twitter Inc.
* http://www.apache.org/licenses/LICENSE-2.0
*/
if (!jQuery) { throw new Error("Bootstrap requires jQuery") }

/* ========================================================================
 * Bootstrap: transition.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#transitions
 * ========================================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
    // ============================================================

    function transitionEnd() {
        var el = document.createElement('bootstrap')

        var transEndEventNames = {
            'WebkitTransition': 'webkitTransitionEnd'
            , 'MozTransition': 'transitionend'
            , 'OTransition': 'oTransitionEnd otransitionend'
            , 'transition': 'transitionend'
        }

        for (var name in transEndEventNames) {
            if (el.style[name] !== undefined) {
                return { end: transEndEventNames[name] }
            }
        }
    }

    // http://blog.alexmaccaw.com/css-transitions
    $.fn.emulateTransitionEnd = function (duration) {
        var called = false, $el = this
        $(this).one($.support.transition.end, function () { called = true })
        var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
        setTimeout(callback, duration)
        return this
    }

    $(function () {
        $.support.transition = transitionEnd()
    })

}(window.jQuery);

/* ========================================================================
 * Bootstrap: alert.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#alerts
 * ========================================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // ALERT CLASS DEFINITION
    // ======================

    var dismiss = '[data-dismiss="alert"]'
    var Alert = function (el) {
        $(el).on('click', dismiss, this.close)
    }

    Alert.prototype.close = function (e) {
        var $this = $(this)
        var selector = $this.attr('data-target')

        if (!selector) {
            selector = $this.attr('href')
            selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }

        var $parent = $(selector)

        if (e) e.preventDefault()

        if (!$parent.length) {
            $parent = $this.hasClass('alert') ? $this : $this.parent()
        }

        $parent.trigger(e = $.Event('close.bs.alert'))

        if (e.isDefaultPrevented()) return

        $parent.removeClass('in')

        function removeElement() {
            $parent.trigger('closed.bs.alert').remove()
        }

        $.support.transition && $parent.hasClass('fade') ?
            $parent
                .one($.support.transition.end, removeElement)
                .emulateTransitionEnd(150) :
            removeElement()
    }


    // ALERT PLUGIN DEFINITION
    // =======================

    var old = $.fn.alert

    $.fn.alert = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.alert')

            if (!data) $this.data('bs.alert', (data = new Alert(this)))
            if (typeof option == 'string') data[option].call($this)
        })
    }

    $.fn.alert.Constructor = Alert


    // ALERT NO CONFLICT
    // =================

    $.fn.alert.noConflict = function () {
        $.fn.alert = old
        return this
    }


    // ALERT DATA-API
    // ==============

    $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)

}(window.jQuery);

/* ========================================================================
 * Bootstrap: button.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#buttons
 * ========================================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // BUTTON PUBLIC CLASS DEFINITION
    // ==============================

    var Button = function (element, options) {
        this.$element = $(element)
        this.options = $.extend({}, Button.DEFAULTS, options)
    }

    Button.DEFAULTS = {
        loadingText: 'loading...'
    }

    Button.prototype.setState = function (state) {
        var d = 'disabled'
        var $el = this.$element
        var val = $el.is('input') ? 'val' : 'html'
        var data = $el.data()

        state = state + 'Text'

        if (!data.resetText) $el.data('resetText', $el[val]())

        $el[val](data[state] || this.options[state])

        // push to event loop to allow forms to submit
        setTimeout(function () {
            state == 'loadingText' ?
                $el.addClass(d).attr(d, d) :
                $el.removeClass(d).removeAttr(d);
        }, 0)
    }

    Button.prototype.toggle = function () {
        var $parent = this.$element.closest('[data-toggle="buttons"]')

        if ($parent.length) {
            var $input = this.$element.find('input')
                .prop('checked', !this.$element.hasClass('active'))
                .trigger('change')
            if ($input.prop('type') === 'radio') $parent.find('.active').removeClass('active')
        }

        this.$element.toggleClass('active')
    }


    // BUTTON PLUGIN DEFINITION
    // ========================

    var old = $.fn.button

    $.fn.button = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.button')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.button', (data = new Button(this, options)))

            if (option == 'toggle') data.toggle()
            else if (option) data.setState(option)
        })
    }

    $.fn.button.Constructor = Button


    // BUTTON NO CONFLICT
    // ==================

    $.fn.button.noConflict = function () {
        $.fn.button = old
        return this
    }


    // BUTTON DATA-API
    // ===============

    $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) {
        var $btn = $(e.target)
        if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
        $btn.button('toggle')
        e.preventDefault()
    })

}(window.jQuery);

/* ========================================================================
 * Bootstrap: carousel.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#carousel
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // CAROUSEL CLASS DEFINITION
    // =========================

    var Carousel = function (element, options) {
        this.$element = $(element)
        this.$indicators = this.$element.find('.carousel-indicators')
        this.options = options
        this.paused =
            this.sliding =
            this.interval =
            this.$active =
            this.$items = null

        this.options.pause == 'hover' && this.$element
            .on('mouseenter', $.proxy(this.pause, this))
            .on('mouseleave', $.proxy(this.cycle, this))
    }

    Carousel.DEFAULTS = {
        interval: 5000
        , pause: 'hover'
        , wrap: true
    }

    Carousel.prototype.cycle = function (e) {
        e || (this.paused = false)

        this.interval && clearInterval(this.interval)

        this.options.interval
            && !this.paused
            && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))

        return this
    }

    Carousel.prototype.getActiveIndex = function () {
        this.$active = this.$element.find('.item.active')
        this.$items = this.$active.parent().children()

        return this.$items.index(this.$active)
    }

    Carousel.prototype.to = function (pos) {
        var that = this
        var activeIndex = this.getActiveIndex()

        if (pos > (this.$items.length - 1) || pos < 0) return

        if (this.sliding) return this.$element.one('slid', function () { that.to(pos) })
        if (activeIndex == pos) return this.pause().cycle()

        return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
    }

    Carousel.prototype.pause = function (e) {
        e || (this.paused = true)

        if (this.$element.find('.next, .prev').length && $.support.transition.end) {
            this.$element.trigger($.support.transition.end)
            this.cycle(true)
        }

        this.interval = clearInterval(this.interval)

        return this
    }

    Carousel.prototype.next = function () {
        if (this.sliding) return
        return this.slide('next')
    }

    Carousel.prototype.prev = function () {
        if (this.sliding) return
        return this.slide('prev')
    }

    Carousel.prototype.slide = function (type, next) {
        var $active = this.$element.find('.item.active')
        var $next = next || $active[type]()
        var isCycling = this.interval
        var direction = type == 'next' ? 'left' : 'right'
        var fallback = type == 'next' ? 'first' : 'last'
        var that = this

        if (!$next.length) {
            if (!this.options.wrap) return
            $next = this.$element.find('.item')[fallback]()
        }

        this.sliding = true

        isCycling && this.pause()

        var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction })

        if ($next.hasClass('active')) return

        if (this.$indicators.length) {
            this.$indicators.find('.active').removeClass('active')
            this.$element.one('slid', function () {
                var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
                $nextIndicator && $nextIndicator.addClass('active')
            })
        }

        if ($.support.transition && this.$element.hasClass('slide')) {
            this.$element.trigger(e)
            if (e.isDefaultPrevented()) return
            $next.addClass(type)
            $next[0].offsetWidth // force reflow
            $active.addClass(direction)
            $next.addClass(direction)
            $active
                .one($.support.transition.end, function () {
                    $next.removeClass([type, direction].join(' ')).addClass('active')
                    $active.removeClass(['active', direction].join(' '))
                    that.sliding = false
                    setTimeout(function () { that.$element.trigger('slid') }, 0)
                })
                .emulateTransitionEnd(600)
        } else {
            this.$element.trigger(e)
            if (e.isDefaultPrevented()) return
            $active.removeClass('active')
            $next.addClass('active')
            this.sliding = false
            this.$element.trigger('slid')
        }

        isCycling && this.cycle()

        return this
    }


    // CAROUSEL PLUGIN DEFINITION
    // ==========================

    var old = $.fn.carousel

    $.fn.carousel = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.carousel')
            var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
            var action = typeof option == 'string' ? option : options.slide

            if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
            if (typeof option == 'number') data.to(option)
            else if (action) data[action]()
            else if (options.interval) data.pause().cycle()
        })
    }

    $.fn.carousel.Constructor = Carousel


    // CAROUSEL NO CONFLICT
    // ====================

    $.fn.carousel.noConflict = function () {
        $.fn.carousel = old
        return this
    }


    // CAROUSEL DATA-API
    // =================

    $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
        var $this = $(this), href
        var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
        var options = $.extend({}, $target.data(), $this.data())
        var slideIndex = $this.attr('data-slide-to')
        if (slideIndex) options.interval = false

        $target.carousel(options)

        if (slideIndex = $this.attr('data-slide-to')) {
            $target.data('bs.carousel').to(slideIndex)
        }

        e.preventDefault()
    })

    $(window).on('load', function () {
        $('[data-ride="carousel"]').each(function () {
            var $carousel = $(this)
            $carousel.carousel($carousel.data())
        })
    })

}(window.jQuery);

/* ========================================================================
 * Bootstrap: collapse.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#collapse
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // COLLAPSE PUBLIC CLASS DEFINITION
    // ================================

    var Collapse = function (element, options) {
        this.$element = $(element)
        this.options = $.extend({}, Collapse.DEFAULTS, options)
        this.transitioning = null

        if (this.options.parent) this.$parent = $(this.options.parent)
        if (this.options.toggle) this.toggle()
    }

    Collapse.DEFAULTS = {
        toggle: true
    }

    Collapse.prototype.dimension = function () {
        var hasWidth = this.$element.hasClass('width')
        return hasWidth ? 'width' : 'height'
    }

    Collapse.prototype.show = function () {
        if (this.transitioning || this.$element.hasClass('in')) return

        var startEvent = $.Event('show.bs.collapse')
        this.$element.trigger(startEvent)
        if (startEvent.isDefaultPrevented()) return

        var actives = this.$parent && this.$parent.find('> .panel > .in')

        if (actives && actives.length) {
            var hasData = actives.data('bs.collapse')
            if (hasData && hasData.transitioning) return
            actives.collapse('hide')
            hasData || actives.data('bs.collapse', null)
        }

        var dimension = this.dimension()

        this.$element
            .removeClass('collapse')
            .addClass('collapsing')
        [dimension](0)

        this.transitioning = 1

        var complete = function () {
            this.$element
                .removeClass('collapsing')
                .addClass('in')
            [dimension]('auto')
            this.transitioning = 0
            this.$element.trigger('shown.bs.collapse')
        }

        if (!$.support.transition) return complete.call(this)

        var scrollSize = $.camelCase(['scroll', dimension].join('-'))

        this.$element
            .one($.support.transition.end, $.proxy(complete, this))
            .emulateTransitionEnd(350)
        [dimension](this.$element[0][scrollSize])
    }

    Collapse.prototype.hide = function () {
        if (this.transitioning || !this.$element.hasClass('in')) return

        var startEvent = $.Event('hide.bs.collapse')
        this.$element.trigger(startEvent)
        if (startEvent.isDefaultPrevented()) return

        var dimension = this.dimension()

        this.$element
        [dimension](this.$element[dimension]())
        [0].offsetHeight

        this.$element
            .addClass('collapsing')
            .removeClass('collapse')
            .removeClass('in')

        this.transitioning = 1

        var complete = function () {
            this.transitioning = 0
            this.$element
                .trigger('hidden.bs.collapse')
                .removeClass('collapsing')
                .addClass('collapse')
        }

        if (!$.support.transition) return complete.call(this)

        this.$element
        [dimension](0)
            .one($.support.transition.end, $.proxy(complete, this))
            .emulateTransitionEnd(350)
    }

    Collapse.prototype.toggle = function () {
        this[this.$element.hasClass('in') ? 'hide' : 'show']()
    }


    // COLLAPSE PLUGIN DEFINITION
    // ==========================

    var old = $.fn.collapse

    $.fn.collapse = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.collapse')
            var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)

            if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.collapse.Constructor = Collapse


    // COLLAPSE NO CONFLICT
    // ====================

    $.fn.collapse.noConflict = function () {
        $.fn.collapse = old
        return this
    }


    // COLLAPSE DATA-API
    // =================

    $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) {
        var $this = $(this), href
        var target = $this.attr('data-target')
            || e.preventDefault()
            || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
        var $target = $(target)
        var data = $target.data('bs.collapse')
        var option = data ? 'toggle' : $this.data()
        var parent = $this.attr('data-parent')
        var $parent = parent && $(parent)

        if (!data || !data.transitioning) {
            if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
            $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
        }

        $target.collapse(option)
    })

}(window.jQuery);

/* ========================================================================
 * Bootstrap: dropdown.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#dropdowns
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // DROPDOWN CLASS DEFINITION
    // =========================

    var backdrop = '.dropdown-backdrop'
    var toggle = '[data-toggle=dropdown]'
    var Dropdown = function (element) {
        var $el = $(element).on('click.bs.dropdown', this.toggle)
    }

    Dropdown.prototype.toggle = function (e) {
        var $this = $(this)

        if ($this.is('.disabled, :disabled')) return

        var $parent = getParent($this)
        var isActive = $parent.hasClass('open')

        clearMenus()

        if (!isActive) {
            if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
                // if mobile we we use a backdrop because click events don't delegate
                $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
            }

            $parent.trigger(e = $.Event('show.bs.dropdown'))

            if (e.isDefaultPrevented()) return

            $parent
                .toggleClass('open')
                .trigger('shown.bs.dropdown')

            $this.trigger("focus")
        }

        return false
    }

    Dropdown.prototype.keydown = function (e) {
        if (!/(38|40|27)/.test(e.keyCode)) return

        var $this = $(this)

        e.preventDefault()
        e.stopPropagation()

        if ($this.is('.disabled, :disabled')) return

        var $parent = getParent($this)
        var isActive = $parent.hasClass('open')

        if (!isActive || (isActive && e.keyCode == 27)) {
            if (e.which == 27) $parent.find(toggle).trigger("focus")
            return $this.trigger("click")
        }

        var $items = $('[role=menu] li:not(.divider):visible a', $parent)

        if (!$items.length) return

        var index = $items.index($items.filter(':focus'))

        if (e.keyCode == 38 && index > 0) index--                        // up
        if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
        if (!~index) index = 0

        $items.eq(index).trigger("focus")
    }

    function clearMenus() {
        $(backdrop).remove()
        $(toggle).each(function (e) {
            var $parent = getParent($(this))
            if (!$parent.hasClass('open')) return
            $parent.trigger(e = $.Event('hide.bs.dropdown'))
            if (e.isDefaultPrevented()) return
            $parent.removeClass('open').trigger('hidden.bs.dropdown')
        })
    }

    function getParent($this) {
        var selector = $this.attr('data-target')

        if (!selector) {
            selector = $this.attr('href')
            selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
        }

        var $parent = selector && $(selector)

        return $parent && $parent.length ? $parent : $this.parent()
    }


    // DROPDOWN PLUGIN DEFINITION
    // ==========================

    var old = $.fn.dropdown

    $.fn.dropdown = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('dropdown')

            if (!data) $this.data('dropdown', (data = new Dropdown(this)))
            if (typeof option == 'string') data[option].call($this)
        })
    }

    $.fn.dropdown.Constructor = Dropdown


    // DROPDOWN NO CONFLICT
    // ====================

    $.fn.dropdown.noConflict = function () {
        $.fn.dropdown = old
        return this
    }


    // APPLY TO STANDARD DROPDOWN ELEMENTS
    // ===================================

    $(document)
        .on('click.bs.dropdown.data-api', clearMenus)
        .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
        .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
        .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]', Dropdown.prototype.keydown)

}(window.jQuery);

/* ========================================================================
 * Bootstrap: modal.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#modals
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // MODAL CLASS DEFINITION
    // ======================

    var Modal = function (element, options) {
        this.options = options
        this.$element = $(element)
        this.$backdrop =
            this.isShown = null

        if (this.options.remote) this.$element.on("load", this.options.remote)
    }

    Modal.DEFAULTS = {
        backdrop: true
        , keyboard: true
        , show: true
    }

    Modal.prototype.toggle = function (_relatedTarget) {
        return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
    }

    Modal.prototype.show = function (_relatedTarget) {
        var that = this
        var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })

        this.$element.trigger(e)

        if (this.isShown || e.isDefaultPrevented()) return

        this.isShown = true

        this.escape()

        this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))

        this.backdrop(function () {
            var transition = $.support.transition && that.$element.hasClass('fade')

            if (!that.$element.parent().length) {
                that.$element.appendTo(document.body) // don't move modals dom position
            }

            that.$element.show()

            if (transition) {
                that.$element[0].offsetWidth // force reflow
            }

            that.$element
                .addClass('in')
                .attr('aria-hidden', false)

            that.enforceFocus()

            var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })

            transition ?
                that.$element.find('.modal-dialog') // wait for modal to slide in
                    .one($.support.transition.end, function () {
                        that.$element.trigger("focus").trigger(e)
                    })
                    .emulateTransitionEnd(300) :
                that.$element.trigger("focus").trigger(e)
        })
    }

    Modal.prototype.hide = function (e) {
        if (e) e.preventDefault()

        e = $.Event('hide.bs.modal')

        this.$element.trigger(e)

        if (!this.isShown || e.isDefaultPrevented()) return

        this.isShown = false

        this.escape()

        $(document).off('focusin.bs.modal')

        this.$element
            .removeClass('in')
            .attr('aria-hidden', true)
            .off('click.dismiss.modal')

        $.support.transition && this.$element.hasClass('fade') ?
            this.$element
                .one($.support.transition.end, $.proxy(this.hideModal, this))
                .emulateTransitionEnd(300) :
            this.hideModal()
    }

    Modal.prototype.enforceFocus = function () {
        $(document)
            .off('focusin.bs.modal') // guard against infinite focus loop
            .on('focusin.bs.modal', $.proxy(function (e) {
                if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
                    this.$element.trigger("focus")
                }
            }, this))
    }

    Modal.prototype.escape = function () {
        if (this.isShown && this.options.keyboard) {
            this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
                e.which == 27 && this.hide()
            }, this))
        } else if (!this.isShown) {
            this.$element.off('keyup.dismiss.bs.modal')
        }
    }

    Modal.prototype.hideModal = function () {
        var that = this
        this.$element.hide()
        this.backdrop(function () {
            that.removeBackdrop()
            that.$element.trigger('hidden.bs.modal')
        })
    }

    Modal.prototype.removeBackdrop = function () {
        this.$backdrop && this.$backdrop.remove()
        this.$backdrop = null
    }

    Modal.prototype.backdrop = function (callback) {
        var that = this
        var animate = this.$element.hasClass('fade') ? 'fade' : ''

        if (this.isShown && this.options.backdrop) {
            var doAnimate = $.support.transition && animate

            this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
                .appendTo(document.body)

            this.$element.on('click.dismiss.modal', $.proxy(function (e) {
                if (e.target !== e.currentTarget) return
                this.options.backdrop == 'static'
                    ? this.$element[0].focus.call(this.$element[0])
                    : this.hide.call(this)
            }, this))

            if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

            this.$backdrop.addClass('in')

            if (!callback) return

            doAnimate ?
                this.$backdrop
                    .one($.support.transition.end, callback)
                    .emulateTransitionEnd(150) :
                callback()

        } else if (!this.isShown && this.$backdrop) {
            this.$backdrop.removeClass('in')

            $.support.transition && this.$element.hasClass('fade') ?
                this.$backdrop
                    .one($.support.transition.end, callback)
                    .emulateTransitionEnd(150) :
                callback()

        } else if (callback) {
            callback()
        }
    }


    // MODAL PLUGIN DEFINITION
    // =======================

    var old = $.fn.modal

    $.fn.modal = function (option, _relatedTarget) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.modal')
            var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

            if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
            if (typeof option == 'string') data[option](_relatedTarget)
            else if (options.show) data.show(_relatedTarget)
        })
    }

    $.fn.modal.Constructor = Modal


    // MODAL NO CONFLICT
    // =================

    $.fn.modal.noConflict = function () {
        $.fn.modal = old
        return this
    }


    // MODAL DATA-API
    // ==============

    $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
        var $this = $(this)
        var href = $this.attr('href')
        var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
        var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())

        e.preventDefault()

        $target
            .modal(option, this)
            .one('hide', function () {
                $this.is(':visible') && $this.trigger("focus")
            })
    })

    $(document)
        .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') })
        .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })

}(window.jQuery);

/* ========================================================================
 * Bootstrap: tooltip.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#tooltip
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // TOOLTIP PUBLIC CLASS DEFINITION
    // ===============================

    var Tooltip = function (element, options) {
        this.type =
            this.options =
            this.enabled =
            this.timeout =
            this.hoverState =
            this.$element = null

        this.init('tooltip', element, options)
    }

    Tooltip.DEFAULTS = {
        animation: true
        , placement: 'top'
        , selector: false
        , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
        , trigger: 'hover focus'
        , title: ''
        , delay: 0
        , html: false
        , container: false
    }

    Tooltip.prototype.init = function (type, element, options) {
        this.enabled = true
        this.type = type
        this.$element = $(element)
        this.options = this.getOptions(options)

        var triggers = this.options.trigger.split(' ')

        for (var i = triggers.length; i--;) {
            var trigger = triggers[i]

            if (trigger == 'click') {
                this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
            } else if (trigger != 'manual') {
                var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
                var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'

                this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
                this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
            }
        }

        this.options.selector ?
            (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
            this.fixTitle()
    }

    Tooltip.prototype.getDefaults = function () {
        return Tooltip.DEFAULTS
    }

    Tooltip.prototype.getOptions = function (options) {
        options = $.extend({}, this.getDefaults(), this.$element.data(), options)

        if (options.delay && typeof options.delay == 'number') {
            options.delay = {
                show: options.delay
                , hide: options.delay
            }
        }

        return options
    }

    Tooltip.prototype.getDelegateOptions = function () {
        var options = {}
        var defaults = this.getDefaults()

        this._options && $.each(this._options, function (key, value) {
            if (defaults[key] != value) options[key] = value
        })

        return options
    }

    Tooltip.prototype.enter = function (obj) {
        var self = obj instanceof this.constructor ?
            obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)

        clearTimeout(self.timeout)

        self.hoverState = 'in'

        if (!self.options.delay || !self.options.delay.show) return self.show()

        self.timeout = setTimeout(function () {
            if (self.hoverState == 'in') self.show()
        }, self.options.delay.show)
    }

    Tooltip.prototype.leave = function (obj) {
        var self = obj instanceof this.constructor ?
            obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)

        clearTimeout(self.timeout)

        self.hoverState = 'out'

        if (!self.options.delay || !self.options.delay.hide) return self.hide()

        self.timeout = setTimeout(function () {
            if (self.hoverState == 'out') self.hide()
        }, self.options.delay.hide)
    }

    Tooltip.prototype.show = function () {
        var e = $.Event('show.bs.' + this.type)

        if (this.hasContent() && this.enabled) {
            this.$element.trigger(e)

            if (e.isDefaultPrevented()) return

            var $tip = this.tip()

            this.setContent()

            if (this.options.animation) $tip.addClass('fade')

            var placement = typeof this.options.placement == 'function' ?
                this.options.placement.call(this, $tip[0], this.$element[0]) :
                this.options.placement

            var autoToken = /\s?auto?\s?/i
            var autoPlace = autoToken.test(placement)
            if (autoPlace) placement = placement.replace(autoToken, '') || 'top'

            $tip
                .detach()
                .css({ top: 0, left: 0, display: 'block' })
                .addClass(placement)

            this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)

            var pos = this.getPosition()
            var actualWidth = $tip[0].offsetWidth
            var actualHeight = $tip[0].offsetHeight

            if (autoPlace) {
                var $parent = this.$element.parent()

                var orgPlacement = placement
                var docScroll = document.documentElement.scrollTop || document.body.scrollTop
                var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth()
                var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
                var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left

                placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
                    placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
                        placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
                            placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
                                placement

                $tip
                    .removeClass(orgPlacement)
                    .addClass(placement)
            }

            var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

            this.applyPlacement(calculatedOffset, placement)
            this.$element.trigger('shown.bs.' + this.type)
        }
    }

    Tooltip.prototype.applyPlacement = function (offset, placement) {
        var replace
        var $tip = this.tip()
        var width = $tip[0].offsetWidth
        var height = $tip[0].offsetHeight

        // manually read margins because getBoundingClientRect includes difference
        var marginTop = parseInt($tip.css('margin-top'), 10)
        var marginLeft = parseInt($tip.css('margin-left'), 10)

        // we must check for NaN for ie 8/9
        if (isNaN(marginTop)) marginTop = 0
        if (isNaN(marginLeft)) marginLeft = 0

        offset.top = offset.top + marginTop
        offset.left = offset.left + marginLeft

        $tip
            .offset(offset)
            .addClass('in')

        // check to see if placing tip in new offset caused the tip to resize itself
        var actualWidth = $tip[0].offsetWidth
        var actualHeight = $tip[0].offsetHeight

        if (placement == 'top' && actualHeight != height) {
            replace = true
            offset.top = offset.top + height - actualHeight
        }

        if (/bottom|top/.test(placement)) {
            var delta = 0

            if (offset.left < 0) {
                delta = offset.left * -2
                offset.left = 0

                $tip.offset(offset)

                actualWidth = $tip[0].offsetWidth
                actualHeight = $tip[0].offsetHeight
            }

            this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
        } else {
            this.replaceArrow(actualHeight - height, actualHeight, 'top')
        }

        if (replace) $tip.offset(offset)
    }

    Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
        this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
    }

    Tooltip.prototype.setContent = function () {
        var $tip = this.tip()
        var title = this.getTitle()

        $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
        $tip.removeClass('fade in top bottom left right')
    }

    Tooltip.prototype.hide = function () {
        var that = this
        var $tip = this.tip()
        var e = $.Event('hide.bs.' + this.type)

        function complete() {
            if (that.hoverState != 'in') $tip.detach()
        }

        this.$element.trigger(e)

        if (e.isDefaultPrevented()) return

        $tip.removeClass('in')

        $.support.transition && this.$tip.hasClass('fade') ?
            $tip
                .one($.support.transition.end, complete)
                .emulateTransitionEnd(150) :
            complete()

        this.$element.trigger('hidden.bs.' + this.type)

        return this
    }

    Tooltip.prototype.fixTitle = function () {
        var $e = this.$element
        if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
            $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
        }
    }

    Tooltip.prototype.hasContent = function () {
        return this.getTitle()
    }

    Tooltip.prototype.getPosition = function () {
        var el = this.$element[0]
        return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
            width: el.offsetWidth
            , height: el.offsetHeight
        }, this.$element.offset())
    }

    Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
        return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
            placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
                placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
    }

    Tooltip.prototype.getTitle = function () {
        var title
        var $e = this.$element
        var o = this.options

        title = $e.attr('data-original-title')
            || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)

        return title
    }

    Tooltip.prototype.tip = function () {
        return this.$tip = this.$tip || $(this.options.template)
    }

    Tooltip.prototype.arrow = function () {
        return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
    }

    Tooltip.prototype.validate = function () {
        if (!this.$element[0].parentNode) {
            this.hide()
            this.$element = null
            this.options = null
        }
    }

    Tooltip.prototype.enable = function () {
        this.enabled = true
    }

    Tooltip.prototype.disable = function () {
        this.enabled = false
    }

    Tooltip.prototype.toggleEnabled = function () {
        this.enabled = !this.enabled
    }

    Tooltip.prototype.toggle = function (e) {
        var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
        self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
    }

    Tooltip.prototype.destroy = function () {
        this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
    }


    // TOOLTIP PLUGIN DEFINITION
    // =========================

    var old = $.fn.tooltip

    $.fn.tooltip = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.tooltip')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.tooltip.Constructor = Tooltip


    // TOOLTIP NO CONFLICT
    // ===================

    $.fn.tooltip.noConflict = function () {
        $.fn.tooltip = old
        return this
    }

}(window.jQuery);

/* ========================================================================
 * Bootstrap: popover.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#popovers
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // POPOVER PUBLIC CLASS DEFINITION
    // ===============================

    var Popover = function (element, options) {
        this.init('popover', element, options)
    }

    if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')

    Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
        placement: 'right'
        , trigger: 'click'
        , content: ''
        , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
    })


    // NOTE: POPOVER EXTENDS tooltip.js
    // ================================

    Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)

    Popover.prototype.constructor = Popover

    Popover.prototype.getDefaults = function () {
        return Popover.DEFAULTS
    }

    Popover.prototype.setContent = function () {
        var $tip = this.tip()
        var title = this.getTitle()
        var content = this.getContent()

        $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
        $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)

        $tip.removeClass('fade top bottom left right in')

        // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
        // this manually by checking the contents.
        if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
    }

    Popover.prototype.hasContent = function () {
        return this.getTitle() || this.getContent()
    }

    Popover.prototype.getContent = function () {
        var $e = this.$element
        var o = this.options

        return $e.attr('data-content')
            || (typeof o.content == 'function' ?
                o.content.call($e[0]) :
                o.content)
    }

    Popover.prototype.arrow = function () {
        return this.$arrow = this.$arrow || this.tip().find('.arrow')
    }

    Popover.prototype.tip = function () {
        if (!this.$tip) this.$tip = $(this.options.template)
        return this.$tip
    }


    // POPOVER PLUGIN DEFINITION
    // =========================

    var old = $.fn.popover

    $.fn.popover = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.popover')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.popover.Constructor = Popover


    // POPOVER NO CONFLICT
    // ===================

    $.fn.popover.noConflict = function () {
        $.fn.popover = old
        return this
    }

}(window.jQuery);

/* ========================================================================
 * Bootstrap: scrollspy.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#scrollspy
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // SCROLLSPY CLASS DEFINITION
    // ==========================

    function ScrollSpy(element, options) {
        var href
        var process = $.proxy(this.process, this)

        this.$element = $(element).is('body') ? $(window) : $(element)
        this.$body = $('body')
        this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
        this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
        this.selector = (this.options.target
            || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
            || '') + ' .nav li > a'
        this.offsets = $([])
        this.targets = $([])
        this.activeTarget = null

        this.refresh()
        this.process()
    }

    ScrollSpy.DEFAULTS = {
        offset: 10
    }

    ScrollSpy.prototype.refresh = function () {
        var offsetMethod = this.$element[0] == window ? 'offset' : 'position'

        this.offsets = $([])
        this.targets = $([])

        var self = this
        var $targets = this.$body
            .find(this.selector)
            .map(function () {
                var $el = $(this)
                var href = $el.data('target') || $el.attr('href')
                var $href = /^#\w/.test(href) && $(href)

                return ($href
                    && $href.length
                    && [[$href[offsetMethod]().top + (!(self.$scrollElement.get(0) != null && self.$scrollElement.get(0) == self.$scrollElement.get(0).window) && self.$scrollElement.scrollTop()), href]]) || null
            })
            .sort(function (a, b) { return a[0] - b[0] })
            .each(function () {
                self.offsets.push(this[0])
                self.targets.push(this[1])
            })
    }

    ScrollSpy.prototype.process = function () {
        var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
        var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
        var maxScroll = scrollHeight - this.$scrollElement.height()
        var offsets = this.offsets
        var targets = this.targets
        var activeTarget = this.activeTarget
        var i

        if (scrollTop >= maxScroll) {
            return activeTarget != (i = targets.last()[0]) && this.activate(i)
        }

        for (i = offsets.length; i--;) {
            activeTarget != targets[i]
                && scrollTop >= offsets[i]
                && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
                && this.activate(targets[i])
        }
    }

    ScrollSpy.prototype.activate = function (target) {
        this.activeTarget = target

        $(this.selector)
            .parents('.active')
            .removeClass('active')

        var selector = this.selector
            + '[data-target="' + target + '"],'
            + this.selector + '[href="' + target + '"]'

        var active = $(selector)
            .parents('li')
            .addClass('active')

        if (active.parent('.dropdown-menu').length) {
            active = active
                .closest('li.dropdown')
                .addClass('active')
        }

        active.trigger('activate')
    }


    // SCROLLSPY PLUGIN DEFINITION
    // ===========================

    var old = $.fn.scrollspy

    $.fn.scrollspy = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.scrollspy')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.scrollspy.Constructor = ScrollSpy


    // SCROLLSPY NO CONFLICT
    // =====================

    $.fn.scrollspy.noConflict = function () {
        $.fn.scrollspy = old
        return this
    }


    // SCROLLSPY DATA-API
    // ==================

    $(window).on('load', function () {
        $('[data-spy="scroll"]').each(function () {
            var $spy = $(this)
            $spy.scrollspy($spy.data())
        })
    })

}(window.jQuery);

/* ========================================================================
 * Bootstrap: tab.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#tabs
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // TAB CLASS DEFINITION
    // ====================

    var Tab = function (element) {
        this.element = $(element)
    }

    Tab.prototype.show = function () {
        var $this = this.element
        var $ul = $this.closest('ul:not(.dropdown-menu)')
        var selector = $this.attr('data-target')

        if (!selector) {
            selector = $this.attr('href')
            selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
        }

        if ($this.parent('li').hasClass('active')) return

        var previous = $ul.find('.active').last().find('a')[0]
        var e = $.Event('show.bs.tab', {
            relatedTarget: previous
        })

        $this.trigger(e)

        if (e.isDefaultPrevented()) return

        //jQuery Upgrade bug
        //When selector is equal to #, replace with empty string
        if (selector === "#")
            selector = '';

        var $target = $(selector)

        this.activate($this.parent('li'), $ul)
        this.activate($target, $target.parent(), function () {
            $this.trigger({
                type: 'shown.bs.tab'
                , relatedTarget: previous
            })
        })
    }

    Tab.prototype.activate = function (element, container, callback) {
        var $active = container.find('> .active')
        var transition = callback
            && $.support.transition
            && $active.hasClass('fade')

        function next() {
            $active
                .removeClass('active')
                .find('> .dropdown-menu > .active')
                .removeClass('active')

            element.addClass('active')

            if (transition) {
                element[0].offsetWidth // reflow for transition
                element.addClass('in')
            } else {
                element.removeClass('fade')
            }

            if (element.parent('.dropdown-menu')) {
                element.closest('li.dropdown').addClass('active')
            }

            callback && callback()
        }

        transition ?
            $active
                .one($.support.transition.end, next)
                .emulateTransitionEnd(150) :
            next()

        $active.removeClass('in')
    }


    // TAB PLUGIN DEFINITION
    // =====================

    var old = $.fn.tab

    $.fn.tab = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.tab')

            if (!data) $this.data('bs.tab', (data = new Tab(this)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.tab.Constructor = Tab


    // TAB NO CONFLICT
    // ===============

    $.fn.tab.noConflict = function () {
        $.fn.tab = old
        return this
    }


    // TAB DATA-API
    // ============

    $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
        e.preventDefault()
        $(this).tab('show')
    })

}(window.jQuery);

/* ========================================================================
 * Bootstrap: affix.js v3.0.0
 * http://twbs.github.com/bootstrap/javascript.html#affix
 * ========================================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================================== */


+function ($) {
    "use strict";

    // AFFIX CLASS DEFINITION
    // ======================

    var Affix = function (element, options) {
        this.options = $.extend({}, Affix.DEFAULTS, options)
        this.$window = $(window)
            .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
            .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))

        this.$element = $(element)
        this.affixed =
            this.unpin = null

        this.checkPosition()
    }

    Affix.RESET = 'affix affix-top affix-bottom'

    Affix.DEFAULTS = {
        offset: 0
    }

    Affix.prototype.checkPositionWithEventLoop = function () {
        setTimeout($.proxy(this.checkPosition, this), 1)
    }

    Affix.prototype.checkPosition = function () {
        if (!this.$element.is(':visible')) return

        var scrollHeight = $(document).height()
        var scrollTop = this.$window.scrollTop()
        var position = this.$element.offset()
        var offset = this.options.offset
        var offsetTop = offset.top
        var offsetBottom = offset.bottom

        if (typeof offset != 'object') offsetBottom = offsetTop = offset
        if (typeof offsetTop == 'function') offsetTop = offset.top()
        if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()

        var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
            offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
                offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false

        if (this.affixed === affix) return
        if (this.unpin) this.$element.css('top', '')

        this.affixed = affix
        this.unpin = affix == 'bottom' ? position.top - scrollTop : null

        this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))

        if (affix == 'bottom') {
            this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() })
        }
    }


    // AFFIX PLUGIN DEFINITION
    // =======================

    var old = $.fn.affix

    $.fn.affix = function (option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.affix')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    $.fn.affix.Constructor = Affix


    // AFFIX NO CONFLICT
    // =================

    $.fn.affix.noConflict = function () {
        $.fn.affix = old
        return this
    }


    // AFFIX DATA-API
    // ==============

    $(window).on('load', function () {
        $('[data-spy="affix"]').each(function () {
            var $spy = $(this)
            var data = $spy.data()

            data.offset = data.offset || {}

            if (data.offsetBottom) data.offset.bottom = data.offsetBottom
            if (data.offsetTop) data.offset.top = data.offsetTop

            $spy.affix(data)
        })
    })

}(window.jQuery);

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\bootstrap-select.js
/*version 2*/
/*!
 * bootstrap-select v1.4.2
 * http://silviomoreto.github.io/bootstrap-select/
 *
 * Copyright 2013 bootstrap-select
 * Licensed under the MIT license
 */

!function ($) {

    'use strict';

    $.expr.pseudos.icontains = function (obj, index, meta) {
        return $(obj).text().toUpperCase().indexOf(meta[3].toUpperCase()) >= 0;
    };

    var Selectpicker = function (element, options, e) {
        if (e) {
            e.stopPropagation();
            e.preventDefault();
        }
        this.$element = $(element);
        this.$newElement = null;
        this.$button = null;
        this.$menu = null;

        //Merge defaults, options and data-attributes to make our options
        this.options = $.extend({}, $.fn.selectpicker.defaults, this.$element.data(), typeof options == 'object' && options);

        //If we have no title yet, check the attribute 'title' (this is missed by jq as its not a data-attribute
        if (this.options.title === null) {
            this.options.title = this.$element.attr('title');
        }

        //Expose public methods
        this.val = Selectpicker.prototype.val;
        this.render = Selectpicker.prototype.render;
        this.refresh = Selectpicker.prototype.refresh;
        this.setStyle = Selectpicker.prototype.setStyle;
        this.selectAll = Selectpicker.prototype.selectAll;
        this.deselectAll = Selectpicker.prototype.deselectAll;
        this.init();
    };

    Selectpicker.prototype = {

        constructor: Selectpicker,

        init: function () {
            this.$element.hide();
            this.multiple = this.$element.prop('multiple');
            var id = this.$element.attr('id');
            this.$newElement = this.createView();
            this.$element.after(this.$newElement);
            this.$menu = this.$newElement.find('> .dropdown-menu');
            this.$button = this.$newElement.find('> button');
            this.$searchbox = this.$newElement.find('input');

            if (id !== undefined) {
                var that = this;
                this.$button.attr('data-id', id);
                $('label[for="' + id + '"]').on("click", function (e) {
                    e.preventDefault();
                    that.$button.trigger("focus");
                });
            }

            this.checkDisabled();
            this.clickListener();
            if (this.options.liveSearch) {
                this.liveSearchListener();
            }
            this.render();
            this.liHeight();
            this.setStyle();
            this.setWidth();
            if (this.options.container) {
                this.selectPosition();
            }
            this.$menu.data('this', this);
            this.$newElement.data('this', this);
        },

        createDropdown: function () {
            //If we are multiple, then add the show-tick class by default
            var multiple = this.multiple ? ' show-tick' : '';
            var header = this.options.header ? '<div class="popover-title"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + '</div>' : '';
            var searchbox = this.options.liveSearch ? '<div class="bootstrap-select-searchbox"><input type="text" class="input-block-level form-control" /></div>' : '';
            var drop =
                '<div class="btn-group bootstrap-select' + multiple + '" role="combobox">' +
                '<button type="button" class="btn filter-option" data-toggle="dropdown">' +
                '</button>' +
                '<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" tabindex="-1">' +
                '<span class="acn-icon icon-arrow-dropdown"></span>' +
                '<span class="sr-only">Toggle Dropdown</span>' +
                '</button>' +

                '<div class="dropdown-menu open">' +
                header +
                searchbox +
                '<ul class="dropdown-menu inner " role="menu">' +
                '</ul>' +
                '</div>' +
                '</div>';

            return $(drop);
        },

        createView: function () {
            var $drop = this.createDropdown();
            //[AJS 01/08] Accessibility Relationship_between_slider_and_content_pane -start
            if (typeof this.$element.data('ul-id') != "undefined" && this.$element.data('label-id') != "undefined") {
                $drop.attr({
                    'aria-labelledby': this.$element.data('label-id'),
                    'aria-owns': this.$element.data('ul-id')
                });
                $drop.find('ul').attr('id', this.$element.data('ul-id'));
            }
            //-end
            var $li = this.createLi();
            $drop.find('ul').append($li);
            return $drop;
        },

        reloadLi: function () {
            //Remove all children.
            this.destroyLi();
            //Re build
            var $li = this.createLi();
            this.$menu.find('ul').append($li);
        },

        destroyLi: function () {
            this.$menu.find('li').remove();
        },

        createLi: function () {
            var that = this,
                _liA = [],
                _liHtml = '';

            this.$element.find('option').each(function () {
                var $this = $(this);

                //Get the class and text for the option
                var optionClass = $this.attr('class') || '';
                var inline = $this.attr('style') || '';
                var text = $this.data('content') ? $this.data('content') : $this.html();
                var subtext = $this.data('subtext') !== undefined ? '<small class="muted text-muted">' + $this.data('subtext') + '</small>' : '';
                var icon = $this.data('icon') !== undefined ? '<i class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></i> ' : '';
                if (icon !== '' && ($this.is(':disabled') || $this.parent().is(':disabled'))) {
                    icon = '<span>' + icon + '</span>';
                }

                if (!$this.data('content')) {
                    //Prepend any icon and append any subtext to the main text.
                    text = icon + '<span class="text">' + text + subtext + '</span>';
                }

                if (that.options.hideDisabled && ($this.is(':disabled') || $this.parent().is(':disabled'))) {
                    _liA.push('<a style="min-height: 0; padding: 0"></a>');
                } else if ($this.parent().is('optgroup') && $this.data('divider') !== true) {
                    if ($this.index() === 0) {
                        //Get the opt group label
                        var label = $this.parent().attr('label');
                        var labelSubtext = $this.parent().data('subtext') !== undefined ? '<small class="muted text-muted">' + $this.parent().data('subtext') + '</small>' : '';
                        var labelIcon = $this.parent().data('icon') ? '<i class="' + $this.parent().data('icon') + '"></i> ' : '';
                        label = labelIcon + '<span class="text">' + label + labelSubtext + '</span>';

                        if ($this[0].index !== 0) {
                            _liA.push(
                                '<div class="div-contain"><div class="divider"></div></div>' +
                                '<dt>' + label + '</dt>' +
                                that.createA(text, 'opt ' + optionClass, inline)
                            );
                        } else {
                            _liA.push(
                                '<dt>' + label + '</dt>' +
                                that.createA(text, 'opt ' + optionClass, inline));
                        }
                    } else {
                        _liA.push(that.createA(text, 'opt ' + optionClass, inline));
                    }
                } else if ($this.data('divider') === true) {
                    _liA.push('<div class="div-contain"><div class="divider"></div></div>');
                } else if ($(this).data('hidden') === true) {
                    _liA.push('');
                } else {
                    _liA.push(that.createA(text, optionClass, inline));
                }
            });

            $.each(_liA, function (i, item) {
                _liHtml += '<li rel=' + i + '>' + item + '</li>';
            });

            //If we are not multiple, and we dont have a selected item, and we dont have a title, select the first element so something is set in the button
            if (!this.multiple && this.$element.find('option:selected').length === 0 && !this.options.title) {
                this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected');
            }

            return $(_liHtml);
        },

        createA: function (text, classes, inline) {
            return '<a tabindex="0" class="' + classes + '" style="' + inline + '">' +
                text +
                '<i class="' + this.options.iconBase + ' ' + this.options.tickIcon + ' icon-ok check-mark"></i>' +
                '</a>';
        },

        render: function () {
            var that = this;

            //Update the LI to match the SELECT
            this.$element.find('option').each(function (index) {
                that.setDisabled(index, $(this).is(':disabled') || $(this).parent().is(':disabled'));
                that.setSelected(index, $(this).is(':selected'));
            });

            this.tabIndex();

            var selectedItems = this.$element.find('option:selected').map(function () {
                var $this = $(this);
                var icon = $this.data('icon') && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></i> ' : '';
                var subtext;
                if (that.options.showSubtext && $this.attr('data-subtext') && !that.multiple) {
                    subtext = ' <small class="muted text-muted">' + $this.data('subtext') + '</small>';
                } else {
                    subtext = '';
                }
                if ($this.data('content') && that.options.showContent) {
                    return $this.data('content');
                } else if ($this.attr('title') !== undefined) {
                    return $this.attr('title');
                } else {
                    return icon + $this.html() + subtext;
                }
            }).toArray();

            //Fixes issue in IE10 occurring when no default option is selected and at least one option is disabled
            //Convert all the values into a comma delimited string
            var title = !this.multiple ? selectedItems[0] : selectedItems.join(this.options.multipleSeparator);

            //If this is multi select, and the selectText type is count, the show 1 of 2 selected etc..
            if (this.multiple && this.options.selectedTextFormat.indexOf('count') > -1) {
                var max = this.options.selectedTextFormat.split('>');
                var notDisabled = this.options.hideDisabled ? ':not([disabled])' : '';
                if ((max.length > 1 && selectedItems.length > max[1]) || (max.length == 1 && selectedItems.length >= 2)) {
                    title = this.options.countSelectedText.replace('{0}', selectedItems.length).replace('{1}', this.$element.find('option:not([data-divider="true"]):not([data-hidden="true"])' + notDisabled).length);
                }
            }

            //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
            if (!title) {
                title = this.options.title !== undefined ? this.options.title : this.options.noneSelectedText;
            }

            this.$button.attr('title', $.trim(title));
            this.$newElement.find('.filter-option').html('<span class="shortText dotdot">' + title + '</span>');
        },

        setStyle: function (style, status) {
            if (this.$element.attr('class')) {
                this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device/gi, ''));
            }

            var buttonClass = style ? style : this.options.style;

            if (status == 'add') {
                this.$button.addClass(buttonClass);
            } else if (status == 'remove') {
                this.$button.removeClass(buttonClass);
            } else {
                this.$button.removeClass(this.options.style);
                this.$button.addClass(buttonClass);
            }
        },

        liHeight: function () {
            var $selectClone = this.$menu.parent().clone().appendTo('body'),
                $menuClone = $selectClone.addClass('open').find('> .dropdown-menu'),
                liHeight = $menuClone.find('li > a').outerHeight(),
                headerHeight = this.options.header ? $menuClone.find('.popover-title').outerHeight() : 0,
                searchHeight = this.options.liveSearch ? $menuClone.find('.bootstrap-select-searchbox').outerHeight() : 0;

            $selectClone.remove();

            this.$newElement
                .data('liHeight', liHeight)
                .data('headerHeight', headerHeight)
                .data('searchHeight', searchHeight);
        },

        setSize: function () {
            var that = this,
                menu = this.$menu,
                menuInner = menu.find('.inner'),
                selectHeight = this.$newElement.outerHeight(),
                liHeight = this.$newElement.data('liHeight'),
                headerHeight = this.$newElement.data('headerHeight'),
                searchHeight = this.$newElement.data('searchHeight'),
                divHeight = menu.find('li .divider').outerHeight(true),
                menuPadding = parseInt(menu.css('padding-top')) +
                    parseInt(menu.css('padding-bottom')) +
                    parseInt(menu.css('border-top-width')) +
                    parseInt(menu.css('border-bottom-width')),
                notDisabled = this.options.hideDisabled ? ':not(.disabled)' : '',
                $window = $(window),
                menuExtras = menuPadding + parseInt(menu.css('margin-top')) + parseInt(menu.css('margin-bottom')) + 2,
                menuHeight,
                selectOffsetTop,
                selectOffsetBot,
                posVert = function () {
                    selectOffsetTop = that.$newElement.offset().top - $window.scrollTop();
                    selectOffsetBot = $window.height() - selectOffsetTop - selectHeight;
                };
            posVert();
            if (this.options.header) menu.css('padding-top', 0);

            if (this.options.size == 'auto') {
                var getSize = function () {
                    var minHeight;
                    posVert();
                    menuHeight = selectOffsetBot - menuExtras;
                    if (that.options.dropupAuto) {
                        that.$newElement.toggleClass('dropup', (selectOffsetTop > selectOffsetBot) && ((menuHeight - menuExtras) < menu.height()));
                    }
                    if (that.$newElement.hasClass('dropup')) {
                        menuHeight = selectOffsetTop - menuExtras - 70; // restricting height of the menu up to global nav
                    }
                    if ((menu.find('li').length + menu.find('dt').length) > 3) {
                        minHeight = liHeight * 3 + menuExtras - 2;
                    } else {
                        minHeight = 0;
                    }
                    menu.css({ 'max-height': menuHeight + 'px', 'overflow': 'hidden', 'min-height': minHeight + 'px' });
                    menuInner.css({ 'max-height': menuHeight - headerHeight - searchHeight - menuPadding + 'px', 'overflow-y': 'auto', 'min-height': minHeight - menuPadding + 'px' });
                };
                getSize();
                $(window).on("resize", getSize);
                $(window).on("scroll", getSize);
            } else if (this.options.size && this.options.size != 'auto' && menu.find('li' + notDisabled).length > this.options.size) {
                var optIndex = menu.find('li' + notDisabled + ' > *').filter(':not(.div-contain)').slice(0, this.options.size).last().parent().index();
                var divLength = menu.find('li').slice(0, optIndex + 1).find('.div-contain').length;
                menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding;
                if (that.options.dropupAuto) {
                    this.$newElement.toggleClass('dropup', (selectOffsetTop > selectOffsetBot) && (menuHeight < menu.height()));
                }
                menu.css({ 'max-height': menuHeight + headerHeight + searchHeight + 'px', 'overflow': 'hidden' });
                menuInner.css({ 'max-height': menuHeight - menuPadding + 'px', 'overflow-y': 'auto' });
            }
        },

        setWidth: function () {
            if (this.options.width == 'auto') {
                this.$menu.css('min-width', '0');

                // Get correct width if element hidden
                var selectClone = this.$newElement.clone().appendTo('body');
                var ulWidth = selectClone.find('> .dropdown-menu').css('width');
                selectClone.remove();

                this.$newElement.css('width', ulWidth);
            } else if (this.options.width == 'fit') {
                // Remove inline min-width so width can be changed from 'auto'
                this.$menu.css('min-width', '');
                this.$newElement.css('width', '').addClass('fit-width');
            } else if (this.options.width) {
                // Remove inline min-width so width can be changed from 'auto'
                this.$menu.css('min-width', '');
                this.$newElement.css('width', this.options.width);
            } else {
                // Remove inline min-width/width so width can be changed
                this.$menu.css('min-width', '');
                this.$newElement.css('width', '');
            }
            // Remove fit-width class if width is changed programmatically
            if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
                this.$newElement.removeClass('fit-width');
            }
        },

        selectPosition: function () {
            var that = this,
                drop = '<div />',
                $drop = $(drop),
                pos,
                actualHeight,
                getPlacement = function ($element) {
                    $drop.addClass($element.attr('class')).toggleClass('dropup', $element.hasClass('dropup'));
                    pos = $element.offset();
                    actualHeight = $element.hasClass('dropup') ? 0 : $element[0].offsetHeight;
                    $drop.css({ 'top': pos.top + actualHeight, 'left': pos.left, 'width': $element[0].offsetWidth, 'position': 'absolute' });
                };
            this.$newElement.on('click', function () {
                getPlacement($(this));
                $drop.appendTo(that.options.container);
                $drop.toggleClass('open', !$(this).hasClass('open'));
                $drop.append(that.$menu);
            });
            $(window).on("resize", function () {
                getPlacement(that.$newElement);
            });
            $(window).on('scroll', function () {
                getPlacement(that.$newElement);
            });
            $('html').on('click', function (e) {
                if ($(e.target).closest(that.$newElement).length < 1) {
                    $drop.removeClass('open');
                }
            });
        },

        mobile: function () {
            this.$element.addClass('mobile-device').appendTo(this.$newElement);
            if (this.options.container) this.$menu.hide();
        },

        refresh: function () {
            this.reloadLi();
            this.render();
            this.setWidth();
            this.setStyle();
            this.checkDisabled();
            this.liHeight();
        },

        update: function () {
            this.reloadLi();
            this.setWidth();
            this.setStyle();
            this.checkDisabled();
            this.liHeight();
        },

        setSelected: function (index, selected) {
            this.$menu.find('li').eq(index).toggleClass('selected', selected);
        },

        setDisabled: function (index, disabled) {
            if (disabled) {
                this.$menu.find('li').eq(index).addClass('disabled').find('a').attr('href', '#').attr('tabindex', -1);
            } else {
                this.$menu.find('li').eq(index).removeClass('disabled').find('a').removeAttr('href').attr('tabindex', 0);
            }
        },

        isDisabled: function () {
            return this.$element.is(':disabled');
        },

        checkDisabled: function () {
            var that = this;

            if (this.isDisabled()) {
                this.$button.addClass('disabled').attr('tabindex', -1);
            } else {
                if (this.$button.hasClass('disabled')) {
                    this.$button.removeClass('disabled');
                }

                if (this.$button.attr('tabindex') == -1) {
                    if (!this.$element.data('tabindex')) this.$button.removeAttr('tabindex');
                }
            }

            this.$button.on("click", function () {
                return !that.isDisabled();
            });
        },

        tabIndex: function () {
            if (this.$element.is('[tabindex]')) {
                this.$element.data('tabindex', this.$element.attr('tabindex'));
                this.$button.attr('tabindex', this.$element.data('tabindex'));
            }
        },

        clickListener: function () {
            var that = this;

            $('body').on('touchstart.dropdown', '.dropdown-menu', function (e) {
                e.stopPropagation();
            });

            this.$newElement.on('click', function () {
                that.setSize();
                if (!that.options.liveSearch && !that.multiple) {
                    setTimeout(function () {
                        that.$menu.find('.selected a').trigger("focus");
                    }, 10);
                }
            });

            this.$menu.on('click', 'li a', function (e) {
                var clickedIndex = $(this).parent().index(),
                    prevValue = that.$element.val(),
                    prevIndex = that.$element.prop('selectedIndex');

                //Dont close on multi choice menu
                if (that.multiple) {
                    e.stopPropagation();
                }

                e.preventDefault();

                //Dont run if we have been disabled
                if (!that.isDisabled() && !$(this).parent().hasClass('disabled')) {
                    var $options = that.$element.find('option');
                    var $option = $options.eq(clickedIndex);

                    //Deselect all others if not multi select box
                    if (!that.multiple) {
                        $options.prop('selected', false);
                        $option.prop('selected', true);
                    }
                    //Else toggle the one we have chosen if we are multi select.
                    else {
                        var state = $option.prop('selected');

                        $option.prop('selected', !state);
                    }

                    if (!that.multiple) {
                        that.$button.trigger("focus");
                    } else if (that.options.liveSearch) {
                        that.$searchbox.trigger("focus");
                    }

                    // Trigger select 'change'
                    if ((prevValue != that.$element.val() && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
                        that.$element.trigger("change");
                    }
                }
            });

            this.$menu.on('click', 'li.disabled a, li dt, li .div-contain, .popover-title, .popover-title :not(.close)', function (e) {
                if (e.target == this) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (!that.options.liveSearch) {
                        that.$button.trigger("focus");
                    } else {
                        that.$searchbox.trigger("focus");
                    }
                }
            });

            this.$menu.on('click', '.popover-title .close', function () {
                that.$button.trigger("focus");
            });

            this.$searchbox.on('click', function (e) {
                e.stopPropagation();
            });

            this.$element.on("change", function () {
                that.render();
            });
        },

        liveSearchListener: function () {
            var that = this,
                no_results = $('<li class="no-results"></li>');

            this.$newElement.on('click.dropdown.data-api', function () {
                that.$menu.find('.active').removeClass('active');
                if (!!that.$searchbox.val()) {
                    that.$searchbox.val('');
                    that.$menu.find('li').show();
                    if (!!no_results.parent().length) no_results.remove();
                }
                if (!that.multiple) that.$menu.find('.selected').addClass('active');
                setTimeout(function () {
                    that.$searchbox.trigger("focus");
                }, 10);
            });

            this.$searchbox.on('input propertychange', function () {
                if (that.$searchbox.val()) {
                    that.$menu.find('li').show().not(':icontains(' + that.$searchbox.val() + ')').hide();

                    if (!that.$menu.find('li').filter(':visible:not(.no-results)').length) {
                        if (!!no_results.parent().length) no_results.remove();
                        no_results.html('No results match "' + that.$searchbox.val() + '"').show();
                        that.$menu.find('li').last().after(no_results);
                    } else if (!!no_results.parent().length) {
                        no_results.remove();
                    }

                } else {
                    that.$menu.find('li').show();
                    if (!!no_results.parent().length) no_results.remove();
                }

                that.$menu.find('li.active').removeClass('active');
                that.$menu.find('li').filter(':visible:not(.divider)').eq(0).addClass('active').find('a').trigger("focus");
                $(this).trigger("focus");
            });

            this.$menu.on('mouseenter', 'a', function (e) {
                that.$menu.find('.active').removeClass('active');
                $(e.currentTarget).parent().not('.disabled').addClass('active');
            });

            this.$menu.on('mouseleave', 'a', function () {
                that.$menu.find('.active').removeClass('active');
            });
        },

        val: function (value) {

            if (value !== undefined) {
                this.$element.val(value);

                this.$element.trigger("change");
                return this.$element;
            } else {
                return this.$element.val();
            }
        },

        selectAll: function () {
            this.$element.find('option').prop('selected', true).attr('selected', 'selected');
            this.render();
        },

        deselectAll: function () {
            this.$element.find('option').prop('selected', false);
            this.render();
        },

        keydown: function (e) {
            var $this,
                $items,
                $parent,
                index,
                next,
                first,
                last,
                prev,
                nextPrev,
                that,
                prevIndex,
                isActive,
                keyCodeMap = {
                    32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', 54: '6', 55: '7', 56: '8', 57: '9', 59: ';',
                    65: 'a', 66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h', 73: 'i', 74: 'j', 75: 'k', 76: 'l',
                    77: 'm', 78: 'n', 79: 'o', 80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v', 87: 'w', 88: 'x',
                    89: 'y', 90: 'z', 96: '0', 97: '1', 98: '2', 99: '3', 100: '4', 101: '5', 102: '6', 103: '7', 104: '8', 105: '9'
                };

            $this = $(this);

            $parent = $this.parent();

            if ($this.is('input')) $parent = $this.parent().parent();

            that = $parent.data('this');

            if (that.options.liveSearch) $parent = $this.parent().parent();

            if (that.options.container) $parent = that.$menu;

            $items = $('[role=menu] li:not(.divider) a', $parent);

            isActive = that.$menu.parent().hasClass('open');

            if (that.options.liveSearch) {
                if (/(^9$|27)/.test(e.keyCode) && isActive && that.$menu.find('.active').length === 0) {
                    e.preventDefault();
                    that.$menu.parent().removeClass('open');
                    that.$button.trigger("focus");
                }
                $items = $('[role=menu] li:not(.divider):visible', $parent);
                if (!$this.val() && !/(38|40)/.test(e.keyCode)) {
                    if ($items.filter('.active').length === 0) {
                        $items = that.$newElement.find('li').filter(':icontains(' + keyCodeMap[e.keyCode] + ')');
                    }
                }
            }

            if (!$items.length) return;

            if (/(38|40)/.test(e.keyCode)) {

                if (!isActive) {
                    that.$menu.parent().addClass('open');
                }

                index = $items.index($items.filter(':focus'));
                first = $items.parent(':not(.disabled):visible').first().index();
                last = $items.parent(':not(.disabled):visible').last().index();
                next = $items.eq(index).parent().nextAll(':not(.disabled):visible').eq(0).index();
                prev = $items.eq(index).parent().prevAll(':not(.disabled):visible').eq(0).index();
                nextPrev = $items.eq(next).parent().prevAll(':not(.disabled):visible').eq(0).index();

                if (that.options.liveSearch) {
                    $items.each(function (i) {
                        if ($(this).is(':not(.disabled)')) {
                            $(this).data('index', i);
                        }
                    });
                    index = $items.index($items.filter('.active'));
                    first = $items.filter(':not(.disabled):visible').first().data('index');
                    last = $items.filter(':not(.disabled):visible').last().data('index');
                    next = $items.eq(index).nextAll(':not(.disabled):visible').eq(0).data('index');
                    prev = $items.eq(index).prevAll(':not(.disabled):visible').eq(0).data('index');
                    nextPrev = $items.eq(next).prevAll(':not(.disabled):visible').eq(0).data('index');
                }

                prevIndex = $this.data('prevIndex');

                if (e.keyCode == 38) {
                    if (that.options.liveSearch) index -= 1;
                    if (index != nextPrev && index > prev) index = prev;
                    if (index < first) index = first;
                    if (index == prevIndex) index = last;
                }

                if (e.keyCode == 40) {
                    if (that.options.liveSearch) index += 1;
                    if (index == -1) index = 0;
                    if (index != nextPrev && index < next) index = next;
                    if (index > last) index = last;
                    if (index == prevIndex) index = first;
                }

                $this.data('prevIndex', index);

                if (!that.options.liveSearch) {
                    $items.eq(index).trigger("focus");
                } else {
                    e.preventDefault();
                    if (!$this.is('.dropdown-toggle')) {
                        $items.removeClass('active');
                        $items.eq(index).addClass('active').find('a').trigger("focus");
                        $this.trigger("focus");
                    }
                }

            } else if (!$this.is('input')) {

                var keyIndex = [],
                    count,
                    prevKey;

                $items.each(function () {
                    if ($(this).parent().is(':not(.disabled)')) {
                        if ($.trim($(this).text().toLowerCase()).substring(0, 1) == keyCodeMap[e.keyCode]) {
                            keyIndex.push($(this).parent().index());
                        }
                    }
                });

                count = $(document).data('keycount');
                count++;
                $(document).data('keycount', count);

                prevKey = $.trim($(':focus').text().toLowerCase()).substring(0, 1);

                if (prevKey != keyCodeMap[e.keyCode]) {
                    count = 1;
                    $(document).data('keycount', count);
                } else if (count >= keyIndex.length) {
                    $(document).data('keycount', 0);
                    if (count > keyIndex.length) count = 1;
                }

                $items.eq(keyIndex[count - 1]).trigger("focus");
            }

            // Select focused option if "Enter", "Spacebar", "Tab" are pressed inside the menu.
            if (/(13|32|^9$)/.test(e.keyCode) && isActive) {
                if (!/(32)/.test(e.keyCode)) e.preventDefault();
                if (!that.options.liveSearch) {
                    $(':focus').trigger("click");
                } else if (!/(32)/.test(e.keyCode)) {
                    that.$menu.find('.active a').trigger("click");
                    $this.trigger("focus");
                }
                $(document).data('keycount', 0);
            }

            if ((/(^9$|27)/.test(e.keyCode) && isActive && (that.multiple || that.options.liveSearch)) || (/(27)/.test(e.keyCode) && !isActive)) {
                that.$menu.parent().removeClass('open');
                that.$button.trigger("focus");
            }

        },

        hide: function () {
            this.$newElement.hide();
        },

        show: function () {
            this.$newElement.show();
        },

        destroy: function () {
            this.$newElement.remove();
            this.$element.remove();
        }
    };

    $.fn.selectpicker = function (option, event) {
        //get the args of the outer function..
        var args = arguments;
        var value;
        var chain = this.each(function () {
            if ($(this).is('select')) {
                var $this = $(this),
                    data = $this.data('selectpicker'),
                    options = typeof option == 'object' && option;

                if (!data) {
                    $this.data('selectpicker', (data = new Selectpicker(this, options, event)));
                } else if (options) {
                    for (var i in options) {
                        data.options[i] = options[i];
                    }
                }

                if (typeof option == 'string') {
                    //Copy the value of option, as once we shift the arguments
                    //it also shifts the value of option.
                    var property = option;
                    if (data[property] instanceof Function) {
                        [].shift.apply(args);
                        value = data[property].apply(data, args);
                    } else {
                        value = data.options[property];
                    }
                }
            }
        });

        if (value !== undefined) {
            return value;
        } else {
            return chain;
        }
    };

    $.fn.selectpicker.defaults = {
        style: 'btn-default',
        size: 'auto',
        title: null,
        selectedTextFormat: 'values',
        noneSelectedText: 'Nothing selected',
        countSelectedText: '{0} of {1} selected',
        width: false,
        container: false,
        hideDisabled: false,
        showSubtext: false,
        showIcon: true,
        showContent: true,
        dropupAuto: true,
        header: false,
        liveSearch: false,
        multipleSeparator: ', ',
        iconBase: 'glyphicon',
        tickIcon: 'glyphicon-ok'
    };

    $(document)
        .data('keycount', 0)
        .on('keydown', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bootstrap-select-searchbox input', Selectpicker.prototype.keydown)
        .on('focusin.modal', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bootstrap-select-searchbox input', function (e) { e.stopPropagation(); });

}(window.jQuery);



;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.loadTemplate-1.3.2.js
//version 2

(function ($) {
    "use strict";
    var templates = {},
        queue = {},
        formatters = {};

    function loadTemplate(template, data, options) {
        var $that = this,
            $template,
            settings,
            isFile;

        data = data || {};

        settings = $.extend({
            // These are the defaults.
            overwriteCache: false,
            complete: null,
            success: null,
            error: function () {
                $(this).each(function () {
                    $(this).html(settings.errorMessage);
                });
            },
            errorMessage: "There was an error loading the template.",
            paged: false,
            pageNo: 1,
            elemPerPage: 10,
            append: false,
            prepend: false,
            beforeInsert: null,
            afterInsert: null
        }, options);

        if (Array.isArray(data)) {
            return processArray.call(this, template, data, settings);
        }

        if (!containsSlashes(template)) {
            $template = $(template);
            if (typeof template === 'string' && template.indexOf('#') === 0) {
                settings.isFile = false;
            }
        }

        isFile = settings.isFile || (typeof settings.isFile === "undefined" && (typeof $template === "undefined" || $template.length === 0));

        if (isFile && !settings.overwriteCache && templates[template]) {
            prepareTemplateFromCache(template, $that, data, settings);
        } else if (isFile && !settings.overwriteCache && templates.hasOwnProperty(template)) {
            addToQueue(template, $that, data, settings);
        } else if (isFile) {
            loadAndPrepareTemplate(template, $that, data, settings);
        } else {
            loadTemplateFromDocument($template, $that, data, settings);
        }
        return this;
    }

    function addTemplateFormatter(key, formatter) {
        if (formatter) {
            formatters[key] = formatter;
        } else {
            formatters = $.extend(formatters, key);
        }
    }

    function containsSlashes(str) {
        return typeof str === "string" && str.indexOf("/") > -1;
    }

    function processArray(template, data, settings) {
        settings = settings || {};
        var $that = this,
            todo = data.length,
            doPrepend = settings.prepend && !settings.append,
            done = 0,
            success = 0,
            errored = false,
            newOptions;

        if (settings.paged) {
            var startNo = (settings.pageNo - 1) * settings.elemPerPage;
            data = data.slice(startNo, startNo + settings.elemPerPage);
            todo = data.length;
        }

        newOptions = $.extend(
            {},
            settings,
            {
                complete: function () {
                    if (doPrepend) {
                        $that.prepend(this.html());
                    } else {
                        $that.append(this.html());
                    }
                    done++;
                    if (done === todo) {
                        if (errored && settings && typeof settings.error === "function") {
                            settings.error.call($that);
                        }
                        if (settings && typeof settings.complete === "function") {
                            settings.always();
                        }
                    }
                },
                success: function () {
                    success++;
                    if (success === todo) {
                        if (settings && typeof settings.success === "function") {
                            settings.success();
                        }
                    }
                },
                error: function () {
                    errored = true;
                }
            }
        );

        if (!settings.append && !settings.prepend) {
            $that.html("");
        }

        if (doPrepend) data.reverse();
        $(data).each(function () {
            var $div = $("<div/>");
            loadTemplate.call($div, template, this, newOptions);
        });

        return this;
    }

    function addToQueue(template, selection, data, settings) {
        if (queue[template]) {
            queue[template].push({ data: data, selection: selection, settings: settings });
        } else {
            queue[template] = [{ data: data, selection: selection, settings: settings}];
        }
    }

    function prepareTemplateFromCache(template, selection, data, settings) {
        var $templateContainer = templates[template].clone();

        prepareTemplate.call(selection, $templateContainer, data, settings);
        if (typeof settings.success === "function") {
            settings.success();
        }
    }

    function uniqueId() {
        return new Date().getTime();
    }

    function urlAvoidCache(url) {
        if (url.indexOf('?') !== -1) {
            return url += "&_=" + uniqueId();
        }
        else {
            return url += "?_=" + uniqueId();
        }
    }

    function loadAndPrepareTemplate(template, selection, data, settings) {
        var $templateContainer = $("<div/>");

        templates[template] = null;
        if (settings.overwriteCache) {
            template = urlAvoidCache(template);
        }
        $templateContainer.on("load", template, function (responseText, textStatus) {
            if (textStatus === "error") {
                handleTemplateLoadingError(template, selection, data, settings);
            } else {
                handleTemplateLoadingSuccess($templateContainer, template, selection, data, settings);
            }
        });
    }

    function loadTemplateFromDocument($template, selection, data, settings) {
        var $templateContainer = $("<div/>");

        if ($template.is("script")) {
            $template = $.parseHTML($.trim($template.html()));
        }
		
		try{
			$templateContainer.html($template);
		}
		catch(error){
			if(error.message == "WrongDocumentError")
				$templateContainer.append($template[0].outerHTML);
		}
		
        prepareTemplate.call(selection, $templateContainer, data, settings);

        if (typeof settings.success === "function") {
            settings.success();
        }
    }

    function prepareTemplate(template, data, settings) {
        bindData(template, data);

        $(this).each(function () {
            var $templateHtml = $(template.html());
            if (settings.beforeInsert) {
                settings.beforeInsert($templateHtml);
            }
            if (settings.append) {

                $(this).append($templateHtml);
            } else if (settings.prepend) {
                $(this).prepend($templateHtml);
            } else {
                $(this).html($templateHtml);
            }
            if (settings.afterInsert) {
                settings.afterInsert($templateHtml);
            }
        });

        if (typeof settings.complete === "function") {
            settings.complete.call($(this));
        }
    }

    function handleTemplateLoadingError(template, selection, data, settings) {
        var value;

        if (typeof settings.error === "function") {
            settings.error.call(selection);
        }

        $(queue[template]).each(function (key, value) {
            if (typeof value.settings.error === "function") {
                value.settings.error.call(value.selection);
            }
        });

        if (typeof settings.complete === "function") {
            settings.complete.call(selection);
        }

        while (queue[template] && (value = queue[template].shift())) {
            if (typeof value.settings.complete === "function") {
                value.settings.complete.call(value.selection);
            }
        }

        if (typeof queue[template] !== 'undefined' && queue[template].length > 0) {
            queue[template] = [];
        }
    }

    function handleTemplateLoadingSuccess($templateContainer, template, selection, data, settings) {
        var value;

        templates[template] = $templateContainer.clone();
        prepareTemplate.call(selection, $templateContainer, data, settings);

        if (typeof settings.success === "function") {
            settings.success.call(selection);
        }

        while (queue[template] && (value = queue[template].shift())) {
            prepareTemplate.call(value.selection, templates[template].clone(), value.data, value.settings);
            if (typeof value.settings.success === "function") {
                value.settings.success.call(value.selection);
            }
        }
    }

    function bindData(template, data) {
        data = data || {};

        processElements("data-content", template, data, function ($elem, value) {
            $elem.html(applyFormatters($elem, value, "content"));
        });

        processElements("data-content-append", template, data, function ($elem, value) {
            $elem.append(applyFormatters($elem, value, "content"));
        });

        processElements("data-content-prepend", template, data, function ($elem, value) {
            $elem.prepend(applyFormatters($elem, value, "content"));
        });

        processElements("data-content-text", template, data, function ($elem, value) {
            $elem.text(applyFormatters($elem, value, "content"));
        });

        processElements("data-src", template, data, function ($elem, value) {
            $elem.attr("src", applyFormatters($elem, value, "src"));
        }, function ($elem) {
            $elem.remove();
        });

        processElements("data-alt", template, data, function ($elem, value) {
            $elem.attr("alt", applyFormatters($elem, value, "alt"));
        });

        processElements("data-title", template, data, function ($elem, value) {
            $elem.attr("title", value);
        });

        processElements("data-value", template, data, function ($elem, value) {
            $elem.attr("value", applyFormatters($elem, value, "value"));
        });

        processElements("data-link", template, data, function ($elem, value) {
            var $linkElem = $("<a/>");
            $linkElem.attr("href", applyFormatters($elem, value, "link"));
            $linkElem.html($elem.html());
            $elem.html($linkElem);
        });

        processElements("data-link-href", template, data, function ($elem, value) {
            $elem.attr("href", applyFormatters($elem, value, "link"));
        });

        processElements("data-link-wrap", template, data, function ($elem, value) {
            var $linkElem = $("<a/>");
            $linkElem.attr("href", applyFormatters($elem, value, "link-wrap"));
            $elem.wrap($linkElem);
        });

        processElements("data-options", template, data, function ($elem, value) {
            $(value).each(function () {
                var $option = $("<option/>");
                $option.attr('value', this).text(this).appendTo($elem);
            });
        });

        processAllElements(template, data);
    }

    function processElements(attribute, template, data, dataBindFunction, noDataFunction) {
        $("[" + attribute + "]", template).each(function () {
            var $this = $(this),
                param = $this.attr(attribute),
                value = getValue(data, param);

            $this.removeAttr(attribute);

            if (typeof value !== 'undefined' && dataBindFunction) {
                dataBindFunction($this, value);
            } else if (noDataFunction) {
                noDataFunction($this);
            }
        });
        return;
    }

    function processAllElements(template, data) {
        $("[data-template-bind]", template).each(function () {
            var $this = $(this),
                param = JSON.parse($this.attr("data-template-bind"));

            $this.removeAttr("data-template-bind");

            $(param).each(function () {
                var value;

                if (typeof (this.value) === 'object') {
                    value = getValue(data, this.value.data);
                } else {
                    value = getValue(data, this.value);
                }
                if (typeof value !== "undefined" && this.attribute) {
                    switch (this.attribute) {
                        case "content":
                            $this.html(applyDataBindFormatters($this, value, this));
                            break;
                        case "contentAppend":
                            $this.append(applyDataBindFormatters($this, value, this));
                            break;
                        case "contentPrepend":
                            $this.prepend(applyDataBindFormatters($this, value, this));
                            break;
                        case "contentText":
                            $this.text(applyDataBindFormatters($this, value, this));
                            break;
                        case "options":
                            var optionsData = this;
                            $(value).each(function () {
                                var $option = $("<option/>");
                                $option
                                    .attr('value', this[optionsData.value.value])
                                    .text(applyDataBindFormatters($this, this[optionsData.value.content], optionsData))
                                    .attr('selected', typeof this[optionsData.value.selected] == undefined ? false : this[optionsData.value.selected])
                                    .appendTo($this);
                            });
                            break;
                        default:
                            $this.attr(this.attribute, applyDataBindFormatters($this, value, this));
                    }
                }
            });
        });
    }

    function applyDataBindFormatters($elem, value, data) {
        if (data.formatter && formatters[data.formatter]) {
            return formatters[data.formatter].call($elem, value, data.formatOptions);
        }
        return value;
    }

    function getValue(data, param) {
        if (param === "this") {
            return data;
        }
        var paramParts = param.split('.'),
            part,
            value = data;

        while ((part = paramParts.shift()) && typeof value !== "undefined") {
            value = value[part];
        }

        return value;
    }

    function applyFormatters($elem, value, attr) {
        var formatterTarget = $elem.attr("data-format-target"),
            formatter;

        if (formatterTarget === attr || (!formatterTarget && attr === "content")) {
            formatter = $elem.attr("data-format");
            if (formatter && typeof formatters[formatter] === "function") {
                var formatOptions = $elem.attr("data-format-options");
                return formatters[formatter].call($elem[0], value, formatOptions);
            }
        }

        return value;
    }
    addTemplateFormatter("nestedTemplateFormatter", function (value, options) {
        if (!options) {
            return;
        }
        
        if (typeof options === "string" && options[0] === "{") {
            options = JSON.parse(options);
        }

        var parentElement = options.parentElement || "div";
        var template = options.template || options;
        return $("<" + parentElement + "/>").loadTemplate(template, value);
    });
    $.fn.loadTemplate = loadTemplate;
    $.addTemplateFormatter = addTemplateFormatter;

})(jQuery);

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\ui.styleCore-engine.js
/* version="61" */
///---------------------------------------------------------------///
//Page Initialization and Event Binding
///---------------------------------------------------------------///
//TO DO: Remove this once all console.log is remove from all scripts.
if (!(window.console && console.log)) {
    console = {
        log: function () { },
        debug: function () { },
        info: function () { },
        warn: function () { },
        error: function () { }
    };
}

//console.log('stylecore refactor');
var pageState = {};
var callAdjustLayout;
var $divUiContainer;
var divUiContainerLength;

persistHash();
$(window).on('load resize orientationchange', function () {
    $('div.ui-container').each(function (index) {
        var $this = $(this);
        var mediaId = $this.data('background-mediaid');
        var playerId = $this.data('background-playerid');
        var vidContainer = $this.find('.media-container');
        var vidPlayIcon = $this.find('.acn-icon.icon-circle');
        var vidText = $this.find('.component.richtext');
        var vidDesc = $this.find('.our-people-desc');
        var vidHeader = $this.find('.our-people-header');
        var vidDownloadModule = $('.media-gallery').find('.our-people-download');
        var showVidButton = $(".show-videos");
        var mediaGallery = $('.media-gallery');
        var optIn = $('#module-email-alerts-optin');
        var twoTone = $('.two-tone');
        var thirdParent = optIn.parents().eq(2).children().length;
        var fifthParent = optIn.parents().eq(4).children().length;

        if (isTablet()) {
            if (twoTone.attr('id') == 'block-recommendations' && (thirdParent != 1) && (fifthParent != 1)) {
                if ($(window).width() < $(window).height()) {
                    optIn.parents().eq(1).css("margin-top", "22px");
                }
                else {
                    optIn.parents().eq(1).css("margin-top", "");
                }
            }
        }

        if ($this.attr("id") != "block-footer") {
            var a = ($this.next().length && $this.next().attr("data-shape") !== "undefined") ? $this.next().attr("data-shape") : "undefined"
            var b = ($this.next().length && $this.next().attr("id") !== "undefined") ? $this.next().attr("id") : "undefined"
            var c = ($this.length && $this.attr("data-shape") !== "undefined") ? $this.attr("data-shape") : "undefined"

            if (c == "square" && a == "square" && b == "block-footer") {
                $this.addClass("last-block")
            }
            else if (c == "square" && a != "square") {
                $this.addClass("last-square")
            }
            else if (c != "square" && a == "square") {
                $this.addClass("last-edge-delta")
            }
        }

        if ((mediaId != "" && mediaId != undefined) && (playerId != "" && playerId != undefined)) {
            if (IsTouch()) {
                var vidHeight = ($(window).width() * 9) / 16;
                var leftSpacing = ($(window).width() * 20.5) / -414;
                var acnIconPosition = ($(window).width() * 20) / 46;
                $this.find('.ui-content-box.inline').css({ "padding": "0" });
                if ($(window).width() == 960 && $(window).height() == 600) {
                    $this.css({ "width": $(window).width(), "height": "427px" });
                    vidContainer.css({ "width": $(window).width(), "height": "432px", "overflow": "hidden" });
                    vidPlayIcon.css({ "margin-top": "-655px", "margin-left": "440px", "position": "", "left": "", "top": "", "z-index": "" });
                    vidText.css({ "margin-top": "-431px", "margin-left": "27px" });
                    vidDesc.css({ "margin-top": "-27px" });
                    vidDownloadModule.css({ 'margin-top': '360px' });
                }
                else if ($(window).width() >= 768 && $(window).width() < 1024) {
                    $this.css({ "width": $(window).width(), "height": "427px" });
                    vidContainer.css({ "width": $(window).width(), "height": "432px", "overflow": "hidden" });
                    vidPlayIcon.css({ "position": "absolute", "top": "260px", "margin-left": "344px" });
                    vidText.css({ "margin-top": "-50px", "margin-left": "27px" });
                    vidDesc.css({ "margin-top": "-27px" });
                    $this.find('.col-sm-12.visible-sm.visible-md').css({ "position": "absolute", "top": "-109px" });
                    if ($(window).width() == 800) {
                        $this.find(".col-sm-12.visible-lg").addClass("visible-sm visible-md").removeClass("visible-lg");
                        $this.find(".blockVideoBackground.visible-sm.visible-md").addClass("visible-lg").removeClass("visible-sm visible-md");
                        $this.find(".icon-play").css("font-size", "35px");
                    }
                }
                else if ($(window).width() >= 1024) {
                    $this.css({ "width": $(window).width(), "height": "573px", "margin": "0" });
                    vidContainer.css({ "width": $(window).width(), "height": "576px", "overflow": "hidden" });
                    vidPlayIcon.css({ "position": "absolute", "top": "320px", "margin-left": "475px" });
                    vidText.css({ "margin-top": "-55px", "margin-left": "65px" });
                    vidDesc.css({ "margin-top": "-53px" });
                    $this.find('.col-sm-12.visible-sm.visible-md').css({ "position": "absolute", "top": "-109px" });
                    if ($(window).width() == 1280) {
                        $this.find(".blockVideoBackground.visible-lg").addClass("visible-sm visible-md").removeClass("visible-lg");
                        $this.find(".col-sm-12.visible-sm.visible-md").addClass("visible-lg").removeClass("visible-sm visible-md");
                        vidPlayIcon.css("margin-left", "580px");
                        $this.find(".icon-play").css("font-size", "45px");
                        vidText.css("margin-left", "130px");
                    }
                }
                else if ($(window).width() == 600 && $(window).height() == 960) {
                    $this.css({ "width": $(window).width(), "height": vidHeight + "px", "margin": "0" });
                    $this.find('.col-sm-12.visible-xs').css({ "position": "absolute", "top": "-21px", "left": leftSpacing + "px" });
                    vidContainer.css({ "width": $(window).width(), "height": vidHeight + "px", "overflow": "hidden" });
                    vidPlayIcon.css({ "position": "absolute", "left": acnIconPosition + "px", "top": "135px", "z-index": 1, "margin-top": "0px", "margin-left": "0px" });
                    vidText.css({ "margin-top": "0px", "margin-left": "20px" });
                    vidDesc.css({ "margin-top": "-20px" });
                }
                else if (($(window).width() <= 767) && ($(window).width() < $(window).height())) {
                    $this.css({ "width": $(window).width(), "height": vidHeight + "px", "margin": "0" });
                    $this.find('.col-sm-12.visible-xs').css({ "position": "absolute", "top": "-21px", "left": leftSpacing + "px" });
                    vidContainer.css({ "width": $(window).width(), "height": vidHeight + "px", "overflow": "hidden" });
                    vidPlayIcon.css({ "position": "absolute", "left": acnIconPosition + "px", "top": "135px", "z-index": 1 });
                    vidText.css({ "margin-top": "0px", "margin-left": "20px" });
                    vidDesc.css({ "margin-top": "-20px" });
                    $('.videofilter-container').hide();
                    if ($this.hasClass('media-gallery')) {
                        showVidButton.css('margin-top', mediaGallery.height() - showVidButton.height() - 2);
                        mediaGallery.css('height', mediaGallery.height() + showVidButton.height());
                        vidDownloadModule.css({ 'left': '40px', 'position': 'absolute' });
                    }
                }
                else if (($(window).width() <= 767) && ($(window).width() > $(window).height())) {
                    $this.css({ "width": $(window).width(), "height": $(window).height(), "margin": "0" });
                    $this.find('.col-sm-12.visible-xs').css({ "position": "absolute", "top": "-22px", "left": leftSpacing - 0.5 + "px" });
                    vidContainer.css({ "width": $(window).width(), "height": vidHeight + "px", "overflow": "hidden" });
                    vidPlayIcon.css({ "position": "absolute", "left": acnIconPosition + "px", "top": "210px", "z-index": 1 });
                    vidText.css({ "margin-top": "0px", "margin-left": "20px" });
                    vidDesc.css({ "margin-top": "-20px" });
                    $('.videofilter-container').hide();
                    if ($this.hasClass('media-gallery')) {
                        showVidButton.css('margin-top', mediaGallery.height() - showVidButton.height() - 2);
                        mediaGallery.css('height', mediaGallery.height() + showVidButton.height());
                        vidDownloadModule.css({ 'left': '37px', 'margin-left': '0px', 'position': 'relative' });
                        vidText.css('margin-left', '32px');
                    }
                }
            }

            if ($this.hasClass('media-gallery')) {
                var resultHeight;
                var filterWidth;
                var newVideoWidth;
                var emptyContHeight;
                var RichtextMarginLeft;
                var leftDistance = RichtextMarginLeft + 10;
                var filterCont = $this.find('.videofilter-container');
                var filterHeight = filterCont.height();
                var emptyCont = $this.find(".empty-container");
                var filterResultCont = $this.find('.videofilter-results');
                var filterResult = $this.find('.media-container.displayBlock');
                emptyCont.css("display", "table");
                emptyCont.find("p").css({ "display": "table-cell", "text-align": "center", "vertical-align": "middle" });
                var playPosition;
                if (isMobile() && IsTouch()) {
                    //
                }
                else if (isTablet() || IsTouch()) {
                    if ($(window).width() > $(window).height()) {
                        resultHeight = (($this.height() + 3.5) - filterHeight) / 4;
                        if ($(window).width() == 1280) {
                            var downloadPosition = parseInt(vidText.first().css("margin-left")) + 10;
                            vidDownloadModule.css({ 'margin-top': '448px', 'left': downloadPosition + "px" });
                        }
                        else if ($(window).width() == 1024) {
                            var downloadPosition = parseInt(vidText.first().css("margin-left")) + 10;
                            vidDownloadModule.css({ 'margin-top': '428px', 'left': downloadPosition + "px" });
                        }
                    }
                    else {
                        filterCont.css("width", "256px");
                        resultHeight = (($this.height() + 5.5) - filterHeight) / 4;

                        if ($(window).width() == 800) {
                            vidDownloadModule.css({ 'margin-top': '298px', 'left': "" });
                        }
                        else if ($(window).width() == 768) {
                            vidDownloadModule.css({ 'margin-top': '295px', 'left': "" });
                        }
                    }
                    filterWidth = filterCont.width();
                    newVideoWidth = $(window).width() - filterWidth;
                    emptyContHeight = (resultHeight * (4 - filterResult.length));
                    playPosition = ((newVideoWidth / 2) - 37) + "px";
                    $this.css({ "margin-top": "2px", "background-image": "" });
                    $this.find('.video-container').css({ "padding-right": "20px", "bottom": "13px" });
                    $this.find('.player-container').parents().eq(1).css("top", "50px");
                    vidContainer.last().children().first().css({ "width": newVideoWidth + "px", "height": $this.height() + 6 + "px" });
                    filterResultCont.addClass("bg-color-cranberry-red").children().css({ "width": filterWidth, "height": resultHeight + "px" });
                    filterResult.find('img').css({ "width": filterWidth, "height": resultHeight + "px" });
                    vidPlayIcon.css("margin-left", playPosition);
                    emptyCont.css("height", emptyContHeight + "px");
                    $('div.ui-container').css('margin-top', '-2px');
                    $this.find('.col-sm-12.visible-sm.visible-md').css({ "position": "absolute", "top": "-65px" });
                }
                else if (isDesktop()) {
                    if (filterResultCont.children().length > 0) {
                        $this.css({ "height": "717px", "min-height": "" });
                        filterCont.css('margin-top', '-16px');
                        var textPosition = parseInt($this.siblings().css("margin-left"));
                        if (!$this.parents().hasClass('firefox')) {
                            vidText.css({ "position": "absolute", "left": textPosition + "px", "width": "472px" });
                            if (($(window).width() >= 1580) && ($(window).width() <= 1600)) {
                                vidText.css("left", "190px");
                            }
                            $this.find('.component.richtext a').parent().css("left", textPosition + 15 + "px");
                        }
                        else {
                            if ($(window).width() <= 1280) {
                                vidText.css({ "position": "absolute", "left": "115px", "width": "472px" });
                                $this.find('.component.richtext a').parent().css("left", "130px");
                            }
                            else if ($(window).width() <= 1350) {
                                vidText.css({ "position": "absolute", "left": "155px", "width": "472px" });
                                $this.find('.component.richtext a').parent().css("left", "170px");
                            }
                            else if ($(window).width() <= 1600) {
                                vidText.css({ "position": "absolute", "left": "190px", "width": "472px" });
                                $this.find('.component.richtext a').parent().css("left", "291px");
                                vidDownloadModule.css({ 'margin-top': '550px' });
                            }
                        }
                        $this.find('.media-container img').css({ "width": "348px", "height": "172px" });
                        filterResultCont.css("height", "688px");
                        filterWidth = filterCont.width();
                        newVideoWidth = $(window).width() - filterWidth;
                        resultHeight = filterResultCont.height() / 4;
                        emptyContHeight = (resultHeight * (4 - filterResult.length));
                        emptyCont.css({ "width": filterWidth, "height": emptyContHeight + "px" });
                        $this.find('.video-container').css("bottom", "10px");
                        playPosition = ((newVideoWidth / 2) - 70) + "px";
                        vidPlayIcon.css("margin-left", playPosition);
                        vidDownloadModule.css({ 'bottom': '-585px' });
                    }
                }
                if (filterResult.length == 0) {
                    emptyCont.show();
                }
                if (filterResult.length == 4) {
                    emptyCont.hide();
                }
            }
        }
    });
    $('.ui-square').find('.video-wrapper-background').each(function (index) {
        $this = $(this);
        $backVid = $this.parents().eq(1);
        $backVid.css('height', ($backVid.height() - 5) + 'px');

        var zoomFactor = (Math.round((screen.width / window.innerWidth) * 10) / 10).toFixed(2);
        var videoBackground = $('.video-wrapper.video-wrapper-background');
        var blockOurPeople = $('#block-our-people');
        var blockVideoBackground = $('.blockVideoBackground');

        if (zoomFactor >= 1.1 && zoomFactor < 1.2) {
            if (screen.height >= 1024) {
                videoBackground.parents().eq(1).css("height", "954px");
                blockVideoBackground.addClass("visible-md");
            }
            else {
                videoBackground.parents().eq(1).css("height", "975px");
            }
        }
        if (zoomFactor >= 1.2 && zoomFactor < 1.5) {
            blockOurPeople.removeClass("row");
            blockOurPeople.css("margin-top", '-15px');
            blockVideoBackground.addClass("visible-md");
            if (screen.height >= 1024) {
                videoBackground.parents().eq(1).css("height", "933px");
            }
            else {
                videoBackground.parents().eq(1).css("height", "945px");
            }
        }
        if (zoomFactor >= 1.5) {
            blockOurPeople.css("background-image", "");
        }
    });
});

(function () {
    function adjustFromHeightChange() {
        setState();
        callAdjustLayout();
        PositionLayout();
        //CovertibleCarousel(); can't find a page where this actually does anything: the selector in function.carousel.js is never matched
        //setupVideoPlayers();
    }
    var debouncedResizeHandler = debounce(adjustFromHeightChange);
    var debouncedBrowserResizeHandler = debounce(adjustFromHeightChange);
    var i;

    $(function () {
        setState();
        CreateLayout();
        adjustFromHeightChange();

        if (IsTouch()) {
            addSwipeToCarousels();
            $('select.form-control').selectpicker('mobile');
        } else {
            $('select.form-control').selectpicker();
        }
        for (i = 0; i < divUiContainerLength; i++) {
            $($divUiContainer[i]).onHeightChange(debouncedResizeHandler);
        }

        $('body').onBrowserResize(debouncedBrowserResizeHandler);

        if (IsIOS()) {
            $(document)
                .on('focus', 'textarea,input,select', function (e) {
                    $('body').addClass('keyboard-shown');

                    if ($('.has-cookie-nav').length > 0) {
                        $('#header-topnav, #ui-wrapper').css('top', '');
                    }

                    if (isMobile()) {
                        $('body').css('padding-top', '0');
                        $('#ui-wrapper').css('top', '60px');
                        $('#header-topnav').css({ 'position': 'absolute', 'top': '-60px' });
                    }

                    $('#contact-main-modal').css('position', 'absolute');
                    $('.modal-backdrop').css('position', 'absolute').height("100vh");
                })
                .on('blur', 'textarea,input,select', function (e) {
                    $('body').removeClass('keyboard-shown');

                    if (isMobile()) {
                        $('body').css('padding-top', '');
                        $('#ui-wrapper').css('top', '');
                        $('#header-topnav').css({ 'position': '', 'top': '' });
                    }

                    $('#contact-main-modal').css('position', '');
                    $('.modal-backdrop').css('position', '');
                });
        }
    });

    // Couldn't find a single page where this selector was matched and the code would actually run
    // $(".panel-collapse").on("shown.bs.collapse", function () {
    //     var clickedHeader = $(this).closest('.panel').find('.panel-heading');
    //     var offset = $(clickedHeader[0]).offset();
    //     var top = $(window).scrollTop();
    //     if (offset) {
    //         var topOfHeader = offset.top;
    //         if (topOfHeader < top) {
    //             $('html, body').animate({ scrollTop: topOfHeader - 80 }, 100, 'swing');
    //         }
    //     }
    // });
}());

///---------------------------------------------------------------///
//Layout Functions
///---------------------------------------------------------------///

// This method creates all trapezoidal shapes in the layout-wrapper in the background
// based on the sizes of the content and classes/data tags attached at html
function CreateLayout() {
    function eachLayout(origElm, shapeIndex) {
        function makeShapeDivs() {
            var outerDiv = document.createElement('div');
            var innerDiv = document.createElement('div');
            var innerDiv2;
            var vidCfg = {};
            var vidObject;
            outerDiv.id = shapeId;
            outerDiv.className = 'outer';
            outerDiv.setAttribute('data-content-id', origElm.id);

            innerDiv.id = 'inner_' + shapeId;
            innerDiv.className = 'inner';
            outerDiv.appendChild(innerDiv);

            //3459
            var modulesToCheck = ["#module-email-alerts-optin", ".comments-module", ".related-content-container"];
            var containerContents = $this.find('.container-block').children('.col-sm-12');
            var isCreated = false;
            var contentBox;
            var containerBlock;
            var containerLParent;
            var lP = $this.find('.linking-to-parent-topic');
            var uiContentBox = $this.find('.ui-content-box');
            var uiContainerBox = $this.find('.ui-content-box').children('.container-block');
            var bottomModule;

            if (containerContents.length > 1) {
                containerContents.each(function () {

                    for (y in modulesToCheck) {
                        if ($(this).find(modulesToCheck[y])[0]) {
                            if ($(this).find(modulesToCheck[y]).css("display") == "block") {
                                if (!isCreated) {

                                    contentBox = document.createElement('div');
                                    containerBlock = document.createElement('div');
                                    containerLParent = document.createElement('div');
                                    containerLParent.className = 'col-sm-12';
                                    contentBox.className = 'ui-content-box twotonebottom';
                                    containerBlock.className = 'container-block';
                                    contentBox.appendChild(containerBlock);
                                    $this.append(contentBox);
                                    $this.addClass('two-tone');
                                    uiContentBox.addClass('twotonetop');
                                    bottomModule = modulesToCheck[y];
                                    if (lP[0]) {
                                        lP.appendTo(containerLParent);
                                        uiContainerBox.append(containerLParent);
                                    }
                                    isCreated = true;
                                }

                                if (isCreated) {
                                    $(this).appendTo(containerBlock);
                                }
                            }
                        }
                    }
                });
            }

            if (lP[0]) {
                if (bottomModule == "#module-email-alerts-optin") {
                    if (!($('body').find('.two-tone .linking-to-parent-topic').length > 0)) {
                        lP.css('margin-bottom', '-60px');
                    }
                }
                else {
                    lP.css('margin-bottom', '20px');
                }
            }

            //3459

            if ($this.hasClass('two-tone')) {
                innerDiv2 = document.createElement('div');
                innerDiv2.id = 'inner_2_' + shapeId;
                innerDiv2.className = 'inner'; //3459 two-tone fix 
                outerDiv.appendChild(innerDiv2);
            }

            return outerDiv;
        }
        function addVideo(parent) {
            var $blockBack = $this;
            function toggleButtonState() {
                $blockBack.find('#play').toggle();
                $blockBack.find('#pause').toggle();
                $blockBack.find('#playPauseIcon').toggleClass("icon-pause");
                $blockBack.find('#playPauseIcon').toggleClass("icon-play");
            }

            function onButtonClick() {
                var vid = document.getElementById(playerId);
                var state = vid.doGetCurrentPlayState();
                toggleButtonState();

                if (state.isPlaying) {
                    vid.doPause();
                    if ($blockBack.hasClass('c-ui-square')) {
                        $blockBack.find('.icon-circle').fadeIn(500);
                    }
                } else {
                    vid.doPlay();
                    if ($blockBack.hasClass('c-ui-square')) {
                        $blockBack.find(".icon-circle").fadeOut(500);
                        $blockBack.css("background-image", "");
                        $blockBack.find(".our-people-header").fadeOut(500);
                        $blockBack.find(".our-people-desc").fadeOut(500);
                        $blockBack.find(".ourpeoplesubtext").fadeOut(500);
                        $blockBack.find("#DownloadModule").fadeOut(500);
                    }
                }
            }

            if ($blockBack.hasClass('c-ui-square')) {
                $($blockBack)
                    .on("mouseenter",
                        function () {
                            if ($blockBack.find('#play').css("display") == "none" || $blockBack.find('.icon-circle').css("display") == "none") {
                                $blockBack.find('.icon-circle').fadeIn(500);
                            }
                        }).on("mouseleave",
                            function () {
                                if ($blockBack.find('#play').css("display") == "none") {
                                    $blockBack.find('.icon-circle').fadeOut(500);
                                }
                            }
                        );
            }

            var video = $this.data('background-video');
            var mediaId = $this.data('background-mediaid');
            var playerId = $this.data('background-playerid');
            var autoPlay = $this.data('background-autoplay');
            var autoLoop = $this.data('background-autoloop');
            var classOdd = shapeIndex % 2 == 0 ? 'odd' : 'even';
            var blockBackgroundID = $this[0].id;
            var videoID = blockBackgroundID + "Video";
            var playerForm = $this.data('background-playerform');

            var mediaPlayerNetwork = '//assets.delvenetworks.com/player/loader.swf';
            var wMode = 'window';

            if (InternetExplorer()) {
                wMode = 'transparent';
            }

            //var videoHeight = parseInt(videoWidth, 10) * 0.95;
            var block = $this.height()
            var xfactor = Math.ceil($(window).width() * 0.40220017); /* tangent (21.91deg)*/
            var videoHeight = block + xfactor;
            var videoWidth = (videoHeight * 4) / 3;

            $shape.find('.inner').addClass("noPaddingTop noPaddingBottom").append("<div class='video-wrapper video-wrapper-background' style='top:0; display:inline-block; left:0'>" +
                "<object type='application/x-shockwave-flash' " +
                "id='" + playerId + "' name='" + playerId + "' width='100%' height='" + videoHeight + "px'" +
                "class='visible-md visible-lg' data='" + mediaPlayerNetwork + "'>" +
                "<param name='movie' value='" + mediaPlayerNetwork + "'>" +
                "<param name='wmode' value='" + wMode + "'>" +
                "<param name='allowScriptAccess' value='sameDomain'>" +
                "<param name='allowFullScreen' value='true'>" +
                "<param name='autoLoop' value='" + autoLoop + "'>" +
                "<param name='flashVars' value='playerForm=" + playerForm + "&amp;mediaId=" + mediaId + "&defaultQuality=1200'>" +
                "</object>" +
                "</div>");

            containerImage = true;

            blockBackgroundHeight = ($("#" + blockBackgroundID).height() / 2);

            if ($("#" + blockBackgroundID).find(".block-title").hasClass("first")) {
                videoBackgroundPlayIconLocation = (blockBackgroundHeight - 170).toFixed().toString() + "px";
            } else {
                videoBackgroundPlayIconLocation = (blockBackgroundHeight - 230).toFixed().toString() + "px";
            }

            if (autoPlay == "False") {
                toggleButtonState();
            }

            if ($this.hasClass('c-ui-square')) {
                $('.video-wrapper-background').css('margin-left', '0px');
                $this.css("background-image", $this.data('background-image'));
                $this.css({ "background-size": "cover", "width": "auto", "height": "auto" });
            }

            $this.find(" .acn-icon.floating.bvideo").css("top", videoBackgroundPlayIconLocation).on("click", onButtonClick);

        }
        var $this = $(origElm);
        var shapeId = 'shape-' + shapeIndex;
        var IsHidden = $this.css('display') == "none" ? true : false;
        var viewport_height = $(window).height(), height = $this.height();
        var total = viewport_height + height + 100;
        var $shape = $(makeShapeDivs());
        var image = $this.data('background-image');
        var video = $this.data('background-video');
        var mediaId = $this.data('background-mediaid');
        var playerId = $this.data('background-playerid');
        var containerImage = false;
        var classOdd = shapeIndex % 2 === 0 ? 'odd' : 'even';
        var shapeContainer = $this.data("shape");
        var dataShapeVal;

        if (shapeContainer != null) {
            dataShapeVal = shapeContainer.toLowerCase();
        }

        if (!$("#iscrisscrossed")) { //SIR 303273
            $("#content-wrapper div div").first().addClass("first");
        }

        if ($this.find('.ui-content-box.inline .floatcontainer').length > 0) {  //SIR#?
            $this.find('.ui-content-box.inline').css('padding-bottom', '120px');
        }

        if (shapeIndex === 0 || IsIE8()) {
            $('#overflow-controller').before($shape);
        } else {
            $('#overflow-controller').append($shape);
        }

        var showTopLineClass = "";
        if ($this.data('show-top-line') == 'True') {
            showTopLineClass = "block-separator";
        }

        // 1. 2nd container is left + edge by default
        // 2. if previous is left + delta  = next is right edge/delta
        // 3. if previous is right + delta  =  next is left edge/delta
        // 4. if previous is left + edge = next is left edge/delta
        // 5. if previous is right + edge = next is left edge/delta

        if (preContainerType != "edge") {
            preContainerDirection = (preContainerDirection == "left" ? "right" : "left");
        }

        preContainerType = "edge"; // Getting data-shape attribute from HTML
        if (dataShapeVal == "delta") {
            preContainerType = "delta";
        } else if (dataShapeVal == "square") {
            preContainerType = "square";
        }

        // Adding respective class of direction - left/right, and shape - ui-edge/ui-delta
        $shape.addClass(preContainerDirection).addClass('ui-' + preContainerType).addClass(showTopLineClass);
        $this.addClass('c-' + preContainerDirection).addClass('c-ui-' + preContainerType);

        if (image) {
            var screenWidth = $(window).width();
            image = image.replace("__w__", "w" + screenWidth);
        }

        if (IsIE8()) {  //ie8 will not display background video, this condition forces a background image
            $shape.addClass(classOdd)
                .find('.inner')
                .before("<div class='terminator before'></div>")
                .after("<div class='terminator after'></div>");

            if (origElm.id !== "block-footer") {
                if (isValidString(image) && classOdd === 'even') {
                    $shape.css('background-image', image).addClass('image-shape parallax');
                    containerImage = true;
                }
            }
        } else { //if there's a background video, set it up
            if (isValidString(mediaId) && isValidString(playerId) && !IsTouch()) {
                addVideo($shape.find('.inner')[0]);
            } else if (isValidString(image) && !isValidString(mediaId)) {
                $shape.find('.inner').first().addClass('parallax').css({ 'background-image': image });
                containerImage = true;
            }
            //create shapes for block carousels
            if ($this.find('ul.convBlockCarousel').length > 0) {
                $shape.find('.inner').addClass('parallax').html(GetCarouselBackground($this));
            }
        }

        if (!IsHidden) {
            preContainerImage = containerImage;
        } else {
            $shape.css('display', 'none');
        }
    }
    var preContainerType = "edge";
    var preContainerDirection = "left";
    var preContainerImage = true;
    var i;

    for (i = 0; i < divUiContainerLength; i++) {
        eachLayout($divUiContainer[i], i);
    }

    if (!IsIE8()) {
        $("#shape-0").wrap("<div id='overflow-docking'></div>");
    }

    //Adjusting Hero background
    $('.hero .item, .hero-article .item, #block-hero').each(function () {
        var $slide = $(this);
        var url = $slide.data('background-image');
        if (typeof url === "undefined")
            url = "";

        //[RMT 6072][US005b][About Accenture - Hero - Mobile - Background Image and Alignment]
        var urlMobile = $slide.data('mobile-image');
        if (typeof urlMobile === "undefined")
            urlMobile = "";

        var imageOverride = $slide.data('image-override');
        var originalStyle = $slide.attr("style");

        if (url != undefined && url != "") {
            url = url.replace("__w__", "w" + pageState.viewPortWidth);
        }

        if (isMobile() && urlMobile != "" && imageOverride) {
            if (typeof orginalStyle === "undefined") {
                originalStyle = "";
            }
            $slide.attr('style', originalStyle + 'background-image: url(' + urlMobile + ') !important');
        }
        else if (isMobile() && url != "" && imageOverride) {
            $slide.attr('style', originalStyle + 'background-image: url(' + url + ') !important');
        }
        else {
            if (url != "")
                $slide.css('background-image', 'url(' + url + ')');
        }
    });

    addParallaxEventHandler();
}

function AdjustLayout() { //TODO: cleanup DOM interactions and var hoisting
    function eachLayout(origElm, index) {
        var $this = $(origElm);
        var height = $this.outerHeight(true) * 1;
        var shapeColor = '-color-white';
        var optIn = $('#module-email-alerts-optin');
        var firstParent = optIn.parents().eq(0).children().length;
        var secondParent = optIn.parents().eq(1).children().length;
        var thirdParent = optIn.parents().eq(2).children().length;
        var fifthParent = optIn.parents().eq(4).children().length;
        var twoTone = $('.two-tone');
        var twoToneBottom = $('.twotonebottom');
        var blockTwoTone = $('[data-content-id=block-twotone]');

        $this.find('.ui-content-box.dock').outerWidth('100%');

        if (isValidString($this.data('shape-color'))) {
            shapeColor = '-color-' + $this.data('shape-color');
        }

        //2. Create two inner if $this.hasClass('two-tone')
        if ($this.hasClass('two-tone')) {
            var contentBoxHeight = $this.find('.ui-content-box').eq(0).outerHeight(true) * 1;
            var dfactor = $this.data('shape') == "delta" ? 1 : 0;
            var variableOffset = 5;

            var hr = $this.find('.ui-content-box').eq(1).find('hr');
            var hrTag = 0;
            if ($('.ui-content-box.twotonebottom .col-sm-12').eq(0).find("hr").eq(0)[0]) {
                hrTag = $('.ui-content-box.twotonebottom .col-sm-12').find("hr").eq(0).offset().top - $('.ui-content-box.twotonebottom').offset().top + parseInt($('.ui-content-box.twotonebottom').css('margin-top'));
            }

            if (hrTag > 100) {
                hrTag = 0;
            }

            if (pageState.isMobile) {
                variableOffset = -15;
            }
            if (pageState.isTablet) {
                variableOffset = 0;
            }

            if ($this.find('.ui-content-box.twotonetop .component.richtext')[0] && pageState.isMobile) {
                variableOffset = 5;
            }

            $("div[data-content-id='" + origElm.id + "']")
                .css({
                    'margin-top': -1 * (1 + preshape) * xfactor * (index == 0 ? 0 : 1) // If delta then -2x else -x
                })
                .find('.inner:nth-child(1)').addClass('bg' + shapeColor)
                //.height(height + (dfactor) * xfactor) // If delta then 3x height else 2x;
                //3. inner1.height = height1 + 1 * xfactor
                .css({
                    'padding-top': xfactor,
                    //'padding-bottom': xfactor,
                    'margin-top': -1 * xfactor,
                    'height': contentBoxHeight + variableOffset + xfactor + hrTag
                });

            var contentBoxHeight = $this.find('.ui-content-box').eq(1).outerHeight(true) * 1;
            //4. inner2.height = height2 + (dfactor + 1) * xfactor
            $("div[data-content-id='" + $this[0].id + "']").find('.inner:nth-child(2)')
                //.addClass('bg-color-' + $this.data('tone-color')) 3459 change to lighter-gray
                .addClass('bg-color-lighter-gray')
                .css({
                    //'padding-top': xfactor,
                    'padding-bottom': xfactor,
                    //'margin-top': -1 * xfactor,
                    'height': contentBoxHeight + (dfactor + 1) * xfactor
                });

            preshape = dfactor;

            if (isDesktop()) {
                if (twoTone.attr('id') == 'block-recommendations') {
                    if ((thirdParent == 1) && (fifthParent == 1)) {
                        twoToneBottom.css({ position: "relative", top: "-39px" });
                    }
                }
                else if ((optIn.parents().eq(3).hasClass('twotonebottom')) &&
                    ((secondParent == 1) || (thirdParent == 1))) {
                    twoToneBottom.css({ position: "relative", top: "-40px" });
                }
                else {
                    if (optIn.parents().eq(4).prev().height() > 800) {
                        optIn.parents().eq(3).css("margin-top", "28px");
                    }
                    else {
                        optIn.parents().eq(3).css("margin-top", "32px");
                    }
                }
            }
            else if (isTablet()) {
                if (twoTone.attr('id') == 'block-recommendations') {
                    if ((thirdParent == 1) && (fifthParent == 1)) {
                        twoToneBottom.css({ position: "relative", top: "-28px" });
                    }
                    else {
                        if ($(window).width() == 960) {
                            optIn.parents().eq(1).css("margin-top", "-4px");
                        }
                        else if ($(window).width() < $(window).height()) {
                            optIn.parents().eq(1).css("margin-top", "22px");
                        }
                        else if ($(window).width() > $(window).height()) {
                            optIn.parents().eq(1).css("margin-top", "");
                        }
                    }
                }
                else if ((optIn.parents().eq(3).hasClass('twotonebottom')) &&
                    ((secondParent == 1) || (thirdParent == 1))) {
                    twoToneBottom.css({ position: "relative", top: "-25px" });
                }
                else {
                    if (optIn.parents().eq(4).prev().height() > 700) {
                        optIn.parents().eq(3).css("margin-top", "33px");
                    }
                    else {
                        optIn.parents().eq(3).css("margin-top", "42px");
                    }
                }
            }
            else {
                if (twoTone.attr('id') == 'block-recommendations') {
                    if ((thirdParent == 1) && (fifthParent == 1)) {
                        twoToneBottom.css({ position: "relative", top: "-19px" });
                    }
                    twoToneBottom.css("margin-bottom", "-125px");
                }
                else if ((optIn.parents().eq(3).hasClass('twotonebottom')) &&
                    ((secondParent == 1) || (thirdParent == 1))) {
                    twoToneBottom.css({ position: "relative", top: "2px" });
                }
                else {
                    if (optIn.parents().eq(4).prev().height() > 600) {
                        optIn.parents().eq(3).css("margin-top", "28px");
                    }
                    else {
                        optIn.parents().eq(3).css("margin-top", "37px");
                    }
                }
            }


            if ($('body').hasClass("blogpostpage") || $('body').hasClass("accenturehomepage")) {
                if ($(window).width() == 2560) {
                    if (blockTwoTone.hasClass('left')) {
                        blockTwoTone.css('width', '3690px');
                    }
                    if (blockTwoTone.hasClass('right')) {
                        blockTwoTone.css('margin-right', '-370px');
                    }
                }
                if ($(window).width() == 1920) {
                    blockTwoTone.css('width', '2435px');
                    if (blockTwoTone.hasClass('left')) {
                        blockTwoTone.css('margin-right', '-515px');
                    }
                }
                if ($(window).width() == 1600) {
                    blockTwoTone.css('width', '1800px');
                    if (blockTwoTone.hasClass('left')) {
                        blockTwoTone.css('margin-right', '-200px');
                    }
                    if (blockTwoTone.hasClass('right')) {
                        blockTwoTone.css('margin-left', '-200px');
                    }
                }
                if ($(window).width() == 1080) {
                    blockTwoTone.css('height', '910px');
                }
                if ($(window).width() >= 850 && $(window).width() < 1050) {
                    blockTwoTone.css('width', '1050px');
                    if (blockTwoTone.hasClass('left')) {
                        blockTwoTone.css({ 'margin-right': '-25px', "height": "875px" });
                    }
                    if (blockTwoTone.hasClass('right')) {
                        blockTwoTone.css('margin-left', '-25px');
                    }
                }
                if ($(window).width() >= 650 && $(window).width() < 750) {
                    blockTwoTone.css({ 'width': '855px', "height": "660px" });
                    if (blockTwoTone.hasClass('right')) {
                        blockTwoTone.css('margin-left', '-120px');
                    }
                }
                if ($(window).width() >= 550 && $(window).width() < 650) {
                    blockTwoTone.css('width', '730px');
                    if (blockTwoTone.hasClass('right')) {
                        blockTwoTone.css('margin-left', '-90px');
                    }
                }
            }
        }

        else {
            dfactor = $this.data('shape') == "delta" ? 1 : 0;
            var image = $this.data('background-image');
            var video = $this.data('background-video');
            var align = $this.data('background-align');
            var blockHeight = height + (dfactor + 2) * xfactor + 8;
            var marginAdjustment;
            var shapeContainer = $this.data("shape");
            var dataShapeVal;

            if (shapeContainer != null) {
                dataShapeVal = shapeContainer.toLowerCase();
            }

            if (isValidString(image)) {
                var screenWidth = $(window).width();
                image = image.replace("__w__", "w" + screenWidth);
            }

            if (!isMobile() && $(this).hasClass('module-announcement')) {
                blockHeight = 0;
            }

            if (dataShapeVal == "square") {
                marginAdjustment = 10;
            } else if (dataShapeVal == "edge") {
                marginAdjustment = 10.2;
            } else {
                marginAdjustment = 9.7;
            }

            $("div[data-content-id='" + $this[0].id + "']").addClass('shape' + shapeColor)
                .css({
                    'margin-top': (-1 * (1 + preshape) * xfactor * (index == 0 ? 0 : 1) - marginAdjustment)  // If delta then -2x else -x
                })
                .find('.inner')
                //.height(height + (dfactor) * xfactor) // If delta then 3x height else 2x;
                .css({
                    'padding-top': xfactor,
                    'padding-bottom': xfactor,
                    'margin-top': -1 * xfactor,
                    'height': blockHeight,
                    'background-position': align
                });
            preshape = dfactor;

            if (firstParent > 1) {
                if (isDesktop() || $(window).width() == 960) {
                    optIn.css("margin-top", "-10px");
                }
            }
        }
    }
    function adjustOverflow() {  //fixes overflow of bottom shapes
        var $shape1 = $('#shape-1');
        var mt = -2 * xfactor;
        var h = $('#content-wrapper').outerHeight() - $('#' + $('#shape-0').data('content-id')).outerHeight() + xfactor;
        var firstBlockShape = $('#content-wrapper > section > div').first();
        var marginTopAdjustment;
        var firstBlockShapeVal = firstBlockShape.data('shape').toLowerCase();

        $('#overflow-controller').css({
            'margin-top': mt,
            'padding-top': xfactor,
            'height': h
        });
        //[3/18/15] Merge 1/29 from Main Release Branch
        $('#shape-0').css('margin-top', 0);

        if (firstBlockShapeVal == "square") {
            marginTopAdjustment = -6.5;
        } else if (firstBlockShapeVal == "edge") {
            marginTopAdjustment = -8;
        } else {
            marginTopAdjustment = -4;
        }

        $('#shape-1').css('margin-top', marginTopAdjustment);

        //// Overflow fix for docking
        mt = $shape1.outerHeight(true) - $shape1.outerHeight() - xfactor;

        h = $('#shape-0').outerHeight();

        $('#overflow-docking').css({
            'margin-top': mt,
            'padding-top': mt * -1,
        });

        if ($('#shape-0').hasClass('ui-delta')) {
            $('#overflow-docking').css('height', h);
        }
    }
    var xfactor = Math.ceil(pageState.globalHalf_x); // adjusted by half to adjust background images on shapes
    var dfactor = 0;
    var preshape = 0;
    var i = 0;

    //overlapping blocks
    $('.ui-container:not(.c-ui-square)').each(function () {
        $(this).css('min-height', xfactor * 2);
    });
    $('#block-footer').css("min-height", "471px");

    for (i = 0; i < divUiContainerLength; i++) {
        eachLayout($divUiContainer[i], i);
    }
    adjustOverflow();
}

function AdjustLayoutIE8() {  //TODO: cleanup DOM interactions and var hoisting
    function SetACNLogo() {
        if (document.documentMode == 8) {
            $(".acn-icon.icon-accent").addClass("ie8-acn-logo");
        }
    }
    var xfactor = Math.ceil($(window).width() * 0.40220017); /* tangent (21.91deg)*/
    $('div.ui-container').each(function (index) {
        var $this = $(this);
        if (index == 0 && $('#accent').length > 0)
            $this.find('.block-title').css({ 'margin-top': 112, 'margin-bottom': 60 });

        var height = $this.outerHeight() * 1;

        var marginTop = -1 * xfactor * (index == 0 ? 0 : 0.5);
        var shapeColor = 'shape-color-white';
        if ($this.data('shape-color').length > 0) shapeColor = 'shape-color-' + $this.data('shape-color');

        var $shape = $("div[data-content-id='" + $this[0].id + "']");

        $shape.addClass(shapeColor)
            .css({
                'margin-top': (marginTop * ($shape.hasClass('image-shape') ? 2 : 1) - 5) // for IE8 only -x
            })
            .find('.inner')
            .css({
                'height': height - xfactor * ($shape.hasClass('image-shape') ? 0.5 : 1) //- (index %2 == 0? 100 : 0 ) //- xfactor * 0.75
            });
    });
    SetTerminators();
    SetACNLogo();
}

function PositionLayout() {  //TODO: cleanup DOM interactions and var hoisting
    var screen = pageState.windowWidth;
    var xfactor = pageState.global_x / 2;
    var iconAccent = $('#accent > .icon-accent');
    var imageAccent = $('.image-accent');
    var visibleWindow = $('#content-wrapper').css('marginTop').replace('px', '') * 1;
    var left = ((screen - $('.ui-container').innerWidth()) / 2);
    var marqueeParallax = $('#block-hero .item');

    marqueeParallax.height(visibleWindow + xfactor);
    $('.ui-content-box .floatcontainer').removeAttr('style');

    // chevron logo object on interactive and non-interactive pages
    var chevronLogo = {
        customLogoItem: $('.customLogo'),
        parsedOffset: parseInt($("#layout-wrapper").offset().top) - Math.ceil(xfactor),
        screenLaptopMin: 1000,
        screenLaptop: 1200,
        screenTablet: 768,

        init: function () {
            this.configIcon();
        },

        configIcon: function () {
            if (this.customLogoItem.length > 0) {
                this.customLogoDefault();
            } else {
                this.nonCustomLogoDefault();
            }
            iconAccent.css('display', 'block');
        },

        leftFactor: function () {
            var pxAdjustment;
            var mobileDistort = 666;

            if (screen >= this.screenLaptopMin) {
                pxAdjustment = 26;
            } else if (screen >= this.screenTablet && screen < this.screenLaptopMin) {
                pxAdjustment = 28;
            } else if (screen >= mobileDistort + 1 && screen < this.screenTablet) {
                pxAdjustment = 36;
            } else if (screen > 450 && screen < mobileDistort) {
                pxAdjustment = 31;
            } else {
                pxAdjustment = 20;
            }
            return pxAdjustment;
        },

        // CUSTOM LOGO METHODS:
        // customIconDefault
        // customIconFont 
        // customIconPosition     
        customLogoDefault: function () {
            this.customLogoPosition();
            this.customLogoFont();

            iconAccent.css({
                'left': this.leftFactor() + left + 'px',
                'transform': 'rotate(0.9deg)'
            });

        },

        customLogoFont: function () {
            var customAccent = $('#accent');
            var cssStylesLaptop = { 'width': '295px', 'height': '295px' };
            var cssStylesTablet = { 'width': '255px', 'height': '255px' };
            var cssStylesMobile = { 'width': '150px', 'height': '150px' };

            if (screen >= this.screenLaptopMin) {
                iconAccent.css('font-size', '295px');
                if ($('.ie').length > 0) {
                    customAccent.css(cssStylesLaptop);
                }
                else {
                    imageAccent.css(cssStylesLaptop);
                }
            } else if (screen >= this.screenTablet) {
                iconAccent.css('font-size', '255px');
                if ($('.ie').length > 0) {
                    customAccent.css(cssStylesTablet);
                }
                else {
                    imageAccent.css(cssStylesTablet);
                }
            } else {
                iconAccent.css('font-size', '150px');
                if ($('.ie').length > 0) {
                    customAccent.css(cssStylesMobile);
                }
                else {
                    imageAccent.css(cssStylesMobile);
                }
            }
        },

        customLogoPosition: function () {
            var skewPerChevronDistance = Math.ceil(0.40220017 * (left + this.leftFactor()));
            var diffFactor;
            var imageAccent = $('.image-accent');

            if (screen >= this.screenLaptopMin) {
                diffFactor = 60.5 - skewPerChevronDistance;
            } else if (screen >= this.screenTablet) {
                diffFactor = 52 - skewPerChevronDistance;
            } else if (screen === 600) {
                // For Nexus 7
                diffFactor = 29.5 - skewPerChevronDistance;
            } else if (screen === 414) {
                // For iPhone 6+
                diffFactor = 30.5 - skewPerChevronDistance;
            } else if (screen === 360) {
                //For S5
                if (window.innerWidth < window.innerHeight) {
                    // For Portrait Orientation
                    diffFactor = 30 - skewPerChevronDistance;
                } else
                    // For Landscape Orientation
                    diffFactor = 30.5 - skewPerChevronDistance;
            } else if (screen === 375) {
                // For Iphone 6
                if (window.innerWidth < window.innerHeight) {
                    // For Portrait Orientation
                    diffFactor = 30 - skewPerChevronDistance;
                } else
                    // For Landscape Orientation
                    diffFactor = 29 - skewPerChevronDistance;
            } else if (screen === 568) {
                // For iPhone 5
                if (window.innerWidth < window.innerHeight) {
                    // For Portrait Orientation
                    diffFactor = 29.5 - skewPerChevronDistance;
                } else
                    // For Landscape Orientation
                    diffFactor = 29 - skewPerChevronDistance;
            } else {
                diffFactor = 29.5 - skewPerChevronDistance;
            }

            // For Chrome and Safari
            if (window.chrome && window.chrome.webstore || navigator.userAgent.indexOf("Safari") > -1) {
                diffFactor += 1;
            }

            iconAccent.css('top', visibleWindow - xfactor - (diffFactor));

            //For IE
            if ($('.ie').length > 0) {
                imageAccent.css('top', visibleWindow - xfactor - (diffFactor + 1.5));
            }
        },

        // NON-CUSTOM LOGO METHODS:
        // nonCustomIconDefault
        // nonCustomIconFont 
        // nonCustomIconPosition  
        nonCustomLogoDefault: function () {
            this.nonCustomLogoPosition();
            this.nonCustomLogoFont();
        },

        nonCustomLogoFont: function () {

            var accentLogo = $('#accent');

            if (screen < this.screenLaptop) {
                var computedXfactor = Math.ceil(xfactor * 2.001);

                iconAccent.css('font-size', computedXfactor);

                //Customizing size of Accenture Logo for IE

                if ($('.ie').length > 0) {

                    if (imageAccent.closest('#accent').length > 0) {
                        accentLogo.css('height', computedXfactor);
                        accentLogo.css('width', computedXfactor);
                    }
                } else {
                    imageAccent.css('height', computedXfactor);
                    imageAccent.css('width', computedXfactor);
                }

            } else {
                iconAccent.css('font-size', '');

                accentLogo.css('height', '');
                accentLogo.css('width', '');

                imageAccent.css('height', '');
                imageAccent.css('width', '');
            }

        },

        nonCustomLogoPosition: function () {
            iconAccent.css({
                'left': '0px',
                'top': visibleWindow - xfactor,
                'transform': 'none'
            });

            imageAccent.css({
                'left': '-2px',
                'transform': 'rotate(.4deg)',
            });

            //Fixing gap for S5
            if (screen === 360) {
                imageAccent.css({
                    'top': visibleWindow - xfactor,
                });
            }
            //Fixing gap for iPhone5
            else if (screen === 320) {
                imageAccent.css({
                    'top': visibleWindow - xfactor + 0.5,
                    'transform': 'rotate(.2deg)',
                });
            }
            else {
                imageAccent.css({
                    'top': visibleWindow - xfactor + 1,
                });
            }
        }
    }

    // activating chevron logo object
    chevronLogo.init();

    var right = 0;
    if (screen >= 1000) right = (screen - 1000) / 2;
    else right = (screen / 20);

    $('#block-blockannouncement , .cookie-hero').css('right', right + 'px');
    $('#block-blockannouncement').show('slow');

    $('.video-wrapper-background').each(function () {
        var $this = $(this);

        if ($this.parents().eq(2).hasClass('ui-square')) {
            videoHeight = $(".c-ui-square").height() + 15;
            if ($('.videofilter-results').children().length > 0) {
                var vidBackground = $(".blockVideoBackground ");
                videoWidth = $("#content-wrapper").width() - $('.videofilter-results').width();
                vidBackground.parents().eq(2).css('margin-left', '0px');
                vidBackground.parents().eq(2).css('width', videoWidth);
                vidBackground.parents().eq(2).css('background-repeat', 'round');
            }
            else {
                videoWidth = $("#content-wrapper").width();
                $('.videofilter-container').hide();
            }
            videoHeight = 730;
        } else {
            var $block = $this.closest('.inner');

            var block = $block.height();
            var xfactor = pageState.global_x;
            var videoHeight = (block + 2);

            if (getViewportSizeWidth() >= 1696) { videoHeight = (block + 2); }
            var videoWidth = (videoHeight * 16) / 9;

            if (videoWidth < $block.width()) {
                videoWidth = $block.width();
                videoHeight = (videoWidth * 9) / 16;
            }
        }
        $this.removeAttr('style').attr({ 'height': videoHeight - 10 + 'px', 'width': videoWidth + 'px' });
    });
}

// For IE8
function SetTerminators() {  //TODO: cleanup DOM interactions and var hoisting, maybe move this into scope of AdjustLayoutIE8 function
    var xfactor = pageState.global_x;
    var dfactor = 0;
    var preshape = 0;
    var shape = {};
    shape.IsLeft = false;
    shape.IsDelta = false;
    shape.height = 0;

    var $uiContainer = $('div.ui-container');
    $uiContainer.each(function (index) {
        var $this = $(this);
        var $shape = $("div[data-content-id='" + $this[0].id + "']");
        shape.height = $this.outerHeight() * 1;
        shape.IsDelta = $shape.hasClass('ui-delta');
        shape.IsLeft = $shape.hasClass('left');

        dfactor = $this.data('shape') == "delta" ? 1 : 0;

        // Setting broder width for triangular shape
        var xBorderWidth = $(window).width();

        $shape.find("div.terminator.before").css({
            'border-top-width': xfactor,
            'margin-top': -0.5 * xfactor
        }).next('.inner').css('margin-top', '');

        if (index != $uiContainer.length - 1) {
            $shape.find("div.terminator.after").css({ 'border-bottom-width': xfactor });
        } else {
            $shape.find("div.terminator.after").addClass('footer-terminator');
        }

        if (shape.IsLeft && shape.IsDelta) {
            $shape.find("div.terminator.before, div.terminator.after").css({ 'border-left-width': xBorderWidth });
        }
        else if (!shape.IsLeft && shape.IsDelta) {
            $shape.find("div.terminator.before, div.terminator.after").css({ 'border-right-width': xBorderWidth });
        }
        else if (shape.IsLeft && !shape.IsDelta) {
            $shape.find("div.terminator.before").css({ 'border-left-width': xBorderWidth });
            $shape.find("div.terminator.after").css({ 'border-right-width': xBorderWidth });
        }
        else {
            $shape.find("div.terminator.before").css({ 'border-right-width': xBorderWidth });
            $shape.find("div.terminator.after").css({ 'border-left-width': xBorderWidth });
        }
    });
}

function GetCarouselBackground(container) {
    function addProxySlide(slide) {
        function addVideo(slide) {
            var span = document.createElement('span');
            var cfg = {
                height: '100%',
                mediaId: video,
                playerId: video,
                width: '100%',
                wMode: 'transparent'
            };

            insertVideoObject(slide, cfg);
        }
        var $slide = $(slide);
        var image = $slide.data('bg-image');
        var color = $slide.data('bg-color');
        var video = $slide.data('bg-video');
        var videoAutoPlay = $slide.data('bg-video-autoplay');
        var proxySlide = document.createElement('div');
        var proxyClass = 'item parallax image';

        if (isValidString(videoAutoPlay)) {
            proxyClass += ' ' + videoAutoPlay;
        }
        if ($slide.hasClass('active')) {
            proxyClass += ' active';
        }

        if (!isMobile()) {
            if (isValidString(image)) {
                image = image.replace('__w__', 'w' + pageState.windowWidth);
                proxySlide.style.backgroundImage = image;
            }
            if (isValidString(video)) {
                addVideo();
            }
        } else {
            proxyClass += ' bg-color-' + color;
        }
        proxySlide.className = proxyClass;
        carouselInner.appendChild(proxySlide);
    }
    //this method takes container and adds a proxy carousel inside the 'inner'
    var proxyCarousel = document.createElement('div');
    var carouselInner = document.createElement('div');
    var $carousel = $(container).find('.block-carousel');
    var items = $carousel.find('.item');
    var itemLen = items.length;
    var i;

    if ($carousel.length > 0) {
        carouselInner.className = 'carousel-inner';
        carouselInner.style.height = '100%';
        proxyCarousel.id = 'proxy-' + $carousel[0].id;
        proxyCarousel.className = 'carousel convertible-block-carousel';
        proxyCarousel.setAttribute('data-interval', 99999999);
        proxyCarousel.setAttribute('data-ride', 'carousel');
        proxyCarousel.setAttribute('data-wrap', true);
        proxyCarousel.style.height = '100%';
        proxyCarousel.appendChild(carouselInner);

        for (i = 0; i < itemLen; i++) {
            addProxySlide(items[i]);
        }
    }
    return proxyCarousel;
}

function addSwipeToCarousels(carousel) { //TODO: review this code
    var control = (carousel == undefined || carousel == null) ? '.carousel-inner' : carousel;

    $(control).swipe({
        //Generic swipe handler for all directions
        swipeLeft: function (event, direction, distance, duration, fingerCount) {
            if (fingerCount > 0) {
                $(this).parent().carousel('next');
            }
        },
        swipeRight: function (event, direction, distance, duration, fingerCount) {
            if (fingerCount > 0) {
                $(this).parent().carousel('prev');
            }
        },
        tap: function (event, target) {
            //Bug 356203: Share Icons are not displayed when Share component is clicked.
            if ($(target).hasClass('icon-share') || $(target).parent().hasClass('icon-share')) {
                var socialShare = $(target).closest('.social-likes_single-w');
                socialShare.popover({
                    html: true,
                    placement: 'bottom',
                    container: 'body',
                    content: function () {
                        return socialShare.find('#tooltipPopup').html();
                    }
                });
                return;
            }

            var sitetarget = new String($(target).attr('href'));
            var targetWindow = '';

            //do not handle anything except left mouse click
            if (typeof event.button != 'undefined' && event.button > 0)
                return;

            event.preventDefault ? event.preventDefault() : event.returnValue = false;

            var url = '';
            // to handle article title with links
            if ($(target).is('a') || $(target).hasClass('cta')) {
                url = $(target).attr('href');
                targetWindow = $(target).attr('target');
            }
            else {
                target = $(target).closest('a');
                url = target.attr('href');
                targetWindow = target.attr('target');
            }
            //check if in edit mode
            var editMode = $(control).hasClass('edit-mode');

            if (!editMode) {
                //redirect to original target
                if (sitetarget != 'undefined' & sitetarget != null & sitetarget.length > 0) {
                    // handle if there is a target attribute specified
                    targetWindow == '_blank' ? window.open(sitetarget, '_blank') : window.location = sitetarget;
                }
                //redirect if url is present
                else {
                    // SIR #426805: About Accenture pages Layout: Displays error message when clicking the CTA link
                    if (url && url.length > 0) {
                        targetWindow == '_blank' ? window.open(url, '_blank') : window.location = url;
                    }
                }
            }
        },
        //Default is 75px, set to 0 for demo so any distance triggers swipe
        threshold: 0,
    });
}

function setupVideoPlayers() {
    var i;
    function eachPlayer(origElm) {
        function isValidPlayer() {
            return typeof player === 'object' && player !== null && typeof player.id === 'string';
        }
        var $this = $(origElm);
        var playerId = $this.data('background-playerid');
        var player = document.getElementById('playerId');

        if (isMobile() && isValidPlayer()) {
            $(player).width(315).height(236).data('orig-width', 315);
        } else if (isTablet() && isValidPlayer()) {
            $(player).width(640).height(480).data('orig-width', 640);
        } else if (($this.find('.ui-content-box section .col-sm-12 .col-sm-6.visible-sm div').hasClass('player-container')) ||
            ($this.find('.ui-content-box section .col-sm-12 .col-sm-12.visible-xs div').hasClass('player-container'))) {
            $this.find('.ui-content-box section > .col-sm-12 .col-sm-12.visible-xs').remove()
                .find('.ui-content-box section > .col-sm-12 > .col-sm-6.visible-sm').empty();
        }
    }

    for (i = 0; i < divUiContainerLength; i++) {
        eachPlayer($divUiContainer);
    }
}

///---------------------------------------------------------------///
//Helper Functions
///---------------------------------------------------------------///

//This is to persist the hash in the URL.
function persistHash() {
    var prevUrl;
    var prevUrlArray;

    if (typeof sessionStorage === "object") {
        prevUrl = sessionStorage.getItem("hashCallback");
        if (isValidString(prevUrl)) {
            if (window.location.hash === "" && window.location.href.localeCompare(prevUrl) !== 0) {
                prevUrlArray = prevUrl.split('#');
                if (window.location.href.localeCompare(prevUrlArray[0]) === 0) {
                    location.href = prevUrl;
                }
            } else {
                sessionStorage.setItem("hashCallback", "");
            }
        }
    }
}

function setState() {
    function InternetExplorer() {
        var msie = ua.indexOf("msie ");
        var ieno = -1;

        if (msie > 0) { // If Internet Explorer, return version number
            ieno = parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)));
        }
        else if (ua.indexOf("trident/7.0") != -1 && appName == "netscape") {
            ieno = "11";
        }
        return ieno;
    }
    var $html = $('html');
    var ieno;
    var mozillaFirefox = "firefox";
    var microsoftEdge = "edge";
    var ua = navigator.userAgent.toLowerCase();
    var platform = window.navigator.platform;
    var appName = navigator.appName.toLowerCase();

    pageState.windowWidth = $(window).width(); // tangent (21.91deg)
    pageState.viewPortWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    pageState.global_x = Math.ceil(pageState.windowWidth * 0.40220017);
    pageState.globalHalf_x = pageState.global_x / 2;
    if (typeof pageState.isEmbedScript !== 'boolean') {//this is the only pageState property that should be set outside this function
        pageState.isEmbedScript = false;               //it is set asynchronously once an optional script for video players is loaded
    }

    if (pageState.windowWidth < 768) $divUiContainer = $('div.ui-container');
    else $divUiContainer = $('div.ui-container:not(.floating)');

    //$divUiContainer = $('div.ui-container');
    divUiContainerLength = $divUiContainer.length;
    callAdjustLayout = AdjustLayout;

    pageState.ieno = ieno = InternetExplorer();
    if (ieno > 0) {
        pageState.isIE = true;
        $html.addClass('ie'); //Bug #304543: adds ie class to html element
        if (ieno > 6 && ieno < 9) {
            callAdjustLayout = AdjustLayoutIE8;
            $html.addClass('lte-ie8');
        } else {
            $html.removeClass('lte-ie8');
        }
    } else {
        pageState.isIe = false;
        $html.removeClass('ie');
    }

    //RMT5715 US041
    if (navigator.userAgent.toLowerCase().indexOf(mozillaFirefox) > -1) {
        $html.addClass('firefox');
    }

    //RMT 7441 US002 Edge 200% alignment fix
    if (navigator.userAgent.toLowerCase().indexOf(microsoftEdge) > -1) {
        $html.addClass('ie-edge');
    }

    if (ua.indexOf("safari/") !== -1 && ua.indexOf("windows") !== -1 && ua.indexOf("chrom") === -1) {
        pageState.isWindowsSafari = true; // It says it's Safari, it says it's on Windows, it DOESN'T say it's Chrome/Chromium
        $html.addClass('windows-safari'); //Bug #304537 ( Modified): The field 'Assigned To' contains a value that is not in the list of supported values.
    } else {
        pageState.isWindowsSafari = false;
        $html.removeClass('windows-safari');
    }

    if (ua.indexOf('chrom') !== -1) {
        pageState.isWindowsChrome = true;
    } else {
        pageState.isWindowsChrome = false;
    }

    if (isValidString(platform)) {
        platform = platform.toLowerCase();
        if (platform.indexOf('iphone') >= 0 || platform.indexOf('ipod') >= 0 || platform.indexOf('ipad') >= 0) {
            pageState.isIOS = true;
        } else {
            pageState.isIOS = false;
        }
    }

    if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch || window.navigator.msMaxTouchPoints) {
        pageState.isTouch = true;
        $html.addClass('touch');
    } else {
        pageState.isTouch = false;
        $html.removeClass('touch');
    }

    if (pageState.viewPortWidth < 768) {
        pageState.isMobile = true;
        $html.addClass('mobile');
    } else {
        pageState.isMobile = false;
        $html.removeClass('mobile');
    }
    if (pageState.viewPortWidth >= 768 && pageState.viewPortWidth <= 1000) {
        pageState.isTablet = true;
        $html.addClass('tablet');
    } else {
        pageState.isTablet = false;
        $html.removeClass('tablet');
    }
    if (pageState.viewPortWidth >= 1000) {
        pageState.isDesktop = true;
        $html.addClass('desktop');
    } else {
        pageState.isDesktop = false;
        $html.removeClass('desktop');
    }
}

function insertVideoObject(parent, cfg) {
    function makeParam(name, value) {
        var param = document.createElement('param');
        param.name = name;
        param.value = value;
        return param;
    }
    function initPlayer() {
        //$(object).width(cfg.width).height(cfg.height); //setting this while creating the object was causing bugs
        if (isValidString(cfg.marginWidth)) {
            $(object).css({ 'margin-left': cfg.marginLeft });
        }
    }

    var object = document.createElement('object');
    var flashVars = 'mediaId=' + cfg.mediaId;

    if (typeof parent.appendChild === 'function') {
        object.id = object.name = cfg.playerId;
        object.type = 'application/x-shockwave-flash';
        //object.className = 'LimelightEmbeddedPlayerFlash visible-lg'; //visible-lg was getting display:none?

        object.appendChild(makeParam('wmode', cfg.wMode));
        object.appendChild(makeParam('allowScriptAccess', 'sameDomain'));
        object.appendChild(makeParam('allowFullScreen', 'true'));
        if (isValidString(cfg.autoLoop)) {
            object.appendChild(makeParam('autoLoop', cfg.autoLoop));
        }
        if (isValidString(cfg.playerForm)) {
            flashVars = 'playerForm=' + cfg.playerForm + '&' + flashVars;
        } else {
            flashVars = 'playerForm=LVPPlayer&' + flashVars;
        }
        if (isValidString(cfg.autoPlay) && cfg.autoplay == 'true') {
            flashVars += '&autoplay=true';
        }
        //set default video quality
        flashVars += '&defaultQuality=1200';

        object.appendChild(makeParam('flashVars', flashVars));
        parent.appendChild(object);

        if (videoEmbedScript()) {
            initPlayer();
        }
    }
}

function addParallaxEventHandler() {
    function handleParallaxScroll() {
        function eachParallaxScroll(elm) {
            var $this = $(elm);
            var top = $this.offset().top;
            var bottom = top + $this.height() + viewportHeight;
            var pos;

            if (scrollTop >= top - viewportHeight && scrollTop <= bottom) {
                if (isWindowsSafari) {
                    pos = Math.ceil((scrollTop - top) * 0.2);
                } else {
                    pos = Math.ceil(-(scrollTop - top) * 0.07);
                }

                if (isWindowsChrome) {
                    $this.css("background-position", '0px ' + pos + 'px');
                    $('.hasProxyCarousel .carousel-inner .active').css('background-position', '0px ' + pos + 'px');
                }
                else { $this.css("background-position-y", pos).siblings('.item').css('background-position-y', pos); }
            } //else { //else clause doesn't seem to have any effect
            //$this.css("background-position-y", '');
            //}
        }
        var $visible = $parallax.filter(':visible');
        var visibleLength = $visible.length || 0;
        var scrollTop = $(window).scrollTop();
        var viewportHeight = $(window).innerHeight();
        var isWindowsSafari = IsWindowsSafari();
        var isWindowsChrome = IsWindowsChrome();
        var i;

        for (i = 0; i < visibleLength; i++) {
            eachParallaxScroll($visible[i]);
        }
    }
    var $parallax = $('.parallax');
    var parallaxLength = $parallax.length || 0;
    var i = 0;

    if (!IsTouch()) {
        $parallax.each(function () {
            var $this = $(this);
            var container = $this.closest('.outer').data('content-id');
            //For hero
            if ($this.closest('.carousel.hero').length > 0)
                container = this.id;
            if ($('#' + container).data('background-align') == 'Right')
                $this.css('background-position-x', 'right');
            else
                $this.css('background-position-x', 'left'); // default

            if ($('#' + container).data('background-cover') == 'True')
                $this.css('background-size', 'cover'); //else CSS will apply 100%, auto
        });

        $(window).on('scroll', function () {
            if (typeof requestAnimationFrame === 'function') {
                requestAnimationFrame(handleParallaxScroll);
            } else {
                handleParallaxScroll();
            }
        });
    }
}

///---------------------------------------------------------------///
//Utility Functions
///---------------------------------------------------------------///

function IsTouch() {
    return pageState.isTouch;
}
function InternetExplorer() {
    return pageState.ieno;
}
function IsIE() {
    return pageState.isIE;
}
function IsIE8() {
    return pageState.isIE && pageState.ieno < 9;
}
function IsWindowsSafari() {
    return pageState.isWindowsSafari;
}
function IsWindowsChrome() {
    return pageState.isWindowsChrome;
}
function IsIOS() {
    return pageState.isIOS;
}
function getViewportSizeWidth() {
    return pageState.viewPortWidth;
}

function isMobile() {
    return pageState.isMobile;
}

function isTablet() {
    return pageState.isTablet;
}

function isDesktop() {
    return pageState.isDesktop;
}
function videoEmbedScript() {
    return pageState.isEmbedScript;
}

function debounce(func, threshold, immediate) {
    var timeout;

    return function debounced() {
        if (timeout) {
            clearTimeout(timeout);
        } else if (immediate) {
            func();
        }
        timeout = setTimeout(func, threshold || 100);
    };
}

$.fn.extend({
    onHeightChange: function (callback) {
        var elm = this[0];
        var timer;
        function checkHeight() {
            var height = $(elm).height();
            if (elm.oldHeight && elm.oldHeight !== height) {
                callback();
            }
            else if (elm.oldHeight == undefined) {
                callback();
            }

            elm.oldHeight = height;
            timer = setTimeout(checkHeight, 500);
        }
        checkHeight();
    }
});

$.fn.extend({
    onBrowserResize: function (callback) {
        var elm = this[0];
        var timer;
        function checkWidth() {
            var width = $(elm).width();
            if (elm.oldWidth && elm.oldWidth !== width) {
                callback();
            }
            elm.oldWidth = width;
            timer = setTimeout(checkWidth, 500);
        }
        checkWidth();
    }
});

function isValidString(str) {
    return (typeof str === 'string' && str !== '');
}
function replaceAll(find, replace, str) {
    return typeof str == 'undefined' || str === null ? '' : str.replace(new RegExp(find, 'g'), replace);
}

//Convert Limelight video from Background to Media Player
function convertVideo() {

    $('div.ui-container').each(function (index) {
        var $this = $(this);
        var mediaId = $this.data('background-mediaid');
        var playerId = $this.data('background-playerid');
        var thumbnail = $this.data('background-image');

        if ((mediaId != "" && mediaId != undefined) && (playerId != "" && playerId != undefined)) {
            var autoPlay = $this.data('background-autoplay');
            var autoLoop = $this.data('background-autoloop');
            var wMode = 'transparent';
            var displayThumbnail = "";
            var displayType = "display:block";

            if ($(this).hasClass('c-ui-square') && thumbnail !== undefined) {
                displayThumbnail = "<div id='media-video-thumbnail' data-video-player-id='" + playerId + "'>" +
                    "<img src=" + thumbnail + " class='img-responsive img-responsive welcome-image' style='width:100%;height:100%'>" +
                    "<div class='acn-icon icon-circle color-primary floating'>" +
                    "<span id='playPauseIcon' class='acn-icon icon-play' tabindex='-1'></span>" +
                    "<span id='play' class='icon-text hidden'>PLAY</span>" +
                    "<span id='pause' class='icon-text' style='display: none;'>PAUSE</span>" +
                    "</div>" +
                    "</div>";
                displayType = "display:none";
            }

            if (isMobile() && IsTouch()) {
                if (!$this.find('.ui-content-box section .col-sm-12 .col-sm-12.visible-xs div').hasClass('player-container')) {
                    $this.find('.ui-content-box section > .col-sm-12 > .col-sm-6.visible-sm').remove();
                    $this.find('.ui-content-box section > .col-sm-12').prepend("<div class='col-sm-12 visible-xs'><div class='player-container'></div><div class='media-container'>" +
                        displayThumbnail +
                        "<span style='" + displayType + "'>" +
                        "<object type='application/x-shockwave-flash' width='100%' height='100%' data-orig-width='640'" +
                        "id='" + playerId + "' name='" + playerId + "'>" +
                        "<param name='movie' value=''>" +
                        "<param name='wmode' value='" + wMode + "'>" +
                        "<param name='allowScriptAccess' value='sameDomain'>" +
                        "<param name='allowFullScreen' value='true'>" +
                        "<param name='autoLoop' value='" + autoLoop + "'>" +
                        "<param name='flashVars' value='playerForm=LVPPlayer&amp;mediaId=" + mediaId + "'>" +
                        "</object>" +
                        "</span></div></div></div>");
                }
            }
            else if (isTablet() || IsTouch()) {
                if (!$this.find('.ui-content-box section .col-sm-12 .col-sm-6.visible-sm div').hasClass('player-container')) {
                    $this.find('.ui-content-box section > .col-sm-12 > .col-sm-12.visible-xs').remove();
                    $this.find('.ui-content-box section > .col-sm-12').prepend("<div class='col-sm-12 visible-sm visible-md'><div class='player-container'></div><div class='media-container'>" +
                        displayThumbnail +
                        "<span style='" + displayType + "'>" +
                        "<object type='application/x-shockwave-flash' width='100%' height='100%' data-orig-width='640'" +
                        "id='" + playerId + "' name='" + playerId + "' " +
                        "data=''>" +
                        "<param name='movie' value=''>" +
                        "<param name='wmode' value='" + wMode + "'>" +
                        "<param name='allowScriptAccess' value='sameDomain'>" +
                        "<param name='allowFullScreen' value='true'>" +
                        "<param name='autoLoop' value='" + autoLoop + "'>" +
                        "<param name='flashVars' value='playerForm=LVPPlayer&amp;mediaId=" + mediaId + "'>" +
                        "</object>" +
                        "</span></div></div></div>");
                }
                $this.find('.icon-play').css({ "font-size": "35px", "margin-left": "3px" });
            }
            else {
                $(this).css('margin-top', '-2px');
                if (($this.find('.ui-content-box section .col-sm-12 .col-sm-6.visible-sm div').hasClass('player-container')) ||
                    ($this.find('.ui-content-box section .col-sm-12 .col-sm-12.visible-xs div').hasClass('player-container'))) {
                    $this.find('.ui-content-box section > .col-sm-12 .col-sm-12.visible-xs').remove()
                        .find('.ui-content-box section > .col-sm-12 > .col-sm-6.visible-sm').empty();
                }
            }
        }

    });
}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.sidr.js
/*version 1*/
/*
 * Sidr
 * https://github.com/artberri/sidr
 *
 * Copyright (c) 2013 Alberto Varela
 * Licensed under the MIT license.
 */

;(function( $ ){

  var sidrMoving = false,
      sidrOpened = false;

  // Private methods
  var privateMethods = {
    // Check for valids urls
    // From : http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url
    isUrl: function (str) {
      var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
      if(!pattern.test(str)) {
        return false;
      } else {
        return true;
      }
    },
    // Loads the content into the menu bar
    loadContent: function($menu, content) {
      $menu.html(content);
    },
    // Add sidr prefixes
    addPrefix: function($element) {
      var elementId = $element.attr('id'),
          elementClass = $element.attr('class');

      if(typeof elementId === 'string' && '' !== elementId) {
        $element.attr('id', elementId.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-id-$1'));
      }
      if(typeof elementClass === 'string' && '' !== elementClass && 'sidr-inner' !== elementClass) {
        $element.attr('class', elementClass.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-class-$1'));
      }
      $element.removeAttr('style');
    },
    execute: function(action, name, callback) {
      // Check arguments
      if(typeof name === 'function') {
        callback = name;
        name = 'sidr';
      }
      else if(!name) {
        name = 'sidr';
      }

      // Declaring
      var $menu = $('#' + name),
          $body = $($menu.data('body')),
          $html = $('html'),
          menuWidth = $menu.outerWidth(true),
          speed = $menu.data('speed'),
          side = $menu.data('side'),
          displace = $menu.data('displace'),
          onOpen = $menu.data('onOpen'),
          onClose = $menu.data('onClose'),
          bodyAnimation,
          menuAnimation,
          scrollTop,
          bodyClass = (name === 'sidr' ? 'sidr-open' : 'sidr-open ' + name + '-open');

      // Open Sidr
      if('open' === action || ('toggle' === action && !$menu.is(':visible'))) {
        // Check if we can open it
        if( $menu.is(':visible') || sidrMoving ) {
          return;
        }

        // If another menu opened close first
        if(sidrOpened !== false) {
          methods.close(sidrOpened, function() {
            methods.open(name);
          });

          return;
        }

        // Lock sidr
        sidrMoving = true;

        // Left or right?
        if(side === 'left') {
          bodyAnimation = {left: menuWidth + 'px'};
          menuAnimation = {left: '0px'};
        }
        else {
          bodyAnimation = {right: menuWidth + 'px'};
          menuAnimation = {right: '0px'};
        }

        // Prepare page if container is body
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.css('overflow-x', 'hidden').scrollTop(scrollTop);
        }

        // Open menu
        if(displace){
          $body.addClass('sidr-animating').css({
            width: $body.width(),
            position: 'absolute'
          }).animate(bodyAnimation, speed, function() {
            $(this).addClass(bodyClass);
          });
        }
        else {
          setTimeout(function() {
            $(this).addClass(bodyClass);
          }, speed);
        }
        $menu.css('display', 'block').animate(menuAnimation, speed, function() {
          sidrMoving = false;
          sidrOpened = name;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onOpen callback
        onOpen();
      }
      // Close Sidr
      else {
        // Check if we can close it
        if( !$menu.is(':visible') || sidrMoving ) {
          return;
        }

        // Lock sidr
        sidrMoving = true;

        // Right or left menu?
        if(side === 'left') {
          bodyAnimation = {left: 0};
          menuAnimation = {left: '-' + menuWidth + 'px'};
        }
        else {
          bodyAnimation = {right: 0};
          menuAnimation = {right: '-' + menuWidth + 'px'};
        }

        // Close menu
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.removeAttr('style').scrollTop(scrollTop);
        }
        $body.addClass('sidr-animating').animate(bodyAnimation, speed).removeClass(bodyClass);
        $menu.animate(menuAnimation, speed, function() {
          $menu.removeAttr('style').hide();
          $body.removeAttr('style');
          $('html').removeAttr('style');
          sidrMoving = false;
          sidrOpened = false;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onClose callback
        onClose();
      }
    }
  };

  // Sidr public methods
  var methods = {
    open: function(name, callback) {
      privateMethods.execute('open', name, callback);
    },
    close: function(name, callback) {
      privateMethods.execute('close', name, callback);
    },
    toggle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    },
    // I made a typo, so I mantain this method to keep backward compatibilty with 1.1.1v and previous
    toogle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    }
  };

  $.sidr = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    }
    else if ( typeof method === 'function' || typeof method === 'string' || ! method ) {
      return methods.toggle.apply( this, arguments );
    }
    else {
      $.error( 'Method ' + method + ' does not exist on jQuery.sidr' );
    }

  };

  $.fn.sidr = function( options ) {

    var settings = $.extend( {
      name          : 'sidr',         // Name for the 'sidr'
      speed         : 200,            // Accepts standard jQuery effects speeds (i.e. fast, normal or milliseconds)
      side          : 'left',         // Accepts 'left' or 'right'
      source        : null,           // Override the source of the content.
      renaming      : true,           // The ids and classes will be prepended with a prefix when loading existent content
      body          : 'body',         // Page container selector,
      displace: true, // Displace the body content or not
      onOpen        : function() {},  // Callback when sidr opened
      onClose       : function() {}   // Callback when sidr closed
    }, options);

    var name = settings.name,
        $sideMenu = $('#' + name);

    // If the side menu do not exist create it
    if( $sideMenu.length === 0 ) {
      $sideMenu = $('<div />')
        .attr('id', name)
        .appendTo($('body'));
    }

    // Adding styles and options
    $sideMenu
      .addClass('sidr')
      .addClass(settings.side)
      .data({
        speed          : settings.speed,
        side           : settings.side,
        body           : settings.body,
        displace      : settings.displace,
        onOpen         : settings.onOpen,
        onClose        : settings.onClose
      });

    // The menu content
    if(typeof settings.source === 'function') {
      var newContent = settings.source(name);
      privateMethods.loadContent($sideMenu, newContent);
    }
    else if(typeof settings.source === 'string' && privateMethods.isUrl(settings.source)) {
      $.get(settings.source, function(data) {
        privateMethods.loadContent($sideMenu, data);
      });
    }
    else if(typeof settings.source === 'string') {
      var htmlContent = '',
          selectors = settings.source.split(',');

      $.each(selectors, function(index, element) {
        htmlContent += '<div class="sidr-inner">' + $(element).html() + '</div>';
      });

      // Renaming ids and classes
      if(settings.renaming) {
        var $htmlContent = $('<div />').html(htmlContent);
        $htmlContent.find('*').each(function(index, element) {
          var $element = $(element);
          privateMethods.addPrefix($element);
        });
        htmlContent = $htmlContent.html();
      }
      privateMethods.loadContent($sideMenu, htmlContent);
    }
    else if(settings.source !== null) {
      $.error('Invalid Sidr Source');
    }

    return this.each(function(){
      var $this = $(this),
          data = $this.data('sidr');

      // If the plugin hasn't been initialized yet
      if ( ! data ) {

        $this.data('sidr', name);
        if('ontouchstart' in document.documentElement) {
          $this.on('touchstart', function(e) {
            var theEvent = e.originalEvent.touches[0];
            this.touched = e.timeStamp;
          });
          $this.on('touchend', function(e) {
            var delta = Math.abs(e.timeStamp - this.touched);
            if(delta < 200) {
              e.preventDefault();
              methods.toggle(name);
            }
          });
        }
        else {
          $this.on("click", function(e) {
            e.preventDefault();
            methods.toggle(name);
          });
        }
      }
    });
  };

})( jQuery );

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\mutate.events.js
 
mutate_event_stack = [
			{
				name: 'width',
				handler: function (elem){
					n = {el:elem}
					if(!$(n.el).data('mutate-width'))$(n.el).data('mutate-width', $(n.el).width());
					if ($(n.el).data('mutate-width')&&$(n.el).width() != $(n.el).data('mutate-width')  ) {
						$(n.el).data('mutate-width', $(n.el).width());
						return true;
					}
					return false;
				}
			},
			{
				name:'height',
				handler: function (n){
					element = n;
					if(!$(element).data('mutate-height'))$(element).data('mutate-height', $(element).height());
					if ($(element).data('mutate-height')&&$(element).height() != $(element).data('mutate-height')  ) {
						$(element).data('mutate-height', $(element).height());
						return true;
					}
				}
			},
			{
				name		: 'top',
				handler 	: function (n){
					if(!$(n).data('mutate-top'))$(n).data('mutate-top', $(n).css('top'));
					
					if ($(n).data('mutate-top')&&$(n).css('top') != $(n).data('mutate-top')  ) {
						$(n).data('mutate-top', $(n).css('top'));
						return true;
					}
				}
			},
			{
				name		: 'bottom',
				handler 	: function (n){
					if(!$(n).data('mutate-bottom'))$(n).data('mutate-bottom', $(n).css('bottom'));
					
					if ($(n).data('mutate-bottom')&&$(n).css('bottom') != $(n).data('mutate-bottom')  ) {
						$(n).data('mutate-bottom', $(n).css('bottom'));
						return true;
					}
				}
			},
			{
				name		: 'right',
				handler 	: function (n){
					if(!$(n).data('mutate-right'))$(n).data('mutate-right', $(n).css('right'));
					
					if ($(n).data('mutate-right')&&$(n).css('right') != $(n).data('mutate-right')  ) {
						$(n).data('mutate-right', $(n).css('right'));
						return true;
					}
				}
			},
			{
				name		: 'left',
				handler 	: function (n){
					if(!$(n).data('mutate-left'))$(n).data('mutate-left', $(n).css('left'));
					
					if ($(n).data('mutate-left')&&$(n).css('left') != $(n).data('mutate-left')  ) {
						$(n).data('mutate-left', $(n).css('left'));
						return true;
					}
				}
			},
			{
				name		: 'hide',
				handler 	: function (n){ if ($(n).is(':hidden'))	return true; }
			},
			{
				name		: 'show',
				handler 	: function (n){ if ($(n).is(':visible'))	return true; }
			},
			{
				name		: 'scrollHeight',
				handler 	: function (n){
					if(!$(n).data('prev-scrollHeight'))$(n).data('prev-scrollHeight', $(n)[0].scrollHeight);
					
					if ($(n).data('prev-scrollHeight')&&$(n)[0].scrollHeight != $(n).data('prev-scrollHeight')  ) {
						$(n).data('prev-scrollHeight', $(n)[0].scrollHeight);
						return true;
					}
				}
			},
			{
				name		: 'scrollWidth',
				handler 	: function (n){
					if(!$(n).data('prev-scrollWidth'))$(n).data('prev-scrollWidth', $(n)[0].scrollWidth);
					
					if ($(n).data('prev-scrollWidth')&&$(n)[0].scrollWidth != $(n).data('prev-scrollWidth')  ) {
						$(n).data('prev-scrollWidth', $(n)[0].scrollWidth);
						return true;
					}
				}
			},
			{
				name		: 'scrollTop',
				handler 	: function (n){
					if(!$(n).data('prev-scrollTop'))$(n).data('prev-scrollTop', $(n)[0].scrollTop());
					
					if ($(n).data('prev-scrollTop')&&$(n)[0].scrollTop() != $(n).data('prev-scrollTop')  ) {
						$(n).data('prev-scrollTop', $(n)[0].scrollTop());
						return true;
					}
				}
			},
			{
				name		: 'scrollLeft',
				handler 	: function (n){
					if(!$(n).data('prev-scrollLeft'))$(n).data('prev-scrollLeft', $(n)[0].scrollLeft());
					
					if ($(n).data('prev-scrollLeft')&&$(n)[0].scrollLeft() != $(n).data('prev-scrollLeft')  ) {
						$(n).data('prev-scrollLeft', $(n)[0].scrollLeft());
						return true;
					}
				}
			}
		];
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\mutate.min.js
// version 2
;(function($){mutate={speed:1,event_stack:mutate_event_stack,stack:[],events:{},add_event:function(evt){mutate.events[evt.name]=evt.handler;},add:function(event_name,selector,callback,false_callback){mutate.stack[mutate.stack.length]={event_name:event_name,selector:selector,callback:callback,false_callback:false_callback}}};function reset(){var parent=mutate;if(parent.event_stack!='undefined'&&parent.event_stack.length){$.each(parent.event_stack,function(j,k){mutate.add_event(k);});}
parent.event_stack=[];$.each(parent.stack,function(i,n){$(n).each(function(a,b){if(parent.events[n.event_name](b)===true){if(n['callback'])n.callback(b,n);}else{if(n['false_callback'])n.false_callback(b,n)}})})
setTimeout(reset,mutate.speed);}
reset();$.fn.extend({mutate:function(){var event_name=false,callback=arguments[1],selector=this,false_callback=arguments[2]?arguments[2]:function(){};if(arguments[0].toLowerCase()=='extend'){mutate.add_event(callback);return this;}
$.each($.trim(arguments[0]).split(' '),function(i,n){event_name=n;mutate.add(event_name,selector,callback,false_callback);});return this;}});})(jQuery); 
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.touchSwipe.js
/*version2*/
/*
* @fileOverview TouchSwipe - jQuery Plugin
* @version 1.6.5 
*
* @author Matt Bryson http://www.github.com/mattbryson
* @see https://github.com/mattbryson/TouchSwipe-Jquery-Plugin
* @see http://labs.skinkers.com/touchSwipe/
* @see http://plugins.jquery.com/project/touchSwipe
*
* Copyright (c) 2010 Matt Bryson
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*
* Changelog
* $Date: 2010-12-12 (Wed, 12 Dec 2010) $
* $version: 1.0.0
* $version: 1.0.1 - removed multibyte comments
*
* $Date: 2011-21-02 (Mon, 21 Feb 2011) $
* $version: 1.1.0 	- added allowPageScroll property to allow swiping and scrolling of page
*					- changed handler signatures so one handler can be used for multiple events
* $Date: 2011-23-02 (Wed, 23 Feb 2011) $
* $version: 1.2.0 	- added click handler. This is fired if the user simply clicks and does not swipe. The event object and click target are passed to handler.
*					- If you use the http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ plugin, you can also assign jQuery mouse events to children of a touchSwipe object.
* $version: 1.2.1 	- removed console log!
*
* $version: 1.2.2 	- Fixed bug where scope was not preserved in callback methods.
*
* $Date: 2011-28-04 (Thurs, 28 April 2011) $
* $version: 1.2.4 	- Changed licence terms to be MIT or GPL inline with jQuery. Added check for support of touch events to stop non compatible browsers erroring.
*
* $Date: 2011-27-09 (Tues, 27 September 2011) $
* $version: 1.2.5 	- Added support for testing swipes with mouse on desktop browser (thanks to https://github.com/joelhy)
*
* $Date: 2012-14-05 (Mon, 14 May 2012) $
* $version: 1.2.6 	- Added timeThreshold between start and end touch, so user can ignore slow swipes (thanks to Mark Chase). Default is null, all swipes are detected
*
* $Date: 2012-05-06 (Tues, 05 June 2012) $
* $version: 1.2.7 	- Changed time threshold to have null default for backwards compatibility. Added duration param passed back in events, and refactored how time is handled.
*
* $Date: 2012-05-06 (Tues, 05 June 2012) $
* $version: 1.2.8 	- Added the possibility to return a value like null or false in the trigger callback. In that way we can control when the touch start/move should take effect or not (simply by returning in some cases return null; or return false;) This effects the ontouchstart/ontouchmove event.
*
* $Date: 2012-06-06 (Wed, 06 June 2012) $
* $version: 1.3.0 	- Refactored whole plugin to allow for methods to be executed, as well as exposed defaults for user override. Added 'enable', 'disable', and 'destroy' methods
*
* $Date: 2012-05-06 (Fri, 05 June 2012) $
* $version: 1.3.1 	- Bug fixes  - bind() with false as last argument is no longer supported in jQuery 1.6, also, if you just click, the duration is now returned correctly.
*
* $Date: 2012-29-07 (Sun, 29 July 2012) $
* $version: 1.3.2	- Added fallbackToMouseEvents option to NOT capture mouse events on non touch devices.
* 			- Added "all" fingers value to the fingers property, so any combination of fingers triggers the swipe, allowing event handlers to check the finger count
*
* $Date: 2012-09-08 (Thurs, 9 Aug 2012) $
* $version: 1.3.3	- Code tidy prep for minefied version
*
* $Date: 2012-04-10 (wed, 4 Oct 2012) $
* $version: 1.4.0	- Added pinch support, pinchIn and pinchOut
*
* $Date: 2012-11-10 (Thurs, 11 Oct 2012) $
* $version: 1.5.0	- Added excludedElements, a jquery selector that specifies child elements that do NOT trigger swipes. By default, this is one select that removes all form, input select, button and anchor elements.
*
* $Date: 2012-22-10 (Mon, 22 Oct 2012) $
* $version: 1.5.1	- Fixed bug with jQuery 1.8 and trailing comma in excludedElements
*					- Fixed bug with IE and eventPreventDefault()
* $Date: 2013-01-12 (Fri, 12 Jan 2013) $
* $version: 1.6.0	- Fixed bugs with pinching, mainly when both pinch and swipe enabled, as well as adding time threshold for multifinger gestures, so releasing one finger beofre the other doesnt trigger as single finger gesture.
*					- made the demo site all static local HTML pages so they can be run locally by a developer
*					- added jsDoc comments and added documentation for the plugin	
*					- code tidy
*					- added triggerOnTouchLeave property that will end the event when the user swipes off the element.
* $Date: 2013-03-23 (Sat, 23 Mar 2013) $
* $version: 1.6.1	- Added support for ie8 touch events
* $version: 1.6.2	- Added support for events binding with on / off / bind in jQ for all callback names.
*                   - Deprecated the 'click' handler in favour of tap.
*                   - added cancelThreshold property
*                   - added option method to update init options at runtime
*
* $version 1.6.3    - added doubletap, longtap events and longTapThreshold, doubleTapThreshold property
* $Date: 2013-04-04 (Thurs, 04 April 2013) $
* $version 1.6.4    - Fixed bug with cancelThreshold introduced in 1.6.3, where swipe status no longer fired start event, and stopped once swiping back.
*
* $Date: 2013-08-24 (Sat, 24 Aug 2013) $
* $version 1.6.5    - Merged a few pull requests fixing various bugs, added AMD support.

*/

/**
 * See (http://jquery.com/).
 * @name $
 * @class 
 * See the jQuery Library  (http://jquery.com/) for full details.  This just
 * documents the function and classes that are added to jQuery by this plug-in.
 */

/**
 * See (http://jquery.com/)
 * @name fn
 * @class 
 * See the jQuery Library  (http://jquery.com/) for full details.  This just
 * documents the function and classes that are added to jQuery by this plug-in.
 * @memberOf $
 */



(function (factory) {
    if (typeof define === 'function' && define.amd && define.amd.jQuery) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals.
        factory(jQuery);
    }
}(function ($) {
    "use strict";

    //Constants
    var LEFT = "left",
        RIGHT = "right",
        UP = "up",
        DOWN = "down",
        IN = "in",
        OUT = "out",

        NONE = "none",
        AUTO = "auto",

        SWIPE = "swipe",
        PINCH = "pinch",
        TAP = "tap",
        DOUBLE_TAP = "doubletap",
        LONG_TAP = "longtap",

        HORIZONTAL = "horizontal",
        VERTICAL = "vertical",

        ALL_FINGERS = "all",

        DOUBLE_TAP_THRESHOLD = 10,

        PHASE_START = "start",
        PHASE_MOVE = "move",
        PHASE_END = "end",
        PHASE_CANCEL = "cancel",

        SUPPORTS_TOUCH = 'ontouchstart' in window,

        PLUGIN_NS = 'TouchSwipe';



	/**
	* The default configuration, and available options to configure touch swipe with.
	* You can set the default values by updating any of the properties prior to instantiation.
	* @name $.fn.swipe.defaults
	* @namespace
	* @property {int} [fingers=1] The number of fingers to detect in a swipe. Any swipes that do not meet this requirement will NOT trigger swipe handlers.
	* @property {int} [threshold=75] The number of pixels that the user must move their finger by before it is considered a swipe. 
	* @property {int} [cancelThreshold=null] The number of pixels that the user must move their finger back from the original swipe direction to cancel the gesture.
	* @property {int} [pinchThreshold=20] The number of pixels that the user must pinch their finger by before it is considered a pinch. 
	* @property {int} [maxTimeThreshold=null] Time, in milliseconds, between touchStart and touchEnd must NOT exceed in order to be considered a swipe. 
	* @property {int} [fingerReleaseThreshold=250] Time in milliseconds between releasing multiple fingers.  If 2 fingers are down, and are released one after the other, if they are within this threshold, it counts as a simultaneous release. 
	* @property {int} [longTapThreshold=500] Time in milliseconds between tap and release for a long tap
    * @property {int} [doubleTapThreshold=200] Time in milliseconds between 2 taps to count as a double tap
	* @property {function} [swipe=null] A handler to catch all swipes. See {@link $.fn.swipe#event:swipe}
	* @property {function} [swipeLeft=null] A handler that is triggered for "left" swipes. See {@link $.fn.swipe#event:swipeLeft}
	* @property {function} [swipeRight=null] A handler that is triggered for "right" swipes. See {@link $.fn.swipe#event:swipeRight}
	* @property {function} [swipeUp=null] A handler that is triggered for "up" swipes. See {@link $.fn.swipe#event:swipeUp}
	* @property {function} [swipeDown=null] A handler that is triggered for "down" swipes. See {@link $.fn.swipe#event:swipeDown}
	* @property {function} [swipeStatus=null] A handler triggered for every phase of the swipe. See {@link $.fn.swipe#event:swipeStatus}
	* @property {function} [pinchIn=null] A handler triggered for pinch in events. See {@link $.fn.swipe#event:pinchIn}
	* @property {function} [pinchOut=null] A handler triggered for pinch out events. See {@link $.fn.swipe#event:pinchOut}
	* @property {function} [pinchStatus=null] A handler triggered for every phase of a pinch. See {@link $.fn.swipe#event:pinchStatus}
	* @property {function} [tap=null] A handler triggered when a user just taps on the item, rather than swipes it. If they do not move, tap is triggered, if they do move, it is not. 
	* @property {function} [doubleTap=null] A handler triggered when a user double taps on the item. The delay between taps can be set with the doubleTapThreshold property. See {@link $.fn.swipe.defaults#doubleTapThreshold}
	* @property {function} [longTap=null] A handler triggered when a user long taps on the item. The delay between start and end can be set with the longTapThreshold property. See {@link $.fn.swipe.defaults#doubleTapThreshold}
	* @property {boolean} [triggerOnTouchEnd=true] If true, the swipe events are triggered when the touch end event is received (user releases finger).  If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically. 
	* @property {boolean} [triggerOnTouchLeave=false] If true, then when the user leaves the swipe object, the swipe will end and trigger appropriate handlers. 
	* @property {string|undefined} [allowPageScroll='auto'] How the browser handles page scrolls when the user is swiping on a touchSwipe object. See {@link $.fn.swipe.pageScroll}.  <br/><br/>
										<code>"auto"</code> : all undefined swipes will cause the page to scroll in that direction. <br/>
										<code>"none"</code> : the page will not scroll when user swipes. <br/>
										<code>"horizontal"</code> : will force page to scroll on horizontal swipes. <br/>
										<code>"vertical"</code> : will force page to scroll on vertical swipes. <br/>
	* @property {boolean} [fallbackToMouseEvents=true] If true mouse events are used when run on a non touch device, false will stop swipes being triggered by mouse events on non tocuh devices. 
	* @property {string} [excludedElements="button, input, select, textarea, a, .noSwipe"] A jquery selector that specifies child elements that do NOT trigger swipes. By default this excludes all form, input, select, button, anchor and .noSwipe elements. 
	
	*/
    var defaults = {
        fingers: 1,
        threshold: 75,
        cancelThreshold: null,
        pinchThreshold: 20,
        maxTimeThreshold: null,
        fingerReleaseThreshold: 250,
        longTapThreshold: 500,
        doubleTapThreshold: 200,
        swipe: null,
        swipeLeft: null,
        swipeRight: null,
        swipeUp: null,
        swipeDown: null,
        swipeStatus: null,
        pinchIn: null,
        pinchOut: null,
        pinchStatus: null,
        click: null, //Deprecated since 1.6.2
        tap: null,
        doubleTap: null,
        longTap: null,
        triggerOnTouchEnd: true,
        triggerOnTouchLeave: false,
        allowPageScroll: "auto",
        fallbackToMouseEvents: true,
        excludedElements: "label, button, input, select, textarea, .noSwipe, object"
    };



	/**
	* Applies TouchSwipe behaviour to one or more jQuery objects.
	* The TouchSwipe plugin can be instantiated via this method, or methods within 
	* TouchSwipe can be executed via this method as per jQuery plugin architecture.
	* @see TouchSwipe
	* @class
	* @param {Mixed} method If the current DOMNode is a TouchSwipe object, and <code>method</code> is a TouchSwipe method, then
	* the <code>method</code> is executed, and any following arguments are passed to the TouchSwipe method.
	* If <code>method</code> is an object, then the TouchSwipe class is instantiated on the current DOMNode, passing the 
	* configuration properties defined in the object. See TouchSwipe
	*
	*/
    $.fn.swipe = function (method) {
        var $this = $(this),
            plugin = $this.data(PLUGIN_NS);

        //Check if we are already instantiated and trying to execute a method	
        if (plugin && typeof method === 'string') {
            if (plugin[method]) {
                return plugin[method].apply(this, Array.prototype.slice.call(arguments, 1));
            } else {
                $.error('Method ' + method + ' does not exist on jQuery.swipe');
            }
        }
        //Else not instantiated and trying to pass init object (or nothing)
        else if (!plugin && (typeof method === 'object' || !method)) {
            return init.apply(this, arguments);
        }

        return $this;
    };

    //Expose our defaults so a user could override the plugin defaults
    $.fn.swipe.defaults = defaults;

	/**
	* The phases that a touch event goes through.  The <code>phase</code> is passed to the event handlers. 
	* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
	* @namespace
	* @readonly
	* @property {string} PHASE_START Constant indicating the start phase of the touch event. Value is <code>"start"</code>.
	* @property {string} PHASE_MOVE Constant indicating the move phase of the touch event. Value is <code>"move"</code>.
	* @property {string} PHASE_END Constant indicating the end phase of the touch event. Value is <code>"end"</code>.
	* @property {string} PHASE_CANCEL Constant indicating the cancel phase of the touch event. Value is <code>"cancel"</code>.
	*/
    $.fn.swipe.phases = {
        PHASE_START: PHASE_START,
        PHASE_MOVE: PHASE_MOVE,
        PHASE_END: PHASE_END,
        PHASE_CANCEL: PHASE_CANCEL
    };

	/**
	* The direction constants that are passed to the event handlers. 
	* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
	* @namespace
	* @readonly
	* @property {string} LEFT Constant indicating the left direction. Value is <code>"left"</code>.
	* @property {string} RIGHT Constant indicating the right direction. Value is <code>"right"</code>.
	* @property {string} UP Constant indicating the up direction. Value is <code>"up"</code>.
	* @property {string} DOWN Constant indicating the down direction. Value is <code>"cancel"</code>.
	* @property {string} IN Constant indicating the in direction. Value is <code>"in"</code>.
	* @property {string} OUT Constant indicating the out direction. Value is <code>"out"</code>.
	*/
    $.fn.swipe.directions = {
        LEFT: LEFT,
        RIGHT: RIGHT,
        UP: UP,
        DOWN: DOWN,
        IN: IN,
        OUT: OUT
    };

	/**
	* The page scroll constants that can be used to set the value of <code>allowPageScroll</code> option
	* These properties are read only
	* @namespace
	* @readonly
	* @see $.fn.swipe.defaults#allowPageScroll
	* @property {string} NONE Constant indicating no page scrolling is allowed. Value is <code>"none"</code>.
	* @property {string} HORIZONTAL Constant indicating horizontal page scrolling is allowed. Value is <code>"horizontal"</code>.
	* @property {string} VERTICAL Constant indicating vertical page scrolling is allowed. Value is <code>"vertical"</code>.
	* @property {string} AUTO Constant indicating either horizontal or vertical will be allowed, depending on the swipe handlers registered. Value is <code>"auto"</code>.
	*/
    $.fn.swipe.pageScroll = {
        NONE: NONE,
        HORIZONTAL: HORIZONTAL,
        VERTICAL: VERTICAL,
        AUTO: AUTO
    };

	/**
	* Constants representing the number of fingers used in a swipe.  These are used to set both the value of <code>fingers</code> in the 
	* options object, as well as the value of the <code>fingers</code> event property.
	* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
	* @namespace
	* @readonly
	* @see $.fn.swipe.defaults#fingers
	* @property {string} ONE Constant indicating 1 finger is to be detected / was detected. Value is <code>1</code>.
	* @property {string} TWO Constant indicating 2 fingers are to be detected / were detected. Value is <code>1</code>.
	* @property {string} THREE Constant indicating 3 finger are to be detected / were detected. Value is <code>1</code>.
	* @property {string} ALL Constant indicating any combination of finger are to be detected.  Value is <code>"all"</code>.
	*/
    $.fn.swipe.fingers = {
        ONE: 1,
        TWO: 2,
        THREE: 3,
        ALL: ALL_FINGERS
    };

	/**
	* Initialise the plugin for each DOM element matched
	* This creates a new instance of the main TouchSwipe class for each DOM element, and then
	* saves a reference to that instance in the elements data property.
	* @internal
	*/
    function init(options) {
        //Prep and extend the options
        if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) {
            options.allowPageScroll = NONE;
        }

        //Check for deprecated options
        //Ensure that any old click handlers are assigned to the new tap, unless we have a tap
        if (options.click !== undefined && options.tap === undefined) {
            options.tap = options.click;
        }

        if (!options) {
            options = {};
        }

        //pass empty object so we dont modify the defaults
        options = $.extend({}, $.fn.swipe.defaults, options);

        //For each element instantiate the plugin
        return this.each(function () {
            var $this = $(this);

            //Check we havent already initialised the plugin
            var plugin = $this.data(PLUGIN_NS);

            if (!plugin) {
                plugin = new TouchSwipe(this, options);
                $this.data(PLUGIN_NS, plugin);
            }
        });
    }

	/**
	* Main TouchSwipe Plugin Class.
	* Do not use this to construct your TouchSwipe object, use the jQuery plugin method $.fn.swipe(); {@link $.fn.swipe}
	* @private
	* @name TouchSwipe
	* @param {DOMNode} element The HTML DOM object to apply to plugin to
	* @param {Object} options The options to configure the plugin with.  @link {$.fn.swipe.defaults}
	* @see $.fh.swipe.defaults
	* @see $.fh.swipe
    * @class
	*/
    function TouchSwipe(element, options) {
        var useTouchEvents = (SUPPORTS_TOUCH || !options.fallbackToMouseEvents),
            START_EV = useTouchEvents ? 'touchstart' : 'mousedown',
            MOVE_EV = useTouchEvents ? 'touchmove' : 'mousemove',
            END_EV = useTouchEvents ? 'touchend' : 'mouseup',
            LEAVE_EV = useTouchEvents ? null : 'mouseleave', //we manually detect leave on touch devices, so null event here
            CANCEL_EV = 'touchcancel';



        //touch properties
        var distance = 0,
            direction = null,
            duration = 0,
            startTouchesDistance = 0,
            endTouchesDistance = 0,
            pinchZoom = 1,
            pinchDistance = 0,
            pinchDirection = 0,
            maximumsMap = null;



        //jQuery wrapped element for this instance
        var $element = $(element);

        //Current phase of th touch cycle
        var phase = "start";

        // the current number of fingers being used.
        var fingerCount = 0;

        //track mouse points / delta
        var fingerData = null;

        //track times
        var startTime = 0,
            endTime = 0,
            previousTouchEndTime = 0,
            previousTouchFingerCount = 0,
            doubleTapStartTime = 0;

        //Timeouts
        var singleTapTimeout = null;

        // Add gestures to all swipable areas if supported
        try {
            $element.on(START_EV, touchStart);
            $element.on(CANCEL_EV, touchCancel);
        }
        catch (e) {
            $.error('events not supported ' + START_EV + ',' + CANCEL_EV + ' on jQuery.swipe');
        }

        //
        //Public methods
        //

		/**
		* re-enables the swipe plugin with the previous configuration
		* @function
		* @name $.fn.swipe#enable
		* @return {DOMNode} The Dom element that was registered with TouchSwipe 
		* @example $("#element").swipe("enable");
		*/
        this.enable = function () {
            $element.on(START_EV, touchStart);
            $element.on(CANCEL_EV, touchCancel);
            return $element;
        };

		/**
		* disables the swipe plugin
		* @function
		* @name $.fn.swipe#disable
		* @return {DOMNode} The Dom element that is now registered with TouchSwipe
	    * @example $("#element").swipe("disable");
		*/
        this.disable = function () {
            removeListeners();
            return $element;
        };

		/**
		* Destroy the swipe plugin completely. To use any swipe methods, you must re initialise the plugin.
		* @function
		* @name $.fn.swipe#destroy
		* @return {DOMNode} The Dom element that was registered with TouchSwipe 
		* @example $("#element").swipe("destroy");
		*/
        this.destroy = function () {
            removeListeners();
            $element.data(PLUGIN_NS, null);
            return $element;
        };


        /**
         * Allows run time updating of the swipe configuration options.
         * @function
    	 * @name $.fn.swipe#option
    	 * @param {String} property The option property to get or set
         * @param {Object} [value] The value to set the property to
		 * @return {Object} If only a property name is passed, then that property value is returned.
		 * @example $("#element").swipe("option", "threshold"); // return the threshold
         * @example $("#element").swipe("option", "threshold", 100); // set the threshold after init
         * @see $.fn.swipe.defaults
         *
         */
        this.option = function (property, value) {
            if (options[property] !== undefined) {
                if (value === undefined) {
                    return options[property];
                } else {
                    options[property] = value;
                }
            } else {
                $.error('Option ' + property + ' does not exist on jQuery.swipe.options');
            }

            return null;
        }

        //
        // Private methods
        //

        //
        // EVENTS
        //
		/**
		* Event handler for a touch start event.
		* Stops the default click event from triggering and stores where we touched
		* @inner
		* @param {object} jqEvent The normalised jQuery event object.
		*/
        function touchStart(jqEvent) {
            //If we already in a touch event (a finger already in use) then ignore subsequent ones..
            if (getTouchInProgress())
                return;

            //Check if this element matches any in the excluded elements selectors,  or its parent is excluded, if so, DON'T swipe
            if ($(jqEvent.target).closest(options.excludedElements, $element).length > 0)
                return;

            //As we use Jquery bind for events, we need to target the original event object
            //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
            var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;

            var ret,
                evt = SUPPORTS_TOUCH ? event.touches[0] : event;

            phase = PHASE_START;

            //If we support touches, get the finger count
            if (SUPPORTS_TOUCH) {
                // get the total number of fingers touching the screen
                fingerCount = event.touches.length;
            }
            //Else this is the desktop, so stop the browser from dragging the image
            else {
                jqEvent.preventDefault(); //call this on jq event so we are cross browser
            }

            //clear vars..
            distance = 0;
            direction = null;
            pinchDirection = null;
            duration = 0;
            startTouchesDistance = 0;
            endTouchesDistance = 0;
            pinchZoom = 1;
            pinchDistance = 0;
            fingerData = createAllFingerData();
            maximumsMap = createMaximumsData();
            cancelMultiFingerRelease();


            // check the number of fingers is what we are looking for, or we are capturing pinches
            if (!SUPPORTS_TOUCH || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) {
                // get the coordinates of the touch
                createFingerData(0, evt);
                startTime = getTimeStamp();

                if (fingerCount == 2) {
                    //Keep track of the initial pinch distance, so we can calculate the diff later
                    //Store second finger data as start
                    createFingerData(1, event.touches[1]);
                    startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
                }

                if (options.swipeStatus || options.pinchStatus) {
                    ret = triggerHandler(event, phase);
                }
            }
            else {
                //A touch with more or less than the fingers we are looking for, so cancel
                ret = false;
            }

            //If we have a return value from the users handler, then return and cancel
            if (ret === false) {
                phase = PHASE_CANCEL;
                triggerHandler(event, phase);
                return ret;
            }
            else {
                setTouchInProgress(true);
            }

            return null;
        };



		/**
		* Event handler for a touch move event. 
		* If we change fingers during move, then cancel the event
		* @inner
		* @param {object} jqEvent The normalised jQuery event object.
		*/
        function touchMove(jqEvent) {

            //As we use Jquery bind for events, we need to target the original event object
            //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
            var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;

            //If we are ending, cancelling, or within the threshold of 2 fingers being released, don't track anything..
            if (phase === PHASE_END || phase === PHASE_CANCEL || inMultiFingerRelease())
                return;

            var ret,
                evt = SUPPORTS_TOUCH ? event.touches[0] : event;


            //Update the  finger data 
            var currentFinger = updateFingerData(evt);
            endTime = getTimeStamp();

            if (SUPPORTS_TOUCH) {
                fingerCount = event.touches.length;
            }

            phase = PHASE_MOVE;

            //If we have 2 fingers get Touches distance as well
            if (fingerCount == 2) {

                //Keep track of the initial pinch distance, so we can calculate the diff later
                //We do this here as well as the start event, in case they start with 1 finger, and the press 2 fingers
                if (startTouchesDistance == 0) {
                    //Create second finger if this is the first time...
                    createFingerData(1, event.touches[1]);

                    startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
                } else {
                    //Else just update the second finger
                    updateFingerData(event.touches[1]);

                    endTouchesDistance = calculateTouchesDistance(fingerData[0].end, fingerData[1].end);
                    pinchDirection = calculatePinchDirection(fingerData[0].end, fingerData[1].end);
                }


                pinchZoom = calculatePinchZoom(startTouchesDistance, endTouchesDistance);
                pinchDistance = Math.abs(startTouchesDistance - endTouchesDistance);
            }


            if ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH || hasPinches()) {

                direction = calculateDirection(currentFinger.start, currentFinger.end);

                //Check if we need to prevent default event (page scroll / pinch zoom) or not
                validateDefaultEvent(jqEvent, direction);

                //Distance and duration are all off the main finger
                distance = calculateDistance(currentFinger.start, currentFinger.end);
                duration = calculateDuration();

                //Cache the maximum distance we made in this direction
                setMaxDistance(direction, distance);


                if (options.swipeStatus || options.pinchStatus) {
                    ret = triggerHandler(event, phase);
                }


                //If we trigger end events when threshold are met, or trigger events when touch leaves element
                if (!options.triggerOnTouchEnd || options.triggerOnTouchLeave) {

                    var inBounds = true;

                    //If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit)
                    if (options.triggerOnTouchLeave) {
                        var bounds = getbounds(this);
                        inBounds = isInBounds(currentFinger.end, bounds);
                    }

                    //Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these..
                    if (!options.triggerOnTouchEnd && inBounds) {
                        phase = getNextPhase(PHASE_MOVE);
                    }
                    //We end if out of bounds here, so set current phase to END, and check if its modified 
                    else if (options.triggerOnTouchLeave && !inBounds) {
                        phase = getNextPhase(PHASE_END);
                    }

                    if (phase == PHASE_CANCEL || phase == PHASE_END) {
                        triggerHandler(event, phase);
                    }
                }
            }
            else {
                phase = PHASE_CANCEL;
                triggerHandler(event, phase);
            }

            if (ret === false) {
                phase = PHASE_CANCEL;
                triggerHandler(event, phase);
            }
        }



		/**
		* Event handler for a touch end event. 
		* Calculate the direction and trigger events
		* @inner
		* @param {object} jqEvent The normalised jQuery event object.
		*/
        function touchEnd(jqEvent) {
            //As we use Jquery bind for events, we need to target the original event object
            var event = jqEvent.originalEvent;


            //If we are still in a touch with another finger return
            //This allows us to wait a fraction and see if the other finger comes up, if it does within the threshold, then we treat it as a multi release, not a single release.
            if (SUPPORTS_TOUCH) {
                if (event.touches.length > 0) {
                    startMultiFingerRelease();
                    return true;
                }
            }

            //If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release.
            //This is used to allow 2 fingers to release fractionally after each other, whilst maintainig the event as containg 2 fingers, not 1
            if (inMultiFingerRelease()) {
                fingerCount = previousTouchFingerCount;
            }

            //call this on jq event so we are cross browser 
            jqEvent.preventDefault();

            //Set end of swipe
            endTime = getTimeStamp();

            //Get duration incase move was never fired
            duration = calculateDuration();

            //If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase
            if (didSwipeBackToCancel()) {
                phase = PHASE_CANCEL;
                triggerHandler(event, phase);
            } else if (options.triggerOnTouchEnd || (options.triggerOnTouchEnd == false && phase === PHASE_MOVE)) {
                phase = PHASE_END;
                triggerHandler(event, phase);
            }
            //Special cases - A tap should always fire on touch end regardless,
            //So here we manually trigger the tap end handler by itself
            //We dont run trigger handler as it will re-trigger events that may have fired already
            else if (!options.triggerOnTouchEnd && hasTap()) {
                //Trigger the pinch events...
                phase = PHASE_END;
                triggerHandlerForGesture(event, phase, TAP);
            }
            else if (phase === PHASE_MOVE) {
                phase = PHASE_CANCEL;
                triggerHandler(event, phase);
            }

            setTouchInProgress(false);

            return null;
        }



		/**
		* Event handler for a touch cancel event. 
		* Clears current vars
		* @inner
		*/
        function touchCancel() {
            // reset the variables back to default values
            fingerCount = 0;
            endTime = 0;
            startTime = 0;
            startTouchesDistance = 0;
            endTouchesDistance = 0;
            pinchZoom = 1;

            //If we were in progress of tracking a possible multi touch end, then re set it.
            cancelMultiFingerRelease();

            setTouchInProgress(false);
        }


		/**
		* Event handler for a touch leave event. 
		* This is only triggered on desktops, in touch we work this out manually
		* as the touchleave event is not supported in webkit
		* @inner
		*/
        function touchLeave(jqEvent) {
            var event = jqEvent.originalEvent;

            //If we have the trigger on leave property set....
            if (options.triggerOnTouchLeave) {
                phase = getNextPhase(PHASE_END);
                triggerHandler(event, phase);
            }
        }

		/**
		* Removes all listeners that were associated with the plugin
		* @inner
		*/
        function removeListeners() {
            $element.off(START_EV, touchStart);
            $element.off(CANCEL_EV, touchCancel);
            $element.off(MOVE_EV, touchMove);
            $element.off(END_EV, touchEnd);

            //we only have leave events on desktop, we manually calculate leave on touch as its not supported in webkit
            if (LEAVE_EV) {
                $element.off(LEAVE_EV, touchLeave);
            }

            setTouchInProgress(false);
        }


		/**
		 * Checks if the time and distance thresholds have been met, and if so then the appropriate handlers are fired.
		 */
        function getNextPhase(currentPhase) {

            var nextPhase = currentPhase;

            // Ensure we have valid swipe (under time and over distance  and check if we are out of bound...)
            var validTime = validateSwipeTime();
            var validDistance = validateSwipeDistance();
            var didCancel = didSwipeBackToCancel();

            //If we have exceeded our time, then cancel	
            if (!validTime || didCancel) {
                nextPhase = PHASE_CANCEL;
            }
            //Else if we are moving, and have reached distance then end
            else if (validDistance && currentPhase == PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave)) {
                nextPhase = PHASE_END;
            }
            //Else if we have ended by leaving and didn't reach distance, then cancel
            else if (!validDistance && currentPhase == PHASE_END && options.triggerOnTouchLeave) {
                nextPhase = PHASE_CANCEL;
            }

            return nextPhase;
        }


		/**
		* Trigger the relevant event handler
		* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
		* @param {object} event the original event object
		* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
		* @inner
		*/
        function triggerHandler(event, phase) {

            var ret = undefined;

            // SWIPE GESTURES
            if (didSwipe() || hasSwipes()) { //hasSwipes as status needs to fire even if swipe is invalid
                //Trigger the swipe events...
                ret = triggerHandlerForGesture(event, phase, SWIPE);
            }

            // PINCH GESTURES (if the above didn't cancel)
            else if ((didPinch() || hasPinches()) && ret !== false) {
                //Trigger the pinch events...
                ret = triggerHandlerForGesture(event, phase, PINCH);
            }

            // CLICK / TAP (if the above didn't cancel)
            if (didDoubleTap() && ret !== false) {
                //Trigger the tap events...
                ret = triggerHandlerForGesture(event, phase, DOUBLE_TAP);
            }

            // CLICK / TAP (if the above didn't cancel)
            else if (didLongTap() && ret !== false) {
                //Trigger the tap events...
                ret = triggerHandlerForGesture(event, phase, LONG_TAP);
            }

            // CLICK / TAP (if the above didn't cancel)
            else if (didTap() && ret !== false) {
                //Trigger the tap event..
                ret = triggerHandlerForGesture(event, phase, TAP);
            }



            // If we are cancelling the gesture, then manually trigger the reset handler
            if (phase === PHASE_CANCEL) {
                touchCancel(event);
            }

            // If we are ending the gesture, then manually trigger the reset handler IF all fingers are off
            if (phase === PHASE_END) {
                //If we support touch, then check that all fingers are off before we cancel
                if (SUPPORTS_TOUCH) {
                    if (event.touches.length == 0) {
                        touchCancel(event);
                    }
                }
                else {
                    touchCancel(event);
                }
            }

            return ret;
        }



		/**
		* Trigger the relevant event handler
		* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
		* @param {object} event the original event object
		* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
		* @param {string} gesture the gesture to trigger a handler for : PINCH or SWIPE {@link $.fn.swipe.gestures}
		* @return Boolean False, to indicate that the event should stop propagation, or void.
		* @inner
		*/
        function triggerHandlerForGesture(event, phase, gesture) {

            var ret = undefined;

            //SWIPES....
            if (gesture == SWIPE) {
                //Trigger status every time..

                //Trigger the event...
                $element.trigger('swipeStatus', [phase, direction || null, distance || 0, duration || 0, fingerCount]);

                //Fire the callback
                if (options.swipeStatus) {
                    ret = options.swipeStatus.call($element, event, phase, direction || null, distance || 0, duration || 0, fingerCount);
                    //If the status cancels, then dont run the subsequent event handlers..
                    if (ret === false) return false;
                }




                if (phase == PHASE_END && validateSwipe()) {
                    //Fire the catch all event
                    $element.trigger('swipe', [direction, distance, duration, fingerCount]);

                    //Fire catch all callback
                    if (options.swipe) {
                        ret = options.swipe.call($element, event, direction, distance, duration, fingerCount);
                        //If the status cancels, then dont run the subsequent event handlers..
                        if (ret === false) return false;
                    }

                    //trigger direction specific event handlers	
                    switch (direction) {
                        case LEFT:
                            //Trigger the event
                            $element.trigger('swipeLeft', [direction, distance, duration, fingerCount]);

                            //Fire the callback
                            if (options.swipeLeft) {
                                ret = options.swipeLeft.call($element, event, direction, distance, duration, fingerCount);
                            }
                            break;

                        case RIGHT:
                            //Trigger the event
                            $element.trigger('swipeRight', [direction, distance, duration, fingerCount]);

                            //Fire the callback
                            if (options.swipeRight) {
                                ret = options.swipeRight.call($element, event, direction, distance, duration, fingerCount);
                            }
                            break;

                        case UP:
                            //Trigger the event
                            $element.trigger('swipeUp', [direction, distance, duration, fingerCount]);

                            //Fire the callback
                            if (options.swipeUp) {
                                ret = options.swipeUp.call($element, event, direction, distance, duration, fingerCount);
                            }
                            break;

                        case DOWN:
                            //Trigger the event
                            $element.trigger('swipeDown', [direction, distance, duration, fingerCount]);

                            //Fire the callback
                            if (options.swipeDown) {
                                ret = options.swipeDown.call($element, event, direction, distance, duration, fingerCount);
                            }
                            break;
                    }
                }
            }


            //PINCHES....
            if (gesture == PINCH) {
                //Trigger the event
                $element.trigger('pinchStatus', [phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom]);

                //Fire the callback
                if (options.pinchStatus) {
                    ret = options.pinchStatus.call($element, event, phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom);
                    //If the status cancels, then dont run the subsequent event handlers..
                    if (ret === false) return false;
                }

                if (phase == PHASE_END && validatePinch()) {

                    switch (pinchDirection) {
                        case IN:
                            //Trigger the event
                            $element.trigger('pinchIn', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom]);

                            //Fire the callback
                            if (options.pinchIn) {
                                ret = options.pinchIn.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom);
                            }
                            break;

                        case OUT:
                            //Trigger the event
                            $element.trigger('pinchOut', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom]);

                            //Fire the callback
                            if (options.pinchOut) {
                                ret = options.pinchOut.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom);
                            }
                            break;
                    }
                }
            }





            if (gesture == TAP) {
                if (phase === PHASE_CANCEL || phase === PHASE_END) {


                    //Cancel any existing double tap
                    clearTimeout(singleTapTimeout);

                    //If we are also looking for doubelTaps, wait incase this is one...
                    if (hasDoubleTap() && !inDoubleTap()) {
                        //Cache the time of this tap
                        doubleTapStartTime = getTimeStamp();

                        //Now wait for the double tap timeout, and trigger this single tap
                        //if its not cancelled by a double tap
                        singleTapTimeout = setTimeout($.proxy(function () {
                            doubleTapStartTime = null;
                            //Trigger the event
                            $element.trigger('tap', [event.target]);


                            //Fire the callback
                            if (options.tap) {
                                ret = options.tap.call($element, event, event.target);
                            }
                        }, this), options.doubleTapThreshold);

                    } else {
                        doubleTapStartTime = null;

                        //Trigger the event
                        $element.trigger('tap', [event.target]);


                        //Fire the callback
                        if (options.tap) {
                            ret = options.tap.call($element, event, event.target);
                        }
                    }
                }
            }

            else if (gesture == DOUBLE_TAP) {
                if (phase === PHASE_CANCEL || phase === PHASE_END) {
                    //Cancel any pending singletap 
                    clearTimeout(singleTapTimeout);
                    doubleTapStartTime = null;

                    //Trigger the event
                    $element.trigger('doubletap', [event.target]);

                    //Fire the callback
                    if (options.doubleTap) {
                        ret = options.doubleTap.call($element, event, event.target);
                    }
                }
            }

            else if (gesture == LONG_TAP) {
                if (phase === PHASE_CANCEL || phase === PHASE_END) {
                    //Cancel any pending singletap (shouldnt be one)
                    clearTimeout(singleTapTimeout);
                    doubleTapStartTime = null;

                    //Trigger the event
                    $element.trigger('longtap', [event.target]);

                    //Fire the callback
                    if (options.longTap) {
                        ret = options.longTap.call($element, event, event.target);
                    }
                }
            }

            return ret;
        }




        //
        // GESTURE VALIDATION
        //

		/**
		* Checks the user has swipe far enough
		* @return Boolean if <code>threshold</code> has been set, return true if the threshold was met, else false.
		* If no threshold was set, then we return true.
		* @inner
		*/
        function validateSwipeDistance() {
            var valid = true;
            //If we made it past the min swipe distance..
            if (options.threshold !== null) {
                valid = distance >= options.threshold;
            }

            return valid;
        }

		/**
		* Checks the user has swiped back to cancel.
		* @return Boolean if <code>cancelThreshold</code> has been set, return true if the cancelThreshold was met, else false.
		* If no cancelThreshold was set, then we return true.
		* @inner
		*/
        function didSwipeBackToCancel() {
            var cancelled = false;
            if (options.cancelThreshold !== null && direction !== null) {
                cancelled = (getMaxDistance(direction) - distance) >= options.cancelThreshold;
            }

            return cancelled;
        }

		/**
		* Checks the user has pinched far enough
		* @return Boolean if <code>pinchThreshold</code> has been set, return true if the threshold was met, else false.
		* If no threshold was set, then we return true.
		* @inner
		*/
        function validatePinchDistance() {
            if (options.pinchThreshold !== null) {
                return pinchDistance >= options.pinchThreshold;
            }
            return true;
        }

		/**
		* Checks that the time taken to swipe meets the minimum / maximum requirements
		* @return Boolean
		* @inner
		*/
        function validateSwipeTime() {
            var result;
            //If no time set, then return true

            if (options.maxTimeThreshold) {
                if (duration >= options.maxTimeThreshold) {
                    result = false;
                } else {
                    result = true;
                }
            }
            else {
                result = true;
            }

            return result;
        }


		/**
		* Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
		* This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
		* @param {object} jqEvent The normalised jQuery representation of the event object.
		* @param {string} direction The direction of the event. See {@link $.fn.swipe.directions}
		* @see $.fn.swipe.directions
		* @inner
		*/
        function validateDefaultEvent(jqEvent, direction) {
            if (options.allowPageScroll === NONE || hasPinches()) {
                jqEvent.preventDefault();
            } else {
                var auto = options.allowPageScroll === AUTO;

                switch (direction) {
                    case LEFT:
                        if ((options.swipeLeft && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
                            jqEvent.preventDefault();
                        }
                        break;

                    case RIGHT:
                        if ((options.swipeRight && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
                            jqEvent.preventDefault();
                        }
                        break;

                    case UP:
                        if ((options.swipeUp && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
                            jqEvent.preventDefault();
                        }
                        break;

                    case DOWN:
                        if ((options.swipeDown && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
                            jqEvent.preventDefault();
                        }
                        break;
                }
            }

        }


        // PINCHES
		/**
		 * Returns true of the current pinch meets the thresholds
		 * @return Boolean
		 * @inner
		*/
        function validatePinch() {
            var hasCorrectFingerCount = validateFingers();
            var hasEndPoint = validateEndPoint();
            var hasCorrectDistance = validatePinchDistance();
            return hasCorrectFingerCount && hasEndPoint && hasCorrectDistance;

        }

		/**
		 * Returns true if any Pinch events have been registered
		 * @return Boolean
		 * @inner
		*/
        function hasPinches() {
            //Enure we dont return 0 or null for false values
            return !!(options.pinchStatus || options.pinchIn || options.pinchOut);
        }

		/**
		 * Returns true if we are detecting pinches, and have one
		 * @return Boolean
		 * @inner
		 */
        function didPinch() {
            //Enure we dont return 0 or null for false values
            return !!(validatePinch() && hasPinches());
        }




        // SWIPES
		/**
		 * Returns true if the current swipe meets the thresholds
		 * @return Boolean
		 * @inner
		*/
        function validateSwipe() {
            //Check validity of swipe
            var hasValidTime = validateSwipeTime();
            var hasValidDistance = validateSwipeDistance();
            var hasCorrectFingerCount = validateFingers();
            var hasEndPoint = validateEndPoint();
            var didCancel = didSwipeBackToCancel();

            // if the user swiped more than the minimum length, perform the appropriate action
            // hasValidDistance is null when no distance is set 
            var valid = !didCancel && hasEndPoint && hasCorrectFingerCount && hasValidDistance && hasValidTime;

            return valid;
        }

		/**
		 * Returns true if any Swipe events have been registered
		 * @return Boolean
		 * @inner
		*/
        function hasSwipes() {
            //Enure we dont return 0 or null for false values
            return !!(options.swipe || options.swipeStatus || options.swipeLeft || options.swipeRight || options.swipeUp || options.swipeDown);
        }


		/**
		 * Returns true if we are detecting swipes and have one
		 * @return Boolean
		 * @inner
		*/
        function didSwipe() {
            //Enure we dont return 0 or null for false values
            return !!(validateSwipe() && hasSwipes());
        }

        /**
		 * Returns true if we have matched the number of fingers we are looking for
		 * @return Boolean
		 * @inner
		*/
        function validateFingers() {
            //The number of fingers we want were matched, or on desktop we ignore
            return ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH);
        }

        /**
		 * Returns true if we have an end point for the swipe
		 * @return Boolean
		 * @inner
		*/
        function validateEndPoint() {
            //We have an end value for the finger
            return fingerData[0].end.x !== 0;
        }

        // TAP / CLICK
		/**
		 * Returns true if a click / tap events have been registered
		 * @return Boolean
		 * @inner
		*/
        function hasTap() {
            //Enure we dont return 0 or null for false values
            return !!(options.tap);
        }

		/**
		 * Returns true if a double tap events have been registered
		 * @return Boolean
		 * @inner
		*/
        function hasDoubleTap() {
            //Enure we dont return 0 or null for false values
            return !!(options.doubleTap);
        }

		/**
		 * Returns true if any long tap events have been registered
		 * @return Boolean
		 * @inner
		*/
        function hasLongTap() {
            //Enure we dont return 0 or null for false values
            return !!(options.longTap);
        }

		/**
		 * Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
		 * @return Boolean
		 * @inner
		*/
        function validateDoubleTap() {
            if (doubleTapStartTime == null) {
                return false;
            }
            var now = getTimeStamp();
            return (hasDoubleTap() && ((now - doubleTapStartTime) <= options.doubleTapThreshold));
        }

		/**
		 * Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
		 * @return Boolean
		 * @inner
		*/
        function inDoubleTap() {
            return validateDoubleTap();
        }


		/**
		 * Returns true if we have a valid tap
		 * @return Boolean
		 * @inner
		*/
        function validateTap() {
            return ((fingerCount === 1 || !SUPPORTS_TOUCH) && (isNaN(distance) || distance === 0));
        }

		/**
		 * Returns true if we have a valid long tap
		 * @return Boolean
		 * @inner
		*/
        function validateLongTap() {
            //slight threshold on moving finger
            return ((duration > options.longTapThreshold) && (distance < DOUBLE_TAP_THRESHOLD));
        }

		/**
		 * Returns true if we are detecting taps and have one
		 * @return Boolean
		 * @inner
		*/
        function didTap() {
            //Enure we dont return 0 or null for false values
            return !!(validateTap() && hasTap());
        }


		/**
		 * Returns true if we are detecting double taps and have one
		 * @return Boolean
		 * @inner
		*/
        function didDoubleTap() {
            //Enure we dont return 0 or null for false values
            return !!(validateDoubleTap() && hasDoubleTap());
        }

		/**
		 * Returns true if we are detecting long taps and have one
		 * @return Boolean
		 * @inner
		*/
        function didLongTap() {
            //Enure we dont return 0 or null for false values
            return !!(validateLongTap() && hasLongTap());
        }




        // MULTI FINGER TOUCH
		/**
		 * Starts tracking the time between 2 finger releases, and keeps track of how many fingers we initially had up
		 * @inner
		*/
        function startMultiFingerRelease() {
            previousTouchEndTime = getTimeStamp();
            previousTouchFingerCount = event.touches.length + 1;
        }

		/**
		 * Cancels the tracking of time between 2 finger releases, and resets counters
		 * @inner
		*/
        function cancelMultiFingerRelease() {
            previousTouchEndTime = 0;
            previousTouchFingerCount = 0;
        }

		/**
		 * Checks if we are in the threshold between 2 fingers being released 
		 * @return Boolean
		 * @inner
		*/
        function inMultiFingerRelease() {

            var withinThreshold = false;

            if (previousTouchEndTime) {
                var diff = getTimeStamp() - previousTouchEndTime
                if (diff <= options.fingerReleaseThreshold) {
                    withinThreshold = true;
                }
            }

            return withinThreshold;
        }


		/**
		* gets a data flag to indicate that a touch is in progress
		* @return Boolean
		* @inner
		*/
        function getTouchInProgress() {
            //strict equality to ensure only true and false are returned
            return !!($element.data(PLUGIN_NS + '_intouch') === true);
        }

		/**
		* Sets a data flag to indicate that a touch is in progress
		* @param {boolean} val The value to set the property to
		* @inner
		*/
        function setTouchInProgress(val) {

            //Add or remove event listeners depending on touch status
            if (val === true) {
                $element.on(MOVE_EV, touchMove);
                $element.on(END_EV, touchEnd);

                //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
                if (LEAVE_EV) {
                    $element.on(LEAVE_EV, touchLeave);
                }
            } else {
                $element.off(MOVE_EV, touchMove, false);
                $element.off(END_EV, touchEnd, false);

                //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
                if (LEAVE_EV) {
                    $element.off(LEAVE_EV, touchLeave, false);
                }
            }


            //strict equality to ensure only true and false can update the value
            $element.data(PLUGIN_NS + '_intouch', val === true);
        }


		/**
		 * Creates the finger data for the touch/finger in the event object.
		 * @param {int} index The index in the array to store the finger data (usually the order the fingers were pressed)
		 * @param {object} evt The event object containing finger data
		 * @return finger data object
		 * @inner
		*/
        function createFingerData(index, evt) {
            var id = evt.identifier !== undefined ? evt.identifier : 0;

            fingerData[index].identifier = id;
            fingerData[index].start.x = fingerData[index].end.x = evt.pageX || evt.clientX;
            fingerData[index].start.y = fingerData[index].end.y = evt.pageY || evt.clientY;

            return fingerData[index];
        }

		/**
		 * Updates the finger data for a particular event object
		 * @param {object} evt The event object containing the touch/finger data to upadte
		 * @return a finger data object.
		 * @inner
		*/
        function updateFingerData(evt) {

            var id = evt.identifier !== undefined ? evt.identifier : 0;
            var f = getFingerData(id);

            f.end.x = evt.pageX || evt.clientX;
            f.end.y = evt.pageY || evt.clientY;

            return f;
        }

		/**
		 * Returns a finger data object by its event ID.
		 * Each touch event has an identifier property, which is used 
		 * to track repeat touches
		 * @param {int} id The unique id of the finger in the sequence of touch events.
		 * @return a finger data object.
		 * @inner
		*/
        function getFingerData(id) {
            for (var i = 0; i < fingerData.length; i++) {
                if (fingerData[i].identifier == id) {
                    return fingerData[i];
                }
            }
        }

		/**
		 * Creats all the finger onjects and returns an array of finger data
		 * @return Array of finger objects
		 * @inner
		*/
        function createAllFingerData() {
            var fingerData = [];
            for (var i = 0; i <= 5; i++) {
                fingerData.push({
                    start: { x: 0, y: 0 },
                    end: { x: 0, y: 0 },
                    identifier: 0
                });
            }

            return fingerData;
        }

		/**
		 * Sets the maximum distance swiped in the given direction. 
		 * If the new value is lower than the current value, the max value is not changed.
		 * @param {string}  direction The direction of the swipe
		 * @param {int}  distance The distance of the swipe
		 * @inner
		*/
        function setMaxDistance(direction, distance) {
            distance = Math.max(distance, getMaxDistance(direction));
            maximumsMap[direction].distance = distance;
        }

        /**
		 * gets the maximum distance swiped in the given direction. 
		 * @param {string}  direction The direction of the swipe
		 * @return int  The distance of the swipe
		 * @inner
		*/
        function getMaxDistance(direction) {
            if (maximumsMap[direction]) return maximumsMap[direction].distance;
            return undefined;
        }

		/**
		 * Creats a map of directions to maximum swiped values.
		 * @return Object A dictionary of maximum values, indexed by direction.
		 * @inner
		*/
        function createMaximumsData() {
            var maxData = {};
            maxData[LEFT] = createMaximumVO(LEFT);
            maxData[RIGHT] = createMaximumVO(RIGHT);
            maxData[UP] = createMaximumVO(UP);
            maxData[DOWN] = createMaximumVO(DOWN);

            return maxData;
        }

		/**
		 * Creates a map maximum swiped values for a given swipe direction
		 * @param {string} The direction that these values will be associated with
		 * @return Object Maximum values
		 * @inner
		*/
        function createMaximumVO(dir) {
            return {
                direction: dir,
                distance: 0
            }
        }


        //
        // MATHS / UTILS
        //

		/**
		* Calculate the duration of the swipe
		* @return int
		* @inner
		*/
        function calculateDuration() {
            return endTime - startTime;
        }

		/**
		* Calculate the distance between 2 touches (pinch)
		* @param {point} startPoint A point object containing x and y co-ordinates
	    * @param {point} endPoint A point object containing x and y co-ordinates
	    * @return int;
		* @inner
		*/
        function calculateTouchesDistance(startPoint, endPoint) {
            var diffX = Math.abs(startPoint.x - endPoint.x);
            var diffY = Math.abs(startPoint.y - endPoint.y);

            return Math.round(Math.sqrt(diffX * diffX + diffY * diffY));
        }

		/**
		* Calculate the zoom factor between the start and end distances
		* @param {int} startDistance Distance (between 2 fingers) the user started pinching at
	    * @param {int} endDistance Distance (between 2 fingers) the user ended pinching at
	    * @return float The zoom value from 0 to 1.
		* @inner
		*/
        function calculatePinchZoom(startDistance, endDistance) {
            var percent = (endDistance / startDistance) * 1;
            return percent.toFixed(2);
        }


		/**
		* Returns the pinch direction, either IN or OUT for the given points
		* @return string Either {@link $.fn.swipe.directions.IN} or {@link $.fn.swipe.directions.OUT}
		* @see $.fn.swipe.directions
		* @inner
		*/
        function calculatePinchDirection() {
            if (pinchZoom < 1) {
                return OUT;
            }
            else {
                return IN;
            }
        }


		/**
		* Calculate the length / distance of the swipe
		* @param {point} startPoint A point object containing x and y co-ordinates
	    * @param {point} endPoint A point object containing x and y co-ordinates
	    * @return int
		* @inner
		*/
        function calculateDistance(startPoint, endPoint) {
            return Math.round(Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2)));
        }

		/**
		* Calculate the angle of the swipe
		* @param {point} startPoint A point object containing x and y co-ordinates
	    * @param {point} endPoint A point object containing x and y co-ordinates
	    * @return int
		* @inner
		*/
        function calculateAngle(startPoint, endPoint) {
            var x = startPoint.x - endPoint.x;
            var y = endPoint.y - startPoint.y;
            var r = Math.atan2(y, x); //radians
            var angle = Math.round(r * 180 / Math.PI); //degrees

            //ensure value is positive
            if (angle < 0) {
                angle = 360 - Math.abs(angle);
            }

            return angle;
        }

		/**
		* Calculate the direction of the swipe
		* This will also call calculateAngle to get the latest angle of swipe
		* @param {point} startPoint A point object containing x and y co-ordinates
	    * @param {point} endPoint A point object containing x and y co-ordinates
	    * @return string Either {@link $.fn.swipe.directions.LEFT} / {@link $.fn.swipe.directions.RIGHT} / {@link $.fn.swipe.directions.DOWN} / {@link $.fn.swipe.directions.UP}
		* @see $.fn.swipe.directions
		* @inner
		*/
        function calculateDirection(startPoint, endPoint) {
            var angle = calculateAngle(startPoint, endPoint);

            if ((angle <= 45) && (angle >= 0)) {
                return LEFT;
            } else if ((angle <= 360) && (angle >= 315)) {
                return LEFT;
            } else if ((angle >= 135) && (angle <= 225)) {
                return RIGHT;
            } else if ((angle > 45) && (angle < 135)) {
                return DOWN;
            } else {
                return UP;
            }
        }


		/**
		* Returns a MS time stamp of the current time
		* @return int
		* @inner
		*/
        function getTimeStamp() {
            var now = new Date();
            return now.getTime();
        }



		/**
		 * Returns a bounds object with left, right, top and bottom properties for the element specified.
		 * @param {DomNode} The DOM node to get the bounds for.
		 */
        function getbounds(el) {
            el = $(el);
            var offset = el.offset();

            var bounds = {
                left: offset.left,
                right: offset.left + el.outerWidth(),
                top: offset.top,
                bottom: offset.top + el.outerHeight()
            }

            return bounds;
        }


		/**
		 * Checks if the point object is in the bounds object.
		 * @param {object} point A point object.
		 * @param {int} point.x The x value of the point.
		 * @param {int} point.y The x value of the point.
		 * @param {object} bounds The bounds object to test
		 * @param {int} bounds.left The leftmost value
		 * @param {int} bounds.right The righttmost value
		 * @param {int} bounds.top The topmost value
		* @param {int} bounds.bottom The bottommost value
		 */
        function isInBounds(point, bounds) {
            return (point.x > bounds.left && point.x < bounds.right && point.y > bounds.top && point.y < bounds.bottom);
        };


    }




    /**
     * A catch all handler that is triggered for all swipe directions. 
     * @name $.fn.swipe#swipe
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user swiped
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     */




    /**
     * A handler that is triggered for "left" swipes.
     * @name $.fn.swipe#swipeLeft
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user swiped
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     */

    /**
     * A handler that is triggered for "right" swipes.
     * @name $.fn.swipe#swipeRight
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user swiped
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     */

    /**
     * A handler that is triggered for "up" swipes.
     * @name $.fn.swipe#swipeUp
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user swiped
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     */

    /**
     * A handler that is triggered for "down" swipes.
     * @name $.fn.swipe#swipeDown
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user swiped
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     */

    /**
     * A handler triggered for every phase of the swipe. This handler is constantly fired for the duration of the pinch.
     * This is triggered regardless of swipe thresholds.
     * @name $.fn.swipe#swipeStatus
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {string} phase The phase of the swipe event. See {@link $.fn.swipe.phases}
     * @param {string} direction The direction the user swiped in. This is null if the user has yet to move. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user swiped. This is 0 if the user has yet to move.
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     */

    /**
     * A handler triggered for pinch in events.
     * @name $.fn.swipe#pinchIn
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user pinched
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     * @param {int} zoom The zoom/scale level the user pinched too, 0-1.
     */

    /**
     * A handler triggered for pinch out events.
     * @name $.fn.swipe#pinchOut
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user pinched
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     * @param {int} zoom The zoom/scale level the user pinched too, 0-1.
     */

    /**
     * A handler triggered for all pinch events. This handler is constantly fired for the duration of the pinch. This is triggered regardless of thresholds.
     * @name $.fn.swipe#pinchStatus
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
     * @param {int} distance The distance the user pinched
     * @param {int} duration The duration of the swipe in milliseconds
     * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
     * @param {int} zoom The zoom/scale level the user pinched too, 0-1.
     */

    /**
     * A click handler triggered when a user simply clicks, rather than swipes on an element.
     * This is deprecated since version 1.6.2, any assignment to click will be assigned to the tap handler.
     * You cannot use <code>on</code> to bind to this event as the default jQ <code>click</code> event will be triggered.
     * Use the <code>tap</code> event instead.
     * @name $.fn.swipe#click
     * @event
     * @deprecated since version 1.6.2, please use {@link $.fn.swipe#tap} instead 
     * @default null
     * @param {EventObject} event The original event object
     * @param {DomObject} target The element clicked on.
     */

    /**
    * A click / tap handler triggered when a user simply clicks or taps, rather than swipes on an element.
    * @name $.fn.swipe#tap
    * @event
    * @default null
    * @param {EventObject} event The original event object
    * @param {DomObject} target The element clicked on.
    */

    /**
     * A double tap handler triggered when a user double clicks or taps on an element.
     * You can set the time delay for a double tap with the {@link $.fn.swipe.defaults#doubleTapThreshold} property. 
     * Note: If you set both <code>doubleTap</code> and <code>tap</code> handlers, the <code>tap</code> event will be delayed by the <code>doubleTapThreshold</code>
     * as the script needs to check if its a double tap.
     * @name $.fn.swipe#doubleTap
     * @see  $.fn.swipe.defaults#doubleTapThreshold
     * @event
     * @default null
     * @param {EventObject} event The original event object
     * @param {DomObject} target The element clicked on.
     */

    /**
    * A long tap handler triggered when a user long clicks or taps on an element.
    * You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property. 
    * @name $.fn.swipe#longTap
    * @see  $.fn.swipe.defaults#longTapThreshold
    * @event
    * @default null
    * @param {EventObject} event The original event object
    * @param {DomObject} target The element clicked on.
    */

}));
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.datetimepicker.js
/*version 2*/
/**
 * @preserve jQuery DateTimePicker plugin v2.4.1
 * @homepage http://dtp.net/jqplugins/datetimepicker/
 * (c) 2014, Chupurnov Valeriy.
 */
/*global document,window,jQuery,setTimeout,clearTimeout*/

//JQuery v3.0 Compatible

(function ($) {
    'use strict';
    var default_options = {
        i18n: {
            ar: { // Arabic
                months: [
					"كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"
                ],
                dayOfWeek: [
					"ن", "ث", "ع", "خ", "ج", "س", "ح"
                ]
            },
            ro: { // Romanian
                months: [
					"ianuarie", "februarie", "martie", "aprilie", "mai", "iunie", "iulie", "august", "septembrie", "octombrie", "noiembrie", "decembrie"
                ],
                dayOfWeek: [
					"l", "ma", "mi", "j", "v", "s", "d"
                ]
            },
            id: { // Indonesian
                months: [
					"Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
                ],
                dayOfWeek: [
					"Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Min"
                ]
            },
            bg: { // Bulgarian
                months: [
					"Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
                ],
                dayOfWeek: [
					"Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
                ]
            },
            fa: { // Persian/Farsi
                months: [
					'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
                ],
                dayOfWeek: [
					'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
                ]
            },
            ru: { // Russian
                months: [
					'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
                ],
                dayOfWeek: [
					"Вск", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
                ]
            },
            uk: { // Ukrainian
                months: [
					'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'
                ],
                dayOfWeek: [
					"Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт"
                ]
            },
            en: { // English
                months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
                ],
                dayOfWeek: [
					"S", "M", "T", "W", "T", "F", "S"
                ]
            },
            el: { // Ελληνικά
                months: [
					"Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
                ],
                dayOfWeek: [
					"Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
                ]
            },
            de: { // German
                months: [
					'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
                ],
                dayOfWeek: [
					"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
                ]
            },
            nl: { // Dutch
                months: [
					"januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
                ],
                dayOfWeek: [
					"zo", "ma", "di", "wo", "do", "vr", "za"
                ]
            },
            tr: { // Turkish
                months: [
					"Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
                ],
                dayOfWeek: [
					"Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
                ]
            },
            fr: { //French
                months: [
					"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
                ],
                dayOfWeek: [
					"Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
                ]
            },
            es: { // Spanish
                months: [
					"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
                ],
                dayOfWeek: [
					"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
                ]
            },
            th: { // Thai
                months: [
					'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
                ],
                dayOfWeek: [
					'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'
                ]
            },
            pl: { // Polish
                months: [
					"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
                ],
                dayOfWeek: [
					"nd", "pn", "wt", "śr", "cz", "pt", "sb"
                ]
            },
            pt: { // Portuguese
                months: [
					"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
                ],
                dayOfWeek: [
					"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
                ]
            },
            ch: { // Simplified Chinese
                months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
                ],
                dayOfWeek: [
					"日", "一", "二", "三", "四", "五", "六"
                ]
            },
            cn: { // Simplified Chinese
                months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
                ],
                dayOfWeek: [
					"日", "一", "二", "三", "四", "五", "六"
                ]
            },
            se: { // Swedish
                months: [
					"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
                ],
                dayOfWeek: [
					"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
                ]
            },
            kr: { // Korean
                months: [
					"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
                ],
                dayOfWeek: [
					"일", "월", "화", "수", "목", "금", "토"
                ]
            },
            it: { // Italian
                months: [
					"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
                ],
                dayOfWeek: [
					"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
                ]
            },
            da: { // Dansk
                months: [
					"January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December"
                ],
                dayOfWeek: [
					"Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
                ]
            },
            no: { // Norwegian
                months: [
					"Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"
                ],
                dayOfWeek: [
					"Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
                ]
            },
            ja: { // Japanese
                months: [
					"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
                ],
                dayOfWeek: [
					"日", "月", "火", "水", "木", "金", "土"
                ]
            },
            vi: { // Vietnamese
                months: [
					"Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
                ],
                dayOfWeek: [
					"CN", "T2", "T3", "T4", "T5", "T6", "T7"
                ]
            },
            sl: { // Slovenščina
                months: [
					"Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
                ],
                dayOfWeek: [
					"Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
                ]
            },
            cs: { // Čeština
                months: [
					"Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
                ],
                dayOfWeek: [
					"Ne", "Po", "Út", "St", "Čt", "Pá", "So"
                ]
            },
            hu: { // Hungarian
                months: [
					"Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
                ],
                dayOfWeek: [
					"Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"
                ]
            },
            az: { //Azerbaijanian (Azeri)
                months: [
					"Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"
                ],
                dayOfWeek: [
					"B", "Be", "Ça", "Ç", "Ca", "C", "Ş"
                ]
            },
            bs: { //Bosanski
                months: [
					"Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
                ],
                dayOfWeek: [
					"Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
                ]
            },
            ca: { //Català
                months: [
					"Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"
                ],
                dayOfWeek: [
					"Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"
                ]
            },
            'en-GB': { //English (British)
                months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
                ],
                dayOfWeek: [
					"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
                ]
            },
            et: { //"Eesti"
                months: [
					"Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"
                ],
                dayOfWeek: [
					"P", "E", "T", "K", "N", "R", "L"
                ]
            },
            eu: { //Euskara
                months: [
					"Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"
                ],
                dayOfWeek: [
					"Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."
                ]
            },
            fi: { //Finnish (Suomi)
                months: [
					"Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"
                ],
                dayOfWeek: [
					"Su", "Ma", "Ti", "Ke", "To", "Pe", "La"
                ]
            },
            gl: { //Galego
                months: [
					"Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"
                ],
                dayOfWeek: [
					"Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"
                ]
            },
            hr: { //Hrvatski
                months: [
					"Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"
                ],
                dayOfWeek: [
					"Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
                ]
            },
            ko: { //Korean (한국어)
                months: [
					"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
                ],
                dayOfWeek: [
					"일", "월", "화", "수", "목", "금", "토"
                ]
            },
            lt: { //Lithuanian (lietuvių)
                months: [
					"Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"
                ],
                dayOfWeek: [
					"Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"
                ]
            },
            lv: { //Latvian (Latviešu)
                months: [
					"Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"
                ],
                dayOfWeek: [
					"Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"
                ]
            },
            mk: { //Macedonian (Македонски)
                months: [
					"јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"
                ],
                dayOfWeek: [
					"нед", "пон", "вто", "сре", "чет", "пет", "саб"
                ]
            },
            mn: { //Mongolian (Монгол)
                months: [
					"1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"
                ],
                dayOfWeek: [
					"Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"
                ]
            },
            'pt-BR': { //Português(Brasil)
                months: [
					"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
                ],
                dayOfWeek: [
					"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"
                ]
            },
            sk: { //Slovenčina
                months: [
					"Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
                ],
                dayOfWeek: [
					"Ne", "Po", "Ut", "St", "Št", "Pi", "So"
                ]
            },
            sq: { //Albanian (Shqip)
                months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
                ],
                dayOfWeek: [
					"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
                ]
            },
            'sr-YU': { //Serbian (Srpski)
                months: [
					"Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
                ],
                dayOfWeek: [
					"Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"
                ]
            },
            sr: { //Serbian Cyrillic (Српски)
                months: [
					"јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"
                ],
                dayOfWeek: [
					"нед", "пон", "уто", "сре", "чет", "пет", "суб"
                ]
            },
            sv: { //Svenska
                months: [
					"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
                ],
                dayOfWeek: [
					"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
                ]
            },
            'zh-TW': { //Traditional Chinese (繁體中文)
                months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
                ],
                dayOfWeek: [
					"日", "一", "二", "三", "四", "五", "六"
                ]
            },
            zh: { //Simplified Chinese (简体中文)
                months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
                ],
                dayOfWeek: [
					"日", "一", "二", "三", "四", "五", "六"
                ]
            },
            he: { //Hebrew (עברית)
                months: [
					'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
                ],
                dayOfWeek: [
					'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'
                ]
            }
        },
        value: '',
        lang: 'en',

        format: 'Y/m/d H:i',
        formatTime: 'H:i',
        formatDate: 'Y/m/d',

        startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
        step: 60,
        monthChangeSpinner: true,

        closeOnDateSelect: false,
        closeOnWithoutClick: true,
        closeOnInputClick: true,

        timepicker: true,
        datepicker: true,
        weeks: false,

        defaultTime: false,	// use formatTime format (ex. '10:00' for formatTime:	'H:i')
        defaultDate: false,	// use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05')

        minDate: false,
        maxDate: false,
        minTime: false,
        maxTime: false,

        allowTimes: [],
        opened: false,
        initTime: true,
        inline: false,
        theme: '',

        onSelectDate: function () { },
        onSelectTime: function () { },
        onChangeMonth: function () { },
        onChangeYear: function () { },
        onChangeDateTime: function () { },
        onShow: function () { },
        onClose: function () { },
        onGenerate: function () { },

        withoutCopyright: true,
        inverseButton: false,
        hours12: false,
        next: 'dtp_next',
        prev: 'dtp_prev',
        dayOfWeekStart: 0,
        parentID: 'body',
        timeHeightInTimePicker: 25,
        timepickerScrollbar: true,
        todayButton: true,
        defaultSelect: true,

        scrollMonth: true,
        scrollTime: true,
        scrollInput: true,

        lazyInit: false,
        mask: false,
        validateOnBlur: false,
        allowBlank: true,
        yearStart: 1950,
        yearEnd: 2050,
        style: '',
        id: '',
        fixed: false,
        roundTime: 'round', // ceil, floor
        className: '',
        weekends: [],
        disabledDates: [],
        yearOffset: 0,
        beforeShowDay: null,

        enterLikeTab: true
    };
    // fix for ie8
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (obj, start) {
            var i, j;
            for (i = (start || 0), j = this.length; i < j; i += 1) {
                if (this[i] === obj) { return i; }
            }
            return -1;
        };
    }
    Date.prototype.countDaysInMonth = function () {
        return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
    };
    $.fn.dtpScroller = function (percent) {
        return this.each(function () {
            var timeboxparent = $(this),
				pointerEventToXY = function (e) {
				    var out = { x: 0, y: 0 },
						touch;
				    if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
				        touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
				        out.x = touch.clientX;
				        out.y = touch.clientY;
				    } else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
				        out.x = e.clientX;
				        out.y = e.clientY;
				    }
				    return out;
				},
				move = 0,
				timebox,
				parentHeight,
				height,
				scrollbar,
				scroller,
				maximumOffset = 100,
				start = false,
				startY = 0,
				startTop = 0,
				h1 = 0,
				touchStart = false,
				startTopScroll = 0,
				calcOffset = function () { };
            if (percent === 'hide') {
                timeboxparent.find('.dtp_scrollbar').hide();
                return;
            }
            if (!$(this).hasClass('dtp_scroller_box')) {
                timebox = timeboxparent.children().eq(0);
                parentHeight = timeboxparent[0].clientHeight;
                height = timebox[0].offsetHeight;
                scrollbar = $('<div class="dtp_scrollbar"></div>');
                scroller = $('<div class="dtp_scroller"></div>');
                scrollbar.append(scroller);

                timeboxparent.addClass('dtp_scroller_box').append(scrollbar);
                calcOffset = function calcOffset(event) {
                    var offset = pointerEventToXY(event).y - startY + startTopScroll;
                    if (offset < 0) {
                        offset = 0;
                    }
                    if (offset + scroller[0].offsetHeight > h1) {
                        offset = h1 - scroller[0].offsetHeight;
                    }
                    timeboxparent.trigger('scroll_element.dtp_scroller', [maximumOffset ? offset / maximumOffset : 0]);
                };

                scroller
					.on('touchstart.dtp_scroller mousedown.dtp_scroller', function (event) {
					    if (!parentHeight) {
					        timeboxparent.trigger('resize_scroll.dtp_scroller', [percent]);
					    }

					    startY = pointerEventToXY(event).y;
					    startTopScroll = parseInt(scroller.css('margin-top'), 10);
					    h1 = scrollbar[0].offsetHeight;

					    if (event.type === 'mousedown') {
					        if (document) {
					            $(document.body).addClass('dtp_noselect');
					        }
					        $([document.body, window]).on('mouseup.dtp_scroller', function arguments_callee() {
					            $([document.body, window]).off('mouseup.dtp_scroller', arguments_callee)
									.off('mousemove.dtp_scroller', calcOffset)
									.removeClass('dtp_noselect');
					        });
					        $(document.body).on('mousemove.dtp_scroller', calcOffset);
					    } else {
					        touchStart = true;
					        event.stopPropagation();
					        event.preventDefault();
					    }
					})
					.on('touchmove', function (event) {
					    if (touchStart) {
					        event.preventDefault();
					        calcOffset(event);
					    }
					})
					.on('touchend touchcancel', function (event) {
					    touchStart = false;
					    startTopScroll = 0;
					});

                timeboxparent
					.on('scroll_element.dtp_scroller', function (event, percentage) {
					    if (!parentHeight) {
					        timeboxparent.trigger('resize_scroll.dtp_scroller', [percentage, true]);
					    }
					    percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage;

					    scroller.css('margin-top', maximumOffset * percentage);

					    setTimeout(function () {
					        timebox.css('marginTop', -parseInt((timebox[0].offsetHeight - parentHeight) * percentage, 10));
					    }, 10);
					})
					.on('resize_scroll.dtp_scroller', function (event, percentage, noTriggerScroll) {
					    var percent, sh;
					    parentHeight = timeboxparent[0].clientHeight;
					    height = timebox[0].offsetHeight;
					    percent = parentHeight / height;
					    sh = percent * scrollbar[0].offsetHeight;
					    if (percent > 1) {
					        scroller.hide();
					    } else {
					        scroller.show();
					        scroller.css('height', parseInt(sh > 10 ? sh : 10, 10));
					        maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight;
					        if (noTriggerScroll !== true) {
					            timeboxparent.trigger('scroll_element.dtp_scroller', [percentage || Math.abs(parseInt(timebox.css('marginTop'), 10)) / (height - parentHeight)]);
					        }
					    }
					});

                timeboxparent.on('mousewheel', function (event) {
                    var top = Math.abs(parseInt(timebox.css('marginTop'), 10));

                    top = top - (event.deltaY * 20);
                    if (top < 0) {
                        top = 0;
                    }

                    timeboxparent.trigger('scroll_element.dtp_scroller', [top / (height - parentHeight)]);
                    event.stopPropagation();
                    return false;
                });

                timeboxparent.on('touchstart', function (event) {
                    start = pointerEventToXY(event);
                    startTop = Math.abs(parseInt(timebox.css('marginTop'), 10));
                });

                timeboxparent.on('touchmove', function (event) {
                    if (start) {
                        event.preventDefault();
                        var coord = pointerEventToXY(event);
                        timeboxparent.trigger('scroll_element.dtp_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]);
                    }
                });

                timeboxparent.on('touchend touchcancel', function (event) {
                    start = false;
                    startTop = 0;
                });
            }
            timeboxparent.trigger('resize_scroll.dtp_scroller', [percent]);
        });
    };

    $.fn.datetimepicker = function (opt) {
        var KEY0 = 48,
			KEY9 = 57,
			_KEY0 = 96,
			_KEY9 = 105,
			CTRLKEY = 17,
			DEL = 46,
			ENTER = 13,
			ESC = 27,
			BACKSPACE = 8,
			ARROWLEFT = 37,
			ARROWUP = 38,
			ARROWRIGHT = 39,
			ARROWDOWN = 40,
			TAB = 9,
			F5 = 116,
			AKEY = 65,
			CKEY = 67,
			VKEY = 86,
			ZKEY = 90,
			YKEY = 89,
			ctrlDown = false,
			options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options),

			lazyInitTimer = 0,
			createDateTimePicker,
			destroyDateTimePicker,

			lazyInit = function (input) {
			    input
					.on('open.dtp focusin.dtp mousedown.dtp', function initOnActionCallback(event) {
					    if (input.is(':disabled') || input.data('dtp_datetimepicker')) {
					        return;
					    }
					    clearTimeout(lazyInitTimer);
					    lazyInitTimer = setTimeout(function () {

					        if (!input.data('dtp_datetimepicker')) {
					            createDateTimePicker(input);
					        }
					        input
								.off('open.dtp focusin.dtp mousedown.dtp', initOnActionCallback)
								.trigger('open.dtp');
					    }, 100);
					});
			};

        createDateTimePicker = function (input) {
            var datetimepicker = $('<div ' + (options.id ? 'id="' + options.id + '"' : '') + ' ' + (options.style ? 'style="' + options.style + '"' : '') + ' class="dtp_datetimepicker dtp_' + options.theme + ' dtp_noselect ' + (options.weeks ? ' dtp_showweeks' : '') + options.className + '"></div>'),
				dtp_copyright = $('<div class="dtp_copyright"><a target="_blank" href="http://dtp.net/jqplugins/datetimepicker/">dtp.net</a></div>'),
				datepicker = $('<div class="dtp_datepicker active"></div>'),
				mounth_picker = $('<div class="dtp_mounthpicker"><button type="button" class="dtp_prev acn-icon icon-calendar-arrow-lt"></button><button type="button" class="dtp_today_button"></button>' +
					'<div class="dtp_label dtp_month"><span></span><i></i></div>' +
					'<div class="dtp_label dtp_year"><span></span><i></i></div>' +
					'<button type="button" class="dtp_next acn-icon icon-calendar-arrow-rt"></button></div>'),
				calendar = $('<div class="dtp_calendar"></div>'),
				timepicker = $('<div class="dtp_timepicker active"><button type="button" class="dtp_prev"></button><div class="dtp_time_box"></div><button type="button" class="dtp_next"></button></div>'),
				timeboxparent = timepicker.find('.dtp_time_box').eq(0),
				timebox = $('<div class="dtp_time_variant"></div>'),
				/*scrollbar = $('<div class="dtp_scrollbar"></div>'),
				scroller = $('<div class="dtp_scroller"></div>'),*/
				monthselect = $('<div class="dtp_select dtp_monthselect"><div></div></div>'),
				yearselect = $('<div class="dtp_select dtp_yearselect"><div></div></div>'),
				triggerAfterOpen = false,
				dtp_datetime,
				//scroll_element,
				xchangeTimer,
				timerclick,
				current_time_index,
				setPos,
				timer = 0,
				timer1 = 0,
				_dtp_datetime;

            mounth_picker
				.find('.dtp_month span')
					.after(monthselect);
            mounth_picker
				.find('.dtp_year span')
					.after(yearselect);

            mounth_picker
				.find('.dtp_month,.dtp_year')
					.on('mousedown.dtp', function (event) {
					    var select = $(this).find('.dtp_select').eq(0),
                            val = 0,
                            top = 0,
                            visible = select.is(':visible'),
                            items,
                            i;

					    mounth_picker
                            .find('.dtp_select')
                                .hide();
					    if (_dtp_datetime.currentTime) {
					        val = _dtp_datetime.currentTime[$(this).hasClass('dtp_month') ? 'getMonth' : 'getFullYear']();
					    }

					    select[visible ? 'hide' : 'show']();
					    for (items = select.find('div.dtp_option'), i = 0; i < items.length; i += 1) {
					        if (items.eq(i).data('value') === val) {
					            break;
					        } else {
					            top += items[0].offsetHeight;
					        }
					    }

					    select.dtpScroller(top / (select.children()[0].offsetHeight - (select[0].clientHeight)));
					    event.stopPropagation();
					    return false;
					});

            mounth_picker
				.find('.dtp_select')
					.dtpScroller()
				.on('mousedown.dtp', function (event) {
				    event.stopPropagation();
				    event.preventDefault();
				})
				.on('mousedown.dtp', '.dtp_option', function (event) {
				    var year = _dtp_datetime.currentTime.getFullYear();
				    if (_dtp_datetime && _dtp_datetime.currentTime) {
				        _dtp_datetime.currentTime[$(this).parent().parent().hasClass('dtp_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value'));
				    }

				    $(this).parent().parent().hide();

				    datetimepicker.trigger('xchange.dtp');
				    if (options.onChangeMonth && typeof options.onChangeMonth === "function") {
				        options.onChangeMonth.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'));
				    }

				    if (year !== _dtp_datetime.currentTime.getFullYear() && typeof options.onChangeYear === "function") {
				        options.onChangeYear.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'));
				    }
				});

            datetimepicker.setOptions = function (_options) {
                options = $.extend(true, {}, options, _options);

                if (_options.allowTimes && Array.isArray(_options.allowTimes) && _options.allowTimes.length) {
                    options.allowTimes = $.extend(true, [], _options.allowTimes);
                }

                if (_options.weekends && Array.isArray(_options.weekends) && _options.weekends.length) {
                    options.weekends = $.extend(true, [], _options.weekends);
                }

                if (_options.disabledDates && Array.isArray(_options.disabledDates) && _options.disabledDates.length) {
                    options.disabledDates = $.extend(true, [], _options.disabledDates);
                }

                if ((options.open || options.opened) && (!options.inline)) {
                    input.trigger('open.dtp');
                }

                if (options.inline) {
                    triggerAfterOpen = true;
                    datetimepicker.addClass('dtp_inline');
                    input.after(datetimepicker).hide();
                }

                if (options.inverseButton) {
                    options.next = 'dtp_prev';
                    options.prev = 'dtp_next';
                }

                if (options.datepicker) {
                    datepicker.addClass('active');
                } else {
                    datepicker.removeClass('active');
                }

                if (options.timepicker) {
                    timepicker.addClass('active');
                } else {
                    timepicker.removeClass('active');
                }

                if (options.value) {
                    if (input && input.val) {
                        input.val(options.value);
                    }
                    _dtp_datetime.setCurrentTime(options.value);
                }

                if (isNaN(options.dayOfWeekStart)) {
                    options.dayOfWeekStart = 0;
                } else {
                    options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7;
                }

                if (!options.timepickerScrollbar) {
                    timeboxparent.dtpScroller('hide');
                }

                if (options.minDate && /^-(.*)$/.test(options.minDate)) {
                    options.minDate = _dtp_datetime.strToDateTime(options.minDate).dateFormat(options.formatDate);
                }

                if (options.maxDate && /^\+(.*)$/.test(options.maxDate)) {
                    options.maxDate = _dtp_datetime.strToDateTime(options.maxDate).dateFormat(options.formatDate);
                }

                mounth_picker
					.find('.dtp_today_button')
						.css('visibility', !options.todayButton ? 'hidden' : 'visible');

                if (options.mask) {
                    var e,
						getCaretPos = function (input) {
						    try {
						        if (document.selection && document.selection.createRange) {
						            var range = document.selection.createRange();
						            return range.getBookmark().charCodeAt(2) - 2;
						        }
						        if (input.setSelectionRange) {
						            return input.selectionStart;
						        }
						    } catch (e) {
						        return 0;
						    }
						},
						setCaretPos = function (node, pos) {
						    node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node;
						    if (!node) {
						        return false;
						    }
						    if (node.createTextRange) {
						        var textRange = node.createTextRange();
						        textRange.collapse(true);
						        textRange.moveEnd('character', pos);
						        textRange.moveStart('character', pos);
						        textRange.trigger("select");
						        return true;
						    }
						    if (node.setSelectionRange) {
						        node.setSelectionRange(pos, pos);
						        return true;
						    }
						    return false;
						},
						isValidValue = function (mask, value) {
						    var reg = mask
								.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1')
								.replace(/_/g, '{digit+}')
								.replace(/([0-9]{1})/g, '{digit$1}')
								.replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}')
								.replace(/\{digit[\+]\}/g, '[0-9_]{1}');
						    return (new RegExp(reg)).test(value);
						};
                    input.off('keydown.dtp');

                    if (options.mask === true) {
                        options.mask = options.format
							.replace(/Y/g, '9999')
							.replace(/F/g, '9999')
							.replace(/m/g, '19')
							.replace(/d/g, '39')
							.replace(/H/g, '29')
							.replace(/i/g, '59')
							.replace(/s/g, '59');
                    }

                    if (typeof options.mask === 'string') {
                        if (!isValidValue(options.mask, input.val())) {
                            input.val(options.mask.replace(/[0-9]/g, '_'));
                        }

                        input.on('keydown.dtp', function (event) {
                            var val = this.value,
								key = event.which,
								pos,
								digit;

                            if (((key >= KEY0 && key <= KEY9) || (key >= _KEY0 && key <= _KEY9)) || (key === BACKSPACE || key === DEL)) {
                                pos = getCaretPos(this);
                                digit = (key !== BACKSPACE && key !== DEL) ? String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key) : '_';

                                if ((key === BACKSPACE || key === DEL) && pos) {
                                    pos -= 1;
                                    digit = '_';
                                }

                                while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
                                    pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
                                }

                                val = val.substr(0, pos) + digit + val.substr(pos + 1);
                                if ($.trim(val) === '') {
                                    val = options.mask.replace(/[0-9]/g, '_');
                                } else {
                                    if (pos === options.mask.length) {
                                        event.preventDefault();
                                        return false;
                                    }
                                }

                                pos += (key === BACKSPACE || key === DEL) ? 0 : 1;
                                while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
                                    pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
                                }

                                if (isValidValue(options.mask, val)) {
                                    this.value = val;
                                    setCaretPos(this, pos);
                                } else if ($.trim(val) === '') {
                                    this.value = options.mask.replace(/[0-9]/g, '_');
                                } else {
                                    input.trigger('error_input.dtp');
                                }
                            } else {
                                if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) {
                                    return true;
                                }
                            }

                            event.preventDefault();
                            return false;
                        });
                    }
                }
                if (options.validateOnBlur) {
                    input
						.off('blur.dtp')
						.on('blur.dtp', function () {
						    if (options.allowBlank && !$.trim($(this).val()).length) {
						        $(this).val(null);
						        datetimepicker.data('dtp_datetime').empty();
						    } else if (!Date.parseDate($(this).val(), options.format)) {
						        $(this).val((_dtp_datetime.now()).dateFormat(options.format));
						        datetimepicker.data('dtp_datetime').setCurrentTime($(this).val());
						    } else {
						        datetimepicker.data('dtp_datetime').setCurrentTime($(this).val());
						    }
						    datetimepicker.trigger('changedatetime.dtp');
						});
                }
                options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1;

                datetimepicker
					.trigger('xchange.dtp')
					.trigger('afterOpen.dtp');
            };

            datetimepicker
				.data('options', options)
				.on('mousedown.dtp', function (event) {
				    event.stopPropagation();
				    event.preventDefault();
				    yearselect.hide();
				    monthselect.hide();
				    return false;
				});

            //scroll_element = timepicker.find('.dtp_time_box');
            timeboxparent.append(timebox);
            timeboxparent.dtpScroller();

            datetimepicker.on('afterOpen.dtp', function () {
                timeboxparent.dtpScroller();
            });

            datetimepicker
				.append(datepicker)
				.append(timepicker);

            if (options.withoutCopyright !== true) {
                datetimepicker
					.append(dtp_copyright);
            }

            datepicker
				.append(mounth_picker)
				.append(calendar);

            $(options.parentID)
				.append(datetimepicker);

            dtp_datetime = function () {
                var _this = this;
                _this.now = function (norecursion) {
                    var d = new Date(),
						date,
						time;

                    if (!norecursion && options.defaultDate) {
                        date = _this.strToDate(options.defaultDate);
                        d.setFullYear(date.getFullYear());
                        d.setMonth(date.getMonth());
                        d.setDate(date.getDate());
                    }

                    if (options.yearOffset) {
                        d.setFullYear(d.getFullYear() + options.yearOffset);
                    }

                    if (!norecursion && options.defaultTime) {
                        time = _this.strtotime(options.defaultTime);
                        d.setHours(time.getHours());
                        d.setMinutes(time.getMinutes());
                    }

                    return d;
                };

                _this.isValidDate = function (d) {
                    if (Object.prototype.toString.call(d) !== "[object Date]") {
                        return false;
                    }
                    return !isNaN(d.getTime());
                };

                _this.setCurrentTime = function (dTime) {
                    _this.currentTime = (typeof dTime === 'string') ? _this.strToDateTime(dTime) : _this.isValidDate(dTime) ? dTime : _this.now();
                    datetimepicker.trigger('xchange.dtp');
                };

                _this.empty = function () {
                    _this.currentTime = null;
                };

                _this.getCurrentTime = function (dTime) {
                    return _this.currentTime;
                };

                _this.nextMonth = function () {
                    var month = _this.currentTime.getMonth() + 1,
						year;
                    if (month === 12) {
                        _this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1);
                        month = 0;
                    }

                    year = _this.currentTime.getFullYear();

                    _this.currentTime.setDate(
						Math.min(
							new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
							_this.currentTime.getDate()
						)
					);
                    _this.currentTime.setMonth(month);

                    if (options.onChangeMonth && typeof options.onChangeMonth === "function") {
                        options.onChangeMonth.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'));
                    }

                    if (year !== _this.currentTime.getFullYear() && typeof options.onChangeYear === "function") {
                        options.onChangeYear.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'));
                    }

                    datetimepicker.trigger('xchange.dtp');
                    return month;
                };

                _this.prevMonth = function () {
                    var month = _this.currentTime.getMonth() - 1;
                    if (month === -1) {
                        _this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1);
                        month = 11;
                    }
                    _this.currentTime.setDate(
						Math.min(
							new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
							_this.currentTime.getDate()
						)
					);
                    _this.currentTime.setMonth(month);
                    if (options.onChangeMonth && typeof options.onChangeMonth === "function") {
                        options.onChangeMonth.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'));
                    }
                    datetimepicker.trigger('xchange.dtp');
                    return month;
                };

                _this.getWeekOfYear = function (datetime) {
                    var onejan = new Date(datetime.getFullYear(), 0, 1);
                    return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7);
                };

                _this.strToDateTime = function (sDateTime) {
                    var tmpDate = [], timeOffset, currentTime;

                    if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) {
                        return sDateTime;
                    }

                    tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime);
                    if (tmpDate) {
                        tmpDate[2] = Date.parseDate(tmpDate[2], options.formatDate);
                    }
                    if (tmpDate && tmpDate[2]) {
                        timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000;
                        currentTime = new Date((_dtp_datetime.now()).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset);
                    } else {
                        currentTime = sDateTime ? Date.parseDate(sDateTime, options.format) : _this.now();
                    }

                    if (!_this.isValidDate(currentTime)) {
                        currentTime = _this.now();
                    }

                    return currentTime;
                };

                _this.strToDate = function (sDate) {
                    if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) {
                        return sDate;
                    }

                    var currentTime = sDate ? Date.parseDate(sDate, options.formatDate) : _this.now(true);
                    if (!_this.isValidDate(currentTime)) {
                        currentTime = _this.now(true);
                    }
                    return currentTime;
                };

                _this.strtotime = function (sTime) {
                    if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) {
                        return sTime;
                    }
                    var currentTime = sTime ? Date.parseDate(sTime, options.formatTime) : _this.now(true);
                    if (!_this.isValidDate(currentTime)) {
                        currentTime = _this.now(true);
                    }
                    return currentTime;
                };

                _this.str = function () {
                    return _this.currentTime.dateFormat(options.format);
                };
                _this.currentTime = this.now();
            };

            _dtp_datetime = new dtp_datetime();

            mounth_picker
				.find('.dtp_today_button')
				.on('mousedown.dtp', function () {
				    datetimepicker.data('changed', true);
				    _dtp_datetime.setCurrentTime(0);
				    datetimepicker.trigger('afterOpen.dtp');
				}).on('dblclick.dtp', function () {
				    input.val(_dtp_datetime.str());
				    datetimepicker.trigger('close.dtp');
				});
            mounth_picker
				.find('.dtp_prev,.dtp_next')
				.on('mousedown.dtp', function () {
				    var $this = $(this),
						timer = 0,
						stop = false;

				    (function arguments_callee1(v) {
				        var month = _dtp_datetime.currentTime.getMonth();
				        if ($this.hasClass(options.next)) {
				            _dtp_datetime.nextMonth();
				        } else if ($this.hasClass(options.prev)) {
				            _dtp_datetime.prevMonth();
				        }
				        if (options.monthChangeSpinner) {
				            if (!stop) {
				                timer = setTimeout(arguments_callee1, v || 100);
				            }
				        }
				    }(500));

				    $([document.body, window]).on('mouseup.dtp', function arguments_callee2() {
				        clearTimeout(timer);
				        stop = true;
				        $([document.body, window]).off('mouseup.dtp', arguments_callee2);
				    });
				});

            timepicker
				.find('.dtp_prev,.dtp_next')
				.on('mousedown.dtp', function () {
				    var $this = $(this),
						timer = 0,
						stop = false,
						period = 110;
				    (function arguments_callee4(v) {
				        var pheight = timeboxparent[0].clientHeight,
							height = timebox[0].offsetHeight,
							top = Math.abs(parseInt(timebox.css('marginTop'), 10));
				        if ($this.hasClass(options.next) && (height - pheight) - options.timeHeightInTimePicker >= top) {
				            timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px');
				        } else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) {
				            timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px');
				        }
				        timeboxparent.trigger('scroll_element.dtp_scroller', [Math.abs(parseInt(timebox.css('marginTop'), 10) / (height - pheight))]);
				        period = (period > 10) ? 10 : period - 10;
				        if (!stop) {
				            timer = setTimeout(arguments_callee4, v || period);
				        }
				    }(500));
				    $([document.body, window]).on('mouseup.dtp', function arguments_callee5() {
				        clearTimeout(timer);
				        stop = true;
				        $([document.body, window])
							.off('mouseup.dtp', arguments_callee5);
				    });
				});

            xchangeTimer = 0;
            // base handler - generating a calendar and timepicker
            datetimepicker
				.on('xchange.dtp', function (event) {
				    clearTimeout(xchangeTimer);
				    xchangeTimer = setTimeout(function () {
				        var table = '',
							start = new Date(_dtp_datetime.currentTime.getFullYear(), _dtp_datetime.currentTime.getMonth(), 1, 12, 0, 0),
							i = 0,
							j,
							today = _dtp_datetime.now(),
							maxDate = false,
							minDate = false,
							d,
							y,
							m,
							w,
							classes = [],
							customDateSettings,
							newRow = true,
							time = '',
							h = '',
							line_time;

				        while (start.getDay() !== options.dayOfWeekStart) {
				            start.setDate(start.getDate() - 1);
				        }

				        table += '<table><thead><tr>';

				        if (options.weeks) {
				            table += '<th></th>';
				        }

				        for (j = 0; j < 7; j += 1) {
				            table += '<th>' + options.i18n[options.lang].dayOfWeek[(j + options.dayOfWeekStart) % 7] + '</th>';
				        }

				        table += '</tr></thead>';
				        table += '<tbody>';

				        if (options.maxDate !== false) {
				            maxDate = _dtp_datetime.strToDate(options.maxDate);
				            maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999);
				        }

				        if (options.minDate !== false) {
				            minDate = _dtp_datetime.strToDate(options.minDate);
				            minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
				        }

				        while (i < _dtp_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _dtp_datetime.currentTime.getMonth() === start.getMonth()) {
				            classes = [];
				            i += 1;

				            d = start.getDate();
				            y = start.getFullYear();
				            m = start.getMonth();
				            w = _dtp_datetime.getWeekOfYear(start);

				            classes.push('dtp_date');

				            if (options.beforeShowDay && typeof options.beforeShowDay.call === "function") {
				                customDateSettings = options.beforeShowDay.call(datetimepicker, start);
				            } else {
				                customDateSettings = null;
				            }

				            if ((maxDate !== false && start > maxDate) || (minDate !== false && start < minDate) || (customDateSettings && customDateSettings[0] === false)) {
				                classes.push('dtp_disabled');
				            } else if (options.disabledDates.indexOf(start.dateFormat(options.formatDate)) !== -1) {
				                classes.push('dtp_disabled');
				            }

				            if (customDateSettings && customDateSettings[1] !== "") {
				                classes.push(customDateSettings[1]);
				            }

				            if (_dtp_datetime.currentTime.getMonth() !== m) {
				                classes.push('dtp_other_month');
				            }

				            if ((options.defaultSelect || datetimepicker.data('changed')) && _dtp_datetime.currentTime.dateFormat(options.formatDate) === start.dateFormat(options.formatDate)) {
				                classes.push('dtp_current');
				            }

				            if (today.dateFormat(options.formatDate) === start.dateFormat(options.formatDate)) {
				                classes.push('dtp_today');
				            }

				            if (start.getDay() === 0 || start.getDay() === 6 || ~options.weekends.indexOf(start.dateFormat(options.formatDate))) {
				                classes.push('dtp_weekend');
				            }

				            if (options.beforeShowDay && typeof options.beforeShowDay === "function") {
				                classes.push(options.beforeShowDay(start));
				            }

				            if (newRow) {
				                table += '<tr>';
				                newRow = false;
				                if (options.weeks) {
				                    table += '<th>' + w + '</th>';
				                }
				            }

				            table += '<td data-date="' + d + '" data-month="' + m + '" data-year="' + y + '"' + ' class="dtp_date dtp_day_of_week' + start.getDay() + ' ' + classes.join(' ') + '">' +
										'<div>' + d + '</div>' +
									'</td>';

				            if (start.getDay() === options.dayOfWeekStartPrev) {
				                table += '</tr>';
				                newRow = true;
				            }

				            start.setDate(d + 1);
				        }
				        table += '</tbody></table>';

				        calendar.html(table);

				        mounth_picker.find('.dtp_label span').eq(0).text(options.i18n[options.lang].months[_dtp_datetime.currentTime.getMonth()]);
				        mounth_picker.find('.dtp_label span').eq(1).text(_dtp_datetime.currentTime.getFullYear());

				        // generate timebox
				        time = '';
				        h = '';
				        m = '';
				        line_time = function line_time(h, m) {
				            var now = _dtp_datetime.now();
				            now.setHours(h);
				            h = parseInt(now.getHours(), 10);
				            now.setMinutes(m);
				            m = parseInt(now.getMinutes(), 10);
				            var optionDateTime = new Date(_dtp_datetime.currentTime)
				            optionDateTime.setHours(h);
				            optionDateTime.setMinutes(m);
				            classes = [];
				            if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || (options.maxTime !== false && _dtp_datetime.strtotime(options.maxTime).getTime() < now.getTime()) || (options.minTime !== false && _dtp_datetime.strtotime(options.minTime).getTime() > now.getTime())) {
				                classes.push('dtp_disabled');
				            }
				            if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && parseInt(_dtp_datetime.currentTime.getHours(), 10) === parseInt(h, 10) && (options.step > 59 || Math[options.roundTime](_dtp_datetime.currentTime.getMinutes() / options.step) * options.step === parseInt(m, 10))) {
				                if (options.defaultSelect || datetimepicker.data('changed')) {
				                    classes.push('dtp_current');
				                } else if (options.initTime) {
				                    classes.push('dtp_init_time');
				                }
				            }
				            if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) {
				                classes.push('dtp_today');
				            }
				            time += '<div class="dtp_time ' + classes.join(' ') + '" data-hour="' + h + '" data-minute="' + m + '">' + now.dateFormat(options.formatTime) + '</div>';
				        };

				        if (!options.allowTimes || !Array.isArray(options.allowTimes) || !options.allowTimes.length) {
				            for (i = 0, j = 0; i < (options.hours12 ? 12 : 24) ; i += 1) {
				                for (j = 0; j < 60; j += options.step) {
				                    h = (i < 10 ? '0' : '') + i;
				                    m = (j < 10 ? '0' : '') + j;
				                    line_time(h, m);
				                }
				            }
				        } else {
				            for (i = 0; i < options.allowTimes.length; i += 1) {
				                h = _dtp_datetime.strtotime(options.allowTimes[i]).getHours();
				                m = _dtp_datetime.strtotime(options.allowTimes[i]).getMinutes();
				                line_time(h, m);
				            }
				        }

				        timebox.html(time);

				        opt = '';
				        i = 0;

				        for (i = parseInt(options.yearStart, 10) + options.yearOffset; i <= parseInt(options.yearEnd, 10) + options.yearOffset; i += 1) {
				            opt += '<div class="dtp_option ' + (_dtp_datetime.currentTime.getFullYear() === i ? 'dtp_current' : '') + '" data-value="' + i + '">' + i + '</div>';
				        }
				        yearselect.children().eq(0)
												.html(opt);

				        for (i = 0, opt = ''; i <= 11; i += 1) {
				            opt += '<div class="dtp_option ' + (_dtp_datetime.currentTime.getMonth() === i ? 'dtp_current' : '') + '" data-value="' + i + '">' + options.i18n[options.lang].months[i] + '</div>';
				        }
				        monthselect.children().eq(0).html(opt);
				        $(datetimepicker)
							.trigger('generate.dtp');
				        
				    }, 10);
				    event.stopPropagation();
				})
				.on('afterOpen.dtp', function () {
				    if (options.timepicker) {
				        var classType, pheight, height, top;
				        if (timebox.find('.dtp_current').length) {
				            classType = '.dtp_current';
				        } else if (timebox.find('.dtp_init_time').length) {
				            classType = '.dtp_init_time';
				        }
				        if (classType) {
				            pheight = timeboxparent[0].clientHeight;
				            height = timebox[0].offsetHeight;
				            top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1;
				            if ((height - pheight) < top) {
				                top = height - pheight;
				            }
				            timeboxparent.trigger('scroll_element.dtp_scroller', [parseInt(top, 10) / (height - pheight)]);
				        } else {
				            timeboxparent.trigger('scroll_element.dtp_scroller', [0]);
				        }
				    }
				});

            timerclick = 0;
            calendar
				.on('click.dtp', 'td', function (xdevent) {
				    xdevent.stopPropagation();  // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
				    timerclick += 1;
				    var $this = $(this),
						currentTime = _dtp_datetime.currentTime;

				    if (currentTime === undefined || currentTime === null) {
				        _dtp_datetime.currentTime = _dtp_datetime.now();
				        currentTime = _dtp_datetime.currentTime;
				    }

				    if ($this.hasClass('dtp_disabled')) {
				        return false;
				    }

				    currentTime.setDate(1);
				    currentTime.setFullYear($this.data('year'));
				    currentTime.setMonth($this.data('month'));
				    currentTime.setDate($this.data('date'));

				    datetimepicker.trigger('select.dtp', [currentTime]);

				    input.val(_dtp_datetime.str());
				    if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === 0 && !options.timepicker))) && !options.inline) {
				        datetimepicker.trigger('close.dtp');
				    }

                    if (options.onSelectDate && typeof options.onSelectDate === "function") {
				        options.onSelectDate.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'), xdevent);
				    }

				    datetimepicker.data('changed', true);
				    datetimepicker.trigger('xchange.dtp');
				    datetimepicker.trigger('changedatetime.dtp');
				    setTimeout(function () {
				        timerclick = 0;
				    }, 200);
				});

            timebox
				.on('click.dtp', 'div', function (xdevent) {
				    xdevent.stopPropagation();
				    var $this = $(this),
						currentTime = _dtp_datetime.currentTime;

				    if (currentTime === undefined || currentTime === null) {
				        _dtp_datetime.currentTime = _dtp_datetime.now();
				        currentTime = _dtp_datetime.currentTime;
				    }

				    if ($this.hasClass('dtp_disabled')) {
				        return false;
				    }
				    currentTime.setHours($this.data('hour'));
				    currentTime.setMinutes($this.data('minute'));
				    datetimepicker.trigger('select.dtp', [currentTime]);

				    datetimepicker.data('input').val(_dtp_datetime.str());
				    if (!options.inline) {
				        datetimepicker.trigger('close.dtp');
				    }

                    if (options.onSelectTime && typeof options.onSelectTime === "function") {
				        options.onSelectTime.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'), xdevent);
				    }
				    datetimepicker.data('changed', true);
				    datetimepicker.trigger('xchange.dtp');
				    datetimepicker.trigger('changedatetime.dtp');
				});


            datepicker
				.on('mousewheel.dtp', function (event) {
				    if (!options.scrollMonth) {
				        return true;
				    }
				    if (event.deltaY < 0) {
				        _dtp_datetime.nextMonth();
				    } else {
				        _dtp_datetime.prevMonth();
				    }
				    return false;
				});

            input
				.on('mousewheel.dtp', function (event) {
				    if (!options.scrollInput) {
				        return true;
				    }
				    if (!options.datepicker && options.timepicker) {
				        current_time_index = timebox.find('.dtp_current').length ? timebox.find('.dtp_current').eq(0).index() : 0;
				        if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) {
				            current_time_index += event.deltaY;
				        }
				        if (timebox.children().eq(current_time_index).length) {
				            timebox.children().eq(current_time_index).trigger('mousedown');
				        }
				        return false;
				    }
				    if (options.datepicker && !options.timepicker) {
				        datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]);
				        if (input.val) {
				            input.val(_dtp_datetime.str());
				        }
				        datetimepicker.trigger('changedatetime.dtp');
				        return false;
				    }
				});

            datetimepicker
				.on('changedatetime.dtp', function (event) {
                    if (options.onChangeDateTime && typeof options.onChangeDateTime === "function") {
				        var $input = datetimepicker.data('input');
				        options.onChangeDateTime.call(datetimepicker, _dtp_datetime.currentTime, $input, event);
				        delete options.value;
				        $input.trigger('change');
				    }
				})
				.on('generate.dtp', function () {
                    if (options.onGenerate && typeof options.onGenerate === "function") {
				        options.onGenerate.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'));
				    }
				    if (triggerAfterOpen) {
				        datetimepicker.trigger('afterOpen.dtp');
				        triggerAfterOpen = false;
				    }
				})
				.on('click.dtp', function (xdevent) {
				    xdevent.stopPropagation();
				});

            current_time_index = 0;

            setPos = function () {
                var offset = datetimepicker.data('input').offset() || { top: 0, left: 0 }, top = offset.top + datetimepicker.data('input')[0].offsetHeight - 1, left = offset.left, position = "absolute";
                if (options.fixed) {
                    top -= $(window).scrollTop();
                    left -= $(window).scrollLeft();
                    position = "fixed";
                } else {
                    if (top + datetimepicker[0].offsetHeight > $(window).height() + $(window).scrollTop()) {
                        top = offset.top - datetimepicker[0].offsetHeight + 1;
                    }
                    if (top < 0) {
                        top = 0;
                    }
                    if (left + datetimepicker[0].offsetWidth > $(window).width()) {
                        left = $(window).width() - datetimepicker[0].offsetWidth;
                    }
                }
                datetimepicker.css({
                    left: left,
                    top: top,
                    position: position
                });
            };
            datetimepicker
				.on('open.dtp', function (event) {
				    var onShow = true;
                    if (options.onShow && typeof options.onShow === "function") {
				        onShow = options.onShow.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'), event);
				    }
				    if (onShow !== false) {
				        datetimepicker.show();
				        setPos();
				        $(window)
							.off('resize.dtp', setPos)
							.on('resize.dtp', setPos);

				        if (options.closeOnWithoutClick) {
				            $([document.body, window]).on('mousedown.dtp', function arguments_callee6() {
				                datetimepicker.trigger('close.dtp');
				                $([document.body, window]).off('mousedown.dtp', arguments_callee6);
				            });
				        }
				    }
				})
				.on('close.dtp', function (event) {
				    var onClose = true;
				    mounth_picker
						.find('.dtp_month,.dtp_year')
							.find('.dtp_select')
								.hide();
                    if (options.onClose && typeof options.onClose === "function") {
				        onClose = options.onClose.call(datetimepicker, _dtp_datetime.currentTime, datetimepicker.data('input'), event);
				    }
				    if (onClose !== false && !options.opened && !options.inline) {
				        datetimepicker.hide();
				    }
				    event.stopPropagation();
				})
				.on('toggle.dtp', function (event) {
				    if (datetimepicker.is(':visible')) {
				        datetimepicker.trigger('close.dtp');
				    } else {
				        datetimepicker.trigger('open.dtp');
				    }
				})
				.data('input', input);

            timer = 0;
            timer1 = 0;

            datetimepicker.data('dtp_datetime', _dtp_datetime);
            datetimepicker.setOptions(options);

            function getCurrentValue() {

                var ct = false, time;

                if (options.startDate) {
                    ct = _dtp_datetime.strToDate(options.startDate);
                } else {
                    ct = options.value || ((input && input.val && input.val()) ? input.val() : '');
                    if (ct) {
                        ct = _dtp_datetime.strToDateTime(ct);
                    } else if (options.defaultDate) {
                        ct = _dtp_datetime.strToDate(options.defaultDate);
                        if (options.defaultTime) {
                            time = _dtp_datetime.strtotime(options.defaultTime);
                            ct.setHours(time.getHours());
                            ct.setMinutes(time.getMinutes());
                        }
                    }
                }

                if (ct && _dtp_datetime.isValidDate(ct)) {
                    datetimepicker.data('changed', true);
                } else {
                    ct = '';
                }

                return ct || 0;
            }

            _dtp_datetime.setCurrentTime(getCurrentValue());

            input
				.data('dtp_datetimepicker', datetimepicker)
				.on('open.dtp focusin.dtp mousedown.dtp', function (event) {
				    if (input.is(':disabled') || (input.data('dtp_datetimepicker').is(':visible') && options.closeOnInputClick)) {
				        return;
				    }
				    clearTimeout(timer);
				    timer = setTimeout(function () {
				        if (input.is(':disabled')) {
				            return;
				        }

				        triggerAfterOpen = true;
				        _dtp_datetime.setCurrentTime(getCurrentValue());

				        datetimepicker.trigger('open.dtp');
				    }, 100);
				})
				.on('keydown.dtp', function (event) {
				    var val = this.value, elementSelector,
						key = event.which;
				    if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) {
				        elementSelector = $("input:visible,textarea:visible");
				        datetimepicker.trigger('close.dtp');
				        elementSelector.eq(elementSelector.index(this) + 1).trigger("focus");
				        return false;
				    }
				    if ([TAB].indexOf(key) !== -1) {
				        datetimepicker.trigger('close.dtp');
				        return true;
				    }
				});
        };
        destroyDateTimePicker = function (input) {
            var datetimepicker = input.data('dtp_datetimepicker');
            if (datetimepicker) {
                datetimepicker.data('dtp_datetime', null);
                datetimepicker.remove();
                input
					.data('dtp_datetimepicker', null)
					.off('.dtp');
                $(window).off('resize.dtp');
                $([window, document.body]).off('mousedown.dtp');
                if (input.unmousewheel) {
                    input.unmousewheel();
                }
            }
        };
        $(document)
			.off('keydown.dtpctrl keyup.dtpctrl')
			.on('keydown.dtpctrl', function (e) {
			    if (e.keyCode === CTRLKEY) {
			        ctrlDown = true;
			    }
			})
			.on('keyup.dtpctrl', function (e) {
			    if (e.keyCode === CTRLKEY) {
			        ctrlDown = false;
			    }
			});
        return this.each(function () {

            if (IsTouch() === false) {
                var datetimepicker = $(this).data('dtp_datetimepicker');
                if (datetimepicker) {
                    if (typeof opt === 'string') {
                        switch (opt) {
                            case 'show':
                                $(this).trigger("select").trigger("focus");
                                datetimepicker.trigger('open.dtp');
                                break;
                            case 'hide':
                                datetimepicker.trigger('close.dtp');
                                break;
                            case 'toggle':
                                datetimepicker.trigger('toggle.dtp');
                                break;
                            case 'destroy':
                                destroyDateTimePicker($(this));
                                break;
                            case 'reset':
                                this.value = this.defaultValue;
                                if (!this.value || !datetimepicker.data('dtp_datetime').isValidDate(Date.parseDate(this.value, options.format))) {
                                    datetimepicker.data('changed', false);
                                }
                                datetimepicker.data('dtp_datetime').setCurrentTime(this.value);
                                break;
                        }
                    } else {
                        datetimepicker
							.setOptions(opt);
                    }
                    return 0;
                }
                if (typeof opt !== 'string') {
                    if (!options.lazyInit || options.open || options.inline) {
                        createDateTimePicker($(this));
                    } else {
                        lazyInit($(this));
                    }
                }
            } else {
                var $dtp = $(this);

                if ($dtp.hasClass('dtp-datetime-local')) {
                    $('.dtp-datetime-local').removeAttr('data-bv-date data-bv-date-format data-bv-date-message');
                    $dtp.attr("type", "datetime-local");
                }
                else if ($dtp.hasClass('dtp-time')) {
                    $('.dtp-time').removeAttr('pattern');
                    $dtp.attr("type", "time");
                }
                else if ($dtp.hasClass('dtp-date')) {
                    $('.dtp-date').removeAttr('data-bv-date data-bv-date-format data-bv-date-message');
                    $dtp.attr("type", "date");
                }
                else if ($dtp.hasClass('dtp-week-year')) {
                    $('.dtp-week-year').removeAttr('pattern');
                    $dtp.attr("type", "week");
                }
                else if ($dtp.hasClass('dtp-month-year')) {
                    $('.dtp-month-year').removeAttr('pattern');
                    $dtp.attr("type", "month");
                }
            }



        });

    };
    $.fn.datetimepicker.defaults = default_options;
}(jQuery));
(function () {

    /*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
     * Licensed under the MIT License (LICENSE.txt).
     *
     * Version: 3.1.12
     *
     * Requires: jQuery 1.2.2+
     */
    !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; 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.on("mousewheel", a) : this.trigger("mousewheel") }, unmousewheel: function (a) { return this.off("mousewheel", a) } }) });

    // Parse and Format Library
    //http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
    /*
     * Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
     *
     * This program is free software; you can redistribute it and/or modify it
     * under the terms of the GNU Lesser General Public License as published by the
     * Free Software Foundation, version 2.1.
     *
     * This program is distributed in the hope that it will be useful, but WITHOUT
     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
     * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
     * details.
     */
    Date.parseFunctions = { count: 0 }; Date.parseRegexes = []; Date.formatFunctions = { count: 0 }; Date.prototype.dateFormat = function (b) { if (b == "unixtime") { return parseInt(this.getTime() / 1000); } if (Date.formatFunctions[b] == null) { Date.createNewFormat(b); } var a = Date.formatFunctions[b]; return this[a](); }; Date.createNewFormat = function (format) { var funcName = "format" + Date.formatFunctions.count++; Date.formatFunctions[format] = funcName; var code = "Date.prototype." + funcName + " = function() {return "; var special = false; var ch = ""; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else { if (special) { special = false; code += "'" + String.escape(ch) + "' + "; } else { code += Date.getFormatCode(ch); } } } eval(code.substring(0, code.length - 3) + ";}"); }; Date.getFormatCode = function (a) { switch (a) { case "d": return "String.leftPad(this.getDate(), 2, '0') + "; case "D": return "Date.dayNames[this.getDay()].substring(0, 3) + "; case "j": return "this.getDate() + "; case "l": return "Date.dayNames[this.getDay()] + "; case "S": return "this.getSuffix() + "; case "w": return "this.getDay() + "; case "z": return "this.getDayOfYear() + "; case "W": return "this.getWeekOfYear() + "; case "F": return "Date.monthNames[this.getMonth()] + "; case "m": return "String.leftPad(this.getMonth() + 1, 2, '0') + "; case "M": return "Date.monthNames[this.getMonth()].substring(0, 3) + "; case "n": return "(this.getMonth() + 1) + "; case "t": return "this.getDaysInMonth() + "; case "L": return "(this.isLeapYear() ? 1 : 0) + "; case "Y": return "this.getFullYear() + "; case "y": return "('' + this.getFullYear()).substring(2, 4) + "; case "a": return "(this.getHours() < 12 ? 'am' : 'pm') + "; case "A": return "(this.getHours() < 12 ? 'AM' : 'PM') + "; case "g": return "((this.getHours() %12) ? this.getHours() % 12 : 12) + "; case "G": return "this.getHours() + "; case "h": return "String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + "; case "H": return "String.leftPad(this.getHours(), 2, '0') + "; case "i": return "String.leftPad(this.getMinutes(), 2, '0') + "; case "s": return "String.leftPad(this.getSeconds(), 2, '0') + "; case "O": return "this.getGMTOffset() + "; case "T": return "this.getTimezone() + "; case "Z": return "(this.getTimezoneOffset() * -60) + "; default: return "'" + String.escape(a) + "' + "; } }; Date.parseDate = function (a, c) { if (c == "unixtime") { return new Date(!isNaN(parseInt(a)) ? parseInt(a) * 1000 : 0); } if (Date.parseFunctions[c] == null) { Date.createParser(c); } var b = Date.parseFunctions[c]; return Date[b](a); }; Date.createParser = function (format) { var funcName = "parse" + Date.parseFunctions.count++; var regexNum = Date.parseRegexes.length; var currentGroup = 1; Date.parseFunctions[format] = funcName; var code = "Date." + funcName + " = function(input) {\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, z = -1;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes[" + regexNum + "]);\nif (results && results.length > 0) {"; var regex = ""; var special = false; var ch = ""; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else { if (special) { special = false; regex += String.escape(ch); } else { obj = Date.formatCodeToRegex(ch, currentGroup); currentGroup += obj.g; regex += obj.s; if (obj.g && obj.c) { code += obj.c; } } } } code += "if (y > 0 && z > 0){\nvar doyDate = new Date(y,0);\ndoyDate.setDate(z);\nm = doyDate.getMonth();\nd = doyDate.getDate();\n}"; code += "if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{return new Date(y, m, d, h, i, s);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{return new Date(y, m, d, h, i);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0)\n{return new Date(y, m, d, h);}\nelse if (y > 0 && m >= 0 && d > 0)\n{return new Date(y, m, d);}\nelse if (y > 0 && m >= 0)\n{return new Date(y, m);}\nelse if (y > 0)\n{return new Date(y);}\n}return null;}"; Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$"); eval(code); }; Date.formatCodeToRegex = function (b, a) { switch (b) { case "D": return { g: 0, c: null, s: "(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)" }; case "j": case "d": return { g: 1, c: "d = parseInt(results[" + a + "], 10);\n", s: "(\\d{1,2})" }; case "l": return { g: 0, c: null, s: "(?:" + Date.dayNames.join("|") + ")" }; case "S": return { g: 0, c: null, s: "(?:st|nd|rd|th)" }; case "w": return { g: 0, c: null, s: "\\d" }; case "z": return { g: 1, c: "z = parseInt(results[" + a + "], 10);\n", s: "(\\d{1,3})" }; case "W": return { g: 0, c: null, s: "(?:\\d{2})" }; case "F": return { g: 1, c: "m = parseInt(Date.monthNumbers[results[" + a + "].substring(0, 3)], 10);\n", s: "(" + Date.monthNames.join("|") + ")" }; case "M": return { g: 1, c: "m = parseInt(Date.monthNumbers[results[" + a + "]], 10);\n", s: "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" }; case "n": case "m": return { g: 1, c: "m = parseInt(results[" + a + "], 10) - 1;\n", s: "(\\d{1,2})" }; case "t": return { g: 0, c: null, s: "\\d{1,2}" }; case "L": return { g: 0, c: null, s: "(?:1|0)" }; case "Y": return { g: 1, c: "y = parseInt(results[" + a + "], 10);\n", s: "(\\d{4})" }; case "y": return { g: 1, c: "var ty = parseInt(results[" + a + "], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", s: "(\\d{1,2})" }; case "a": return { g: 1, c: "if (results[" + a + "] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}", s: "(am|pm)" }; case "A": return { g: 1, c: "if (results[" + a + "] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}", s: "(AM|PM)" }; case "g": case "G": case "h": case "H": return { g: 1, c: "h = parseInt(results[" + a + "], 10);\n", s: "(\\d{1,2})" }; case "i": return { g: 1, c: "i = parseInt(results[" + a + "], 10);\n", s: "(\\d{2})" }; case "s": return { g: 1, c: "s = parseInt(results[" + a + "], 10);\n", s: "(\\d{2})" }; case "O": return { g: 0, c: null, s: "[+-]\\d{4}" }; case "T": return { g: 0, c: null, s: "[A-Z]{3}" }; case "Z": return { g: 0, c: null, s: "[+-]\\d{1,5}" }; default: return { g: 0, c: null, s: String.escape(b) }; } }; Date.prototype.getTimezone = function () { return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/, "$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/, "$1$2$3"); }; Date.prototype.getGMTOffset = function () { return (this.getTimezoneOffset() > 0 ? "-" : "+") + String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0") + String.leftPad(Math.abs(this.getTimezoneOffset()) % 60, 2, "0"); }; Date.prototype.getDayOfYear = function () { var a = 0; Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; for (var b = 0; b < this.getMonth() ; ++b) { a += Date.daysInMonth[b]; } return a + this.getDate(); }; Date.prototype.getWeekOfYear = function () { var b = this.getDayOfYear() + (4 - this.getDay()); var a = new Date(this.getFullYear(), 0, 1); var c = (7 - a.getDay() + 4); return String.leftPad(Math.ceil((b - c) / 7) + 1, 2, "0"); }; Date.prototype.isLeapYear = function () { var a = this.getFullYear(); return ((a & 3) == 0 && (a % 100 || (a % 400 == 0 && a))); }; Date.prototype.getFirstDayOfMonth = function () { var a = (this.getDay() - (this.getDate() - 1)) % 7; return (a < 0) ? (a + 7) : a; }; Date.prototype.getLastDayOfMonth = function () { var a = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7; return (a < 0) ? (a + 7) : a; }; Date.prototype.getDaysInMonth = function () { Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; return Date.daysInMonth[this.getMonth()]; }; Date.prototype.getSuffix = function () { switch (this.getDate()) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }; String.escape = function (a) { return a.replace(/('|\\)/g, "\\$1"); }; String.leftPad = function (d, b, c) { var a = new String(d); if (c == null) { c = " "; } while (a.length < b) { a = c + a; } return a; }; Date.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; Date.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; Date.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; Date.y2kYear = 50; Date.monthNumbers = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }; Date.patterns = { ISO8601LongPattern: "Y-m-d H:i:s", ISO8601ShortPattern: "Y-m-d", ShortDatePattern: "n/j/Y", LongDatePattern: "l, F d, Y", FullDateTimePattern: "l, F d, Y g:i:s A", MonthDayPattern: "F d", ShortTimePattern: "g:i A", LongTimePattern: "g:i:s A", SortableDateTimePattern: "Y-m-d\\TH:i:s", UniversalSortableDateTimePattern: "Y-m-d H:i:sO", YearMonthPattern: "F, Y" };
}());

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\matchMedia.js
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */

window.matchMedia || (window.matchMedia = function() {
    "use strict";

    // For browsers that support matchMedium api such as IE 9 and webkit
    var styleMedia = (window.styleMedia || window.media);

    // For those that don't support matchMedium
    if (!styleMedia) {
        var style       = document.createElement('style'),
            script      = document.getElementsByTagName('script')[0],
            info        = null;

        style.type  = 'text/css';
        style.id    = 'matchmediajs-test';

        script.parentNode.insertBefore(style, script);

        // 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
        info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;

        styleMedia = {
            matchMedium: function(media) {
                var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';

                // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
                if (style.styleSheet) {
                    style.styleSheet.cssText = text;
                } else {
                    style.textContent = text;
                }

                // Test if media query is true or false
                return info.width === '1px';
            }
        };
    }

    return function(media) {
        return {
            matches: styleMedia.matchMedium(media || 'all'),
            media: media || 'all'
        };
    };
}());

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\appendSRC.js
/*version="11"*/
$(function () {
    var srcParam = queryStringAppender.getSrcParam();
    var storedSrcParam = queryStringAppender.getSrcSession();

    //TLA App
    if (window.location.href.toLowerCase().indexOf("tlaapp") === -1) {
        if (window.OptanonActiveGroups.indexOf("2") !== -1) {
            // without src/SRC querystring and Append_SRCparam has different value
            if (storedSrcParam != escape(srcParam) && typeof srcParam !== 'undefined' && srcParam != null) {
                sessionStorage.setItem('Append_SRCparam', srcParam);
            }

            linksProcessing.appendSRC(srcParam, storedSrcParam);

            if (storedSrcParam !== null && srcParam === null) {
                var params = document.location.search.substr(1).split('&');
                if (params[0] !== "" || params[0] !== null) {
                    let newParams = storedSrcParam + "&" + params.join('&');
                    window.history.pushState({}, '', '?' + newParams);
                }
                else {
                    window.history.pushState({}, '', '?' + storedSrcParam);
                }
            }
        }
    }

});
var urlParams = window.location.search.substring(1);
var separators = ['&', '\\?'];

var queryStringAppender = {
    getSrcParam: function () {
        if (urlParams != "") {
            var urlVariables = urlParams.split(new RegExp(separators.join('|')));
            for (var i = 0; i < urlVariables.length; i++) {
                var paramName = urlVariables[i].split('=')[0];
                if (paramName.toLowerCase() == 'src' && urlVariables[i] !== 'src=') {
                    return urlVariables[i];
                }
            }
        }
        return null;
    },
    getSrcSession: function () {
        var srcSess = sessionStorage.getItem("Append_SRCparam");
        if (typeof srcSess !== 'undefined' && srcSess !== null) {
            return srcSess;
        }
        return null;
    }

};
var linksProcessing = {

    appendSRC: function (srcParam, cachedSRC) {
        var links = document.links;

        if (cachedSRC !== null && cachedSRC !== 'src%3D') {
            cachedSRC = $.trim(cachedSRC.replace('%3D', '='));
        }
        for (var i = 0; i < links.length; i++) {
            if (links[i].hostname === "philjobs.accenture.com" || links[i].hostname === "india.jobs.accenture.com" || links[i].hostname === "tas-accenture.taleo.net") {
                if (links[i].href.toLowerCase().indexOf("src") === -1) {
                    if (srcParam !== null) {
                        links[i].setAttribute('href', links[i].getAttribute('href') + '&' + srcParam);
                    }
                    else if (srcParam === null && cachedSRC !== null) {
                        links[i].setAttribute('href', links[i].getAttribute('href') + '&' + cachedSRC);
                    }
                }
                else {
                    var p = links[i].href.split(new RegExp(separators.join('|')));
                    for (var j = 0; j < p.length; j++) {
                        if (p[j] === 'src=') {
                            if (srcParam !== null) {
                                links[i].setAttribute('href', links[i].href.replace("src=", srcParam));
                            }
                            else if (srcParam === null && cachedSRC !== null) {
                                links[i].setAttribute('href', links[i].href.replace("src=", cachedSRC));
                            }
                        }
                    }
                }
            }
        }
    }
};


;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\typeahead.jquery.js
/*version = 4*/
/*!
* typeahead.js 0.10.4
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/

//JQuery v3.0 Compatible

(function ($) {
    var _ = function () {
        "use strict";
        return {
            isMsie: function () {
                return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
            },
            isBlankString: function (str) {
                return !str || /^\s*$/.test(str);
            },
            escapeRegExChars: function (str) {
                return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            },
            isString: function (obj) {
                return typeof obj === "string";
            },
            isNumber: function (obj) {
                return typeof obj === "number";
            },
            isArray: Array.isArray,
            isObject: $.isPlainObject,
            isUndefined: function (obj) {
                return typeof obj === "undefined";
            },
            toStr: function toStr(s) {
                return _.isUndefined(s) || s === null ? "" : s + "";
            },
            bind: $.proxy,
            isFunction: function (obj) {
                if (typeof obj === "function") {
                    return true;
                }
                else {
                    return false;
                }
            },
            each: function (collection, cb) {
                $.each(collection, reverseArgs);
                function reverseArgs(index, value) {
                    return cb(value, index);
                }
            },
            map: $.map,
            filter: $.grep,
            every: function (obj, test) {
                var result = true;
                if (!obj) {
                    return result;
                }
                $.each(obj, function (key, val) {
                    if (!(result = test.call(null, val, key, obj))) {
                        return false;
                    }
                });
                return !!result;
            },
            some: function (obj, test) {
                var result = false;
                if (!obj) {
                    return result;
                }
                $.each(obj, function (key, val) {
                    if (result = test.call(null, val, key, obj)) {
                        return false;
                    }
                });
                return !!result;
            },
            mixin: $.extend,
            getUniqueId: function () {
                var counter = 0;
                return function () {
                    return counter++;
                };
            }(),
            templatify: function templatify(obj) {
                return typeof obj === "function" ? obj : template;
                function template() {
                    return String(obj);
                }
            },
            defer: function (fn) {
                setTimeout(fn, 0);
            },
            debounce: function (func, wait, immediate) {
                var timeout, result;
                return function () {
                    var context = this, args = arguments, later, callNow;
                    later = function () {
                        timeout = null;
                        if (!immediate) {
                            result = func.apply(context, args);
                        }
                    };
                    callNow = immediate && !timeout;
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                    if (callNow) {
                        result = func.apply(context, args);
                    }
                    return result;
                };
            },
            throttle: function (func, wait) {
                var context, args, timeout, result, previous, later;
                previous = 0;
                later = function () {
                    previous = new Date();
                    timeout = null;
                    result = func.apply(context, args);
                };
                return function () {
                    var now = new Date(), remaining = wait - (now - previous);
                    context = this;
                    args = arguments;
                    if (remaining <= 0) {
                        clearTimeout(timeout);
                        timeout = null;
                        previous = now;
                        result = func.apply(context, args);
                    } else if (!timeout) {
                        timeout = setTimeout(later, remaining);
                    }
                    return result;
                };
            },
            noop: function () { }
        };
    }();
    var VERSION = "0.10.4";
    var tokenizers = function () {
        "use strict";
        return {
            nonword: nonword,
            whitespace: whitespace,
            obj: {
                nonword: getObjTokenizer(nonword),
                whitespace: getObjTokenizer(whitespace)
            }
        };
        function whitespace(str) {
            str = _.toStr(str);
            return str ? str.split(/\s+/) : [];
        };
        function nonword(str) {
            str = _.toStr(str);
            return str ? str.split(/\W+/) : [];
        };
        function getObjTokenizer(tokenizer) {
            return function setKey() {
                var args = [].slice.call(arguments, 0);
                return function tokenize(o) {
                    var tokens = [];
                    _.each(args, function (k) {
                        tokens = tokens.concat(tokenizer(_.toStr(o[k])));
                    });
                    return tokens;
                };
            };
        };
    }();
    var LruCache = function () {
        "use strict";
        function LruCache(maxSize) {
            this.maxSize = _.isNumber(maxSize) ? maxSize : 100;
            this.reset();
            if (this.maxSize <= 0) {
                this.set = this.get = $.noop;
            }
        };
        _.mixin(LruCache.prototype, {
            set: function set(key, val) {
                var tailItem = this.list.tail, node;
                if (this.size >= this.maxSize) {
                    this.list.remove(tailItem);
                    delete this.hash[tailItem.key];
                }
                if (node = this.hash[key]) {
                    node.val = val;
                    this.list.moveToFront(node);
                } else {
                    node = new Node(key, val);
                    this.list.add(node);
                    this.hash[key] = node;
                    this.size++;
                }
            },
            get: function get(key) {
                var node = this.hash[key];
                if (node) {
                    this.list.moveToFront(node);
                    return node.val;
                }
            },
            reset: function reset() {
                this.size = 0;
                this.hash = {};
                this.list = new List();
            }
        });
        function List() {
            this.head = this.tail = null;
        };
        _.mixin(List.prototype, {
            add: function add(node) {
                if (this.head) {
                    node.next = this.head;
                    this.head.prev = node;
                }
                this.head = node;
                this.tail = this.tail || node;
            },
            remove: function remove(node) {
                node.prev ? node.prev.next = node.next : this.head = node.next;
                node.next ? node.next.prev = node.prev : this.tail = node.prev;
            },
            moveToFront: function (node) {
                this.remove(node);
                this.add(node);
            }
        });
        function Node(key, val) {
            this.key = key;
            this.val = val;
            this.prev = this.next = null;
        }
        return LruCache;
    }();
    var PersistentStorage = function () {
        "use strict";
        var ls, methods;
        try {
            ls = window.localStorage;
            ls.setItem("~~~", "!");
            ls.removeItem("~~~");
        } catch (err) {
            ls = null;
        }
        function PersistentStorage(namespace) {
            this.prefix = ["__", namespace, "__"].join("");
            this.ttlKey = "__ttl__";
            this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix));
        };
        if (ls && window.JSON) {
            methods = {
                _prefix: function (key) {
                    return this.prefix + key;
                },
                _ttlKey: function (key) {
                    return this._prefix(key) + this.ttlKey;
                },
                get: function (key) {
                    if (this.isExpired(key)) {
                        this.remove(key);
                    }
                    return decode(ls.getItem(this._prefix(key)));
                },
                set: function (key, val, ttl) {
                    if (_.isNumber(ttl)) {
                        ls.setItem(this._ttlKey(key), encode(now() + ttl));
                    } else {
                        ls.removeItem(this._ttlKey(key));
                    }
                    return ls.setItem(this._prefix(key), encode(val));
                },
                remove: function (key) {
                    ls.removeItem(this._ttlKey(key));
                    ls.removeItem(this._prefix(key));
                    return this;
                },
                clear: function () {
                    var i, key, keys = [], len = ls.length;
                    for (i = 0; i < len; i++) {
                        if ((key = ls.key(i)).match(this.keyMatcher)) {
                            keys.push(key.replace(this.keyMatcher, ""));
                        }
                    }
                    for (i = keys.length; i--;) {
                        this.remove(keys[i]);
                    }
                    return this;
                },
                isExpired: function (key) {
                    var ttl = decode(ls.getItem(this._ttlKey(key)));
                    return _.isNumber(ttl) && now() > ttl ? true : false;
                }
            };
        } else {
            methods = {
                get: _.noop,
                set: _.noop,
                remove: _.noop,
                clear: _.noop,
                isExpired: _.noop
            };
        }
        _.mixin(PersistentStorage.prototype, methods);
        return PersistentStorage;
        function now() {
            return new Date().getTime();
        };
        function encode(val) {
            return JSON.stringify(_.isUndefined(val) ? null : val);
        };
        function decode(val) {
            return JSON.parse(val);
        };
    }();
    var Transport = function () {
        "use strict";
        var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10);
        function Transport(o) {
            o = o || {};
            this.cancelled = false;
            this.lastUrl = null;
            this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax;
            this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get;
            this._cache = o.cache === false ? new LruCache(0) : sharedCache;
        };
        Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
            maxPendingRequests = num;
        };
        Transport.resetCache = function resetCache() {
            sharedCache.reset();
        };
        _.mixin(Transport.prototype, {
            _get: function (url, o, cb) {
                var that = this, jqXhr;
                if (this.cancelled || url !== this.lastUrl) {
                    return;
                }
                if (jqXhr = pendingRequests[url]) {
                    jqXhr.done(done).fail(fail);
                } else if (pendingRequestsCount < maxPendingRequests) {
                    pendingRequestsCount++;
                    pendingRequests[url] = this._send(url, o).done(done).fail(fail).always(always);
                } else {
                    this.onDeckRequestArgs = [].slice.call(arguments, 0);
                }
                function done(resp) {
                    cb && cb(null, resp);
                    that._cache.set(url, resp);
                }
                function fail() {
                    cb && cb(true);
                }
                function always() {
                    pendingRequestsCount--;
                    delete pendingRequests[url];
                    if (that.onDeckRequestArgs) {
                        that._get.apply(that, that.onDeckRequestArgs);
                        that.onDeckRequestArgs = null;
                    }
                }
            },
            get: function (url, o, cb) {
                var resp;
                if (_.isFunction(o)) {
                    cb = o;
                    o = {};
                }
                this.cancelled = false;
                this.lastUrl = url;
                if (resp = this._cache.get(url)) {
                    _.defer(function () {
                        cb && cb(null, resp);
                    });
                } else {
                    this._get(url, o, cb);
                }
                return !!resp;
            },
            cancel: function () {
                this.cancelled = true;
            }
        });
        return Transport;
        function callbackToDeferred(fn) {
            return function customSendWrapper(url, o) {
                var deferred = $.Deferred();
                fn(url, o, onSuccess, onError);
                return deferred;
                function onSuccess(resp) {
                    _.defer(function () {
                        deferred.resolve(resp);
                    });
                }
                function onError(err) {
                    _.defer(function () {
                        deferred.reject(err);
                    });
                }
            };
        };
    }();
    var SearchIndex = function () {
        "use strict";
        function SearchIndex(o) {
            o = o || {};
            if (!o.datumTokenizer || !o.queryTokenizer) {
                $.error("datumTokenizer and queryTokenizer are both required");
            }
            this.datumTokenizer = o.datumTokenizer;
            this.queryTokenizer = o.queryTokenizer;
            this.reset();
        };
        _.mixin(SearchIndex.prototype, {
            bootstrap: function bootstrap(o) {
                this.datums = o.datums;
                this.trie = o.trie;
            },
            add: function (data) {
                var that = this;
                data = _.isArray(data) ? data : [data];
                _.each(data, function (datum) {
                    var id, tokens;
                    id = that.datums.push(datum) - 1;
                    tokens = normalizeTokens(that.datumTokenizer(datum));
                    _.each(tokens, function (token) {
                        var node, chars, ch;
                        node = that.trie;
                        chars = token.split("");
                        while (ch = chars.shift()) {
                            node = node.children[ch] || (node.children[ch] = newNode());
                            node.ids.push(id);
                        }
                    });
                });
            },
            get: function get(query) {
                var that = this, tokens, matches;
                tokens = normalizeTokens(this.queryTokenizer(query));
                _.each(tokens, function (token) {
                    var node, chars, ch, ids;
                    if (matches && matches.length === 0) {
                        return false;
                    }
                    node = that.trie;
                    chars = token.split("");
                    while (node && (ch = chars.shift())) {
                        node = node.children[ch];
                    }
                    if (node && chars.length === 0) {
                        ids = node.ids.slice(0);
                        matches = matches ? getIntersection(matches, ids) : ids;
                    } else {
                        matches = [];
                        return false;
                    }
                });
                return matches ? _.map(unique(matches), function (id) {
                    return that.datums[id];
                }) : [];
            },
            reset: function reset() {
                this.datums = [];
                this.trie = newNode();
            },
            serialize: function serialize() {
                return {
                    datums: this.datums,
                    trie: this.trie
                };
            }
        });
        return SearchIndex;
        function normalizeTokens(tokens) {
            tokens = _.filter(tokens, function (token) {
                return !!token;
            });
            tokens = _.map(tokens, function (token) {
                return token.toLowerCase();
            });
            return tokens;
        };
        function newNode() {
            return {
                ids: [],
                children: {}
            };
        };
        function unique(array) {
            var seen = {}, uniques = [];
            for (var i = 0, len = array.length; i < len; i++) {
                if (!seen[array[i]]) {
                    seen[array[i]] = true;
                    uniques.push(array[i]);
                }
            }
            return uniques;
        };
        function getIntersection(arrayA, arrayB) {
            var ai = 0, bi = 0, intersection = [];
            arrayA = arrayA.sort(compare);
            arrayB = arrayB.sort(compare);
            var lenArrayA = arrayA.length, lenArrayB = arrayB.length;
            while (ai < lenArrayA && bi < lenArrayB) {
                if (arrayA[ai] < arrayB[bi]) {
                    ai++;
                } else if (arrayA[ai] > arrayB[bi]) {
                    bi++;
                } else {
                    intersection.push(arrayA[ai]);
                    ai++;
                    bi++;
                }
            }
            return intersection;
            function compare(a, b) {
                return a - b;
            }
        };
    }();
    var oParser = function () {
        "use strict";
        return {
            local: getLocal,
            prefetch: getPrefetch,
            remote: getRemote
        };
        function getLocal(o) {
            return o.local || null;
        };
        function getPrefetch(o) {
            var prefetch, defaults;
            defaults = {
                url: null,
                thumbprint: "",
                ttl: 24 * 60 * 60 * 1e3,
                filter: null,
                ajax: {}
            };
            if (prefetch = o.prefetch || null) {
                prefetch = _.isString(prefetch) ? {
                    url: prefetch
                } : prefetch;
                prefetch = _.mixin(defaults, prefetch);
                prefetch.thumbprint = VERSION + prefetch.thumbprint;
                prefetch.ajax.type = prefetch.ajax.type || "GET";
                prefetch.ajax.dataType = prefetch.ajax.dataType || "json";
                !prefetch.url && $.error("prefetch requires url to be set");
            }
            return prefetch;
        };
        function getRemote(o) {
            var remote, defaults;
            defaults = {
                url: null,
                cache: true,
                wildcard: "%QUERY",
                replace: null,
                rateLimitBy: "debounce",
                rateLimitWait: 300,
                send: null,
                filter: null,
                ajax: {}
            };
            if (remote = o.remote || null) {
                remote = _.isString(remote) ? {
                    url: remote
                } : remote;
                remote = _.mixin(defaults, remote);
                remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);
                remote.ajax.type = remote.ajax.type || "GET";
                remote.ajax.dataType = remote.ajax.dataType || "json";
                delete remote.rateLimitBy;
                delete remote.rateLimitWait;
                !remote.url && $.error("remote requires url to be set");
            }
            return remote;
            function byDebounce(wait) {
                return function (fn) {
                    return _.debounce(fn, wait);
                };
            };
            function byThrottle(wait) {
                return function (fn) {
                    return _.throttle(fn, wait);
                };
            };
        };
    }();
    (function (root) {
        "use strict";
        var old, keys;
        old = root.Bloodhound;
        keys = {
            data: "data",
            protocol: "protocol",
            thumbprint: "thumbprint"
        };
        root.Bloodhound = Bloodhound;
        function Bloodhound(o) {
            if (!o || !o.local && !o.prefetch && !o.remote) {
                $.error("one of local, prefetch, or remote is required");
            }
            this.limit = o.limit || 5;
            this.sorter = getSorter(o.sorter);
            this.dupDetector = o.dupDetector || ignoreDuplicates;
            this.local = oParser.local(o);
            this.prefetch = oParser.prefetch(o);
            this.remote = oParser.remote(o);
            this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null;
            this.index = new SearchIndex({
                datumTokenizer: o.datumTokenizer,
                queryTokenizer: o.queryTokenizer
            });
            this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null;
        };
        Bloodhound.noConflict = function noConflict() {
            root.Bloodhound = old;
            return Bloodhound;
        };
        Bloodhound.tokenizers = tokenizers;
        _.mixin(Bloodhound.prototype, {
            _loadPrefetch: function loadPrefetch(o) {
                var that = this, serialized, deferred;
                if (serialized = this._readFromStorage(o.thumbprint)) {
                    this.index.bootstrap(serialized);
                    deferred = $.Deferred().resolve();
                } else {
                    deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
                }
                return deferred;
                function handlePrefetchResponse(resp) {
                    that.clear();
                    that.add(o.filter ? o.filter(resp) : resp);
                    that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
                }
            },
            _getFromRemote: function getFromRemote(query, cb) {
                var that = this, url, uriEncodedQuery;
                if (!this.transport) {
                    return;
                }
                query = query || "";
                uriEncodedQuery = encodeURIComponent(query);
                url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);
                return this.transport.get(url, this.remote.ajax, handleRemoteResponse);
                function handleRemoteResponse(err, resp) {
                    err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp);
                }
            },
            _cancelLastRemoteRequest: function cancelLastRemoteRequest() {
                this.transport && this.transport.cancel();
            },
            _saveToStorage: function saveToStorage(data, thumbprint, ttl) {
                if (this.storage) {
                    this.storage.set(keys.data, data, ttl);
                    this.storage.set(keys.protocol, location.protocol, ttl);
                    this.storage.set(keys.thumbprint, thumbprint, ttl);
                }
            },
            _readFromStorage: function readFromStorage(thumbprint) {
                var stored = {}, isExpired;
                if (this.storage) {
                    stored.data = this.storage.get(keys.data);
                    stored.protocol = this.storage.get(keys.protocol);
                    stored.thumbprint = this.storage.get(keys.thumbprint);
                }
                isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol;
                return stored.data && !isExpired ? stored.data : null;
            },
            _initialize: function initialize() {
                var that = this, local = this.local, deferred;
                deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve();
                local && deferred.done(addLocalToIndex);
                this.transport = this.remote ? new Transport(this.remote) : null;
                return this.initPromise = deferred.promise();
                function addLocalToIndex() {
                    that.add(_.isFunction(local) ? local() : local);
                }
            },
            initialize: function initialize(force) {
                return !this.initPromise || force ? this._initialize() : this.initPromise;
            },
            add: function add(data) {
                this.index.add(data);
            },
            get: function get(query, cb) {
                var that = this, matches = [], cacheHit = false;
                matches = this.index.get(query);
                matches = this.sorter(matches).slice(0, this.limit);
                matches.length < this.limit ? cacheHit = this._getFromRemote(query, returnRemoteMatches) : this._cancelLastRemoteRequest();
                if (!cacheHit) {
                    (matches.length > 0 || !this.transport) && cb && cb(matches);
                }
                function returnRemoteMatches(remoteMatches) {
                    var matchesWithBackfill = matches.slice(0);
                    _.each(remoteMatches, function (remoteMatch) {
                        var isDuplicate;
                        isDuplicate = _.some(matchesWithBackfill, function (match) {
                            return that.dupDetector(remoteMatch, match);
                        });
                        !isDuplicate && matchesWithBackfill.push(remoteMatch);
                        return matchesWithBackfill.length < that.limit;
                    });
                    cb && cb(that.sorter(matchesWithBackfill));
                }
            },
            clear: function clear() {
                this.index.reset();
            },
            clearPrefetchCache: function clearPrefetchCache() {
                this.storage && this.storage.clear();
            },
            clearRemoteCache: function clearRemoteCache() {
                this.transport && Transport.resetCache();
            },
            ttAdapter: function ttAdapter() {
                return _.bind(this.get, this);
            }
        });
        return Bloodhound;
        function getSorter(sortFn) {
            return _.isFunction(sortFn) ? sort : noSort;
            function sort(array) {
                return array.sort(sortFn);
            };
            function noSort(array) {
                return array;
            };
        };
        function ignoreDuplicates() {
            return false;
        };
    })(this);
    var html = function () {
        return {
            wrapper: '<div class="twitter-typeahead"></div>',
            dropdown: '<div class="tt-dropdown-menu"></div>',
            dataset: '<div class="tt-dataset-%CLASS%"></div>',
            suggestions: '<ul role="listbox" class="tt-suggestions autocomplete-list"></ul>',
            suggestion: '<li role="option" aria-selected="false" class="tt-suggestion autocomplete-item"></li>'
        };
    }();
    var css = function () {
        "use strict";
        var css;
        if ($(".redesign-search-page").length === 0 && $(".job-search-hero-block").length === 0 && $(".reinvent-locations-hero-module").length === 0) {
            css = {
                wrapper: {
                    position: "relative",
                    display: "inline-block"
                },
                hint: {
                    position: "absolute",
                    top: "0",
                    left: "0",
                    borderColor: "transparent",
                    boxShadow: "none",
                    opacity: "1"
                },
                input: {
                    position: "relative",
                    verticalAlign: "top",
                    backgroundColor: "transparent"
                },
                inputWithNoHint: {
                    position: "relative",
                    verticalAlign: "top"
                },
                dropdown: {
                    position: "absolute",
                    top: "100%",
                    left: "0",
                    zIndex: "100",
                    display: "none"
                },
                suggestions: {
                    display: "block"
                },
                suggestion: {
                    whiteSpace: "nowrap",
                    cursor: "pointer"
                },
                suggestionChild: {
                    whiteSpace: "normal"
                },
                ltr: {
                    left: "0",
                    right: "auto"
                },
                rtl: {
                    left: "auto",
                    right: " 0"
                }
            };
        }
        else {
            css = {
                wrapper: {
                    position: "relative",
                    display: "initial"
                },
                hint: {
                    position: "relative",
                    top: "0",
                    left: "0",
                    borderColor: "transparent",
                    boxShadow: "none",
                    opacity: "1",
                    display: "none"
                },
                input: {
                    position: "relative",
                    verticalAlign: "top",
                    backgroundColor: "white"
                },
                inputWithNoHint: {
                    position: "relative",
                    verticalAlign: "top"
                },
                dropdown: {
                    position: "relative",
                    top: "100%",
                    left: "0",
                    zIndex: "100"
                },
                suggestions: {
                    display: "block"
                },
                suggestion: {
                    whiteSpace: "nowrap",
                    cursor: "pointer"
                },
                suggestionChild: {
                    whiteSpace: "normal"
                },
                ltr: {
                    left: "0",
                    right: "auto"
                },
                rtl: {
                    left: "auto",
                    right: " 0"
                }
            };
        }

        if (_.isMsie()) {
            _.mixin(css.input, {
                backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
            });
        }
        if (_.isMsie() && _.isMsie() <= 7) {
            _.mixin(css.input, {
                marginTop: "-1px"
            });
        }
        return css;
    }();
    var EventBus = function () {
        "use strict";
        var namespace = "typeahead:";
        function EventBus(o) {
            if (!o || !o.el) {
                $.error("EventBus initialized without el");
            }
            this.$el = $(o.el);
        }
        _.mixin(EventBus.prototype, {
            trigger: function (type) {
                var args = [].slice.call(arguments, 1);
                this.$el.trigger(namespace + type, args);
            }
        });
        return EventBus;
    }();
    var EventEmitter = function () {
        "use strict";
        var splitter = /\s+/, nextTick = getNextTick();
        return {
            onSync: onSync,
            onAsync: onAsync,
            off: off,
            trigger: trigger
        };
        function on(method, types, cb, context) {
            var type;
            if (!cb) {
                return this;
            }
            types = types.split(splitter);
            cb = context ? bindContext(cb, context) : cb;
            this._callbacks = this._callbacks || {};
            while (type = types.shift()) {
                this._callbacks[type] = this._callbacks[type] || {
                    sync: [],
                    async: []
                };
                this._callbacks[type][method].push(cb);
            }
            return this;
        };
        function onAsync(types, cb, context) {
            return on.call(this, "async", types, cb, context);
        };
        function onSync(types, cb, context) {
            return on.call(this, "sync", types, cb, context);
        };
        function off(types) {
            var type;
            if (!this._callbacks) {
                return this;
            }
            types = types.split(splitter);
            while (type = types.shift()) {
                delete this._callbacks[type];
            }
            return this;
        };
        function trigger(types) {
            var type, callbacks, args, syncFlush, asyncFlush;
            if (!this._callbacks) {
                return this;
            }
            types = types.split(splitter);
            args = [].slice.call(arguments, 1);
            while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
                syncFlush = getFlush(callbacks.sync, this, [type].concat(args));
                asyncFlush = getFlush(callbacks.async, this, [type].concat(args));
                syncFlush() && nextTick(asyncFlush);
            }
            return this;
        };
        function getFlush(callbacks, context, args) {
            return flush;
            function flush() {
                var cancelled;
                for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
                    cancelled = callbacks[i].apply(context, args) === false;
                }
                return !cancelled;
            }
        };
        function getNextTick() {
            var nextTickFn;
            if (window.setImmediate) {
                nextTickFn = function nextTickSetImmediate(fn) {
                    setImmediate(function () {
                        fn();
                    });
                };
            } else {
                nextTickFn = function nextTickSetTimeout(fn) {
                    setTimeout(function () {
                        fn();
                    }, 0);
                };
            }
            return nextTickFn;
        };
        function bindContext(fn, context) {
            return fn.bind ? fn.bind(context) : function () {
                fn.apply(context, [].slice.call(arguments, 0));
            };
        };
    }();
    var highlight = function (doc) {
        "use strict";
        var defaults = {
            node: null,
            pattern: null,
            tagName: "strong",
            className: null,
            wordsOnly: false,
            caseSensitive: false
        };

        return function hightlight(o) {
            var regex;
            o = _.mixin({}, defaults, o);
            if (!o.node || !o.pattern) {
                return;
            }
            o.pattern = _.isArray(o.pattern) ? o.pattern : [o.pattern];
            regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
            traverse(o.node, hightlightTextNode);
            function hightlightTextNode(textNode) {
                var match, patternNode, wrapperNode;
                if (match = regex.exec(textNode.data)) {
                    wrapperNode = doc.createElement(o.tagName);
                    o.className && (wrapperNode.className = o.className);
                    patternNode = textNode.splitText(match.index);
                    patternNode.splitText(match[0].length);
                    wrapperNode.appendChild(patternNode.cloneNode(true));
                    textNode.parentNode.replaceChild(wrapperNode, patternNode);
                }
                return !!match;
            };
            function traverse(el, hightlightTextNode) {
                var childNode, TEXT_NODE_TYPE = 3;
                for (var i = 0; i < el.childNodes.length; i++) {
                    childNode = el.childNodes[i];
                    if (childNode.nodeType === TEXT_NODE_TYPE) {
                        i += hightlightTextNode(childNode) ? 1 : 0;
                    } else {
                        traverse(childNode, hightlightTextNode);
                    }
                }
            };
        };
        function getRegex(patterns, caseSensitive, wordsOnly) {
            var escapedPatterns = [], regexStr;
            for (var i = 0, len = patterns.length; i < len; i++) {
                escapedPatterns.push(_.escapeRegExChars(patterns[i]));
            }
            regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
            return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
        };
    }(window.document);
    var Input = function () {
        "use strict";
        var specialKeyCodeMap;
        specialKeyCodeMap = {
            9: "tab",
            27: "esc",
            37: "left",
            39: "right",
            13: "enter",
            38: "up",
            40: "down"
        };
        function Input(o) {
            var that = this, onBlur, onFocus, onKeydown, onInput;
            o = o || {};
            if (!o.input) {
                $.error("input is missing");
            }
            onBlur = _.bind(this._onBlur, this);
            onFocus = _.bind(this._onFocus, this);
            onKeydown = _.bind(this._onKeydown, this);
            onInput = _.bind(this._onInput, this);
            this.$hint = $(o.hint);
            this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
            if (this.$hint.length === 0) {
                this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
            }
            if (!_.isMsie()) {
                this.$input.on("input.tt", onInput);
            } else {
                this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function ($e) {
                    if (specialKeyCodeMap[$e.which || $e.keyCode]) {
                        return;
                    }
                    _.defer(_.bind(that._onInput, that, $e));
                });
            }
            this.query = this.$input.val();
            this.$overflowHelper = buildOverflowHelper(this.$input);
        };
        Input.normalizeQuery = function (str) {
            return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
        };
        _.mixin(Input.prototype, EventEmitter, {
            _onBlur: function onBlur() {
                this.resetInputValue();
                this.trigger("blurred");
            },
            _onFocus: function onFocus() {
                this.trigger("focused");
            },
            _onKeydown: function onKeydown($e) {
                var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
                this._managePreventDefault(keyName, $e);
                if (keyName && this._shouldTrigger(keyName, $e)) {
                    this.trigger(keyName + "Keyed", $e);
                }
            },
            _onInput: function onInput() {
                this._checkInputValue();
            },
            _managePreventDefault: function managePreventDefault(keyName, $e) {
                var preventDefault, hintValue, inputValue;
                switch (keyName) {
                    case "tab":
                        hintValue = this.getHint();
                        inputValue = this.getInputValue();
                        preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
                        break;

                    case "up":
                    case "down":
                        preventDefault = !withModifier($e);
                        break;

                    default:
                        preventDefault = false;
                }
                preventDefault && $e.preventDefault();
            },
            _shouldTrigger: function shouldTrigger(keyName, $e) {
                var trigger;
                switch (keyName) {
                    case "tab":
                        trigger = !withModifier($e);
                        break;

                    default:
                        trigger = true;
                }
                return trigger;
            },
            _checkInputValue: function checkInputValue() {
                var inputValue, areEquivalent, hasDifferentWhitespace;
                inputValue = this.getInputValue();
                areEquivalent = areQueriesEquivalent(inputValue, this.query);
                hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
                this.query = inputValue;
                if (!areEquivalent) {
                    this.trigger("queryChanged", this.query);
                } else if (hasDifferentWhitespace) {
                    this.trigger("whitespaceChanged", this.query);
                }
            },
            focus: function focus() {
                this.$input.trigger("focus");
            },
            blur: function blur() {
                this.$input.trigger("blur");
            },
            getQuery: function getQuery() {
                return this.query;
            },
            setQuery: function setQuery(query) {
                this.query = query;
            },
            getInputValue: function getInputValue() {
                return this.$input.val();
            },
            setInputValue: function setInputValue(value, silent) {
                this.$input.val(value);
                silent ? this.clearHint() : this._checkInputValue();
            },
            resetInputValue: function resetInputValue() {
                this.setInputValue(this.query, true);
            },
            getHint: function getHint() {
                return this.$hint.val();
            },
            setHint: function setHint(value) {
                this.$hint.val(value);
            },
            clearHint: function clearHint() {
                this.setHint("");
            },
            clearHintIfInvalid: function clearHintIfInvalid() {
                var val, hint, valIsPrefixOfHint, isValid;
                val = this.getInputValue();
                hint = this.getHint();
                valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
                isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
                !isValid && this.clearHint();
            },
            getLanguageDirection: function getLanguageDirection() {
                return (this.$input.css("direction") || "ltr").toLowerCase();
            },
            hasOverflow: function hasOverflow() {
                var constraint = this.$input.width() - 2;
                this.$overflowHelper.text(this.getInputValue());
                return this.$overflowHelper.width() >= constraint;
            },
            isCursorAtEnd: function () {
                var valueLength, selectionStart, range;
                valueLength = this.$input.val().length;
                selectionStart = this.$input[0].selectionStart;
                if (_.isNumber(selectionStart)) {
                    return selectionStart === valueLength;
                } else if (document.selection) {
                    range = document.selection.createRange();
                    range.moveStart("character", -valueLength);
                    return valueLength === range.text.length;
                }
                return true;
            },
            destroy: function destroy() {
                this.$hint.off(".tt");
                this.$input.off(".tt");
                this.$hint = this.$input = this.$overflowHelper = null;
            }
        });
        return Input;
        function buildOverflowHelper($input) {
            return $('<pre aria-hidden="true"></pre>').css({
                position: "absolute",
                visibility: "hidden",
                whiteSpace: "pre",
                fontFamily: $input.css("font-family"),
                fontSize: $input.css("font-size"),
                fontStyle: $input.css("font-style"),
                fontVariant: $input.css("font-variant"),
                fontWeight: $input.css("font-weight"),
                wordSpacing: $input.css("word-spacing"),
                letterSpacing: $input.css("letter-spacing"),
                textIndent: $input.css("text-indent"),
                textRendering: $input.css("text-rendering"),
                textTransform: $input.css("text-transform")
            }).insertAfter($input);
        };
        function areQueriesEquivalent(a, b) {
            return Input.normalizeQuery(a) === Input.normalizeQuery(b);
        };
        function withModifier($e) {
            return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
        };
    }();
    var Dataset = function () {
        "use strict";
        var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
        function Dataset(o) {
            o = o || {};
            o.templates = o.templates || {};
            if (!o.source) {
                $.error("missing source");
            }
            if (o.name && !isValidName(o.name)) {
                $.error("invalid dataset name: " + o.name);
            }
            this.query = null;
            this.highlight = !!o.highlight;
            this.name = o.name || _.getUniqueId();
            this.source = o.source;
            this.displayFn = getDisplayFn(o.display || o.displayKey);
            this.templates = getTemplates(o.templates, this.displayFn);
            this.$el = $(html.dataset.replace("%CLASS%", this.name));
        };
        Dataset.extractDatasetName = function extractDatasetName(el) {
            return $(el).data(datasetKey);
        };
        Dataset.extractValue = function extractDatum(el) {
            return $(el).data(valueKey);
        };
        Dataset.extractDatum = function extractDatum(el) {
            return $(el).data(datumKey);
        };
        _.mixin(Dataset.prototype, EventEmitter, {
            _render: function render(query, suggestions) {
                if (!this.$el) {
                    return;
                }
                var that = this, hasSuggestions;
                this.$el.empty();
                hasSuggestions = suggestions && suggestions.length;
                if (!hasSuggestions && this.templates.empty) {
                    this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
                } else if (hasSuggestions) {
                    this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
                }
                this.trigger("rendered");
                function getEmptyHtml() {
                    return that.templates.empty({
                        query: query,
                        isEmpty: true
                    });
                }
                function getSuggestionsHtml() {
                    var $suggestions, nodes;
                    $suggestions = $(html.suggestions).css(css.suggestions);
                    nodes = _.map(suggestions, getSuggestionNode);
                    $suggestions.append.apply($suggestions, nodes);
                    if (($('.redesign-search-page .search-hero-keywords').is(':focus')) || ($('.job-search-hero-block .search-bar').is(':focus')) || $('.reinvent-locations-hero-module .reinvent-location-keywords').is(':focus')) {
                        that.highlight && highlight({
                            className: "tt-highlight corporate-regular",
                            node: $suggestions[0],
                            pattern: query
                        });
                    }
                    else {
                        that.highlight && highlight({
                            className: "tt-highlight",
                            node: $suggestions[0],
                            pattern: query
                        });
                    }
                    return $suggestions;
                    function getSuggestionNode(suggestion) {
                        var $el;
                        $el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
                        $el.children().each(function () {
                            $(this).css(css.suggestionChild);
                        });
                        return $el;
                    }
                }
                function getHeaderHtml() {
                    return that.templates.header({
                        query: query,
                        isEmpty: !hasSuggestions
                    });
                }
                function getFooterHtml() {
                    return that.templates.footer({
                        query: query,
                        isEmpty: !hasSuggestions
                    });
                }
            },
            getRoot: function getRoot() {
                return this.$el;
            },
            update: function update(query) {
                var that = this;
                this.query = query;
                this.canceled = false;
                this.source(query, render);
                function render(suggestions) {
                    if (!that.canceled && query === that.query) {
                        that._render(query, suggestions);
                    }
                }
            },
            cancel: function cancel() {
                this.canceled = true;
            },
            clear: function clear() {
                this.cancel();
                this.$el.empty();
                this.trigger("rendered");
            },
            isEmpty: function isEmpty() {
                return this.$el.is(":empty");
            },
            destroy: function destroy() {
                this.$el = null;
            }
        });
        return Dataset;
        function getDisplayFn(display) {
            display = display || "value";
            return _.isFunction(display) ? display : displayFn;
            function displayFn(obj) {
                return obj[display];
            }
        };
        function getTemplates(templates, displayFn) {
            return {
                empty: templates.empty && _.templatify(templates.empty),
                header: templates.header && _.templatify(templates.header),
                footer: templates.footer && _.templatify(templates.footer),
                suggestion: templates.suggestion || suggestionTemplate
            };
            function suggestionTemplate(context) {
                // Job Search Hero - change tags for smart suggestion
                if (($(".job-search-hero-block")).is(":visible")) {
                    return "<a class='suggestion-item'>" + displayFn(context) + "</a>";
                }
                else if (($(".about-hero-wrapper")).is(":visible")) {
                    return "<a class='suggestion-item'>" + displayFn(context) + "</a>";
                }
                else if ($('.redesign-search-page .search-hero-keywords').is(':focus')) {
                    return "<p>" + "<strong>" + displayFn(context) + "</strong>" + "</p>";
                }
                else if ($('.reinvent-locations-hero-module .reinvent-location-keywords').is(':focus')) {
                    return "<p>" + "<strong>" + displayFn(context) + "</strong>" + "</p>";
                }
                else {
                    return "<p>" + displayFn(context) + "</p>";
                }
            }
        };
        function isValidName(str) {
            return /^[_a-zA-Z0-9-]+$/.test(str);
        };
    }();
    var Dropdown = function () {
        "use strict";
        function Dropdown(o) {
            var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
            o = o || {};
            if (!o.menu) {
                $.error("menu is required");
            }
            this.isOpen = false;
            this.isEmpty = true;
            this.datasets = _.map(o.datasets, initializeDataset);
            onSuggestionClick = _.bind(this._onSuggestionClick, this);
            onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
            onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
            this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
            _.each(this.datasets, function (dataset) {
                that.$menu.append(dataset.getRoot());
                dataset.onSync("rendered", that._onRendered, that);
            });
        };
        _.mixin(Dropdown.prototype, EventEmitter, {
            _onSuggestionClick: function onSuggestionClick($e) {
                this.trigger("suggestionClicked", $($e.currentTarget));
            },
            _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
                this._removeCursor();
                this._setCursor($($e.currentTarget), true);
            },
            _onSuggestionMouseLeave: function onSuggestionMouseLeave() {
                this._removeCursor();
            },
            _onRendered: function onRendered() {
                this.isEmpty = _.every(this.datasets, isDatasetEmpty);
                this.isEmpty ? this._hide() : this.isOpen && this._show();
                this.trigger("datasetRendered");
                function isDatasetEmpty(dataset) {
                    return dataset.isEmpty();
                }
            },
            _hide: function () {
                this.$menu.hide();
            },
            _show: function () {
                this.$menu.css("display", "block");

                if ($('.reinvent-location-keywords').length === 0) {
                    if ($('.redesign-search-page .tt-suggestions').is(':visible')) {
                        var isShowViewAll = ($('#search-form-label.search-hero-keywords.autocomplete-search-field').attr("data-view-all-results-toggle") !== null && typeof $('#search-form-label.search-hero-keywords.autocomplete-search-field').attr("data-view-all-results-toggle") !== 'undefined') ? $('#search-form-label.search-hero-keywords.autocomplete-search-field').attr("data-view-all-results-toggle").toLowerCase() : "";

                        if (isShowViewAll === "true") {
                            var viewAllKeyword = $(".redesign-search-page .tt-input.search-hero-keywords").val();
                            var viewAllContainer = ".tt-suggestion.view-all-text-container";
                            var $viewAllAttr = $('.search-hero-keywords').attr('data-view-all-results');
                            var $viewAllText = $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .view-all-text');
                            var $viewAllArrow = $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .arrow-strong');

                            jQuery('<li/>', {
                                class: 'tt-suggestion view-all-text-container'
                            }).appendTo('.redesign-search-page .tt-dataset-keywordSuggestions .tt-suggestions');
                            jQuery('<p/>', {
                                class: 'view-all-container',
                            }).appendTo(viewAllContainer);
                            jQuery('<a/>', {
                                class: 'view-all-text cta d-inline corporate-regular',
                                html: $viewAllAttr
                            }).appendTo('.tt-suggestion.view-all-text-container .view-all-container');
                            jQuery('<a/>', {
                                class: 'arrow-strong cta-arrow corporate-regular'
                            }).appendTo('.tt-suggestion.view-all-text-container .view-all-container');

                            $(viewAllContainer).attr('data-attribute-view-all-keyword', viewAllKeyword);
                            $viewAllText.attr('data-analytics-link-name', $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .view-all-text').text().toLowerCase());
                            $viewAllText.attr('data-analytics-content-type', 'search activity');
                            $viewAllArrow.attr('data-analytics-link-name', $('.tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion .view-all-text').text().toLowerCase());
                            $viewAllArrow.attr('data-analytics-content-type', 'search activity');
                        }
                    }
                    else if ($('.job-search-hero-block-form .tt-suggestions').is(':visible')) {

                        if ($('.job-search-hero-block .tt-dataset-keywordSuggestions .tt-suggestions').is(':visible')) {
                            var smartSuggestValue = $('.job-search-hero-block .tt-suggestions .tt-suggestion .suggestion-item');

                            for (var i = 0; i < smartSuggestValue.length; i++) {
                                smartSuggestValue[i].setAttribute("data-analytics-link-name", smartSuggestValue[i].innerText.toLowerCase());
                                smartSuggestValue[i].setAttribute("data-analytics-content-type", "careers job search");
                            }
                        }
                    }
                }
            },
            _getSuggestions: function getSuggestions() {
                $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').on("mouseenter", function () {
                    $('.recent-searches-container.tt-dataset-keywordRecentSearches .recent-search').removeAttr('id', 'selectedOption');
                    $(this).addClass('selected');
                }).on("mouseleave",
                    function () {
                        $(this).removeClass("selected");
                    }
                );
                return this.$menu.find(".tt-suggestion");
            },
            _getCursor: function getCursor() {
                return this.$menu.find(".tt-cursor").first();
            },
            _setCursor: function setCursor($el, silent) {
                $el.first().addClass("tt-cursor");
                !silent && this.trigger("cursorMoved");
            },
            _removeCursor: function removeCursor() {
                this._getCursor().removeClass("tt-cursor");
            },
            _moveCursor: function moveCursor(increment) {
                if (!$('.redesign-search-page .tt-dataset-keywordRecentSearches').is(':visible')) {
                    if (!$('.job-search-hero-block .tt-dataset-keywordRecentSearches').is(':visible')) {
                        var $suggestions, $oldCursor, newCursorIndex, $newCursor;
                        if (!this.isOpen) {
                            return;
                        }
                        $oldCursor = this._getCursor();
                        $suggestions = this._getSuggestions();
                        this._removeCursor();
                        newCursorIndex = $suggestions.index($oldCursor) + increment;
                        newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
                        if (newCursorIndex === -1) {
                            this.trigger("cursorRemoved");
                            return;
                        } else if (newCursorIndex < -1) {
                            newCursorIndex = $suggestions.length - 1;
                        }
                        this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
                        this._ensureVisible($newCursor);
                    }
                }
            },
            _ensureVisible: function ensureVisible($el) {
                var elTop, elBottom, menuScrollTop, menuHeight;
                elTop = $el.position().top;
                elBottom = elTop + $el.outerHeight(true);
                menuScrollTop = this.$menu.scrollTop();
                menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
                if (elTop < 0) {
                    this.$menu.scrollTop(menuScrollTop + elTop);
                } else if (menuHeight < elBottom) {
                    this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
                }
            },
            close: function close() {
                if (this.isOpen) {
                    this.isOpen = false;
                    this._removeCursor();
                    this._hide();
                    this.trigger("closed");
                }
            },
            open: function open() {
                if (!this.isOpen) {
                    this.isOpen = true;
                    !this.isEmpty && this._show();
                    this.trigger("opened");
                }
            },
            setLanguageDirection: function setLanguageDirection(dir) {
                this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
            },
            moveCursorUp: function moveCursorUp() {
                this._moveCursor(-1);
            },
            moveCursorDown: function moveCursorDown() {
                this._moveCursor(+1);
            },
            getDatumForSuggestion: function getDatumForSuggestion($el) {
                var datum = null;
                var $suggestionInnerText = "";
                var $suggestionTextForAnalytics = "";
                if ($el.length) {
                    datum = {
                        raw: Dataset.extractDatum($el),
                        value: Dataset.extractValue($el),
                        datasetName: Dataset.extractDatasetName($el)
                    };

                    var $searchHeroSuggestion = $('.search-hero-form .tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion p');
                    $searchHeroSuggestion.attr('data-analytics-content-type', 'search activity');
                    for (var counter = 0; counter < $('.search-hero-form .tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion p').length; counter++) {
                        $suggestionInnerText = $searchHeroSuggestion[counter].innerText;
                        $suggestionTextForAnalytics = $searchHeroSuggestion[counter];
                        $suggestionTextForAnalytics.setAttribute('data-analytics-link-name', $suggestionInnerText.toLowerCase());
                    }

                    if ($('.reinvent-location-hero-content-container').length !== 0) {
                        var $locationHeroSuggestion = $('.reinvent-location-hero-content-container .tt-dataset-keywordSuggestions .tt-suggestions .tt-suggestion p');
                        var $locationResultBlock = $(".reinvent-location-result-area");
                        var $reinventLocationModule = $('.reinvent-locations-hero-module');

                        $locationHeroSuggestion.attr('data-analytics-content-type', 'engagement');
                        $locationHeroSuggestion.attr('data-linktype', 'engagement');

                        for (var index = 0; index < $locationHeroSuggestion.length; index++) {
                            $suggestionInnerText = $locationHeroSuggestion[index].innerText;
                            $suggestionTextForAnalytics = $locationHeroSuggestion[index];
                            $suggestionTextForAnalytics.setAttribute('data-analytics-link-name', $suggestionInnerText.toLowerCase());
                            if ($locationResultBlock.length === 0 && $reinventLocationModule.attr('data-attribute-hero-home-link') !== "") {
                                $suggestionTextForAnalytics.setAttribute('href', $reinventLocationModule.attr('data-attribute-hero-home-link').replace('{0}', siteName));
                            }
                        }
                    }
                }
                return datum;
            },
            getDatumForCursor: function getDatumForCursor() {
                return this.getDatumForSuggestion(this._getCursor().first());
            },
            getDatumForTopSuggestion: function getDatumForTopSuggestion() {
                return this.getDatumForSuggestion(this._getSuggestions().first());
            },
            update: function update(query) {
                _.each(this.datasets, updateDataset);
                function updateDataset(dataset) {
                    dataset.update(query);
                }
            },
            empty: function empty() {
                _.each(this.datasets, clearDataset);
                this.isEmpty = true;
                function clearDataset(dataset) {
                    dataset.clear();
                }
            },
            isVisible: function isVisible() {
                return this.isOpen && !this.isEmpty;
            },
            destroy: function destroy() {
                this.$menu.off(".tt");
                this.$menu = null;
                _.each(this.datasets, destroyDataset);
                function destroyDataset(dataset) {
                    dataset.destroy();
                }
            }
        });
        return Dropdown;
        function initializeDataset(oDataset) {
            return new Dataset(oDataset);
        };
    }();
    var Typeahead = function () {
        "use strict";
        var attrsKey = "ttAttrs";
        function Typeahead(o) {
            var $menu, $input, $hint;
            o = o || {};
            if (!o.input) {
                $.error("missing input");
            }
            this.isActivated = false;
            this.autoselect = !!o.autoselect;
            this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
            this.$node = buildDom(o.input, o.withHint);
            $menu = this.$node.find(".tt-dropdown-menu");
            $input = this.$node.find(".tt-input");
            $hint = this.$node.find(".tt-hint");
            $input.on("blur.tt", function ($e) {
                var active, isActive, hasActive;
                active = document.activeElement;
                isActive = $menu.is(active);
                hasActive = $menu.has(active).length > 0;
                if (_.isMsie() && (isActive || hasActive)) {
                    $e.preventDefault();
                    $e.stopImmediatePropagation();
                    _.defer(function () {
                        $input.trigger("focus");
                    });
                }
            });
            $menu.on("mousedown.tt", function ($e) {
                $e.preventDefault();
            });
            this.eventBus = o.eventBus || new EventBus({
                el: $input
            });
            this.dropdown = new Dropdown({
                menu: $menu,
                datasets: o.datasets
            }).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
            this.input = new Input({
                input: $input,
                hint: $hint
            }).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
            this._setLanguageDirection();
        };
        _.mixin(Typeahead.prototype, {
            _onSuggestionClicked: function onSuggestionClicked(type, $el) {
                var datum;
                if (datum = this.dropdown.getDatumForSuggestion($el)) {
                    this._select(datum);
                }
            },
            _onCursorMoved: function onCursorMoved() {
                var datum = this.dropdown.getDatumForCursor();
                this.input.setInputValue(datum.value, true);
                this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
            },
            _onCursorRemoved: function onCursorRemoved() {
                this.input.resetInputValue();
                this._updateHint();
            },
            _onDatasetRendered: function onDatasetRendered() {
                this._updateHint();
            },
            _onOpened: function onOpened() {
                this._updateHint();
                this.eventBus.trigger("opened");
            },
            _onClosed: function onClosed() {
                this.input.clearHint();
                this.eventBus.trigger("closed");
            },
            _onFocused: function onFocused() {
                this.isActivated = true;
                this.dropdown.open();
            },
            _onBlurred: function onBlurred() {
                this.isActivated = false;
                this.dropdown.empty();
                this.dropdown.close();
            },
            _onEnterKeyed: function onEnterKeyed(type, $e) {
                var cursorDatum, topSuggestionDatum;
                cursorDatum = this.dropdown.getDatumForCursor();
                topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();

                if (cursorDatum) {
                    this._select(cursorDatum);
                    $e.preventDefault();
                } else if (this.autoselect && topSuggestionDatum) {
                    this._select(topSuggestionDatum);
                    $e.preventDefault();
                }
            },
            _onTabKeyed: function onTabKeyed(type, $e) {
                var datum;
                if (datum = this.dropdown.getDatumForCursor()) {
                    this._select(datum);
                    $e.preventDefault();
                } else {
                    this._autocomplete(true);
                }
            },
            _onEscKeyed: function onEscKeyed() {
                this.dropdown.close();
                this.input.resetInputValue();
            },
            _onUpKeyed: function onUpKeyed() {
                var query = this.input.getQuery();
                this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
                this.dropdown.open();
                if ($('.tt-suggestion.view-all-text-container').length > 1) {
                    $('.tt-suggestion.view-all-text-container')[0].remove();
                }

            },
            _onDownKeyed: function onDownKeyed() {
                var query = this.input.getQuery();
                this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
                this.dropdown.open();
                if ($('.tt-suggestion.view-all-text-container').length > 1) {
                    $('.tt-suggestion.view-all-text-container')[0].remove();
                }
            },
            _onLeftKeyed: function onLeftKeyed() {
                this.dir === "rtl" && this._autocomplete();
            },
            _onRightKeyed: function onRightKeyed() {
                if (!$('.redesign-search-page .search-hero-keywords').is(':focus')) {
                    if (!$('.job-search-hero-block .search-bar').is(':focus')) {
                        this.dir === "ltr" && this._autocomplete();
                    }
                }
            },
            _onQueryChanged: function onQueryChanged(e, query) {
                this.input.clearHintIfInvalid();
                query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
                this.dropdown.open();
                this._setLanguageDirection();
            },
            _onWhitespaceChanged: function onWhitespaceChanged() {
                this._updateHint();
                this.dropdown.open();
            },
            _setLanguageDirection: function setLanguageDirection() {
                var dir;
                if (this.dir !== (dir = this.input.getLanguageDirection())) {
                    this.dir = dir;
                    this.$node.css("direction", dir);
                    this.dropdown.setLanguageDirection(dir);
                }
            },
            _updateHint: function updateHint() {
                var datum, val, query, escapedQuery, frontMatchRegEx, match;
                datum = this.dropdown.getDatumForTopSuggestion();
                if (!$('.redesign-search-page .search-hero-keywords').is(':focus')) {
                    if (!$('.job-search-hero-block .search-bar').is(':focus')) {
                        if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
                            val = this.input.getInputValue();
                            query = Input.normalizeQuery(val);
                            escapedQuery = _.escapeRegExChars(query);
                            frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
                            match = frontMatchRegEx.exec(datum.value);
                            match ? this.input.setHint(val + match[1]) : this.input.clearHint();
                        } else {
                            this.input.clearHint();
                        }
                    }
                }
            },
            _autocomplete: function autocomplete(laxCursor) {
                var hint, query, isCursorAtEnd, datum;
                hint = this.input.getHint();
                query = this.input.getQuery();
                isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
                if (hint && query !== hint && isCursorAtEnd) {
                    datum = this.dropdown.getDatumForTopSuggestion();
                    datum && this.input.setInputValue(datum.value);
                    this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
                }
            },
            _select: function select(datum) {
                this.input.setQuery(datum.value);
                this.input.setInputValue(datum.value, true);
                this._setLanguageDirection();
                this.eventBus.trigger("selected", datum.raw, datum.datasetName);
                this.dropdown.close();
                _.defer(_.bind(this.dropdown.empty, this.dropdown));
            },
            open: function open() {
                this.dropdown.open();
            },
            close: function close() {
                this.dropdown.close();
            },
            setVal: function setVal(val) {
                val = _.toStr(val);
                if (this.isActivated) {
                    this.input.setInputValue(val);
                } else {
                    this.input.setQuery(val);
                    this.input.setInputValue(val, true);
                }
                this._setLanguageDirection();
            },
            getVal: function getVal() {
                return this.input.getQuery();
            },
            destroy: function destroy() {
                this.input.destroy();
                this.dropdown.destroy();
                destroyDomStructure(this.$node);
                this.$node = null;
            }
        });
        return Typeahead;
        function buildDom(input, withHint) {
            var $input, $wrapper, $dropdown, $hint;
            $input = $(input);
            $wrapper = $(html.wrapper).css(css.wrapper);
            $dropdown = $(html.dropdown).css(css.dropdown);
            $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
            $hint.val("").removeData().addClass("tt-hint").prop("readonly", true).prop("required", false).removeAttr("name placeholder").attr({
                autocomplete: "off",
                spellcheck: "false",
                id: "search-form-clone"
            });
            $input.data(attrsKey, {
                dir: $input.attr("dir"),
                autocomplete: $input.attr("autocomplete"),
                spellcheck: $input.attr("spellcheck"),
                style: $input.attr("style")
            });
            $input.addClass("tt-input").attr({
                autocomplete: "off",
                spellcheck: false
            }).css(withHint ? css.input : css.inputWithNoHint);
            try {
                !$input.attr("dir") && $input.attr("dir", "auto");
            } catch (e) { }
            return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
        };
        function getBackgroundStyles($el) {
            return {
                backgroundAttachment: $el.css("background-attachment"),
                backgroundClip: $el.css("background-clip"),
                backgroundColor: $el.css("background-color"),
                backgroundImage: $el.css("background-image"),
                backgroundOrigin: $el.css("background-origin"),
                backgroundPosition: $el.css("background-position"),
                backgroundRepeat: $el.css("background-repeat"),
                backgroundSize: $el.css("background-size")
            };
        };
        function destroyDomStructure($node) {
            var $input = $node.find(".tt-input");
            _.each($input.data(attrsKey), function (val, key) {
                _.isUndefined(val) ? $input.prop(key, false) : $input.attr(key, val);
            });
            $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
            $node.remove();
        };
    }();
    (function () {
        "use strict";
        var old, typeaheadKey, methods;
        old = $.fn.typeahead;
        typeaheadKey = "ttTypeahead";
        methods = {
            initialize: function initialize(o, datasets) {
                datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
                o = o || {};
                return this.each(attach);
                function attach() {
                    var $input = $(this), eventBus, typeahead;
                    _.each(datasets, function (d) {
                        d.highlight = !!o.highlight;
                    });
                    typeahead = new Typeahead({
                        input: $input,
                        eventBus: eventBus = new EventBus({
                            el: $input
                        }),
                        withHint: _.isUndefined(o.hint) ? true : !!o.hint,
                        minLength: o.minLength,
                        autoselect: o.autoselect,
                        datasets: datasets
                    });
                    $input.data(typeaheadKey, typeahead);
                };
            },
            open: function open() {
                return this.each(openTypeahead);
                function openTypeahead() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.open();
                    }
                }
            },
            close: function close() {
                return this.each(closeTypeahead);
                function closeTypeahead() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.close();
                    }
                }
            },
            val: function val(newVal) {
                return !arguments.length ? getVal(this.first()) : this.each(setVal);
                function setVal() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.setVal(newVal);
                    }
                }
                function getVal($input) {
                    var typeahead, query;
                    if (typeahead = $input.data(typeaheadKey)) {
                        query = typeahead.getVal();
                    }
                    return query;
                }
            },
            destroy: function destroy() {
                return this.each(unattach);
                function unattach() {
                    var $input = $(this), typeahead;
                    if (typeahead = $input.data(typeaheadKey)) {
                        typeahead.destroy();
                        $input.removeData(typeaheadKey);
                    }
                }
            }
        };
        $.fn.typeahead = function (method) {
            var tts;
            if (methods[method] && method !== "initialize") {
                tts = this.filter(function () {
                    return !!$(this).data(typeaheadKey);
                });
                return methods[method].apply(tts, [].slice.call(arguments, 1));
            } else {
                return methods.initialize.apply(this, arguments);
            }
        };
        $.fn.typeahead.noConflict = function noConflict() {
            $.fn.typeahead = old;
            return this;
        };
    })();
})(window.jQuery);

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\packery.pkgd.js
/*version3*/
/*!
 * Packery PACKAGED v1.2.3
 * bin-packing layout library
 * http://packery.metafizzy.co
 *
 * Commercial use requires one-time purchase of a commercial license
 * http://packery.metafizzy.co/license.html
 *
 * Non-commercial use is licensed under the GPL v3 License
 *
 * Copyright 2014 Metafizzy
 */

/**
 * Bridget makes jQuery widgets
 * v1.0.1
 */

( function( window ) {



    // -------------------------- utils -------------------------- //
    
    var slice = Array.prototype.slice;
    
    function noop() {}
    
    // -------------------------- definition -------------------------- //
    
    function defineBridget( $ ) {
    
    // bail if no jQuery
    if ( !$ ) {
      return;
    }
    
    // -------------------------- addOptionMethod -------------------------- //
    
    /**
     * adds option method -> $().plugin('option', {...})
     * @param {Function} PluginClass - constructor class
     */
    function addOptionMethod( PluginClass ) {
      // don't overwrite original option method
      if ( PluginClass.prototype.option ) {
        return;
      }
    
      // option setter
      PluginClass.prototype.option = function( opts ) {
        // bail out if not an object
        if ( !$.isPlainObject( opts ) ){
          return;
        }
        this.options = $.extend( true, this.options, opts );
      };
        };
    
    
    // -------------------------- plugin bridge -------------------------- //
    
    // helper function for logging errors
    // $.error breaks jQuery chaining
    var logError = typeof console === 'undefined' ? noop :
      function( message ) {
        console.error( message );
      };
    
    /**
     * jQuery plugin bridge, access methods like $elem.plugin('method')
     * @param {String} namespace - plugin name
     * @param {Function} PluginClass - constructor class
     */
    function bridge( namespace, PluginClass ) {
      // add to jQuery fn namespace
      $.fn[ namespace ] = function( options ) {
        if ( typeof options === 'string' ) {
          // call plugin method when first argument is a string
          // get arguments for method
          var args = slice.call( arguments, 1 );
    
          for ( var i=0, len = this.length; i < len; i++ ) {
            var elem = this[i];
            var instance = $.data( elem, namespace );
            if ( !instance ) {
              logError( "cannot call methods on " + namespace + " prior to initialization; " +
                "attempted to call '" + options + "'" );
              continue;
            }
            if (typeof (instance[options]) !== "function" || options.charAt(0) === '_') {
              logError( "no such method '" + options + "' for " + namespace + " instance" );
              continue;
            }
    
            // trigger method with arguments
            var returnValue = instance[ options ].apply( instance, args );
    
            // break look and return first value if provided
            if ( returnValue !== undefined ) {
              return returnValue;
            }
          }
          // return this if no return value
          return this;
        } else {
          return this.each( function() {
            var instance = $.data( this, namespace );
            if ( instance ) {
              // apply options & init
              instance.option( options );
              instance._init();
            } else {
              // initialize new instance
              instance = new PluginClass( this, options );
              $.data( this, namespace, instance );
            }
          });
        }
      };
    
    }
    
    // -------------------------- bridget -------------------------- //
    
    /**
     * converts a Prototypical class into a proper jQuery plugin
     *   the class must have a ._init method
     * @param {String} namespace - plugin name, used in $().pluginName
     * @param {Function} PluginClass - constructor class
     */
    $.bridget = function( namespace, PluginClass ) {
      addOptionMethod( PluginClass );
      bridge( namespace, PluginClass );
    };
    
    return $.bridget;
    
    };
    
    // transport
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'jquery-bridget/jquery.bridget',[ 'jquery' ], defineBridget );
    } else {
      // get jquery from browser global
      defineBridget( window.jQuery );
    }
    
    })( window );
    
    /*!
     * classie - class helper functions
     * from bonzo https://github.com/ded/bonzo
     * 
     * classie.has( elem, 'my-class' ) -> true/false
     * classie.add( elem, 'my-new-class' )
     * classie.remove( elem, 'my-unwanted-class' )
     * classie.toggle( elem, 'my-class' )
     */
    
    /*jshint browser: true, strict: true, undef: true */
    /*global define: false */
    
    ( function( window ) {
    
    
    
    // class helper functions from bonzo https://github.com/ded/bonzo
    
    function classReg( className ) {
      return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
        };
    
    // classList support for class management
    // altho to be fair, the api sucks because it won't accept multiple classes at once
    var hasClass, addClass, removeClass;
    
    if ( 'classList' in document.documentElement ) {
      hasClass = function( elem, c ) {
        return elem.classList.contains( c );
      };
      addClass = function( elem, c ) {
        elem.classList.add( c );
      };
      removeClass = function( elem, c ) {
        elem.classList.remove( c );
      };
    }
    else {
      hasClass = function( elem, c ) {
        return classReg( c ).test( elem.className );
      };
      addClass = function( elem, c ) {
        if ( !hasClass( elem, c ) ) {
          elem.className = elem.className + ' ' + c;
        }
      };
      removeClass = function( elem, c ) {
        elem.className = elem.className.replace( classReg( c ), ' ' );
      };
    }
    
    function toggleClass( elem, c ) {
      var fn = hasClass( elem, c ) ? removeClass : addClass;
      fn( elem, c );
        };
    
    var classie = {
      // full names
      hasClass: hasClass,
      addClass: addClass,
      removeClass: removeClass,
      toggleClass: toggleClass,
      // short names
      has: hasClass,
      add: addClass,
      remove: removeClass,
      toggle: toggleClass
    };
    
    // transport
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'classie/classie',classie );
    } else {
      // browser global
      window.classie = classie;
    }
    
    })( window );
    
    /*!
     * getStyleProperty v1.0.3
     * original by kangax
     * http://perfectionkills.com/feature-testing-css-properties/
     */
    
    /*jshint browser: true, strict: true, undef: true */
    /*global define: false, exports: false, module: false */
    
    ( function( window ) {
    
    
    
    var prefixes = 'Webkit Moz ms Ms O'.split(' ');
    var docElemStyle = document.documentElement.style;
    
    function getStyleProperty( propName ) {
      if ( !propName ) {
        return;
      }
    
      // test standard property first
      if ( typeof docElemStyle[ propName ] === 'string' ) {
        return propName;
      }
    
      // capitalize
      propName = propName.charAt(0).toUpperCase() + propName.slice(1);
    
      // test vendor specific properties
      var prefixed;
      for ( var i=0, len = prefixes.length; i < len; i++ ) {
        prefixed = prefixes[i] + propName;
        if ( typeof docElemStyle[ prefixed ] === 'string' ) {
          return prefixed;
        }
      }
        };
    
    // transport
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'get-style-property/get-style-property',[],function() {
        return getStyleProperty;
      });
    } else if ( typeof exports === 'object' ) {
      // CommonJS for Component
      module.exports = getStyleProperty;
    } else {
      // browser global
      window.getStyleProperty = getStyleProperty;
    }
    
    })( window );
    
    /**
     * getSize v1.1.7
     * measure size of elements
     */
    
    /*jshint browser: true, strict: true, undef: true, unused: true */
    /*global define: false, exports: false, require: false, module: false */
    
    ( function( window, undefined ) {
    
    
    
    // -------------------------- helpers -------------------------- //
    
    var getComputedStyle = window.getComputedStyle;
    var getStyle = getComputedStyle ?
      function( elem ) {
        return getComputedStyle( elem, null );
      } :
      function( elem ) {
        return elem.currentStyle;
      };
    
    // get a number from a string, not a percentage
    function getStyleSize( value ) {
      var num = parseFloat( value );
      // not a percent like '100%', and a number
      var isValid = value.indexOf('%') === -1 && !isNaN( num );
      return isValid && num;
    }
    
    // -------------------------- measurements -------------------------- //
    
    var measurements = [
      'paddingLeft',
      'paddingRight',
      'paddingTop',
      'paddingBottom',
      'marginLeft',
      'marginRight',
      'marginTop',
      'marginBottom',
      'borderLeftWidth',
      'borderRightWidth',
      'borderTopWidth',
      'borderBottomWidth'
    ];
    
    function getZeroSize() {
      var size = {
        width: 0,
        height: 0,
        innerWidth: 0,
        innerHeight: 0,
        outerWidth: 0,
        outerHeight: 0
      };
      for ( var i=0, len = measurements.length; i < len; i++ ) {
        var measurement = measurements[i];
        size[ measurement ] = 0;
      }
      return size;
        };
    
    
    
    function defineGetSize( getStyleProperty ) {
    
    // -------------------------- box sizing -------------------------- //
    
    var boxSizingProp = getStyleProperty('boxSizing');
    var isBoxSizeOuter;
    
    /**
     * WebKit measures the outer-width on style.width on border-box elems
     * IE & Firefox measures the inner-width
     */
    ( function() {
      if ( !boxSizingProp ) {
        return;
      }
    
      var div = document.createElement('div');
      div.style.width = '200px';
      div.style.padding = '1px 2px 3px 4px';
      div.style.borderStyle = 'solid';
      div.style.borderWidth = '1px 2px 3px 4px';
      div.style[ boxSizingProp ] = 'border-box';
    
      var body = document.body || document.documentElement;
      body.appendChild( div );
      var style = getStyle( div );
    
      isBoxSizeOuter = getStyleSize( style.width ) === 200;
      body.removeChild( div );
    })();
    
    
    // -------------------------- getSize -------------------------- //
    
    function getSize( elem ) {
      // use querySeletor if elem is string
      if ( typeof elem === 'string' ) {
        elem = document.querySelector( elem );
      }
    
      // do not proceed on non-objects
      if ( !elem || typeof elem !== 'object' || !elem.nodeType ) {
        return;
      }
    
      var style = getStyle( elem );
    
      // if hidden, everything is 0
      if ( style.display === 'none' ) {
        return getZeroSize();
      }
    
      var size = {};
      size.width = elem.offsetWidth;
      size.height = elem.offsetHeight;
    
      var isBorderBox = size.isBorderBox = !!( boxSizingProp &&
        style[ boxSizingProp ] && style[ boxSizingProp ] === 'border-box' );
    
      // get all measurements
      for ( var i=0, len = measurements.length; i < len; i++ ) {
        var measurement = measurements[i];
        var value = style[ measurement ];
        value = mungeNonPixel( elem, value );
        var num = parseFloat( value );
        // any 'auto', 'medium' value will be 0
        size[ measurement ] = !isNaN( num ) ? num : 0;
      }
    
      var paddingWidth = size.paddingLeft + size.paddingRight;
      var paddingHeight = size.paddingTop + size.paddingBottom;
      var marginWidth = size.marginLeft + size.marginRight;
      var marginHeight = size.marginTop + size.marginBottom;
      var borderWidth = size.borderLeftWidth + size.borderRightWidth;
      var borderHeight = size.borderTopWidth + size.borderBottomWidth;
    
      var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;
    
      // overwrite width and height if we can get it from style
      var styleWidth = getStyleSize( style.width );
      if ( styleWidth !== false ) {
        size.width = styleWidth +
          // add padding and border unless it's already including it
          ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
      }
    
      var styleHeight = getStyleSize( style.height );
      if ( styleHeight !== false ) {
        size.height = styleHeight +
          // add padding and border unless it's already including it
          ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
      }
    
      size.innerWidth = size.width - ( paddingWidth + borderWidth );
      size.innerHeight = size.height - ( paddingHeight + borderHeight );
    
      size.outerWidth = size.width + marginWidth;
      size.outerHeight = size.height + marginHeight;
    
      return size;
        };
    
    // IE8 returns percent values, not pixels
    // taken from jQuery's curCSS
    function mungeNonPixel( elem, value ) {
      // IE8 and has percent value
      if ( getComputedStyle || value.indexOf('%') === -1 ) {
        return value;
      }
      var style = elem.style;
      // Remember the original values
      var left = style.left;
      var rs = elem.runtimeStyle;
      var rsLeft = rs && rs.left;
    
      // Put in the new values to get a computed value out
      if ( rsLeft ) {
        rs.left = elem.currentStyle.left;
      }
      style.left = value;
      value = style.pixelLeft;
    
      // Revert the changed values
      style.left = left;
      if ( rsLeft ) {
        rs.left = rsLeft;
      }
    
      return value;
        };
    
    return getSize;
    
        };
    
    // transport
    if ( typeof define === 'function' && define.amd ) {
      // AMD for RequireJS
      define( 'get-size/get-size',[ 'get-style-property/get-style-property' ], defineGetSize );
    } else if ( typeof exports === 'object' ) {
      // CommonJS for Component
      module.exports = defineGetSize( require('get-style-property') );
    } else {
      // browser global
      window.getSize = defineGetSize( window.getStyleProperty );
    }
    
    })( window );
    
    /*!
     * eventie v1.0.5
     * event binding helper
     *   eventie.bind( elem, 'click', myFn )
     *   eventie.unbind( elem, 'click', myFn )
     * MIT license
     */
    
    /*jshint browser: true, undef: true, unused: true */
    /*global define: false, module: false */
    
    ( function( window ) {
    
    
    
    var docElem = document.documentElement;
    
    var bind = function() {};
    
    function getIEEvent( obj ) {
      var event = window.event;
      // add event.target
      event.target = event.target || event.srcElement || obj;
      return event;
        };
    
    if ( docElem.addEventListener ) {
      bind = function( obj, type, fn ) {
        obj.addEventListener( type, fn, false );
      };
    } else if ( docElem.attachEvent ) {
      bind = function( obj, type, fn ) {
        obj[ type + fn ] = fn.handleEvent ?
          function() {
            var event = getIEEvent( obj );
            fn.handleEvent.call( fn, event );
          } :
          function() {
            var event = getIEEvent( obj );
            fn.call( obj, event );
          };
        obj.attachEvent( "on" + type, obj[ type + fn ] );
      };
    }
    
    var unbind = function() {};
    
    if ( docElem.removeEventListener ) {
      unbind = function( obj, type, fn ) {
        obj.removeEventListener( type, fn, false );
      };
    } else if ( docElem.detachEvent ) {
      unbind = function( obj, type, fn ) {
        obj.detachEvent( "on" + type, obj[ type + fn ] );
        try {
          delete obj[ type + fn ];
        } catch ( err ) {
          // can't delete window object properties
          obj[ type + fn ] = undefined;
        }
      };
    }
    
    var eventie = {
      bind: bind,
      unbind: unbind
    };
    
    // ----- module definition ----- //
    
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'eventie/eventie',eventie );
    } else if ( typeof exports === 'object' ) {
      // CommonJS
      module.exports = eventie;
    } else {
      // browser global
      window.eventie = eventie;
    }
    
    })( this );
    
    /*!
     * docReady
     * Cross browser DOMContentLoaded event emitter
     */
    
    /*jshint browser: true, strict: true, undef: true, unused: true*/
    /*global define: false */
    
    ( function( window ) {
    
    
    
    var document = window.document;
    // collection of functions to be triggered on ready
    var queue = [];
    
    function docReady( fn ) {
      // throw out non-functions
      if ( typeof fn !== 'function' ) {
        return;
      }
    
      if ( docReady.isReady ) {
        // ready now, hit it
        fn();
      } else {
        // queue function when ready
        queue.push( fn );
      }
        };
    
    docReady.isReady = false;
    
    // triggered on various doc ready events
    function init( event ) {
      // bail if IE8 document is not ready just yet
      var isIE8NotReady = event.type === 'readystatechange' && document.readyState !== 'complete';
      if ( docReady.isReady || isIE8NotReady ) {
        return;
      }
      docReady.isReady = true;
    
      // process queue
      for ( var i=0, len = queue.length; i < len; i++ ) {
        var fn = queue[i];
        fn();
      }
        };
    
    function defineDocReady( eventie ) {
      eventie.bind( document, 'DOMContentLoaded', init );
      eventie.bind( document, 'readystatechange', init );
      eventie.bind( window, 'load', init );
    
      return docReady;
        };
    
    // transport
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      // if RequireJS, then doc is already ready
      docReady.isReady = typeof requirejs === 'function';
      define( 'doc-ready/doc-ready',[ 'eventie/eventie' ], defineDocReady );
    } else {
      // browser global
      window.docReady = defineDocReady( window.eventie );
    }
    
    })( this );
    
    /*!
     * EventEmitter v4.2.7 - git.io/ee
     * Oliver Caldwell
     * MIT license
     * @preserve
     */
    
    (function () {
      
    
      /**
       * Class for managing events.
       * Can be extended to provide event functionality in other classes.
       *
       * @class EventEmitter Manages event registering and emitting.
       */
        function EventEmitter() { };
    
      // Shortcuts to improve speed and size
      var proto = EventEmitter.prototype;
      var exports = this;
      var originalGlobalValue = exports.EventEmitter;
    
      /**
       * Finds the index of the listener for the event in it's storage array.
       *
       * @param {Function[]} listeners Array of listeners to search through.
       * @param {Function} listener Method to look for.
       * @return {Number} Index of the specified listener, -1 if not found
       * @api private
       */
      function indexOfListener(listeners, listener) {
        var i = listeners.length;
        while (i--) {
          if (listeners[i].listener === listener) {
            return i;
          }
        }
    
        return -1;
        };
    
      /**
       * Alias a method while keeping the context correct, to allow for overwriting of target method.
       *
       * @param {String} name The name of the target method.
       * @return {Function} The aliased method
       * @api private
       */
      function alias(name) {
        return function aliasClosure() {
          return this[name].apply(this, arguments);
        };
        };
    
      /**
       * Returns the listener array for the specified event.
       * Will initialise the event object and listener arrays if required.
       * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
       * Each property in the object response is an array of listener functions.
       *
       * @param {String|RegExp} evt Name of the event to return the listeners from.
       * @return {Function[]|Object} All listener functions for the event.
       */
      proto.getListeners = function getListeners(evt) {
        var events = this._getEvents();
        var response;
        var key;
    
        // Return a concatenated array of all matching events if
        // the selector is a regular expression.
        if (evt instanceof RegExp) {
          response = {};
          for (key in events) {
            if (events.hasOwnProperty(key) && evt.test(key)) {
              response[key] = events[key];
            }
          }
        }
        else {
          response = events[evt] || (events[evt] = []);
        }
    
        return response;
      };
    
      /**
       * Takes a list of listener objects and flattens it into a list of listener functions.
       *
       * @param {Object[]} listeners Raw listener objects.
       * @return {Function[]} Just the listener functions.
       */
      proto.flattenListeners = function flattenListeners(listeners) {
        var flatListeners = [];
        var i;
    
        for (i = 0; i < listeners.length; i += 1) {
          flatListeners.push(listeners[i].listener);
        }
    
        return flatListeners;
      };
    
      /**
       * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
       *
       * @param {String|RegExp} evt Name of the event to return the listeners from.
       * @return {Object} All listener functions for an event in an object.
       */
      proto.getListenersAsObject = function getListenersAsObject(evt) {
        var listeners = this.getListeners(evt);
        var response;
    
        if (listeners instanceof Array) {
          response = {};
          response[evt] = listeners;
        }
    
        return response || listeners;
      };
    
      /**
       * Adds a listener function to the specified event.
       * The listener will not be added if it is a duplicate.
       * If the listener returns true then it will be removed after it is called.
       * If you pass a regular expression as the event name then the listener will be added to all events that match it.
       *
       * @param {String|RegExp} evt Name of the event to attach the listener to.
       * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.addListener = function addListener(evt, listener) {
        var listeners = this.getListenersAsObject(evt);
        var listenerIsWrapped = typeof listener === 'object';
        var key;
    
        for (key in listeners) {
          if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
            listeners[key].push(listenerIsWrapped ? listener : {
              listener: listener,
              once: false
            });
          }
        }
    
        return this;
      };
    
      /**
       * Alias of addListener
       */
      proto.on = alias('addListener');
    
      /**
       * Semi-alias of addListener. It will add a listener that will be
       * automatically removed after it's first execution.
       *
       * @param {String|RegExp} evt Name of the event to attach the listener to.
       * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.addOnceListener = function addOnceListener(evt, listener) {
        return this.addListener(evt, {
          listener: listener,
          once: true
        });
      };
    
      /**
       * Alias of addOnceListener.
       */
      proto.once = alias('addOnceListener');
    
      /**
       * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
       * You need to tell it what event names should be matched by a regex.
       *
       * @param {String} evt Name of the event to create.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.defineEvent = function defineEvent(evt) {
        this.getListeners(evt);
        return this;
      };
    
      /**
       * Uses defineEvent to define multiple events.
       *
       * @param {String[]} evts An array of event names to define.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.defineEvents = function defineEvents(evts) {
        for (var i = 0; i < evts.length; i += 1) {
          this.defineEvent(evts[i]);
        }
        return this;
      };
    
      /**
       * Removes a listener function from the specified event.
       * When passed a regular expression as the event name, it will remove the listener from all events that match it.
       *
       * @param {String|RegExp} evt Name of the event to remove the listener from.
       * @param {Function} listener Method to remove from the event.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.removeListener = function removeListener(evt, listener) {
        var listeners = this.getListenersAsObject(evt);
        var index;
        var key;
    
        for (key in listeners) {
          if (listeners.hasOwnProperty(key)) {
            index = indexOfListener(listeners[key], listener);
    
            if (index !== -1) {
              listeners[key].splice(index, 1);
            }
          }
        }
    
        return this;
      };
    
      /**
       * Alias of removeListener
       */
      proto.off = alias('removeListener');
    
      /**
       * Adds listeners in bulk using the manipulateListeners method.
       * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
       * You can also pass it a regular expression to add the array of listeners to all events that match it.
       * Yeah, this function does quite a bit. That's probably a bad thing.
       *
       * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
       * @param {Function[]} [listeners] An optional array of listener functions to add.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.addListeners = function addListeners(evt, listeners) {
        // Pass through to manipulateListeners
        return this.manipulateListeners(false, evt, listeners);
      };
    
      /**
       * Removes listeners in bulk using the manipulateListeners method.
       * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
       * You can also pass it an event name and an array of listeners to be removed.
       * You can also pass it a regular expression to remove the listeners from all events that match it.
       *
       * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
       * @param {Function[]} [listeners] An optional array of listener functions to remove.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.removeListeners = function removeListeners(evt, listeners) {
        // Pass through to manipulateListeners
        return this.manipulateListeners(true, evt, listeners);
      };
    
      /**
       * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
       * The first argument will determine if the listeners are removed (true) or added (false).
       * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
       * You can also pass it an event name and an array of listeners to be added/removed.
       * You can also pass it a regular expression to manipulate the listeners of all events that match it.
       *
       * @param {Boolean} remove True if you want to remove listeners, false if you want to add.
       * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
       * @param {Function[]} [listeners] An optional array of listener functions to add/remove.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
        var i;
        var value;
        var single = remove ? this.removeListener : this.addListener;
        var multiple = remove ? this.removeListeners : this.addListeners;
    
        // If evt is an object then pass each of it's properties to this method
        if (typeof evt === 'object' && !(evt instanceof RegExp)) {
          for (i in evt) {
            if (evt.hasOwnProperty(i) && (value = evt[i])) {
              // Pass the single listener straight through to the singular method
              if (typeof value === 'function') {
                single.call(this, i, value);
              }
              else {
                // Otherwise pass back to the multiple function
                multiple.call(this, i, value);
              }
            }
          }
        }
        else {
          // So evt must be a string
          // And listeners must be an array of listeners
          // Loop over it and pass each one to the multiple method
          i = listeners.length;
          while (i--) {
            single.call(this, evt, listeners[i]);
          }
        }
    
        return this;
      };
    
      /**
       * Removes all listeners from a specified event.
       * If you do not specify an event then all listeners will be removed.
       * That means every event will be emptied.
       * You can also pass a regex to remove all events that match it.
       *
       * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.removeEvent = function removeEvent(evt) {
        var type = typeof evt;
        var events = this._getEvents();
        var key;
    
        // Remove different things depending on the state of evt
        if (type === 'string') {
          // Remove all listeners for the specified event
          delete events[evt];
        }
        else if (evt instanceof RegExp) {
          // Remove all events matching the regex.
          for (key in events) {
            if (events.hasOwnProperty(key) && evt.test(key)) {
              delete events[key];
            }
          }
        }
        else {
          // Remove all listeners in all events
          delete this._events;
        }
    
        return this;
      };
    
      /**
       * Alias of removeEvent.
       *
       * Added to mirror the node API.
       */
      proto.removeAllListeners = alias('removeEvent');
    
      /**
       * Emits an event of your choice.
       * When emitted, every listener attached to that event will be executed.
       * If you pass the optional argument array then those arguments will be passed to every listener upon execution.
       * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
       * So they will not arrive within the array on the other side, they will be separate.
       * You can also pass a regular expression to emit to all events that match it.
       *
       * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
       * @param {Array} [args] Optional array of arguments to be passed to each listener.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.emitEvent = function emitEvent(evt, args) {
        var listeners = this.getListenersAsObject(evt);
        var listener;
        var i;
        var key;
        var response;
    
        for (key in listeners) {
          if (listeners.hasOwnProperty(key)) {
            i = listeners[key].length;
    
            while (i--) {
              // If the listener returns true then it shall be removed from the event
              // The function is executed either with a basic call or an apply if there is an args array
              listener = listeners[key][i];
    
              if (listener.once === true) {
                this.removeListener(evt, listener.listener);
              }
    
              response = listener.listener.apply(this, args || []);
    
              if (response === this._getOnceReturnValue()) {
                this.removeListener(evt, listener.listener);
              }
            }
          }
        }
    
        return this;
      };
    
      /**
       * Alias of emitEvent
       */
      proto.trigger = alias('emitEvent');
    
      /**
       * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
       * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
       *
       * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
       * @param {...*} Optional additional arguments to be passed to each listener.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.emit = function emit(evt) {
        var args = Array.prototype.slice.call(arguments, 1);
        return this.emitEvent(evt, args);
      };
    
      /**
       * Sets the current value to check against when executing listeners. If a
       * listeners return value matches the one set here then it will be removed
       * after execution. This value defaults to true.
       *
       * @param {*} value The new value to check for when executing listeners.
       * @return {Object} Current instance of EventEmitter for chaining.
       */
      proto.setOnceReturnValue = function setOnceReturnValue(value) {
        this._onceReturnValue = value;
        return this;
      };
    
      /**
       * Fetches the current value to check against when executing listeners. If
       * the listeners return value matches this one then it should be removed
       * automatically. It will return true by default.
       *
       * @return {*|Boolean} The current value to check for or the default, true.
       * @api private
       */
      proto._getOnceReturnValue = function _getOnceReturnValue() {
        if (this.hasOwnProperty('_onceReturnValue')) {
          return this._onceReturnValue;
        }
        else {
          return true;
        }
      };
    
      /**
       * Fetches the events object and creates one if required.
       *
       * @return {Object} The events storage object.
       * @api private
       */
      proto._getEvents = function _getEvents() {
        return this._events || (this._events = {});
      };
    
      /**
       * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
       *
       * @return {Function} Non conflicting EventEmitter class.
       */
      EventEmitter.noConflict = function noConflict() {
        exports.EventEmitter = originalGlobalValue;
        return EventEmitter;
      };
    
      // Expose the class either via AMD, CommonJS or the global object
      if (typeof define === 'function' && define.amd) {
        define('eventEmitter/EventEmitter',[],function () {
          return EventEmitter;
        });
      }
      else if (typeof module === 'object' && module.exports){
        module.exports = EventEmitter;
      }
      else {
        this.EventEmitter = EventEmitter;
      }
    }.call(this));
    
    /**
     * matchesSelector helper v1.0.1
     *
     * @name matchesSelector
     *   @param {Element} elem
     *   @param {String} selector
     */
    
    /*jshint browser: true, strict: true, undef: true, unused: true */
    /*global define: false */
    
    ( function( global, ElemProto ) {
    
      
    
      var matchesMethod = ( function() {
        // check un-prefixed
        if ( ElemProto.matchesSelector ) {
          return 'matchesSelector';
        }
        // check vendor prefixes
        var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];
    
        for ( var i=0, len = prefixes.length; i < len; i++ ) {
          var prefix = prefixes[i];
          var method = prefix + 'MatchesSelector';
          if ( ElemProto[ method ] ) {
            return method;
          }
        }
      })();
    
      // ----- match ----- //
    
      function match( elem, selector ) {
        return elem[ matchesMethod ]( selector );
        };
    
      // ----- appendToFragment ----- //
    
      function checkParent( elem ) {
        // not needed if already has parent
        if ( elem.parentNode ) {
          return;
        }
        var fragment = document.createDocumentFragment();
        fragment.appendChild( elem );
        };
    
      // ----- query ----- //
    
      // fall back to using QSA
      // thx @jonathantneal https://gist.github.com/3062955
      function query( elem, selector ) {
        // append to fragment if no parent
        checkParent( elem );
    
        // match elem with all selected elems of parent
        var elems = elem.parentNode.querySelectorAll( selector );
        for ( var i=0, len = elems.length; i < len; i++ ) {
          // return true if match
          if ( elems[i] === elem ) {
            return true;
          }
        }
        // otherwise return false
        return false;
        };
    
      // ----- matchChild ----- //
    
      function matchChild( elem, selector ) {
        checkParent( elem );
        return match( elem, selector );
        };
    
      // ----- matchesSelector ----- //
    
      var matchesSelector;
    
      if ( matchesMethod ) {
        // IE9 supports matchesSelector, but doesn't work on orphaned elems
        // check for that
        var div = document.createElement('div');
        var supportsOrphans = match( div, 'div' );
        matchesSelector = supportsOrphans ? match : matchChild;
      } else {
        matchesSelector = query;
      }
    
      // transport
      if ( typeof define === 'function' && define.amd ) {
        // AMD
        define( 'matches-selector/matches-selector',[],function() {
          return matchesSelector;
        });
      } else {
        // browser global
        window.matchesSelector = matchesSelector;
      }
    
    })( this, Element.prototype );
    
    /**
     * Outlayer Item
     */
    
    ( function( window ) {
    
    
    
    // ----- get style ----- //
    
    var defView = document.defaultView;
    
    var getStyle = defView && defView.getComputedStyle ?
      function( elem ) {
        return defView.getComputedStyle( elem, null );
      } :
      function( elem ) {
        return elem.currentStyle;
      };
    
    
    // extend objects
    function extend( a, b ) {
      for ( var prop in b ) {
        a[ prop ] = b[ prop ];
      }
      return a;
        };
    
    function isEmptyObj( obj ) {
      for ( var prop in obj ) {
        return false;
      }
      prop = null;
      return true;
        };
    
    // http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
    function toDash( str ) {
      return str.replace( /([A-Z])/g, function( $1 ){
        return '-' + $1.toLowerCase();
      });
    }
    
    // -------------------------- Outlayer definition -------------------------- //
    
    function outlayerItemDefinition( EventEmitter, getSize, getStyleProperty ) {
    
    // -------------------------- CSS3 support -------------------------- //
    
    var transitionProperty = getStyleProperty('transition');
    var transformProperty = getStyleProperty('transform');
    var supportsCSS3 = transitionProperty && transformProperty;
    var is3d = !!getStyleProperty('perspective');
    
    var transitionEndEvent = {
      WebkitTransition: 'webkitTransitionEnd',
      MozTransition: 'transitionend',
      OTransition: 'otransitionend',
      transition: 'transitionend'
    }[ transitionProperty ];
    
    // properties that could have vendor prefix
    var prefixableProperties = [
      'transform',
      'transition',
      'transitionDuration',
      'transitionProperty'
    ];
    
    // cache all vendor properties
    var vendorProperties = ( function() {
      var cache = {};
      for ( var i=0, len = prefixableProperties.length; i < len; i++ ) {
        var prop = prefixableProperties[i];
        var supportedProp = getStyleProperty( prop );
        if ( supportedProp && supportedProp !== prop ) {
          cache[ prop ] = supportedProp;
        }
      }
      return cache;
    })();
    
    // -------------------------- Item -------------------------- //
    
    function Item( element, layout ) {
      if ( !element ) {
        return;
      }
    
      this.element = element;
      // parent layout class, i.e. Masonry, Isotope, or Packery
      this.layout = layout;
      this.position = {
        x: 0,
        y: 0
      };
    
      this._create();
        };
    
    // inherit EventEmitter
    extend( Item.prototype, EventEmitter.prototype );
    
    Item.prototype._create = function() {
      // transition objects
      this._transn = {
        ingProperties: {},
        clean: {},
        onEnd: {}
      };
    
      this.css({
        position: 'absolute'
      });
    };
    
    // trigger specified handler for event type
    Item.prototype.handleEvent = function( event ) {
      var method = 'on' + event.type;
      if ( this[ method ] ) {
        this[ method ]( event );
      }
    };
    
    Item.prototype.getSize = function() {
      this.size = getSize( this.element );
    };
    
    /**
     * apply CSS styles to element
     * @param {Object} style
     */
    Item.prototype.css = function( style ) {
      var elemStyle = this.element.style;
    
      for ( var prop in style ) {
        // use vendor property if available
        var supportedProp = vendorProperties[ prop ] || prop;
        elemStyle[ supportedProp ] = style[ prop ];
      }
    };
    
     // measure position, and sets it
    Item.prototype.getPosition = function() {
      var style = getStyle( this.element );
      var layoutOptions = this.layout.options;
      var isOriginLeft = layoutOptions.isOriginLeft;
      var isOriginTop = layoutOptions.isOriginTop;
      var x = parseInt( style[ isOriginLeft ? 'left' : 'right' ], 10 );
      var y = parseInt( style[ isOriginTop ? 'top' : 'bottom' ], 10 );
    
      // clean up 'auto' or other non-integer values
      x = isNaN( x ) ? 0 : x;
      y = isNaN( y ) ? 0 : y;
      // remove padding from measurement
      var layoutSize = this.layout.size;
      x -= isOriginLeft ? layoutSize.paddingLeft : layoutSize.paddingRight;
      y -= isOriginTop ? layoutSize.paddingTop : layoutSize.paddingBottom;
    
      this.position.x = x;
      this.position.y = y;
    };
    
    // set settled position, apply padding
    Item.prototype.layoutPosition = function() {
      var layoutSize = this.layout.size;
      var layoutOptions = this.layout.options;
      var style = {};
    
      if ( layoutOptions.isOriginLeft ) {
        style.left = ( this.position.x + layoutSize.paddingLeft ) + 'px';
        // reset other property
        style.right = '';
      } else {
        style.right = ( this.position.x + layoutSize.paddingRight ) + 'px';
        style.left = '';
      }
    
      if ( layoutOptions.isOriginTop ) {
        style.top = ( this.position.y + layoutSize.paddingTop ) + 'px';
        style.bottom = '';
      } else {
        style.bottom = ( this.position.y + layoutSize.paddingBottom ) + 'px';
        style.top = '';
      }
    
      this.css( style );
      this.emitEvent( 'layout', [ this ] );
    };
    
    
    // transform translate function
    var translate = is3d ?
      function( x, y ) {
        return 'translate3d(' + x + 'px, ' + y + 'px, 0)';
      } :
      function( x, y ) {
        return 'translate(' + x + 'px, ' + y + 'px)';
      };
    
    
    Item.prototype._transitionTo = function( x, y ) {
      this.getPosition();
      // get current x & y from top/left
      var curX = this.position.x;
      var curY = this.position.y;
    
      var compareX = parseInt( x, 10 );
      var compareY = parseInt( y, 10 );
      var didNotMove = compareX === this.position.x && compareY === this.position.y;
    
      // save end position
      this.setPosition( x, y );
    
      // if did not move and not transitioning, just go to layout
      if ( didNotMove && !this.isTransitioning ) {
        this.layoutPosition();
        return;
      }
    
      var transX = x - curX;
      var transY = y - curY;
      var transitionStyle = {};
      // flip cooridinates if origin on right or bottom
      var layoutOptions = this.layout.options;
      transX = layoutOptions.isOriginLeft ? transX : -transX;
      transY = layoutOptions.isOriginTop ? transY : -transY;
      transitionStyle.transform = translate( transX, transY );
    
      this.transition({
        to: transitionStyle,
        onTransitionEnd: {
          transform: this.layoutPosition
        },
        isCleaning: true
      });
    };
    
    // non transition + transform support
    Item.prototype.goTo = function( x, y ) {
      this.setPosition( x, y );
      this.layoutPosition();
    };
    
    // use transition and transforms if supported
    Item.prototype.moveTo = supportsCSS3 ?
      Item.prototype._transitionTo : Item.prototype.goTo;
    
    Item.prototype.setPosition = function( x, y ) {
      this.position.x = parseInt( x, 10 );
      this.position.y = parseInt( y, 10 );
    };
    
    // ----- transition ----- //
    
    /**
     * @param {Object} style - CSS
     * @param {Function} onTransitionEnd
     */
    
    // non transition, just trigger callback
    Item.prototype._nonTransition = function( args ) {
      this.css( args.to );
      if ( args.isCleaning ) {
        this._removeStyles( args.to );
      }
      for ( var prop in args.onTransitionEnd ) {
        args.onTransitionEnd[ prop ].call( this );
      }
    };
    
    /**
     * proper transition
     * @param {Object} args - arguments
     *   @param {Object} to - style to transition to
     *   @param {Object} from - style to start transition from
     *   @param {Boolean} isCleaning - removes transition styles after transition
     *   @param {Function} onTransitionEnd - callback
     */
    Item.prototype._transition = function( args ) {
      // redirect to nonTransition if no transition duration
      if ( !parseFloat( this.layout.options.transitionDuration ) ) {
        this._nonTransition( args );
        return;
      }
    
      var _transition = this._transn;
      // keep track of onTransitionEnd callback by css property
      for ( var prop in args.onTransitionEnd ) {
        _transition.onEnd[ prop ] = args.onTransitionEnd[ prop ];
      }
      // keep track of properties that are transitioning
      for ( prop in args.to ) {
        _transition.ingProperties[ prop ] = true;
        // keep track of properties to clean up when transition is done
        if ( args.isCleaning ) {
          _transition.clean[ prop ] = true;
        }
      }
    
      // set from styles
      if ( args.from ) {
        this.css( args.from );
        // force redraw. http://blog.alexmaccaw.com/css-transitions
        var h = this.element.offsetHeight;
        // hack for JSHint to hush about unused var
        h = null;
      }
      // enable transition
      this.enableTransition( args.to );
      // set styles that are transitioning
      this.css( args.to );
    
      this.isTransitioning = true;
    
    };
    
    var itemTransitionProperties = transformProperty && ( toDash( transformProperty ) +
      ',opacity' );
    
    Item.prototype.enableTransition = function(/* style */) {
      // only enable if not already transitioning
      // bug in IE10 were re-setting transition style will prevent
      // transitionend event from triggering
      if ( this.isTransitioning ) {
        return;
      }
    
      // make transition: foo, bar, baz from style object
      // TODO uncomment this bit when IE10 bug is resolved
      // var transitionValue = [];
      // for ( var prop in style ) {
      //   // dash-ify camelCased properties like WebkitTransition
      //   transitionValue.push( toDash( prop ) );
      // }
      // enable transition styles
      // HACK always enable transform,opacity for IE10
      this.css({
        transitionProperty: itemTransitionProperties,
        transitionDuration: this.layout.options.transitionDuration
      });
      // listen for transition end event
      this.element.addEventListener( transitionEndEvent, this, false );
    };
    
    Item.prototype.transition = Item.prototype[ transitionProperty ? '_transition' : '_nonTransition' ];
    
    // ----- events ----- //
    
    Item.prototype.onwebkitTransitionEnd = function( event ) {
      this.ontransitionend( event );
    };
    
    Item.prototype.onotransitionend = function( event ) {
      this.ontransitionend( event );
    };
    
    // properties that I munge to make my life easier
    var dashedVendorProperties = {
      '-webkit-transform': 'transform',
      '-moz-transform': 'transform',
      '-o-transform': 'transform'
    };
    
    Item.prototype.ontransitionend = function( event ) {
      // disregard bubbled events from children
      if ( event.target !== this.element ) {
        return;
      }
      var _transition = this._transn;
      // get property name of transitioned property, convert to prefix-free
      var propertyName = dashedVendorProperties[ event.propertyName ] || event.propertyName;
    
      // remove property that has completed transitioning
      delete _transition.ingProperties[ propertyName ];
      // check if any properties are still transitioning
      if ( isEmptyObj( _transition.ingProperties ) ) {
        // all properties have completed transitioning
        this.disableTransition();
      }
      // clean style
      if ( propertyName in _transition.clean ) {
        // clean up style
        this.element.style[ event.propertyName ] = '';
        delete _transition.clean[ propertyName ];
      }
      // trigger onTransitionEnd callback
      if ( propertyName in _transition.onEnd ) {
        var onTransitionEnd = _transition.onEnd[ propertyName ];
        onTransitionEnd.call( this );
        delete _transition.onEnd[ propertyName ];
      }
    
      this.emitEvent( 'transitionEnd', [ this ] );
    };
    
    Item.prototype.disableTransition = function() {
      this.removeTransitionStyles();
      this.element.removeEventListener( transitionEndEvent, this, false );
      this.isTransitioning = false;
    };
    
    /**
     * removes style property from element
     * @param {Object} style
    **/
    Item.prototype._removeStyles = function( style ) {
      // clean up transition styles
      var cleanStyle = {};
      for ( var prop in style ) {
        cleanStyle[ prop ] = '';
      }
      this.css( cleanStyle );
    };
    
    var cleanTransitionStyle = {
      transitionProperty: '',
      transitionDuration: ''
    };
    
    Item.prototype.removeTransitionStyles = function() {
      // remove transition
      this.css( cleanTransitionStyle );
    };
    
    // ----- show/hide/remove ----- //
    
    // remove element from DOM
    Item.prototype.removeElem = function() {
      this.element.parentNode.removeChild( this.element );
      this.emitEvent( 'remove', [ this ] );
    };
    
    Item.prototype.remove = function() {
      // just remove element if no transition support or no transition
      if ( !transitionProperty || !parseFloat( this.layout.options.transitionDuration ) ) {
        this.removeElem();
        return;
      }
    
      // start transition
      var _this = this;
      this.on( 'transitionEnd', function() {
        _this.removeElem();
        return true; // bind once
      });
      this.hide();
    };
    
    Item.prototype.reveal = function() {
      delete this.isHidden;
      // remove display: none
      this.css({ display: '' });
    
      var options = this.layout.options;
      this.transition({
        from: options.hiddenStyle,
        to: options.visibleStyle,
        isCleaning: true
      });
    };
    
    Item.prototype.hide = function() {
      // set flag
      this.isHidden = true;
      // remove display: none
      this.css({ display: '' });
    
      var options = this.layout.options;
      this.transition({
        from: options.visibleStyle,
        to: options.hiddenStyle,
        // keep hidden stuff hidden
        isCleaning: true,
        onTransitionEnd: {
          opacity: function() {
            // check if still hidden
            // during transition, item may have been un-hidden
            if ( this.isHidden ) {
              this.css({ display: 'none' });
            }
          }
        }
      });
    };
    
    Item.prototype.destroy = function() {
      this.css({
        position: '',
        left: '',
        right: '',
        top: '',
        bottom: '',
        transition: '',
        transform: ''
      });
    };
    
    return Item;
    
        };
    
    // -------------------------- transport -------------------------- //
    
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'outlayer/item',[
          'eventEmitter/EventEmitter',
          'get-size/get-size',
          'get-style-property/get-style-property'
        ],
        outlayerItemDefinition );
    } else {
      // browser global
      window.Outlayer = {};
      window.Outlayer.Item = outlayerItemDefinition(
        window.EventEmitter,
        window.getSize,
        window.getStyleProperty
      );
    }
    
    })( window );
    
    /*!
     * Outlayer v1.1.10
     * the brains and guts of a layout library
     * MIT license
     */
    
    ( function( window ) {
    
    
    
    // ----- vars ----- //
    
    var document = window.document;
    var console = window.console;
    var jQuery = window.jQuery;
    
    var noop = function() {};
    
    // -------------------------- helpers -------------------------- //
    
    // extend objects
    function extend( a, b ) {
      for ( var prop in b ) {
        a[ prop ] = b[ prop ];
      }
      return a;
        };
    
    
    var objToString = Object.prototype.toString;
    function isArray( obj ) {
      return objToString.call( obj ) === '[object Array]';
        };
    
    // turn element or nodeList into an array
    function makeArray( obj ) {
      var ary = [];
      if ( isArray( obj ) ) {
        // use object if already an array
        ary = obj;
      } else if ( obj && typeof obj.length === 'number' ) {
        // convert nodeList to array
        for ( var i=0, len = obj.length; i < len; i++ ) {
          ary.push( obj[i] );
        }
      } else {
        // array of single index
        ary.push( obj );
      }
      return ary;
        };
    
    // http://stackoverflow.com/a/384380/182183
    var isElement = ( typeof HTMLElement === 'object' ) ?
      function isElementDOM2( obj ) {
        return obj instanceof HTMLElement;
      } :
      function isElementQuirky( obj ) {
        return obj && typeof obj === 'object' &&
          obj.nodeType === 1 && typeof obj.nodeName === 'string';
      };
    
    // index of helper cause IE8
    var indexOf = Array.prototype.indexOf ? function( ary, obj ) {
        return ary.indexOf( obj );
      } : function( ary, obj ) {
        for ( var i=0, len = ary.length; i < len; i++ ) {
          if ( ary[i] === obj ) {
            return i;
          }
        }
        return -1;
      };
    
    function removeFrom( obj, ary ) {
      var index = indexOf( ary, obj );
      if ( index !== -1 ) {
        ary.splice( index, 1 );
      }
        };
    
    // http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
    function toDashed( str ) {
      return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {
        return $1 + '-' + $2;
      }).toLowerCase();
        };
    
    
    function outlayerDefinition( eventie, docReady, EventEmitter, getSize, matchesSelector, Item ) {
    
    // -------------------------- Outlayer -------------------------- //
    
    // globally unique identifiers
    var GUID = 0;
    // internal store of all Outlayer intances
    var instances = {};
    
    
    /**
     * @param {Element, String} element
     * @param {Object} options
     * @constructor
     */
    function Outlayer( element, options ) {
      // use element as selector string
      if ( typeof element === 'string' ) {
        element = document.querySelector( element );
      }
    
      // bail out if not proper element
      if ( !element || !isElement( element ) ) {
        if ( console ) {
          console.error( 'Bad ' + this.constructor.namespace + ' element: ' + element );
        }
        return;
      }
    
      this.element = element;
    
      // options
      this.options = extend( {}, this.options );
      this.option( options );
    
      // add id for Outlayer.getFromElement
      var id = ++GUID;
      this.element.outlayerGUID = id; // expando
      instances[ id ] = this; // associate via id
    
      // kick it off
      this._create();
    
      if ( this.options.isInitLayout ) {
        this.layout();
      }
        };
    
    // settings are for internal use only
    Outlayer.namespace = 'outlayer';
    Outlayer.Item = Item;
    
    // default options
    Outlayer.prototype.options = {
      containerStyle: {
        position: 'relative'
      },
      isInitLayout: true,
      isOriginLeft: true,
      isOriginTop: true,
      isResizeBound: true,
      // item options
      transitionDuration: '0.4s',
      hiddenStyle: {
        opacity: 0,
        transform: 'scale(0.001)'
      },
      visibleStyle: {
        opacity: 1,
        transform: 'scale(1)'
      }
    };
    
    // inherit EventEmitter
    extend( Outlayer.prototype, EventEmitter.prototype );
    
    /**
     * set options
     * @param {Object} opts
     */
    Outlayer.prototype.option = function( opts ) {
      extend( this.options, opts );
    };
    
    Outlayer.prototype._create = function() {
      // get items from children
      this.reloadItems();
      // elements that affect layout, but are not laid out
      this.stamps = [];
      this.stamp( this.options.stamp );
      // set container style
      extend( this.element.style, this.options.containerStyle );
    
      // bind resize method
      if ( this.options.isResizeBound ) {
        this.bindResize();
      }
    };
    
    // goes through all children again and gets bricks in proper order
    Outlayer.prototype.reloadItems = function() {
      // collection of item elements
      this.items = this._itemize( this.element.children );
    };
    
    
    /**
     * turn elements into Outlayer.Items to be used in layout
     * @param {Array or NodeList or HTMLElement} elems
     * @returns {Array} items - collection of new Outlayer Items
     */
    Outlayer.prototype._itemize = function( elems ) {
    
      var itemElems = this._filterFindItemElements( elems );
      var Item = this.constructor.Item;
    
      // create new Outlayer Items for collection
      var items = [];
      for ( var i=0, len = itemElems.length; i < len; i++ ) {
        var elem = itemElems[i];
        var item = new Item( elem, this );
        items.push( item );
      }
    
      return items;
    };
    
    /**
     * get item elements to be used in layout
     * @param {Array or NodeList or HTMLElement} elems
     * @returns {Array} items - item elements
     */
    Outlayer.prototype._filterFindItemElements = function( elems ) {
      // make array of elems
      elems = makeArray( elems );
      var itemSelector = this.options.itemSelector;
      var itemElems = [];
    
      for ( var i=0, len = elems.length; i < len; i++ ) {
        var elem = elems[i];
        // check that elem is an actual element
        if ( !isElement( elem ) ) {
          continue;
        }
        // filter & find items if we have an item selector
        if ( itemSelector ) {
          // filter siblings
          if ( matchesSelector( elem, itemSelector ) ) {
            itemElems.push( elem );
          }
          // find children
          var childElems = elem.querySelectorAll( itemSelector );
          // concat childElems to filterFound array
          for ( var j=0, jLen = childElems.length; j < jLen; j++ ) {
            itemElems.push( childElems[j] );
          }
        } else {
          itemElems.push( elem );
        }
      }
    
      return itemElems;
    };
    
    /**
     * getter method for getting item elements
     * @returns {Array} elems - collection of item elements
     */
    Outlayer.prototype.getItemElements = function() {
      var elems = [];
      for ( var i=0, len = this.items.length; i < len; i++ ) {
        elems.push( this.items[i].element );
      }
      return elems;
    };
    
    // ----- init & layout ----- //
    
    /**
     * lays out all items
     */
    Outlayer.prototype.layout = function() {
      this._resetLayout();
      this._manageStamps();
    
      // don't animate first layout
      var isInstant = this.options.isLayoutInstant !== undefined ?
        this.options.isLayoutInstant : !this._isLayoutInited;
      this.layoutItems( this.items, isInstant );
    
      // flag for initalized
      this._isLayoutInited = true;
    };
    
    // _init is alias for layout
    Outlayer.prototype._init = Outlayer.prototype.layout;
    
    /**
     * logic before any new layout
     */
    Outlayer.prototype._resetLayout = function() {
      this.getSize();
    };
    
    
    Outlayer.prototype.getSize = function() {
      this.size = getSize( this.element );
    };
    
    /**
     * get measurement from option, for columnWidth, rowHeight, gutter
     * if option is String -> get element from selector string, & get size of element
     * if option is Element -> get size of element
     * else use option as a number
     *
     * @param {String} measurement
     * @param {String} size - width or height
     * @private
     */
    Outlayer.prototype._getMeasurement = function( measurement, size ) {
      var option = this.options[ measurement ];
      var elem;
      if ( !option ) {
        // default to 0
        this[ measurement ] = 0;
      } else {
        // use option as an element
        if ( typeof option === 'string' ) {
          elem = this.element.querySelector( option );
        } else if ( isElement( option ) ) {
          elem = option;
        }
        // use size of element, if element
        this[ measurement ] = elem ? getSize( elem )[ size ] : option;
      }
    };
    
    /**
     * layout a collection of item elements
     * @api public
     */
    Outlayer.prototype.layoutItems = function( items, isInstant ) {
      items = this._getItemsForLayout( items );
    
      this._layoutItems( items, isInstant );
    
      this._postLayout();
    };
    
    /**
     * get the items to be laid out
     * you may want to skip over some items
     * @param {Array} items
     * @returns {Array} items
     */
    Outlayer.prototype._getItemsForLayout = function( items ) {
      var layoutItems = [];
      for ( var i=0, len = items.length; i < len; i++ ) {
        var item = items[i];
        if ( !item.isIgnored ) {
          layoutItems.push( item );
        }
      }
      return layoutItems;
    };
    
    /**
     * layout items
     * @param {Array} items
     * @param {Boolean} isInstant
     */
    Outlayer.prototype._layoutItems = function( items, isInstant ) {
      var _this = this;
      function onItemsLayout() {
        _this.emitEvent( 'layoutComplete', [ _this, items ] );
      }
    
      if ( !items || !items.length ) {
        // no items, emit event with empty array
        onItemsLayout();
        return;
      }
    
      // emit layoutComplete when done
      this._itemsOn( items, 'layout', onItemsLayout );
    
      var queue = [];
    
      for ( var i=0, len = items.length; i < len; i++ ) {
        var item = items[i];
        // get x/y object from method
        var position = this._getItemLayoutPosition( item );
        // enqueue
        position.item = item;
        position.isInstant = isInstant || item.isLayoutInstant;
        queue.push( position );
      }
    
      this._processLayoutQueue( queue );
    };
    
    /**
     * get item layout position
     * @param {Outlayer.Item} item
     * @returns {Object} x and y position
     */
    Outlayer.prototype._getItemLayoutPosition = function( /* item */ ) {
      return {
        x: 0,
        y: 0
      };
    };
    
    /**
     * iterate over array and position each item
     * Reason being - separating this logic prevents 'layout invalidation'
     * thx @paul_irish
     * @param {Array} queue
     */
    Outlayer.prototype._processLayoutQueue = function( queue ) {
      for ( var i=0, len = queue.length; i < len; i++ ) {
        var obj = queue[i];
        this._positionItem( obj.item, obj.x, obj.y, obj.isInstant );
      }
    };
    
    /**
     * Sets position of item in DOM
     * @param {Outlayer.Item} item
     * @param {Number} x - horizontal position
     * @param {Number} y - vertical position
     * @param {Boolean} isInstant - disables transitions
     */
    Outlayer.prototype._positionItem = function( item, x, y, isInstant ) {
      if ( isInstant ) {
        // if not transition, just set CSS
        item.goTo( x, y );
      } else {
        item.moveTo( x, y );
      }
    };
    
    /**
     * Any logic you want to do after each layout,
     * i.e. size the container
     */
    Outlayer.prototype._postLayout = function() {
      var size = this._getContainerSize();
      if ( size ) {
        this._setContainerMeasure( size.width, true );
        this._setContainerMeasure( size.height, false );
      }
    };
    
    /**
     * @returns {Object} size
     *   @param {Number} width
     *   @param {Number} height
     */
    Outlayer.prototype._getContainerSize = noop;
    
    /**
     * @param {Number} measure - size of width or height
     * @param {Boolean} isWidth
     */
    Outlayer.prototype._setContainerMeasure = function( measure, isWidth ) {
      if ( measure === undefined ) {
        return;
      }
    
      var elemSize = this.size;
      // add padding and border width if border box
      if ( elemSize.isBorderBox ) {
        measure += isWidth ? elemSize.paddingLeft + elemSize.paddingRight +
          elemSize.borderLeftWidth + elemSize.borderRightWidth :
          elemSize.paddingBottom + elemSize.paddingTop +
          elemSize.borderTopWidth + elemSize.borderBottomWidth;
      }
    
      measure = Math.max( measure, 0 );
      this.element.style[ isWidth ? 'width' : 'height' ] = measure + 'px';
    };
    
    /**
     * trigger a callback for a collection of items events
     * @param {Array} items - Outlayer.Items
     * @param {String} eventName
     * @param {Function} callback
     */
    Outlayer.prototype._itemsOn = function( items, eventName, callback ) {
      var doneCount = 0;
      var count = items.length;
      // event callback
      var _this = this;
      function tick() {
        doneCount++;
        if ( doneCount === count ) {
          callback.call( _this );
        }
        return true; // bind once
      }
      // bind callback
      for ( var i=0, len = items.length; i < len; i++ ) {
        var item = items[i];
        item.on( eventName, tick );
      }
    };
    
    // -------------------------- ignore & stamps -------------------------- //
    
    
    /**
     * keep item in collection, but do not lay it out
     * ignored items do not get skipped in layout
     * @param {Element} elem
     */
    Outlayer.prototype.ignore = function( elem ) {
      var item = this.getItem( elem );
      if ( item ) {
        item.isIgnored = true;
      }
    };
    
    /**
     * return item to layout collection
     * @param {Element} elem
     */
    Outlayer.prototype.unignore = function( elem ) {
      var item = this.getItem( elem );
      if ( item ) {
        delete item.isIgnored;
      }
    };
    
    /**
     * adds elements to stamps
     * @param {NodeList, Array, Element, or String} elems
     */
    Outlayer.prototype.stamp = function( elems ) {
      elems = this._find( elems );
      if ( !elems ) {
        return;
      }
    
      this.stamps = this.stamps.concat( elems );
      // ignore
      for ( var i=0, len = elems.length; i < len; i++ ) {
        var elem = elems[i];
        this.ignore( elem );
      }
    };
    
    /**
     * removes elements to stamps
     * @param {NodeList, Array, or Element} elems
     */
    Outlayer.prototype.unstamp = function( elems ) {
      elems = this._find( elems );
      if ( !elems ){
        return;
      }
    
      for ( var i=0, len = elems.length; i < len; i++ ) {
        var elem = elems[i];
        // filter out removed stamp elements
        removeFrom( elem, this.stamps );
        this.unignore( elem );
      }
    
    };
    
    /**
     * finds child elements
     * @param {NodeList, Array, Element, or String} elems
     * @returns {Array} elems
     */
    Outlayer.prototype._find = function( elems ) {
      if ( !elems ) {
        return;
      }
      // if string, use argument as selector string
      if ( typeof elems === 'string' ) {
        elems = this.element.querySelectorAll( elems );
      }
      elems = makeArray( elems );
      return elems;
    };
    
    Outlayer.prototype._manageStamps = function() {
      if ( !this.stamps || !this.stamps.length ) {
        return;
      }
    
      this._getBoundingRect();
    
      for ( var i=0, len = this.stamps.length; i < len; i++ ) {
        var stamp = this.stamps[i];
        this._manageStamp( stamp );
      }
    };
    
    // update boundingLeft / Top
    Outlayer.prototype._getBoundingRect = function() {
      // get bounding rect for container element
      var boundingRect = this.element.getBoundingClientRect();
      var size = this.size;
      this._boundingRect = {
        left: boundingRect.left + size.paddingLeft + size.borderLeftWidth,
        top: boundingRect.top + size.paddingTop + size.borderTopWidth,
        right: boundingRect.right - ( size.paddingRight + size.borderRightWidth ),
        bottom: boundingRect.bottom - ( size.paddingBottom + size.borderBottomWidth )
      };
    };
    
    /**
     * @param {Element} stamp
    **/
    Outlayer.prototype._manageStamp = noop;
    
    /**
     * get x/y position of element relative to container element
     * @param {Element} elem
     * @returns {Object} offset - has left, top, right, bottom
     */
    Outlayer.prototype._getElementOffset = function( elem ) {
      var boundingRect = elem.getBoundingClientRect();
      var thisRect = this._boundingRect;
      var size = getSize( elem );
      var offset = {
        left: boundingRect.left - thisRect.left - size.marginLeft,
        top: boundingRect.top - thisRect.top - size.marginTop,
        right: thisRect.right - boundingRect.right - size.marginRight,
        bottom: thisRect.bottom - boundingRect.bottom - size.marginBottom
      };
      return offset;
    };
    
    // -------------------------- resize -------------------------- //
    
    // enable event handlers for listeners
    // i.e. resize -> onresize
    Outlayer.prototype.handleEvent = function( event ) {
      var method = 'on' + event.type;
      if ( this[ method ] ) {
        this[ method ]( event );
      }
    };
    
    /**
     * Bind layout to window resizing
     */
    Outlayer.prototype.bindResize = function() {
      // bind just one listener
      if ( this.isResizeBound ) {
        return;
      }
      eventie.bind( window, 'resize', this );
      this.isResizeBound = true;
    };
    
    /**
     * Unbind layout to window resizing
     */
    Outlayer.prototype.unbindResize = function() {
      eventie.unbind( window, 'resize', this );
      this.isResizeBound = false;
    };
    
    // original debounce by John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    
    // this fires every resize
    Outlayer.prototype.onresize = function() {
      if ( this.resizeTimeout ) {
        clearTimeout( this.resizeTimeout );
      }
    
      var _this = this;
      function delayed() {
          _this.trigger("resize");
        delete _this.resizeTimeout;
      }
    
      this.resizeTimeout = setTimeout( delayed, 100 );
    };
    
    // debounced, layout on resize
    Outlayer.prototype.resize = function() {
      // don't trigger if size did not change
      var size = getSize( this.element );
      // check that this.size and size are there
      // IE8 triggers resize on body size change, so they might not be
      var hasSizes = this.size && size;
      if ( hasSizes && size.innerWidth === this.size.innerWidth ) {
        return;
      }
    
      this.layout();
    };
    
    
    // -------------------------- methods -------------------------- //
    
    /**
     * add items to Outlayer instance
     * @param {Array or NodeList or Element} elems
     * @returns {Array} items - Outlayer.Items
    **/
    Outlayer.prototype.addItems = function( elems ) {
      var items = this._itemize( elems );
      // add items to collection
      if ( items.length ) {
        this.items = this.items.concat( items );
      }
      return items;
    };
    
    /**
     * Layout newly-appended item elements
     * @param {Array or NodeList or Element} elems
     */
    Outlayer.prototype.appended = function( elems ) {
      var items = this.addItems( elems );
      if ( !items.length ) {
        return;
      }
      // layout and reveal just the new items
      this.layoutItems( items, true );
      this.reveal( items );
    };
    
    /**
     * Layout prepended elements
     * @param {Array or NodeList or Element} elems
     */
    Outlayer.prototype.prepended = function( elems ) {
      var items = this._itemize( elems );
      if ( !items.length ) {
        return;
      }
      // add items to beginning of collection
      var previousItems = this.items.slice(0);
      this.items = items.concat( previousItems );
      // start new layout
      this._resetLayout();
      this._manageStamps();
      // layout new stuff without transition
      this.layoutItems( items, true );
      this.reveal( items );
      // layout previous items
      this.layoutItems( previousItems );
    };
    
    /**
     * reveal a collection of items
     * @param {Array of Outlayer.Items} items
     */
    Outlayer.prototype.reveal = function( items ) {
      var len = items && items.length;
      if ( !len ) {
        return;
      }
      for ( var i=0; i < len; i++ ) {
        var item = items[i];
        item.reveal();
      }
    };
    
    /**
     * hide a collection of items
     * @param {Array of Outlayer.Items} items
     */
    Outlayer.prototype.hide = function( items ) {
      var len = items && items.length;
      if ( !len ) {
        return;
      }
      for ( var i=0; i < len; i++ ) {
        var item = items[i];
        item.hide();
      }
    };
    
    /**
     * get Outlayer.Item, given an Element
     * @param {Element} elem
     * @param {Function} callback
     * @returns {Outlayer.Item} item
     */
    Outlayer.prototype.getItem = function( elem ) {
      // loop through items to get the one that matches
      for ( var i=0, len = this.items.length; i < len; i++ ) {
        var item = this.items[i];
        if ( item.element === elem ) {
          // return item
          return item;
        }
      }
    };
    
    /**
     * get collection of Outlayer.Items, given Elements
     * @param {Array} elems
     * @returns {Array} items - Outlayer.Items
     */
    Outlayer.prototype.getItems = function( elems ) {
      if ( !elems || !elems.length ) {
        return;
      }
      var items = [];
      for ( var i=0, len = elems.length; i < len; i++ ) {
        var elem = elems[i];
        var item = this.getItem( elem );
        if ( item ) {
          items.push( item );
        }
      }
    
      return items;
    };
    
    /**
     * remove element(s) from instance and DOM
     * @param {Array or NodeList or Element} elems
     */
    Outlayer.prototype.remove = function( elems ) {
      elems = makeArray( elems );
    
      var removeItems = this.getItems( elems );
      // bail if no items to remove
      if ( !removeItems || !removeItems.length ) {
        return;
      }
    
      this._itemsOn( removeItems, 'remove', function() {
        this.emitEvent( 'removeComplete', [ this, removeItems ] );
      });
    
      for ( var i=0, len = removeItems.length; i < len; i++ ) {
        var item = removeItems[i];
        item.remove();
        // remove item from collection
        removeFrom( item, this.items );
      }
    };
    
    // ----- destroy ----- //
    
    // remove and disable Outlayer instance
    Outlayer.prototype.destroy = function() {
      // clean up dynamic styles
      var style = this.element.style;
      style.height = '';
      style.position = '';
      style.width = '';
      // destroy items
      for ( var i=0, len = this.items.length; i < len; i++ ) {
        var item = this.items[i];
        item.destroy();
      }
    
      this.unbindResize();
    
      delete this.element.outlayerGUID;
      // remove data for jQuery
      if ( jQuery ) {
        jQuery.removeData( this.element, this.constructor.namespace );
      }
    
    };
    
    // -------------------------- data -------------------------- //
    
    /**
     * get Outlayer instance from element
     * @param {Element} elem
     * @returns {Outlayer}
     */
    Outlayer.data = function( elem ) {
      var id = elem && elem.outlayerGUID;
      return id && instances[ id ];
    };
    
    // --------------------------  -------------------------- //
    
    // copy an object on the Outlayer prototype to new object
    function copyOutlayerProto( obj, property ) {
      obj.prototype[ property ] = extend( {}, Outlayer.prototype[ property ] );
    }
    
    // -------------------------- create Outlayer class -------------------------- //
    
    /**
     * create a layout class
     * @param {String} namespace
     */
    Outlayer.create = function( namespace, options ) {
      // sub-class Outlayer
      function Layout() {
        Outlayer.apply( this, arguments );
        };
      // inherit Outlayer prototype, use Object.create if there
      if ( Object.create ) {
        Layout.prototype = Object.create( Outlayer.prototype );
      } else {
        extend( Layout.prototype, Outlayer.prototype );
      }
      // set contructor, used for namespace and Item
      Layout.prototype.constructor = Layout;
    
      // copy default options so Outlayer.options don't get touched
      copyOutlayerProto( Layout, 'options' );
      // apply new options
      extend( Layout.prototype.options, options );
    
      Layout.namespace = namespace;
    
      Layout.data = Outlayer.data;
    
      // sub-class Item
      Layout.Item = function LayoutItem() {
        Item.apply( this, arguments );
      };
    
      Layout.Item.prototype = new Item();
    
      // -------------------------- declarative -------------------------- //
    
      /**
       * allow user to initialize Outlayer via .js-namespace class
       * options are parsed from data-namespace-option attribute
       */
      docReady( function() {
        var dashedNamespace = toDashed( namespace );
        var elems = document.querySelectorAll( '.js-' + dashedNamespace );
        var dataAttr = 'data-' + dashedNamespace + '-options';
    
        for ( var i=0, len = elems.length; i < len; i++ ) {
          var elem = elems[i];
          var attr = elem.getAttribute( dataAttr );
          var options;
          try {
            options = attr && JSON.parse( attr );
          } catch ( error ) {
            // log error, do not initialize
            if ( console ) {
              console.error( 'Error parsing ' + dataAttr + ' on ' +
                elem.nodeName.toLowerCase() + ( elem.id ? '#' + elem.id : '' ) + ': ' +
                error );
            }
            continue;
          }
          // initialize
          var instance = new Layout( elem, options );
          // make available via $().data('layoutname')
          if ( jQuery ) {
            jQuery.data( elem, namespace, instance );
          }
        }
      });
    
      // -------------------------- jQuery bridge -------------------------- //
    
      // make into jQuery plugin
      if ( jQuery && jQuery.bridget ) {
        jQuery.bridget( namespace, Layout );
      }
    
      return Layout;
    };
    
    // ----- fin ----- //
    
    // back in global
    Outlayer.Item = Item;
    
    return Outlayer;
    
        };
    
    // -------------------------- transport -------------------------- //
    
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'outlayer/outlayer',[
          'eventie/eventie',
          'doc-ready/doc-ready',
          'eventEmitter/EventEmitter',
          'get-size/get-size',
          'matches-selector/matches-selector',
          './item'
        ],
        outlayerDefinition );
    } else {
      // browser global
      window.Outlayer = outlayerDefinition(
        window.eventie,
        window.docReady,
        window.EventEmitter,
        window.getSize,
        window.matchesSelector,
        window.Outlayer.Item
      );
    }
    
    })( window );
    
    /**
     * Rect
     * low-level utility class for basic geometry
     */
    
    ( function( window ) {
    
    
    
    // -------------------------- Packery -------------------------- //
    
    // global namespace
    var Packery = window.Packery = function() {};
    
    function rectDefinition() {
    
    // -------------------------- Rect -------------------------- //
    
    function Rect( props ) {
      // extend properties from defaults
      for ( var prop in Rect.defaults ) {
        this[ prop ] = Rect.defaults[ prop ];
      }
    
      for ( prop in props ) {
        this[ prop ] = props[ prop ];
      }
    
        };
    
    // make available
    Packery.Rect = Rect;
    
    Rect.defaults = {
      x: 0,
      y: 0,
      width: 0,
      height: 0
    };
    
    /**
     * Determines whether or not this rectangle wholly encloses another rectangle or point.
     * @param {Rect} rect
     * @returns {Boolean}
    **/
    Rect.prototype.contains = function( rect ) {
      // points don't have width or height
      var otherWidth = rect.width || 0;
      var otherHeight = rect.height || 0;
      return this.x <= rect.x &&
        this.y <= rect.y &&
        this.x + this.width >= rect.x + otherWidth &&
        this.y + this.height >= rect.y + otherHeight;
    };
    
    /**
     * Determines whether or not the rectangle intersects with another.
     * @param {Rect} rect
     * @returns {Boolean}
    **/
    Rect.prototype.overlaps = function( rect ) {
      var thisRight = this.x + this.width;
      var thisBottom = this.y + this.height;
      var rectRight = rect.x + rect.width;
      var rectBottom = rect.y + rect.height;
    
      // http://stackoverflow.com/a/306332
      return this.x < rectRight &&
        thisRight > rect.x &&
        this.y < rectBottom &&
        thisBottom > rect.y;
    };
    
    /**
     * @param {Rect} rect - the overlapping rect
     * @returns {Array} freeRects - rects representing the area around the rect
    **/
    Rect.prototype.getMaximalFreeRects = function( rect ) {
    
      // if no intersection, return false
      if ( !this.overlaps( rect ) ) {
        return false;
      }
    
      var freeRects = [];
      var freeRect;
    
      var thisRight = this.x + this.width;
      var thisBottom = this.y + this.height;
      var rectRight = rect.x + rect.width;
      var rectBottom = rect.y + rect.height;
    
      // top
      if ( this.y < rect.y ) {
        freeRect = new Rect({
          x: this.x,
          y: this.y,
          width: this.width,
          height: rect.y - this.y
        });
        freeRects.push( freeRect );
      }
    
      // right
      if ( thisRight > rectRight ) {
        freeRect = new Rect({
          x: rectRight,
          y: this.y,
          width: thisRight - rectRight,
          height: this.height
        });
        freeRects.push( freeRect );
      }
    
      // bottom
      if ( thisBottom > rectBottom ) {
        freeRect = new Rect({
          x: this.x,
          y: rectBottom,
          width: this.width,
          height: thisBottom - rectBottom
        });
        freeRects.push( freeRect );
      }
    
      // left
      if ( this.x < rect.x ) {
        freeRect = new Rect({
          x: this.x,
          y: this.y,
          width: rect.x - this.x,
          height: this.height
        });
        freeRects.push( freeRect );
      }
    
      return freeRects;
    };
    
    Rect.prototype.canFit = function( rect ) {
      return this.width >= rect.width && this.height >= rect.height;
    };
    
    return Rect;
    
        };
    
    // -------------------------- transport -------------------------- //
    
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'packery/js/rect',rectDefinition );
    } else {
      // browser global
      window.Packery = window.Packery || {};
      window.Packery.Rect = rectDefinition();
    }
    
    })( window );
    
    /**
     * Packer
     * bin-packing algorithm
     */
    
    ( function( window ) {
    
    
    
    // -------------------------- Packer -------------------------- //
    
    function packerDefinition( Rect ) {
    
    /**
     * @param {Number} width
     * @param {Number} height
     * @param {String} sortDirection
     *   topLeft for vertical, leftTop for horizontal
     */
    function Packer( width, height, sortDirection ) {
      this.width = width || 0;
      this.height = height || 0;
      this.sortDirection = sortDirection || 'downwardLeftToRight';
    
      this.reset();
        };
    
    Packer.prototype.reset = function() {
      this.spaces = [];
      this.newSpaces = [];
    
      var initialSpace = new Rect({
        x: 0,
        y: 0,
        width: this.width,
        height: this.height
      });
    
      this.spaces.push( initialSpace );
      // set sorter
      this.sorter = sorters[ this.sortDirection ] || sorters.downwardLeftToRight;
    };
    
    // change x and y of rect to fit with in Packer's available spaces
    Packer.prototype.pack = function( rect ) {
      for ( var i=0, len = this.spaces.length; i < len; i++ ) {
        var space = this.spaces[i];
        if ( space.canFit( rect ) ) {
          this.placeInSpace( rect, space );
          break;
        }
      }
    };
    
    Packer.prototype.placeInSpace = function( rect, space ) {
      // place rect in space
      rect.x = space.x;
      rect.y = space.y;
    
      this.placed( rect );
    };
    
    // update spaces with placed rect
    Packer.prototype.placed = function( rect ) {
      // update spaces
      var revisedSpaces = [];
      for ( var i=0, len = this.spaces.length; i < len; i++ ) {
        var space = this.spaces[i];
        var newSpaces = space.getMaximalFreeRects( rect );
        // add either the original space or the new spaces to the revised spaces
        if ( newSpaces ) {
          revisedSpaces.push.apply( revisedSpaces, newSpaces );
        } else {
          revisedSpaces.push( space );
        }
      }
    
      this.spaces = revisedSpaces;
    
      // remove redundant spaces
      Packer.mergeRects( this.spaces );
    
      this.spaces.sort( this.sorter );
    };
    
    // -------------------------- utility functions -------------------------- //
    
    /**
     * Remove redundant rectangle from array of rectangles
     * @param {Array} rects: an array of Rects
     * @returns {Array} rects: an array of Rects
    **/
    Packer.mergeRects = function( rects ) {
      for ( var i=0, len = rects.length; i < len; i++ ) {
        var rect = rects[i];
        // skip over this rect if it was already removed
        if ( !rect ) {
          continue;
        }
        // clone rects we're testing, remove this rect
        var compareRects = rects.slice(0);
        // do not compare with self
        compareRects.splice( i, 1 );
        // compare this rect with others
        var removedCount = 0;
        for ( var j=0, jLen = compareRects.length; j < jLen; j++ ) {
          var compareRect = compareRects[j];
          // if this rect contains another,
          // remove that rect from test collection
          var indexAdjust = i > j ? 0 : 1;
          if ( rect.contains( compareRect ) ) {
            // console.log( 'current test rects:' + testRects.length, testRects );
            // console.log( i, j, indexAdjust, rect, compareRect );
            rects.splice( j + indexAdjust - removedCount, 1 );
            removedCount++;
          }
        }
      }
    
      return rects;
    };
    
    
    // -------------------------- sorters -------------------------- //
    
    // functions for sorting rects in order
    var sorters = {
      // top down, then left to right
      downwardLeftToRight: function( a, b ) {
        return a.y - b.y || a.x - b.x;
      },
      // left to right, then top down
      rightwardTopToBottom: function( a, b ) {
        return a.x - b.x || a.y - b.y;
      }
    };
    
    
    // --------------------------  -------------------------- //
    
    return Packer;
    
        };
    
    // -------------------------- transport -------------------------- //
    
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'packery/js/packer',[ './rect' ], packerDefinition );
    } else {
      // browser global
      var Packery = window.Packery = window.Packery || {};
      Packery.Packer = packerDefinition( Packery.Rect );
    }
    
    })( window );
    
    /**
     * Packery Item Element
    **/
    
    ( function( window ) {
    
    
    
    // -------------------------- Item -------------------------- //
    
    function itemDefinition( getStyleProperty, Outlayer, Rect ) {
    
    var transformProperty = getStyleProperty('transform');
    
    // sub-class Item
    var Item = function PackeryItem() {
      Outlayer.Item.apply( this, arguments );
    };
    
    Item.prototype = new Outlayer.Item();
    
    var protoCreate = Item.prototype._create;
    Item.prototype._create = function() {
      // call default _create logic
      protoCreate.call( this );
      this.rect = new Rect();
      // rect used for placing, in drag or Packery.fit()
      this.placeRect = new Rect();
    };
    
    // -------------------------- drag -------------------------- //
    
    Item.prototype.dragStart = function() {
      this.getPosition();
      this.removeTransitionStyles();
      // remove transform property from transition
      if ( this.isTransitioning && transformProperty ) {
        this.element.style[ transformProperty ] = 'none';
      }
      this.getSize();
      // create place rect, used for position when dragged then dropped
      // or when positioning
      this.isPlacing = true;
      this.needsPositioning = false;
      this.positionPlaceRect( this.position.x, this.position.y );
      this.isTransitioning = false;
      this.didDrag = false;
    };
    
    /**
     * handle item when it is dragged
     * @param {Number} x - horizontal position of dragged item
     * @param {Number} y - vertical position of dragged item
     */
    Item.prototype.dragMove = function( x, y ) {
      this.didDrag = true;
      var packerySize = this.layout.size;
      x -= packerySize.paddingLeft;
      y -= packerySize.paddingTop;
      this.positionPlaceRect( x, y );
    };
    
    Item.prototype.dragStop = function() {
      this.getPosition();
      var isDiffX = this.position.x !== this.placeRect.x;
      var isDiffY = this.position.y !== this.placeRect.y;
      // set post-drag positioning flag
      this.needsPositioning = isDiffX || isDiffY;
      // reset flag
      this.didDrag = false;
    };
    
    // -------------------------- placing -------------------------- //
    
    /**
     * position a rect that will occupy space in the packer
     * @param {Number} x
     * @param {Number} y
     * @param {Boolean} isMaxYContained
     */
    Item.prototype.positionPlaceRect = function( x, y, isMaxYOpen ) {
      this.placeRect.x = this.getPlaceRectCoord( x, true );
      this.placeRect.y = this.getPlaceRectCoord( y, false, isMaxYOpen );
    };
    
    /**
     * get x/y coordinate for place rect
     * @param {Number} coord - x or y
     * @param {Boolean} isX
     * @param {Boolean} isMaxOpen - does not limit value to outer bound
     * @returns {Number} coord - processed x or y
     */
    Item.prototype.getPlaceRectCoord = function( coord, isX, isMaxOpen ) {
      var measure = isX ? 'Width' : 'Height';
      var size = this.size[ 'outer' + measure ];
      var segment = this.layout[ isX ? 'columnWidth' : 'rowHeight' ];
      var parentSize = this.layout.size[ 'inner' + measure ];
    
      // additional parentSize calculations for Y
      if ( !isX ) {
        parentSize = Math.max( parentSize, this.layout.maxY );
        // prevent gutter from bumping up height when non-vertical grid
        if ( !this.layout.rowHeight ) {
          parentSize -= this.layout.gutter;
        }
      }
    
      var max;
    
      if ( segment ) {
        segment += this.layout.gutter;
        // allow for last column to reach the edge
        parentSize += isX ? this.layout.gutter : 0;
        // snap to closest segment
        coord = Math.round( coord / segment );
        // contain to outer bound
        // contain non-growing bound, allow growing bound to grow
        var mathMethod;
        if ( this.layout.options.isHorizontal ) {
          mathMethod = !isX ? 'floor' : 'ceil';
        } else {
          mathMethod = isX ? 'floor' : 'ceil';
        }
        var maxSegments = Math[ mathMethod ]( parentSize / segment );
        maxSegments -= Math.ceil( size / segment );
        max = maxSegments;
      } else {
        max = parentSize - size;
      }
    
      coord = isMaxOpen ? coord : Math.min( coord, max );
      coord *= segment || 1;
    
      return Math.max( 0, coord );
    };
    
    Item.prototype.copyPlaceRectPosition = function() {
      this.rect.x = this.placeRect.x;
      this.rect.y = this.placeRect.y;
    };
    
    return Item;
    
        };
    
    // -------------------------- transport -------------------------- //
    
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( 'packery/js/item',[
          'get-style-property/get-style-property',
          'outlayer/outlayer',
          './rect'
        ],
        itemDefinition );
    } else {
      // browser global
      window.Packery.Item = itemDefinition(
        window.getStyleProperty,
        window.Outlayer,
        window.Packery.Rect
      );
    }
    
    })( window );
    
    /*!
     * Packery v1.2.3
     * bin-packing layout library
     * http://packery.metafizzy.co
     *
     * Commercial use requires one-time purchase of a commercial license
     * http://packery.metafizzy.co/license.html
     *
     * Non-commercial use is licensed under the GPL v3 License
     *
     * Copyright 2014 Metafizzy
     */
    
    ( function( window ) {
    
    
    
    // -------------------------- Packery -------------------------- //
    
    // used for AMD definition and requires
    function packeryDefinition( classie, getSize, Outlayer, Rect, Packer, Item ) {
    
    // create an Outlayer layout class
    var Packery = Outlayer.create('packery');
    Packery.Item = Item;
    
    Packery.prototype._create = function() {
      // call super
      Outlayer.prototype._create.call( this );
    
      // initial properties
      this.packer = new Packer();
    
      // Left over from v1.0
      this.stamp( this.options.stamped );
    
      // create drag handlers
      var _this = this;
      this.handleDraggabilly = {
        dragStart: function( draggie ) {
          _this.itemDragStart( draggie.element );
        },
        dragMove: function( draggie ) {
          _this.itemDragMove( draggie.element, draggie.position.x, draggie.position.y );
        },
        dragEnd: function( draggie ) {
          _this.itemDragEnd( draggie.element );
        }
      };
    
      this.handleUIDraggable = {
        start: function handleUIDraggableStart( event ) {
          _this.itemDragStart( event.currentTarget );
        },
        drag: function handleUIDraggableDrag( event, ui ) {
          _this.itemDragMove( event.currentTarget, ui.position.left, ui.position.top );
        },
        stop: function handleUIDraggableStop( event ) {
          _this.itemDragEnd( event.currentTarget );
        }
      };
    
    };
    
    
    // ----- init & layout ----- //
    
    /**
     * logic before any new layout
     */
    Packery.prototype._resetLayout = function() {
      this.getSize();
    
      this._getMeasurements();
    
      // reset packer
      var packer = this.packer;
      // packer settings, if horizontal or vertical
      if ( this.options.isHorizontal ) {
        packer.width = Number.POSITIVE_INFINITY;
        packer.height = this.size.innerHeight + this.gutter;
        packer.sortDirection = 'rightwardTopToBottom';
      } else {
        packer.width = this.size.innerWidth + this.gutter;
        packer.height = Number.POSITIVE_INFINITY;
        packer.sortDirection = 'downwardLeftToRight';
      }
    
      packer.reset();
    
      // layout
      this.maxY = 0;
      this.maxX = 0;
    };
    
    /**
     * update columnWidth, rowHeight, & gutter
     * @private
     */
    Packery.prototype._getMeasurements = function() {
      this._getMeasurement( 'columnWidth', 'width' );
      this._getMeasurement( 'rowHeight', 'height' );
      this._getMeasurement( 'gutter', 'width' );
    };
    
    Packery.prototype._getItemLayoutPosition = function( item ) {
      this._packItem( item );
      return item.rect;
    };
    
    
    /**
     * layout item in packer
     * @param {Packery.Item} item
     */
    Packery.prototype._packItem = function( item ) {
      this._setRectSize( item.element, item.rect );
      // pack the rect in the packer
      this.packer.pack( item.rect );
      this._setMaxXY( item.rect );
    };
    
    /**
     * set max X and Y value, for size of container
     * @param {Packery.Rect} rect
     * @private
     */
    Packery.prototype._setMaxXY = function( rect ) {
      this.maxX = Math.max( rect.x + rect.width, this.maxX );
      this.maxY = Math.max( rect.y + rect.height, this.maxY );
    };
    
    /**
     * set the width and height of a rect, applying columnWidth and rowHeight
     * @param {Element} elem
     * @param {Packery.Rect} rect
     */
    Packery.prototype._setRectSize = function( elem, rect ) {
      var size = getSize( elem );
      var w = size.outerWidth;
      var h = size.outerHeight;
      // size for columnWidth and rowHeight, if available
      // only check if size is non-zero, #177
      if ( w || h ) {
        var colW = this.columnWidth + this.gutter;
        var rowH = this.rowHeight + this.gutter;
        w = this.columnWidth ? Math.ceil( w / colW ) * colW : w + this.gutter;
        h = this.rowHeight ? Math.ceil( h / rowH ) * rowH : h + this.gutter;
      }
      // rect must fit in packer
      rect.width = Math.min( w, this.packer.width );
      rect.height = Math.min( h, this.packer.height );
    };
    
    Packery.prototype._getContainerSize = function() {
      if ( this.options.isHorizontal ) {
        return {
          width: this.maxX - this.gutter
        };
      } else {
        return {
          height: this.maxY - this.gutter
        };
      }
    };
    
    
    // -------------------------- stamp -------------------------- //
    
    /**
     * makes space for element
     * @param {Element} elem
     */
    Packery.prototype._manageStamp = function( elem ) {
    
      var item = this.getItem( elem );
      var rect;
      if ( item && item.isPlacing ) {
        rect = item.placeRect;
      } else {
        var offset = this._getElementOffset( elem );
        rect = new Rect({
          x: this.options.isOriginLeft ? offset.left : offset.right,
          y: this.options.isOriginTop ? offset.top : offset.bottom
        });
      }
    
      this._setRectSize( elem, rect );
      // save its space in the packer
      this.packer.placed( rect );
      this._setMaxXY( rect );
    };
    
    // -------------------------- methods -------------------------- //
    
    function verticalSorter( a, b ) {
      return a.position.y - b.position.y || a.position.x - b.position.x;
    }
    
    function horizontalSorter( a, b ) {
      return a.position.x - b.position.x || a.position.y - b.position.y;
    }
    
    Packery.prototype.sortItemsByPosition = function() {
      var sorter = this.options.isHorizontal ? horizontalSorter : verticalSorter;
      this.items.sort( sorter );
    };
    
    /**
     * Fit item element in its current position
     * Packery will position elements around it
     * useful for expanding elements
     *
     * @param {Element} elem
     * @param {Number} x - horizontal destination position, optional
     * @param {Number} y - vertical destination position, optional
     */
    Packery.prototype.fit = function( elem, x, y ) {
      var item = this.getItem( elem );
      if ( !item ) {
        return;
      }
    
      // prepare internal properties
      this._getMeasurements();
    
      // stamp item to get it out of layout
      this.stamp( item.element );
      // required for positionPlaceRect
      item.getSize();
      // set placing flag
      item.isPlacing = true;
      // fall back to current position for fitting
      x = x === undefined ? item.rect.x: x;
      y = y === undefined ? item.rect.y: y;
    
      // position it best at its destination
      item.positionPlaceRect( x, y, true );
    
      this._bindFitEvents( item );
      item.moveTo( item.placeRect.x, item.placeRect.y );
      // layout everything else
      this.layout();
    
      // return back to regularly scheduled programming
      this.unstamp( item.element );
      this.sortItemsByPosition();
      // un set placing flag, back to normal
      item.isPlacing = false;
      // copy place rect position
      item.copyPlaceRectPosition();
    };
    
    /**
     * emit event when item is fit and other items are laid out
     * @param {Packery.Item} item
     * @private
     */
    Packery.prototype._bindFitEvents = function( item ) {
      var _this = this;
      var ticks = 0;
      function tick() {
        ticks++;
        if ( ticks !== 2 ) {
          return;
        }
        _this.emitEvent( 'fitComplete', [ _this, item ] );
      }
      // when item is laid out
      item.on( 'layout', function() {
        tick();
        return true;
      });
      // when all items are laid out
      this.on( 'layoutComplete', function() {
        tick();
        return true;
      });
    };
    
    // -------------------------- resize -------------------------- //
    
    // debounced, layout on resize
    Packery.prototype.resize = function() {
      // don't trigger if size did not change
      var size = getSize( this.element );
      // check that this.size and size are there
      // IE8 triggers resize on body size change, so they might not be
      var hasSizes = this.size && size;
      var innerSize = this.options.isHorizontal ? 'innerHeight' : 'innerWidth';
      if ( hasSizes && size[ innerSize ] === this.size[ innerSize ] ) {
        return;
      }
    
      this.layout();
    };
    
    // -------------------------- drag -------------------------- //
    
    /**
     * handle an item drag start event
     * @param {Element} elem
     */
    Packery.prototype.itemDragStart = function( elem ) {
      this.stamp( elem );
      var item = this.getItem( elem );
      if ( item ) {
        item.dragStart();
      }
    };
    
    /**
     * handle an item drag move event
     * @param {Element} elem
     * @param {Number} x - horizontal change in position
     * @param {Number} y - vertical change in position
     */
    Packery.prototype.itemDragMove = function( elem, x, y ) {
      var item = this.getItem( elem );
      if ( item ) {
        item.dragMove( x, y );
      }
    
      // debounce
      var _this = this;
      // debounce triggering layout
      function delayed() {
        _this.layout();
        delete _this.dragTimeout;
      }
    
      this.clearDragTimeout();
    
      this.dragTimeout = setTimeout( delayed, 40 );
    };
    
    Packery.prototype.clearDragTimeout = function() {
      if ( this.dragTimeout ) {
        clearTimeout( this.dragTimeout );
      }
    };
    
    /**
     * handle an item drag end event
     * @param {Element} elem
     */
    Packery.prototype.itemDragEnd = function( elem ) {
      var item = this.getItem( elem );
      var itemDidDrag;
      if ( item ) {
        itemDidDrag = item.didDrag;
        item.dragStop();
      }
      // if elem didn't move, or if it doesn't need positioning
      // unignore and unstamp and call it a day
      if ( !item || ( !itemDidDrag && !item.needsPositioning ) ) {
        this.unstamp( elem );
        return;
      }
      // procced with dragged item
    
      classie.add( item.element, 'is-positioning-post-drag' );
    
      // save this var, as it could get reset in dragStart
      var onLayoutComplete = this._getDragEndLayoutComplete( elem, item );
    
      if ( item.needsPositioning ) {
        item.on( 'layout', onLayoutComplete );
        item.moveTo( item.placeRect.x, item.placeRect.y );
      } else if ( item ) {
        // item didn't need placement
        item.copyPlaceRectPosition();
      }
    
      this.clearDragTimeout();
      this.on( 'layoutComplete', onLayoutComplete );
      this.layout();
    
    };
    
    /**
     * get drag end callback
     * @param {Element} elem
     * @param {Packery.Item} item
     * @returns {Function} onLayoutComplete
     */
    Packery.prototype._getDragEndLayoutComplete = function( elem, item ) {
      var itemNeedsPositioning = item && item.needsPositioning;
      var completeCount = 0;
      var asyncCount = itemNeedsPositioning ? 2 : 1;
      var _this = this;
    
      return function onLayoutComplete() {
        completeCount++;
        // don't proceed if not complete
        if ( completeCount !== asyncCount ) {
          return true;
        }
        // reset item
        if ( item ) {
          classie.remove( item.element, 'is-positioning-post-drag' );
          item.isPlacing = false;
          item.copyPlaceRectPosition();
        }
    
        _this.unstamp( elem );
        // only sort when item moved
        _this.sortItemsByPosition();
    
        // emit item drag event now that everything is done
        if ( itemNeedsPositioning ) {
          _this.emitEvent( 'dragItemPositioned', [ _this, item ] );
        }
        // listen once
        return true;
      };
    };
    
    /**
     * binds Draggabilly events
     * @param {Draggabilly} draggie
     */
    Packery.prototype.bindDraggabillyEvents = function( draggie ) {
      draggie.on( 'dragStart', this.handleDraggabilly.dragStart );
      draggie.on( 'dragMove', this.handleDraggabilly.dragMove );
      draggie.on( 'dragEnd', this.handleDraggabilly.dragEnd );
    };
    
    /**
     * binds jQuery UI Draggable events
     * @param {jQuery} $elems
     */
    Packery.prototype.bindUIDraggableEvents = function( $elems ) {
      $elems
        .on( 'dragstart', this.handleUIDraggable.start )
        .on( 'drag', this.handleUIDraggable.drag )
        .on( 'dragstop', this.handleUIDraggable.stop );
    };
    
    Packery.Rect = Rect;
    Packery.Packer = Packer;
    
    return Packery;
    
        };
    
    // -------------------------- transport -------------------------- //
    
    if ( typeof define === 'function' && define.amd ) {
      // AMD
      define( [
          'classie/classie',
          'get-size/get-size',
          'outlayer/outlayer',
          'packery/js/rect',
          'packery/js/packer',
          'packery/js/item'
        ],
        packeryDefinition );
    } else {
      // browser global
      window.Packery = packeryDefinition(
        window.classie,
        window.getSize,
        window.Outlayer,
        window.Packery.Rect,
        window.Packery.Packer,
        window.Packery.Item
      );
    }
    
    })( window );
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\clamp.min.js
/*!
* Clamp.js 0.5.1
*
* Copyright 2011-2013, Joseph Schmitt http://joe.sh
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*/

(function(){
    /**
     * Clamps a text node.
     * @param {HTMLElement} element. Element containing the text node to clamp.
     * @param {Object} options. Options to pass to the clamper.
     */
    function clamp(element, options) {
        options = options || {};

        var self = this,
            win = window,
            opt = {
                clamp:              options.clamp || 2,
                useNativeClamp:     typeof(options.useNativeClamp) != 'undefined' ? options.useNativeClamp : true,
                splitOnChars:       options.splitOnChars || ['.', '-', '–', '—', ' '], //Split on sentences (periods), hypens, en-dashes, em-dashes, and words (spaces).
                animate:            options.animate || false,
                truncationChar:     options.truncationChar || '…',
                truncationHTML:     options.truncationHTML
            },

            sty = element.style,
            originalText = element.innerHTML,

            supportsNativeClamp = typeof(element.style.webkitLineClamp) != 'undefined',
            clampValue = opt.clamp,
            isCSSValue = clampValue.indexOf && (clampValue.indexOf('px') > -1 || clampValue.indexOf('em') > -1),
            truncationHTMLContainer;
            
        if (opt.truncationHTML) {
            truncationHTMLContainer = document.createElement('span');
            truncationHTMLContainer.innerHTML = opt.truncationHTML;
        }


// UTILITY FUNCTIONS __________________________________________________________

        /**
         * Return the current style for an element.
         * @param {HTMLElement} elem The element to compute.
         * @param {string} prop The style property.
         * @returns {number}
         */
        function computeStyle(elem, prop) {
            if (!win.getComputedStyle) {
                win.getComputedStyle = function(el, pseudo) {
                    this.el = el;
                    this.getPropertyValue = function(prop) {
                        var re = /(\-([a-z]){1})/g;
                        if (prop == 'float') prop = 'styleFloat';
                        if (re.test(prop)) {
                            prop = prop.replace(re, function () {
                                return arguments[2].toUpperCase();
                            });
                        }
                        return el.currentStyle && el.currentStyle[prop] ? el.currentStyle[prop] : null;
                    }
                    return this;
                }
            }

            return win.getComputedStyle(elem, null).getPropertyValue(prop);
        }

        /**
         * Returns the maximum number of lines of text that should be rendered based
         * on the current height of the element and the line-height of the text.
         */
        function getMaxLines(height) {
            var availHeight = height || element.clientHeight,
                lineHeight = getLineHeight(element);

            return Math.max(Math.floor(availHeight/lineHeight), 0);
        }

        /**
         * Returns the maximum height a given element should have based on the line-
         * height of the text and the given clamp value.
         */
        function getMaxHeight(clmp) {
            var lineHeight = getLineHeight(element);
            return lineHeight * clmp;
        }

        /**
         * Returns the line-height of an element as an integer.
         */
        function getLineHeight(elem) {
            var lh = computeStyle(elem, 'line-height');
            if (lh == 'normal') {
                // Normal line heights vary from browser to browser. The spec recommends
                // a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff.
                lh = parseInt(computeStyle(elem, 'font-size')) * 1.2;
            }
            return parseInt(lh);
        }


// MEAT AND POTATOES (MMMM, POTATOES...) ______________________________________
        var splitOnChars = opt.splitOnChars.slice(0),
            splitChar = splitOnChars[0],
            chunks,
            lastChunk;
        
        /**
         * Gets an element's last child. That may be another node or a node's contents.
         */
        function getLastChild(elem) {
            
            // fix IE8 error SIR #437567
            if (elem.lastChild) {
                //Current element has children, need to go deeper and get last child as a text node
                if (elem.lastChild.children && elem.lastChild.children.length > 0) {
                    return getLastChild(Array.prototype.slice.call(elem.children).pop());
                }
                    //This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying
                else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue == '' || elem.lastChild.nodeValue == opt.truncationChar) {
                    elem.lastChild.parentNode.removeChild(elem.lastChild);
                    return getLastChild(element);
                }
                    //This is the last child we want, return it
                else {
                    return elem.lastChild;
                }
            }
            else {
                return elem;
            }
        }
        
        /**
         * Removes one character at a time from the text until its width or
         * height is beneath the passed-in max param.
         */
        function truncate(target, maxHeight) {
            if (!maxHeight) {return;}
            
            /**
             * Resets global variables.
             */
            function reset() {
                splitOnChars = opt.splitOnChars.slice(0);
                splitChar = splitOnChars[0];
                chunks = null;
                lastChunk = null;
            }
            
            // fix IE8 error SIR #437567
            var nodeValue = '';
            if (target.nodeValue) {
                nodeValue = target.nodeValue.replace(opt.truncationChar, '');
            }
            
            //Grab the next chunks
            if (!chunks) {
                //If there are more characters to try, grab the next one
                if (splitOnChars.length > 0) {
                    splitChar = splitOnChars.shift();
                }
                //No characters to chunk by. Go character-by-character
                else {
                    splitChar = '';
                }
                
                chunks = nodeValue.split(splitChar);
            }
            
            //If there are chunks left to remove, remove the last one and see if
            // the nodeValue fits.
            if (chunks.length > 1) {
                // console.log('chunks', chunks);
                lastChunk = chunks.pop();
                // console.log('lastChunk', lastChunk);
                applyEllipsis(target, chunks.join(splitChar));
            }
            //No more chunks can be removed using this character
            else {
                chunks = null;
            }
            
            //Insert the custom HTML before the truncation character
            if (truncationHTMLContainer) {
                target.nodeValue = target.nodeValue.replace(opt.truncationChar, '');
                element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
            }

            //Search produced valid chunks
            if (chunks) {
                //It fits
                if (element.clientHeight <= maxHeight) {
                    //There's still more characters to try splitting on, not quite done yet
                    if (splitOnChars.length >= 0 && splitChar != '') {
                        applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk);
                        chunks = null;
                    }
                    //Finished!
                    else {
                        return element.innerHTML;
                    }
                }
            }
            //No valid chunks produced
            else {
                //No valid chunks even when splitting by letter, time to move
                //on to the next node
                if (splitChar == '') {
                    applyEllipsis(target, '');
                    target = getLastChild(element);
                    
                    reset();
                }
            }
            
            //If you get here it means still too big, let's keep truncating
            if (opt.animate) {
                setTimeout(function() {
                    truncate(target, maxHeight);
                }, opt.animate === true ? 10 : opt.animate);
            }
            else {
                return truncate(target, maxHeight);
            }
        }
        
        function applyEllipsis(elem, str) {
            elem.nodeValue = str + opt.truncationChar;
        }


// CONSTRUCTOR ________________________________________________________________

        if (clampValue == 'auto') {
            clampValue = getMaxLines();
        }
        else if (isCSSValue) {
            clampValue = getMaxLines(parseInt(clampValue));
        }

        var clampedText;
        if (supportsNativeClamp && opt.useNativeClamp) {
            sty.overflow = 'hidden';
            sty.textOverflow = 'ellipsis';
            sty.webkitBoxOrient = 'vertical';
            sty.display = '-webkit-box';
            sty.webkitLineClamp = clampValue;

            if (isCSSValue) {
                sty.height = opt.clamp + 'px';
            }
        }
        else {
            var height = getMaxHeight(clampValue);
            if (height <= element.clientHeight) {
                clampedText = truncate(getLastChild(element), height);
            }
        }
        
        return {
            'original': originalText,
            'clamped': clampedText
        }
    }

    window.$clamp = clamp;
})();
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\jquery.acn.module-clamping.js
/*version 3.0*/
/**
 * jquery.acn.module-clamping
 *
 * A jQuery plugin for clamping texts. Use with clamp.js
 *
 * @version     v0.1.6-dev
 * @author      joseph.g.j.ocena, marlon.m.montes, fahim.ahmad.khan
 * @copyright   (c) 2013 - 2014 Accenture Inc.
 * @license
 */

/**
* When merging, please use this one in Enhancement branch.
**/

(function ($, window, document, undefined) {
    //Main functions
    $.fn.moduleClamping = function (option) {
        var options = $.extend({}, $.fn.moduleClamping.options, option);
        var clampCtr = 0;
        var clampDataArray = [];
        var $this = $(this);
        var onHovered = false; // Chrome does not move/arrange the tiles dynamically (packery) when unclamped, clamp should be called again

        var touch = 'ontouchstart' in window // works on most browsers
					|| window.navigator.msMaxTouchPoints;

        return this.each(function () {
            $(this).find(options.moduleSelector).each(function () {
                if (!$(this).find(options.titleSelector).hasClass('clamp')) {
                    ClampModule(this, options.titleMaximumRowCount, options.bodyMaximumRowCount, options.totalMaximumRowCount);
                    if (options.mouseOver == 'expand') {
                        ClampModuleEventHandlerBind(this);
                        if (touch) {
                            // for touch devices
                            $(this).find('a.articleHeadline')
                                .attr('onClick', 'return false;')
                                .addClass('touch-inactive');
                            $(this).addClass('touch-inactive');
                        }
                    }
                }
            });
        }).addClass("clamp-container");

        function ClampModule(module, tmax, bmax, total) {
            var $this = $(module);
            var title = $this.find(options.titleSelector)[0];
            var body = $this.find(options.bodySelector)[0];
            var unclampedHeight = module.offsetHeight;

            var lines = 0;
            //Clamp it upto 3 lines
            if (title != undefined && title != null) {
                // Calculate available lines
                var titleHeight = $(title).height();
                var lineHeight = $(title).css('line-height').replace("px", "");
                lines = Math.round(titleHeight / parseInt(lineHeight));

                //decide here whether to use clamp or fallback
                if (lines > tmax || onHovered == true) {
                    SaveClampText(title);
                    $clamp(title, { clamp: tmax });
                }

                if (lines > tmax) {
                    lines = tmax;
                }
            }
            if (body != undefined && body != null) {
                var bodyHeight = $(body).height();
                var bodyLineHeight = $(body).css('line-height').replace("px", "");
                bodyLines = Math.round(bodyHeight / parseInt(bodyLineHeight));

                var clampBodyLine = total - lines;

                //decide here whether to use clamp or fallback
                if (bodyLines > clampBodyLine || onHovered == true) {
                    SaveClampText(body);

                    if (clampBodyLine > bmax) {
                        clampBodyLine = bmax;
                    }

                    $clamp(body, { clamp: clampBodyLine });
                }
            }
            var clampedHeight = module.offsetHeight;

            if (touch && unclampedHeight != clampedHeight) { //if clamped addclass
                $(module).addClass('touch-inactive');
            }
        };

        function SaveClampText(element) {
            if (!$(element).hasClass('clamp')) {
                $(element).addClass('clamp')
                    .data('clamp-id', clampCtr);
                clampDataArray[clampCtr] = $(element).html();

                clampCtr++;
            }
        };

        function RestoreClampText(element) {
            var id = $(element).data('clamp-id');
            $(element).html(clampDataArray[id]);
        };

        function ClampModuleEventHandlerBind(component) {
            //data binding
            if (touch) {
                // for touch devices
                var $title = $(component).find('a.articleHeadline');

                $(component).on("click", function () {
                    var $component = $(this);
                    if ($component.hasClass('touch-inactive')) {
                        // activate						
                        ActivateArticleDynamicFeaturedModule(component);
                        $title.removeAttr('onClick');
                        $component.removeClass('touch-inactive');
                    }
                    else {
                        // deactivate
                        DeactivateArticleDynamicFeaturedModule(component);
                        $title.attr('onClick', 'return false;');
                        $component.addClass('touch-inactive');
                    }
                });

                $(component).on("mouseleave", function () {
                    // deactivate
                    DeactivateArticleDynamicFeaturedModule(component);
                    $title.attr('onClick', 'return false;');
                    $(this).addClass('touch-inactive');
                });
            }
            else {
                $(component).on("mouseenter",
                    function () {
                        ActivateArticleDynamicFeaturedModule(component);
                    }).on("mouseleave",
                        function () {
                            DeactivateArticleDynamicFeaturedModule(component);
                        }
                    );
            }
        };

        function ActivateArticleDynamicFeaturedModule(component) {
            var $comp = $(component);
            var title = $comp.find(options.titleSelector)[0];
            var body = $comp.find(options.bodySelector)[0];

            if (title != undefined && title != null) {
                RestoreClampText(title);
            }

            if (body != undefined && body != null) {
                RestoreClampText(body);
            }

            onHovered = true;

            ClampModule($comp, 50, 50, 100);
            options.onMouseOver.call($comp);
            $(body).attr('style', '');
            return false;
        };

        function DeactivateArticleDynamicFeaturedModule(component) {
            var $comp = $(component);
            var $title = $(component).find('a.articleHeadline');
            $comp.css('opacity', 1);

            var beforeClamp = component.offsetHeight;

            onHovered = false;

            ClampModule($comp, options.titleMaximumRowCount, options.bodyMaximumRowCount, options.totalMaximumRowCount);
            var mouseEntered = $(component).hasClass('mouse-entered-onload');
            var afterClamp = component.offsetHeight;
            if (touch && !mouseEntered) {
                if (beforeClamp == afterClamp) { //if true, meaning it was not clamped orginally, redirect
                    var url = $title.attr('href'), target = $title.attr('target');
                    if (url && url.length > 0) {
                        target == '_blank' ? window.open(url, '_blank') : window.location = url;
                    }
                }
            }
            options.onMouseOut.call($comp);

            return false;
        };
    };

    //default settings.
    $.fn.moduleClamping.options = {
        moduleSelector: ".module-article",
        titleSelector: "h4",
        bodySelector: ".module-body",
        titleMaximumRowCount: 3,
        bodyMaximumRowCount: 3,
        totalMaximumRowCount: 5,
        mouseOver: 'expand',
        onMouseOver: function () { },
        onMouseOut: function () { }
    };
})(jQuery, window, document);

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\styleCore\jquery.acn.smartModuleClamping.js
/*version 2.0*/
/**
 * jquery.acn.module-clamping
 *
 * A jQuery plugin for clamping texts. Use with clamp.js
 *
 * @version     v.2.2.0
 * @author      joseph.g.j.ocena
 * @copyright   (c) 2013 - 2014 Accenture Inc.
 * @license
 */

/**
* When merging, please use this one in Enhancement branch.
**/

(function ($, window, document, undefined) {
    //Main functions
    $.fn.smartModuleClamping = function (option) {
        var options = $.extend({}, $.fn.smartModuleClamping.options, option);
        var clampSelectors = JSON.parse(options.clampSelectors);
        var touch = 'ontouchstart' in window || window.navigator.msMaxTouchPoints;
        var removeClamp = 9999;
        var supportsNativeClamp = typeof (document.body.style.webkitLineClamp) != 'undefined';
        return this.each(function () {
            var $module = $(this).find(options.moduleSelector);

            $module.on("mouseenter", function () {
                if (options.expandOnHover == true) {
                    doClamping($(this), removeClamp);
                    $(this).find('p').attr('style', '');
                }
                options.onMouseEnter.call();
            }).on("mouseleave", function () {
                if (options.expandOnHover == true) {
                    doClamping($(this), 0);
                }
                options.onMouseLeave.call();
            })
                .each(function () {
                    doClamping($(this), 0);
                });

            if (touch && options.expandOnMobile == 'true') {
                $module.on("click", function () {
                    if ($module.hasClass("touch-clamp")) {
                        doClamping($(this), 0);
                        $module.removeClass("touch-clamp");
                    } else {
                        doClamping($(this), removeClamp);
                        $module.addClass("touch-clamp");
                    }
                });
            }
        })

        function doClamping(item, clampOverrideCount) {
            if (typeof clampSelectors !== "undefined") {
                $.each(clampSelectors, function (k, v) {
                    var clampSelector = item.find(k)[0];
                    if (typeof clampSelector !== "undefined") {
                        var clampCount = clampOverrideCount;
                        var $clampSelector = $(clampSelector);

                        if (clampCount != removeClamp) {
                            if (!supportsNativeClamp && typeof $clampSelector.data("clamp-text") == 'undefined') {
                                $clampSelector.data("clamp-text", encodeURI($clampSelector.html()))
                            }

                            clampCount = v;
                            var dataClampCount = $clampSelector.data("maxline");
                            if (typeof dataClampCount != "undefined") {
                                clampCount = dataClampCount;
                            }
                        }

                        if ($clampSelector.hasClass("clamp-list") == false) {
                            if (supportsNativeClamp || clampOverrideCount != removeClamp) {
                                $clamp(clampSelector, { clamp: clampCount, useNativeClamp: true });
                            } else {
                                $clampSelector.html(decodeURI($clampSelector.data("clamp-text")));
                            }
                        } else {
                            if (clampCount != removeClamp) {
                                $clampSelector.addClass("clamp-truncate").css("height", clampCount);
                            } else {
                                $clampSelector.removeClass("clamp-truncate").css("height", "");
                            }
                        }
                    }
                });
            }
        }
    };

    //default settings.
    $.fn.smartModuleClamping.options = {
        moduleSelector: ".module-article",
        clampSelectors: '{".clamp-title":"3", ".clamp-body":"3", ".clamp-list":"2"}',
        expandOnHover: true,
        expandOnMobile: "true",
        onMouseLeave: function () { },
        onMouseEnter: function () { }
    };
})(jQuery, window, document);

;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\acn\URLTracking.js
/* version="2" */
$(function () {
    if (navigator.userAgent.toLowerCase().indexOf('safari') == -1) {
        var isacncmAlive = typeof acncm.CacheManager != 'undefined' && acncm.CacheManager != null;
        if (isacncmAlive) {
            var url = $(location).attr('href');
            acncm.CacheManager.writeUrl("TrackingHistory", url);
        }

        SaveExternalReferrerUrl();
    }

});

function SaveExternalReferrerUrl() {

    var curDomain = document.domain;

    //check if 'External_ReferrerUrl' is existing
    var extRefUrl = localStorage.getItem("External_ReferrerUrl");
    var getReferrerUrl = '';
    if (document.referrer != '' && document.referrer != 'undefined' && document.referrer != null) {
        getReferrerUrl = document.referrer;
    }

    if (extRefUrl == 'undefined' || extRefUrl == null) {
        if (!(getReferrerUrl.indexOf(curDomain) > -1))
            localStorage.setItem("External_ReferrerUrl", getReferrerUrl);
    }
        //sets the value of 'External_ReferrerUrl'
    else if (extRefUrl == '') {
        if (!(getReferrerUrl.indexOf(curDomain) > -1))
            localStorage.setItem("External_ReferrerUrl", getReferrerUrl);
    }

}
;///#SOURCE 1 1 D:\Web\ACN\Website\Scripts\lib\jquery.lazy.js
/*version 2*/
/*!
 * jQuery & Zepto Lazy - v1.7.5
 * http://jquery.eisbehr.de/lazy/
 *
 * Copyright 2012 - 2017, Daniel 'Eisbehr' Kern
 *
 * Dual licensed under the MIT and GPL-2.0 licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl-2.0.html
 *
 * $("img.lazy").lazy();
 */

;(function(window, undefined) {
    "use strict";

    // noinspection JSUnresolvedVariable
    /**
     * library instance - here and not in construct to be shorter in minimization
     * @return void
     */
    var $ = window.jQuery || window.Zepto,

    /**
     * unique plugin instance id counter
     * @type {number}
     */
    lazyInstanceId = 0,

    /**
     * helper to register window load for jQuery 3
     * @type {boolean}
     */    
    windowLoaded = false;

    /**
     * make lazy available to jquery - and make it a bit more case-insensitive :)
     * @access public
     * @type {function}
     * @param {object} settings
     * @return void
     */
    $.fn.Lazy = $.fn.lazy = function(settings) {
        return new LazyPlugin(this, settings);
    };

    /**
     * helper to add plugins to lazy prototype configuration
     * @access public
     * @type {function}
     * @param {string|Array} names
     * @param {string|Array} [elements]
     * @param {function} loader
     * @return void
     */
    $.Lazy = $.lazy = function(names, elements, loader) {
        // make second parameter optional
        if (typeof elements === "function"  ) {
            loader = elements;
            elements = [];
        }

        // exit here if parameter is not a callable function
        if (typeof loader !== "function" ) return;

        // make parameters an array of names to be sure
        names = Array.isArray(names) ? names : [names];
        elements = Array.isArray(elements) ? elements : [elements];

        var config = LazyPlugin.prototype.config,
            forced = config._f || (config._f = {});

        // add the loader plugin for every name
        for( var i = 0, l = names.length; i < l; i++ )
            if (config[names[i]] === undefined || typeof config[names[i]] === "function" )
                config[names[i]] = loader;

        // add forced elements loader
        for( var c = 0, a = elements.length; c < a; c++ )
            forced[elements[c]] = names[0];
    };

    /**
     * contains all logic and the whole element handling
     * is packed in a private function outside class to reduce memory usage, because it will not be created on every plugin instance
     * @access private
     * @type {function}
     * @param {LazyPlugin} instance
     * @param {object} config
     * @param {object|Array} items
     * @param {object} events
     * @param {string} namespace
     * @return void
     */
    function _executeLazy(instance, config, items, events, namespace) {
        /**
         * a helper to trigger the 'onFinishedAll' callback after all other events
         * @access private
         * @type {number}
         */
        var _awaitingAfterLoad = 0,

        /**
         * visible content width
         * @access private
         * @type {number}
         */
        _actualWidth = -1,

        /**
         * visible content height
         * @access private
         * @type {number}
         */
        _actualHeight = -1,

        /**
         * determine possibly detected high pixel density
         * @access private
         * @type {boolean}
         */
        _isRetinaDisplay = false, 

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _afterLoad = "afterLoad",

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _load = "load",

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _error = "error",

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _img = "img",

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _src = "src",

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _srcset = "srcset",

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _sizes = "sizes",

        /**
         * dictionary entry for better minimization
         * @access private
         * @type {string}
         */
        _backgroundImage = "background-image";

        /**
         * initialize plugin
         * bind loading to events or set delay time to load all items at once
         * @access private
         * @return void
         */
        function _initialize() {
            // detect actual device pixel ratio
            // noinspection JSUnresolvedVariable
            _isRetinaDisplay = window.devicePixelRatio > 1;

            // prepare all initial items
            _prepareItems(items);

            // if delay time is set load all items at once after delay time
            if( config.delay >= 0 ) setTimeout(function() { _lazyLoadItems(true); }, config.delay);

            // if no delay is set or combine usage is active bind events
            if( config.delay < 0 || config.combined ) {
                // create unique event function
                events.e = _throttle(config.throttle, function(event) {
                    // reset detected window size on resize event
                    if( event.type === "resize" )
                        _actualWidth = _actualHeight = -1;

                    // execute 'lazy magic'
                    _lazyLoadItems(event.all);
                });

                // create function to add new items to instance
                events.a = function(additionalItems) {
                    _prepareItems(additionalItems);
                    items.push.apply(items, additionalItems);
                };

                // create function to get all instance items left
                events.g = function() {
                    // filter loaded items before return in case internal filter was not running until now
                    return (items = $(items).filter(function() {
                        return !$(this).data(config.loadedName);
                    }));
                };

                // create function to force loading elements
                events.f = function(forcedItems) {
                    for( var i = 0; i < forcedItems.length; i++ ) {
                        // only handle item if available in current instance
                        // use a compare function, because Zepto can't handle object parameter for filter
                        // var item = items.filter(forcedItems[i]);
                        /* jshint loopfunc: true */
                        var item = items.filter(function() {
                            return this === forcedItems[i];
                        });

                        if( item.length ) {
                            _lazyLoadItems(false, item);   
                        }
                    }
                };

                // load initial items
                _lazyLoadItems();

                // bind lazy load functions to scroll and resize event
                // noinspection JSUnresolvedVariable
                $(config.appendScroll).on("scroll." + namespace + " resize." + namespace, events.e);
            }
        }; 

        /**
         * prepare items before handle them
         * @access private
         * @param {Array|object|jQuery} items
         * @return void
         */
        function _prepareItems(items) {
            // fetch used configurations before loops
            var defaultImage = config.defaultImage,
                placeholder = config.placeholder,
                imageBase = config.imageBase,
                srcsetAttribute = config.srcsetAttribute,
                loaderAttribute = config.loaderAttribute,
                forcedTags = config._f || {};

            // filter items and only add those who not handled yet and got needed attributes available
            items = $(items).filter(function() {
                var element = $(this),
                    tag = _getElementTagName(this);

                return !element.data(config.handledName) && 
                       (element.attr(config.attribute) || element.attr(srcsetAttribute) || element.attr(loaderAttribute) || forcedTags[tag] !== undefined);
            })

            // append plugin instance to all elements
            .data("plugin_" + config.name, instance);

            for( var i = 0, l = items.length; i < l; i++ ) {
                var element = $(items[i]),
                    tag = _getElementTagName(items[i]),
                    elementImageBase = element.attr(config.imageBaseAttribute) || imageBase;

                // generate and update source set if an image base is set
                if( tag === _img && elementImageBase && element.attr(srcsetAttribute) )
                    element.attr(srcsetAttribute, _getCorrectedSrcSet(element.attr(srcsetAttribute), elementImageBase));

                // add loader to forced element types
                if( forcedTags[tag] !== undefined && !element.attr(loaderAttribute) )
                    element.attr(loaderAttribute, forcedTags[tag]);

                // set default image on every element without source
                if( tag === _img && defaultImage && !element.attr(_src) )
                    element.attr(_src, defaultImage);

                // set placeholder on every element without background image
                else if( tag !== _img && placeholder && (!element.css(_backgroundImage) || element.css(_backgroundImage) === "none") )
                    element.css(_backgroundImage, "url('" + placeholder + "')");
            }
        };

        /**
         * the 'lazy magic' - check all items
         * @access private
         * @param {boolean} [allItems]
         * @param {object} [forced]
         * @return void
         */
        function _lazyLoadItems(allItems, forced) {
            // skip if no items where left
            if( !items.length ) {
                // destroy instance if option is enabled
                if( config.autoDestroy )
                    // noinspection JSUnresolvedFunction
                    instance.destroy();

                return;
            }

            var elements = forced || items,
                loadTriggered = false,
                imageBase = config.imageBase || "",
                srcsetAttribute = config.srcsetAttribute,
                handledName = config.handledName;

            // loop all available items
            for( var i = 0; i < elements.length; i++ ) {
                // item is at least in loadable area
                if( allItems || forced || _isInLoadableArea(elements[i]) ) {
                    var element = $(elements[i]),
                        tag = _getElementTagName(elements[i]),
                        attribute = element.attr(config.attribute),
                        elementImageBase = element.attr(config.imageBaseAttribute) || imageBase,
                        customLoader = element.attr(config.loaderAttribute);

                        // is not already handled 
                    if( !element.data(handledName) &&
                        // and is visible or visibility doesn't matter
                        (!config.visibleOnly || element.is(":visible")) && (
                        // and image source or source set attribute is available
                        (attribute || element.attr(srcsetAttribute)) && (
                            // and is image tag where attribute is not equal source or source set
                            (tag === _img && (elementImageBase + attribute !== element.attr(_src) || element.attr(srcsetAttribute) !== element.attr(_srcset))) ||
                            // or is non image tag where attribute is not equal background
                            (tag !== _img && elementImageBase + attribute !== element.css(_backgroundImage)) 
                        ) ||
                        // or custom loader is available
                        customLoader ))
                    {
                        // mark element always as handled as this point to prevent double handling
                        loadTriggered = true;
                        element.data(handledName, true);

                        // load item
                        _handleItem(element, tag, elementImageBase, customLoader);
                    }
                }
            }

            // when something was loaded remove them from remaining items
            if( loadTriggered )
                items = $(items).filter(function() {
                    return !$(this).data(handledName);
                });
        };

        /**
         * load the given element the lazy way
         * @access private
         * @param {object} element
         * @param {string} tag
         * @param {string} imageBase
         * @param {function} [customLoader]
         * @return void
         */
        function _handleItem(element, tag, imageBase, customLoader) {
            // increment count of items waiting for after load
            ++_awaitingAfterLoad;

            // extended error callback for correct 'onFinishedAll' handling
            var errorCallback = function() {
                _triggerCallback("onError", element);
                _reduceAwaiting();

                // prevent further callback calls
                errorCallback = $.noop;
            };

            // trigger function before loading image
            _triggerCallback("beforeLoad", element);

            // fetch all double used data here for better code minimization
            var srcAttribute = config.attribute,
                srcsetAttribute = config.srcsetAttribute,
                sizesAttribute = config.sizesAttribute,
                retinaAttribute = config.retinaAttribute,
                removeAttribute = config.removeAttribute,
                loadedName = config.loadedName,
                elementRetina = element.attr(retinaAttribute);

            // handle custom loader
            if( customLoader ) {
                // on load callback
                var loadCallback = function() {
                    // remove attribute from element
                    if( removeAttribute )
                        element.removeAttr(config.loaderAttribute);

                    // mark element as loaded
                    element.data(loadedName, true);

                    // call after load event
                    _triggerCallback(_afterLoad, element);

                    // remove item from waiting queue and possibly trigger finished event
                    // it's needed to be asynchronous to run after filter was in _lazyLoadItems
                    setTimeout(_reduceAwaiting, 1);

                    // prevent further callback calls
                    loadCallback = $.noop;
                };

                // bind error event to trigger callback and reduce waiting amount
                element.off(_error).one(_error, errorCallback)

                // bind after load callback to element
                .one(_load, loadCallback);

                // trigger custom loader and handle response
                if( !_triggerCallback(customLoader, element, function(response) {
                    if( response ) {
                        element.off(_load);
                        loadCallback();
                    }
                    else {
                        element.off(_error);
                        errorCallback();
                    }
                })) element.trigger(_error);
            }

            // handle images
            else {
                // create image object
                var imageObj = $(new Image());

                // bind error event to trigger callback and reduce waiting amount
                imageObj.one(_error, errorCallback)

                // bind after load callback to image
                .one(_load, function() {
                    // remove element from view
                    element.hide();

                    // set image back to element
                    // do it as single 'attr' calls, to be sure 'src' is set after 'srcset'
                    if( tag === _img )
                        element.attr(_sizes, imageObj.attr(_sizes))
                               .attr(_srcset, imageObj.attr(_srcset))
                               .attr(_src, imageObj.attr(_src));
                    else
                        element.css(_backgroundImage, "url('" + imageObj.attr(_src) + "')");

                    // bring it back with some effect!
                    element[config.effect](config.effectTime);

                    // remove attribute from element
                    if( removeAttribute ) {
                        element.removeAttr(srcAttribute + " " + srcsetAttribute + " " + retinaAttribute + " " + config.imageBaseAttribute);

                        // only remove 'sizes' attribute, if it was a custom one
                        if( sizesAttribute !== _sizes )
                            element.removeAttr(sizesAttribute);
                    }

                    // mark element as loaded
                    element.data(loadedName, true);

                    // call after load event
                    _triggerCallback(_afterLoad, element);

                    // cleanup image object
                    imageObj.remove();

                    // remove item from waiting queue and possibly trigger finished event
                    _reduceAwaiting();
                });

                // set sources
                // do it as single 'attr' calls, to be sure 'src' is set after 'srcset'
                var imageSrc = (_isRetinaDisplay && elementRetina ? elementRetina : element.attr(srcAttribute)) || "";
                imageObj.attr(_sizes, element.attr(sizesAttribute))
                        .attr(_srcset, element.attr(srcsetAttribute))
                        .attr(_src, imageSrc ? imageBase + imageSrc : null);

                // call after load even on cached image
                imageObj.complete && imageObj.trigger(_load); // jshint ignore : line
            }
        };

        /**
         * check if the given element is inside the current viewport or threshold
         * @access private
         * @param {object} element
         * @return {boolean}
         */
        function _isInLoadableArea(element) {
            var elementBound = element.getBoundingClientRect(),
                direction    = config.scrollDirection,
                threshold    = config.threshold,
                vertical     = // check if element is in loadable area from top
                               ((_getActualHeight() + threshold) > elementBound.top) &&
                               // check if element is even in loadable are from bottom
                               (-threshold < elementBound.bottom),
                horizontal   = // check if element is in loadable area from left
                               ((_getActualWidth() + threshold) > elementBound.left) &&
                               // check if element is even in loadable area from right
                               (-threshold < elementBound.right);

            if( direction === "vertical" ) return vertical;
            else if( direction === "horizontal" ) return horizontal;

            return vertical && horizontal;
        }; 

        /**
         * receive the current viewed width of the browser
         * @access private
         * @return {number}
         */
        function _getActualWidth() {
            return _actualWidth >= 0 ? _actualWidth : (_actualWidth = $(window).width());
        }; 

        /**
         * receive the current viewed height of the browser
         * @access private
         * @return {number}
         */
        function _getActualHeight() {
            return _actualHeight >= 0 ? _actualHeight : (_actualHeight = $(window).height());
        }; 

        /**
         * get lowercase tag name of an element
         * @access private
         * @param {object} element
         * @returns {string}
         */
        function _getElementTagName(element) {
            return element.tagName.toLowerCase();
        }; 

        /**
         * prepend image base to all srcset entries
         * @access private
         * @param {string} srcset
         * @param {string} imageBase
         * @returns {string}
         */
        function _getCorrectedSrcSet(srcset, imageBase) {
            if( imageBase ) {
                // trim, remove unnecessary spaces and split entries
                var entries = srcset.split(",");
                srcset = "";

                for( var i = 0, l = entries.length; i < l; i++ )
                    srcset += imageBase + entries[i].trim() + (i !== l - 1 ? "," : "");
            }

            return srcset;
        }; 

        /**
         * helper function to throttle down event triggering
         * @access private
         * @param {number} delay
         * @param {function} callback
         * @return {function}
         */
        function _throttle(delay, callback) {
            var timeout,
                lastExecute = 0;

            return function(event, ignoreThrottle) {
                var elapsed = +new Date() - lastExecute;

                function run() {
                    lastExecute = +new Date();
                    callback.call(instance, event);
                }

                timeout && clearTimeout(timeout); // jshint ignore : line

                if( elapsed > delay || !config.enableThrottle || ignoreThrottle ) run();
                else timeout = setTimeout(run, delay - elapsed);
            };
        }; 

        /**
         * reduce count of awaiting elements to 'afterLoad' event and fire 'onFinishedAll' if reached zero
         * @access private
         * @return void
         */
        function _reduceAwaiting() {
            --_awaitingAfterLoad;

            // if no items were left trigger finished event
            if( !items.length && !_awaitingAfterLoad ) _triggerCallback("onFinishedAll");
        }; 

        /**
         * single implementation to handle callbacks, pass element and set 'this' to current instance
         * @access private
         * @param {string|function} callback
         * @param {object} [element]
         * @param {*} [args]
         * @return {boolean}
         */
        function _triggerCallback(callback, element, args) {
            if( (callback = config[callback]) ) {
                // jQuery's internal '$(arguments).slice(1)' are causing problems at least on old iPads
                // below is shorthand of 'Array.prototype.slice.call(arguments, 1)'
                callback.apply(instance, [].slice.call(arguments, 1));
                return true;
            }

            return false;
        }; 

        // if event driven or window is already loaded don't wait for page loading
        if( config.bind === "event" || windowLoaded )
            _initialize();

        // otherwise load initial items and start lazy after page load
        else // noinspection JSUnresolvedVariable
            $(window).on(_load + "." + namespace, _initialize);
    }

    /**
     * lazy plugin class constructor
     * @constructor
     * @access private
     * @param {object} elements
     * @param {object} settings
     * @return {object|LazyPlugin}
     */
    function LazyPlugin(elements, settings) {
        /**
         * this lazy plugin instance
         * @access private
         * @type {object|LazyPlugin|LazyPlugin.prototype}
         */
        var _instance = this,

        /**
         * this lazy plugin instance configuration
         * @access private
         * @type {object}
         */
        _config = $.extend({}, _instance.config, settings),

        /**
         * instance generated event executed on container scroll or resize
         * packed in an object to be referenceable and short named because properties will not be minified
         * @access private
         * @type {object}
         */
        _events = {},

        /**
         * unique namespace for instance related events
         * @access private
         * @type {string}
         */
        _namespace = _config.name + "-" + (++lazyInstanceId);

        // noinspection JSUndefinedPropertyAssignment
        /**
         * wrapper to get or set an entry from plugin instance configuration
         * much smaller on minify as direct access
         * @access public
         * @type {function}
         * @param {string} entryName
         * @param {*} [value]
         * @return {LazyPlugin|*}
         */
        _instance.config = function(entryName, value) {
            if( value === undefined )
                return _config[entryName];

            _config[entryName] = value;
            return _instance;
        };

        // noinspection JSUndefinedPropertyAssignment
        /**
         * add additional items to current instance
         * @access public
         * @param {Array|object|string} items
         * @return {LazyPlugin}
         */
        _instance.addItems = function(items) {
            _events.a && _events.a(typeof items === "string" ? $(items) : items); // jshint ignore : line
            return _instance;
        };

        // noinspection JSUndefinedPropertyAssignment
        /**
         * get all left items of this instance
         * @access public
         * @returns {object}
         */
        _instance.getItems = function() {
            return _events.g ? _events.g() : {};
        };

        // noinspection JSUndefinedPropertyAssignment
        /**
         * force lazy to load all items in loadable area right now
         * by default without throttle
         * @access public
         * @type {function}
         * @param {boolean} [useThrottle]
         * @return {LazyPlugin}
         */
        _instance.update = function(useThrottle) {
            _events.e && _events.e({}, !useThrottle); // jshint ignore : line
            return _instance;
        };

        // noinspection JSUndefinedPropertyAssignment
        /**
         * force element(s) to load directly, ignoring the viewport
         * @access public
         * @param {Array|object|string} items
         * @return {LazyPlugin}
         */
        _instance.force = function(items) {
            _events.f && _events.f(typeof items === "string" ? $(items) : items); // jshint ignore : line
            return _instance;
        };

        // noinspection JSUndefinedPropertyAssignment
        /**
         * force lazy to load all available items right now
         * this call ignores throttling
         * @access public
         * @type {function}
         * @return {LazyPlugin}
         */
        _instance.loadAll = function() {
            _events.e && _events.e({all: true}, true); // jshint ignore : line
            return _instance;
        };

        // noinspection JSUndefinedPropertyAssignment
        /**
         * destroy this plugin instance
         * @access public
         * @type {function}
         * @return undefined
         */
        _instance.destroy = function() {
            // unbind instance generated events
            // noinspection JSUnresolvedFunction, JSUnresolvedVariable
            $(_config.appendScroll).off("." + _namespace, _events.e);
            // noinspection JSUnresolvedVariable
            $(window).off("." + _namespace);

            // clear events
            _events = {};

            return undefined;
        };

        // start using lazy and return all elements to be chainable or instance for further use
        // noinspection JSUnresolvedVariable
        _executeLazy(_instance, _config, elements, _events, _namespace);
        return _config.chainable ? elements : _instance;
    }; 

    /**
     * settings and configuration data
     * @access public
     * @type {object}
     */
    LazyPlugin.prototype.config = {
        // general
        name               : "lazy",
        chainable          : true,
        autoDestroy        : true,
        bind               : "load",
        threshold          : 500,
        visibleOnly        : false,
        appendScroll       : window,
        scrollDirection    : "both",
        imageBase          : null,
        defaultImage       : "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==",
        placeholder        : null,
        delay              : -1,
        combined           : false,

        // attributes
        attribute          : "data-src",
        srcsetAttribute    : "data-srcset",
        sizesAttribute     : "data-sizes",
        retinaAttribute    : "data-retina",
        loaderAttribute    : "data-loader",
        imageBaseAttribute : "data-imagebase",
        removeAttribute    : true,
        handledName        : "handled",
        loadedName         : "loaded",

        // effect
        effect             : "show",
        effectTime         : 0,

        // throttle
        enableThrottle     : true,
        throttle           : 250,

        // callbacks
        beforeLoad         : undefined,
        afterLoad          : undefined,
        onError            : undefined,
        onFinishedAll      : undefined
    };

    // register window load event globally to prevent not loading elements
    // since jQuery 3.X ready state is fully async and may be executed after 'load' 
    $(window).on("load", function() { windowLoaded = true; });
})(window);
