PageSourceSearch

https://www.semcoop.com/sites/www.semcoop.com/files/js/js_37b4d4f9f6690d00b25e225384b0d800.js

js semcoop.com collected 2026-10-02 03:55:46 UTC 371,353 bytes, 6,995 lines download raw bytes

1/*
2 * jQuery JavaScript Library v1.3.2
3 * http://jquery.com/
4 *
5 * Copyright (c) 2009 John Resig
6 * Dual licensed under the MIT and GPL licenses.
7 * http://docs.jquery.com/License
8 *
9 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
10 * Revision: 6246
11 */
12(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})}
12,css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})}
12,remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?
120:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];
12if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
13/*
14 * Sizzle CSS Selector Engine - v0.9.3
15 *  Copyright 2009, The Dojo Foundation
16 *  Released under the MIT, BSD, and GPL Licenses.
17 *  More information: http://sizzlejs.com/
18 */
19(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*
19)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}
19if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCo
19de clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}
19o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();
19if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["o
19pacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;
19if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.
19clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();;
20/**
21 * For jQuery versions less than 3.4.0, this replaces the jQuery.extend
22 * function with the one from jQuery 3.4.0, slightly modified (documented
23 * below) to be compatible with older jQuery versions and browsers.
24 *
25 * This provides the Object.prototype pollution vulnerability fix to Drupal
26 * installations running older jQuery versions, including the versions shipped
27 * with Drupal core and https://www.drupal.org/project/jquery_update.
28 *
29 * @see https://github.com/jquery/jquery/pull/4333
30 */
31
32(function (jQuery) {
33
34// Do not override jQuery.extend() if the jQuery version is already >=3.4.0.
35var versionParts = jQuery.fn.jquery.split('.');
36var majorVersion = parseInt(versionParts[0]);
37var minorVersion = parseInt(versionParts[1]);
38var patchVersion = parseInt(versionParts[2]);
39var isPreReleaseVersion = (patchVersion.toString() !== versionParts[2]);
40if (
41  (majorVersion > 3) ||
42  (majorVersion === 3 && minorVersion > 4) ||
43  (majorVersion === 3 && minorVersion === 4 && patchVersion > 0) ||
44  (majorVersion === 3 && minorVersion === 4 && patchVersion === 0 && !isPreReleaseVersion)
45) {
46  return;
47}
48
49/**
50 * This adds some funtions from jQuery 1.4.4 (the default version used in
51 * Drupal 7) for when they aren't present, like when using jQuery 1.2.6 (the
52 * default version used in Drupal 6).
53 */
54
55if (typeof jQuery.type === 'undefined') {
56  var toString = Object.prototype.toString,
57      class2type = {};
58
59  // Populate the class2type map
60  jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
61    class2type[ "[object " + name + "]" ] = name.toLowerCase();
62  });
63
64  jQuery.type = function (obj) {
65    return obj == null ?
66      String( obj ) :
67      class2type[ toString.call(obj) ] || "object";
68  };
69}
70
71if (typeof jQuery.isArray === 'undefined') {
72  jQuery.isArray = function (obj) {
73    return jQuery.type(obj) === "array";
74  };
75}
76
77if (typeof jQuery.isWindow === 'undefined') {
78  jQuery.isWindow = function (obj) {
79    return obj && typeof obj === "object" && "setInterval" in obj;
80  };
81}
82
83if (typeof jQuery.isPlainObject === 'undefined') {
84  var hasOwn = Object.prototype.hasOwnProperty;
85
86  jQuery.isPlainObject = function (obj) {
87    // Must be an Object.
88    // Because of IE, we also have to check the presence of the constructor property.
89    // Make sure that DOM nodes and window objects don't pass through, as well
90    if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
91      return false;
92    }
93
94    // Not own constructor property must be Object
95    if ( obj.constructor &&
96      !hasOwn.call(obj, "constructor") &&
97      !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
98      return false;
99    }
100
101    // Own properties are enumerated firstly, so to speed up,
102    // if last one is own, then all properties are own.
103
104    var key;
105    for ( key in obj ) {}
106
107    return key === undefined || hasOwn.call( obj, key );
108  };
109}
110
111/**
112 * This is almost verbatim copied from jQuery 3.4.0.
113 *
114 * Only two minor changes have been made:
115 * - The call to isFunction() is changed to jQuery.isFunction().
116 * - The two calls to Array.isArray() is changed to jQuery.isArray().
117 *
118 * The above two changes ensure compatibility with all older jQuery versions
119 * (1.2.6 - 3.3.1) and older browser versions (e.g., IE8).
120 */
121jQuery.extend = jQuery.fn.extend = function() {
122  var options, name, src, copy, copyIsArray, clone,
123    target = arguments[ 0 ] || {},
124    i = 1,
125    length = arguments.length,
126    deep = false;
127
128  // Handle a deep copy situation
129  if ( typeof target === "boolean" ) {
130    deep = target;
131
132    // Skip the boolean and the target
133    target = arguments[ i ] || {};
134    i++;
135  }
136
137  // Handle case when target is a string or something (possible in deep copy)
138  if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
139    target = {};
140  }
141
142  // Extend jQuery itself if only one argument is passed
143  if ( i === length ) {
144    target = this;
145    i--;
146  }
147
148  for ( ; i < length; i++ ) {
149
150    // Only deal with non-null/undefined values
151    if ( ( options = arguments[ i ] ) != null ) {
152
153      // Extend the base object
154      for ( name in options ) {
155        copy = options[ name ];
156
157        // Prevent Object.prototype pollution
158        // Prevent never-ending loop
159        if ( name === "__proto__" || target === copy ) {
160          continue;
161        }
162
163        // Recurse if we're merging plain objects or arrays
164        if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
165          ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
166          src = target[ name ];
167
168          // Ensure proper type for the source value
169          if ( copyIsArray && !jQuery.isArray( src ) ) {
170            clone = [];
171          } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
172            clone = {};
173          } else {
174            clone = src;
175          }
176          copyIsArray = false;
177
178          // Never move original objects, clone them
179          target[ name ] = jQuery.extend( deep, clone, copy );
180
181          // Don't bring in undefined values
182        } else if ( copy !== undefined ) {
183          target[ name ] = copy;
184        }
185      }
186    }
187  }
188
189  // Return the modified object
190  return target;
191};
192
193})(jQuery);
194;
195/**
196 * For jQuery versions less than 3.5.0, this replaces the jQuery.htmlPrefilter()
197 * function with one that fixes these security vulnerabilities while also
198 * retaining the pre-3.5.0 behavior where it's safe to do so.
199 * - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-11022
200 * - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-11023
201 *
202 * Additionally, for jQuery versions that do not have a jQuery.htmlPrefilter()
203 * function (1.x prior to 1.12 and 2.x prior to 2.2), this adds it, and
204 * extends the functions that need to call it to do so.
205 *
206 * Drupal core's jQuery version is 1.4.4, but jQuery Update can provide a
207 * different version, so this covers all versions between 1.4.4 and 3.4.1.
208 * The GitHub links in the code comments below link to jQuery 1.5 code, because
209 * 1.4.4 isn't on GitHub, but the referenced code didn't change from 1.4.4 to
210 * 1.5.
211 */
212
213(function (jQuery) {
214
215  // Parts of this backport differ by jQuery version.
216  var versionParts = jQuery.fn.jquery.split('.');
217  var majorVersion = parseInt(versionParts[0]);
218  var minorVersion = parseInt(versionParts[1]);
219
220  // No backport is needed if we're already on jQuery 3.5 or higher.
221  if ( (majorVersion > 3) || (majorVersion === 3 && minorVersion >= 5) ) {
222    return;
223  }
224
225  // Prior to jQuery 3.5, jQuery converted XHTML-style self-closing tags to
226  // their XML equivalent: e.g., "<div />" to "<div></div>". This is
227  // problematic for several reasons, including that it's vulnerable to XSS
228  // attacks. However, since this was jQuery's behavior for many years, many
229  // Drupal modules and jQuery plugins may be relying on it. Therefore, we
230  // preserve that behavior, but for a limited set of tags only, that we believe
231  // to not be vulnerable. This is the set of HTML tags that satisfy all of the
232  // following conditions:
233  // - In DOMPurify's list of HTML tags. If an HTML tag isn't safe enough to
234  //   appear in that list, then we don't want to mess with it here either.
235  //   @see https://github.com/cure53/DOMPurify/blob/2.0.11/dist/purify.js#L128
236  // - A normal element (not a void, template, text, or foreign element).
237  //   @see https://html.spec.whatwg.org/multipage/syntax.html#elements-2
238  // - An element that is still defined by the current HTML specification
239  //   (not a deprecated element), because we do not want to rely on how
240  //   browsers parse deprecated elements.
241  //   @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element
242  // - Not 'html', 'head', or 'body', because this pseudo-XHTML expansion is
243  //   designed for fragments, not entire documents.
244  // - Not 'colgroup', because due to an idiosyncrasy of jQuery's original
245  //   regular expression, it didn't match on colgroup, and we don't want to
246  //   introduce a behavior change for that.
247  var selfClosingTagsToReplace = [
248    'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo',
249    'blockquote', 'button', 'canvas', 'caption', 'cite', 'code', 'data',
250    'datalist', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em',
251    'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3',
252    'h4', 'h5', 'h6', 'header', 'hgroup', 'i', 'ins', 'kbd', 'label', 'legend',
253    'li', 'main', 'map', 'mark', 'menu', 'meter', 'nav', 'ol', 'optgroup',
254    'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt',
255    'ruby', 's', 'samp', 'section', 'select', 'small', 'source', 'span',
256    'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th',
257    'thead', 'time', 'tr', 'u', 'ul', 'var', 'video'
258  ];
259
260  // Define regular expressions for <TAG/> and <TAG ATTRIBUTES/>. Doing this as
261  // two expressions makes it easier to target <a/> without also targeting
262  // every tag that starts with "a".
263  var xhtmlRegExpGroup = '(' + selfClosingTagsToReplace.join('|') + ')';
264  var whitespace = '[\\x20\\t\\r\\n\\f]';
265  var rxhtmlTagWithoutSpaceOrAttributes = new RegExp('<' + xhtmlRegExpGroup + '\\/>', 'gi');
266  var rxhtmlTagWithSpaceAndMaybeAttributes = new RegExp('<' + xhtmlRegExpGroup + '(' + whitespace + '[^>]*)\\/>', 'gi');
267
268  // jQuery 3.5 also fixed a vulnerability for when </select> appears within
269  // an <option> or <optgroup>, but it did that in local code that we can't
270  // backport directly. Instead, we filter such cases out. To do so, we need to
271  // determine when jQuery would otherwise invoke the vulnerable code, which it
272  // uses this regular expression to determine. The regular expression changed
273  // for version 3.0.0 and changed again for 3.4.0.
274  // @see https://github.com/jquery/jquery/blob/1.5/jquery.js#L4958
275  // @see https://github.com/jquery/jquery/blob/3.0.0/dist/jquery.js#L4584
276  // @see https://github.com/jquery/jquery/blob/3.4.0/dist/jquery.js#L4712
277  var rtagName;
278  if (majorVersion < 3) {
279    rtagName = /<([\w:]+)/;
280  }
281  else if (minorVersion < 4) {
282    rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]+)/i;
283  }
284  else {
285    rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i;
286  }
287
288  // The regular expression that jQuery uses to determine which self-closing
289  // tags to expand to open and close tags. This is vulnerable, because it
290  // matches all tag names except the few excluded ones. We only use this
291  // expression for determining vulnerability. The expression changed for
292  // version 3, but we only need to check for vulnerability in versions 1 and 2,
293  // so we use the expression from those versions.
294  // @see https://github.com/jquery/jquery/blob/1.5/jquery.js#L4957
295  var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
296
297  jQuery.extend({
298    htmlPrefilter: function (html) {
299      // This is how jQuery determines the first tag in the HTML.
300      // @see https://github.com/jquery/jquery/blob/1.5/jquery.js#L5521
301      var tag = ( rtagName.exec( html ) || [ "", "" ] )[ 1 ].toLowerCase();
302
303      // It is not valid HTML for <option> or <optgroup> to have <select> as
304      // either a descendant or sibling, and attempts to inject one can cause
305      // XSS on jQuery versions before 3.5. Since this is invalid HTML and a
306      // possible XSS attack, reject the entire string.
307      // @see https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-11023
308      if ((tag === 'option' || tag === 'optgroup') && html.match(/<\/?select/i)) {
309        html = '';
310      }
311
312      // Retain jQuery's prior to 3.5 conversion of pseudo-XHTML, but for only
313      // the tags in the `selfClosingTagsToReplace` list defined above.
314      // @see https://github.com/jquery/jquery/blob/1.5/jquery.js#L5518
315      // @see https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-11022
316      html = html.replace(rxhtmlTagWithoutSpaceOrAttributes, "<$1></$1>");
317      html = html.replace(rxhtmlTagWithSpaceAndMaybeAttributes, "<$1$2></$1>");
318
319      // Prior to jQuery 1.12 and 2.2, this function gets called (via code later
320      // in this file) in addition to, rather than instead of, the unsafe
321      // expansion of self-closing tags (including ones not in the list above).
322      // We can't prevent that unsafe expansion from running, so instead we
323      // check to make sure that it doesn't affect the DOM returned by the
324      // browser's parsing logic. If it does affect it, then it's vulnerable to
325      // XSS, so we reject the entire string.
326      if ( (majorVersion === 1 && minorVersion < 12) || (majorVersion === 2 && minorVersion < 2) ) {
327        var htmlRisky = html.replace(rxhtmlTag, "<$1></$2>");
328        if (htmlRisky !== html) {
329          // Even though htmlRisky and html are different strings, they might
330          // represent the same HTML structure once parsed, in which case,
331          // htmlRisky is actually safe. We can ask the browser to parse both
332          // to find out, but the browser can't parse table fragments (e.g., a
333          // root-level "<td>"), so we need to wrap them. We just need this
334          // technique to work on all supported browsers; we don't need to
335          // copy from the specific jQuery version we're using.
336          // @see https://github.com/jquery/jquery/blob/3.5.1/dist/jquery.js#L4939
337          var wrapMap = {
338            thead: [ 1, "<table>", "</table>" ],
339            col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
340            tr: [ 2, "<table><tbody>", "</tbody></table>" ],
341            td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
342          };
343          wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
344          wrapMap.th = wrapMap.td;
345
346          // Function to wrap HTML into something that a browser can parse.
347          // @see https://github.com/jquery/jquery/blob/3.5.1/dist/jquery.js#L5032
348          var getWrappedHtml = function (html) {
349            var wrap = wrapMap[tag];
350            if (wrap) {
351              html = wrap[1] + html + wrap[2];
352            }
353            return html;
354          };
355
356          // Function to return canonical HTML after parsing it. This parses
357          // only; it doesn't execute scripts.
358          // @see https://github.com/jquery/jquery-migrate/blob/3.3.0/src/jquery/manipulation.js#L5
359          var getParsedHtml = function (html) {
360            var doc = window.document.implementation.createHTMLDocument( "" );
361            doc.body.innerHTML = html;
362            return doc.body ? doc.body.innerHTML : '';
363          };
364
365          // If the browser couldn't parse either one successfully, or if
366          // htmlRisky parses differently than html, then html is vulnerable,
367          // so reject it.
368          var htmlParsed = getParsedHtml(getWrappedHtml(html));
369          var htmlRiskyParsed = getParsedHtml(getWrappedHtml(htmlRisky));
370          if (htmlRiskyParsed === '' || htmlParsed === '' || (htmlRiskyParsed !== htmlParsed)) {
371            html = '';
372          }
373        }
374      }
375
376      return html;
377    }
378  });
379
380  // Prior to jQuery 1.12 and 2.2, jQuery.clean(), jQuery.buildFragment(), and
381  // jQuery.fn.html() did not call jQuery.htmlPrefilter(), so we add that.
382  if ( (majorVersion === 1 && minorVersion < 12) || (majorVersion === 2 && minorVersion < 2) ) {
383    // Filter the HTML coming into jQuery.fn.html().
384    var fnOriginalHtml = jQuery.fn.html;
385    jQuery.fn.extend({
386      // @see https://github.com/jquery/jquery/blob/1.5/jquery.js#L5147
387      html: function (value) {
388        if (typeof value === "string") {
389          value = jQuery.htmlPrefilter(value);
390        }
391        // .html() can be called as a setter (with an argument) or as a getter
392        // (without an argument), so invoke fnOriginalHtml() the same way that
393        // we were invoked.
394        return fnOriginalHtml.apply(this, arguments.length ? [value] : []);
395      }
396    });
397
398    // The regular expression that jQuery uses to determine if a string is HTML.
399    // Used by both clean() and buildFragment().
400    // @see https://github.com/jquery/jquery/blob/1.5/jquery.js#L4960
401    var rhtml = /<|&#?\w+;/;
402
403    // Filter HTML coming into:
404    // - jQuery.clean() for versions prior to 1.9.
405    // - jQuery.buildFragment() for 1.9 and above.
406    //
407    // The looping constructs in the two functions might be essentially
408    // identical, but they're each expressed here in the way that most closely
409    // matches their original expression in jQuery, so that we filter all of
410    // the items and only the items that jQuery will treat as HTML strings.
411    if (majorVersion === 1 && minorVersion < 9) {
412      var originalClean = jQuery.clean;
413      jQuery.extend({
414        // @see https://github.com/jquery/jquery/blob/1.5/jquery.js#L5493
415        'clean': function (elems, context, fragment, scripts) {
416          for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
417            if ( typeof elem === "string" && rhtml.test( elem ) ) {
418              elems[i] = elem = jQuery.htmlPrefilter(elem);
419            }
420          }
421          return originalClean.call(this, elems, context, fragment, scripts);
422        }
423      });
424    }
425    else {
426      var originalBuildFragment = jQuery.buildFragment;
427      jQuery.extend({
428        // @see https://github.com/jquery/jquery/blob/1.9.0/jquery.js#L6419
429        'buildFragment': function (elems, context, scripts, selection) {
430          var l = elems.length;
431          for ( var i = 0; i < l; i++ ) {
432            var elem = elems[i];
433            if (elem || elem === 0) {
434              if ( jQuery.type( elem ) !== "object" && rhtml.test( elem ) ) {
435                elems[i] = elem = jQuery.htmlPrefilter(elem);
436              }
437            }
438          }
439          return originalBuildFragment.call(this, elems, context, scripts, selection);
440        }
441      });
442    }
443  }
444
445})(jQuery);
446;
447
448/**
449 * Override jQuery.fn.init to guard against XSS attacks.
450 *
451 * See http://bugs.jquery.com/ticket/9521
452 */
453(function () {
454  var jquery_init = jQuery.fn.init;
455  jQuery.fn.init = function (selector, context, rootjQuery) {
456    // If the string contains a "#" before a "<", treat it as invalid HTML.
457    if (selector && typeof selector === 'string') {
458      var hash_position = selector.indexOf('#');
459      if (hash_position >= 0) {
460        var bracket_position = selector.indexOf('<');
461        if (bracket_position > hash_position) {
462          throw 'Syntax error, unrecognized expression: ' + selector;
463        }
464      }
465    }
466    return jquery_init.call(this, selector, context, rootjQuery);
467  };
468  jQuery.fn.init.prototype = jquery_init.prototype;
469
470  /**
471   * Pre-filter Ajax requests to guard against XSS attacks.
472   *
473   * See https://github.com/jquery/jquery/issues/2432
474   */
475  if ($.ajaxPrefilter) {
476    // For newer versions of jQuery, use an Ajax prefilter to prevent
477    // auto-executing script tags from untrusted domains. This is similar to the
478    // fix that is built in to jQuery 3.0 and higher.
479    $.ajaxPrefilter(function (s) {
480      if (s.crossDomain) {
481        s.contents.script = false;
482      }
483    });
484  }
485  else if ($.httpData) {
486    // For the version of jQuery that ships with Drupal core, override
487    // jQuery.httpData to prevent auto-detecting "script" data types from
488    // untrusted domains.
489    var jquery_httpData = $.httpData;
490    $.httpData = function (xhr, type, s) {
491      // @todo Consider backporting code from newer jQuery versions to check for
492      //   a cross-domain request here, rather than using Drupal.urlIsLocal() to
493      //   block scripts from all URLs that are not on the same site.
494      if (!type && (!s || !Drupal.urlIsLocal(s.url))) {
495        var content_type = xhr.getResponseHeader('content-type') || '';
496        if (content_type.indexOf('javascript') >= 0) {
497          // Default to a safe data type.
498          type = 'text';
499        }
500      }
501      return jquery_httpData.call(this, xhr, type, s);
502    };
503    $.httpData.prototype = jquery_httpData.prototype;
504  }
505})();
506
507var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };
508
509/**
510 * Set the variable that indicates if JavaScript behaviors should be applied
511 */
512Drupal.jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById;
513
514/**
515 * Attach all registered behaviors to a page element.
516 *
517 * Behaviors are event-triggered actions that attach to page elements, enhancing
518 * default non-Javascript UIs. Behaviors are registered in the Drupal.behaviors
519 * object as follows:
520 * @code
521 *    Drupal.behaviors.behaviorName = function () {
522 *      ...
523 *    };
524 * @endcode
525 *
526 * Drupal.attachBehaviors is added below to the jQuery ready event and so
527 * runs on initial page load. Developers implementing AHAH/AJAX in their
528 * solutions should also call this function after new page content has been
529 * loaded, feeding in an element to be processed, in order to attach all
530 * behaviors to the new content.
531 *
532 * Behaviors should use a class in the form behaviorName-processed to ensure
533 * the behavior is attached only once to a given element. (Doing so enables
534 * the reprocessing of given elements, which may be needed on occasion despite
535 * the ability to limit behavior attachment to a particular element.)
536 *
537 * @param context
538 *   An element to attach behaviors to. If none is given, the document element
539 *   is used.
540 */
541Drupal.attachBehaviors = function(context) {
542  context = context || document;
543  if (Drupal.jsEnabled) {
544    // Execute all of them.
545    jQuery.each(Drupal.behaviors, function() {
546      this(context);
547    });
548  }
549};
550
551/**
552 * Encode special characters in a plain-text string for display as HTML.
553 */
554Drupal.checkPlain = function(str) {
555  str = String(str);
556  var replace = { '&': '&amp;', "'": '&#39;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
557  for (var character in replace) {
558    var regex = new RegExp(character, 'g');
559    str = str.replace(regex, replace[character]);
560  }
561  return str;
562};
563
564/**
565 * Translate strings to the page language or a given language.
566 *
567 * See the documentation of the server-side t() function for further details.
568 *
569 * @param str
570 *   A string containing the English string to translate.
571 * @param args
572 *   An object of replacements pairs to make after translation. Incidences
573 *   of any key in this array are replaced with the corresponding value.
574 *   Based on the first character of the key, the value is escaped and/or themed:
575 *    - !variable: inserted as is
576 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
577 *    - %variable: escape text and theme as a placeholder for user-submitted
578 *      content (checkPlain + Drupal.theme('placeholder'))
579 * @return
580 *   The translated string.
581 */
582Drupal.t = function(str, args) {
583  // Fetch the localized version of the string.
584  if (Drupal.locale.strings && Drupal.locale.strings[str]) {
585    str = Drupal.locale.strings[str];
586  }
587
588  if (args) {
589    // Transform arguments before inserting them
590    for (var key in args) {
591      switch (key.charAt(0)) {
592        // Escaped only
593        case '@':
594          args[key] = Drupal.checkPlain(args[key]);
595        break;
596        // Pass-through
597        case '!':
598          break;
599        // Escaped and placeholder
600        case '%':
601        default:
602          args[key] = Drupal.theme('placeholder', args[key]);
603          break;
604      }
605      str = str.replace(key, args[key]);
606    }
607  }
608  return str;
609};
610
611/**
612 * Format a string containing a count of items.
613 *
614 * This function ensures that the string is pluralized correctly. Since Drupal.t() is
615 * called by this function, make sure not to pass already-localized strings to it.
616 *
617 * See the documentation of the server-side format_plural() function for further details.
618 *
619 * @param count
620 *   The item count to display.
621 * @param singular
622 *   The string for the singular case. Please make sure it is clear this is
623 *   singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
624 *   Do not use @count in the singular string.
625 * @param plural
626 *   The string for the plural case. Please make sure it is clear this is plural,
627 *   to ease translation. Use @count in place of the item count, as in "@count
628 *   new comments".
629 * @param args
630 *   An object of replacements pairs to make after translation. Incidences
631 *   of any key in this array are replaced with the corresponding value.
632 *   Based on the first character of the key, the value is escaped and/or themed:
633 *    - !variable: inserted as is
634 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
635 *    - %variable: escape text and theme as a placeholder for user-submitted
636 *      content (checkPlain + Drupal.theme('placeholder'))
637 *   Note that you do not need to include @count in this array.
638 *   This replacement is done automatically for the plural case.
639 * @return
640 *   A translated string.
641 */
642Drupal.formatPlural = function(count, singular, plural, args) {
643  var args = args || {};
644  args['@count'] = count;
645  // Determine the index of the plural form.
646  var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);
647
648  if (index == 0) {
649    return Drupal.t(singular, args);
650  }
651  else if (index == 1) {
652    return Drupal.t(plural, args);
653  }
654  else {
655    args['@count['+ index +']'] = args['@count'];
656    delete args['@count'];
657    return Drupal.t(plural.replace('@count', '@count['+ index +']'), args);
658  }
659};
660
661/**
662 * Returns the passed in URL as an absolute URL.
663 *
664 * @param url
665 *   The URL string to be normalized to an absolute URL.
666 *
667 * @return
668 *   The normalized, absolute URL.
669 *
670 * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
671 * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
672 * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
673 */
674Drupal.absoluteUrl = function (url) {
675  var urlParsingNode = document.createElement('a');
676
677  // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
678  // strings may throw an exception.
679  try {
680    url = decodeURIComponent(url);
681  } catch (e) {}
682
683  urlParsingNode.setAttribute('href', url);
684
685  // IE <= 7 normalizes the URL when assigned to the anchor node similar to
686  // the other browsers.
687  return urlParsingNode.cloneNode(false).href;
688};
689
690/**
691 * Returns true if the URL is within Drupal's base path.
692 *
693 * @param url
694 *   The URL string to be tested.
695 *
696 * @return
697 *   Boolean true if local.
698 *
699 * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
700 */
701Drupal.urlIsLocal = function (url) {
702  // Always use browser-derived absolute URLs in the comparison, to avoid
703  // attempts to break out of the base path using directory traversal.
704  var absoluteUrl = Drupal.absoluteUrl(url);
705  var protocol = location.protocol;
706
707  // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
708  // as local as well.
709  if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
710    protocol = 'https:';
711  }
712  var baseUrl = protocol + '//' + location.host + Drupal.settings.basePath.slice(0, -1);
713
714  // Decoding non-UTF-8 strings may throw an exception.
715  try {
716    absoluteUrl = decodeURIComponent(absoluteUrl);
717  } catch (e) {}
718  try {
719    baseUrl = decodeURIComponent(baseUrl);
720  } catch (e) {}
721
722  // The given URL matches the site's base URL, or has a path under the site's
723  // base URL.
724  return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
725};
726
727/**
728 * Generate the themed representation of a Drupal object.
729 *
730 * All requests for themed output must go through this function. It examines
731 * the request and routes it to the appropriate theme function. If the current
732 * theme does not provide an override function, the generic theme function is
733 * called.
734 *
735 * For example, to retrieve the HTML that is output by theme_placeholder(text),
736 * call Drupal.theme('placeholder', text).
737 *
738 * @param func
739 *   The name of the theme function to call.
740 * @param ...
741 *   Additional arguments to pass along to the theme function.
742 * @return
743 *   Any data the theme function returns. This could be a plain HTML string,
744 *   but also a complex object.
745 */
746Drupal.theme = function(func) {
747  for (var i = 1, args = []; i < arguments.length; i++) {
748    args.push(arguments[i]);
749  }
750
751  return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
752};
753
754/**
755 * Parse a JSON response.
756 *
757 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
758 */
759Drupal.parseJson = function (data) {
760  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
761    return { status: 0, data: data.length ? data : Drupal.t('Unspecified error') };
762  }
763  return eval('(' + data + ');');
764};
765
766/**
767 * Freeze the current body height (as minimum height). Used to prevent
768 * unnecessary upwards scrolling when doing DOM manipulations.
769 */
770Drupal.freezeHeight = function () {
771  Drupal.unfreezeHeight();
772  var div = document.createElement('div');
773  $(div).css({
774    position: 'absolute',
775    top: '0px',
776    left: '0px',
777    width: '1px',
778    height: $('body').css('height')
779  }).attr('id', 'freeze-height');
780  $('body').append(div);
781};
782
783/**
784 * Unfreeze the body height
785 */
786Drupal.unfreezeHeight = function () {
787  $('#freeze-height').remove();
788};
789
790/**
791 * Wrapper around encodeURIComponent() which avoids Apache quirks (equivalent of
792 * drupal_urlencode() in PHP). This function should only be used on paths, not
793 * on query string arguments.
794 */
795Drupal.encodeURIComponent = function (item, uri) {
796  uri = uri || location.href;
797  item = encodeURIComponent(item).replace(/%2F/g, '/');
798  return (uri.indexOf('?q=') != -1) ? item : item.replace(/%26/g, '%2526').replace(/%23/g, '%2523').replace(/\/\//g, '/%252F');
799};
800
801/**
802 * Get the text selection in a textarea.
803 */
804Drupal.getSelection = function (element) {
805  if (typeof(element.selectionStart) != 'number' && document.selection) {
806    // The current selection
807    var range1 = document.selection.createRange();
808    var range2 = range1.duplicate();
809    // Select all text.
810    range2.moveToElementText(element);
811    // Now move 'dummy' end point to end point of original range.
812    range2.setEndPoint('EndToEnd', range1);
813    // Now we can calculate start and end points.
814    var start = range2.text.length - range1.text.length;
815    var end = start + range1.text.length;
816    return { 'start': start, 'end': end };
817  }
818  return { 'start': element.selectionStart, 'end': element.selectionEnd };
819};
820
821/**
822 * Sanitizes a URL for use with jQuery.ajax().
823 *
824 * @param url
825 *   The URL string to be sanitized.
826 *
827 * @return
828 *   The sanitized URL.
829 */
830Drupal.sanitizeAjaxUrl = function (url) {
831  var regex = /\=\?(&|$)/;
832  while (url.match(regex)) {
833    url = url.replace(regex, '');
834  }
835  return url;
836}
837
838/**
839 * Build an error message from ahah response.
840 */
841Drupal.ahahError = function(xmlhttp, uri) {
842  if (xmlhttp.status == 200) {
843    if (jQuery.trim($(xmlhttp.responseText).text())) {
844      var message = Drupal.t("An error occurred. \n@uri\n@text", {'@uri': uri, '@text': xmlhttp.responseText });
845    }
846    else {
847      var message = Drupal.t("An error occurred. \n@uri\n(no information available).", {'@uri': uri, '@text': xmlhttp.responseText });
848    }
849  }
850  else {
851    var message = Drupal.t("An HTTP error @status occurred. \n@uri", {'@uri': uri, '@status': xmlhttp.status });
852  }
853  return message;
854}
855
856// Global Killswitch on the <html> element
857if (Drupal.jsEnabled) {
858  // Global Killswitch on the <html> element
859  $(document.documentElement).addClass('js');
860  // 'js enabled' cookie
861  document.cookie = 'has_js=1; path=/';
862  // Attach all behaviors.
863  $(document).ready(function() {
864    Drupal.attachBehaviors(this);
865  });
866}
867
868/**
869 * The default themes.
870 */
871Drupal.theme.prototype = {
872
873  /**
874   * Formats text for emphasized display in a placeholder inside a sentence.
875   *
876   * @param str
877   *   The text to format (plain-text).
878   * @return
879   *   The formatted text (html).
880   */
881  placeholder: function(str) {
882    return '<em>' + Drupal.checkPlain(str) + '</em>';
883  }
884};
885;
886
887Drupal.behaviors.block_edit = function (context) {
888  if (Drupal.settings.block_edit.hover_links) {
889    $('.node-edit-link, .block-edit-link').hide();
890    $('div.block, div.node').mouseover(function() {
891      $(this).find('.node-edit-link, .block-edit-link').css('display', 'block');
892    });
893
894    $('div.block, div.node').mouseout(function() {
895      $(this).find('.node-edit-link, .block-edit-link').css('display', 'none');
896    });
897  };
898};
899;
900var lateBinds = [];
901var lateBindCount = 0;
902var lateBindInterval = false;
903function lateBind(cls, sel, evt, fnc, onload) { lateBinds.push({ cls: cls, sel: sel, evt: evt, fnc: fnc, onload: onload }); }
904function doLateBinds() {
905  lateBindCount++; if(lateBindCount > 1200) clearInterval(lateBindInterval);
906  jQuery.each(lateBinds, function(k, el) {
907    if(jQuery(el['sel']).not('.'+el['cls']).length > 0) {
908      jQuery(el['sel']).not('.'+el['cls']).addClass(el['cls']);
909      if (typeof jQuery(el['sel'])[el['evt']] != 'function') { console.log(el['evt']+' is not a valid event for '+el['sel']); return; }
910      jQuery(el['sel'])[el['evt']](el['fnc']);
911      // If passed a boolean, call event if boolean is true
912      if (typeof el['onload'] === 'boolean' && el['onload']) { jQuery(el['sel'])[el['evt']](); }
913      // If passed a selector string, call event if item matches selector
914      if (typeof el['onload'] === 'string') { jQuery(el['sel']).filter(el['onload'])[el['evt']](); }
915    }
916  });
917}
918jQuery(document).ready(function($) {
919  lateBindInterval = setInterval(doLateBinds, 500);
920  // lateBind Binds an event on an object that is added dynamically after page load
921  // USAGE:
922  // lateBind('UNIQNAME', 'SELECTOR', 'BINDEVENT', FUNCTION() {});
923  // EXAMPLE:
924  // lateBind('payment-radio-change', 'input[name="panes[payment][payment_method]"]:radio', 'change', function() {
925  //  console.log('pmt method changed to '+$(this).val());
926  // });
927
928  /* inline-block fix - prevents whitespace between LIs messing up the inline-blocks - no floats required! */
929  $('ul li:first-child').each(function() { if($(this).css('display') == 'inline-block') $(this).parent().addClass("herk-inline-block-fix"); });
930  var css = document.createElement("style"); css.type = "text/css";
931  css.innerHTML = "ul.herk-inline-block-fix { letter-spacing: -0.31em; *letter-spacing: normal; word-spacing: -0.43em; } ul.herk-inline-block-fix li { zoom: 1; *display: inline; letter-spacing: normal; word-spacing: normal; vertical-align: top; }";
932  document.body.appendChild(css);
933
934});  
935;
936// $Id: dhtml_menu.js,v 1.18.2.10 2009/01/12 10:13:30 arancaytar Exp $
937
938/**
939 * @file dhtml_menu.js
940 * The Javascript code for DHTML Menu
941 */
942 
943Drupal.dhtmlMenu = {};
944
945/**
946 * Initialize the module's JS functions
947 */
948Drupal.behaviors.dhtmlMenu = function() {
949  // Do not run this function more than once.
950  if (Drupal.dhtmlMenu.init) {
951    return;
952  }
953  else {
954    Drupal.dhtmlMenu.init = true;
955  }
956
957  // Get the settings.
958  var effects = Drupal.settings.dhtmlMenu;
959
960  $('.collapsed').removeClass('expanded');
961
962  // Get cookie
963  if (!effects.siblings) {
964    var cookie = Drupal.dhtmlMenu.cookieGet();
965    for (var i in cookie) {
966      // If the cookie was not applied to the HTML code yet, do so now.
967      var li = $('#dhtml_menu-' + cookie[i]).parents('li:first');
968      if ($(li).hasClass('collapsed')) {
969        Drupal.dhtmlMenu.toggleMenu(li);
970      }
971    }
972  }
973
974  /* Add jQuery effects and listeners to all menu items.
975   * The ~ (sibling) selector is unidirectional and selects 
976   * only the latter element, so we must use siblings() to get 
977   * back to the link element.
978   */
979   $('ul.menu li.dhtml-menu:not(.leaf,.no-dhtml)').each(function() {
980    var li = this;
981    if (effects.clone) {
982      var ul = $(li).find('ul:first');
983      if (ul.length) {
984        $(li).find('a:first').clone().prependTo(ul).wrap('<li class="leaf fake-leaf"></li>');
985      }
986    }
987
988    if (effects.doubleclick) {
989      $(li).find('a:first').dblclick(function(e) {
990        window.location = this.href;
991      });
992    }
993
994    $(li).find('a:first').click(function(e) {
995      Drupal.dhtmlMenu.toggleMenu($(li));
996      return false;
997    });
998  });
999}
1000
1001/**
1002 * Toggles the menu's state between open and closed.
1003 *
1004 * @param li
1005 *   Object. The <li> element that will be expanded or collapsed.
1006 */
1007Drupal.dhtmlMenu.toggleMenu = function(li) {
1008  var effects = Drupal.settings.dhtmlMenu;
1009
1010  // If the menu is expanded, collapse it.
1011  if($(li).hasClass('expanded')) {
1012    if (effects.slide) {
1013      $(li).find('ul:first').animate({height: 'hide', opacity: 'hide'}, '1000');
1014    }
1015    else $(li).find('ul:first').css('display', 'none');
1016
1017    // If children are closed automatically, find and close them now.
1018    if (effects.children) {
1019      if (effects.slide) {
1020        $(li).find('li.expanded').find('ul:first').animate({height: 'hide', opacity: 'hide'}, '1000');
1021      }
1022      else $(li).find('li.expanded').find('ul:first').css('display', 'none');
1023
1024      $(li).find('li.expanded').removeClass('expanded').addClass('collapsed')
1025    }
1026
1027    $(li).removeClass('expanded').addClass('collapsed');
1028  }
1029
1030  // Otherwise, expand it.
1031  else {
1032    if (effects.slide) {
1033      $(li).find('ul:first').animate({height: 'show', opacity: 'show'}, '1000');
1034    }
1035    else $(li).find('ul:first').css('display', 'block');
1036    $(li).removeClass('collapsed').addClass('expanded');
1037
1038    // If the siblings effect is on, close all sibling menus.
1039    if (effects.siblings) {
1040      var id = $(li).find('a:first').attr('id');
1041
1042      // Siblings are all open menus that are neither parents nor children of this menu.
1043      $(li).find('li').addClass('own-children-temp');
1044	  
1045      // If the relativity option is on, select only the siblings that have the same parent
1046      if (effects.relativity) {
1047        var siblings = $(li).parent().find('li.expanded').not('.own-children-temp').not(':has(#' + id + ')');
1048      }
1049      // Otherwise, select all menus of the same level
1050      else {
1051        var siblings = $('ul.menu li.expanded').not('.own-children-temp').not(':has(#' + id + ')');
1052      }
1053
1054      // If children should not get closed automatically...
1055      if (!effects.children) {
1056        // Remove items that are currently hidden from view (do not close these).
1057        $('li.collapsed li.expanded').addClass('sibling-children-temp');
1058        // Only close the top-most open sibling, not its children.
1059        $(siblings).find('li.expanded').addClass('sibling-children-temp');
1060        siblings = $(siblings).not('.sibling-children-temp');
1061      }
1062
1063      $('.own-children-temp, .sibling-children-temp').removeClass('own-children-temp').removeClass('sibling-children-temp');
1064
1065      if (effects.slide) {
1066        $(siblings).find('ul:first').animate({height: 'hide', opacity: 'hide'}, '1000');
1067      }
1068      else $(siblings).find('ul:first').css('display', 'none');
1069
1070      $(siblings).removeClass('expanded').addClass('collapsed');
1071    }
1072  }
1073
1074  // Save the current state of the menus in the cookie.
1075  Drupal.dhtmlMenu.cookieSet();
1076}
1077
1078/**
1079 * Reads the dhtml_menu cookie.
1080 */
1081Drupal.dhtmlMenu.cookieGet = function() {
1082  var c = /dhtml_menu=(.*?)(;|$)/.exec(document.cookie);
1083  if (c) {
1084    return c[1];
1085  }
1086  else return '';
1087}
1088
1089/**
1090 * Saves the dhtml_menu cooki.
1091 */
1092Drupal.dhtmlMenu.cookieSet = function() {
1093  var expanded = new Array();
1094  $('li.expanded').each(function() {
1095    expanded.push($(this).find('a:first').attr('id').substr(5));
1096  });
1097  document.cookie = 'dhtml_menu=' + expanded.join(',') + ';path=/';
1098}
1099
1100;
1101
1102/**
1103 * @file
1104 * Enables and disables expiration fields to prevent invalid configurations.
1105 */
1106
1107/**
1108 * Disables duration amount when its type is "never".
1109 */
1110function _uc_role_expiration_disable_check(granularity, quantity) {
1111  // 'never' means there's no point in setting a duration.
1112  if ($(granularity).val() == 'never') {
1113    $(quantity).attr('disabled', 'disabled').val('');
1114  }
1115  // Anything besides 'never' should enable setting a duration.
1116  else {
1117    $(quantity).removeAttr('disabled');
1118  }
1119}
1120
1121/**
1122 * Switch between relative and absolute expiration durations.
1123 */
1124function expiration_switcher() {
1125  if ($('#edit-expiration').val() == 'abs') {
1126    $("#edit-uc-roles-expire-relative-duration-wrapper").hide();
1127    $("#edit-uc-roles-expire-relative-granularity-wrapper").hide();
1128    $("#edit-uc-roles-by-quantity-wrapper").hide();
1129    $("#edit-uc-roles-expire-absolute-wrapper").show();
1130  }
1131  else {
1132    $("#edit-uc-roles-expire-absolute-wrapper").hide();
1133    $("#edit-uc-roles-expire-relative-duration-wrapper").show();
1134    $("#edit-uc-roles-expire-relative-granularity-wrapper").show();
1135    $("#edit-uc-roles-by-quantity-wrapper").show();
1136  }
1137}
1138
1139/**
1140 * Set the default state for expiration duration.
1141 */
1142function expiration_switcher_default() {
1143  if ($('#edit-uc-roles-default-end-expiration').val() == 'abs') {
1144    $("#edit-uc-roles-default-length-wrapper").attr('style', 'display:none;');
1145    $("#edit-uc-roles-default-granularity-wrapper").attr('style', 'display:none;');
1146    $("#edit-uc-roles-default-by-quantity-wrapper").attr('style', 'display:none;');
1147    $("#edit-uc-roles-default-end-time-wrapper").removeAttr('style');
1148  }
1149  else {
1150    $("#edit-uc-roles-default-length-wrapper").removeAttr('style');
1151    $("#edit-uc-roles-default-granularity-wrapper").removeAttr('style');
1152    $("#edit-uc-roles-default-by-quantity-wrapper").removeAttr('style');
1153    $("#edit-uc-roles-default-end-time-wrapper").attr('style', 'display:none;');
1154  }
1155}
1156
1157/**
1158 * Override the expiration duration default state.
1159 */
1160function uc_roles_expiration_default_override() {
1161  if ($('#edit-end-override').length == 0) {
1162    return;
1163  }
1164
1165  if ($('#edit-end-override').attr('checked')) {
1166    $('#edit-expiration-wrapper').removeAttr('style');
1167    $('#edit-uc-roles-expire-absolute-wrapper').removeAttr('style');
1168    $('#edit-uc-roles-expire-relative-duration-wrapper').removeAttr('style');
1169    $('#edit-uc-roles-expire-relative-granularity-wrapper').removeAttr('style');
1170    $('#edit-uc-roles-by-quantity-wrapper').removeAttr('style');
1171    expiration_switcher();
1172  }
1173  else {
1174    $('#edit-expiration-wrapper').attr('style', 'display:none;');
1175    $('#edit-uc-roles-expire-relative-duration-wrapper').attr('style', 'display:none;');
1176    $('#edit-uc-roles-expire-relative-granularity-wrapper').attr('style', 'display:none;');
1177    $('#edit-uc-roles-by-quantity-wrapper').attr('style', 'display:none;');
1178    $('#edit-uc-roles-expire-absolute-wrapper').attr('style', 'display:none;');
1179  }
1180}
1181
1182$(document).ready(
1183  function() {
1184    _uc_role_expiration_disable_check('#edit-uc-roles-expire-relative-granularity', '#edit-uc-roles-expire-relative-duration');
1185    _uc_role_expiration_disable_check('#edit-uc-roles-default-granularity', '#edit-uc-roles-default-length');
1186    _uc_role_expiration_disable_check('#edit-uc-roles-reminder-granularity', '#edit-uc-roles-reminder-length');
1187    uc_roles_expiration_default_override();
1188    expiration_switcher_default();
1189  }
1190);
1191
1192// When you change the role expiration time select.
1193Drupal.behaviors.ucRoleExpirationTime = function(context) {
1194  $("#edit-expiration:not(.ucRoleExpirationTime-processed)", context).addClass('ucRoleExpirationTime-processed').change(
1195    function() {
1196      expiration_switcher();
1197    }
1198  );
1199}
1200
1201// When you change the default role expiration time select.
1202Drupal.behaviors.ucRoleDefaultExpirationTimeDefault = function(context) {
1203  $("#edit-uc-roles-default-end-expiration:not(.ucRoleDefaultExpirationTimeDefault-processed)", context).addClass('ucRoleDefaultExpirationTimeDefault-processed').change(
1204    function() {
1205      expiration_switcher_default();
1206    }
1207  );
1208}
1209
1210// When you change the role expiration time select.
1211Drupal.behaviors.ucRoleExpirationTimeDefault = function(context) {
1212  $("#edit-uc-roles-end-expiration:not(.ucRoleExpirationTimeDefault-processed)", context).addClass('ucRoleExpirationTimeDefault-processed').change(
1213    function() {
1214      expiration_switcher_default();
1215    }
1216  );
1217}
1218
1219// When you change the role expiration granularity select.
1220Drupal.behaviors.ucRoleExpirationGranularity = function(context) {
1221  $('#edit-uc-roles-expire-relative-granularity:not(.ucRoleExpirationGranularity-processed)', context).addClass('ucRoleExpirationGranularity-processed').change(
1222    function() {
1223      _uc_role_expiration_disable_check('#edit-uc-roles-expire-relative-granularity', '#edit-uc-roles-expire-relative-duration');
1224    }
1225  );
1226}
1227
1228// When you change the default role expiration granularity select.
1229Drupal.behaviors.ucRoleDefaultExpirationGranularity = function(context) {
1230  $('#edit-uc-roles-default-granularity:not(.ucRoleDefaultExpirationGranularity-processed)', context).addClass('ucRoleDefaultExpirationGranularity-processed').change(
1231    function() {
1232      _uc_role_expiration_disable_check('#edit-uc-roles-default-granularity', '#edit-uc-roles-default-length');
1233    }
1234  );
1235}
1236
1237// When you change the default role expiration granularity select.
1238Drupal.behaviors.ucRoleReminderExpirationGranularity = function(context) {
1239  $('#edit-uc-roles-reminder-granularity:not(.ucRoleReminderExpirationGranularity-processed)', context).addClass('ucRoleReminderExpirationGranularity-processed').change(
1240    function() {
1241      _uc_role_expiration_disable_check('#edit-uc-roles-reminder-granularity', '#edit-uc-roles-reminder-length');
1242    }
1243  );
1244}
1245
1246// When you change the default role expiration granularity select.
1247Drupal.behaviors.ucRoleExpirationEndOverride = function(context) {
1248  $('#edit-end-override:not(.ucRoleExpirationEndOverride-processed)', context).addClass('ucRoleExpirationEndOverride-processed').click(
1249    function() {
1250      uc_roles_expiration_default_override();
1251    }
1252  );
1253}
1254
1255;
1256/* $Id: lightbox.js,v 1.5.2.6.2.136 2010/09/24 08:39:40 snpower Exp $ */
1257
1258/**
1259 * jQuery Lightbox
1260 * @author
1261 *   Stella Power, <http://drupal.org/user/66894>
1262 *
1263 * Based on Lightbox v2.03.3 by Lokesh Dhakar
1264 * <http://www.huddletogether.com/projects/lightbox2/>
1265 * Also partially based on the jQuery Lightbox by Warren Krewenki
1266 *   <http://warren.mesozen.com>
1267 *
1268 * Permission has been granted to Mark Ashmead & other Drupal Lightbox2 module
1269 * maintainers to distribute this file via Drupal.org
1270 * Under GPL license.
1271 *
1272 * Slideshow, iframe and video functionality added by Stella Power.
1273 */
1274
1275var Lightbox = {
1276  auto_modal : false,
1277  overlayOpacity : 0.8, // Controls transparency of shadow overlay.
1278  overlayColor : '000', // Controls colour of shadow overlay.
1279  disableCloseClick : true,
1280  // Controls the order of the lightbox resizing animation sequence.
1281  resizeSequence: 0, // 0: simultaneous, 1: width then height, 2: height then width.
1282  resizeSpeed: 'normal', // Controls the speed of the lightbox resizing animation.
1283  fadeInSpeed: 'normal', // Controls the speed of the image appearance.
1284  slideDownSpeed: 'slow', // Controls the speed of the image details appearance.
1285  minWidth: 240,
1286  borderSize : 10,
1287  boxColor : 'fff',
1288  fontColor : '000',
1289  topPosition : '',
1290  infoHeight: 20,
1291  alternative_layout : false,
1292  imageArray : [],
1293  imageNum : null,
1294  total : 0,
1295  activeImage : null,
1296  inprogress : false,
1297  disableResize : false,
1298  disableZoom : false,
1299  isZoomedIn : false,
1300  rtl : false,
1301  loopItems : false,
1302  keysClose : ['c', 'x', 27],
1303  keysPrevious : ['p', 37],
1304  keysNext : ['n', 39],
1305  keysZoom : ['z'],
1306  keysPlayPause : [32],
1307
1308  // Slideshow options.
1309  slideInterval : 5000, // In milliseconds.
1310  showPlayPause : true,
1311  autoStart : true,
1312  autoExit : true,
1313  pauseOnNextClick : false, // True to pause the slideshow when the "Next" button is clicked.
1314  pauseOnPrevClick : true, // True to pause the slideshow when the "Prev" button is clicked.
1315  slideIdArray : [],
1316  slideIdCount : 0,
1317  isSlideshow : false,
1318  isPaused : false,
1319  loopSlides : false,
1320
1321  // Iframe options.
1322  isLightframe : false,
1323  iframe_width : 600,
1324  iframe_height : 400,
1325  iframe_border : 1,
1326
1327  // Video and modal options.
1328  enableVideo : false,
1329  flvPlayer : '/flvplayer.swf',
1330  flvFlashvars : '',
1331  isModal : false,
1332  isVideo : false,
1333  videoId : false,
1334  modalWidth : 400,
1335  modalHeight : 400,
1336  modalHTML : null,
1337
1338
1339  // initialize()
1340  // Constructor runs on completion of the DOM loading.
1341  // The function inserts html at the bottom of the page which is used
1342  // to display the shadow overlay and the image container.
1343  initialize: function() {
1344
1345    var s = Drupal.settings.lightbox2;
1346    Lightbox.overlayOpacity = s.overlay_opacity;
1347    Lightbox.overlayColor = s.overlay_color;
1348    Lightbox.disableCloseClick = s.disable_close_click;
1349    Lightbox.resizeSequence = s.resize_sequence;
1350    Lightbox.resizeSpeed = s.resize_speed;
1351    Lightbox.fadeInSpeed = s.fade_in_speed;
1352    Lightbox.slideDownSpeed = s.slide_down_speed;
1353    Lightbox.borderSize = s.border_size;
1354    Lightbox.boxColor = s.box_color;
1355    Lightbox.fontColor = s.font_color;
1356    Lightbox.topPosition = s.top_position;
1357    Lightbox.rtl = s.rtl;
1358    Lightbox.loopItems = s.loop_items;
1359    Lightbox.keysClose = s.keys_close.split(" ");
1360    Lightbox.keysPrevious = s.keys_previous.split(" ");
1361    Lightbox.keysNext = s.keys_next.split(" ");
1362    Lightbox.keysZoom = s.keys_zoom.split(" ");
1363    Lightbox.keysPlayPause = s.keys_play_pause.split(" ");
1364    Lightbox.disableResize = s.disable_resize;
1365    Lightbox.disableZoom = s.disable_zoom;
1366    Lightbox.slideInterval = s.slideshow_interval;
1367    Lightbox.showPlayPause = s.show_play_pause;
1368    Lightbox.showCaption = s.show_caption;
1369    Lightbox.autoStart = s.slideshow_automatic_start;
1370    Lightbox.autoExit = s.slideshow_automatic_exit;
1371    Lightbox.pauseOnNextClick = s.pause_on_next_click;
1372    Lightbox.pauseOnPrevClick = s.pause_on_previous_click;
1373    Lightbox.loopSlides = s.loop_slides;
1374    Lightbox.alternative_layout = s.use_alt_layout;
1375    Lightbox.iframe_width = s.iframe_width;
1376    Lightbox.iframe_height = s.iframe_height;
1377    Lightbox.iframe_border = s.iframe_border;
1378    Lightbox.enableVideo = s.enable_video;
1379    if (s.enable_video) {
1380      Lightbox.flvPlayer = s.flvPlayer;
1381      Lightbox.flvFlashvars = s.flvFlashvars;
1382    }
1383
1384    // Make the lightbox divs.
1385    var layout_class = (s.use_alt_layout ? 'lightbox2-alt-layout' : 'lightbox2-orig-layout');
1386    var output = '<div id="lightbox2-overlay" style="display: none;"></div>\
1387      <div id="lightbox" style="display: none;" class="' + layout_class + '">\
1388        <div id="outerImageContainer"></div>\
1389        <div id="imageDataContainer" class="clearfix">\
1390          <div id="imageData"></div>\
1391        </div>\
1392      </div>';
1393    var loading = '<div id="loading"><a href="#" id="loadingLink"></a></div>';
1394    var modal = '<div id="modalContainer" style="display: none;"></div>';
1395    var frame = '<div id="frameContainer" style="display: none;"></div>';
1396    var imageContainer = '<div id="imageContainer" style="display: none;"></div>';
1397    var details = '<div id="imageDetails"></div>';
1398    var bottomNav = '<div id="bottomNav"></div>';
1399    var image = '<img id="lightboxImage" alt="" />';
1400    var hoverNav = '<div id="hoverNav"><a id="prevLink" href="#"></a><a id="nextLink" href="#"></a></div>';
1401    var frameNav = '<div id="frameHoverNav"><a id="framePrevLink" href="#"></a><a id="frameNextLink" href="#"></a></div>';
1402    var hoverNav = '<div id="hoverNav"><a id="prevLink" title="' + Drupal.t('Previous') + '" href="#"></a><a id="nextLink" title="' + Drupal.t('Next') + '" href="#"></a></div>';
1403    var frameNav = '<div id="frameHoverNav"><a id="framePrevLink" title="' + Drupal.t('Previous') + '" href="#"></a><a id="frameNextLink" title="' + Drupal.t('Next') + '" href="#"></a></div>';
1404    var caption = '<span id="caption"></span>';
1405    var numberDisplay = '<span id="numberDisplay"></span>';
1406    var close = '<a id="bottomNavClose" title="' + Drupal.t('Close') + '" href="#"></a>';
1407    var zoom = '<a id="bottomNavZoom" href="#"></a>';
1408    var zoomOut = '<a id="bottomNavZoomOut" href="#"></a>';
1409    var pause = '<a id="lightshowPause" title="' + Drupal.t('Pause Slideshow') + '" href="#" style="display: none;"></a>';
1410    var play = '<a id="lightshowPlay" title="' + Drupal.t('Play Slideshow') + '" href="#" style="display: none;"></a>';
1411
1412    $("body").append(output);
1413    $('#outerImageContainer').append(modal + frame + imageContainer + loading);
1414    if (!s.use_alt_layout) {
1415      $('#imageContainer').append(image + hoverNav);
1416      $('#imageData').append(details + bottomNav);
1417      $('#imageDetails').append(caption + numberDisplay);
1418      $('#bottomNav').append(frameNav + close + zoom + zoomOut + pause + play);
1419    }
1420    else {
1421      $('#outerImageContainer').append(bottomNav);
1422      $('#imageContainer').append(image);
1423      $('#bottomNav').append(close + zoom + zoomOut);
1424      $('#imageData').append(hoverNav + details);
1425      $('#imageDetails').append(caption + numberDisplay + pause + play);
1426    }
1427
1428    // Setup onclick handlers.
1429    if (Lightbox.disableCloseClick) {
1430      $('#lightbox2-overlay').click(function() { Lightbox.end(); return false; } ).hide();
1431    }
1432    $('#loadingLink, #bottomNavClose').click(function() { Lightbox.end('forceClose'); return false; } );
1433    $('#prevLink, #framePrevLink').click(function() { Lightbox.changeData(Lightbox.activeImage - 1); return false; } );
1434    $('#nextLink, #frameNextLink').click(function() { Lightbox.changeData(Lightbox.activeImage + 1); return false; } );
1435    $('#bottomNavZoom').click(function() { Lightbox.changeData(Lightbox.activeImage, true); return false; } );
1436    $('#bottomNavZoomOut').click(function() { Lightbox.changeData(Lightbox.activeImage, false); return false; } );
1437    $('#lightshowPause').click(function() { Lightbox.togglePlayPause("lightshowPause", "lightshowPlay"); return false; } );
1438    $('#lightshowPlay').click(function() { Lightbox.togglePlayPause("lightshowPlay", "lightshowPause"); return false; } );
1439
1440    // Fix positioning.
1441    $('#prevLink, #nextLink, #framePrevLink, #frameNextLink').css({ 'paddingTop': Lightbox.borderSize + 'px'});
1442    $('#imageContainer, #frameContainer, #modalContainer').css({ 'padding': Lightbox.borderSize + 'px'});
1443    $('#outerImageContainer, #imageDataContainer, #bottomNavClose').css({'backgroundColor': '#' + Lightbox.boxColor, 'color': '#'+Lightbox.fontColor});
1444    if (Lightbox.alternative_layout) {
1445      $('#bottomNavZoom, #bottomNavZoomOut').css({'bottom': Lightbox.borderSize + 'px', 'right': Lightbox.borderSize + 'px'});
1446    }
1447    else if (Lightbox.rtl == 1 && $.browser.msie) {
1448      $('#bottomNavZoom, #bottomNavZoomOut').css({'left': '0px'});
1449    }
1450
1451    // Force navigation links to always be displayed
1452    if (s.force_show_nav) {
1453      $('#prevLink, #nextLink').addClass("force_show_nav");
1454    }
1455
1456  },
1457
1458  // initList()
1459  // Loops through anchor tags looking for 'lightbox', 'lightshow' and
1460  // 'lightframe', etc, references and applies onclick events to appropriate
1461  // links. You can rerun after dynamically adding images w/ajax.
1462  initList : function(context) {
1463
1464    if (context == undefined || context == null) {
1465      context = document;
1466    }
1467
1468    // Attach lightbox to any links with rel 'lightbox', 'lightshow' or
1469    // 'lightframe', etc.
1470    $("a[rel^='lightbox']:not(.lightbox-processed), area[rel^='lightbox']:not(.lightbox-processed)", context).addClass('lightbox-processed').click(function(e) {
1471      if (Lightbox.disableCloseClick) {
1472        $('#lightbox').unbind('click');
1473        $('#lightbox').click(function() { Lightbox.end('forceClose'); } );
1474      }
1475      Lightbox.start(this, false, false, false, false);
1476      if (e.preventDefault) { e.preventDefault(); }
1477      return false;
1478    });
1479    $("a[rel^='lightshow']:not(.lightbox-processed), area[rel^='lightshow']:not(.lightbox-processed)", context).addClass('lightbox-processed').click(function(e) {
1480      if (Lightbox.disableCloseClick) {
1481        $('#lightbox').unbind('click');
1482        $('#lightbox').click(function() { Lightbox.end('forceClose'); } );
1483      }
1484      Lightbox.start(this, true, false, false, false);
1485      if (e.preventDefault) { e.preventDefault(); }
1486      return false;
1487    });
1488    $("a[rel^='lightframe']:not(.lightbox-processed), area[rel^='lightframe']:not(.lightbox-processed)", context).addClass('lightbox-processed').click(function(e) {
1489      if (Lightbox.disableCloseClick) {
1490        $('#lightbox').unbind('click');
1491        $('#lightbox').click(function() { Lightbox.end('forceClose'); } );
1492      }
1493      Lightbox.start(this, false, true, false, false);
1494      if (e.preventDefault) { e.preventDefault(); }
1495      return false;
1496    });
1497    if (Lightbox.enableVideo) {
1498      $("a[rel^='lightvideo']:not(.lightbox-processed), area[rel^='lightvideo']:not(.lightbox-processed)", context).addClass('lightbox-processed').click(function(e) {
1499        if (Lightbox.disableCloseClick) {
1500          $('#lightbox').unbind('click');
1501          $('#lightbox').click(function() { Lightbox.end('forceClose'); } );
1502        }
1503        Lightbox.start(this, false, false, true, false);
1504        if (e.preventDefault) { e.preventDefault(); }
1505        return false;
1506      });
1507    }
1508    $("a[rel^='lightmodal']:not(.lightbox-processed), area[rel^='lightmodal']:not(.lightbox-processed)", context).addClass('lightbox-processed').click(function(e) {
1509      $('#lightbox').unbind('click');
1510      // Add classes from the link to the lightbox div - don't include lightbox-processed
1511      $('#lightbox').addClass($(this).attr('class'));
1512      $('#lightbox').removeClass('lightbox-processed');
1513      Lightbox.start(this, false, false, false, true);
1514      if (e.preventDefault) { e.preventDefault(); }
1515      return false;
1516    });
1517    $("#lightboxAutoModal:not(.lightbox-processed)", context).addClass('lightbox-processed').click(function(e) {
1518      Lightbox.auto_modal = true;
1519      $('#lightbox').unbind('click');
1520      Lightbox.start(this, false, false, false, true);
1521      if (e.preventDefault) { e.preventDefault(); }
1522      return false;
1523    });
1524  },
1525
1526  // start()
1527  // Display overlay and lightbox. If image is part of a set, add siblings to
1528  // imageArray.
1529  start: function(imageLink, slideshow, lightframe, lightvideo, lightmodal) {
1530
1531    Lightbox.isPaused = !Lightbox.autoStart;
1532
1533    // Replaces hideSelectBoxes() and hideFlash() calls in original lightbox2.
1534    Lightbox.toggleSelectsFlash('hide');
1535
1536    // Stretch overlay to fill page and fade in.
1537    var arrayPageSize = Lightbox.getPageSize();
1538    $("#lightbox2-overlay").hide().css({
1539      'width': '100%',
1540      'zIndex': '10090',
1541      'height': arrayPageSize[1] + 'px',
1542      'backgroundColor' : '#' + Lightbox.overlayColor
1543    });
1544    // Detect OS X FF2 opacity + flash issue.
1545    if (lightvideo && this.detectMacFF2()) {
1546      $("#lightbox2-overlay").removeClass("overlay_default");
1547      $("#lightbox2-overlay").addClass("overlay_macff2");
1548      $("#lightbox2-overlay").css({'opacity' : null});
1549    }
1550    else {
1551      $("#lightbox2-overlay").removeClass("overlay_macff2");
1552      $("#lightbox2-overlay").addClass("overlay_default");
1553      $("#lightbox2-overlay").css({'opacity' : Lightbox.overlayOpacity});
1554    }
1555    $("#lightbox2-overlay").fadeIn(Lightbox.fadeInSpeed);
1556
1557
1558    Lightbox.isSlideshow = slideshow;
1559    Lightbox.isLightframe = lightframe;
1560    Lightbox.isVideo = lightvideo;
1561    Lightbox.isModal = lightmodal;
1562    Lightbox.imageArray = [];
1563    Lightbox.imageNum = 0;
1564
1565    var anchors = $(imageLink.tagName);
1566    var anchor = null;
1567    var rel_parts = Lightbox.parseRel(imageLink);
1568    var rel = rel_parts["rel"];
1569    var rel_group = rel_parts["group"];
1570    var title = (rel_parts["title"] ? rel_parts["title"] : imageLink.title);
1571    var rel_style = null;
1572    var i = 0;
1573
1574    if (rel_parts["flashvars"]) {
1575      Lightbox.flvFlashvars = Lightbox.flvFlashvars + '&' + rel_parts["flashvars"];
1576    }
1577
1578    // Set the title for image alternative text.
1579    var alt = imageLink.title;
1580    if (!alt) {
1581      var img = $(imageLink).find("img");
1582      if (img && $(img).attr("alt")) {
1583        alt = $(img).attr("alt");
1584      }
1585      else {
1586        alt = title;
1587      }
1588    }
1589
1590    if ($(imageLink).attr('id') == 'lightboxAutoModal') {
1591      rel_style = rel_parts["style"];
1592      Lightbox.imageArray.push(['#lightboxAutoModal > *', title, alt, rel_style, 1]);
1593    }
1594    else {
1595      // Handle lightbox images with no grouping.
1596      if ((rel == 'lightbox' || rel == 'lightshow') && !rel_group) {
1597        Lightbox.imageArray.push([imageLink.href, title, alt]);
1598      }
1599
1600      // Handle other items with no grouping.
1601      else if (!rel_group) {
1602        rel_style = rel_parts["style"];
1603        Lightbox.imageArray.push([imageLink.href, title, alt, rel_style]);
1604      }
1605
1606      // Handle grouped items.
1607      else {
1608
1609        // Loop through anchors and add them to imageArray.
1610        for (i = 0; i < anchors.length; i++) {
1611          anchor = anchors[i];
1612          if (anchor.href && typeof(anchor.href) == "string" && $(anchor).attr('rel')) {
1613            var rel_data = Lightbox.parseRel(anchor);
1614            var anchor_title = (rel_data["title"] ? rel_data["title"] : anchor.title);
1615            img_alt = anchor.title;
1616            if (!img_alt) {
1617              var anchor_img = $(anchor).find("img");
1618              if (anchor_img && $(anchor_img).attr("alt")) {
1619                img_alt = $(anchor_img).attr("alt");
1620              }
1621              else {
1622                img_alt = title;
1623              }
1624            }
1625            if (rel_data["rel"] == rel) {
1626              if (rel_data["group"] == rel_group) {
1627                if (Lightbox.isLightframe || Lightbox.isModal || Lightbox.isVideo) {
1628                  rel_style = rel_data["style"];
1629                }
1630                Lightbox.imageArray.push([anchor.href, anchor_title, img_alt, rel_style]);
1631              }
1632            }
1633          }
1634        }
1635
1636        // Remove duplicates.
1637        for (i = 0; i < Lightbox.imageArray.length; i++) {
1638          for (j = Lightbox.imageArray.length-1; j > i; j--) {
1639            if (Lightbox.imageArray[i][0] == Lightbox.imageArray[j][0]) {
1640              Lightbox.imageArray.splice(j,1);
1641            }
1642          }
1643        }
1644        while (Lightbox.imageArray[Lightbox.imageNum][0] != imageLink.href) {
1645          Lightbox.imageNum++;
1646        }
1647      }
1648    }
1649
1650    if (Lightbox.isSlideshow && Lightbox.showPlayPause && Lightbox.isPaused) {
1651      $('#lightshowPlay').show();
1652      $('#lightshowPause').hide();
1653    }
1654
1655    // Calculate top and left offset for the lightbox.
1656    var arrayPageScroll = Lightbox.getPageScroll();
1657    var lightboxTop = arrayPageScroll[1] + (Lightbox.topPosition == '' ? (arrayPageSize[3] / 10) : Lightbox.topPosition) * 1;
1658    var lightboxLeft = arrayPageScroll[0];
1659    $('#frameContainer, #modalContainer, #lightboxImage').hide();
1660    $('#hoverNav, #prevLink, #nextLink, #frameHoverNav, #framePrevLink, #frameNextLink').hide();
1661    $('#imageDataContainer, #numberDisplay, #bottomNavZoom, #bottomNavZoomOut').hide();
1662    $('#outerImageContainer').css({'width': '250px', 'height': '250px'});
1663    $('#lightbox').css({
1664      'zIndex': '10500',
1665      'top': lightboxTop + 'px',
1666      'left': lightboxLeft + 'px'
1667    }).show();
1668
1669    Lightbox.total = Lightbox.imageArray.length;
1670    Lightbox.changeData(Lightbox.imageNum);
1671  },
1672
1673  // changeData()
1674  // Hide most elements and preload image in preparation for resizing image
1675  // container.
1676  changeData: function(imageNum, zoomIn) {
1677
1678    if (Lightbox.inprogress === false) {
1679      if (Lightbox.total > 1 && ((Lightbox.isSlideshow && Lightbox.loopSlides) || (!Lightbox.isSlideshow && Lightbox.loopItems))) {
1680        if (imageNum >= Lightbox.total) imageNum = 0;
1681        if (imageNum < 0) imageNum = Lightbox.total - 1;
1682      }
1683
1684      if (Lightbox.isSlideshow) {
1685        for (var i = 0; i < Lightbox.slideIdCount; i++) {
1686          window.clearTimeout(Lightbox.slideIdArray[i]);
1687        }
1688      }
1689      Lightbox.inprogress = true;
1690      Lightbox.activeImage = imageNum;
1691
1692      if (Lightbox.disableResize && !Lightbox.isSlideshow) {
1693        zoomIn = true;
1694      }
1695      Lightbox.isZoomedIn = zoomIn;
1696
1697
1698      // Hide elements during transition.
1699      $('#loading').css({'zIndex': '10500'}).show();
1700      if (!Lightbox.alternative_layout) {
1701        $('#imageContainer').hide();
1702      }
1703      $('#frameContainer, #modalContainer, #lightboxImage').hide();
1704      $('#hoverNav, #prevLink, #nextLink, #frameHoverNav, #framePrevLink, #frameNextLink').hide();
1705      $('#imageDataContainer, #numberDisplay, #bottomNavZoom, #bottomNavZoomOut').hide();
1706
1707      // Preload image content, but not iframe pages.
1708      if (!Lightbox.isLightframe && !Lightbox.isVideo && !Lightbox.isModal) {
1709        $("#lightbox #imageDataContainer").removeClass('lightbox2-alt-layout-data');
1710        imgPreloader = new Image();
1711        imgPreloader.onerror = function() { Lightbox.imgNodeLoadingError(this); };
1712
1713        imgPreloader.onload = function() {
1714          var photo = document.getElementById('lightboxImage');
1715          photo.src = Lightbox.imageArray[Lightbox.activeImage][0];
1716          photo.alt = Lightbox.imageArray[Lightbox.activeImage][2];
1717
1718          var imageWidth = imgPreloader.width;
1719          var imageHeight = imgPreloader.height;
1720
1721          // Resize code.
1722          var arrayPageSize = Lightbox.getPageSize();
1723          var targ = { w:arrayPageSize[2] - (Lightbox.borderSize * 2), h:arrayPageSize[3] - (Lightbox.borderSize * 6) - (Lightbox.infoHeight * 4) - (arrayPageSize[3] / 10) };
1724          var orig = { w:imgPreloader.width, h:imgPreloader.height };
1725
1726          // Image is very large, so show a smaller version of the larger image
1727          // with zoom button.
1728          if (zoomIn !== true) {
1729            var ratio = 1.0; // Shrink image with the same aspect.
1730            $('#bottomNavZoomOut, #bottomNavZoom').hide();
1731            if ((orig.w >= targ.w || orig.h >= targ.h) && orig.h && orig.w) {
1732              ratio = ((targ.w / orig.w) < (targ.h / orig.h)) ? targ.w / orig.w : targ.h / orig.h;
1733              if (!Lightbox.disableZoom && !Lightbox.isSlideshow) {
1734                $('#bottomNavZoom').css({'zIndex': '10500'}).show();
1735              }
1736            }
1737
1738            imageWidth  = Math.floor(orig.w * ratio);
1739            imageHeight = Math.floor(orig.h * ratio);
1740          }
1741
1742          else {
1743            $('#bottomNavZoom').hide();
1744            // Only display zoom out button if the image is zoomed in already.
1745            if ((orig.w >= targ.w || orig.h >= targ.h) && orig.h && orig.w) {
1746              // Only display zoom out button if not a slideshow and if the
1747              // buttons aren't disabled.
1748              if (!Lightbox.disableResize && Lightbox.isSlideshow === false && !Lightbox.disableZoom) {
1749                $('#bottomNavZoomOut').css({'zIndex': '10500'}).show();
1750              }
1751            }
1752          }
1753
1754          photo.style.width = (imageWidth) + 'px';
1755          photo.style.height = (imageHeight) + 'px';
1756          Lightbox.resizeContainer(imageWidth, imageHeight);
1757
1758          // Clear onLoad, IE behaves irratically with animated gifs otherwise.
1759          imgPreloader.onload = function() {};
1760        };
1761
1762        imgPreloader.src = Lightbox.imageArray[Lightbox.activeImage][0];
1763        imgPreloader.alt = Lightbox.imageArray[Lightbox.activeImage][2];
1764      }
1765
1766      // Set up frame size, etc.
1767      else if (Lightbox.isLightframe) {
1768        $("#lightbox #imageDataContainer").addClass('lightbox2-alt-layout-data');
1769        var src = Lightbox.imageArray[Lightbox.activeImage][0];
1770        $('#frameContainer').html('<iframe id="lightboxFrame" style="display: none;" src="'+src+'"></iframe>');
1771
1772        // Enable swf support in Gecko browsers.
1773        if ($.browser.mozilla && src.indexOf('.swf') != -1) {
1774          setTimeout(function () {
1775            document.getElementById("lightboxFrame").src = Lightbox.imageArray[Lightbox.activeImage][0];
1776          }, 1000);
1777        }
1778
1779        if (!Lightbox.iframe_border) {
1780          $('#lightboxFrame').css({'border': 'none'});
1781          $('#lightboxFrame').attr('frameborder', '0');
1782        }
1783        var iframe = document.getElementById('lightboxFrame');
1784        var iframeStyles = Lightbox.imageArray[Lightbox.activeImage][3];
1785        iframe = Lightbox.setStyles(iframe, iframeStyles);
1786        Lightbox.resizeContainer(parseInt(iframe.width, 10), parseInt(iframe.height, 10));
1787      }
1788      else if (Lightbox.isVideo || Lightbox.isModal) {
1789        $("#lightbox #imageDataContainer").addClass('lightbox2-alt-layout-data');
1790        var container = document.getElementById('modalContainer');
1791        var modalStyles = Lightbox.imageArray[Lightbox.activeImage][3];
1792        container = Lightbox.setStyles(container, modalStyles);
1793        if (Lightbox.isVideo) {
1794          Lightbox.modalHeight =  parseInt(container.height, 10) - 10;
1795          Lightbox.modalWidth =  parseInt(container.width, 10) - 10;
1796          Lightvideo.startVideo(Lightbox.imageArray[Lightbox.activeImage][0]);
1797        }
1798        Lightbox.resizeContainer(parseInt(container.width, 10), parseInt(container.height, 10));
1799      }
1800    }
1801  },
1802
1803  // imgNodeLoadingError()
1804  imgNodeLoadingError: function(image) {
1805    var s = Drupal.settings.lightbox2;
1806    var original_image = Lightbox.imageArray[Lightbox.activeImage][0];
1807    if (s.display_image_size !== "") {
1808      original_image = original_image.replace(new RegExp("."+s.display_image_size), "");
1809    }
1810    Lightbox.imageArray[Lightbox.activeImage][0] = original_image;
1811    image.onerror = function() { Lightbox.imgLoadingError(image); };
1812    image.src = original_image;
1813  },
1814
1815  // imgLoadingError()
1816  imgLoadingError: function(image) {
1817    var s = Drupal.settings.lightbox2;
1818    Lightbox.imageArray[Lightbox.activeImage][0] = s.default_image;
1819    image.src = s.default_image;
1820  },
1821
1822  // resizeContainer()
1823  resizeContainer: function(imgWidth, imgHeight) {
1824
1825    imgWidth = (imgWidth < Lightbox.minWidth ? Lightbox.minWidth : imgWidth);
1826
1827    this.widthCurrent = $('#outerImageContainer').width();
1828    this.heightCurrent = $('#outerImageContainer').height();
1829
1830    var widthNew = (imgWidth  + (Lightbox.borderSize * 2));
1831    var heightNew = (imgHeight  + (Lightbox.borderSize * 2));
1832
1833    // Scalars based on change from old to new.
1834    this.xScale = ( widthNew / this.widthCurrent) * 100;
1835    this.yScale = ( heightNew / this.heightCurrent) * 100;
1836
1837    // Calculate size difference between new and old image, and resize if
1838    // necessary.
1839    wDiff = this.widthCurrent - widthNew;
1840    hDiff = this.heightCurrent - heightNew;
1841
1842    $('#modalContainer').css({'width': imgWidth, 'height': imgHeight});
1843    // Detect animation sequence.
1844    if (Lightbox.resizeSequence) {
1845      var animate1 = {width: widthNew};
1846      var animate2 = {height: heightNew};
1847      if (Lightbox.resizeSequence == 2) {
1848        animate1 = {height: heightNew};
1849        animate2 = {width: widthNew};
1850      }
1851      $('#outerImageContainer').animate(animate1, Lightbox.resizeSpeed).animate(animate2, Lightbox.resizeSpeed, 'linear', function() { Lightbox.showData(); });
1852    }
1853    // Simultaneous.
1854    else {
1855      $('#outerImageContainer').animate({'width': widthNew, 'height': heightNew}, Lightbox.resizeSpeed, 'linear', function() { Lightbox.showData(); });
1856    }
1857
1858    // If new and old image are same size and no scaling transition is necessary
1859    // do a quick pause to prevent image flicker.
1860    if ((hDiff === 0) && (wDiff === 0)) {
1861      if ($.browser.msie) {
1862        Lightbox.pause(250);
1863      }
1864      else {
1865        Lightbox.pause(100);
1866      }
1867    }
1868
1869    var s = Drupal.settings.lightbox2;
1870    if (!s.use_alt_layout) {
1871      $('#prevLink, #nextLink').css({'height': imgHeight + 'px'});
1872    }
1873    $('#imageDataContainer').css({'width': widthNew + 'px'});
1874  },
1875
1876  // showData()
1877  // Display image and begin preloading neighbors.
1878  showData: function() {
1879    $('#loading').hide();
1880
1881    if (Lightbox.isLightframe || Lightbox.isVideo || Lightbox.isModal) {
1882      Lightbox.updateDetails();
1883      if (Lightbox.isLightframe) {
1884        $('#frameContainer').show();
1885        if ($.browser.safari || Lightbox.fadeInSpeed === 0) {
1886          $('#lightboxFrame').css({'zIndex': '10500'}).show();
1887        }
1888        else {
1889          $('#lightboxFrame').css({'zIndex': '10500'}).fadeIn(Lightbox.fadeInSpeed);
1890        }
1891      }
1892      else {
1893        if (Lightbox.isVideo) {
1894          $("#modalContainer").html(Lightbox.modalHTML).click(function(){return false;}).css('zIndex', '10500').show();
1895        }
1896        else {
1897          var src = unescape(Lightbox.imageArray[Lightbox.activeImage][0]);
1898          if (Lightbox.imageArray[Lightbox.activeImage][4]) {
1899            $(src).appendTo("#modalContainer");
1900            $('#modalContainer').css({'zIndex': '10500'}).show();
1901          }
1902          else {
1903            // Use a callback to show the new image, otherwise you get flicker.
1904            $("#modalContainer").hide().load(src, function () {$('#modalContainer').css({'zIndex': '10500'}).show();});
1905          }
1906          $('#modalContainer').unbind('click');
1907        }
1908        // This might be needed in the Lightframe section above.
1909        //$('#modalContainer').css({'zIndex': '10500'}).show();
1910      }
1911    }
1912
1913    // Handle display of image content.
1914    else {
1915      $('#imageContainer').show();
1916      if ($.browser.safari || Lightbox.fadeInSpeed === 0) {
1917        $('#lightboxImage').css({'zIndex': '10500'}).show();
1918      }
1919      else {
1920        $('#lightboxImage').css({'zIndex': '10500'}).fadeIn(Lightbox.fadeInSpeed);
1921      }
1922      Lightbox.updateDetails();
1923      this.preloadNeighborImages();
1924    }
1925    Lightbox.inprogress = false;
1926
1927    // Slideshow specific stuff.
1928    if (Lightbox.isSlideshow) {
1929      if (!Lightbox.loopSlides && Lightbox.activeImage == (Lightbox.total - 1)) {
1930        if (Lightbox.autoExit) {
1931          Lightbox.slideIdArray[Lightbox.slideIdCount++] = setTimeout(function () {Lightbox.end('slideshow');}, Lightbox.slideInterval);
1932        }
1933      }
1934      else {
1935        if (!Lightbox.isPaused && Lightbox.total > 1) {
1936          Lightbox.slideIdArray[Lightbox.slideIdCount++] = setTimeout(function () {Lightbox.changeData(Lightbox.activeImage + 1);}, Lightbox.slideInterval);
1937        }
1938      }
1939      if (Lightbox.showPlayPause && Lightbox.total > 1 && !Lightbox.isPaused) {
1940        $('#lightshowPause').show();
1941        $('#lightshowPlay').hide();
1942      }
1943      else if (Lightbox.showPlayPause && Lightbox.total > 1) {
1944        $('#lightshowPause').hide();
1945        $('#lightshowPlay').show();
1946      }
1947    }
1948
1949    // Adjust the page overlay size.
1950    var arrayPageSize = Lightbox.getPageSize();
1951    var arrayPageScroll = Lightbox.getPageScroll();
1952    var pageHeight = arrayPageSize[1];
1953    if (Lightbox.isZoomedIn && arrayPageSize[1] > arrayPageSize[3]) {
1954      var lightboxTop = (Lightbox.topPosition == '' ? (arrayPageSize[3] / 10) : Lightbox.topPosition) * 1;
1955      pageHeight = pageHeight + arrayPageScroll[1] + lightboxTop;
1956    }
1957    $('#lightbox2-overlay').css({'height': pageHeight + 'px', 'width': arrayPageSize[0] + 'px'});
1958
1959    // Gecko browsers (e.g. Firefox, SeaMonkey, etc) don't handle pdfs as
1960    // expected.
1961    if ($.browser.mozilla) {
1962      if (Lightbox.imageArray[Lightbox.activeImage][0].indexOf(".pdf") != -1) {
1963        setTimeout(function () {
1964          document.getElementById("lightboxFrame").src = Lightbox.imageArray[Lightbox.activeImage][0];
1965        }, 1000);
1966      }
1967    }
1968  },
1969
1970  // updateDetails()
1971  // Display caption, image number, and bottom nav.
1972  updateDetails: function() {
1973
1974    $("#imageDataContainer").hide();
1975
1976    var s = Drupal.settings.lightbox2;
1977
1978    if (s.show_caption) {
1979      var caption = Lightbox.filterXSS(Lightbox.imageArray[Lightbox.activeImage][1]);
1980      if (!caption) caption = '';
1981      $('#caption').html(caption).css({'zIndex': '10500'}).show();
1982    }
1983
1984    // If image is part of set display 'Image x of x'.
1985    var numberDisplay = null;
1986    if (s.image_count && Lightbox.total > 1) {
1987      var currentImage = Lightbox.activeImage + 1;
1988      if (!Lightbox.isLightframe && !Lightbox.isModal && !Lightbox.isVideo) {
1989        numberDisplay = s.image_count.replace(/\!current/, currentImage).replace(/\!total/, Lightbox.total);
1990      }
1991      else if (Lightbox.isVideo) {
1992        numberDisplay = s.video_count.replace(/\!current/, currentImage).replace(/\!total/, Lightbox.total);
1993      }
1994      else {
1995        numberDisplay = s.page_count.replace(/\!current/, currentImage).replace(/\!total/, Lightbox.total);
1996      }
1997      $('#numberDisplay').html(numberDisplay).css({'zIndex': '10500'}).show();
1998    }
1999    else {
2000      $('#numberDisplay').hide();
2001    }
2002
2003    $("#imageDataContainer").hide().slideDown(Lightbox.slideDownSpeed, function() {
2004      $("#bottomNav").show();
2005    });
2006    if (Lightbox.rtl == 1) {
2007      $("#bottomNav").css({'float': 'left'});
2008    }
2009    Lightbox.updateNav();
2010  },
2011
2012  // updateNav()
2013  // Display appropriate previous and next hover navigation.
2014  updateNav: function() {
2015
2016    $('#hoverNav').css({'zIndex': '10500'}).show();
2017    var prevLink = '#prevLink';
2018    var nextLink = '#nextLink';
2019
2020    // Slideshow is separated as we need to show play / pause button.
2021    if (Lightbox.isSlideshow) {
2022      if ((Lightbox.total > 1 && Lightbox.loopSlides) || Lightbox.activeImage !== 0) {
2023        $(prevLink).css({'zIndex': '10500'}).show().click(function() {
2024          if (Lightbox.pauseOnPrevClick) {
2025            Lightbox.togglePlayPause("lightshowPause", "lightshowPlay");
2026          }
2027          Lightbox.changeData(Lightbox.activeImage - 1); return false;
2028        });
2029      }
2030      else {
2031        $(prevLink).hide();
2032      }
2033
2034      // If not last image in set, display next image button.
2035      if ((Lightbox.total > 1 && Lightbox.loopSlides) || Lightbox.activeImage != (Lightbox.total - 1)) {
2036        $(nextLink).css({'zIndex': '10500'}).show().click(function() {
2037          if (Lightbox.pauseOnNextClick) {
2038            Lightbox.togglePlayPause("lightshowPause", "lightshowPlay");
2039          }
2040          Lightbox.changeData(Lightbox.activeImage + 1); return false;
2041        });
2042      }
2043      // Safari browsers need to have hide() called again.
2044      else {
2045        $(nextLink).hide();
2046      }
2047    }
2048
2049    // All other types of content.
2050    else {
2051
2052      if ((Lightbox.isLightframe || Lightbox.isModal || Lightbox.isVideo) && !Lightbox.alternative_layout) {
2053        $('#frameHoverNav').css({'zIndex': '10500'}).show();
2054        $('#hoverNav').css({'zIndex': '10500'}).hide();
2055        prevLink = '#framePrevLink';
2056        nextLink = '#frameNextLink';
2057      }
2058
2059      // If not first image in set, display prev image button.
2060      if ((Lightbox.total > 1 && Lightbox.loopItems) || Lightbox.activeImage !== 0) {
2061        // Unbind any other click handlers, otherwise this adds a new click handler
2062        // each time the arrow is clicked.
2063        $(prevLink).css({'zIndex': '10500'}).show().unbind().click(function() {
2064          Lightbox.changeData(Lightbox.activeImage - 1); return false;
2065        });
2066      }
2067      // Safari browsers need to have hide() called again.
2068      else {
2069        $(prevLink).hide();
2070      }
2071
2072      // If not last image in set, display next image button.
2073      if ((Lightbox.total > 1 && Lightbox.loopItems) || Lightbox.activeImage != (Lightbox.total - 1)) {
2074        // Unbind any other click handlers, otherwise this adds a new click handler
2075        // each time the arrow is clicked.
2076        $(nextLink).css({'zIndex': '10500'}).show().unbind().click(function() {
2077          Lightbox.changeData(Lightbox.activeImage + 1); return false;
2078        });
2079      }
2080      // Safari browsers need to have hide() called again.
2081      else {
2082        $(nextLink).hide();
2083      }
2084    }
2085
2086    // Don't enable keyboard shortcuts so forms will work.
2087    if (!Lightbox.isModal) {
2088      this.enableKeyboardNav();
2089    }
2090  },
2091
2092
2093  // enableKeyboardNav()
2094  enableKeyboardNav: function() {
2095    $(document).bind("keydown", this.keyboardAction);
2096  },
2097
2098  // disableKeyboardNav()
2099  disableKeyboardNav: function() {
2100    $(document).unbind("keydown", this.keyboardAction);
2101  },
2102
2103  // keyboardAction()
2104  keyboardAction: function(e) {
2105    if (e === null) { // IE.
2106      keycode = event.keyCode;
2107      escapeKey = 27;
2108    }
2109    else { // Mozilla.
2110      keycode = e.keyCode;
2111      escapeKey = e.DOM_VK_ESCAPE;
2112    }
2113
2114    key = String.fromCharCode(keycode).toLowerCase();
2115
2116    // Close lightbox.
2117    if (Lightbox.checkKey(Lightbox.keysClose, key, keycode)) {
2118      Lightbox.end('forceClose');
2119    }
2120    // Display previous image (p, <-).
2121    else if (Lightbox.checkKey(Lightbox.keysPrevious, key, keycode)) {
2122      if ((Lightbox.total > 1 && ((Lightbox.isSlideshow && Lightbox.loopSlides) || (!Lightbox.isSlideshow && Lightbox.loopItems))) || Lightbox.activeImage !== 0) {
2123        Lightbox.changeData(Lightbox.activeImage - 1);
2124      }
2125
2126    }
2127    // Display next image (n, ->).
2128    else if (Lightbox.checkKey(Lightbox.keysNext, key, keycode)) {
2129      if ((Lightbox.total > 1 && ((Lightbox.isSlideshow && Lightbox.loopSlides) || (!Lightbox.isSlideshow && Lightbox.loopItems))) || Lightbox.activeImage != (Lightbox.total - 1)) {
2130        Lightbox.changeData(Lightbox.activeImage + 1);
2131      }
2132    }
2133    // Zoom in.
2134    else if (Lightbox.checkKey(Lightbox.keysZoom, key, keycode) && !Lightbox.disableResize && !Lightbox.disableZoom && !Lightbox.isSlideshow && !Lightbox.isLightframe) {
2135      if (Lightbox.isZoomedIn) {
2136        Lightbox.changeData(Lightbox.activeImage, false);
2137      }
2138      else if (!Lightbox.isZoomedIn) {
2139        Lightbox.changeData(Lightbox.activeImage, true);
2140      }
2141      return false;
2142    }
2143    // Toggle play / pause (space).
2144    else if (Lightbox.checkKey(Lightbox.keysPlayPause, key, keycode) && Lightbox.isSlideshow) {
2145
2146      if (Lightbox.isPaused) {
2147        Lightbox.togglePlayPause("lightshowPlay", "lightshowPause");
2148      }
2149      else {
2150        Lightbox.togglePlayPause("lightshowPause", "lightshowPlay");
2151      }
2152      return false;
2153    }
2154  },
2155
2156  preloadNeighborImages: function() {
2157
2158    if ((Lightbox.total - 1) > Lightbox.activeImage) {
2159      preloadNextImage = new Image();
2160      preloadNextImage.src = Lightbox.imageArray[Lightbox.activeImage + 1][0];
2161    }
2162    if (Lightbox.activeImage > 0) {
2163      preloadPrevImage = new Image();
2164      preloadPrevImage.src = Lightbox.imageArray[Lightbox.activeImage - 1][0];
2165    }
2166
2167  },
2168
2169  end: function(caller) {
2170    var closeClick = (caller == 'slideshow' ? false : true);
2171    if (Lightbox.isSlideshow && Lightbox.isPaused && !closeClick) {
2172      return;
2173    }
2174    // To prevent double clicks on navigation links.
2175    if (Lightbox.inprogress === true && caller != 'forceClose') {
2176      return;
2177    }
2178    Lightbox.disableKeyboardNav();
2179    $('#lightbox').hide();
2180    $("#lightbox2-overlay").fadeOut();
2181    Lightbox.isPaused = true;
2182    Lightbox.inprogress = false;
2183    // Replaces calls to showSelectBoxes() and showFlash() in original
2184    // lightbox2.
2185    Lightbox.toggleSelectsFlash('visible');
2186    if (Lightbox.isSlideshow) {
2187      for (var i = 0; i < Lightbox.slideIdCount; i++) {
2188        window.clearTimeout(Lightbox.slideIdArray[i]);
2189      }
2190      $('#lightshowPause, #lightshowPlay').hide();
2191    }
2192    else if (Lightbox.isLightframe) {
2193      $('#frameContainer').empty().hide();
2194    }
2195    else if (Lightbox.isVideo || Lightbox.isModal) {
2196      if (!Lightbox.auto_modal) {
2197        $('#modalContainer').hide().html("");
2198      }
2199      Lightbox.auto_modal = false;
2200    }
2201  },
2202
2203
2204  // getPageScroll()
2205  // Returns array with x,y page scroll values.
2206  // Core code from - quirksmode.com.
2207  getPageScroll : function() {
2208
2209    var xScroll, yScroll;
2210
2211    if (self.pageYOffset || self.pageXOffset) {
2212      yScroll = self.pageYOffset;
2213      xScroll = self.pageXOffset;
2214    }
2215    else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {  // Explorer 6 Strict.
2216      yScroll = document.documentElement.scrollTop;
2217      xScroll = document.documentElement.scrollLeft;
2218    }
2219    else if (document.body) {// All other Explorers.
2220      yScroll = document.body.scrollTop;
2221      xScroll = document.body.scrollLeft;
2222    }
2223
2224    arrayPageScroll = [xScroll,yScroll];
2225    return arrayPageScroll;
2226  },
2227
2228  // getPageSize()
2229  // Returns array with page width, height and window width, height.
2230  // Core code from - quirksmode.com.
2231  // Edit for Firefox by pHaez.
2232
2233  getPageSize : function() {
2234
2235    var xScroll, yScroll;
2236
2237    if (window.innerHeight && window.scrollMaxY) {
2238      xScroll = window.innerWidth + window.scrollMaxX;
2239      yScroll = window.innerHeight + window.scrollMaxY;
2240    }
2241    else if (document.body.scrollHeight > document.body.offsetHeight) { // All but Explorer Mac.
2242      xScroll = document.body.scrollWidth;
2243      yScroll = document.body.scrollHeight;
2244    }
2245    else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari.
2246      xScroll = document.body.offsetWidth;
2247      yScroll = document.body.offsetHeight;
2248    }
2249
2250    var windowWidth, windowHeight;
2251
2252    if (self.innerHeight) { // All except Explorer.
2253      if (document.documentElement.clientWidth) {
2254        windowWidth = document.documentElement.clientWidth;
2255      }
2256      else {
2257        windowWidth = self.innerWidth;
2258      }
2259      windowHeight = self.innerHeight;
2260    }
2261    else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode.
2262      windowWidth = document.documentElement.clientWidth;
2263      windowHeight = document.documentElement.clientHeight;
2264    }
2265    else if (document.body) { // Other Explorers.
2266      windowWidth = document.body.clientWidth;
2267      windowHeight = document.body.clientHeight;
2268    }
2269    // For small pages with total height less than height of the viewport.
2270    if (yScroll < windowHeight) {
2271      pageHeight = windowHeight;
2272    }
2273    else {
2274      pageHeight = yScroll;
2275    }
2276    // For small pages with total width less than width of the viewport.
2277    if (xScroll < windowWidth) {
2278      pageWidth = xScroll;
2279    }
2280    else {
2281      pageWidth = windowWidth;
2282    }
2283    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
2284    return arrayPageSize;
2285  },
2286
2287
2288  // pause(numberMillis)
2289  pause : function(ms) {
2290    var date = new Date();
2291    var curDate = null;
2292    do { curDate = new Date(); }
2293    while (curDate - date < ms);
2294  },
2295
2296
2297  // toggleSelectsFlash()
2298  // Hide / unhide select lists and flash objects as they appear above the
2299  // lightbox in some browsers.
2300  toggleSelectsFlash: function (state) {
2301    if (state == 'visible') {
2302      $("select.lightbox_hidden, embed.lightbox_hidden, object.lightbox_hidden").show();
2303    }
2304    else if (state == 'hide') {
2305      $("select:visible, embed:visible, object:visible").not('#lightboxAutoModal select, #lightboxAutoModal embed, #lightboxAutoModal object').addClass("lightbox_hidden");
2306      $("select.lightbox_hidden, embed.lightbox_hidden, object.lightbox_hidden").hide();
2307    }
2308  },
2309
2310
2311  // parseRel()
2312  parseRel: function (link) {
2313    var parts = [];
2314    parts["rel"] = parts["title"] = parts["group"] = parts["style"] = parts["flashvars"] = null;
2315    if (!$(link).attr('rel')) return parts;
2316    parts["rel"] = $(link).attr('rel').match(/\w+/)[0];
2317
2318    if ($(link).attr('rel').match(/\[(.*)\]/)) {
2319      var info = $(link).attr('rel').match(/\[(.*?)\]/)[1].split('|');
2320      parts["group"] = info[0];
2321      parts["style"] = info[1];
2322      if (parts["style"] != undefined && parts["style"].match(/flashvars:\s?(.*?);/)) {
2323        parts["flashvars"] = parts["style"].match(/flashvars:\s?(.*?);/)[1];
2324      }
2325    }
2326    if ($(link).attr('rel').match(/\[.*\]\[(.*)\]/)) {
2327      parts["title"] = $(link).attr('rel').match(/\[.*\]\[(.*)\]/)[1];
2328    }
2329    return parts;
2330  },
2331
2332  // setStyles()
2333  setStyles: function(item, styles) {
2334    item.width = Lightbox.iframe_width;
2335    item.height = Lightbox.iframe_height;
2336    item.scrolling = "auto";
2337
2338    if (!styles) return item;
2339    var stylesArray = styles.split(';');
2340    for (var i = 0; i< stylesArray.length; i++) {
2341      if (stylesArray[i].indexOf('width:') >= 0) {
2342        var w = stylesArray[i].replace('width:', '');
2343        item.width = jQuery.trim(w);
2344      }
2345      else if (stylesArray[i].indexOf('height:') >= 0) {
2346        var h = stylesArray[i].replace('height:', '');
2347        item.height = jQuery.trim(h);
2348      }
2349      else if (stylesArray[i].indexOf('scrolling:') >= 0) {
2350        var scrolling = stylesArray[i].replace('scrolling:', '');
2351        item.scrolling = jQuery.trim(scrolling);
2352      }
2353      else if (stylesArray[i].indexOf('overflow:') >= 0) {
2354        var overflow = stylesArray[i].replace('overflow:', '');
2355        item.overflow = jQuery.trim(overflow);
2356      }
2357    }
2358    return item;
2359  },
2360
2361
2362  // togglePlayPause()
2363  // Hide the pause / play button as appropriate.  If pausing the slideshow also
2364  // clear the timers, otherwise move onto the next image.
2365  togglePlayPause: function(hideId, showId) {
2366    if (Lightbox.isSlideshow && hideId == "lightshowPause") {
2367      for (var i = 0; i < Lightbox.slideIdCount; i++) {
2368        window.clearTimeout(Lightbox.slideIdArray[i]);
2369      }
2370    }
2371    $('#' + hideId).hide();
2372    $('#' + showId).show();
2373
2374    if (hideId == "lightshowPlay") {
2375      Lightbox.isPaused = false;
2376      if (!Lightbox.loopSlides && Lightbox.activeImage == (Lightbox.total - 1)) {
2377        Lightbox.end();
2378      }
2379      else if (Lightbox.total > 1) {
2380        Lightbox.changeData(Lightbox.activeImage + 1);
2381      }
2382    }
2383    else {
2384      Lightbox.isPaused = true;
2385    }
2386  },
2387
2388  triggerLightbox: function (rel_type, rel_group) {
2389    if (rel_type.length) {
2390      if (rel_group && rel_group.length) {
2391        $("a[rel^='" + rel_type +"\[" + rel_group + "\]'], area[rel^='" + rel_type +"\[" + rel_group + "\]']").eq(0).trigger("click");
2392      }
2393      else {
2394        $("a[rel^='" + rel_type +"'], area[rel^='" + rel_type +"']").eq(0).trigger("click");
2395      }
2396    }
2397  },
2398
2399  detectMacFF2: function() {
2400    var ua = navigator.userAgent.toLowerCase();
2401    if (/firefox[\/\s](\d+\.\d+)/.test(ua)) {
2402      var ffversion = new Number(RegExp.$1);
2403      if (ffversion < 3 && ua.indexOf('mac') != -1) {
2404        return true;
2405      }
2406    }
2407    return false;
2408  },
2409
2410  checkKey: function(keys, key, code) {
2411    return (jQuery.inArray(key, keys) != -1 || jQuery.inArray(String(code), keys) != -1);
2412  },
2413
2414  filterXSS: function(str, allowed_tags) {
2415    var output = "";
2416    $.ajax({
2417      url: Drupal.settings.basePath + 'system/lightbox2/filter-xss',
2418      data: {
2419        'string' : str,
2420        'allowed_tags' : allowed_tags
2421      },
2422      type: "POST",
2423      async: false,
2424      dataType:  "json",
2425      success: function(data) {
2426        output = data;
2427      }
2428    });
2429    return output;
2430  }
2431
2432};
2433
2434// Initialize the lightbox.
2435Drupal.behaviors.initLightbox = function (context) {
2436  $('body:not(.lightbox-processed)', context).addClass('lightbox-processed').each(function() {
2437    Lightbox.initialize();
2438    return false; // Break the each loop.
2439  });
2440
2441  // Attach lightbox to any links with lightbox rels.
2442  Lightbox.initList(context);
2443  $('#lightboxAutoModal', context).triggerHandler('click');
2444};
2445
2446;
2447
2448/*
2449 * Superfish v1.4.8 - jQuery menu widget
2450 * Copyright (c) 2008 Joel Birch
2451 *
2452 * Dual licensed under the MIT and GPL licenses:
2453 * 	http://www.opensource.org/licenses/mit-license.php
2454 * 	http://www.gnu.org/licenses/gpl.html
2455 *
2456 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
2457 */
2458
2459;(function($){
2460	$.fn.superfish = function(op){
2461
2462		var sf = $.fn.superfish,
2463			c = sf.c,
2464			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
2465			over = function(){
2466				var $$ = $(this), menu = getMenu($$);
2467				clearTimeout(menu.sfTimer);
2468				$$.showSuperfishUl().siblings().hideSuperfishUl();
2469			},
2470			out = function(){
2471				var $$ = $(this), menu = getMenu($$), o = sf.op;
2472				clearTimeout(menu.sfTimer);
2473				menu.sfTimer=setTimeout(function(){
2474					o.retainPath=($.inArray($$[0],o.$path)>-1);
2475					$$.hideSuperfishUl();
2476					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
2477				},o.delay);	
2478			},
2479			getMenu = function($menu){
2480				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
2481				sf.op = sf.o[menu.serial];
2482				return menu;
2483			},
2484			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
2485			
2486		return this.each(function() {
2487			var s = this.serial = sf.o.length;
2488			var o = $.extend({},sf.defaults,op);
2489			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
2490				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
2491					.filter('li:has(ul)').removeClass(o.pathClass);
2492			});
2493			sf.o[s] = sf.op = o;
2494			
2495			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
2496				if (o.autoArrows) addArrow( $('>a:first-child',this) );
2497			})
2498			.not('.'+c.bcClass)
2499				.hideSuperfishUl();
2500			
2501			var $a = $('a',this);
2502			$a.each(function(i){
2503				var $li = $a.eq(i).parents('li');
2504				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
2505			});
2506			o.onInit.call(this);
2507			
2508		}).each(function() {
2509			var menuClasses = [c.menuClass];
2510			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
2511			$(this).addClass(menuClasses.join(' '));
2512		});
2513	};
2514
2515	var sf = $.fn.superfish;
2516	sf.o = [];
2517	sf.op = {};
2518	sf.IE7fix = function(){
2519		var o = sf.op;
2520		if ($.browser.msie && $.browser.version >
2520 6 && o.dropShadows && o.animation.opacity!=undefined)
2521			this.toggleClass(sf.c.shadowClass+'-off');
2522		};
2523	sf.c = {
2524		bcClass     : 'sf-breadcrumb',
2525		menuClass   : 'sf-js-enabled',
2526		anchorClass : 'sf-with-ul',
2527		arrowClass  : 'sf-sub-indicator',
2528		shadowClass : 'sf-shadow'
2529	};
2530	sf.defaults = {
2531		hoverClass	: 'sfHover',
2532		pathClass	: 'overideThisToUse',
2533		pathLevels	: 1,
2534		delay		: 800,
2535		animation	: {opacity:'show'},
2536		speed		: 'normal',
2537		autoArrows	: true,
2538		dropShadows : true,
2539		disableHI	: false,		// true disables hoverIntent detection
2540		onInit		: function(){}, // callback functions
2541		onBeforeShow: function(){},
2542		onShow		: function(){},
2543		onHide		: function(){}
2544	};
2545	$.fn.extend({
2546		hideSuperfishUl : function(){
2547			var o = sf.op,
2548				not = (o.retainPath===true) ? o.$path : '';
2549			o.retainPath = false;
2550			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
2551					.find('>ul').hide().css('visibility','hidden');
2552			o.onHide.call($ul);
2553			return this;
2554		},
2555		showSuperfishUl : function(){
2556			var o = sf.op,
2557				sh = sf.c.shadowClass+'-off',
2558				$ul = this.addClass(o.hoverClass)
2559					.find('>ul:hidden').css('visibility','visible');
2560			sf.IE7fix.call($ul);
2561			o.onBeforeShow.call($ul);
2562			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
2563			return this;
2564		}
2565	});
2566
2567})(jQuery);
2568;
2569/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
2570 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
2571 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
2572 *
2573 * $LastChangedDate: 2007-06-19 20:25:28 -0500 (Tue, 19 Jun 2007) $
2574 * $Rev: 2111 $
2575 *
2576 * Version 2.1
2577 */
2578(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&parseInt($.browser.version)<=6){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};if(!$.browser.version)$.browser.version=navigator.userAgent.toLowerCase().match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)[1];})(jQuery);;
2579/**
2580* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
2581* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
2582* 
2583* @param  f  onMouseOver function || An object with configuration options
2584* @param  g  onMouseOut function  || Nothing (use configuration options object)
2585* @author    Brian Cherne <[email protected]>
2586*/
2587(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);;
2588// $Id: nice_menus.js,v 1.21 2010/06/18 06:14:12 vordude Exp $
2589
2590// This uses Superfish 1.4.8
2591// (http://users.tpg.com.au/j_birch/plugins/superfish)
2592
2593// Add Superfish to all Nice menus with some basic options.
2594(function ($) {
2595  $(document).ready(function() {
2596    $('ul.nice-menu').superfish({
2597      // Apply a generic hover class.
2598      hoverClass: 'over',
2599      // Disable generation of arrow mark-up.
2600      autoArrows: false,
2601      // Disable drop shadows.
2602      dropShadows: false,
2603      // Mouse delay.
2604      delay: Drupal.settings.nice_menus_options.delay,
2605      // Animation speed.
2606      speed: Drupal.settings.nice_menus_options.speed
2607    // Add in Brandon Aaron’s bgIframe plugin for IE select issues.
2608    // http://plugins.jquery.com/node/46/release
2609    }).find('ul').bgIframe({opacity:false});
2610    $('ul.nice-menu ul').css('display', 'none');
2611  });
2612})(jQuery);
2613;
2614$(document).ready(function() {
2615  // build the cycle initially, although might no be perfect
2616  buildHerkProductCycles();
2617});
2618
2619// on window load
2620$(window).load(function() {
2621  // resize the cycle on window load, after all images have loaded
2622  resizeHerkProductCycles(); 
2623});
2624
2625// on window reisize
2626$(window).resize(function() {
2627  // resize the cycle on window resize, in case responsive styles have changed
2628  // the overall width
2629  resizeHerkProductCycles(); 
2630});
2631
2632
2633
2634// function to build the sliders
2635function buildHerkProductCycles() {
2636  // loop through all cycles on the page and build them
2637  var herkCycleID = 0;
2638  var herkCycleAmount = 500;
2639  var herkCycleSpeed = 500;
2640  $('.herk-product-cycle').hide();
2641  $('.herk-product-cycle').each(function() {
2642    // add a unique id to the cycle
2643    var herkCycleIDClass = 'herk-product-cycle-'+herkCycleID;
2644    $(this).addClass(herkCycleIDClass);
2645    // get the width of all items in the cycler
2646    var herkCycleItemsWidth = 0;
2647    var herkCycleItemsOuterWidth = 0;
2648    var herkCycleItemsBounding = 0;
2649    $(this).find('.herk-product-cycle-row').each(function() {
2650      // herkCycleItemsWidth = herkCycleItemsWidth + $(this).width();
2651      // herkCycleItemsOuterWidth = herkCycleItemsOuterWidth + $(this).outerWidth();
2652       var rect = this.getBoundingClientRect();
2653       var width = rect.right - rect.left;
2654       herkCycleItemsBounding = herkCycleItemsBounding + Math.ceil(width);
2655    });
2656
2657    // add the navigation arrows
2658    $(this).append('<div class="herk-cycle-nav herk-cycle-prev"><a href="#" data-direction="prev" data-cycle-id="'+herkCycleIDClass+'"><span class="label">Previous</span></a></div><div class="herk-cycle-nav herk-cycle-next"><a data-direction="next" href="#" data-cycle-id="'+herkCycleIDClass+'"><span class="label">Next</span></a></div>');
2659    // add the width to the container of items
2660    // $(this).find('.herk-product-cycle-inner').css('width', herkCycleItemsBounding); COMMENTED THIS OUT SO THE PAGE DOESN'T LOOK LIKE ARSE BEFORE THE JS FIRES
2661    // if found a taxo link in the first row, add to the footer with "view all" 
2662    // prepended
2663    var herkCycleCategoryLink = $(this).find('.herk-product-cycle-row:first-child .taxo_link a');
2664    if(herkCycleCategoryLink) {
2665      // add a category link to the footer
2666      var herkCycleCategoryViewLink = '<a href="'+herkCycleCategoryLink.attr('href')+'">View '+herkCycleCategoryLink.html()+'</a>';
2667      $(this).append('<div class="category-link">'+herkCycleCategoryViewLink+'</div>');
2668      // replace the block header
2669      var herkCycleHeaderLink = '<a href="'+herkCycleCategoryLink.attr('href')+'"><h2>'+herkCycleCategoryLink.html()+'</h2></a>';
2670      $(this).parent('.content').parent('.block').find('h2').remove();
2671      $(this).parent('.content').parent('.block').prepend(herkCycleHeaderLink);
2672    }
2673    // increase the cycleID
2674    herkCycleID++;
2675  });
2676  $('.herk-product-cycle').show();
2677
2678  // click events for scrolling
2679  $('.herk-product-cycle .herk-cycle-nav a').click(function(event) {
2680    event.preventDefault();
2681    // get the button direction
2682    var herkCycleNavDirection = $(this).attr('data-direction');
2683    // get the cycle id
2684    var herkCycleIDClass = $(this).attr('data-cycle-id');
2685    // get the current cycle, it's contents and it's width
2686    var herkCycle = $('.'+herkCycleIDClass);
2687    var herkCycleWidth = herkCycle.width();
2688    var herkCycleContent = herkCycle.find('.herk-product-cycle-inner');
2689    var herkCycleContentWidth = herkCycleContent.width();
2690    // get the current position, and subtract the cycle amount
2691    var herkCycleContentPosition = parseFloat(herkCycleContent.css('left'));
2692    var newPosition = false;
2693    if(herkCycleNavDirection == 'prev') {
2694      // prev: scroll backwards
2695      newPosition = herkCycleContentPosition + herkCycleAmount;
2696      // if it's over the amount, reset
2697      if(newPosition > 0) {
2698        // if the current position is equal to the exact start, set the new 
2699        // position to the entire width minus the content width to scroll to the
2700        // exact end of the content
2701        if(herkCycleContentPosition == 0) {
2702          newPosition = (herkCycleContentWidth - herkCycleWidth) * -1;
2703        } else {
2704          // otherwise, we haven't reached the exact start yet, so push to the
2705          // exact start, since we would be pushing over it
2706          newPosition = 0;
2707        }
2708      }
2709    } else if(herkCycleNavDirection == 'next') {
2710      // next: scroll forward
2711      newPosition = herkCycleContentPosition - herkCycleAmount;
2712      // if it's over the amount, reset
2713      // using + because the value of newPosition for "next" will be negative
2714      if((herkCycleContentWidth + newPosition - herkCycleWidth) < 0) {
2715        // if the current position is equal to the exact end, reset to 0 to 
2716        // scroll to the beginning
2717        if(herkCycleContentPosition == (herkCycleContentWidth - herkCycleWidth) * -1) {
2718          newPosition = 0;
2719        } else {
2720          // otherwise, we haven't reached the exact end yet, so push to the
2721          // exact end, since we would be pushing over it
2722          // set the new position to the entire width minus the content width to
2723          // scroll to the end of the content
2724          newPosition = (herkCycleContentWidth - herkCycleWidth) * -1;
2725        }
2726      }
2727    }
2728    if(newPosition !== false) {
2729      // set the new position on the cycler
2730      herkCycleContent.animate({
2731        left: newPosition,
2732      }, herkCycleSpeed, function() {
2733        // animation completed
2734      });
2735    }
2736  });
2737}
2738
2739// function to build the slider sizes
2740function resizeHerkProductCycles() {
2741  // loop through all cycles on the page and build them
2742  var herkCycleID = 0;
2743  $('.herk-product-cycle').each(function() {
2744    // get the width of all items in the cycler
2745    var herkCycleItemsWidth = 0;
2746    var herkCycleItemsOuterWidth = 0;
2747    var herkCycleItemsBounding = 0;
2748    $(this).find('.herk-product-cycle-row').each(function() {
2749      // herkCycleItemsWidth = herkCycleItemsWidth + $(this).width();
2750      // herkCycleItemsOuterWidth = herkCycleItemsOuterWidth + $(this).outerWidth();
2751       var rect = this.getBoundingClientRect();
2752       var width = rect.right - rect.left;
2753       herkCycleItemsBounding = herkCycleItemsBounding + Math.ceil(width);
2754    });
2755
2756    // add the width to the container of items
2757    $(this).find('.herk-product-cycle-inner').css('width', herkCycleItemsBounding);
2758    // increase the cycleID
2759    herkCycleID++;
2760  });
2761}
2762;
2763/** Global (every page) javascript for timber tweaks */
2764
2765// function asdf(output, description) {
2766//   if(description) {
2767//     console.log(description, output);
2768//   } else {
2769//     console.log(output)
2770//   }
2771// }
2772
2773function timberCheckoutGetShippingCost() {
2774  return $('input[name="quote-option"]:radio').filter(':checked').parents('.form-item').filter(':first').find('input[type="hidden"]').filter(':first').val();
2775}
2776
2777// var timberReported = false;
2778// // This code is intended to intercept console.log output and detect a known fraud script
2779// (function(){
2780//  var preservedConsoleLog = console.log;
2781//  //overriding console.log function so we can watch for evil
2782//  console.log = function() {
2783//    preservedConsoleLog.apply(console, arguments);
2784//    if(typeof(arguments[0]) == 'undefined') return;
2785//    var output = arguments[0].toString().trim();
2786//    if (typeof Raven != "undefined") {
2787//      // Evil detected - let's tell the Raven!
2788//      switch(output) {
2789//        case 'undesirable script':
2790//        case 'fraud detected':
2791//          // Only log once
2792//          if(timberReported) return;
2793//          // Print all scripts src included on the page
2794//          $('script').each(function() {
2795//            if(typeof($(this).attr('src')) != 'undefined') {
2796//              console.log('SCRIPT SRC '+$(this).attr('src'));
2797//            }
2798//          });
2799//          // Log the error
2800//          Raven.captureMessage('I am literally the worst', {
2801//            details: {
2802//              url: window.location.href
2803//            }
2804//          });
2805//          timberReported = true;
2806//          break;
2807//      }
2808//    }
2809//  }
2810// })();
2811
2812var timberPaymentChangeBound = false;
2813// var timberShippingRestore = false; // Don't restore shipping type on page load
2814// var timberShippingRemember = false; // Don't remember shipping type at first page load
2815var shipInterval = false;
2816var shipWatcher = false;
2817var substitution_pref_orig_description = '';
2818
2819var timberInitRun = false;
2820var timberStartRun = false;
2821
2822var timberAdminStates = {
2823  states: {},
2824  set add(key) {
2825    this.states[key] = key;
2826  },
2827  set remove(key) {
2828    delete(this.states[key]);
2829  },
2830  get join() {
2831    var str = '';
2832    for(var i in this.states) {
2833      str += ' '+i;
2834    }
2835    return str;
2836  }
2837};
2838timberAdminStates.add = 'A';
2839
2840// Pre-set these to avoid undefined variable errors
2841if(typeof timberIsAdmin === 'undefined') timberIsAdmin = false;
2842if(typeof timberCartOptions === 'undefined') timberCartOptions = { };
2843
2844var timberOptions = {};
2845var timberIsAdmin = false;
2846function timberInit(context) {
2847  if(timberInitRun) return;
2848  timberInitRun = true;
2849
2850  timberOptions = Drupal.settings.timberOptions;
2851  timberIsAdmin = Drupal.settings.timberOptions.timberIsAdmin;
2852  // Add a message to the top of the admin menu block
2853  if(
2854    timberIsAdmin
2855    && Drupal.settings.timberOptions.menuMessage.length > 0
2856  ) {
2857    $(Drupal.settings.timberOptions.menuMessage).prependTo('#block-user-1 .content > ul.menu');
2858  }
2859
2860  // Only run if we're on the cart checkout page
2861  if($('#edit-panes-quotes-quote-button').length > 0) {
2862    if(typeof timberCartOptions != 'undefined') {
2863      timberCartOptions.instorePickup = false;
2864    }
2865
2866    // To compensate for Microsoft Edge not triggering the event-handler to copy Billing State to Delivery State
2867    var billing_fname = '';
2868    var billing_lname = '';
2869    var billing_company = '';
2870    var billing_street1 = '';
2871    var billing_street2 = '';
2872    var billing_city = '';
2873    var billing_country = '';
2874    var billing_state = '';
2875    var billing_postal = '';
2876    var billing_phone = '';
2877
2878    //We need to check once per second for changes to the Billing fields.
2879    setInterval(function () {
2880
2881      // If the "Copy Billing to Delivery" checkbox is enabled, then acquire values from Billing and write to Delivery        if ($('#edit-panes-delivery-copy-address').attr('checked')) {
2882
2883      //Get Values from Billing Fields
2884      billing_fname = $('#edit-panes-billing-billing-first-name').val();
2885      billing_lname = $('#edit-panes-billing-billing-last-name').val();
2886      billing_company = $('#edit-panes-billing-billing-company').val();
2887      billing_street1 = $('#edit-panes-billing-billing-street1').val();
2888      billing_street2 = $('#edit-panes-billing-billing-street2').val();
2889      billing_city = $('#edit-panes-billing-billing-city').val();
2890      billing_country = $('#edit-panes-billing-billing-country').val();
2891      billing_state = $('#edit-panes-billing-billing-zone').val();
2892      billing_postal = $('#edit-panes-billing-billing-postal-code').val();
2893      billing_phone = $('#edit-panes-billing-billing-phone').val();
2894
2895      // Set the same value in Delivery Fields
2896      $('#edit-panes-billing-billing-first-name').val(billing_fname);
2897      $('#edit-panes-billing-billing-last-name').val(billing_lname);
2898      $('#edit-panes-billing-billing-company').val(billing_company);
2899      $('#edit-panes-billing-billing-street1').val(billing_street1);
2900      $('#edit-panes-billing-billing-street2').val(billing_street2);
2901      $('#edit-panes-billing-billing-city').val(billing_city);
2902      $('#edit-panes-billing-billing-country').val(billing_country);
2903      $('#edit-panes-billing-billing-zone').val(billing_state);
2904      $('#edit-panes-billing-billing-postal-code').val(billing_postal);
2905      $('#edit-panes-billing-billing-phone').val(billing_phone);
2906    }, 1000); // 1000 milliseconds = 1 second
2907}
2908  // SBL: Only run if sequential cart layout is being used (e.g. using ubcart's next button feature)
2909  if($('#uc-cart-checkout-form.sequential-checkout').length > 0) {
2910    // wrap the checkout panes into their own divs
2911    $('.pane').wrapAll('<div id="checkout-main"></div>');
2912    // wrap the cart contents and order total preview into their own div
2913    $('.order-preview').wrapAll(' <div id="checkout-sidebar"></div>');
2914    $('#checkout-main, #checkout-sidebar').wrapAll('<div id="checkout-wrap"></div>');
2915    $('.pane').each(function () {
2916      var next = $(this).find('.next-button');
2917      var prev = $(this).find('.prev-button');
2918      var navButtons = next.add(prev);
2919      navButtons.wrapAll('<div id="nav-buttons" class="herk-hack"></div>');
2920    });
2921  }
2922}
2923
2924Drupal.behaviors.timberBehavior = function(context) {
2925    timberInit(context);
2926
2927  //ADA - Remove empty fields 
2928  setTimeout(function () {
2929    if ($('body:not(.node-type-product)').length) {
2930      $('a#bottomNavZoom, a#bottomNavZoomOut, #loading').remove();
2931      console.log('here');
2932    }
2933  }, 1000);
2934
2935  //ADA - Rewrite required asterisks
2936    $('span.form-required').each(function() {
2937        var $span = $(this);
2938        var $img = $span.find('img:first');
2939
2940        if ($span.text().indexOf('(required)') === -1) {
2941          $(this).html('<span class="required-ada2026">* (required)</span>');
2942            $img.before('(required)');
2943        }
2944    });
2945
2946    //ADA - add label to taxonomy term view switch
2947    $('div[class*="view-taxonomy-term"] label.switch').each(function(){
2948      $(this).prepend('<span class="hide">Change Views</span>');
2949    });
2950
2951  //Add Body Class for Ingram Product - nem
2952  if ($('.node-type-product .sku-ingram, .node-type-product .sku-INGRAM', context).length > 0) {
2953    $('body').addClass('ingram-product');
2954  }
2955
2956  //Add Body Class for Cat 00 Products - nem
2957  if ($('a.breadcrumb-sub[href*="/category/00"]', context).length > 0) {
2958    $('body').addClass('cat-00-product');
2959  }
2960
2961  //Add a Class for Ingram Product - nem
2962  if ($('.timber-price-for-sku[class*="ingram"],.timber-price-for-sku[class*="INGRAM"]', context).length > 0) {
2963    $('.timber-cart-toplevel').addClass('ingram-product');
2964  }
2965
2966  //Add an ARIA lable to add-to-cart buttons -nem
2967  $('input[class*="add-to-cart"]').attr('aria-label','Add item to your cart');
2968  $('input[id*="solr-search-text"]').attr('aria-label','Enter search words');
2969
2970
2971  //Declare that product attribute fields are required - nem
2972  $('.add-to-cart select').each(function(){
2973    $(this).attr('aria-required','true');
2974  });
2975  $('.add-to-cart .form-required').each(function(){
2976    //$(this).prepend('<span style="color:black;">(Required)</span>')
2977  });
2978
2979  //Update logo image to have a sensible alt tag
2980  var sitename = $('head title').text();
2981  sitename = sitename.split('|')[1] + ' Logo';
2982  $('header a[href='/'] img').attr('alt',sitename);
2983  $('header *[class*="logo"] img').attr('alt',sitename);
2984  $('header *[id*="logo"] img').attr('alt',sitename);  
2985
2986  //Add some helpful text to let visitor know that more images are available - nem
2987  $('.node-type-product .node .field-field-image .field-item:nth-child(2)').each(function(){
2988    $(this).parent().addClass('has-multiple-images added-by-timber-js');
2989  });
2990
2991  //Only run if we are adding/editing a coupon - nem
2992  if($('#uc-coupon-add-form', context).length > 0){
2993    $('#edit-max-uses-wrapper .description').prepend('<strong>Leave blank for unlimited. </strong>');
2994    $('#edit-max-uses-per-user-wrapper .description').prepend('<strong>Leave blank for unlimited.</strong> ');
2995    $('#edit-max-qty-wrapper .description').prepend('<strong>Leave blank for unlimited.</strong> ');
2996  }
2997
2998  //Add title tags to category menu options
2999  var menu_title = '';
3000  $('.tvmenu li a').each(function(){
3001    menu_title = $(this).text();
3002    $(this).attr('title', 'More information about items in category ' + menu_title);
3003  });
3004
3005  //Improve the Site Off-Line page layout by adding some content and style from /files - nem
3006  if($('.left-corner h2:contains("Site off-line")', context).length > 0){
3007    var style_element = $(document.createElement('link'));
3008    style_element.attr({href:'files/offline-override/override.css', rel:'stylesheet', type:'text/css', id:'override-css'});
3009    $('head').append(style_element);
3010
3011    var script_element = $(document.createElement('script'));
3012    script_element.attr({src:'files/offline-override/override_funcs.js', type:'text/javascript', id:'override-funcs'});
3013    $('head').append(script_element);
3014  }
3015
3016  //Cart Page:  Sends users back one page, instead of to home page
3017  $('#continue-shopping-link a', context).click(function(){
3018    parent.history.back();
3019    return false;
3020  });
3021
3022  // Hides Administrator role & herkimer role from users that are not administrator and herkimer
3023  if(!$('body', context).hasClass('is-admin')) {
3024    $('body.page-user:not(.role-administrator) .form-checkboxes .form-item .option').each(function(){
3025      if($(this).text().trim() == 'administrator'){
3026        $(this).parent().hide();
3027      }
3028    });
3029    $('body.page-user:not(.role-herkimer) .form-checkboxes .form-item .option').each(function(){
3030      if($(this).text().trim() == 'herkimer') {
3031        $(this).parent().hide();
3032      }
3033    });
3034  }
3035
3036  // 2019-02-28 SBL:
3037  // On the checkout page,
3038  // If tax lookup method is county,
3039  // And a tax state is configured
3040  if(
3041    $(".page-cart-checkout").length > 0
3042    && timberOptions.tt_tax_lookup_method == 'county'
3043    && timberOptions.timber_tax_state
3044  ) {
3045    // first, set the county fields to not required
3046    $("#edit-panes-delivery-delivery-ucxf-county").removeClass("required");
3047    $("#edit-panes-billing-billing-ucxf-county").removeClass("required");
3048    // do not let autocomplete set these fields
3049    $("#edit-panes-delivery-delivery-ucxf-county").attr("autocomplete","new-password");
3050    $("#edit-panes-billing-billing-ucxf-county").attr("autocomplete","new-password");
3051
3052    // If delivery state has changed, show or hide the county
3053    $("#edit-panes-delivery-delivery-zone").not('.timberCheckoutAddressChangeBound').change(function() {
3054      if($(this).val() == timberOptions.timber_tax_state) {
3055        $("#edit-panes-delivery-delivery-ucxf-county").addClass("required").css("border","2px solid red").parents("tr").filter(":first").css("display","table-row");
3056      } else {
3057        $("#edit-panes-delivery-delivery-ucxf-county").val("").removeClass("required").change().parents("tr").filter(":first").css("display","none");
3058      }
3059    }).addClass('timberCheckoutAddressChangeBound');
3060    // If billing state has changed, show or hide the county
3061    $("#edit-panes-billing-billing-zone").not('.timberCheckoutAddressChangeBound').change(function() {
3062      if($(this).val() == timberOptions.timber_tax_state) {
3063        $("#edit-panes-billing-billing-ucxf-county").addClass("required").css("border","2px solid red").parents("tr").filter(":first").css("display","table-row");
3064      } else {
3065        $("#edit-panes-billing-billing-ucxf-county").val("").removeClass("required").change().parents("tr").filter(":first").css("display","none");
3066      }
3067    }).addClass('timberCheckoutAddressChangeBound');
3068  }
3069
3070  if(timberOptions.timber_college_redirect_adopted_search) {
3071    // Wrap Search Results in a link to force Textbook Lookup the right way
3072    $('.apachesolr_search-results .timber-result.cond-adopted', context).each(function(){
3073      $(this).prepend('<a class="redirect-adopted-search-overlay" href="'+timberOptions.timber_college_redirect_adopted_search_path+'">'+timberOptions.timber_college_redirect_adopted_search_text+'</a>');
3074    });
3075  }
3076
3077  // This controls how the main category/classes blocks are hidden and expanded when their titles are clicked
3078  $('#sidebar-left .block-views .block-inner .view-content', context).hide();
3079  $('#sidebar-left .block-views h2.title', context).bind("mouseenter", function(e){
3080    $(this).addClass("hover");
3081  }).bind("mouseleave", function(e){
3082    $(this).removeClass("hover");
3083  }).bind("click", function(e){
3084    if(!$(this).parent().hasClass('expanded')) {
3085      $(this).parent().addClass('expanded');
3086      $(this).parent().find('.view-content').fadeIn('slow');
3087    } else {
3088      $(this).parent().removeClass('expanded');
3089      $(this).parent().find('.view-content').fadeOut('fast');
3090    }
3091  });
3092
3093  // Word-case the product attributes.
3094  $('select.timber-attribute > option', context).ucwords();
3095
3096  // Clean up the ISBN/SKU field label
3097  $('.field-field-in-isbn', context).each(function(){
3098    var lbl = $(this).find('.field-label');
3099    if(lbl.length == 0) return;
3100    if($(this).find('.field-item').html().trim().match(/^(97(8|9))?\d{9}(\d|X)$/g)) {
3101      //Product has an ISBN
3102      lbl.html(lbl.html().replace('/SKU',''));
3103    } else {
3104      //Product has a SKU
3105      lbl.html(lbl.html().replace('ISBN/',''));
3106      $(this).parent().find('.field-field-pub-date').hide();
3107      $(this).parent().find('.field-field-publisher').hide();
3108    }
3109  });
3110
3111  //NEM - UPS Shipment UI Improvement for faytechcc
3112  if($('#uc-ups-confirm-shipment', context).length > 0) {
3113    $('<div id="addl-submit">').prependTo('#uc-ups-confirm-shipment');
3114    $('#uc-ups-confirm-shipment #edit-submit,#edit-request-pickup-wrapper').clone().prependTo('#addl-submit');
3115  }
3116
3117  // Bind checkout hooks
3118  if($('#uc-cart-checkout-form', context).length > 0) {
3119    if (typeof timberCartOptionsInit == 'function') timberCartOptionsInit();
3120
3121    // JS Hook - add function timberPaymentChange(paymentType) to your theme
3122    lateBind('timberPaymentChange', 'input[name="panes[payment][payment_method]"]:radio', 'change', function(el) {
3123      timberAdminStates.add = 'timberPaymentChange';
3124      // if(timberIsAdmin) console.log(timberAdminStates.join+': lateBind timberPaymentChange');
3125
3126      //NEM - need to add a class to #payment_details, so that we can hide unwanted Check explanation
3127      selected_pay = $(this).val();
3128      //Remove stale selected option
3129      $('#payment-pane').attr('class','collapsible');
3130      //Add currently-selected option
3131      $(this).parent().parent().parent().parent().parent().parent().addClass('payselect-' + selected_pay);
3132
3133      // If a radio is checked and also disabled, click the first enabled one
3134      if($('.timberPaymentChange:checked:disabled').length) {
3135        $('.timberPaymentChange:enabled').filter(':first').click()
3136      }
3137
3138      // If no payment methods are available!!
3139      if(
3140        $('.timberPaymentChange').length > 1
3141        && $('.timberPaymentChange:enabled').length == 0
3142      ) {
3143        // One DISABLED radio is still checked!! Let's get rid of it
3144        if($('.timberPaymentChange:checked').length > 0) {
3145          var tmp = setTimeout(function() {
3146            // Bizarre way to uncheck this radio button - it works!
3147            // We timeout this after 1 second to avoid running before any ajax change event returns there may be on page load
3148            // (lets hope it takes longer than 2 seconds for the ajax to load)
3149            $('#payment-pane .form-radios').append('<input id="removethis" type="radio" name="panes[payment][payment_method]" value="removethis");" />');
3150            $('#removethis').click().remove();
3151          }, 2000);
3152        }
3153        // Show the error message(s), and disable the checkout by removing the continue button
3154        if($('.timber-error-credit-no-methods').length == 0) { // Don't do this twice!
3155          var errmsg = '<div class="timber-error-credit-no-methods notok">'+timberCartOptions.creditNoMethodsMessage+'</div>';
3156          $('#payment_details').html(errmsg);
3157          $('#checkout-form-bottom').append(errmsg);
3158          $('#payment-pane .form-radios i.warning').addClass('notok');
3159          $('#edit-continue').remove();
3160          $('#checkout-form-bottom').append('<a href="/cart" class="warning">Return To Shopping Cart</a>');
3161        }
3162      }
3163      // }
3164      timberCartOptions.paymentType = $(this).val();
3165      if (typeof timberPaymentChange == 'function') timberPaymentChange($(this));
3166      studentIDUpdate();
3167      triggerQuoteCallback();
3168
3169      timberAdminStates.remove = 'timberPaymentChange';
3170    });
3171
3172    $('input[name="panes[payment][payment_method]"]:radio:checked').click();
3173
3174    // JS Hook - add function timberShippingChange(shippingType) to your theme
3175    lateBind('timberShippingChange', 'input[name="quote-option"]:radio', 'change', function(el) {
3176      timberAdminStates.add = 'timberShippingChange';
3177      // if(timberIsAdmin) console.log(timberAdminStates.join+': lateBind timberShippingChange');
3178
3179      if(
3180        typeof el.originalEvent != 'undefined' // This was an actual click, not programmatically-triggered click
3181      ) {
3182        setShippingType($("input[name='quote-option']:checked").val());
3183      }
3184
3185      timberCartOptions.shippingCost = $(this).parents('.form-item').filter(':first').find('input[type="hidden"]').filter(':first').val();
3186
3187      if (typeof timberShippingChange == 'function') timberShippingChange($(this));
3188      studentIDUpdate();
3189      timberAdminStates.remove = 'timberShippingChange';
3190    }, '*');
3191
3192    if(timberCartOptions.ucxfPmtType) {
3193      $('#'+timberCartOptions.ucxfPmtType, context).change(function() {
3194        studentIDUpdate()
3195      });
3196    }
3197
3198    if($('#edit-panes-delivery-delivery-postal-code').length > 0) {
3199      if(!$('#edit-panes-delivery-delivery-postal-code').hasClass('watcher-bound')) {
3200        $('#edit-panes-delivery-delivery-postal-code').addClass('watcher-bound');
3201      }
3202    }
3203    //SBL update for county taxes
3204    // if($('#edit-panes-delivery-delivery-ucxf-county-wrapper').length > 0) {
3205    //  if(!$('#edit-panes-delivery-delivery-ucxf-county-wrapper').hasClass('watcher-bound')) {
3206    //    $('#edit-panes-delivery-delivery-ucxf-county-wrapper').addClass('watcher-bound');
3207    //  }
3208    // }
3209
3210    var sidfield = '';
3211    $('.uc-extra-fields-pane-table input[type="text"]').each(function() {
3212      if($(this).attr('id').indexOf('student-id') != -1) sidfield = $(this).attr('id');
3213    });
3214    if(sidfield) {
3215
3216      $('#'+sidfield).addClass('timberStudentID');
3217      lateBind('timberStudentIDChange', '#'+sidfield, 'blur', function(el) {
3218        timberAdminStates.add = 'timberStudentIDChange';
3219        timberCartOptions.studentID = $(this).val();
3220        if (typeof timberStudentIDChange == 'function') timberStudentIDChange($(this));
3221        studentIDUpdate();
3222        timberAdminStates.remove = 'timberStudentIDChange';
3223      }, 'input');
3224      lateBind('timberStudentIDKeyUp', '#'+sidfield, 'keyup', function(el) {
3225        timberAdminStates.add = 'timberStudentIDKeyUp';
3226        if(timberCartOptions.sidUppercase) {
3227          var testSID = $(this).val().toUpperCase();
3228          if($(this).val() !== testSID) $(this).val(testSID);
3229        }
3230        timberCartOptions.studentID = $(this).val();
3231        if (typeof timberStudentIDKeyUp == 'function') timberStudentIDKeyUp($(this));
3232        timberCartOptions.studentID = $(this).val();
3233        studentIDUpdate();
3234        timberAdminStates.remove = 'timberStudentIDKeyUp';
3235      });
3236    }
3237
3238    // Substitutions Preference YES alert -- Predicated on the above studentIDUpdate() function
3239    // Also added some custom functionality if you provide an html description field with 'yes_substitution' and 'no_substitution'
3240    // classes.  Those will be shown INSTEAD of the default alert message.
3241    if(
3242      timberCartOptions.preauthMax == '1'
3243      || timberCartOptions.printSubstitutionPreference == '1'
3244    ) {
3245      var substitution_pref_obj = $('#edit-panes-extra-information-information-ucxf-substitutions-pref-wrapper');
3246      var hasHtmlDescription = false;
3247      if(substitution_pref_obj && substitution_pref_obj.find('.description').html()) {
3248        hasHtmlDescription = substitution_pref_obj.find('.description').html().indexOf('yes_substitutions');
3249      }
3250      $('#edit-panes-extra-information-information-ucxf-substitutions-pref', context).change(function(){
3251        var substitution_pref_message = '';
3252        if(substitution_pref_orig_description == '') {
3253          substitution_pref_orig_description = substitution_pref_obj.find('.description').html();
3254        }
3255
3256        if($(this).attr('value') == 'yes_substitutions') {
3257          substitution_pref_message = 'You have chosen to allow for substitutions if your new/used choices are not available. This means that your card will be temporarily authorized for a higher dollar amount based on new book prices. This authorization will temporarily show up on your credit card as a pending transaction, but you will only be charged a final dollar amount based on the availability of new/used materials.';
3258        } else {
3259          substitution_pref_message = '';
3260        }
3261        if(hasHtmlDescription) {
3262          $('.yes_substitutions,.no_substitutions').addClass('hide');
3263          $('.'+$(this).val()).removeClass('hide');
3264        } else {
3265          if(substitution_pref_message) {
3266            alert(substitution_pref_message);
3267          }
3268        }
3269
3270      });
3271      if(hasHtmlDescription && substitution_pref_obj.find('.description').length > 0) {
3272        $('#edit-panes-extra-information-information-ucxf-substitutions-pref').change();
3273      }
3274    }
3275
3276    // Determines the credit card type automatically
3277    lateBind('timberAutoCCNum', '#edit-cc-number', 'blur', function(el) {
3278      cc_type = creditCardNumToType($(this).val());
3279      if($('#ccTypeInvalid').length == 0) {
3280        $('#edit-cc-type').prepend('<option value="visa" id="ccTypeInvalid">-- please select card type --</option>');
3281      }
3282      $('#edit-cc-type').val(cc_type).change();
3283      //if(cc_type == 'UNKNOWN') $('#edit-cc-type').attr('disabled','');
3284      //else $('#edit-cc-type').attr('disabled','disabled');
3285    });
3286    // Sets an error class on the CC number field if cc type is 'unknown'
3287    // Unsets the error if anything but 'unknown' is selected
3288    // This allows the user to enter an 'unknown' CC type, but manually select the type to clear the error
3289    lateBind('timberAutoCCType', '#edit-cc-type', 'change', function(el) {
3290      if($(this).val() == 'visa') $('#edit-cc-number').addClass('error');
3291      else $('#edit-cc-number').removeClass('error');
3292    });
3293
3294  }
3295
3296  // Add Qty Buttons to Cart Form for Items that Have Default Add-To-Cart Quantity
3297  if($('#uc-cart-view-form', context).length > 0) {
3298    $('#uc-cart-view-form .timber_dis_cart_qty', context).each(function() {
3299      var atc_qty = $(this).attr('atc_qty');
3300
3301      $(this).prepend('<a class="sub-qty" atc_qty="-'+atc_qty+'"> - </a>');
3302      $(this).append('<a class="add-qty" atc_qty="'+atc_qty+'"> + </a>');
3303
3304    });
3305    $('#uc-cart-view-form .sub-qty, #uc-cart-view-form .add-qty').click(function() {
3306      var atc_qty = parseInt($(this).attr('atc_qty'));
3307      var boxval = parseInt($(this).parent().find('.form-item input').val());
3308      if(boxval + atc_qty >= 0) {
3309        $(this).parent().find('.form-item input').val(boxval+atc_qty);
3310      }
3311    });
3312    $('#uc-cart-view-form', context).submit(function(event) {
3313      $('#uc-cart-view-form .timber_dis_cart_qty .form-item input').attr('disabled','');
3314    });
3315  }
3316
3317
3318  // Turn the order IDs on the store orders table into links so we can :visited colorize them
3319  $('.page-admin-store-orders .uc-orders-table tr td:nth-child(2)', context).each(function() {
3320    var oid = $(this).html();
3321    $(this).html("<a href='/admin/store/orders/"+oid+"'>"+oid+"</a>");
3322  });
3323
3324  // Prevent checkout if Student ID is invalid or any required field is missing.
3325  $('#uc-cart-checkout-form', context).submit(function(event) {
3326
3327    $('#uc-cart-checkout-form .error').removeClass('error');
3328
3329    // -nem 02/10, UWOsh was allowing checkouts with invalid SID. This removes class that hides Checkout Review.
3330    $('body').removeClass('hide-review-button');
3331
3332    $('#uc-cart-checkout-form .required').each(function() {
3333      if ($(this).val() == '' || $(this).val() == 'please_select') {
3334        $(this).addClass('error');
3335      }
3336    });
3337    // SBL expand the pane of the error if using the sequential checkout layout
3338    if($('#uc-cart-checkout-form.sequential-checkout').length > 0) {
3339      var pane = $(this).find('.pane');
3340      pane.each(function (e) {
3341        var error = $(this).find('.error:first');
3342        if(error.length > 0) {
3343          if($(this).hasClass('collapsed')) {
3344            $(this).find('legend a').click();
3345          }
3346          $('html, body').animate({
3347            scrollTop: error.offset().top + -100
3348          }, 1000);
3349          return false;
3350        }
3351      });
3352    }
3353    if( timberCartOptions.sidRequired && !timberCartOptions.sidValid ) {
3354      // Student ID validation
3355      document.getElementById($('.timberStudentID').attr('id')).scrollIntoView();
3356      alert("Please enter a valid ID number.");
3357      failLog('validation', $('.timberStudentID').attr('id'), $('.timberStudentID').val());
3358      $('.timberStudentID').addClass('error');
3359
3360      // -nem 02/10, UWOsh was allowing checkouts with invalid SID. This adds class that hides Checkout Review.
3361      $('body').addClass('hide-review-button');
3362
3363      return false;
3364    }
3365    if ($('#uc-cart-checkout-form .error').length > 0 && document.activeElement.id != 'edit-cancel') {
3366      $('#uc-cart-checkout-form .error').parents().removeClass('admin-only');
3367      var id = $('#uc-cart-checkout-form .error:first').attr('id');
3368      if(id) {
3369        document.getElementById(id).scrollIntoView();
3370      }
3371      alert("Please fill in all the required fields (highlighted in red)");
3372      failLog('required', id, $('#uc-cart-checkout-form .error:first').val());
3373      return false;
3374    }
3375  });
3376
3377  // Trim the email address field on checkout - spaces make it unhappy
3378  $('#edit-panes-customer-primary-email', context).blur(function() {
3379    $(this).val($(this).val().trim());
3380  });
3381
3382
3383  // Fill in the store's address into delivery option pane and then hide on in-store pickup
3384  $("input[name='panes[delivery_preference][delivery_preference]']", context).change(function() {
3385    setDeliveryPreference($(this).val());
3386    timberCartOptions.storeLocation = 'default';
3387
3388    if($(this).val() == 'delivery') { // delivery
3389      timberCartOptions.instorePickup = false;
3390      // if delivery, unhide the delivery address pane, and "same as billing"
3391      // checkbox
3392      $('#delivery-pane').removeClass('admin-only');
3393      $('#edit-panes-billing-copy-address-wrapper').removeClass('admin-only');
3394      $('#edit-panes-delivery-copy-address-wrapper').removeClass('admin-only');
3395      // if delivery, fill in the delivery fields with the billing fields
3396      // Is this really an auto-assumption we want to be making? Maybe this
3397      // could be a feature? Right now I think it might mess up addShipInterval
3398      $('#edit-panes-billing-billing-first-name,#edit-panes-billing-billing-last-name,#edit-panes-billing-billing-company,#edit-panes-billing-billing-street1,#edit-panes-billing-billing-street2,#edit-panes-billing-billing-city,#edit-panes-billing-billing-postal-code,#edit-panes-billing-billing-phone,#edit-panes-billing-billing-country,#edit-panes-billing-billing-zone').each(function() {
3399        var fieldid = '#'+$(this).attr('id').replace('billing-billing','delivery-delivery');
3400        $(fieldid).val($(this).val());
3401      });
3402      // unhide the shipping methods/quotes pane and uncheck all shipping
3403      // methods
3404      $('#quotes-pane').removeClass('admin-only');
3405      $('#quote input').removeAttr('checked');
3406
3407      if (typeof triggerQuoteCallback !== "undefined") {
3408        if($('#edit-panes-quotes-quote-button').hasClass('timberQuoteActionOverride')) {
3409          triggerQuoteCallback();
3410        }
3411      }
3412
3413    } else { // in-store-pickup
3414      timberCartOptions.instorePickup = true;
3415      if(typeof(storeAddress[$(this).val()]) == 'object' && storeAddress[$(this).val()].location.length > 0) {
3416        timberCartOptions.storeLocation = $(this).val();
3417      }
3418
3419      // hide the delivery address, uncheck the "same as billing" checkbox, and
3420      // set the values of the delivery address to the appropriate pickup
3421      // address and customer information values
3422      $('#delivery-pane').addClass('admin-only');
3423      // the same as billing checkbox is different depending on the order of
3424      // the address panes, so do both "billing" and "delivery"
3425      if($('#edit-panes-billing-copy-address').attr('checked')) {
3426        $('#edit-panes-billing-copy-address').click();
3427      }
3428      $('#edit-panes-billing-copy-address-wrapper').addClass('admin-only');
3429      if($('#edit-panes-delivery-copy-address').attr('checked')) {
3430        $('#edit-panes-delivery-copy-address').click();
3431      }
3432      $('#edit-panes-delivery-copy-address-wrapper').addClass('admin-only');
3433      // Unset the saved address field for the Delivery Address
3434      $('#edit-panes-delivery-delivery-address-select').val('0');
3435      // input store's address into the delivery information form
3436      $('#edit-panes-delivery-delivery-first-name').val($('#edit-panes-billing-billing-first-name').val());
3437      $('#edit-panes-delivery-delivery-last-name').val($('#edit-panes-billing-billing-last-name').val());
3438      $('#edit-panes-delivery-delivery-company').val('');
3439      $('#edit-panes-delivery-delivery-street1').val(storeAddress[timberCartOptions.storeLocation].street1);
3440      $('#edit-panes-delivery-delivery-street2').val(storeAddress[timberCartOptions.storeLocation].street2);
3441      $('#edit-panes-delivery-delivery-city').val(storeAddress[timberCartOptions.storeLocation].city);
3442      $('#edit-panes-delivery-delivery-postal-code').val(storeAddress[timberCartOptions.storeLocation].postal_code);
3443      $('#edit-panes-delivery-delivery-phone').val($('#edit-panes-billing-billing-phone').val());
3444      $('#edit-panes-delivery-delivery-country').val(storeAddress[timberCartOptions.storeLocation].country);
3445      $('#edit-panes-delivery-delivery-zone').val(storeAddress[timberCartOptions.storeLocation].zone);
3446
3447      if (typeof triggerQuoteCallback !== "undefined") {
3448        if($('#edit-panes-quotes-quote-button').hasClass('timberQuoteActionOverride')) {
3449          triggerQuoteCallback();
3450        }
3451      }
3452    }
3453
3454    if (typeof timberDeliveryPreferenceChange == 'function') timberDeliveryPreferenceChange($(this));
3455  });
3456
3457  // if in-store pickup, change the first, last names and phone number of the
3458  // delivery address (which is auto-set to the store pickup address) to the
3459  // same as the billing when they change
3460  $('#edit-panes-billing-billing-first-name,#edit-panes-billing-billing-last-name,#edit-panes-billing-billing-phone', context).change(function(event) {
3461    if(
3462      $("input[name='panes[delivery_preference][delivery_preference]']").length > 0
3463      && $("input[name='panes[delivery_preference][delivery_preference]']:checked").val()!='delivery'
3464    ) {
3465      var fieldid = '#'+$(this).attr('id').replace('billing-billing','delivery-delivery');
3466      $(fieldid).val($(this).val());
3467    }
3468  });
3469
3470  // Set title,alt on images within the taxonomy term view.
3471  $('.view-taxonomy-term .imagecache', context).each(function() {
3472    // var t = $(this).parents('.node').filter(':first').find('h2').text();
3473    // $(this).attr('title',t).attr('alt',t);
3474  });
3475
3476  //Change Author label globally to By
3477  if($('.view-taxonomy-term-2017 .author').length > 0) {
3478    $('.view-taxonomy-term-2017 .field-content .author').html($('.view-taxonomy-term-2017 .field-content .author').html().replace('Author','By'));
3479  }
3480
3481  //Remove cod wrapper if general merchandise is in cart, if configured
3482  if(timberCartOptions.hasGenMerch && timberCartOptions.faNoGM && !$('body').hasClass('faNoGMProcessed')) {
3483    $('body').addClass('faNoGMProcessed');
3484    var message = '<br /><i class="warning">'+timberCartOptions.faNoGMWarning+'</i>';
3485    $('#edit-panes-payment-payment-method-cod-wrapper label').append(message);
3486    $('#edit-panes-payment-payment-method-ccplus-wrapper label').append(message);
3487    $('#edit-panes-payment-payment-method-etvr-wrapper label').append(message);
3488    $('#edit-panes-payment-payment-method-credit-fa-wrapper label').append(message);
3489
3490    $('#edit-panes-payment-payment-method-cod').attr('disabled', 'disabled');
3491    $('#edit-panes-payment-payment-method-ccplus').attr('disabled', 'disabled');
3492    $('#edit-panes-payment-payment-method-etvr').attr('disabled', 'disabled');
3493    $('#edit-panes-payment-payment-method-credit-fa').attr('disabled', 'disabled');
3494  }
3495
3496  //Remove credit wrappers if adopted materials are in cart, if configured
3497  if(timberCartOptions.hasAdoptions && timberCartOptions.creditNoAdopt && !$('body').hasClass('creditNoAdoptProcessed')) {
3498    $('body').addClass('creditNoAdoptProcessed');
3499    var message = '<br /><i class="warning">'+timberCartOptions.creditNoAdoptWarning+'</i>';
3500    $('#edit-panes-payment-payment-method-touchnet-wrapper label').append(message);
3501    $('#edit-panes-payment-payment-method-quikpay-wrapper label').append(message);
3502
3503    $('#edit-panes-payment-payment-method-touchnet').attr('disabled', 'disabled');
3504    $('#edit-panes-payment-payment-method-quikpay').attr('disabled', 'disabled');
3505  }
3506  //Remove fa wrappers if adopted materials are in cart, if configured
3507  if(timberCartOptions.hasAdoptions && timberCartOptions.faNoAdopt && !$('body').hasClass('faNoAdoptProcessed')) {
3508    $('body').addClass('faNoAdoptProcessed');
3509    var message = '<br /><i class="error">'+timberCartOptions.faNoAdoptWarning+'</i>';
3510    $('#edit-panes-payment-payment-method-credit-fa-wrapper label').append(message);
3511
3512    $('#edit-panes-payment-payment-method-credit-fa').attr('disabled', 'disabled');
3513  }
3514
3515  $('body.page-admin-content-taxonomy-1  .tabs.primary li a[href*="add/term"]').text("Add Parent Category");
3516
3517  //NEM:   Change Author label globally to By
3518  if($('.view-taxonomy-term-2017 .field-content .author').length > 0) {
3519    $('.view-taxonomy-term-2017 .field-content .author').html($('.view-taxonomy-term-2017 .field-content .author').html().replace('Author','By'));
3520  }
3521
3522  //NEM:   to lower-case all the search terms. Having mixed case results in bad search results.
3523  $('#search-form .form-text,#search-form-1 .form-text').blur(function(){
3524    search_string = $(this).val().toLowerCase();
3525    $(this).val(search_string);
3526  });
3527
3528  // SKB: This converts the SVG signature in base64 into an image.
3529  var signatures = document.getElementsByClassName("information_ucxf_student_signature");
3530  for (var i=0, len=signatures.length|0; i<len; i=i+1|0) {
3531    const imgData = signatures[i].textContent;
3532    const trimmedImgData = imgData.replace(/Student Signature: /g, "");
3533    let image = new Image();
3534    image.src = trimmedImgData;
3535    image.className = "signedImage";
3536    signatures[i].textContent = ""
3537    signatures[i].appendChild(image);
3538  }
3539  // SKB: Converts signature on the order view page
3540  if($('#order-pane-extra_information').length > 0 && $('#order-pane-extra_information').contents(':contains("data:image)').length > 0) {
3541    var node = $('#order-pane-extra_information').contents(':contains("data:image)')[0];
3542    const imgData = node.nodeValue.match(/data:image.*/)[0];
3543    if(imgData.length > 0) {
3544      const trimmedImgData = imgData.replace(/Student Signature: /g, "");
3545      let image = new Image();
3546      image.src = trimmedImgData;
3547      image.className = "signedImage";
3548      node.nodeValue = '';
3549      node.replaceWith(image);
3550      $('<br/>').insertBefore('.signedImage');
3551    }
3552  }
3553
3554  timberStart();
3555}; // END OF timberBehavior
3556
3557
3558
3559
3560function timberStart() {
3561  if(timberStartRun) return;
3562  timberStartRun = true;
3563
3564  // Only run if we're on the cart checkout page
3565  if($('#edit-panes-quotes-quote-button').length > 0) {
3566    // if(timberIsAdmin) console.log(timberAdminStates.join+": CALL replaceUC_setQuoteCallbacks from timberStart");
3567    replaceUC_setQuoteCallbacks();
3568    // if(timberIsAdmin) console.log(timberAdminStates.join+": CALL restoreDeliveryPreference from timberStart");
3569    restoreDeliveryPreference();
3570    // Remove default quote options on initial page load - they are wrong.
3571    $('body').addClass('quote-needed');
3572    $('#quote .form-item').remove();
3573  }
3574
3575  // $('#edit-panes-payment-payment-method-quikpay-wrapper').addClass('admin-only');
3576}
3577
3578/**
3579 *  shipInterval is what restores the ship options selected on a previous page (when navigating back)
3580 */
3581function addShipInterval() {
3582  // Only run if we're on the cart checkout page
3583  if($('#edit-panes-quotes-quote-button').length == 0) return;
3584  if(timberIsAdmin) console.log(timberAdminStates.join+": QUEUE shipInterval");
3585
3586  clearInterval(shipInterval);
3587
3588  shipInterval = setInterval(function() {
3589    if($('#quote-dirty').length == 0 && $('#quoteProgress').length == 0 ) {
3590      timberAdminStates.add = 'shipInterval';
3591      clearInterval(shipInterval);
3592      if(timberIsAdmin) console.log(timberAdminStates.join+": RUN shipInterval");
3593
3594      restoreShippingType();
3595
3596      $("input[name='quote-option']").each(function() {
3597        var optionVal = $(this).attr('value');
3598        $(this).parents('.form-item').addClass(optionVal);
3599      });
3600
3601
3602      // if instore pickup and a shipping method is selected, hide the shipping
3603      // pane -- otherwise unhide it -- is this for the Restore code above?
3604      if(timberCartOptions.instorePickup) {
3605        if($("input[name='quote-option']:checked").val()) {
3606          $('#quotes-pane').addClass('admin-only');
3607        } else {
3608          $('#quotes-pane').removeClass('admin-only');
3609        }
3610      }
3611
3612      // if(timberIsAdmin) console.log('timberShipExcludes', timberShipExcludes);
3613      // Exclude shipping quotes from timberShipExcludes
3614      $.each(timberShipExcludes, function(key, exclude) {
3615        $("input[name='quote-option'][value^='" + exclude + "']").parents('.form-item').addClass('admin-only');
3616        $("input[name='panes[delivery_preference][delivery_preference]'][value^='" + exclude + "']").attr('disabled', true).parents('.form-item').addClass('admin-only');
3617      });
3618      if(timberShipRequire) {
3619        // Show only a single ship method if timberShipRequire is set
3620        // hide all shipping methods except the required method
3621        $("input[name='quote-option']").parents('.form-item').addClass('admin-only');
3622        $("input[name='quote-option'][value^='" + timberShipRequire + "']").parents('.form-item').removeClass('admin-only');
3623      }
3624      if(timberIsAdmin) console.log(timberAdminStates.join+': selected ship option AFTER restore:', $("input[name='quote-option']:checked").val());
3625      // SBL still show the delivery pane if we still have a shipping option available
3626      $("input[name='panes[delivery_preference][delivery_preference]']").each(function() {
3627        if($(this).parent().parent().hasClass('admin-only') == false) {
3628          $(this).attr('disabled', false);
3629        }
3630      });
3631
3632      // loop through the shipping quote/method options
3633      $("input[name='quote-option']").each(function() {
3634        if(
3635          (
3636            timberCartOptions.instorePickup
3637            //&& $(this).val().indexOf(timberCartOptions.storeLocation) >= 0
3638            && delPrefShippingMatch(timberCartOptions.storeLocation, $(this).val())
3639          )
3640          || (
3641            timberShipRequire
3642            && delPrefShippingMatch(timberShipRequire, $(this).val())
3643          )
3644        ) {
3645          // if instore pickup, and this is the pick option OR if a shipping
3646          // method is required and this is the required option, select it
3647          //$(this).attr('checked', 'checked');
3648          // can't just check it need to CLICK it
3649          // THESE are the only two cases in which we SHOULD auto-select a
3650          // shipping method, because we are hiding the pane and faciliating the
3651          // pick-up or required shipping method process
3652          $(this).click()
3653          // console.log($(this));
3654          if(timberIsAdmin) console.log(timberAdminStates.join+': Pick-up Preference or Required Shipping auto-selected:', $("input[name='quote-option']:checked").val());
3655        }
3656        if(!timberCartOptions.instorePickup) {
3657          // if instore pick-up is not selected, disable all the in store
3658          // pickup methods and select a non-pickup method
3659          $('#quote input[type="radio"]').each(function() {
3660            var quoteInput = $(this);
3661            $('#delivery_preference-pane input').each(function() {
3662              if(delPrefShippingMatch($(this).val(), quoteInput.val())) {
3663                quoteInput.attr('disabled', 'disabled');
3664              }
3665            });
3666          });
3667        }
3668      });
3669      studentIDUpdate();
3670      timberAdminStates.remove = 'shipInterval';
3671    }
3672  }, 250);
3673}
3674
3675/**
3676 *  shipWatcher watches for misconfigurations in the shipping options and corrects them
3677 */
3678function addShipWatcher() {
3679  // Only run if we're on the cart checkout page
3680  if($('#edit-panes-quotes-quote-button').length == 0) return;
3681  if(timberIsAdmin) console.log(timberAdminStates.join+": QUEUE shipWatcher");
3682
3683  clearInterval(shipWatcher);
3684
3685  shipWatcher = setInterval(function() {
3686    if($('#quote-dirty').length == 0 && $('#quoteProgress').length == 0 ) {
3687      timberAdminStates.add = 'shipWatcher';
3688      // if(timberIsAdmin) console.log(timberAdminStates.join+": RUN shipWatcher");
3689
3690      // The checked delivery preference option is not enabled, uncheck it
3691      if(
3692        $("input[name='panes[delivery_preference][delivery_preference]']").length > 0
3693        && $("input[name='panes[delivery_preference][delivery_preference]']:checked:enabled").length == 0
3694      ) {
3695        // Uncheck the invalid option
3696        $("input[name='panes[delivery_preference][delivery_preference]']:checked").attr('checked', false);
3697      }
3698      // There is only one enabled delivery preference option - select it automatically
3699      if(
3700        $("input[name='panes[delivery_preference][delivery_preference]']:enabled").length == 1
3701        && $("input[name='panes[delivery_preference][delivery_preference]']:enabled:not(:checked)").length == 1
3702      ) {
3703        // Check the only available option
3704        $("input[name='panes[delivery_preference][delivery_preference]']:enabled").attr('checked', true);
3705      }
3706
3707      // The checked shipping quote option is not enabled, uncheck it
3708      if(
3709        $("input[name='quote-option']:checked").length > 0
3710        && $("input[name='quote-option']:checked:enabled").length == 0
3711      ) {
3712        // Uncheck the invalid option
3713        $("input[name='quote-option']:checked").attr('checked', false);
3714        setShippingType('');
3715      }
3716
3717      timberAdminStates.remove = 'shipWatcher';
3718    }
3719  }, 250);
3720}
3721
3722function studentIDUpdate() {
3723  var sid = $('.timberStudentID:nth-child(1)');
3724  var spref = $('#edit-panes-extra-information-information-ucxf-substitutions-pref');
3725  sid.removeClass('required');
3726
3727  // Both cod and credit_fa options exist
3728  if(
3729    $('#edit-panes-payment-payment-method-credit-fa-wrapper').length > 0
3730    && $('#edit-panes-payment-payment-method-cod-wrapper').length > 0
3731  ) {
3732    var shippingCost = 0.00;
3733    shippingCost = parseFloat(timberCheckoutGetShippingCost());
3734    // Switch to credit_fa if...
3735    if(
3736      (timberCartOptions.faChargeShipping && shippingCost > 0.00) // set to charge shipping
3737      || (timberCartOptions.faAuthorizeTotal) // set to authorize the order total
3738      || (timberCartOptions.faRentalCollateral && timberCartOptions.hasRentals) // set to capture a card for rental collateral
3739    ) {
3740      $('#edit-panes-payment-payment-method-cod-wrapper').hide();
3741      $('#edit-panes-payment-payment-method-credit-fa-wrapper').show();
3742      if(
3743        $('#edit-panes-payment-payment-method-cod').is(':checked')
3744      ) {
3745        $('#edit-panes-payment-payment-method-credit-fa').click();
3746      }
3747    }
3748    // Switch to cod if credit_fa isn't required
3749    else {
3750      $('#edit-panes-payment-payment-method-credit-fa-wrapper').hide();
3751      $('#edit-panes-payment-payment-method-cod-wrapper').show();
3752      if($('#edit-panes-payment-payment-method-credit-fa').is(':checked')) {
3753        $('#edit-panes-payment-payment-method-cod').click();
3754      }
3755    }
3756  }
3757
3758  if(
3759    ( timberCartOptions.sidReqRentals && timberCartOptions.hasRentals )
3760    || ( timberCartOptions.sidReqAdopted && timberCartOptions.hasAdoptions )
3761    || ( timberCartOptions.sidReqPmtType && timberCartOptions.paymentType.match('^'+timberCartOptions.sidReqPmtType+'$') != null )
3762  ) {
3763    // Require student ID field
3764    timberCartOptions.sidRequired = true;
3765  } else {
3766    timberCartOptions.sidRequired = false;
3767  }
3768
3769  // Let client code set some options
3770  if (typeof timberCartOptionsInit == 'function') timberCartOptionsInit();
3771
3772  // Substitution preference field visibility
3773  if( spref.length > 0 ) {
3774    if(!timberCartOptions.sprefNotRequired // this option not defined in admin/timber; can use in funcs.js timberCartOptionsInit()
3775      && (
3776        ( timberCartOptions.sidReqRentals && timberCartOptions.hasRentals )
3777        || ( timberCartOptions.sidReqAdopted && timberCartOptions.hasAdoptions )
3778        || ( timberCartOptions.sidReqPmtType && timberCartOptions.paymentType.match('^'+timberCartOptions.sidReqPmtType+'$') != null )
3779        || ( timberCartOptions.preauthMax == '1' && timberCartOptions.hasAdoptions )
3780        || ( timberCartOptions.printSubstitutionPreference == '1' )
3781      )
3782    ) {
3783      // Show/Hide substitution preference field
3784      spref.addClass('required').parents('tr').filter(':first').removeClass('hide');
3785      if($('.unrequire').length > 0 ) { spref.removeClass('required'); }
3786      //Remove substitution preference if general merchandise is in cart and FA is allowed, if configured
3787      if(timberCartOptions.hasGenMerch && timberCartOptions.faNoGMSub && timberCartOptions.mixedCart == false) {
3788        $('#edit-panes-extra-information-information-ucxf-substitutions-pref').val('no_substitutions');
3789        spref.removeClass('required').parents('tr').filter(':first').addClass('hide');
3790      }
3791    } else {
3792      if(!timberCartOptions.hasAdoptions) {
3793        spref.removeClass('required').parents('tr').filter(':first').addClass('hide');
3794      }
3795    }
3796  }
3797
3798  $('.fa-credit-display').remove();
3799
3800  if(
3801    timberCartOptions.studentID.length > 0
3802  ) {
3803    var sidToMatch = timberCartOptions.studentID;
3804    var ucxfPmtTypeField = '';
3805    var ucxfPmtTypeFieldID = '';
3806    if(timberCartOptions.ucxfPmtType) {
3807      ucxfPmtTypeField = timberCartOptions.ucxfPmtType;
3808    }
3809    if(ucxfPmtTypeField && $('#'+ucxfPmtTypeField).length > 0 && $('#'+ucxfPmtTypeField).val()) {
3810      sidToMatch = $('#'+ucxfPmtTypeField).val()+sidToMatch;
3811    }
3812
3813    // If user has entered the correct Student ID
3814    if(sidToMatch == timberCartOptions.user_student_id) {
3815      // Grab the available credit / grants from tt_user.user_credit
3816      var availableCredit = Number(timberCartOptions.user_credit).toFixed(2);
3817      if(availableCredit > 0) {
3818        // Show the available FA Credit/Grants value if it's more than nothing
3819        $('#line-items-div,#edit-panes-payment-payment-method-credit-fa-wrapper,#edit-panes-extra-information-information-ucxf-student-id-wrapper')
3820          .append('<div class="fa-credit-display"><span class="label">Available Financial Aid Credit/Grants:</span> <span class="data">$'+availableCredit+'</span></div>');
3821      }
3822    }
3823
3824    if(
3825      timberCartOptions.studentID.length > 0
3826      && timberCartOptions.valid
3827      && sidToMatch.match('^'+timberCartOptions.valid+'$') == null
3828    ) {
3829      sid.addClass('error');
3830      timberCartOptions.sidValid = false;
3831      if(timberIsAdmin) console.log('Student ID "'+sidToMatch+'" FAILED format validation "'+timberCartOptions.valid+'"');
3832
3833      // -nem 02/10, UWOsh was allowing checkouts with invalid SID. This adds class that hides Checkout Review.
3834      document.body.classList.add('hide-review-button');
3835
3836    } else {
3837      sid.removeClass('error');
3838      timberCartOptions.sidValid = true;
3839
3840      // -nem 02/10, UWOsh was allowing checkouts with invalid SID. This adds class that hides Checkout Review.
3841      $('body').removeClass('hide-review-button');
3842
3843      if(timberIsAdmin) console.log('Student ID "'+sidToMatch+'" PASSED format validation "'+timberCartOptions.valid+'"');
3844    }
3845  }
3846
3847  // Set/unset student ID required class
3848  if( timberCartOptions.sidRequired ) {
3849    sid.addClass('required');
3850  } else {
3851    sid.removeClass('required');
3852  }
3853}
3854function timberCartHasRentals() {
3855  if(timberCartOptions.hasRentals) return true;
3856  return false;
3857}
3858function timberCartHasAdoptions() {
3859  if(timberCartOptions.hasAdoptions) return true;
3860  return false;
3861}
3862
3863function restoreDeliveryPreference() {
3864  timberCartOptions.deliveryPreference = timberGetCookie('deliveryPreference');
3865  if(timberIsAdmin) console.log(timberAdminStates.join+': restoreDeliveryPreference', timberCartOptions.deliveryPreference);
3866  $("input[name='panes[delivery_preference][delivery_preference]'][value='"+timberCartOptions.deliveryPreference+"']").click().change();
3867}
3868function setDeliveryPreference(v) {
3869  timberCartOptions.deliveryPreference = v;
3870  timberSetCookie('deliveryPreference', timberCartOptions.deliveryPreference, 1);
3871}
3872// Restore the desired shipping type - runs after the quote options are returned
3873function restoreShippingType() {
3874  timberCartOptions.shippingType = timberGetCookie('shippingType');
3875  if(timberIsAdmin) console.log(timberAdminStates.join+': restoreShippingType', timberCartOptions.shippingType);
3876  $("input[name='quote-option'][value='"+timberCartOptions.shippingType+"']").click();
3877}
3878// Saves the desired shipping type - runs when the real user clicks a shipping option
3879function setShippingType(v) {
3880  timberCartOptions.shippingType = v;
3881  timberSetCookie('shippingType', timberCartOptions.shippingType, 1);
3882}
3883// match a delivery preference option value from the delivery preference pane to
3884// its corresponding shipping quote option
3885// make sure to pass the .val() for each input as parameters; not the input
3886// itself
3887function delPrefShippingMatch(dp_option, shipping_option) {
3888  // the quote-option input values are formatted as <quotetype>_<id>---<num>
3889  // e.g., flatrate_1---0, flatrate_11---0, usps_1---0
3890  // the dp option in the delivery preference pane is only <quotetype>_<id>
3891  // e.g., flatrate_1, flatrate_11, usps_1
3892  // need to make sure flatrate_1 doesn't match flatrate_11 -- so add a dash to
3893  // the option and then compare
3894  if(shipping_option.indexOf(dp_option + '-') >= 0) return true;
3895  return false;
3896}
3897
3898var failCount = 0;
3899function failLog(failure, element, elementData) {
3900  failCount++;
3901  $.ajax({
3902    url: "/timber/faillog",
3903    data: {
3904      page: window.location.pathname,
3905      failure: failure,
3906      failCount: failCount,
3907      element: element,
3908      elementData: elementData,
3909    },
3910    cache: false,
3911  });
3912
3913}
3914
3915jQuery.fn.ucwords = function() {
3916  return this.each(function() {
3917    var obj = $( this );
3918    var str = obj.html();
3919    // Convert to initial case
3920    str = (str + '').toLowerCase().replace(/\b[a-z\u00E0-\u00FC]/g, function($1) { return $1.toUpperCase(); });
3921    // With some exceptions in all-caps
3922    str = (str + '').replace(/(XX|XXX|XL|XS|DVD|CD|MP3)/ig, function($1) { return $1.toUpperCase(); });
3923    obj.html(str);
3924  });
3925}
3926
3927function timberSetCookie(cname, cvalue, exdays) {
3928  var d = new Date();
3929  d.setTime(d.getTime() + (exdays*24*60*60*1000));
3930  var expires = "expires="+ d.toUTCString();
3931  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
3932}
3933function timberGetCookie(cname) {
3934  var name = cname + "=";
3935  var ca = document.cookie.split(';');
3936  for(var i = 0; i <ca.length; i++) {
3937    var c = ca[i];
3938    while (c.charAt(0) == ' ') {
3939      c = c.substring(1);
3940    }
3941    if (c.indexOf(name) == 0) {
3942      return c.substring(name.length, c.length);
3943    }
3944  }
3945  return "";
3946}
3947function getQueryParameter(name) {
3948  url = window.location.href;
3949  name = name.replace(/[\[\]]/g, "\\$&");
3950  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
3951    results = regex.exec(url);
3952  if (!results) return null;
3953  if (!results[2]) return '';
3954  return decodeURIComponent(results[2].replace(/\+/g, " "));
3955}
3956function creditCardNumToType(num) {
3957  // first, sanitize the number by removing all non-digit characters.
3958  num = num.replace(/[^\d]/g,'');
3959
3960  // now test the number against some regexes to figure out the card type.
3961  if (num.match(/^5[1-5]\d{14}$/)) {
3962    return 'Mastercard';
3963  } else if (num.match(/^4\d{15}/)) {
3964    return 'Visa';
3965  } else if (num.match(/^3[47][0-9]{11}/)) {
3966    return 'American Express';
3967  } else if (num.match(/^6011\d{12}/)) {
3968    return 'Discover';
3969  }
3970  return 'UNKNOWN';
3971}
3972
3973/**
3974 *  This replaces the ubercart setQuoteCallbacks function with a wrapper
3975 *  that calls the triggerQuoteCallback in a setTimeout.
3976 *  This ensures that multiple, rapid, triggers of the quote callback will
3977 *  be reduced to a single shipping quote request.
3978 *  The problem this solves stems from the UCXF saved addresses. Choosing a
3979 *  saved address was resulting in 2 or even 3 posts to /cart/checkout/shipping/quote,
3980 *  and if there was an international method, that would return slower than the others, and
3981 *  so domestic addresses would end up showing international ship methods.
3982 */
3983var triggerQuoteCallbackTimeout = false;
3984var shipIntervalAdded = false;
3985function replaceUC_setQuoteCallbacks() {
3986  // if(timberIsAdmin) console.log(timberAdminStates.join+': replaceUC_setQuoteCallbacks');
3987  // Replace the UC core setQuoteCallbacks method with our own wrapper...
3988  setQuoteCallbacks = function(products, context) {
3989    // if(timberIsAdmin) console.log(timberAdminStates.join+': TIMBER setQuoteCallbacks BEGIN');
3990    triggerQuoteCallback = function() {
3991      // if(timberIsAdmin) console.log(timberAdminStates.join+': TIMBER triggerQuoteCallback');
3992      clearTimeout(triggerQuoteCallbackTimeout);
3993      if(
3994        $("input[name*=delivery_postal_code]").val()
3995        || $("input[name*=delivery_postal_code]").length == 0
3996        || $("select[name*=delivery_ucxf_county]").val() != ''
3997      ) {
3998        triggerQuoteCallbackTimeout = setTimeout(function() {
3999          timberAdminStates.add = 'triggerQuoteCallbackTimeout';
4000          // if(timberIsAdmin) console.log(timberAdminStates.join+': quoteCallback FIRING');
4001          quoteCallback(products);
4002          timberAdminStates.remove = 'triggerQuoteCallbackTimeout';
4003        }, 200);
4004        // if(!shipIntervalAdded) {
4005          addShipInterval();
4006          addShipWatcher();
4007          // shipIntervalAdded = true;
4008        // }
4009      } else {
4010        if(timberIsAdmin) console.log(timberAdminStates.join+': Not queueing quoteCallback since no delivery postal code set');
4011        $('#quote .form-item').remove();
4012      }
4013    };
4014
4015    // Unbind the default Ubercart binds so we don't end up with multiple quote requests
4016    $("input[name*=delivery_postal_code].getQuotes-processed").removeClass('getQuotes-processed').unbind('change');
4017    $("select[name*=delivery_ucxf_county].getQuotes-processed").removeClass('getQuotes-processed').unbind('change');
4018    $("input[id*=quote-button].getQuotes-processed").removeClass('getQuotes-processed').unbind('click');
4019    $("input[name*=quote_method].getQuotes-processed").removeClass('getQuotes-processed').unbind('change');
4020    $("select[name*=delivery_address_select].getQuotes-processed").removeClass('getQuotes-processed').unbind('change');
4021    $("input[id*=delivery-copy-address].getQuotes-processed").removeClass('getQuotes-processed').unbind('click');
4022    $("input[name*=billing_postal_code].getQuotes-processed").removeClass('getQuotes-processed').unbind('change');
4023    $("select[name*=billing_address_select].getQuotes-processed").removeClass('getQuotes-processed').unbind('change');
4024
4025    // Now, set our own binds
4026    $("input[name*=delivery_postal_code]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').bind('change', triggerQuoteCallback);
4027
4028    // SBL tax locale by county
4029    $("select[name*=delivery_ucxf_county]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').bind('change', triggerQuoteCallback);
4030
4031    $("input[id*=quote-button]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').click(function() {
4032      // returns false to prevent default actions and propagation
4033      triggerQuoteCallback();
4034      return false;
4035    });
4036    $("input[name*=quote_method]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').change(function() {
4037      // returns false to prevent default actions and propagation
4038      triggerQuoteCallback();
4039      return false;
4040    });
4041
4042    $("select[name*=delivery_address_select]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').change(function() {
4043      $("input[name*=delivery_postal_code]").trigger('change');
4044    });
4045
4046    $("input[id*=delivery-copy-address]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').click(function() {
4047      if (copy_box_checked == true) {
4048        $("input[name*=billing_postal_code]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').bind('change', triggerQuoteCallback);
4049        $("select[name*=billing_address_select]:not(.timberGetQuotes-processed)", context).addClass('timberGetQuotes-processed').bind('change', triggerQuoteCallback);
4050        triggerQuoteCallback();
4051      }
4052      else {
4053        $("input[name*=billing_postal_code].timberGetQuotes-processed").removeClass('timberGetQuotes-processed').unbind('change', triggerQuoteCallback);
4054        $("select[name*=billing_address_select].timberGetQuotes-processed").removeClass('timberGetQuotes-processed').unbind('change', triggerQuoteCallback);
4055      }
4056    });
4057    if($('body').hasClass('quote-needed')) {
4058      $('body').removeClass('quote-needed');
4059      $('#edit-panes-quotes-quote-button').click();
4060    }
4061
4062  }
4063  $('#edit-panes-quotes-quote-button').addClass('timberQuoteActionOverride');
4064
4065  $('#edit-panes-coupon-code').blur(function() {
4066    getCoupon();
4067  });
4068
4069}
4070
4071/**
4072 * Sets a line item in the order total preview.
4073 */
4074function timber_set_line_item(key, title, value, weight, summed, render) {
4075  if (summed === undefined) {
4076    summed = 1;
4077  }
4078  // Set the values passed in, overriding previous values for that key.
4079  if (key != "") {
4080    li_titles[key] = title;
4081    li_values[key] = value;
4082    li_weight[key] = weight;
4083    li_summed[key] = summed;
4084  }
4085  timber_render_line_items();
4086}
4087
4088var timberRenderLineItemsTimeout = false;
4089var timberRenderLineItemsRevealTimeout = false;
4090/**
4091 * This collects all the various calls to this function, and runs just one
4092 * call to render_line_items after all others have stopped for 500 milliseconds
4093 * And only shows the final calculation after 3000 milliseconds
4094 */
4095function timber_render_line_items() {
4096  // console.log('timber_render_line_items');
4097  $('#line-items-div').addClass('running-graphic '+timberCartOptions.runningGraphic);
4098  $('#running-message').remove();
4099  $('#line-items-div').after("<div id='running-message'>"+timberCartOptions.runningMessage+"</div>");
4100  clearTimeout(timberRenderLineItemsTimeout);
4101  clearTimeout(timberRenderLineItemsRevealTimeout);
4102  timberRenderLineItemsTimeout = setTimeout(function() {
4103    render_line_items();
4104  }, 500);
4105  timberRenderLineItemsRevealTimeout = setTimeout(function() {
4106    $('#line-items-div').removeClass('running-graphic');
4107    $('#running-message').remove();
4108  }, 1000);
4109}
4110
4111$(document).ready(function() {
4112  // Use the behavior instead - don't put code here
4113
4114  //ADA - Changing asterix to required for ADA compliance
4115  $('form .form-required').each(function(){
4116    $(this).parent().addClass('ada-improved funcs').append('<span class="required-field"> (required)</span>');
4117  });
4118
4119  //ADA - adds Skip-to-Content if needed
4120  setTimeout(function() {
4121    skip_html = '<div class="visually-hidden-focusable skip-link"><a href="#">Skip to main content</a></div>';
4122    if($('body:contains("Skip to main content")').length < 1) {
4123      $('body').prepend(skip_html);
4124    }
4125    if($('body:contains("Skip to main content")').length < 1) {
4126      console.log('no');
4127    }
4128    //ADA - animation for Skip-to-Content link
4129    $('.skip-link a').click(function(){
4130      $('html, body').animate({
4131        scrollTop: $('h1').offset().top
4132      }, 500); // Duration in milliseconds
4133      console.log('click');
4134    });
4135  }, 500);
4136
4137  //ADA - set tabindex order for Cart page
4138  cart_tabindex = 1;
4139  $('#cart-form-products tr').each(function(){
4140    $(this).find('.desc a').attr('tabindex',cart_tabindex);
4141    cart_tabindex ++;
4142    $(this).find('.qty input').attr('tabindex',cart_tabindex);
4143    cart_tabindex ++;        
4144    $(this).find('.remove input').attr('tabindex',cart_tabindex);    
4145    cart_tabindex ++;    
4146  });
4147
4148
4149});
4150;
4151Drupal.behaviors.timberCollegeBehavior = function(context) {
4152  // SBL hide repeated item notes
4153  var arr = [];
4154  var previous_note = '';
4155  var previous_grp = '';
4156  var current_note = '';
4157  var current_grp = '';
4158  $(context).find('.timber-item-group .chooser-product .item-note').each(function() {
4159    arr.push($(this));
4160  });
4161  for (var i=0;i<arr.length;i++) {
4162		current_note = arr[i].html();
4163		current_grp = arr[i].parent().attr('grp');
4164    if (
4165    	current_note.length == 0
4166    	|| (
4167    		previous_note === current_note
4168    		&& previous_grp === current_grp
4169    	)
4170    ) {
4171      $(arr[i]).addClass('hide');
4172    }
4173    previous_note = current_note;
4174    previous_grp = current_grp;
4175  }
4176
4177	if($('.item.type-college_term.view-only.selected').length > 0) {
4178		$('.tcc-container').addClass('view-only');
4179	} else {
4180		$('.tcc-container').removeClass('view-only');
4181	}
4182	// $(context).find(".tcc-checkout a").bind('click', function() {
4183	// });
4184	$(context).find(".tcc-row div.item, .tcc-close").bind('click', function() {
4185		clicked = $(this);
4186		if(clicked.hasClass('group')) return;
4187		container = clicked.parents('.parent').filter(':first');
4188		toremove = false;
4189		if(clicked.hasClass('tcc-close') || container.hasClass('selected')) {
4190			if(clicked.hasClass('tcc-close')) {
4191				container = container.prev();
4192				clicked = container.find('a.selected').filter(':first');
4193			}
4194			if(container.length>0) {
4195				container.addClass('selected');
4196				toremove = container.next();
4197			}
4198		}
4199
4200		if(container.hasClass('selected')) { //Hiding
4201			$.ajax({
4202				url: "/timber/college/ajax?clear=1&l="+encodeURIComponent($("div.item.selected a.tcc-item-link").filter(':last').attr('url'))
4203			});
4204			if(!toremove) toremove = container.next();
4205
4206			container.removeClass('selected');
4207			container.find('.item.hide').removeClass('hide');
4208			container.find('.item.selected').removeClass('selected');
4209
4210		} else { // Showing
4211			container.addClass('selected');
4212			// console.log(container);
4213			container.find('.item').addClass('hide'); $(this).removeClass('hide').addClass('selected');
4214
4215			$.ajax({
4216				url: "/timber/college/ajax?l="+encodeURIComponent($(this).find('a.tcc-item-link').attr('url')),
4217				success: function(data) {
4218					obj = $(data);
4219					Drupal.attachBehaviors(obj);
4220
4221					var objid = obj.attr('id');
4222
4223					// Remove old object
4224					$('#'+objid).remove();
4225
4226					obj.appendTo(container.parent());
4227					// Slidedown object - this must be done separately from the appendTo above, since IE sucks
4228					$('#'+objid).hide().slideDown();
4229
4230					updateCheckoutLink();
4231				}
4232			});
4233
4234			go_to = container;
4235			if(container.parents('.parent').filter(':first').length > 0) {
4236				go_to = container.parents('.parent').filter(':first');
4237			}
4238			scrollTo(go_to);
4239			if(go_to && go_to.offset()) {
4240				$('html, body').animate({
4241					scrollTop: go_to.offset().top
4242				}, 500);
4243			}
4244		}
4245
4246		if(toremove && toremove.length>0) {
4247			toremove.addClass('toRemove').nextAll().addClass('toRemove');
4248			$('.toRemove').slideUp({
4249				duration:500,
4250				complete:function(){ $('.toRemove').remove(); }
4251			});
4252		}
4253
4254		return false;
4255	});
4256	$(context).find(".tcc-row div.item .detected-note-link").bind('click', function(event) {
4257		event.stopPropagation();
4258	});
4259	$(context).find(".group-select.select-cheapest").bind('click', function() {
4260		$('.chooser-product').removeClass('selected');
4261		console.log($('.chooser-product'));
4262		$('.chooser-product.cheapest').click();
4263		$('.req-group-P .chooser-product.cheapest').click();
4264		scrollTo('.ajax-cart-link:last');
4265		return false;
4266	});
4267	$(context).find(".group-select.select-cheap-buy").bind('click', function() {
4268		$('.chooser-product').removeClass('selected');
4269		$('.chooser-product.cheap-buy').click();
4270		scrollTo('.ajax-cart-link:last');
4271		return false;
4272	});
4273	$(context).find(".group-select.select-clear").bind('click', function() {
4274		$('.chooser-product').removeClass('selected');
4275		updateCheckoutLink();
4276		return false;
4277	});
4278	if($('#princeton_2021_inspired').length > 0) {
4279		var item_groups = $(context).find(".timber-item-group");
4280		item_groups.each(function() {
4281      var groupobj = $(this);
4282			collegeDetails(groupobj);
4283		});
4284	} else {
4285		// User clicks on a product - this should check/uncheck the selection boxes
4286		$(context).find(".timber-item-group").bind('mouseenter', function() {
4287			$(this).find(".chooser-product")
4288			var groupobj = $(this);
4289			toDelay(() =>  collegeDetails(groupobj) , 5);
4290			$(this).find('.timber-details').addClass('active');
4291		}).bind('mouseleave', function() {
4292			toClear();
4293			$('.timber-details.active').removeClass('active').stop().css('opacity',1).show().fadeOut('fast');
4294		});
4295	}
4296
4297	$(context).find(".chooser-product").bind('click', function(e) {
4298		let isMinimized = false;
4299		// If clicking a link in the field-edition, follow the link instead of toggling the cart checkbox
4300		if($(e.target).parent().hasClass('field-edition')) return;
4301		if($(e.target).hasClass('detected-note-link')) return;
4302
4303		var itemParent = $(this).parents('.item').filter(':first');
4304		if(!$(this).hasClass('unavailable')) {
4305			gid=$(this).attr('grp');
4306			nid=$(this).attr('nid');
4307			if($(this).hasClass('selected')) {
4308				$(this).removeClass('selected');
4309			} else {
4310				itemParent.find('.chooser-product[grp="'+gid+'"]').removeClass('selected');
4311
4312				// this gets added after myclick function, which is causing issues.
4313				$(this).addClass('selected');
4314			}
4315
4316			if($(this).hasClass('selected') && !$(this).hasClass('unavailable')) {
4317				console.log('is selected, and available')
4318				isMinimized = true;
4319			} else if($(this).hasClass('unavailable')) {
4320				console.log('not selected, and unavailable')
4321				isMinimized = false;
4322			}
4323
4324			if(isMinimized) {
4325				itemParent.addClass('minimized');
4326			} else {
4327				itemParent.removeClass('minimized');
4328			}
4329			updateCheckoutLink();
4330		}
4331		return false;
4332	});
4333
4334	$(context).find(".timber-details").bind('click', function(e) {
4335		// If clicking a link inside the timber-details popup, follow the link.
4336		if($(e.target).is('a')) e.stopPropagation();
4337	});
4338
4339	// Check the context when on the textbook lookup page, then look it up through the DOM with the /my-courses page
4340	if($(context).find('#princeton_2021_inspired').length > 0 || $('#princeton_2021_inspired').length > 0) {
4341		$(context).find('#princeton_2021_inspired form').each(function() {
4342			$(this).insertBefore($(this).prev().find('.chooser-section-instructor'));
4343		})
4344		$(context).find('.timber-item-group').each(function() {
4345			let label, price;
4346			let atcText = "Select an option";
4347			var newProduct = $(this).find('.chooser-product.new');
4348			$(this).find('.chooser-product').each(function() {
4349				if(!$(this).hasClass('unavailable')) {
4350					label = $(this).find('.product-type-label').text();
4351					price = $(this).find('.product-type-price').text();
4352				}
4353				if($(this).hasClass('used')) {
4354					$(this).insertAfter(newProduct)
4355				}
4356			})
4357			$(this).find('.chooser-product, .inclusive-access-text, .inclusive-access-link').wrapAll('<div class="student-prices-container"></div>');
4358
4359			if($(this).hasClass('selected'))  atcText = `${label} ${price}`;
4360
4361			// $(`<div class="item-group-atc-button">${atcText}</div>`).insertBefore($(this).find('.tcc-buyback-price:first'))
4362		})
4363}
4364
4365	// Check the context when on the textbook lookup page, then look it up through the DOM with the /my-courses page
4366	if($(context).find('#princeton_2021_inspired').length > 0 || $('#princeton_2021_inspired').length > 0) {
4367
4368		$(context).find('.chooser-product').each(function() {
4369			if($(this).hasClass('selected')) {
4370				$(this).parent().parent().addClass('minimized');
4371			}
4372		})
4373		$(context).find('.tcc-product-link').click(function() {
4374			if(!$(this).parent().hasClass('unavailable')) {
4375				var label = $(this).find('.product-type-label').text();
4376				var price = $(this).find('.product-type-price').text();
4377				let atcText = 'Select an option';
4378
4379				if(!$(this).parent().hasClass('selected'))  atcText = `${label} ${price}`;
4380				$(this).parent().parent().children('.item-group-atc-button').text(`${atcText}`)
4381
4382				// if($(this).parent().hasClass('used')) {
4383				// 	$(this).parent().parent().find('.tcc-buyback-price.Used').css('display', 'block');
4384				// 	$(this).parent().parent().find('.tcc-buyback-price.New').css('display', 'none');
4385				// } else {
4386				// 	$(this).parent().parent().find('.tcc-buyback-price.Used').css('display', 'none');
4387				// 	$(this).parent().parent().find('.tcc-buyback-price.New').css('display', 'block');
4388				// }
4389			}
4390
4391		})
4392
4393	}
4394
4395
4396};
4397$(document).ready(function() {
4398	updateCheckoutLink();
4399
4400	var groupSelectClick = getQueryParameter('groupSelect');
4401  if(groupSelectClick && $('.'+groupSelectClick).length > 0) {
4402		toDelay(function() { $('.'+groupSelectClick).click(); }, 100);
4403  } else {
4404		// Run once on page load - scrolls to the active materials, if there are any
4405		if($('.tcc-section').length > 0) {
4406			scrollTo('#tcc-product');
4407		}
4408	}
4409
4410	// //Wrap cart button in div to aid in styling
4411	// if($('.cart-fixed').length < 1) {
4412	// 	$('.group-select.ajax-cart-link').wrap('<div class="cart-fixed">');
4413	// }
4414
4415	$(function(){
4416	  $(window).resize(function(){
4417	      placeFooter();
4418	  });
4419	  placeFooter();
4420	  // hide it before it's positioned
4421	  // $('.cart-fixed').css('display','inline');
4422	});
4423
4424}); // End Doc Ready
4425
4426function placeFooter() {
4427  var windHeight = $(window).height();
4428  var footerHeight = $('#footer-wrapper').height();
4429  var offset = parseInt(windHeight) - parseInt(footerHeight);
4430  $('.cart-fixed').css('top',offset);
4431}
4432
4433
4434var timeout;
4435function toDelay(func, delay) {
4436	timeout = setTimeout(func, delay);
4437}
4438function scrollTo(selector) {
4439	if(typeof selector == 'string') {
4440		if($(selector).length > 0) {
4441			go_to = $(selector);
4442			if(go_to && go_to.offset()) {
4443				$('html, body').animate({
4444					scrollTop: go_to.offset().top
4445				}, 500);
4446			}
4447		}
4448	} else {
4449		if(selector.length > 0) {
4450			go_to = selector;
4451			if(go_to && go_to.offset()) {
4452				$('html, body').animate({
4453					scrollTop: go_to.offset().top
4454				}, 500);
4455			}
4456		}
4457	}
4458}
4459
4460function collegeDetails(groupobj) {
4461	if(groupobj.find('.timber-details:not(.loaded):not(.loading)').length > 0) {
4462		groupobj.find('.timber-details:not(.loaded):not(.loading)').each(function() {
4463			$(this).addClass('loading');
4464			//if($(this).length == 0) return;
4465			var nid = groupobj.find('.chooser-product').attr('nid');
4466			var csection_id = groupobj.find('.chooser-product').attr('sectionid');
4467			var cadoption_id = parseInt(groupobj.find('.chooser-product').attr('cadoption_id'));
4468			var viewUrl = "/timber/college/details/"+nid; // Old url
4469			if(cadoption_id > 0) {
4470  			var viewUrl = "/timber/college/details/"+nid+"/"+cadoption_id; // new URL if cadoption_id is set
4471			}
4472			$.ajax({
4473				url: viewUrl,
4474				success: function(data) {
4475
4476					obj = $(data);
4477					Drupal.attachBehaviors(obj);
4478					if($('#princeton_2021_inspired').length === 1) {
4479						$('<h6 class="student-discount-header">Student Discount Prices:</h6>').prependTo($(groupobj).find('.student-prices-container'));
4480						if($(data).find('.views-field-list-price').length > 0)	{
4481							$(data).find('.views-field-list-price').prependTo($(groupobj).find('.student-prices-container'));
4482						}
4483					}
4484					$('.timber-details-'+csection_id+'-'+nid).each(function() {
4485						$(this).empty().append(obj).removeClass('hide').removeClass('loading').addClass('loaded');
4486						if(!$('#princeton_2021_inspired').length) {
4487							if(!$(this).hasClass('active')) {
4488								$(this).stop().css('opacity',1).show().fadeOut('fast');
4489							}
4490						}
4491					});
4492					$('.active.timber-details-'+csection_id+'-'+nid).fadeIn('fast');
4493
4494				}
4495			});
4496		});
4497	} else {
4498		groupobj.find('.timber-details').fadeIn('fast');
4499	}
4500
4501}
4502
4503function toClear() {
4504	clearTimeout(timeout);
4505}
4506
4507function updateCheckoutLink() {
4508	var cartlink = '';
4509	var sectionid = '';
4510	$('.tcc-container .chooser-product.selected').each(function() {
4511		cartlink += $(this).attr('cartlink')+'-';
4512		if($(this).attr('sectionid').length > 0) {
4513			var sid = $(this).attr('sectionid');
4514			if(sid) sectionid = sid;
4515		}
4516	});
4517	$('.tcc-container .chooser-product.carted:not(.selected)').each(function() {
4518		cartlink += $(this).attr('cartrm')+'-';
4519	});
4520	if(cartlink) {
4521		cartlink = '/cart/add/'+cartlink+'?sectionid='+sectionid+'&destination=cart%3Fcontinue=college';
4522		$('a.ajax-cart-link').attr('href',cartlink);
4523		atcEnable();
4524	} else {
4525		atcDisable();
4526	}
4527
4528	$('.tcc-grp-message').remove();
4529
4530	var checkoutMessage = '';
4531	var checkoutMessage2 = '';
4532	var num_required = 0;
4533	$('.req-group-R').each(function() {
4534		num_required=num_required + parseInt($(this).attr('num_group_items'));
4535	});
4536	num_selected=$('.req-group-R').find('.chooser-product.selected').length;
4537	if(num_selected != num_required) {
4538		s=num_selected!=1?'s':'';
4539		checkoutMessage += '<div class="red item-warning required">You have only selected '+num_selected+' required item'+s+' ('+num_required+' required)</div>';
4540	}
4541
4542	num_required = 0;
4543	num_selected = 0;
4544	$('.req-group-C').each(function() {
4545
4546		var sectionid = '';
4547		var sid = $(this).attr('sectionid');
4548		if(sid) sectionid = sid;
4549
4550		num_required += parseInt($(this).attr('req_qty'));
4551		num_selected += $(this).find('.chooser-product.selected').length;
4552
4553		if(num_selected < num_required) {
4554			s=num_selected!=1?'s':'';
4555			checkoutMessage += '<div><a class="red item-warning choice" href="#section-details-'+sectionid+'">You have only selected '+num_selected+' choice item'+s+' ('+num_required+' required)</a></div>';
4556		}
4557		if(num_selected > num_required) {
4558			s=num_selected!=1?'s':'';
4559			checkoutMessage += '<div><a class="red item-warning choice" href="#section-details-'+sectionid+'">You have selected '+num_selected+' choice item'+s+' (only '+num_required+' required)</a></div>';
4560			checkoutMessage2 = '<div class="tcc-grp-message tcc-choice-message message"><div class="red">You have selected '+num_selected+' choice item'+s+' (only '+num_required+' required)</div></div>';
4561			$(this).find('.title').after(checkoutMessage2);
4562		}
4563	});
4564
4565	num_required = 0;
4566	num_selected = 0;
4567	$('.req-group-CG .choice-group').each(function() {
4568		var sectionid = '';
4569		var cgname = $(this).attr('choice-group-name');
4570
4571		num_required = parseInt($(this).attr('req_num_group_items'));
4572		num_selected = $(this).find('.chooser-product.selected').length;
4573
4574		if(num_selected < num_required) {
4575			s=num_selected!=1?'s':'';
4576			checkoutMessage += '<div><a class="red item-warning choice" href="#section-details-'+cgname+'">'+cgname+': You have only selected '+num_selected+' choice item'+s+' ('+num_required+' required)</a></div>';
4577		}
4578		if(num_selected > num_required) {
4579			s=num_selected!=1?'s':'';
4580			checkoutMessage += '<div><a class="red item-warning choice" href="#section-details-'+cgname+'">You have selected '+num_selected+' choice item'+s+' (only '+num_required+' required)</a></div>';
4581			checkoutMessage2 = '<div class="tcc-grp-message tcc-choice-message message"><div class="red">You have selected '+num_selected+' choice item'+s+' (only '+num_required+' required)</div></div>';
4582			$(this).find('.title').after(checkoutMessage2);
4583		}
4584	});
4585	num_selected = 0;
4586	$('.req-group-O').each(function() {
4587		num_required = 0;
4588		num_selected += $(this).find('.chooser-product.selected').length;
4589
4590		if(num_selected > num_required) {
4591			s=num_selected!=1?'s':'';
4592			checkoutMessage2 = '<div class="tcc-grp-message tcc-opt-message message"><div class="red">
4592These items are optional and not required for the course.</div></div>';
4593			$(this).find('.title').after(checkoutMessage2);
4594		}
4595
4596	});
4597	if(num_selected > 0) {
4598		s=num_selected!=1?'s':'';
4599		checkoutMessage += '<div class="red item-warning optional">You have selected '+num_selected+' optional item'+s+'. These items are not required for the course, but you may still purchase them.</div>';
4600	}
4601
4602	$('.tcc-req-message').html(checkoutMessage);
4603	if(checkoutMessage.length > 0) {
4604		$('.tcc-req-message').removeClass('hide');
4605	} else {
4606		$('.tcc-req-message').addClass('hide');
4607	}
4608}
4609
4610function atcDisable() {
4611	$('a.ajax-cart-link').attr('href','javaScript:void(0);');
4612	$('.tcc-checkout').addClass('disabled');
4613
4614}
4615
4616function atcEnable() {
4617	$('.tcc-checkout').removeClass('disabled');
4618}
4619;
4620/*
4621 * This filters the attribute option select boxes.
4622 */
4623
4624if(!Object.keys) Object.keys = function(o){
4625 if (o !== Object(o))
4626      throw new TypeError('Object.keys called on non-object');
4627 var ret=[],p;
4628 for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
4629 return ret;
4630}
4631
4632Drupal.behaviors.timberCartBehavior = function(context) {
4633  //Selects the Please Select option.  Not sure why Hiram needs this
4634  $('.add-to-cart select', context).each(function() {
4635    var pleaseSelectOption = $(this).find('option:contains("Please Select")');
4636    if( $(this).find('option').length > 2 ) {
4637      pleaseSelectOption.attr('selected', 'selected');
4638    }
4639  });
4640
4641  //$('.disabled-option').attr('disabled', 'disabled');
4642  //--- Wrap the price and addtocart together into one neat bundle!
4643  $('.field-type-computed.field-field-price, .field-type-computed.field-field-addtocart', context).addClass('price-block-item');
4644  $('.field-type-computed.field-field-price', context).hover(
4645    function() {
4646    $(this).addClass('hover');
4647  },function() {
4648    $(this).removeClass('hover');
4649  });
4650
4651  $('.add-to-cart', context).each(function() {
4652    if($(this).parents('.node').filter(':first').length > 0) {
4653      $(this).parents('.node').filter(':first').addClass('timber-cart-toplevel');
4654    } else if($(this).parents('.views-row').filter(':first').length > 0) {
4655      $(this).parents('.views-row').filter(':first').addClass('timber-cart-toplevel');
4656    }
4657  });
4658  $('.timber-cart-toplevel .field-field-image', context).addClass('timber-cart-images');
4659  $('.timber-cart-toplevel .views-field-field-image-fid', context).addClass('timber-cart-images');
4660  $('.timber-cart-toplevel .field-image', context).addClass('timber-cart-images');
4661
4662  $('#content-area .node', context).each(function() {
4663    $(this).find('.price-block-item').wrapAll('<div class="price-block" />');
4664  });
4665
4666  $(".add-to-cart select.timber-attribute", context).change(onSelectChange);
4667  $(".add-to-cart select.custom-attribute", context).change(onSelectChange);
4668  $(".add-to-cart", context).each(function() {
4669    $(this).find('select.timber-attribute').filter(':first').change();
4670  });
4671
4672  if ($.browser.msie) { // We need to store copies of the select boxes for stupid IE...
4673    $(".add-to-cart select.timber-attribute", context).each(function() {
4674      $(this).data("original", { select: $(this).parent().html() });
4675    });
4676  }
4677
4678  //Hides all but the first image of any image group related to the attribute selectors -- only if there are products with imgflip attributes on the page
4679  // if ($('.add-to-cart .attributes .form-select.imgflip', context).length > 0) {
4680  //   $('.add-to-cart .attributes .form-select.imgflip', context).each(function () {
4681  //     $($(this).parents('.timber-cart-toplevel').get(0)).find('.timber-cart-images .field-item:not(:first)').hide();
4682  //   });
4683  // }
4684
4685};
4686
4687// Helper for image replacement above
4688String.prototype.filename=function(extension) {
4689  var s = this.replace(/\\/g, '/');
4690  s = s.replace(/%20/g, ' ');
4691  s = s.substring(s.lastIndexOf('/')+ 1);
4692  return extension? s.replace(/[?#].+$/, ''): s.split('.')[0];
4693}
4694
4695function hidePrices(obj) {
4696  var tmp = obj.parents('.add-to-cart');
4697  var levels = 0;
4698  do {
4699    levels++;
4700    tmp = tmp.parent();
4701  } while(levels < 5 && tmp.find('.timber-price-for-sku').length == 0);
4702
4703  tmp.find('.timber-price-for-sku').addClass('hide');
4704}
4705
4706function showPrice(nid, sku) {
4707  // NOTE: See matching regex in timber.module, function TT_Product::renderPrice()
4708  sku = sku.replace(/[ \/\\'"\+&]/g,'-');
4709  $('.timber-price-for-sku.sku-'+sku+'.nid-'+nid).removeClass('hide');
4710}
4711
4712function getFormFromElement(obj) {
4713  return 'form#'+ obj.parents('form').get(0).id; // Grab id of parent form tag.
4714}
4715function getFormNidFromElement(obj) {
4716  return getFormFromElement(obj).replace(/.+add-to-cart-form-([0-9]*)(-[0-9]*)?/, "$1");
4717}
4718
4719function onSelectChange() {
4720  var atcForm = getFormFromElement($(this));
4721  var parentNid = getFormNidFromElement($(this));
4722//uc-product-add-to-cart-form
4723
4724  $(atcForm+" select.active").removeClass('active');
4725  $(this).addClass('active');
4726
4727  var attributeParent = '#'+ $(this).attr('id'); // Grab id of select box
4728  var selectedOption = $(atcForm +" "+ attributeParent +" option:selected"); // Grab value of selected option
4729  var selected = selectedOption.val(); // Grab value of selected option
4730
4731  if(selected == '') {
4732    $(this).removeClass('active');
4733  }
4734
4735  if ($.browser.msie) {
4736    // Restore the select boxes from our backup for IE...
4737    $(atcForm +" select").not($(atcForm +" "+ attributeParent +" select")).
4738    each(function() {
4739      currSelect = $(this).find('option:selected').val(); // Save currently selected option
4740      $(this).parent().children().not("select").remove(); // Remove elements
4741      var orgobj = $(this).data("original");
4742      if(typeof orgobj !== 'undefined') {
4743        $(this).replaceWith(orgobj.select); // Replace with saved data
4744      }
4745
4746      // Use current id to..
4747      var currId = '';
4748      var selobj = $(this).parent().children("select").get(0);
4749      if(typeof selobj !== 'undefined') {
4750        currId = selobj.id;
4751        // .. restore the selected option
4752        $(atcForm +' select#'+currId).find("option[value='"+ currSelect +"']").attr('selected', 'selected');
4753        // .. re-bind the change event handler to the new form items
4754        $(atcForm +' select#'+currId).unbind('change', onSelectChange).change(onSelectChange);
4755      }
4756    });
4757  } else {
4758    $(atcForm +" option").not($(atcForm +" "+ attributeParent +" option")).show(); // Make sure all options are visible initially
4759    $(atcForm +" option").not($(atcForm +" "+ attributeParent +" option")).removeAttr('disabled');
4760  }
4761
4762  if (!selected) { // If 'Choose...' (NULL) is selected, reset other boxes too.
4763    if ($.browser.msie) {
4764      // Restore the select boxes from our backup for IE...
4765      $(atcForm +' div.form-item').each(function() {
4766        $(this).children().not("select").remove(); // Remove elements
4767        var orgobj = $(this).children("select").data("original");
4768        if(typeof orgobj !== 'undefined') {
4769          $(this).children("select").replaceWith($(this).children("select").data("original").select); // Replace with saved data
4770        }
4771
4772        // Re-bind the change event handler to the new form items
4773        $(this).children("select").unbind('change', onSelectChange).change(onSelectChange);
4774      });
4775    } else {
4776      $(atcForm +" option").show(); // Make sure all options visible
4777      $(atcForm +" option").removeAttr('disabled');
4778    }
4779  }
4780
4781  var tcOptions = window['timberCartOptions_'+parentNid];
4782  var tcVariants = window['timberCartVariants_'+parentNid];
4783  if(typeof tcOptions !== "undefined" ) {
4784
4785    var imgFlipAttrSelected = false;
4786    all_selected = {};
4787    $(atcForm+" option:selected").each(function() {
4788      v = $(this).attr('value');
4789      if(v != '') {
4790        if($(this).parent().hasClass('imgflip')) imgFlipAttrSelected = true;
4791        all_selected[v] = v;
4792      }
4793    });
4794
4795    // If we haven't made a selection in an imgflip attribute (color), force default images instead of custom ones
4796    var forceDefaultImages = !imgFlipAttrSelected;
4797
4798    /**
4799     *   This decides what to show in the price (a range or single price)
4800     */
4801    attrData = availableAttributeData(all_selected, tcOptions, tcVariants, forceDefaultImages);
4802    attrData.nid = parentNid;
4803    var custom_price = '';
4804    var class_add = 'price-single';
4805    var class_remove = 'price-multiple';
4806    // See if there's a price adjustment attached to a custom attribute (rare, but sometimes used for )
4807    $(atcForm +" .attribute select.custom-attribute") // Iterate over custom attribute sets
4808      .each(function() {
4809        if ($(this).val()) { // The option has a value
4810          if($(this).hasClass('active')) {
4811            if(tcOptions.price_adjustment.length > 0 && tcOptions.price_adjustment[$(this).val()].length > 0 && tcOptions.price_adjustment[$(this).val()]['price']) {
4812              custom_price = tcOptions.price_adjustment[$(this).val()]['display_price'];
4813            }
4814          }
4815        }
4816    });
4817    if(!custom_price) {
4818      if(attrData.pricelow != attrData.pricehigh) {
4819        class_add = 'price-range';
4820        class_remove = 'price-single';
4821      }
4822    }
4823    // Hide all prices, then show just the one we need
4824    // console.log('HIDE ALL PRICES');
4825    hidePrices($(this), attrData.nid);
4826    if(attrData.pricelow == attrData.pricehigh) {
4827      // console.log('SHOW PRICE FOR SKU '+attrData.sku);
4828      showPrice(attrData.nid, attrData.sku);
4829    } else {
4830      // console.log('SHOW DEFAULT PRICE');
4831      showPrice(attrData.nid, 'default');
4832    }
4833  }
4834
4835
4836  /**
4837   *   This shows/hides available options in the select boxes
4838   */
4839  var activeForm = $(this).parents('form').filter(':first');
4840  activeForm.each(function() {
4841    //Get the nid for node associated with the add to cart form
4842    var atcNid = $(this).attr('nid');
4843
4844    // Find the timberCartOptions for this add-to-cart form
4845    var tcOptions = ('timberCartOptions_'+atcNid);
4846    tcOptions = eval(tcOptions);
4847
4848    var selectBoxes = $(this).find(".attribute select.timber-attribute");
4849    if(selectBoxes.length == 0) return;
4850
4851    // if there is only one select box, we will need to now grey out and
4852    // disable options because they are no longer hidden with php
4853    if(selectBoxes.length == 1){
4854      const singleOptions = tcOptions.single_options;
4855      $(this).find(".attribute select.timber-attribute option").each(function(){
4856        for (const optionID in singleOptions) {
4857          if($(this).val() == optionID && singleOptions[optionID] == 0) $(this).attr("disabled","disabled");
4858        }
4859        
4860      });
4861      return;
4862    }
4863
4864    // Loop through all attribute selectors in the form
4865    selectBoxes.each(function() {
4866      var nonEmptyOptions = 0;
4867      $(this).find('option').each(function() {
4868        if($(this).val()) nonEmptyOptions++;
4869      });
4870      if(nonEmptyOptions < 2) return;
4871
4872      var currentAttr = $(this).attr('name').replace("attributes[",'').replace("]",'');
4873      var otherSelectedOptions = [];
4874      // Compute an array of options selected NOT part of this select box
4875      selectBoxes.each(function() {
4876        var innerAttr = $(this).attr('name').replace("attributes[",'').replace("]",'');
4877        if(currentAttr == innerAttr) return;
4878        var innerOption = $(this).val();
4879        if(innerOption > 0) otherSelectedOptions[innerAttr] = innerOption;
4880      });
4881
4882      // Loop through all attribute options in the current selector being processed
4883      $(this).find('option').each(function() {
4884        var option_id = $(this).attr('value');
4885        if (option_id) { // The option has a value (not a null default)
4886
4887          // Get the possible options for other selectors that might enable this option
4888
4889          var possibleOtherOptions = tcOptions.available_options;
4890          // Disable the option if one of the following is true:
4891          //   No variant is available with all selected options, plus the option in question
4892          //   or the option in question results in no available variants at all
4893          if(
4894            !allIn(otherSelectedOptions, possibleOtherOptions, option_id)
4895            || !objectSearch(possibleOtherOptions, option_id)
4896          ) {
4897            if ($.browser.msie) {
4898              $(this).remove(); // IE doesn't allow hide or disable, so remove it
4899            }
4900            else if ($.browser.mozilla) {
4901              // Firefox doesn't change the appearance of disabled options, so we hide them instead
4902              $(this).attr('disabled', 'disabled');
4903              $(this).hide();
4904            }
4905            else { // It's Safari, Chrome or Opera
4906              $(this).attr('disabled', 'disabled');
4907            }
4908          }
4909        }
4910      });
4911
4912      var howManyEnabled = 0;
4913      var lastEnabledOption = null;
4914      var lastEnabledOptionDescription = '';
4915      var howManyTotal = 0;
4916      $(this).find('option').each(function() {
4917        if(
4918          $(this).attr('value') > 0
4919        ) {
4920          howManyTotal++;
4921          if(!$(this).attr('disabled')
4922          ) {
4923            howManyEnabled++;
4924            lastEnabledOption = $(this);
4925            lastEnabledOptionDescription = $(this).html();
4926          }
4927        }
4928      });
4929
4930      if(howManyEnabled == 1) {
4931        lastEnabledOption.attr('selected', 'selected');
4932      }
4933
4934      var strongObj = $(this).parent().find('.description strong');
4935      if(
4936        howManyTotal == 1
4937      ) {
4938        strongObj.html(strongObj.attr('title')+': '+lastEnabledOptionDescription).removeClass('hide').show();
4939      } else {
4940        strongObj.html('').addClass('hide');
4941      }
4942
4943    });
4944  });
4945
4946
4947  //Grab text of selected option, trim it, format it to lowercase, and replace all spaces with underscores
4948  var selectedOption = $(this).find('option:selected');
4949  var selectedAttribute = $.trim(selectedOption.text()).toLowerCase().replace(/ /g,"_");
4950  //Create a variable for the holding div with the .node-type-product class, return the first result based on the starting position $(this) -- which is the add to cart <select> box.
4951  //Cast this value as a JQuery object.
4952  var product = $(selectedOption.parents('.timber-cart-toplevel').get(0));
4953  var images = product.find('.timber-cart-images .field-item');
4954  //Only proceed if there are more than 1 image assigned to this product
4955  if (images.length > 1) {
4956    var defaultImage = product.find('.timber-cart-images .field-item:first-child');
4957
4958    var img_swap_count = Object.keys(attrData.images).length;
4959    if(img_swap_count > 0) {
4960      // console.log('IMAGE FLIP BY CHOSEN IMAGE');
4961      var c = 0;
4962
4963      images.hide();
4964      images.each(function () {
4965        var fName = $(this).find('img').attr('src').filename(true);
4966
4967        if(valueIn(fName, attrData.images)) {
4968          c++;
4969          $(this).show();
4970        }
4971      });
4972      if (c==0) { images.hide(); defaultImage.show(); }
4973
4974    } else if($(this).hasClass('imgflip')) { // Only process if this is an image flip attribute (color)
4975      /*
4976       *   Default image handler by regex color
4977       */
4978      // console.log('IMAGE FLIP BY REGEX METHOD');
4979
4980      images.hide();
4981      //If default option is selected, show all images
4982      if (!selectedOption.val()) {
4983        // console.log('NO SELECTED VALUE, SHOWING DEFAULT IMAGE');
4984        defaultImage.show();
4985      } else {
4986        // console.log('SELECTED VALUE, CHOOSING IMAGES BY REGEX');
4987        var c = 0;
4988        images.each(function () {
4989          var fName = $(this).find('img').attr('src').filename();
4990          //create RegExp variable based on rule above, global + ignore case
4991          var rex = new RegExp(selectedAttribute.replace(/_/g, '([_ -]?)+'), "gi");
4992          //match the above RegExp variable with the filename
4993          var matches = fName.match(rex);
4994
4995          //If filename of image matches the formatted selected attribute, show that image
4996          if (matches) {
4997            c++;
4998            $(this).show();
4999          }
5000        });
5001
5002        if (!c) { images.hide(); defaultImage.show(); }
5003      }
5004    }
5004 else if($(atcForm +" select.imgflip").length == 0) {
5005      // console.log('SHOW DEFAULT IMAGE(S) FOR NON-SWAPPING ATTRIBUTES');
5006
5007      // This used to show only the defaultImage.  Because there is no imgflip class, it means there's no
5008      // flippable attribute, so we should just show all images instead of the default/first image.
5009      images.show();
5010    }
5011  }
5012}
5013
5014// Fixes indexOf for IE
5015if (!Array.indexOf) {
5016  Array.prototype.indexOf = function(obj) {
5017	  for (var i = 0; i < this.length; i++) {
5018	    if (this[i] == obj) {
5019	      return i;
5020      }
5021    }
5022    return -1;
5023	};
5024}
5025
5026function availableAttributeData(all_selected, tcOptions, tcVariants, forceDefaultImages) {
5027  data = {};
5028  data.numinstock = 0;
5029  data.numoutofstock = 0;
5030  data.pricehigh = tcVariants.default_item.price;
5031  data.pricelow = tcVariants.default_item.price;
5032  data.default_sku = tcVariants.default_item.sku;
5033  data.sku = tcVariants.default_item.sku;
5034  data.oos = true;
5035  data.img_swap = tcVariants.default_item.img_swap;
5036  data.display_pricehigh = tcVariants.default_item.display_price;
5037  data.display_pricelow = tcVariants.default_item.display_price;
5038  data.prices = {};
5039  data.stocks = {};
5040  data.images = {};
5041  data.showoptions = {}; //Given the existing filters, how many SKUs are sellable for each option (value > 0 means show the option in the dropdown)
5042
5043  // Get all possible source_ids
5044  var possibleStocks = [];
5045  for (var opt in tcOptions['source_ids']) {
5046    for (var sid in tcOptions['source_ids'][opt]) {
5047      if (possibleStocks.indexOf(sid) === -1) {
5048        possibleStocks.push(sid);
5049      }
5050    }
5051  }
5052
5053  /*
5054   *   User has selected an option
5055   */
5056  if(Object.keys(all_selected).length > 0) {
5057    data.pricehigh = 0;
5058    data.pricelow = 0;
5059
5060    var use_default = true;
5061    // If the selected option appears anywhere in the available options source IDs, don't use default
5062    for (var sel in all_selected) {
5063      for (var opt in tcOptions['source_ids'][sel]) {
5064        use_default = false;
5065      }
5066    }
5067
5068    if(use_default) {
5069      // If there's an img_swap set, add it to the available images
5070      // If no images are added, the swapper will use the default regex by color method
5071      if(tcVariants.default_item.img_swap) {
5072        var img_arr = tcVariants.default_item.img_swap;
5073        img_arr = img_arr.split(",");
5074        for (var img in img_arr) {
5075          data.images[img_arr[img]] = img_arr[img];
5076        }
5077      }
5078
5079      if(tcVariants.default_item.oos) data.numoutofstock++;
5080      else  data.numinstock++;
5081    } else { // !use_default
5082
5083      // Reduce possible source_ids down to only those with all selected options
5084      for (var sel in all_selected) {
5085        var optStocks = []
5086        for (var sid in tcOptions['source_ids'][sel]) {
5087          if (optStocks.indexOf(sid) === -1) {
5088            optStocks.push(sid);
5089          }
5090        }
5091        possibleStocks = array_intersect(possibleStocks, optStocks);
5092      }
5093      // Here, possibleStocks contains a list of all possible source_ids, given the selected options
5094
5095
5096      // Loop through all possible stocks and apply what is found to the data object
5097      for (i = 0; i < possibleStocks.length; i++) {
5098        var source_id = possibleStocks[i];
5099        if(!tcVariants[source_id].oos) {
5100          for (var comb in tcVariants[source_id].combination) {
5101            k=tcVariants[source_id].combination[comb];
5102            if(typeof k !== 'undefined') { // Ignore broken attributes from BL
5103              p = parseFloat(tcVariants[source_id].price);
5104              data.sku = tcVariants[source_id].sku;
5105              data.oos = tcVariants[source_id].oos;
5106              data.prices[p] = p;
5107              if(!data.oos && (!data.pricehigh || p>data.pricehigh)) { data.pricehigh=p; data.display_pricehigh = tcVariants[source_id].display_price; }
5108              if(!data.oos && (!data.pricelow  || p<data.pricelow))  { data.pricelow=p;  data.display_pricelow  = tcVariants[source_id].display_price; }
5109
5110              s = parseInt(tcVariants[source_id].stock);
5111              data.stocks[tcVariants[source_id].sku] = s;
5112
5113              // If there's an img_swap set, add it to the available images
5114              // If no images are added, the swapper will use the default regex by color method
5115              if(forceDefaultImages && tcVariants.default_item.img_swap) {
5116                var img_arr = tcVariants.default_item.img_swap;
5117                img_arr = img_arr.split(",");
5118                for (var img in img_arr) {
5119                  data.images[img_arr[img]] = img_arr[img];
5120                }
5121              }
5122              // If there's an img_swap set, add it to the available images
5123              // If no images are added, the swapper will use the default regex by color method
5124              else if(tcVariants[source_id].img_swap) {
5125                var img_arr = tcVariants[source_id].img_swap;
5126                img_arr = img_arr.split(",");
5127                for (var img in img_arr) {
5128                  data.images[img_arr[img]] = img_arr[img];
5129                }
5130              }
5131
5132              if(!data.showoptions[opt] && typeof data.showoptions[opt] === 'undefined') data.showoptions[opt] = 0;
5133              if(s>0) data.showoptions[opt]++;
5134            }
5135          }
5136        }
5137      }
5138    }
5139  } else { // No attributes are selected yet
5140
5141    // If there's an img_swap set, add it to the available images
5142    // If no images are added, the swapper will use the default regex by color method
5143    if(tcVariants.default_item.img_swap) {
5144      var img_arr = tcVariants.default_item.img_swap;
5145      img_arr = img_arr.split(",");
5146      for (var img in img_arr) {
5147        data.images[img_arr[img]] = img_arr[img];
5148      }
5149    }
5150
5151    // Loop through all possible stocks and apply what is found to the data object
5152    for (i = 0; i < possibleStocks.length; i++) {
5153      var source_id = possibleStocks[i];
5154
5155      if(!tcVariants[source_id].oos) { // Skip out of stock variants
5156        p = parseFloat(tcVariants[source_id].price);
5157        data.oos = tcVariants[source_id].oos;
5158        data.prices[p] = p;
5159        if(!data.oos && (!data.pricehigh || p>data.pricehigh)) { data.pricehigh=p; data.display_pricehigh = tcVariants[source_id].display_price; }
5160        if(!data.oos && (!data.pricelow  || p<data.pricelow))  { data.pricelow=p;  data.display_pricelow  = tcVariants[source_id].display_price; }
5161
5162        s = parseInt(tcVariants[source_id].stock);
5163        data.stocks[tcVariants[source_id].sku] = s;
5164        // Don't set data.images here, so we can use the regex method
5165        data.showoptions[opt]=1;
5166      }
5167    }
5168  }
5169
5170  for (var s in data.stocks) {
5171    if(data.stocks[s]>0) data.numinstock++;
5172    else data.numoutofstock++;
5173  }
5174
5175  if(data.numinstock > 0) data.addtocart = true;
5176  else data.addtocart = false;
5177
5178  return data;
5179}
5180
5181function is_numeric(input){
5182  return typeof(input)=='number';
5183}
5184
5185function valueIn(val, obj) {
5186  for(var prop in obj) {
5187    if(obj.hasOwnProperty(prop) && obj[prop] === val) {
5188      return true;
5189    }
5190  }
5191  return false;
5192}
5193
5194/**
5195 * If value is found anywhere in object, value is returned back, else false
5196 * @param object an n-dimentional object of values or nested objects
5197 * @param value a plain value to search for - numeric or string
5198 * @returns boolean
5199 */
5200function objectSearch(object, value) {
5201  if(typeof object == 'object') {
5202    for(var o in object) {
5203      var retval = objectSearch(object[o], value);
5204      if(retval) return retval;
5205    }
5206  }
5207  if (value == object) {
5208    return object;
5209  }
5210  return false;
5211}
5212
5213function allIn(needles, haystack, selected_option_id) {
5214  // nothing selected
5215  if(needles.length === 0) return true;
5216
5217  var needle_count = needles.filter(x=>1).length;
5218  var success = false;
5219
5220  // compare each needle to each stocks option ids
5221  for (const stock_option_ids in haystack) {
5222    // count each matching needle(selected option_id)
5223    var option_match_count = 0;
5224    for(const needle in needles){
5225      if (
5226        Object.values(haystack[stock_option_ids]).indexOf(needles[needle]) > -1
5227        && Object.values(haystack[stock_option_ids]).indexOf(selected_option_id) > -1
5228        ) {
5229        // the stock ids contains both the selected option id and
5230        // the option id we are checking, so we have 1 match
5231         option_match_count++;
5232      }
5233    }
5234    // if there is enough needles that match the amount of active select list
5235    // pass it as a selected option in the select list
5236    if(option_match_count >= needle_count){
5237      success = true;
5238    }
5239  }
5240
5241  return success;
5242}
5243
5244const array_intersect = (a1, a2) => {
5245  let map = new Map();
5246  let result = []
5247  for (let i of a1) {
5248    if (!map.has(i)) map.set(i, true);
5249  }
5250  for (let i of a2) {
5251    if (map.has(i)) result.push(i)
5252  }
5253  return result;
5254}
5255;
5256
5257Drupal.googleanalytics = {};
5258
5259$(document).ready(function() {
5260
5261  // Attach mousedown, keyup, touchstart events to document only and catch
5262  // clicks on all elements.
5263  $(document.body).bind("mousedown keyup touchstart", function(event) {
5264
5265    // Catch only the first parent link of a clicked element.
5266    $(event.target).parents("a:first,area:first").andSelf().filter("a,area").each(function() {
5267
5268      // Is the clicked URL internal?
5269      if (Drupal.googleanalytics.isInternal(this.href)) {
5270        // Skip 'click' tracking, if custom tracking events are bound.
5271        if ($(this).is('.colorbox')) {
5272          // Do nothing here. The custom event will handle all tracking.
5273          //console.info("Click on .colorbox item has been detected.");
5274        }
5275        // Is download tracking activated and the file extension configured for download tracking?
5276        else if (Drupal.settings.googleanalytics.trackDownload && Drupal.googleanalytics.isDownload(this.href)) {
5277          // Download link clicked.
5278          ga("send", "event", "Downloads", Drupal.googleanalytics.getDownloadExtension(this.href).toUpperCase(), Drupal.googleanalytics.getPageUrl(this.href));
5279        }
5280        else if (Drupal.googleanalytics.isInternalSpecial(this.href)) {
5281          // Keep the internal URL for Google Analytics website overlay intact.
5282          ga("send", "pageview", { "page": Drupal.googleanalytics.getPageUrl(this.href) });
5283        }
5284      }
5285      else {
5286        if (Drupal.settings.googleanalytics.trackMailto && $(this).is("a[href^='mailto:'],area[href^='mailto:']")) {
5287          // Mailto link clicked.
5288          ga("send", "event", "Mails", "Click", this.href.substring(7));
5289        }
5290        else if (Drupal.settings.googleanalytics.trackOutbound && this.href.match(/^\w+:\/\//i)) {
5291          if (Drupal.settings.googleanalytics.trackDomainMode != 2 || (Drupal.settings.googleanalytics.trackDomainMode == 2 && !Drupal.googleanalytics.isCrossDomain(this.hostname, Drupal.settings.googleanalytics.trackCrossDomains))) {
5292            // External link clicked / No top-level cross domain clicked.
5293            ga("send", "event", "Outbound links", "Click", this.href);
5294          }
5295        }
5296      }
5297    });
5298  });
5299
5300  // Track hash changes as unique pageviews, if this option has been enabled.
5301  if (Drupal.settings.googleanalytics.trackUrlFragments) {
5302    window.onhashchange = function() {
5303      ga('send', 'pageview', location.pathname + location.search + location.hash);
5304    }
5305  }
5306
5307  // Colorbox: This event triggers when the transition has completed and the
5308  // newly loaded content has been revealed.
5309  $(document).bind("cbox_complete", function () {
5310    var href = $.colorbox.element().attr("href");
5311    if (href) {
5312      ga("send", "pageview", { "page": Drupal.googleanalytics.getPageUrl(href) });
5313    }
5314  });
5315
5316});
5317
5318/**
5319 * Check whether the hostname is part of the cross domains or not.
5320 *
5321 * @param string hostname
5322 *   The hostname of the clicked URL.
5323 * @param array crossDomains
5324 *   All cross domain hostnames as JS array.
5325 *
5326 * @return boolean
5327 */
5328Drupal.googleanalytics.isCrossDomain = function (hostname, crossDomains) {
5329  /**
5330   * jQuery < 1.6.3 bug: $.inArray crushes IE6 and Chrome if second argument is
5331   * `null` or `undefined`, http://bugs.jquery.com/ticket/10076,
5332   * https://github.com/jquery/jquery/commit/a839af034db2bd934e4d4fa6758a3fed8de74174
5333   *
5334   * @todo: Remove/Refactor in D8
5335   */
5336  if (!crossDomains) {
5337    return false;
5338  }
5339  else {
5340    return $.inArray(hostname, crossDomains) > -1 ? true : false;
5341  }
5342};
5343
5344/**
5345 * Check whether this is a download URL or not.
5346 *
5347 * @param string url
5348 *   The web url to check.
5349 *
5350 * @return boolean
5351 */
5352Drupal.googleanalytics.isDownload = function (url) {
5353  var isDownload = new RegExp("\\.(" + Drupal.settings.googleanalytics.trackDownloadExtensions + ")([\?#].*)?$", "i");
5354  return isDownload.test(url);
5355};
5356
5357/**
5358 * Check whether this is an absolute internal URL or not.
5359 *
5360 * @param string url
5361 *   The web url to check.
5362 *
5363 * @return boolean
5364 */
5365Drupal.googleanalytics.isInternal = function (url) {
5366  var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
5367  return isInternal.test(url);
5368};
5369
5370/**
5371 * Check whether this is a special URL or not.
5372 *
5373 * URL types:
5374 *  - gotwo.module /go/* links.
5375 *
5376 * @param string url
5377 *   The web url to check.
5378 *
5379 * @return boolean
5380 */
5381Drupal.googleanalytics.isInternalSpecial = function (url) {
5382  var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
5383  return isInternalSpecial.test(url);
5384};
5385
5386/**
5387 * Extract the relative internal URL from an absolute internal URL.
5388 *
5389 * Examples:
5390 * - http://mydomain.com/node/1 -> /node/1
5391 * - http://example.com/foo/bar -> http://example.com/foo/bar
5392 *
5393 * @param string url
5394 *   The web url to check.
5395 *
5396 * @return string
5397 *   Internal website URL
5398 */
5399Drupal.googleanalytics.getPageUrl = function (url) {
5400  var extractInternalUrl = new RegExp("^(https?):\/\/" + window.location.host, "i");
5401  return url.replace(extractInternalUrl, '');
5402};
5403
5404/**
5405 * Extract the download file extension from the URL.
5406 *
5407 * @param string url
5408 *   The web url to check.
5409 *
5410 * @return string
5411 *   The file extension of the passed url. e.g. "zip", "txt"
5412 */
5413Drupal.googleanalytics.getDownloadExtension = function (url) {
5414  var extractDownloadextension = new RegExp("\\.(" + Drupal.settings.googleanalytics.trackDownloadExtensions + ")([\?#].*)?$", "i");
5415  var extension = extractDownloadextension.exec(url);
5416  return (extension === null) ? '' : extension[1];
5417};
5418;
5419/*!
5420 * Masonry PACKAGED v3.3.2
5421 * Cascading grid layout library
5422 * http://masonry.desandro.com
5423 * MIT License
5424 * by David DeSandro
5425 */
5426
5427!function(a){function b(){}function c(a){function c(b){b.prototype.option||(b.prototype.option=function(b){a.isPlainObject(b)&&(this.options=a.extend(!0,this.options,b))})}function e(b,c){a.fn[b]=function(e){if("string"==typeof e){for(var g=d.call(arguments,1),h=0,i=this.length;i>h;h++){var j=this[h],k=a.data(j,b);if(k)if(a.isFunction(k[e])&&"_"!==e.charAt(0)){var l=k[e].apply(k,g);if(void 0!==l)return l}else f("no such method '"+e+"' for "+b+" instance");else f("cannot call methods on "+b+" prior to initialization; attempted to call '"+e+"'")}return this}return this.each(function(){var d=a.data(this,b);d?(d.option(e),d._init()):(d=new c(this,e),a.data(this,b,d))})}}if(a){var f="undefined"==typeof console?b:function(a){console.error(a)};return a.bridget=function(a,b){c(b),e(a,b)},a.bridget}}var d=Array.prototype.slice;"function"==typeof define&&define.amd?define("jquery-bridget/jquery.bridget",["jquery"],c):c("object"==typeof exports?require("jquery"):a.jQuery)}(window),function(a){function b(b){var c=a.event;return c.target=c.target||c.srcElement||b,c}var c=document.documentElement,d=function(){};c.addEventListener?d=function(a,b,c){a.addEventListener(b,c,!1)}:c.attachEvent&&(d=function(a,c,d){a[c+d]=d.handleEvent?function(){var c=b(a);d.handleEvent.call(d,c)}:function(){var c=b(a);d.call(a,c)},a.attachEvent("on"+c,a[c+d])});var e=function(){};c.removeEventListener?e=function(a,b,c){a.removeEventListener(b,c,!1)}:c.detachEvent&&(e=function(a,b,c){a.detachEvent("on"+b,a[b+c]);try{delete a[b+c]}catch(d){a[b+c]=void 0}});var f={bind:d,unbind:e};"function"==typeof define&&define.amd?define("eventie/eventie",f):"object"==typeof exports?module.exports=f:a.eventie=f}(window),function(){function a(){}function b(a,b){for(var c=a.length;c--;)if(a[c].listener===b)return c;return-1}function c(a){return function(){return this[a].apply(this,arguments)}}var d=a.prototype,e=this,f=e.EventEmitter;d.getListeners=function(a){var b,c,d=this._getEvents();if(a instanceof RegExp){b={};for(c in d)d.hasOwnProperty(c)&&a.test(c)&&(b[c]=d[c])}else b=d[a]||(d[a]=[]);return b},d.flattenListeners=function(a){var b,c=[];for(b=0;b<a.length;b+=1)c.push(a[b].listener);return c},d.getListenersAsObject=function(a){var b,c=this.getListeners(a);return c instanceof Array&&(b={},b[a]=c),b||c},d.addListener=function(a,c){var d,e=this.getListenersAsObject(a),f="object"==typeof c;for(d in e)e.hasOwnProperty(d)&&-1===b(e[d],c)&&e[d].push(f?c:{listener:c,once:!1});return this},d.on=c("addListener"),d.addOnceListener=function(a,b){return this.addListener(a,{listener:b,once:!0})},d.once=c("addOnceListener"),d.defineEvent=function(a){return this.getListeners(a),this},d.defineEvents=function(a){for(var b=0;b<a.length;b+=1)this.defineEvent(a[b]);return this},d.removeListener=function(a,c){var d,e,f=this.getListenersAsObject(a);for(e in f)f.hasOwnProperty(e)&&(d=b(f[e],c),-1!==d&&f[e].splice(d,1));return this},d.off=c("removeListener"),d.addListeners=function(a,b){return this.manipulateListeners(!1,a,b)},d.removeListeners=function(a,b){return this.manipulateListeners(!0,a,b)},d.manipulateListeners=function(a,b,c){var d,e,f=a?this.removeListener:this.addListener,g=a?this.removeListeners:this.addListeners;if("object"!=typeof b||b instanceof RegExp)for(d=c.length;d--;)f.call(this,b,c[d]);
5427else for(d in b)b.hasOwnProperty(d)&&(e=b[d])&&("function"==typeof e?f.call(this,d,e):g.call(this,d,e));return this},d.removeEvent=function(a){var b,c=typeof a,d=this._getEvents();if("string"===c)delete d[a];else if(a instanceof RegExp)for(b in d)d.hasOwnProperty(b)&&a.test(b)&&delete d[b];else delete this._events;return this},d.removeAllListeners=c("removeEvent"),d.emitEvent=function(a,b){var c,d,e,f,g=this.getListenersAsObject(a);for(e in g)if(g.hasOwnProperty(e))for(d=g[e].length;d--;)c=g[e][d],c.once===!0&&this.removeListener(a,c.listener),f=c.listener.apply(this,b||[]),f===this._getOnceReturnValue()&&this.removeListener(a,c.listener);return this},d.trigger=c("emitEvent"),d.emit=function(a){var b=Array.prototype.slice.call(arguments,1);return this.emitEvent(a,b)},d.setOnceReturnValue=function(a){return this._onceReturnValue=a,this},d._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},d._getEvents=function(){return this._events||(this._events={})},a.noConflict=function(){return e.EventEmitter=f,a},"function"==typeof define&&define.amd?define("eventEmitter/EventEmitter",[],function(){return a}):"object"==typeof module&&module.exports?module.exports=a:e.EventEmitter=a}.call(this),function(a){function b(a){if(a){if("string"==typeof d[a])return a;a=a.charAt(0).toUpperCase()+a.slice(1);for(var b,e=0,f=c.length;f>e;e++)if(b=c[e]+a,"string"==typeof d[b])return b}}var c="Webkit Moz ms Ms O".split(" "),d=document.documentElement.style;"function"==typeof define&&define.amd?define("get-style-property/get-style-property",[],function(){return b}):"object"==typeof exports?module.exports=b:a.getStyleProperty=b}(window),function(a){function b(a){var b=parseFloat(a),c=-1===a.indexOf("%")&&!isNaN(b);return c&&b}function c(){}function d(){for(var a={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},b=0,c=g.length;c>b;b++){var d=g[b];a[d]=0}return a}function e(c){function e(){if(!m){m=!0;var d=a.getComputedStyle;if(j=function(){var a=d?function(a){return d(a,null)}:function(a){return a.currentStyle};return function(b){var c=a(b);return c||f("Style returned "+c+". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"),c}}(),k=c("boxSizing")){var e=document.createElement("div");e.style.width="200px",e.style.padding="1px 2px 3px 4px",e.style.borderStyle="solid",e.style.borderWidth="1px 2px 3px 4px",e.style[k]="border-box";var g=document.body||document.documentElement;g.appendChild(e);var h=j(e);l=200===b(h.width),g.removeChild(e)}}}function h(a){if(e(),"string"==typeof a&&(a=document.querySelector(a)),a&&"object"==typeof a&&a.nodeType){var c=j(a);if("none"===c.display)return d();var f={};f.width=a.offsetWidth,f.height=a.offsetHeight;for(var h=f.isBorderBox=!(!k||!c[k]||"border-box"!==c[k]),m=0,n=g.length;n>m;m++){var o=g[m],p=c[o];p=i(a,p);var q=parseFloat(p);f[o]=isNaN(q)?0:q}var r=f.paddingLeft+f.paddingRight,s=f.paddingTop+f.paddingBottom,t=f.marginLeft+f.marginRight,u=f.marginTop+f.marginBottom,v=f.borderLeftWidth+f.borderRightWidth,w=f.borderTopWidth+f.borderBottomWidth,x=h&&l,y=b(c.width);y!==!1&&(f.width=y+(x?0:r+v));var z=b(c.height);return z!==!1&&(f.height=z+(x?0:s+w)),f.innerWidth=f.width-(r+v),f.innerHeight=f.height-(s+w),f.outerWidth=f.width+t,f.outerHeight=f.height+u,f}}function i(b,c){if(a.getComputedStyle||-1===c.indexOf("%"))return c;var d=b.style,e=d.left,f=b.runtimeStyle,g=f&&f.left;return g&&(f.left=b.currentStyle.left),d.left=c,c=d.pixelLeft,d.left=e,g&&(f.left=g),c}var j,k,l,m=!1;return h}var f="undefined"==typeof console?c:function(a){console.error(a)},g=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];"function"==typeof define&&define.amd?define("get-size/get-size",["get-style-property/get-style-property"],e):"object"==typeof exports?module.exports=e(require("desandro-get-style-property")):a.getSize=e(a.getStyleProperty)}(window),function(a){function b(a){"function"==typeof a&&(b.isReady?a():g.push(a))}function c(a){var c="readystatechange"===a.type&&"complete"!==f.readyState;b.isReady||c||d()}function d(){b.isReady=!0;for(var a=0,c=g.length;c>a;a++){var d=g[a];d()}}function e(e){return"complete"===f.readyState?d():(e.bind(f,"DOMContentLoaded",c),e.bind(f,"readystatechange",c),e.bind(a,"load",c)
5427),b}var f=a.document,g=[];b.isReady=!1,"function"==typeof define&&define.amd?define("doc-ready/doc-ready",["eventie/eventie"],e):"object"==typeof exports?module.exports=e(require("eventie")):a.docReady=e(a.eventie)}(window),function(a){function b(a,b){return a[g](b)}function c(a){if(!a.parentNode){var b=document.createDocumentFragment();b.appendChild(a)}}function d(a,b){c(a);for(var d=a.parentNode.querySelectorAll(b),e=0,f=d.length;f>e;e++)if(d[e]===a)return!0;return!1}function e(a,d){return c(a),b(a,d)}var f,g=function(){if(a.matches)return"matches";if(a.matchesSelector)return"matchesSelector";for(var b=["webkit","moz","ms","o"],c=0,d=b.length;d>c;c++){var e=b[c],f=e+"MatchesSelector";if(a[f])return f}}();if(g){var h=document.createElement("div"),i=b(h,"div");f=i?b:e}else f=d;"function"==typeof define&&define.amd?define("matches-selector/matches-selector",[],function(){return f}):"object"==typeof exports?module.exports=f:window.matchesSelector=f}(Element.prototype),function(a,b){"function"==typeof define&&define.amd?define("fizzy-ui-utils/utils",["doc-ready/doc-ready","matches-selector/matches-selector"],function(c,d){return b(a,c,d)}):"object"==typeof exports?module.exports=b(a,require("doc-ready"),require("desandro-matches-selector")):a.fizzyUIUtils=b(a,a.docReady,a.matchesSelector)}(window,function(a,b,c){var d={};d.extend=function(a,b){for(var c in b)a[c]=b[c];return a},d.modulo=function(a,b){return(a%b+b)%b};var e=Object.prototype.toString;d.isArray=function(a){return"[object Array]"==e.call(a)},d.makeArray=function(a){var b=[];if(d.isArray(a))b=a;else if(a&&"number"==typeof a.length)for(var c=0,e=a.length;e>c;c++)b.push(a[c]);else b.push(a);return b},d.indexOf=Array.prototype.indexOf?function(a,b){return a.indexOf(b)}:function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},d.removeFrom=function(a,b){var c=d.indexOf(a,b);-1!=c&&a.splice(c,1)},d.isElement="function"==typeof HTMLElement||"object"==typeof HTMLElement?function(a){return a instanceof HTMLElement}:function(a){return a&&"object"==typeof a&&1==a.nodeType&&"string"==typeof a.nodeName},d.setText=function(){function a(a,c){b=b||(void 0!==document.documentElement.textContent?"textContent":"innerText"),a[b]=c}var b;return a}(),d.getParent=function(a,b){for(;a!=document.body;)if(a=a.parentNode,c(a,b))return a},d.getQueryElement=function(a){return"string"==typeof a?document.querySelector(a):a},d.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},d.filterFindElements=function(a,b){a=d.makeArray(a);for(var e=[],f=0,g=a.length;g>f;f++){var h=a[f];if(d.isElement(h))if(b){c(h,b)&&e.push(h);for(var i=h.querySelectorAll(b),j=0,k=i.length;k>j;j++)e.push(i[j])}else e.push(h)}return e},d.debounceMethod=function(a,b,c){var d=a.prototype[b],e=b+"Timeout";a.prototype[b]=function(){var a=this[e];a&&clearTimeout(a);var b=arguments,f=this;this[e]=setTimeout(function(){d.apply(f,b),delete f[e]},c||100)}},d.toDashed=function(a){return a.replace(/(.)([A-Z])/g,function(a,b,c){return b+"-"+c}).toLowerCase()};var f=a.console;return d.htmlInit=function(c,e){b(function(){for(var b=d.toDashed(e),g=document.querySelectorAll(".js-"+b),h="data-"+b+"-options",i=0,j=g.length;j>i;i++){var k,l=g[i],m=l.getAttribute(h);try{k=m&&JSON.parse(m)}catch(n){f&&f.error("Error parsing "+h+" on "+l.nodeName.toLowerCase()+(l.id?"#"+l.id:"")+": "+n);continue}var o=new c(l,k),p=a.jQuery;p&&p.data(l,e,o)}})},d}),function(a,b){"function"==typeof define&&define.amd?define("outlayer/item",["eventEmitter/EventEmitter","get-size/get-size","get-style-property/get-style-property","fizzy-ui-utils/utils"],function(c,d,e,f){return b(a,c,d,e,f)}):"object"==typeof exports?module.exports=b(a,require("wolfy87-eventemitter"),require("get-size"),require("desandro-get-style-property"),require("fizzy-ui-utils")):(a.Outlayer={},a.Outlayer.Item=b(a,a.EventEmitter,a.getSize,a.getStyleProperty,a.fizzyUIUtils))}(window,function(a,b,c,d,e){function f(a){for(var b in a)return!1;return b=null,!0}function g(a,b){a&&(this.element=a,this.layout=b,this.position={x:0,y:0},this._create())}function h(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}var i=a.getComputedStyle,j=i?function(a){return i(a,null)}:function(a){return a.currentStyle},k=d("transition"),l=d("transform"),m=k&&l,n=!!d("perspective"),o={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend",transition:"transitionend"}[k],p=["transform","transition","transitionDuration","transitionProperty"],q=function(){for(var a={},b=0,c=p.length;c>b;b++){var e=p[b],f=d(e);f&&f!==e&&(a[e]=f)}return a}();e.extend(g.prototype,b.prototype),g.prototype._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},g.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},g.prototype.getSize=function(){this.size=c(this.element)},g.prototype.css=function(a){var b=this.element.style;for(var c in a){var d=q[c]||c;b[d]=a[c]}},g.prototype.getPosition=function(){var a=j(this.element),b=this.layout.options,c=b.isOriginLeft,d=b.isOriginTop,e=a[c?"left":"right"],f=a[d?"top":"bottom"],g=this.layout.size,h=-1!=e.indexOf("%")?parseFloat(e)/100*g.width:parseInt(e,10),i=-1!=f.indexOf("%")?parseFloat(f)/100*g.height:parseInt(f,10);h=isNaN(h)?0:h,i=isNaN(i)?0:i,h-=c?g.paddingLeft:g.paddingRight,i-=d?g.paddingTop:g.paddingBottom,this.position.x=h,this.position.y=i},g.prototype.layoutPosition=function(){var a=this.layout.size,b=this.layout.options,c={},d=b.isOriginLeft?"paddingLeft":"paddingRight",e=b.isOriginLeft?"left"
5427:"right",f=b.isOriginLeft?"right":"left",g=this.position.x+a[d];c[e]=this.getXValue(g),c[f]="";var h=b.isOriginTop?"paddingTop":"paddingBottom",i=b.isOriginTop?"top":"bottom",j=b.isOriginTop?"bottom":"top",k=this.position.y+a[h];c[i]=this.getYValue(k),c[j]="",this.css(c),this.emitEvent("layout",[this])},g.prototype.getXValue=function(a){var b=this.layout.options;return b.percentPosition&&!b.isHorizontal?a/this.layout.size.width*100+"%":a+"px"},g.prototype.getYValue=function(a){var b=this.layout.options;return b.percentPosition&&b.isHorizontal?a/this.layout.size.height*100+"%":a+"px"},g.prototype._transitionTo=function(a,b){this.getPosition();var c=this.position.x,d=this.position.y,e=parseInt(a,10),f=parseInt(b,10),g=e===this.position.x&&f===this.position.y;if(this.setPosition(a,b),g&&!this.isTransitioning)return void this.layoutPosition();var h=a-c,i=b-d,j={};j.transform=this.getTranslate(h,i),this.transition({to:j,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},g.prototype.getTranslate=function(a,b){var c=this.layout.options;return a=c.isOriginLeft?a:-a,b=c.isOriginTop?b:-b,n?"translate3d("+a+"px, "+b+"px, 0)":"translate("+a+"px, "+b+"px)"},g.prototype.goTo=function(a,b){this.setPosition(a,b),this.layoutPosition()},g.prototype.moveTo=m?g.prototype._transitionTo:g.prototype.goTo,g.prototype.setPosition=function(a,b){this.position.x=parseInt(a,10),this.position.y=parseInt(b,10)},g.prototype._nonTransition=function(a){this.css(a.to),a.isCleaning&&this._removeStyles(a.to);for(var b in a.onTransitionEnd)a.onTransitionEnd[b].call(this)},g.prototype._transition=function(a){if(!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(a);var b=this._transn;for(var c in a.onTransitionEnd)b.onEnd[c]=a.onTransitionEnd[c];for(c in a.to)b.ingProperties[c]=!0,a.isCleaning&&(b.clean[c]=!0);if(a.from){this.css(a.from);var d=this.element.offsetHeight;d=null}this.enableTransition(a.to),this.css(a.to),this.isTransitioning=!0};var r="opacity,"+h(q.transform||"transform");g.prototype.enableTransition=function(){this.isTransitioning||(this.css({transitionProperty:r,transitionDuration:this.layout.options.transitionDuration}),this.element.addEventListener(o,this,!1))},g.prototype.transition=g.prototype[k?"_transition":"_nonTransition"],g.prototype.onwebkitTransitionEnd=function(a){this.ontransitionend(a)},g.prototype.onotransitionend=function(a){this.ontransitionend(a)};var s={"-webkit-transform":"transform","-moz-transform":"transform","-o-transform":"transform"};g.prototype.ontransitionend=function(a){if(a.target===this.element){var b=this._transn,c=s[a.propertyName]||a.propertyName;if(delete b.ingProperties[c],f(b.ingProperties)&&this.disableTransition(),c in b.clean&&(this.element.style[a.propertyName]="",delete b.clean[c]),c in b.onEnd){var d=b.onEnd[c];d.call(this),delete b.onEnd[c]}this.emitEvent("transitionEnd",[this])}},g.prototype.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(o,this,!1),this.isTransitioning=!1},g.prototype._removeStyles=function(a){var b={};for(var c in a)b[c]="";this.css(b)};var t={transitionProperty:"",transitionDuration:""};return g.prototype.removeTransitionStyles=function(){this.css(t)},g.prototype.removeElem=function(){this.element.parentNode.removeChild(this.element),this.css({display:""}),this.emitEvent("remove",[this])},g.prototype.remove=function(){if(!k||!parseFloat(this.layout.options.transitionDuration))return void this.removeElem();var a=this;this.once("transitionEnd",function(){a.removeElem()}),this.hide()},g.prototype.reveal=function(){delete this.isHidden,this.css({display:""});var a=this.layout.options,b={},c=this.getHideRevealTransitionEndProperty("visibleStyle");b[c]=this.onRevealTransitionEnd,this.transition({from:a.hiddenStyle,to:a.visibleStyle,isCleaning:!0,onTransitionEnd:b})},g.prototype.onRevealTransitionEnd=function(){this.isHidden||this.emitEvent("reveal")},g.prototype.getHideRevealTransitionEndProperty=function(a){var b=this.layout.options[a];if(b.opacity)return"opacity";for(var c in b)return c},g.prototype.hide=function(){this.isHidden=!0,this.css({display:""});var a=this.layout.options,b={}
5427,c=this.getHideRevealTransitionEndProperty("hiddenStyle");b[c]=this.onHideTransitionEnd,this.transition({from:a.visibleStyle,to:a.hiddenStyle,isCleaning:!0,onTransitionEnd:b})},g.prototype.onHideTransitionEnd=function(){this.isHidden&&(this.css({display:"none"}),this.emitEvent("hide"))},g.prototype.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},g}),function(a,b){"function"==typeof define&&define.amd?define("outlayer/outlayer",["eventie/eventie","eventEmitter/EventEmitter","get-size/get-size","fizzy-ui-utils/utils","./item"],function(c,d,e,f,g){return b(a,c,d,e,f,g)}):"object"==typeof exports?module.exports=b(a,require("eventie"),require("wolfy87-eventemitter"),require("get-size"),require("fizzy-ui-utils"),require("./item")):a.Outlayer=b(a,a.eventie,a.EventEmitter,a.getSize,a.fizzyUIUtils,a.Outlayer.Item)}(window,function(a,b,c,d,e,f){function g(a,b){var c=e.getQueryElement(a);if(!c)return void(h&&h.error("Bad element for "+this.constructor.namespace+": "+(c||a)));this.element=c,i&&(this.$element=i(this.element)),this.options=e.extend({},this.constructor.defaults),this.option(b);var d=++k;this.element.outlayerGUID=d,l[d]=this,this._create(),this.options.isInitLayout&&this.layout()}var h=a.console,i=a.jQuery,j=function(){},k=0,l={};return g.namespace="outlayer",g.Item=f,g.defaults={containerStyle:{position:"relative"},isInitLayout:!0,isOriginLeft:!0,isOriginTop:!0,isResizeBound:!0,isResizingContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}},e.extend(g.prototype,c.prototype),g.prototype.option=function(a){e.extend(this.options,a)},g.prototype._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),e.extend(this.element.style,this.options.containerStyle),this.options.isResizeBound&&this.bindResize()},g.prototype.reloadItems=function(){this.items=this._itemize(this.element.children)},g.prototype._itemize=function(a){for(var b=this._filterFindItemElements(a),c=this.constructor.Item,d=[],e=0,f=b.length;f>e;e++){var g=b[e],h=new c(g,this);d.push(h)}return d},g.prototype._filterFindItemElements=function(a){return e.filterFindElements(a,this.options.itemSelector)},g.prototype.getItemElements=function(){for(var a=[],b=0,c=this.items.length;c>b;b++)a.push(this.items[b].element);return a},g.prototype.layout=function(){this._resetLayout(),this._manageStamps();var a=void 0!==this.options.isLayoutInstant?this.options.isLayoutInstant:!this._isLayoutInited;this.layoutItems(this.items,a),this._isLayoutInited=!0},g.prototype._init=g.prototype.layout,g.prototype._resetLayout=function(){this.getSize()},g.prototype.getSize=function(){this.size=d(this.element)},g.prototype._getMeasurement=function(a,b){var c,f=this.options[a];f?("string"==typeof f?c=this.element.querySelector(f):e.isElement(f)&&(c=f),this[a]=c?d(c)[b]:f):this[a]=0},g.prototype.layoutItems=function(a,b){a=this._getItemsForLayout(a),this._layoutItems(a,b),this._postLayout()},g.prototype._getItemsForLayout=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];e.isIgnored||b.push(e)}return b},g.prototype._layoutItems=function(a,b){if(this._emitCompleteOnItems("layout",a),a&&a.length){for(var c=[],d=0,e=a.length;e>d;d++){var f=a[d],g=this._getItemLayoutPosition(f);g.item=f,g.isInstant=b||f.isLayoutInstant,c.push(g)}this._processLayoutQueue(c)}},g.prototype._getItemLayoutPosition=function(){return{x:0,y:0}},g.prototype._processLayoutQueue=function(a){for(var b=0,c=a.length;c>b;b++){var d=a[b];this._positionItem(d.item,d.x,d.y,d.isInstant)}},g.prototype._positionItem=function(a,b,c,d){d?a.goTo(b,c):a.moveTo(b,c)},g.prototype._postLayout=function(){this.resizeContainer()},g.prototype.resizeContainer=function(){if(this.options.isResizingContainer){var a=this._getContainerSize();a&&(this._setContainerMeasure(a.width,!0),this._setContainerMeasure(a.height,!1))}},g.prototype._getContainerSize=j,g.prototype._setContainerMeasure=function(a,b){if(void 0!==a){var c=this.size;c.isBorderBox&&(a+=b?c.paddingLeft+c.paddingRight+c.borderLeftWidth+c.borderRightWidth:c.paddingBottom+c.paddingTop+c.borderTopWidth+c.borderBottomWidth),a=Math.max(a,0),this.element.style[b?"width":"height"]=a+"px"}},g.prototype._emitCompleteOnItems=function(a,b){function c(){e.dispatchEvent(a+"Complete",null,[b])}function d(){g++,g===f&&c()}var e=this,f=b.length;if(!b||!f)return void c();for(var g=0,h=0,i=b.length;i>h;h++){var j=b[h];j.once(a,d)}},g.prototype.dispatchEvent=function(a,b,c){var d=b?[b].concat(c):c;if(this.emitEvent(a,d),i)if(this.$element=this.$element||i(this.element),b){var e=i.Event(b);e.type=a,this.$element.trigger(e,c)}else this.$element.trigger(a,c)},g.prototype.ignore=function(a){var b=this.getItem(a);b&&(b.isIgnored=!0)},g.prototype.unignore=function(a){var b=this.getItem(a);b&&delete b.isIgnored}
5427,g.prototype.stamp=function(a){if(a=this._find(a)){this.stamps=this.stamps.concat(a);for(var b=0,c=a.length;c>b;b++){var d=a[b];this.ignore(d)}}},g.prototype.unstamp=function(a){if(a=this._find(a))for(var b=0,c=a.length;c>b;b++){var d=a[b];e.removeFrom(this.stamps,d),this.unignore(d)}},g.prototype._find=function(a){return a?("string"==typeof a&&(a=this.element.querySelectorAll(a)),a=e.makeArray(a)):void 0},g.prototype._manageStamps=function(){if(this.stamps&&this.stamps.length){this._getBoundingRect();for(var a=0,b=this.stamps.length;b>a;a++){var c=this.stamps[a];this._manageStamp(c)}}},g.prototype._getBoundingRect=function(){var a=this.element.getBoundingClientRect(),b=this.size;this._boundingRect={left:a.left+b.paddingLeft+b.borderLeftWidth,top:a.top+b.paddingTop+b.borderTopWidth,right:a.right-(b.paddingRight+b.borderRightWidth),bottom:a.bottom-(b.paddingBottom+b.borderBottomWidth)}},g.prototype._manageStamp=j,g.prototype._getElementOffset=function(a){var b=a.getBoundingClientRect(),c=this._boundingRect,e=d(a),f={left:b.left-c.left-e.marginLeft,top:b.top-c.top-e.marginTop,right:c.right-b.right-e.marginRight,bottom:c.bottom-b.bottom-e.marginBottom};return f},g.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},g.prototype.bindResize=function(){this.isResizeBound||(b.bind(a,"resize",this),this.isResizeBound=!0)},g.prototype.unbindResize=function(){this.isResizeBound&&b.unbind(a,"resize",this),this.isResizeBound=!1},g.prototype.onresize=function(){function a(){b.resize(),delete b.resizeTimeout}this.resizeTimeout&&clearTimeout(this.resizeTimeout);var b=this;this.resizeTimeout=setTimeout(a,100)},g.prototype.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},g.prototype.needsResizeLayout=function(){var a=d(this.element),b=this.size&&a;return b&&a.innerWidth!==this.size.innerWidth},g.prototype.addItems=function(a){var b=this._itemize(a);return b.length&&(this.items=this.items.concat(b)),b},g.prototype.appended=function(a){var b=this.addItems(a);b.length&&(this.layoutItems(b,!0),this.reveal(b))},g.prototype.prepended=function(a){var b=this._itemize(a);if(b.length){var c=this.items.slice(0);this.items=b.concat(c),this._resetLayout(),this._manageStamps(),this.layoutItems(b,!0),this.reveal(b),this.layoutItems(c)}},g.prototype.reveal=function(a){this._emitCompleteOnItems("reveal",a);for(var b=a&&a.length,c=0;b&&b>c;c++){var d=a[c];d.reveal()}},g.prototype.hide=function(a){this._emitCompleteOnItems("hide",a);for(var b=a&&a.length,c=0;b&&b>c;c++){var d=a[c];d.hide()}},g.prototype.revealItemElements=function(a){var b=this.getItems(a);this.reveal(b)},g.prototype.hideItemElements=function(a){var b=this.getItems(a);this.hide(b)},g.prototype.getItem=function(a){for(var b=0,c=this.items.length;c>b;b++){var d=this.items[b];if(d.element===a)return d}},g.prototype.getItems=function(a){a=e.makeArray(a);for(var b=[],c=0,d=a.length;d>c;c++){var f=a[c],g=this.getItem(f);g&&b.push(g)}return b},g.prototype.remove=function(a){var b=this.getItems(a);if(this._emitCompleteOnItems("remove",b),b&&b.length)for(var c=0,d=b.length;d>c;c++){var f=b[c];f.remove(),e.removeFrom(this.items,f)}},g.prototype.destroy=function(){var a=this.element.style;a.height="",a.position="",a.width="";for(var b=0,c=this.items.length;c>b;b++){var d=this.items[b];d.destroy()}this.unbindResize();var e=this.element.outlayerGUID;delete l[e],delete this.element.outlayerGUID,i&&i.removeData(this.element,this.constructor.namespace)},g.data=function(a){a=e.getQueryElement(a);var b=a&&a.outlayerGUID;return b&&l[b]}
5427,g.create=function(a,b){function c(){g.apply(this,arguments)}return Object.create?c.prototype=Object.create(g.prototype):e.extend(c.prototype,g.prototype),c.prototype.constructor=c,c.defaults=e.extend({},g.defaults),e.extend(c.defaults,b),c.prototype.settings={},c.namespace=a,c.data=g.data,c.Item=function(){f.apply(this,arguments)},c.Item.prototype=new f,e.htmlInit(c,a),i&&i.bridget&&i.bridget(a,c),c},g.Item=f,g}),function(a,b){"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size","fizzy-ui-utils/utils"],b):"object"==typeof exports?module.exports=b(require("outlayer"),require("get-size"),require("fizzy-ui-utils")):a.Masonry=b(a.Outlayer,a.getSize,a.fizzyUIUtils)}(window,function(a,b,c){var d=a.create("masonry");return d.prototype._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns();var a=this.cols;for(this.colYs=[];a--;)this.colYs.push(0);this.maxY=0},d.prototype.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var a=this.items[0],c=a&&a.element;this.columnWidth=c&&b(c).outerWidth||this.containerWidth}var d=this.columnWidth+=this.gutter,e=this.containerWidth+this.gutter,f=e/d,g=d-e%d,h=g&&1>g?"round":"floor";f=Math[h](f),this.cols=Math.max(f,1)},d.prototype.getContainerWidth=function(){var a=this.options.isFitWidth?this.element.parentNode:this.element,c=b(a);this.containerWidth=c&&c.innerWidth},d.prototype._getItemLayoutPosition=function(a){a.getSize();var b=a.size.outerWidth%this.columnWidth,d=b&&1>b?"round":"ceil",e=Math[d](a.size.outerWidth/this.columnWidth);e=Math.min(e,this.cols);for(var f=this._getColGroup(e),g=Math.min.apply(Math,f),h=c.indexOf(f,g),i={x:this.columnWidth*h,y:g},j=g+a.size.outerHeight,k=this.cols+1-f.length,l=0;k>l;l++)this.colYs[h+l]=j;return i},d.prototype._getColGroup=function(a){if(2>a)return this.colYs;for(var b=[],c=this.cols+1-a,d=0;c>d;d++){var e=this.colYs.slice(d,d+a);b[d]=Math.max.apply(Math,e)}return b},d.prototype._manageStamp=function(a){var c=b(a),d=this._getElementOffset(a),e=this.options.isOriginLeft?d.left:d.right,f=e+c.outerWidth,g=Math.floor(e/this.columnWidth);g=Math.max(0,g);var h=Math.floor(f/this.columnWidth);h-=f%this.columnWidth?0:1,h=Math.min(this.cols-1,h);for(var i=(this.options.isOriginTop?d.top:d.bottom)+c.outerHeight,j=g;h>=j;j++)this.colYs[j]=Math.max(i,this.colYs[j])},d.prototype._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var a={height:this.maxY};return this.options.isFitWidth&&(a.width=this._getContainerFitWidth()),a},d.prototype._getContainerFitWidth=function(){for(var a=0,b=this.cols;--b&&0===this.colYs[b];)a++;return(this.cols-a)*this.columnWidth-this.gutter},d.prototype.needsResizeLayout=function(){var a=this.containerWidth;return this.getContainerWidth(),a!==this.containerWidth},d});;
5428$(document).ready(function() {
5429
5430// Lightbox Multi-View   [ -- Dont' forget the CSS and to enable the Lightbox 2 Module!!! -- ]
5431  // These blocks set up a mouseenter event system that replaces the visible detail image with a detail image matching the moused-over thumbnail
5432  // Visible Thumbnails are in  .views-field-field-images-fid-1
5433  // Hidden Details are in      .views-field-field-images-fid
5434  // Visible Detail image is    .views-field-field-images-fid-2
5435  var view_class = '.view-id-lightbox_multi_view';
5436  var visible_thumbs = '.views-field-field-images-fid-1';
5437  var hidden_details = '.views-field-field-images-fid';
5438  var visible_detail = '.views-field-field-images-fid-2';
5439  // Give field-images matching item numbers
5440  $(view_class+' .views-row').each(function() {
5441    var itemid = 0;
5442    var sibling = $(this).find(hidden_details+' .field-item:first-child');
5443    $(this).find(visible_thumbs+' .field-item').each(function() {
5444      $(this).attr('itemid',itemid);
5445      sibling.attr('itemid',itemid).addClass('item-'+itemid);
5446      sibling = sibling.next();
5447      itemid++;
5448    });
5449  });
5450  // Add mouseenter events to each of the thumbnail images
5451  $(view_class+' '+visible_thumbs+' img').each(function (i) {
5452    $(this).bind('mouseenter',function(e){
5453      viewsrow = $(this).parent().parent().parent().parent().parent();
5454      var itemid = $(this).parent().parent().attr('itemid');
5455      var linkobj = $(this).parent();
5456
5457      previewimg = viewsrow.find(hidden_details+' .item-'+itemid+' img').attr('src');
5458      viewsrow.find(visible_detail+' img').attr('src',previewimg);
5459      viewsrow.find(visible_detail+' a').attr('href',linkobj.attr('href'));
5460    });
5461  });
5462
5463});;
5464/*!
5465 * jQuery Cookie Plugin v1.4.1
5466 * https://github.com/carhartl/jquery-cookie
5467 *
5468 * Copyright 2006, 2014 Klaus Hartl
5469 * Released under the MIT license
5470 */
5471(function (factory) {
5472	if (typeof define === 'function' && define.amd) {
5473		// AMD (Register as an anonymous module)
5474		define(['jquery'], factory);
5475	} else if (typeof exports === 'object') {
5476		// Node/CommonJS
5477		module.exports = factory(require('jquery'));
5478	} else {
5479		// Browser globals
5480		factory(jQuery);
5481	}
5482}(function ($) {
5483
5484	var pluses = /\+/g;
5485
5486	function encode(s) {
5487		return config.raw ? s : encodeURIComponent(s);
5488	}
5489
5490	function decode(s) {
5491		return config.raw ? s : decodeURIComponent(s);
5492	}
5493
5494	function stringifyCookieValue(value) {
5495		return encode(config.json ? JSON.stringify(value) : String(value));
5496	}
5497
5498	function parseCookieValue(s) {
5499		if (s.indexOf('"') === 0) {
5500			// This is a quoted cookie as according to RFC2068, unescape...
5501			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
5502		}
5503
5504		try {
5505			// Replace server-side written pluses with spaces.
5506			// If we can't decode the cookie, ignore it, it's unusable.
5507			// If we can't parse the cookie, ignore it, it's unusable.
5508			s = decodeURIComponent(s.replace(pluses, ' '));
5509			return config.json ? JSON.parse(s) : s;
5510		} catch(e) {}
5511	}
5512
5513	function read(s, converter) {
5514		var value = config.raw ? s : parseCookieValue(s);
5515		return $.isFunction(converter) ? converter(value) : value;
5516	}
5517
5518	var config = $.cookie = function (key, value, options) {
5519
5520		// Write
5521
5522		if (arguments.length > 1 && !$.isFunction(value)) {
5523			options = $.extend({}, config.defaults, options);
5524
5525			if (typeof options.expires === 'number') {
5526				var days = options.expires, t = options.expires = new Date();
5527				t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
5528			}
5529
5530			return (document.cookie = [
5531				encode(key), '=', stringifyCookieValue(value),
5532				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
5533				options.path    ? '; path=' + options.path : '',
5534				options.domain  ? '; domain=' + options.domain : '',
5535				options.secure  ? '; secure' : ''
5536			].join(''));
5537		}
5538
5539		// Read
5540
5541		var result = key ? undefined : {},
5542			// To prevent the for loop in the first place assign an empty array
5543			// in case there are no cookies at all. Also prevents odd result when
5544			// calling $.cookie().
5545			cookies = document.cookie ? document.cookie.split('; ') : [],
5546			i = 0,
5547			l = cookies.length;
5548
5549		for (; i < l; i++) {
5550			var parts = cookies[i].split('='),
5551				name = decode(parts.shift()),
5552				cookie = parts.join('=');
5553
5554			if (key === name) {
5555				// If second argument (value) is a function it's a converter...
5556				result = read(cookie, value);
5557				break;
5558			}
5559
5560			// Prevent storing a cookie that we couldn't decode.
5561			if (!key && (cookie = read(cookie)) !== undefined) {
5562				result[name] = cookie;
5563			}
5564		}
5565
5566		return result;
5567	};
5568
5569	config.defaults = {};
5570
5571	$.removeCookie = function (key, options) {
5572		// Must not alter options, thus extending a fresh object...
5573		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
5574		return !$.cookie(key);
5575	};
5576
5577}));
5578;
5579$(document).ready(function() {
5580
5581    // Copy Wishlist to Clipboard
5582    $('input[name="wid"]').each(function() {
5583        rel_wid = $(this).val();
5584        $('.linkToCopy').val('https://www.semcoop.com/wishlist/' + rel_wid);
5585    });
5586
5587    $('button.copyButton').click(function() {
5588        //console.log($(this).siblings('input.linkToCopy').select())
5589        $(this).siblings('input.linkToCopy').select();
5590        document.execCommand("copy");
5591    });
5592
5593    // Wishlist Quantity Fix - sets Add to Cart to 1 - Disabled by ASP, screwed with the Want Quantity and the Price per Item code below
5594
5595    // $('#uc-wishlist-view-form input:not(:disabled):[id*="qty"]').each(function() {
5596    //     $(this).attr('value', '1');
5597    // });
5598
5599    //Wishlist Price Fix - divide by Cost by Qty
5600    // $('#uc-wishlist-view-form th:contains("Total")').text("Item Cost");
5601    $('#uc-wishlist-view-form th:contains("Total")').text('');
5602
5603    $('#uc-wishlist-view-form input[id*="wantqty"]').each(function() {
5604        $(this).addClass('wantqty');
5605    });
5606
5607    $('#uc-wishlist-view-form td:nth-child(2)').each(function() {
5608        $(this).addClass('titlecell');
5609        titletext = $(this).text().replace('<br>', '')
5610        $(this).text(titletext);
5611    });
5612
5613    $('#uc-wishlist-view-form td:[nowrap*="nowrap"]').each(function() {
5614        rowqty = parseInt($(this).siblings().children().find('.wantqt
5614y').val());
5615        rowcost = parseInt($(this).text().replace('$', ''));
5616        rowtotal = rowcost / rowqty;
5617        rowtotal = ((Math.round(rowtotal * 100) / 100).toFixed(2));
5618        $(this).text('');
5619        $(this).parent().find('.titlecell').append(' - $' + rowtotal);
5620    });
5621
5622    //Make Wishlist qty set to 1 by default, Andrew
5623    if($('#wishlist-form-products').length > 0) {
5624        $('.sticky-table tr').each(function(i) {
5625            $(`#edit-items-${i}-qty`).val(1);
5626        });
5627    }
5628
5629    //set a cookie when wishlist product added to cart - used for reports
5630    $('#wishlist-form-products tr .form-submit').click(function() {
5631        $.cookie('wishlist_product_in_cart', 'Yes', { path: '/cart' });
5632    })
5633
5634    //if statement, if cookie undefined, do nothing, else add text to new text field
5635    if ($.cookie('wishlist_product_in_cart') === undefined) {
5636        $('#edit-panes-extra-information-information-ucxf-wishlist-product-in-cart-wrapper').val("")
5637    } else {
5638        $('#edit-panes-extra-information-information-ucxf-wishlist-product-in-cart-wrapper').val("Wishlist Product on Order")
5639    }
5640
5641
5642
5643    //---End Wishlist Features
5644
5645    //Add Body Class for Ingram Product
5646    if ($('#node-226589,.page-node-226589-edit, .page-node-226589-timber').length > 0) {
5647        $('body').addClass('ingram-product added-by-funcs');
5648    }
5649
5650
5651    //Clone Search on Home Page
5652    $('.front #search').clone().appendTo('#slider');
5653    $('#slider #search label').text("SEARCH OUR STORES");
5654
5655    // Move the Edit tabs up for authenticated on Home Page
5656    $('.front.role-authenticated-user #content-context div.tabs').prependTo('#branding-wrapper');
5657
5658    $('.view-taxonomy-term-semcoop2').addClass('view-taxonomy-term-semcoop');
5659
5660    // Temporary Hide Menu Items
5661    $('#block-tvmenu-0>.content>.menu>li>a:contains("Political Science")').addClass('hide');
5662    $('#block-tvmenu-0>.content>.menu>li>a:contains("Rock")').addClass('hide');
5663
5664    // run preorder message override
5665    semcoopPreorderOverride();
5666
5667    // CART: Re-Order Action Buttons
5668    if ($('body.page-cart').length > 0) {
5669        $('#cart-form-buttons #edit-checkout').prependTo('#cart-form-buttons');
5670        $('#cart-form-buttons #continue-shopping-link').appendTo('#cart-form-buttons');
5671    }
5672
5673    // CATEGORY SIDEBAR/BROWSE OUR SHELVES: Add Divider Classes between Specific
5674    // Categories
5675    $('#block-tvmenu-0 ul.menu.tvmenu a[href="/category/uchicago-faculty-publications"]').parent('li').addClass('divider');
5676    $('#block-tvmenu-0 ul.menu.tvmenu a[href="/category/untranslated"]').parent('li').addClass('divider');
5677    $('#block-tvmenu-0 ul.menu.tvmenu a[href="/category/childrens-books"]').parent('li').addClass('divider');
5678    $('#block-tvmenu-0 ul.menu.tvmenu a[href="/category/gift-cards"]').parent('li').addClass('divider');
5679
5680    // CATEGORY PAGE: Show/Hide Exposed Filters
5681    // Add the button to toggle the filters
5682    $('.page-taxonomy .view-filters').prepend('<a href="#" id="toggleFilters">+ Show Filters</a>');
5683    // Hook into the button click to toggle the filters
5684    $('.page-taxonomy .view-filters #toggleFilters').click(function() {
5685        toggleTaxoFilters();
5686    });
5687    // Toggle the filters automatically if arguments are present
5688    var taxoFiltersValue = false;
5689    $('.page-taxonomy .views-exposed-widgets input[type="text"]').each(function() {
5690        if ($(this).val()) {
5691            taxoFiltersValue = true;
5692        }
5693    });
5694    if (taxoFiltersValue) {
5695        toggleTaxoFilters();
5696    }
5697    // Helper function to toggle the filters
5698    function toggleTaxoFilters() {
5699        $('.page-taxonomy .views-exposed-form .views-exposed-widgets').toggle('slow', function() {
5700            if ($('.page-taxonomy .view-filters #toggleFilters').html().indexOf('+') >= 0) {
5701                $('.page-taxonomy .view-filters #toggleFilters').html('- Hide Filters');
5702            } else {
5703                $('.page-taxonomy .view-filters #toggleFilters').html('+ Show Filters');
5704            }
5705        });
5706    }
5707
5708
5709    // LOGIN PAGE: Update Text / Add Welcome Message
5710    if ($('.page-login').length > 0) {
5711        // Add a welcome message
5712        //$('.page-login #content-content').prepend('<p><br>Welcome to our new site. If you had an account on the previous site, you will need to <a href="/user/register">register</a> or just place an order to create your new account.</p>');
5713        $('.page-login #content-content').prepend('<p><strong>NOTE</strong>: Our website and in-store membership program are separate systems. If you have not yet used the website you will need to <a href="https://www.semcoop.com/user/register" target="_blank"> create an account</a>
5713. We will link your (new) online account to your existing member account on our end</p>');
5714        // Change the Help Text for the username
5715        $('form#user-login #edit-name-wrapper .description').html('Enter your Seminary Co-op Bookstores username or the Email Address associated with your account.');
5716        // Swap out login to checkout message
5717        $('#messages li').each(function() {
5718            if ($(this).html().toLowerCase().indexOf('must login before you can proceed to checkout') >= 0) {
5719                $(this).html('You must log in or create an account in order to proceed to checkout. If you created a web account after 9/1/16, please log in below. If you are new to the Co-op or if you created a web account prior to 9/1/16, please <a href="https://www.semcoop.com/user/register?destination=cart%2Fcheckout">create an an account here</a>.');
5720            }
5721        });
5722    }
5723    // CREATE NEW ACCOUNT: Add a Custom Error Message if the Email Address is
5724    // already in use when creating a new account
5725    if ($('.page-user #main .messages.error a[href*="user/password"]').length > 0) {
5726        $('.page-user #main .messages.error > ul').append('<li>If you had an account on our previous website, we may have already created one for you. Please <a href="/hours-contact-information">Contact Us</a> for more information.</li>');
5727    }
5728
5729    // Rearranges the author field data
5730    $('.field-field-author, .product-author, .author, .authorBox, .recommend-author').each(function() {
5731        author_name = $(this).text().trim();
5732        author_name = author_name.replace('Written by', '');
5733        author_name = author_name.replace('Author:', '').replace(/&nbsp;/gi, '');
5734        var author_first = author_name.substr(author_name.indexOf(',') + 1);
5735        var author_last = author_name.substr(0, author_name.indexOf(',')).replace(/ /g, '');
5736        author_name = author_first + ' ' + author_last;
5737    });
5738
5739    // Disable login form autocomplete if their password was wrong.  They'll have to re-enter it manually or create a new account.
5740    if ($('a:contains(Have you forgotten your password)').length > 0) {
5741        $('#user-login').attr('autocomplete', 'off');
5742        $('#edit-name').attr('autocomplete', 'off');
5743        $('#edit-pass').attr('autocomplete', 'off');
5744    }
5745
5746    // Remove "product image" from alt and tags
5747    // loop through images
5748    $('img').each(function() {
5749        if ($(this).attr('alt') == 'product image') {
5750            $(this).removeAttr('alt');
5751            $(this).removeAttr('title');
5752        }
5753    });
5754
5755    // Wishlist Page: Customize Access Denied Message for Anonymous Users
5756    var pageURL = $(location).attr('href');
5757    if (pageURL.indexOf('wishlist') >= 0) {
5758        var pageTitle = $('#page-title').html();
5759        if (pageTitle.toLowerCase().indexOf('denied') >= 0) {
5760            $('#content-content').html('<p><strong>Please <a href="/user/login">login to your account</a> to manage your wishlist.</strong></p>');
5761        }
5762    }
5763
5764    // Textbook Page: Product Pop-Up
5765    // Override default behavior: selecting the product
5766    // New behavior: go to the product page
5767    $('.chooser-product .timber-details').click(function() {
5768        // Get the link to the product
5769        var productLink = $(this).find('.field-title a').attr('href');
5770        // Go to the product page
5771        window.location.href = productLink;
5772    });
5773
5774
5775    // Correct display of poorly-encoded apostrophes
5776    /*$('h1').each(function() {
5777      $(this).html($(this).html().replace(/&/g, "").replace('&amp;#8217;', "'")).addClass('text-removed-by-funcs');
5778    });*/
5779
5780
5781    //Show domain-editing tools always
5782
5783    $('#edit-domain-site-wrapper').parent().parent().show();
5784
5785    //Link up the H2 block titles on the Front page
5786
5787    $('.front #content-bottom .view-footer a').each(function() {
5788        h2link = $(this).attr('href');
5789        $(this).parent().parent().parent().parent().find('h2').wrap('<a href="' + h2link + '">');
5790    });
5791
5792
5793
5794    //Adds an ID to fieldset on the Register page
5795    $('.page-user-register #edit-profile-member-id').parent().parent().addClass('member-id-fieldset');
5796
5797
5798    //Creates the desired markup in the secondary menu
5799    $('<span class="cart-quantity"></span><a href="/cart">Shopping Cart</a> ').insertAfter('#block-block-17 .secondaryLinks .logout-link');
5800    $('#block-uc_cart-0 .num-items').prependTo('.cart-quantity');
5801
5802    if ($('.num-items').length == 0) {
5803        $('.cart-quantity').html('0');
5804    }
5805
5806
5807    $('#block-uc_cart-0').prependTo('#block-block-17 .secondaryLinks p');
5808
5809    //Adds timberclasses to views-row
5810    $('.view-taxonomy-term-semcoop .views-row .hoverInfo').each(function() {
5811        row_timberclasses = $(this).attr('timberclasses');
5812        $(this).parent().parent().parent().addClass(row_timberclasses);
5813    });
5814
5815    //Removes undesired Written by
5816    $('.page-search .search-results .detail strong').each(function() {
5817        var html = $(this).html();
5818        $(this).html(html.replace('Written by', 'By:'));
5819    });
5820
5821    // Removes undesired New/Used attribute description
5822    $('.attributes .description:contains("New/Used:")').each(function() {
5823        var html = $(this).html();
5824        $(this).html(html.replace('New/Used:', ''));
5825    });
5826
5827    $('.attributes .description:contains(": New")').each(function() {
5828        var html = $(this).html();
5829        $(this).html(html.replace(': New', 'New'));
5830    });
5831
5832    $('.attributes .description:contains(": Used")').each(function() {
5833        var html = $(this).html();
5834        $(this).html(html.replace(': Used', 'Used'));
5835    });
5836
5837    $('.product-description').each(function() {
5838        var html = $(this).html();
5839        $(this).html(html.replace('Timber Condition:', ''));
5840    });
5841
5842    // Header Logo Text: Move the text depending what domain is active
5843    if ($('.domain-57th-street-books').length > 0) {
5844        $('#block-block-11 ul.text_logos li#logo_57th').prependTo($('#block-block-11 ul.text_logos'));
5845    }
5846
5847    //Add some text to Select a Location
5848    $('#block-semcoop_site-semcoop_site_block .content').prepend('<p class="added-by-funcs">Show me books from </p>');
5849
5850    if ($('#block-views-taxonomy_description-block_1 p').length > 0) {
5851        $('body').addClass('has-taxo-description added-by-funcs')
5852    }
5853
5854    // Remove Pager "Next" and "Previous" Text to fix spacing on taxonomy pages
5855    $('.page-taxonomy #main .pager-previous a, .page-taxonomy #main .pager-next a').html('&nbsp;');
5856
5857    // Add favorite genre question to admin page
5858    $("#edit-taxonomy-1-wrapper label").replaceWith("<label>What genres or types of books do you especially enjoy reading? (hold down ctrl to select mulitple options):</label>");
5859
5860    // Move taxonomy terms to bottom of the page to correspond with genre
5861    // question
5862    if ($('.node-type-staff .terms-inline').length > 0) {
5863        $('<div class="field-label>G</div>"').appendTo('.field-field-nightstand');
5864        $('.node .terms-inline').appendTo('.field-field-nightstand');
5865        $("<span class='term-label added-by-funcs'>What genres or types of books do you especially enjoy reading?:</span>").insertBefore(".node .terms-inline"); //Add label to Genre taxonomy terms
5866    }
5867    if ($('.section-event').length > 0) {
5868        $(".term-label").text("View other events in:"); //Add label to Events taxonomy terms
5869    }
5870    // Detects breadcrumbs and adds a "no breadcrumb" class to the body
5871    if ($('.breadcrumb').length == 0) {
5872        $('body').addClass('no-breadcrumb');
5873    }
5874
5875    // To proper case helper function
5876    function toProperCase(str) {
5877        var noCaps = ['of', 'a', 'the', 'and', 'an', 'am', 'or', 'nor', 'but', 'is', 'if', 'then', 'else', 'when', 'at', 'from', 'by', 'on', 'off', 'for', 'in', 'out', 'to', 'into', 'with'];
5878        return str.replace(/\w\S*/g, function(txt, offset) {
5879            if (offset != 0 && noCaps.indexOf(txt.toLowerCase()) != -1) {
5880                return txt.toLowerCase();
5881            }
5882            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
5883        });
5884    }
5885
5886    // Reformat ALL CAPS as mixed case (requires a helper function up above)
5887    $('.front #content-bottom .views-row .field-title').each(function() {
5888        var ele = $(this);
5889        ele.text(toProperCase(ele.text()));
5890    });
5891
5892    // Mobile Menu
5893    // copy main menu and add to mobile menu
5894    $('#block-nice_menus-1 > .content').clone().removeAttr('id').attr('id', 'mobile-menu').removeClass('block-nice_menus-1 block-nice_menus').addClass('edited-by-funcs').prependTo('body');
5895    // remove contextual links
5896    $('#mobile-menu .contextual-links-wrapper').remove();
5897    // add shopping cart link to bottom of main menu
5898    $('#mobile-menu > ul').append('<li><a href="/cart">Shopping Cart</a></li>');
5899    // copy categories menu and push into mobile menu
5900    var categories_menu = $('#block-tvmenu-0 > .content > ul').clone();
5901    categories_menu.prepend('<li><h4 class="categories">Categories</h4></li>');
5902    categories_menu.removeAttr('id').attr('id', 'mobile-menu').removeClass('block-tvmenu').addClass('edited-by-funcs').appendTo('#mobile-menu');
5903    // remove textbook-hide link
5904    $('#mobile-menu .textbooks-hide').remove();
5905    // strip all classes, inline styles, and id from ul's
5906    $('#mobile-menu ul').removeAttr('class').removeAttr('id').removeAttr('style');
5907    // strip all classes, inline styles, and id from li's except "category-hidden"
5908    // and "category-empty"
5909    $('#mobile-menu li').each(function() {
5910        var extraClasses = '';
5911        if ($(this).hasClass('category-empty')) {
5912            extraClasses = extraClasses + ' category-empty';
5913        }
5914        if ($(this).hasClass('category-hidden')) {
5915            extraClasses = extraClasses + ' category-hidden';
5916        }
5917        $(this).removeAttr('class').removeAttr('id').removeAttr('style'); // remove everything
5918        if (extraClasses != '') {
5919            // add classes
5920            $(this).attr('class', extraClasses);
5921        }
5922    });
5923    // remove all "direct" links
5924    $('#mobile-menu a.direct').remove();
5925    // add class to top level ul
5926    $('#mobile-menu ul:first-child').addClass('mobile-menu-top');
5927    // add menu classes to all ul's
5928    $('#mobile-menu ul').addClass('mobile-menu-item');
5929    // add menu button
5930    $('#header').append('<div id="mobile-menu-button-wrapper"><a id="mobile-menu-button"><span>Menu</span></a></div>');
5931    // add classes to menu / add menu title
5932    $('#mobile-menu').addClass('herk-push-menu herk-push-menu-vertical herk-push-menu-left');
5933    $('body').addClass('herk-push-menu-push');
5934    $('#mobile-menu').prepend('<h3>Close Menu</h3>');
5935    // menu button action
5936    $('#mobile-menu-button').click(function() {
5937        toggle_mobile_menu();
5938    });
5939    // close menu action
5940    $('#mobile-menu h3').click(function() {
5941        toggle_mobile_menu();
5942    });
5943    // toggle mobile menu function
5944    function toggle_mobile_menu() {
5945        $('body').toggleClass('noscroll');
5946        $('body').toggleClass('herk-push-menu-push-toright');
5947        $('html').toggleClass('noscroll');
5948        $('#mobile-menu').toggleClass('herk-push-menu-open');
5949    }
5950    // hide children / duplicate link inside itself / add dummy href to parents
5951    $('#mobile-menu ul > li').each(function() {
5952        if ($(this).children('ul.mobile-menu-item').length > 0) {
5953            $(this).addClass("mobile-collapsed");
5954            $(this).children("ul.mobile-menu-item").addClass("mobile-closed");
5955            $(this).children('a').clone().html('All ' + $(this).children('a').html()).prependTo($(this).children("ul.mobile-menu-item")).wrap('<li class="all"></li>');
5956            $(this).children('a').attr('href', '#');
5957        }
5958    });
5959    // show/hide children
5960    $('#mobile-menu ul > li > a').click(function(e) {
5961        if ($(this).parent().children('ul.mobile-menu-item').hasClass('mobile-open')) {
5962            $(this).parent().removeClass("mobile-expanded");
5963            $(this).parent().addClass("mobile-collapsed");
5964            $(this).parent().children("ul.mobile-menu-item").removeClass("mobile-open");
5965            $(this).parent().children("ul.mobile-menu-item").addClass("mobile-closed");
5966        } else if ($(this).parent().children('ul.mobile-menu-item').hasClass('mobile-closed')) {
5967            $(this).parent().addClass("mobile-expanded");
5968            $(this).parent().removeClass("mobile-collapsed");
5969            $(this).parent().children("ul.mobile-menu-item").addClass("mobile-open");
5970            $(this).parent().children("ul.mobile-menu-item").removeClass("mobile-closed");
5971        }
5972    });
5973
5974
5975    //---wishlist features from Mville
5976
5977    //--- Adds a class to the add-to-wishlist button
5978    $('input[type=submit]').each(function() {
5979        if ($(this).attr('value') == 'Add to wish list') {
5980            $(this).addClass('add-to-wishlist-button');
5981
5982        }
5983    });
5984
5985    //--- Adds Usability to Profile Features
5986    // Read a page's GET URL variables and return them as an associative array.
5987    function getUrlVars() {
5988        var vars = [],
5989            hash;
5990        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
5991        for (var i = 0; i < hashes.length; i++) {
5992            hash = hashes[i].split('=');
5993            vars.push(hash[0]);
5994            vars[hash[0]] = hash[1];
5995
5996        }
5997        return vars;
5998    }
5999
6000    //--- Grabs argument from URL and places into a text field
6001    var message_check = getUrlVars()["message"];
6002    if (message_check == "register_request") {
6003        $("#content-area").prepend("<div class='register-alert'>To add an item to your wishlist, please create a user account. You will receive an email to activate your new account.</div>");
6004    }
6005    if ($('#edit-field-first-name-0-value-wrapper').length > 0) {
6006        $('#edit-field-first-name-0-value-wrapper').each(function() {
6007            $(this).prependTo($(this).parent());
6008        });
6009    }
6010    if ($('.not-logged-in').length > 0) {
6011        $('.view-id-taxonomy_term .price-block form > div').each(function() {
6012            $(this).append('<a href="/user/register?message=register_request" 
6012class="add-to-wishlist-button register_request"></a>');
6013        });
6014    }
6015
6016    // Change the text of the "add selected items" button on the textboook lookup
6017    // page
6018    if ($('#timber-course-chooser #tcc-product #timber-checkout a.ajax-cart-link')) {
6019        $('#timber-course-chooser #tcc-product #timber-checkout a.ajax-cart-link').html('<span>Add Selected Items to Cart</span>');
6020    }
6021
6022    // Facilitate checkout with student id number on the checkout page
6023    if ($('.page-cart-checkout').length > 0) {
6024
6025        $('#edit-panes-extra-information-information-ucxf-substitutions-pref-wrapper').parent().parent().appendTo('#customer-pane .fieldset-wrapper');
6026        //   $('#edit-panes-extra-information-information-ucxf-substitutions-pref-wrapper').append('<label>Substitutions Preference</label>');
6027
6028        //$('legend:contains("Extra order information")').html('Student Information');
6029
6030        //Unrequire the Substitutions Pref  (timber.js looks for this class)
6031        $('#edit-panes-extra-information-information-ucxf-substitutions-pref').addClass('unrequire added-by-funcs');
6032
6033        if ($('#block-views-member_id_display-block_1 .views-row .field-content').length > 0) {
6034            scmemid = $('.page-cart-checkout .views-row .field-content').html();
6035            $('#edit-panes-extra-information-information-ucxf-student-id').val(scmemid).attr('disabled', 'disabled').addClass('disabled');
6036        }
6037
6038
6039
6040
6041
6042    } // end page-checkout
6043    $('#payment-pane #edit-panes-payment-payment-method-other-wrapper label').each(function() {
6044        $(this).html($(this).html().replace('Other', 'Pay In-Store')).addClass('text-modified-by-funcs');
6045    });
6046
6047    // Check for out of stock value and add class
6048    $('.add-to-cart input.form-submit').each(function() {
6049        cartstatus = $(this).attr('value');
6050        if (cartstatus == "Out of stock") {
6051            $(this).addClass('out-of-stock added-by-funcs');
6052        }
6053        cartstatus = 'reset';
6054    });
6055
6056    // Set the search input
6057    $('#solr-search-text').val('SEARCH OUR STORES');
6058    $('#solr-search-text').focus(function() {
6059        if ($(this).val() == 'SEARCH OUR STORES') {
6060            $(this).val('').addClass('filled');
6061        }
6062    });
6063    $('#solr-search-text').blur(function() {
6064        if ($(this).val() == '') {
6065            $(this).val('SEARCH OUR STORES').removeClass('filled');
6066        }
6067    });
6068
6069    // // Primary menu interactivity
6070    // $('#block-tvmenu-0 .expanded>a, #block-tvmenu-0 .collapsed>a').each(function() {
6071    //   $(this).after('<a class="direct" title="Show All" href="'+$(this).attr('href')+'">&nbsp;</a>');
6072    // });
6073
6074
6075
6076    // Looks for Products with Multiple Images, and adds a class
6077    $('.node-type-product .field-field-image .field-item:nth-child(2)').each(function() {
6078        $(this).parent().parent().parent().parent().addClass('multi-image-product added-by-funcs');
6079    });
6080    $('form .form-item label:contains("Pack and Reserve Service: ")').parent().addClass('uc-fee added-by-funcs');
6081
6082    // Makes separate lines of links function as one
6083    $('.views-row').bind('mouseenter', function() {
6084        $(this).addClass('hover');
6085    }).bind('mouseleave', function() {
6086        $(this).removeClass('hover');
6087    });
6088    $('.block').bind('mouseenter', function() {
6089        $(this).addClass('hover');
6090    }).bind('mouseleave', function() {
6091        $(this).removeClass('hover');
6092    });
6093
6094    // Make links open in new window
6095    $("#jdock #block-menu-primary-links").each(function() {
6096        $("a[href^='http']").attr('target', '_blank');
6097    });
6098
6099    // Add a print button to the Orders Page
6100    $('tr.ucOrderClick-processed').each(function() {
6101        var oid = $(this).attr('id');
6102        var oidsubstr = oid.split('-')
6103        $(this).children(":first").append('<a href="/admin/store/orders/' + oidsubstr[1] + '/invoice/print">Print</a>');
6104    });
6105
6106    // Add Textbook Lookup link to sidebar
6107    $('#sidebar-left .content>ul.menu').prepend('<li class="added-by-funcs divider confirm"><a class="confirm" href="/college">Coursebook Lookup</a></li>');
6108
6109
6110    if ($('body').width() < 979) {
6111        $('body').addClass('small');
6112    }
6113
6114
6115    //home rotate background size height
6116    if ($('body.front').length > 0) {
6117        bg_width = $('#block-views-home_rotation-block_1').width();
6118        bg_height = bg_width * .22;
6119        $('#block-views-home_rotation-block_1').css('height', bg_height);
6120    }
6121
6122    // Change body class on product category pages
6123    // Detects add list class to list view page category
6124    if ($('body.section-category').length > 0) {
6125        // $('body').addClass('shelves');
6126    }
6127    // set cookie
6128    var sortProductCookie = 'semcoopShelfType';
6129    if ($.cookie(sortProductCookie) != '') {
6130        if ($.cookie(sortProductCookie) == 'shelves') {
6131            $('body').addClass('shelves').removeClass('list');
6132        } else if ($.cookie(sortProductCookie) == 'list') {
6133            $('body').removeClass('shelves').addClass('list');
6134        }
6135    }
6136    $('#sortProduct').change(function() {
6137        // Get the value
6138        sortType = $('#sortProduct').val();
6139        // Add classes according to that value
6140        if (sortType == 'shelves') {
6141            $('body').addClass('shelves').removeClass('list');
6142            $.cookie(sortProductCookie, 'shelves');
6143        } else if (sortType == 'list') {
6144            $('body').removeClass('shelves').addClass('list');
6145            $.cookie(sortProductCookie, 'list');
6146        }
6147    });
6148    // Force to list type for certain pages
6149    if ($('body.page-category-gift-cards').length > 0) {
6150        $('body').removeClass('shelves').addClass('list');
6151    }
6152    if ($('body.page-category-bookstore-t-shirts-tote-bags').length > 0) {
6153        $('body').removeClass('shelves').addClass('list');
6154    }
6155    // Set sortProduct selector based on the body class set above
6156    if ($('body').hasClass('list')) {
6157        $('#sortProduct').val('list');
6158    } else {
6159        $('#sortProduct').val('shelves');
6160    }
6161
6162    // Add body class on Payment Type change - Disabled by -nem in favor of Unified code below.   2021-09-24
6163    // $('#payment-pane input').change(function() {
6164
6165    //     if (typeof prev_mthd != 'undefined') {
6166    //         $('body').removeClass(prev_mthd);
6167    //     }
6168    //     pmt_mthd = 'pmclass-' + $(this).attr('value');
6169    //     $('body').addClass(pmt_mthd);
6170    //     prev_mthd = pmt_mthd;
6171    // });
6172
6173
6174
6175
6176    //append views block menu to view-header to show above the calendar
6177    $('#block-views-event_series_menu-block_1').insertAfter('.view-events .view-header');
6178    $('#block-block-32').insertBefore('.field-type-computed.field-field-veneer');
6179
6180    // set up new payment option, when selected--->populate select list with UChicago Bookcharge
6181    // console.log($('body.role-herkimer').length > 0);
6182
6183    $('#edit-panes-extra-information-information-ucxf-extra-payment-type-wrapper').parent().parent().addClass('uchicago-payment-radio');
6184
6185    // --- Disabled in favor of Unified code  -nem   2021-09-24
6186    // $('body.page-cart-checkout').click(function() {
6187    //     $('#extra_information-pane').addClass('payment-type-uchicago-selected');
6188
6189    //     if ($('#edit-panes-payment-payment-method-ccplus').is(':checked')) {
6190    //         $('body').addClass('payment-type-uchicago-selected');
6191    //         $('#payment-pane #extra_payment_account_num').show('fast');
6192    //     } else {
6193    //         $('body').removeClass('payment-type-uchicago-selected');
6194    //         $('#payment-pane #extra_payment_account_num').hide('fast');
6195    //     }
6196    // });
6197
6198    // if ($('body.page-cart-checkout').length > 0) {
6199    //     $('#payment-pane input').change(function() {
6200    //         if ($(this).val() == "ccplus") {
6201    //             $('body').addClass('payment-type-uchicago-selected');
6202    //         } else {
6203    //             $('body').removeClass('payment-type-uchicago-selected');
6204    //         }
6205    //     });
6206    // }
6207
6208
6209    //Unified payment field hider/shower   -nem 2021/09/24
6210
6211    if ($('body.page-cart-checkout').length > 0) {
6212        $('#payment-pane .form-radios input').change(function() {
6213
6214            //Clear Existing Classes and deselct
6215            $('body').removeClass("payment-credit-card payment-credit-uchicago-research-account payment-type-uchicago-bookcharge payment-type-gift-card");
6216            $('#payment-pane .form-radios input').each(function() {
6217                // $(this).attr('checked', false);
6218            });
6219
6220            //Add just the one we need
6221            if ($(this).val() == "uc_mercury") {
6222                $('body').addClass('payment-credit-card');
6223                $(this).attr('checked', true);
6224            }
6225            if ($(this).val() == "ccplus") {
6226                $('body').addClass('payment-type-uchicago-bookcharge');
6227                $(this).attr('checked', true);
6228            }
6229            if ($(this).val() == "cod") {
6230                $('body').addClass('payment-credit-uchicago-research-account');
6231                $('#edit-panes-payment-payment-method-other-wrapper input').attr('checked', 'checked');
6232            }
6233            if ($(this).val() == "etvr") {
6234                $('body').addClass('payment-type-gift-card');
6235                $(this).attr('checked', true);
6236            }
6237        });
6238    }
6239
6240
6241    //Code to setup Correct Headers for Staff Page - ASP
6242    if ($('.page-staff').length > 0) {
6243        $('#block-views-staff_product_view-block_1 h2').append("'s Top Five Books")
6244        $('#block-views-staff_product_view-block_5 h2').prepend("Books ");
6245        $('#block-views-staff_product_view-block_5 h2').append(" Really Loved")
6246        $('#block-views-staff_product_view-block_3 h2').prepend("Books on ")
6247        $('#block-views-staff_product_view-block_3 h2').append("'s Nightstand")
6248        $('#block-views-staff_product_view-block_2 h2').append("'s Favorite Authors")
6249        $('#block-views-staff_product_view-block_4 h2').append(" Plans to Read")
6250
6251        $('.view-Staff .view-content').prepend('<div class="all-staff"><a href="/staff">All Staff</a></div>')
6252    }
6253
6254    if ($('.page-staff').length > 0) {
6255        index = 1;
6256        $('.view-staff-product-view .view-content').children().each(function() {
6257            $(this).addClass('rows');
6258            $(this).addClass('row-' + index);
6259            index = index + 1;
6260        })
6261
6262        $($('.view-display-id-page_1 .view-header')).append('<div class="all_staff_image"><p><img src="/files/uploaded-images/staff-page-image.jpg"></p></div>')
6263    }
6264
6265    //Track Wishlist
6266    // var wishlist = "";
6267
6268    // if ($('.page-user-1-wishlist').length > 0) {
6269    //     var mysrc = $('.page-title').text();
6270    //     mysrc = mysrc.replace(/\s+/g, '-').replace(/\./g, "").replace(/\(|\)/g, "");
6271    //     mysrc = mysrc.toLowerCase();
6272    //     wishlist = mysrc;
6273
6274    //     console.log(wishlist)
6275    //     $('#wishlist-form-products tr .form-submit').click(function() {
6276    //         createCookie('wishlistCookie', mysrc);
6277
6278    //     })
6279    // }
6280
6281    // console.log(wishlist)
6282    // if ($.cookie('wishlistName') === wishlist) {
6283    //     $('#edit-panes-extra-information-information-ucxf-wishlist-name').attr('value', wishlist);
6284    // }
6285
6286    $('#wishlist-form-products tr .form-submit').click(function() {
6287        if ($(this).data('clicked'))
6288            $.cookie('wishlist_product_in_cart', 'Yes', { expires: 30 / 1440, path: '/cart' })
6289    })
6290
6291    //if statement, if cookie undefined, do nothing, else add text to new text field
6292    if ($.cookie('wishlist_product_in_cart') === undefined) {
6293        $('#edit-panes-extra-information-information-ucxf-wishlist-product-in-cart').val("")
6294    } else {
6295        $('#edit-panes-extra-information-information-ucxf-wishlist-product-in-cart').val("Wishlist Product on Order")
6296    }
6297
6298
6299}); //end doc ready
6300
6301
6302// on window load (after resources have been loaded)
6303$(window).load(function() {
6304    // run preorder message override
6305    semcoopPreorderOverride();
6306
6307    // Product grid masonry inclusion
6308    $('.product-masonry .view-content').masonry({
6309        itemSelector: '.views-row'
6310    });
6311
6312    /*if($('#divEventsCalendar').length > 0) {
6313        // Start calendar
6314      var c = new Calendar("divEventsCalendar");
6315      c.showCurrent();
6316
6317      // Bind next and previous button clicks
6318      document.getElementById('btnNext').onclick = function() {
6319        c.nextMonth();
6320      };
6321      document.getElementById('btnPrev').onclick = function() {
6322        c.previousMonth();
6323      };
6324    }*/
6325
6326}); //end window load
6327
6328
6329
6330// on window load (after resources have been loaded)
6331$(window).load(function() {
6332
6333    //Sets height on slider on Doc Ready
6334    if ($('body.front').length > 0) {
6335        slid_height = $('#block-views-home_rotation-block_1 .views-rotator-item .field-image img').height();
6336        $('#block-views-home_rotation-block_1').css('height', slid_height);
6337        //$('#views-rotator-home_rotation-block_1').css('height',slid_height);
6338    }
6339
6340    //Sets height on slider if Window is resized
6341    $(window).resize(function() {
6342        slid_height = 0;
6343        // Loop through views-rotator-items to find the one that is visible (tallest)
6344        $('#block-views-home_rotation-block_1 .views-rotator-item .field-image img').each(function() {
6345            if ($(this).height() > slid_height) {
6346                slid_height = $(this).height();
6347            }
6348        });
6349        $('#block-views-home_rotation-block_1').css('height', slid_height);
6350        //$('#views-rotator-home_rotation-block_1').css('height',slid_height);
6351    });
6352
6353
6354    //Sets height on slider on Doc Ready
6355    if ($('body.front').length > 0) {
6356        slid_height = $('#views-rotator-events-block_1 .views-rotator-item').height();
6357        $('#views-rotator-events-block_1').css('height', slid_height);
6358        //$('#views-rotator-home_rotation-block_1').css('height',slid_height);
6359    }
6360
6361    //Sets height on slider if Window is resized
6362    $(window).resize(function() {
6363        slid_height = 0;
6364        // Loop through views-rotator-items to find the one that is visible (tallest)
6365        $('#views-rotator-events-block_1 .views-rotator-item').each(function() {
6366            if ($(this).height() > slid_height) {
6367                slid_height = $(this).height();
6368            }
6369        });
6370        $('#views-rotator-events-block_1').css('height', slid_height);
6371        //$('#views-rotator-home_rotation-block_1').css('height',slid_height);
6372    });
6373
6374
6375
6376});
6377
6378// Remove ships in 3-5 days message for pre-order products
6379// hacked in code; should add directly into the preorder text timber module
6380// support and then remove this code
6381// probably add a separate condition class to the node called "cond-preorder"
6382// and then style appropriately to remove the message
6383function semcoopPreorderOverride() {
6384    // site-woodlawn
6385    // site-57th-street-books
6386    // look for add to cart buttons
6387    if ($('.add-to-cart').length > 0) {
6388        // loop through add to cart buttons if found
6389        $('.add-to-cart').each(function() {
6390            // find the add to cart input button, check if it's text has been
6391            // re-written
6392            if ($(this).find('input.node-add-to-cart').attr('value').toLowerCase().replace(/ /g, "") != 'addtocart') {
6393                // if the text has been re-written, it's most likely a pre-order
6394                // set the preorder-override class
6395                $(this).addClass('preorder-override');
6396            }
6397        });
6398    }
6399}
6400;
6401// Dynamic Shelving script to replicate the Herk-Cycle Shelfs
6402
6403$(document).ready(function() {
6404
6405    if($('body.front').length > 0 ) {
6406
6407      // Clone & add our Next & Prev buttons
6408
6409      // Wrap our semantic views in our herk-cycle div
6410      $('.view-dynamic-shelf .herk-product-cycle-inner').each(function() {
6411          $(this).wrap("<div class='herk-product-cycle'></div>");
6412      })
6413      
6414      buildHerkProductCycles();
6415
6416      // function to build the sliders
6417      function buildHerkProductCycles() {
6418        // loop through all cycles on the page and build them
6419        var herkCycleID = 8;
6420        var herkCycleAmount = 500;
6421        var herkCycleSpeed = 500;
6422        $('.herk-product-cycle').hide();
6423        $('.herk-product-cycle').each(function() {
6424          // add a unique id to the cycle
6425          var herkCycleIDClass = 'herk-product-cycle-'+ herkCycleID;
6426          $(this).addClass(herkCycleIDClass);
6427          
6428          // get the width of all items in the cycler
6429          var herkCycleItemsBounding = 0;
6430          $(this).find('.herk-product-cycle-row').each(function() {
6431              var rect = this.getBoundingClientRect();
6432              var width = rect.right - rect.left;
6433              herkCycleItemsBounding = herkCycleItemsBounding + Math.ceil(width);
6434          });
6435      
6436          // add the navigation arrows
6437          if($(this).parent().parent().hasClass('view-dynamic-shelf')) $(this).append('<div class="herk-cycle-nav herk-cycle-prev"><a href="#" data-direction="prev" data-cycle-id="'+herkCycleIDClass+'"><span class="label">Previous</span></a></div><div class="herk-cycle-nav herk-cycle-next"><a data-direction="next" href="#" data-cycle-id="'+herkCycleIDClass+'"><span class="label">Next</span></a></div>');
6438
6439          var herkCycleCategoryLinks = $(this).find('.herk-product-cycle-row .taxo_link a');
6440          var uniqueLinks = {};
6441          herkCycleCategoryLinks.each(function() {
6442            //console.log($(this).attr('href'));
6443            uniqueLinks[$(this).attr('href')] = [
6444              $(this).attr('href'),
6445              $(this).html()
6446            ];
6447          });
6448
6449          // add the width to the container of items
6450          // if found a taxo link in the first row, add to the footer with "view all" 
6451          // prepended
6452          var herkCycleCategoryLink = $(this).find('.herk-product-cycle-row:first-child .taxo_link a');
6453          
6454          $(this).parent('.content').parent('.block').find('h2').remove();
6455          if(Object.keys(uniqueLinks).length <= 5) {
6456            for(let i=0; i<Object.keys(uniqueLinks).length; i++) {
6457              // add a category link to the footer
6458              var theURL = Object.keys(uniqueLinks)[i];
6459              var herkCycleCategoryViewLink = '<a href="'+uniqueLinks[theURL][0]+'">Browse '+uniqueLinks[theURL][1]+'</a>';
6460              if($(this).parent().parent().hasClass('view-dynamic-shelf')) $(this).append('<div class="category-link">'+herkCycleCategoryViewLink+'</div>');
6461              // replace the block header
6462              var herkCycleHeaderLink = '<a href="'+uniqueLinks[theURL].href+'"><h2>'+herkCycleCategoryLink.html()+'</h2></a>';
6463              $(this).parent('.content').parent('.block').prepend(herkCycleHeaderLink);
6464            }
6465          }
6466          // increase the cycleID
6467          herkCycleID++;
6468        });
6469        $('.herk-product-cycle').show();
6470      
6471        // click events for scrolling
6472        $('.herk-product-cycle .herk-cycle-nav a').click(function(event) {
6473          event.preventDefault();
6474          // get the button direction
6475          var herkCycleNavDirection = $(this).attr('data-direction');
6476          // get the cycle id
6477          var herkCycleIDClass = $(this).attr('data-cycle-id');
6478          // get the current cycle, it's contents and it's width
6479          var herkCycle = $('.'+herkCycleIDClass);
6480          var herkCycleWidth = herkCycle.width();
vendor: 5,237 bytes, lines 6481-6539
6481          var herkCycleContent = herkCycle.find('.herk-product-cycle-inner');
6482          var herkCycleContentWidth = herkCycleContent.width();
6483          // get the current position, and subtract the cycle amount
6484          var herkCycleContentPosition = parseFloat(herkCycleContent.css('left'));
6485          var newPosition = false;
6486          if(herkCycleNavDirection == 'prev') {
6487            // prev: scroll backwards
6488            newPosition = herkCycleContentPosition + herkCycleAmount;
6489            // if it's over the amount, reset
6490            if(newPosition > 0) {
6491              // if the current position is equal to the exact start, set the new 
6492              // position to the entire width minus the content width to scroll to the
6493              // exact end of the content
6494              if(herkCycleContentPosition == 0) {
6495                newPosition = (herkCycleContentWidth - herkCycleWidth) * -1;
6496              } else {
6497                // otherwise, we haven't reached the exact start yet, so push to the
6498                // exact start, since we would be pushing over it
6499                newPosition = 0;
6500              }
6501            }
6502          } else if(herkCycleNavDirection == 'next') {
6503            // next: scroll forward
6504            newPosition = herkCycleContentPosition - herkCycleAmount;
6505            // if it's over the amount, reset
6506            // using + because the value of newPosition for "next" will be negative
6507            if((herkCycleContentWidth + newPosition - herkCycleWidth) < 0) {
6508              // if the current position is equal to the exact end, reset to 0 to 
6509              // scroll to the beginning
6510              if(herkCycleContentPosition == (herkCycleContentWidth - herkCycleWidth) * -1) {
6511                newPosition = 0;
6512              } else {
6513                // otherwise, we haven't reached the exact end yet, so push to the
6514                // exact end, since we would be pushing over it
6515                // set the new position to the entire width minus the content width to
6516                // scroll to the end of the content
6517                newPosition = (herkCycleContentWidth - herkCycleWidth) * -1;
6518              }
6519            }
6520          }
6521          if(newPosition !== false) {
6522            // set the new position on the cycler
6523            herkCycleContent.animate({
6524              left: newPosition,
6525            }, herkCycleSpeed, function() {
6526              // animation completed
6527            });
6528          }
6529        });
6530      }   
6531    }
6532    // $('.node-type-dynamic-shelf #edit-taxonomy-1').attr('multiple',false);
6533});;
6534/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
6535/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
6536window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='&shy;<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document);
6537
6538/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs  */
6539(function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B<y;B++){A=D[B],z=A.href,C=A.media,x=A.rel&&A.rel.toLowerCase()==="stylesheet";if(!!z&&x&&!o[z]){if(A.styleSheet&&A.styleSheet.rawCssText){m(A.styleSheet.rawCssText,z,C);o[z]=true}else{if((!/^([a-zA-Z:]*\/\/)/.test(z)&&!g)||z.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:z,media:C})}}}}u()},u=function(){if(d.length){var x=d.shift();n(x.href,function(y){m(y,x.href,x.media);o[x.href]=true;u()})}},m=function(I,x,z){var G=I.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),J=G&&G.length||0,x=x.substring(0,x.lastIndexOf("/")),y=function(K){return K.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+x+"$2$3")},A=!J&&z,D=0,C,E,F,B,H;if(x.length){x+="/"}if(A){J=1}for(;D<J;D++){C=0;if(A){E=z;k.push(y(I))}else{E=G[D].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&y(RegExp.$2))}B=E.split(",");H=B.length;for(;C<H;C++){F=B[C];i.push({media:F.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:k.length-1,hasquery:F.indexOf("(")>-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);
6539s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l<h){clearTimeout(r);r=setTimeout(j,h);return}else{l=z}for(var E in i){var K=i[E],C=K.minw,J=K.maxw,A=C===null,L=J===null,y="em";if(!!C){C=parseFloat(C)*(C.indexOf(y)>-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this);;
6540$(document).ready(function() {
6541	//console.log("Semcoop: Custom Checkout");
6542
6543  // var watchingForShipping = false;
6544
6545  // REVIEW ORDER: Moves Panes around
6546  var hideReviewPane = false;
6547  var reviewPaneTitle = 'none';
6548  var reviewPaneOrder = false;
6549  var reviewPaneTax = false;
6550  var lastReviewRow = false;
6551  var reviewRowCount = 0;
6552  var extraPaymentReview = '';
6553  var extraPaymentReviewType = 'none';
6554  $('table.order-review-table tr').each(function() {
6555    // check the pane title
6556    if($(this).hasClass('pane-title-row')) {
6557      // this is a title row
6558      hideReviewPane = false;
6559      reviewPaneOrder = false;
6560      reviewPaneTitle = $(this).find('td:first-child').html();
6561      // 2018-07-30 -- commented out delivery information; they want to show
6562      // this now
6563      if( //reviewPaneTitle == 'Delivery information' ||
6564          reviewPaneTitle == 'Cart contents' ||
6565          //reviewPaneTitle == 'Delivery Information'||
6566          reviewPaneTitle == 'Delivery Preference') {
6567        hideReviewPane = true;
6568      }
6569      if(reviewPaneTitle == 'Order total') {
6570        reviewPaneOrder = true;
6571      }
6572      if(reviewPaneTitle == 'Tax-exempt Information') {
6573        reviewPaneTax = true;
6574        hideReviewPane = true;
6575      }
6576    } else {
6577      if(reviewPaneTax) {
6578        // tax exempt pane
6579        // hide fields that aren't applicable to taxes
6580        if($(this).find('td.title-col').html() == 'Payment Type:') {
6581          extraPaymentReview += '<tr class="extra_payment_type extra_payment_review">'+$(this).html()+'</tr>';
6582          extraPaymentReviewType = $(this).find('td.data-col').html();
6583          $(this).css('display', 'none');
6584        }
6585        if($(this).find('td.title-col').html() == ' Seminary Co-Op:') {
6586          $(this).css('display', 'none');
6587        }
6588        if($(this).find('td.title-col').html() == 'Gift Card #:') {
6589          extraPaymentReview += '<tr class="gift_card_num extra_payment_review">'+$(this).html()+'</tr>';
6590          $(this).css('display', 'none');
6591        }
6592        if($(this).find('td.title-col').html() == 'House Account #:') {
6593          extraPaymentReview += '<tr class="house_card_num extra_payment_review">'+$(this).html()+'</tr>';
6594          $(this).css('display', 'none');
6595        }
6596      }
6597      // not a title row
6598      // check payment type
6599      if($(this).find('td.title-col').html() == 'Paying by:') {
6600        // add the extra payment info below
6601        $(this).after(extraPaymentReview);
6602        // hide the extra payment info
6603        $('.extra_payment_review').css('display', 'none');
6604        // check for credit card
6605        if($(this).find('td.data-col').html() == 'Mercury Pay') {
6606          // change the label to credit card from mercury pay
6607          $(this).find('td.data-col').html("Credit Card");
6608          // add a credit card warning message to the top
6609          $('#content-content p:first-child').after('<p class="credit_card_message"><strong>Please enter your Credit Card details at the bottom of the page.</strong></p>')
6610        }
6611        if($(this).find('td.data-col').html() == 'Other') {
6612          // check for other payment
6613          extraPaymentReviewType = extraPaymentReviewType.toLowerCase().replace(/ /g, '_');
6614          if(extraPaymentReviewType == 'pay_in_store') {
6615            $('.extra_payment_type.extra_payment_review').css('display', 'block');
6616          }
6617          if(extraPaymentReviewType == 'house_account') {
6618            $('.extra_payment_type.extra_payment_review').css('display', 'block');
6619            $('.house_card_num.extra_payment_review').css('display', 'block');
6620          }
6621          if(extraPaymentReviewType == 'gift_card') {
6622            $('.extra_payment_type.extra_payment_review').css('display', 'block');
6623            $('.gift_card_num.extra_payment_review').css('display', 'block');
6624          }
6625        }
6626      }
6627    }
6628    if(hideReviewPane) {
6629      console.log('hide ' + reviewPaneTitle);
6630      $(this).css('display', 'none');
6631    }
6632    if(reviewPaneOrder) {
6633      console.log('move ' + reviewPaneTitle + ' to top');
6634      var currentReviewRow = 'review-row-' + reviewRowCount;
6635      $(this).addClass(currentReviewRow);
6636      if(reviewRowCount == 0) {
6637        $(this).prependTo('table.order-review-table');
6638      } else {
6639        $('table.order-review-table tr.' + lastReviewRow).after($(this));
6640      }
6641      lastReviewRow = currentReviewRow;
6642      reviewRowCount++;
6643    }
6644  });
6645
6646	// CHECKOUT: Gift Card, House Account, or Pay In Store Payment Method
6647  // Customization
6648  // move the two extra fields into the payment method pane
6649  // find the timberPaymentChange function at the bottom of this file for more
6650  // relevant code
6651
6652
6653  //Create the container
6654  $('#uc-cart-checkout-form #payment-pane > .fieldset-wrapper').append('<div id="extra_payment_account_num"><table></table><div id="extraError"></div></div>');
6655
6656  //Move UChicago Booknum into container
6657  $('#edit-panes-extra-information-information-ucxf-uchi-bookcharge-num-wrapper').parent().parent().attr('id', 'uchicago_bookcharge_num_tr');
6658  $('#uchicago_bookcharge_num_tr').prependTo('#uc-cart-checkout-form #payment-pane #extra_payment_account_num table');
6659
6660  //Move UChicago Booknum into container
6661  $('#edit-panes-extra-information-information-ucxf-research-account-name-wrapper').parent().parent().attr('id', 'uchicago_research_account_name_tr');
6662  $('#uchicago_research_account_name_tr').prependTo('#uc-cart-checkout-form #payment-pane #extra_payment_account_num table');
6663
6664  //Move House Account Num into container
6665  $('#uc-cart-checkout-form #extra_information-pane #edit-panes-extra-information-information-ucxf-hosue-account-num-wrapper').parent('td').parent('tr').attr('id', 'house_account_num_tr');
6666  $('#uc-cart-checkout-form #extra_information-pane #house_account_num_tr').prependTo('#uc-cart-checkout-form #payment-pane #extra_payment_account_num table');
6667
6668  //Move Gift Card Num into container
6669  $('#uc-cart-checkout-form #extra_information-pane #edit-panes-extra-information-information-ucxf-gift-card-num-wrapper').parent('td').parent('tr').attr('id', 'gift_card_num_tr');
6670  $('#uc-cart-checkout-form #extra_information-pane #gift_card_num_tr').prependTo('#uc-cart-checkout-form #payment-pane #extra_payment_account_num table');
6671
6672  $('#edit-panes-extra-information-information-ucxf-extra-payment-type').change(function() {
6673    var togglePayment = false;
6674    if($(this).val() == 'house_account') {
6675      togglePayment = '#house_account_num_tr';
6676    } else if($(this).val() == 'gift_card') {
6677      togglePayment = '#gift_card_num_tr';
6678    } else if($(this).val() == 'uchicago_bookcharge') {
6679      togglePayment = '#uchicago_bookcharge_num_tr';
6680    } else if($(this).val() == 'uchicago_research_account') {
6681      togglePayment = '#uchicago_research_account_name_tr';
6682    }
6683
6684    $('#uc-cart-checkout-form #payment-pane #extra_payment_account_num table tr').each(function() {
6685      if($(this).attr('id') == $(togglePayment).attr('id')) {
6686        // toggle the payment field
6687        $(this).slideDown('fast', function() {});
6688      } else {
6689        // untoggle the payment field
6690        $(this).slideUp('fast', function() {});
6691      }
6692    });
6693  });
6694  // Require these extra payment methods if other payment method selected
6695  $('form#uc-cart-checkout-form #edit-continue').click(function(event) {
6696    var currentPayment = $('input[name="panes[payment][payment_method]"]:checked').val();
6697    if(currentPayment == 'other') {
6698      var extraPayment = $('#edit-panes-extra-information-information-ucxf-extra-payment-type').val();
6699      var epError = false;
6700      if(extraPayment == 'house_account') {
6701        // make sure the field is visible
6702        $('#payment-pane #extra_payment_account_num #house_account_num_tr').show('fast');
6703        // check house account number field
6704        if(!$('#edit-panes-extra-information-information-ucxf-hosue-account-num').val()) {
6705          $('#edit-panes-extra-information-information-ucxf-hosue-account-num').addClass('error');
6706          epError = "Please enter a House Account #";
6707        }
6708      } else if (extraPayment == 'gift_card') {
6709        // make sure the field is visible
6710        $('#payment-pane #extra_payment_account_num #gift_card_num_tr').show('fast');
6711        // check gift card number field
6712        if(!$('#edit-panes-extra-information-information-ucxf-gift-card-num').val()) {
6713          $('#edit-panes-extra-information-information-ucxf-gift-card-num').addClass('error');
6714          epError = "Please enter a Gift Card #";
6715        }
6716
6717
6718      } else if (extraPayment == 'uchicago_bookcharge') {
6719        console.log(true);
6720        // make sure the field is visible
6721        $('#payment-pane #extra_payment_account_num #uchicago_bookcharge_num_tr').show('fast');
6722        // check gift card number field
6723        if(!$('#edit-panes-extra-information-information-ucxf-uchi-bookcharge-num').val()) {
6724          $('#edit-panes-extra-information-information-ucxf-uchi-bookcharge-num').addClass('error');
6725          epError = "Please enter a UChicago Student ID #";
6726        }
6727
6728      } else if (extraPayment == 'uchicago_research_account') {
6729        // make sure the field is visible
6730        $('#payment-pane #extra_payment_account_num #uchicago_research_account_name_tr').show('fast');
6731        // check gift card number field
6732        if(!$('#edit-panes-extra-information-information-ucxf-research-account-name').val()) {
6733          $('#edit-panes-extra-information-information-ucxf-research-account-name').addClass('error');
6734          epError = "Please enter a research account name";
6735        }
6736
6737      } else if (extraPayment == 'pay_in_store') {
6738        // pay in store
6739      } else {
6740        // add error and error class
6741        $('#edit-panes-extra-information-information-ucxf-extra-payment-type').addClass('error');
6742        epError = "Please select a Payment Type";
6743      }
6744      if(epError) {
6745        // prevent form submission
6746        event.preventDefault();
6747        // add the error
6748        $('#extra_payment_account_num #extraError').html('<div class="error">' + epError + '</div>');
6749        // scroll to the payment section
6750        $('html, body').animate({
6751          scrollTop: $("#extra_payment_info").offset().top
6752        }, 500);
6753      }  else {
6754        // no errors on this part, remove error class and errors
6755        $('#extra_payment_account_num input, #extra_payment_account_num select').removeClass('error');
6756        $('#extra_payment_account_num #extraError').html('');
6757      }
6758
6759    } else if(currentPayment == 'ccplus') {
6760      console.log(true);
6761      $('#edit-panes-extra-information-information-ucxf-student-id').removeClass('error required');
6762    }
6763  });
6764
6765
6766
6767  // CHECKOUT: House Account / Pay In Store Merge
6768  $('#extra_information-pane table tr').each(function() {
6769    if($(this).find('#edit-panes-extra-information-information-ucxf-extra-payment-type-wrapper').length > 0) {
6770      $('#payment-pane #payment_details').after('<div id="extra_payment_info"><table></table></div>');
6771      $(this).appendTo($('#payment-pane #extra_payment_info table'));
6772    }
6773  });
6774
6775  // CHECKOUT: Change Order Comments Description
6776  $('#comments-pane .fieldset-wrapper > .description').html("<strong>IMPORTANT:</strong> Please let us know if we should apply your store credits to this order. Also, is this a gift?  If so, let us know and we will gladly include a note, provide gift wrapping and/or omit pricing information.").addClass('modified-by-semcoop-checkout-js');
6777
6778  // CHECKOUT: Re-order Billing Countries
6779  // Move us, canada, uk to the top of the list
6780  $('#edit-panes-billing-billing-country option').each(function() {
6781    // canada
6782    if($(this).val() == '124') {$(this).prependTo('#edit-panes-billing-billing-country');}
6783    // uk
6784    if($(this).val() == '826') {$(this).prependTo('#edit-panes-billing-billing-country');}
6785    // us (do last to be at top)
6786    if($(this).val() == '840') {$(this).prependTo('#edit-panes-billing-billing-country');}
6787  });
6788
6789  // CHECKOUT: Add "Edit Cart" link to Cart Contents Pane
6790  if($('#uc-cart-checkout-form #cart-pane').length > 0) {
6791    $('#uc-cart-checkout-form #cart-pane').append('<div class="edit-cart-link"><a href="/cart">Edit Cart</a></div>');
6792  }
6793
6794  // CHECKOUT: Add Credit Card Warning
6795  if(!$('#coopCreditHelp').length > 0) {
6796    var coopCreditHelp = '<div id="coopCreditHelp"><div class="message"><p>You will be asked for your Credit Card on the next page after reviewing your order.</p></div></div>';
6797    $('#payment-pane > .fieldset-wrapper > .form-item').append(coopCreditHelp);
6798  }
6799  $('#payment-pane input[name="panes[payment][payment_method]"]').change(function() {
6800    if($(this).val() == 'uc_mercury') {
6801      if($('#coopCreditHelp').css('display') == 'none') {
6802        $('#coopCreditHelp').slideToggle('fast', function() {
6803
6804        });
6805      }
6806    } else {
6807      if($('#coopCreditHelp').css('display') == 'block') {
6808        $('#coopCreditHelp').slideToggle('fast', function() {
6809
6810        });
6811      }
6812    }
6813  });
6814
6815  // CHECKOUT: Tax Exempt Checkout Pane
6816  if($('#extra_information-pane').length > 0) {
6817    // Show the Extra Information (Tax Exempt) Pane on Checkout when a Tax
6818    // Exempt state is selected
6819    var selectedCountry = 'none';
6820    // when the user selects a country update the selectedcountry var
6821    $('#edit-panes-billing-billing-zone').change(function() {
6822      selectedCountry = ($('#edit-panes-billing-billing-zone option:selected').text());
6823      // check if the state is tax excempt
6824      if (selectedCountry.toLowerCase().indexOf("tax exempt") >= 0) {
6825        // show the tax exemption pane
6826        $('#extra_information-pane').show('fast');
6827      } else {
6828        // hide the tax exemption pane
6829        $('#extra_information-pane').hide('fast');
6830      }
6831    });
6832    // Disable the tax exempt country field to lock it in on United States
6833    $('#edit-panes-extra-information-information-ucxf-tax-country').attr('disabled', 'disabled');
6834    // Add tax exempt information to the top of the pane
6835    $('#extra_information-pane .uc-extra-fields-pane-table tr:first-child').prepend('<tr class="tax-exempt-info"><td>
6835If you qualify for sales tax exemption, please provide your organization information. Organization name and tax-exempt number are required to be considered for tax exemption.</td></tr>');
6836  }
6837
6838  // CHECKOUT: Bind to a shipping change
6839  // $('#quotes-pane #quote').bind('DOMNodeInserted DOMSubtreeModified DOMNodeRemoved', function(e) {
6840  //     console.log('SHIPPING CHANGED');
6841  //     // if(!watchingForShipping) {
6842  //     //   watchingForShipping = true;
6843  //     //   semcoopCustomCheckout();
6844  //     // }
6845  // })
6846  // console.log($('.flatrate_11---0'));
6847  $('#edit-panes-customer-primary-email-wrapper').next().hide();
6848});
6849let behaviorCounter = 0;
6850Drupal.behaviors.checkOut = function(context) {
6851  if(typeof context[0] === 'undefined') return;
6852  if($('div').find('input[name=rate[flatrate_11---0]]').parent().length === 1) {
6853    behaviorCounter += 1;
6854    if(behaviorCounter === 1) {
6855        const deliveryText = $('<p>&nbsp;By selecting delivery, you agree to the guidelines listed on <a href="https://semcoop.com/delivery" target=_blank">semcoop.com/delivery</a>.</p>');
6856        $('div').find('input[name=rate[flatrate_11---0]]').next().after(deliveryText);
6857      }
6858    }
6859
6860  if($('div').find('input[name=rate[flatrate_12---0]]').parent().length === 1) {
6861    if(behaviorCounter === 1 || behaviorCounter === 0 || behaviorCounter === 2) {
6862      const deliveryText = $('<p>&nbsp;By selecting curbside pickup, you agree to the guidelines listed on <a href="https://semcoop.com/curbside-pickup" target=_blank">semcoop.com/curbside-pickup</a>.</p>');
6863      $('div').find('input[name=rate[flatrate_12---0]]').next().after(deliveryText);
6864    }
6865  }
6866}
6867
6868// CHECKOUT: SemCoop Custom Checkout
6869// When the shipping options are re-calculated, alter the options based on
6870// the delivery preference
6871function semcoopCustomCheckout() {
6872  // console.log('semcoopCustomCheckout');
6873  // Trigger the SemCoop Custom Checkout after the shipping options have
6874  // come in
6875  // var waitForShipping = false;
6876  // clearInterval(waitForShipping);
6877  // waitForShipping = setInterval(function() {
6878  //   console.log("waiting for shipping options");
6879
6880  // }, 250);
6881}
6882
6883function timberPaymentChange(obj) {
6884  if(obj.val() == 'other') {
6885    $('#payment-pane #extra_payment_info').show('fast');
6886    $('#payment-pane #extra_payment_account_num').show('fast');
6887  } else {
6888    $('#payment-pane #extra_payment_info').hide('fast');
6889    $('#payment-pane #extra_payment_account_num').hide('fast');
6890  }
6891}
6892
6893// Fires on page load and after almost anything changes on the page, shipping options in particular.
6894function timberCartOptionsInit() {
6895  // make sure the shipping values have come in
6896  if($('#quote-dirty').length == 0 && $('#quoteProgress').length == 0 ) {
6897    // console.log("found shipping options");
6898    // watchingForShipping = false;
6899
6900    // clearInterval(waitForShipping);
6901    // var deliveryPreference = $('#delivery_preference-pane input[name="panes[delivery_preference][delivery_preference]"]:checked').val();
6902    // console.log("Delivery Preference: " + deliveryPreference);
6903    // make sure the Delivery Preference has been set before continuing
6904    if(typeof timberCartOptions.deliveryPreference !== 'undefined') {
6905      if(timberCartOptions.deliveryPreference == 'delivery') {
6906        // Delivery
6907        // Enable the Billing, Delivery same checkbox
6908        $('#edit-panes-delivery-copy-address').removeClass('admin-only');
6909        // Disable pay in store option in extra payment fields
6910        $('#edit-panes-extra-information-information-ucxf-extra-payment-type option[value="pay_in_store"]').attr('disabled', 'disabled');
6911        // Disable Pickup Options
6912        // Loop through the shipping form items
6913        // $('#quotes-pane .form-item').each(function() {
6914        //   // Make sure the element contains an input field
6915        //   if($(this).find('input[name="quote-option"]').length > 0) {
6916        //     // Store the input field in a variable
6917        //     var loopedShipping = $(this).find('input[name="quote-option"]').val();
6918        //     loopedShipping = loopedShipping.split('-');
6919        //     loopedShipping = loopedShipping[0];
6920        //     // Check if the input is a pick-up option
6921        //     if(typeof(storeAddress[loopedShipping]) == 'object' && storeAddress[loopedShipping].location.length > 0) {
6922        //       // Found pick-up option, hide it
6923        //       $(this).addClass('admin-only');
6924        //     }
6925        //   }
6926
6927        // If the ship option is one of the two pickup locations (flat rates 4 and 5), switch it to media mail (6 or 7)
6928        if(timberCartOptions.shippingType.match('^flatrate_[45]-')) {
6929          // Set Shipping to Media Mail
6930          if($('input[type="radio"][value="flatrate_6---0"]').length > 0) {
6931            // console.log("found and set delivery 6");
6932            $('input[type="radio"][value="flatrate_6---0"]').click();
6933          }
6934          if($('input[type="radio"][value="flatrate_7---0"]').length > 0) {
6935            // console.log("found and set delivery 7");
6936            $('input[type="radio"][value="flatrate_7---0"]').click();
6937          }
6938        }
6939        // });
6940      } else {
6941        // Pick-Up -- Currently disabled as of 6/12/2020
6942        // Disable and uncheck the Billing, Delivery same checkbox, if checked
6943        if($('#edit-panes-delivery-copy-address').is(':checked')) {
6944          $('#edit-panes-delivery-copy-address').click();
6945        }
6946        $('#edit-panes-delivery-copy-address').addClass('admin-only');
6947        // fill in the delivery first, last name based on the store, using the
6948        // timber.js storeAddress object
6949        coopLocation = 'default';
6950        if(typeof(storeAddress[timberCartOptions.deliveryPreference]) == 'object' && storeAddress[timberCartOptions.deliveryPreference].location.length > 0) {
6951          coopLocation = timberCartOptions.deliveryPreference;
6952        }
6953        // $('#edit-panes-delivery-delivery-first-name').val(storeAddress[coopLocation].location);
6954        // $('#edit-panes-delivery-delivery-last-name').val(storeAddress[coopLocation].location);
6955
6956        // Unset the saved address field for the Delivery Address
6957        // $('#uc-cart-checkout-form #edit-panes-delivery-delivery-address-select').val('0');
6958
6959        // console.log('Saved Address Reset');
6960        // Enable pay in store option in extra payment fields
6961        // $('#edit-panes-extra-information-information-ucxf-extra-payment-type option[value="pay_in_store"]').removeAttr('disabled');
6962
6963        // Enable Pickup Options
6964        // Loop through the shipping form items
6965        // $('#quotes-pane .form-item').each(function() {
6966          // Make sure the element contains an input field
6967          // if($(this).find('input[name="quote-option"]').length > 0) {
6968          //   // Store the input field in a variable
6969          //   var loopedShipping = $(this).find('input[name="quote-option"]').val();
6970          //   loopedShipping = loopedShipping.split('-');
6971          //   loopedShipping = loopedShipping[0];
6972          //   // Check if the input is a pick-up option
6973          //   if(typeof(storeAddress[loopedShipping]) == 'object' && storeAddress[loopedShipping].location.length > 0) {
6974          //     // It is a pick-up option, show it
6975          //     $(this).removeClass('admin-only');
6976          //   }
6977          //   // Select the pick up shipping option that matches the delivery
6978          //   // preference selected
6979          //   // Check if the input is the selected pick-up option
6980          //   if(loopedShipping == timberCartOptions.deliveryPreference) {
6981          //     if(typeof(storeAddress[timberCartOptions.deliveryPreference]) == 'object' && storeAddress[timberCartOptions.deliveryPreference].location.length > 0) {
6982          //       $(this).find('input[name="quote-option"]').click();
6983          //     }
6984          //   }
6985          // }
6986        // });
6987      }
6988    }
6989  }
6990
6991
6992
6993
6994}
6995;

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.