/*! jQuery v2.0.0 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */ (function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],f="2.0.0",p=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=f.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]!==undefined)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){var r,i=[],o=0,s=e.length;for(n=!!n;s>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,s=j(e),a=[];if(s)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(a[a.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(a[a.length]=r);return p.apply([],a)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(n=e[t],t=e,e=n),x.isFunction(e)?(r=d.call(arguments,2),i=function(){return e.apply(t||this,r.concat(d.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):undefined},access:function(e,t,n,r,i,o,s){var a=0,u=e.length,l=null==n;if("object"===x.type(n)){i=!0;for(a in n)x.access(e,t,a,n[a],!0,o,s)}else if(r!==undefined&&(i=!0,x.isFunction(r)||(s=!0),l&&(s?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(x(e),n)})),t))for(;u>a;a++)t(e[a],n,s?r:r.call(e[a],a,t(e[a],n)));return i?e:l?t.call(e):u?t(e[0],n):o},now:Date.now,swap:function(e,t,n,r){var i,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=s[o];return i}}),x.ready.promise=function(t){return n||(n=x.Deferred(),"complete"===o.readyState?setTimeout(x.ready):(o.addEventListener("DOMContentLoaded",S,!1),e.addEventListener("load",S,!1))),n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function j(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}t=x(o),function(e,undefined){var t,n,r,i,o,s,a,u,l,c,f,p,h,d,g,m,y="sizzle"+-new Date,v=e.document,b={},w=0,T=0,C=ot(),k=ot(),N=ot(),E=!1,S=function(){return 0},j=typeof undefined,D=1<<31,A=[],L=A.pop,q=A.push,H=A.push,O=A.slice,F=A.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",R="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=M.replace("w","w#"),$="\\["+R+"*("+M+")"+R+"*(?:([*^$|!~]?=)"+R+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+R+"*\\]",B=":("+M+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",I=RegExp("^"+R+"+|((?:^|[^\\\\])(?:\\\\.)*)"+R+"+$","g"),z=RegExp("^"+R+"*,"+R+"*"),_=RegExp("^"+R+"*([>+~]|"+R+")"+R+"*"),X=RegExp(R+"*[+~]"),U=RegExp("="+R+"*([^\\]'\"]*)"+R+"*\\]","g"),Y=RegExp(B),V=RegExp("^"+W+"$"),G={ID:RegExp("^#("+M+")"),CLASS:RegExp("^\\.("+M+")"),TAG:RegExp("^("+M.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+B),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+R+"*(even|odd|(([+-]|)(\\d*)n|)"+R+"*(?:([+-]|)"+R+"*(\\d+)|))"+R+"*\\)|)","i"),"boolean":RegExp("^(?:"+P+")$","i"),needsContext:RegExp("^"+R+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+R+"*((?:-\\d)?\\d*)"+R+"*\\)|)(?=[^-]|$)","i")},J=/^[^{]+\{\s*\[native \w/,Q=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,et=/'|\\/g,tt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,nt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{H.apply(A=O.call(v.childNodes),v.childNodes),A[v.childNodes.length].nodeType}catch(rt){H={apply:A.length?function(e,t){q.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function it(e){return J.test(e+"")}function ot(){var e,t=[];return e=function(n,i){return t.push(n+=" ")>r.cacheLength&&delete e[t.shift()],e[n]=i}}function st(e){return e[y]=!0,e}function at(e){var t=c.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ut(e,t,n,r){var i,o,s,a,u,f,d,g,x,w;if((t?t.ownerDocument||t:v)!==c&&l(t),t=t||c,n=n||[],!e||"string"!=typeof e)return n;if(1!==(a=t.nodeType)&&9!==a)return[];if(p&&!r){if(i=Q.exec(e))if(s=i[1]){if(9===a){if(o=t.getElementById(s),!o||!o.parentNode)return n;if(o.id===s)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&m(t,o)&&o.id===s)return n.push(o),n}else{if(i[2])return H.apply(n,t.getElementsByTagName(e)),n;if((s=i[3])&&b.getElementsByClassName&&t.getElementsByClassName)return H.apply(n,t.getElementsByClassName(s)),n}if(b.qsa&&(!h||!h.test(e))){if(g=d=y,x=t,w=9===a&&e,1===a&&"object"!==t.nodeName.toLowerCase()){f=gt(e),(d=t.getAttribute("id"))?g=d.replace(et,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=f.length;while(u--)f[u]=g+mt(f[u]);x=X.test(e)&&t.parentNode||t,w=f.join(",")}if(w)try{return H.apply(n,x.querySelectorAll(w)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(I,"$1"),t,n,r)}o=ut.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},l=ut.setDocument=function(e){var t=e?e.ownerDocument||e:v;return t!==c&&9===t.nodeType&&t.documentElement?(c=t,f=t.documentElement,p=!o(t),b.getElementsByTagName=at(function(e){return e.appendChild(t.createComment("")),!e.getElementsByTagName("*").length}),b.attributes=at(function(e){return e.className="i",!e.getAttribute("className")}),b.getElementsByClassName=at(function(e){return e.innerHTML="
",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),b.sortDetached=at(function(e){return 1&e.compareDocumentPosition(c.createElement("div"))}),b.getById=at(function(e){return f.appendChild(e).id=y,!t.getElementsByName||!t.getElementsByName(y).length}),b.getById?(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){return e.getAttribute("id")===t}}):(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n?n.id===e||typeof n.getAttributeNode!==j&&n.getAttributeNode("id").value===e?[n]:undefined:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),r.find.TAG=b.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==j?t.getElementsByTagName(e):undefined}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=b.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==j&&p?t.getElementsByClassName(e):undefined},d=[],h=[],(b.qsa=it(t.querySelectorAll))&&(at(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||h.push("\\["+R+"*(?:value|"+P+")"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){var t=c.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&h.push("[*^$]="+R+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(b.matchesSelector=it(g=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){b.disconnectedMatch=g.call(e,"div"),g.call(e,"[s!='']:x"),d.push("!=",B)}),h=h.length&&RegExp(h.join("|")),d=d.length&&RegExp(d.join("|")),m=it(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},S=f.compareDocumentPosition?function(e,n){if(e===n)return E=!0,0;var r=n.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(n);return r?1&r||!b.sortDetached&&n.compareDocumentPosition(e)===r?e===t||m(v,e)?-1:n===t||m(v,n)?1:u?F.call(u,e)-F.call(u,n):0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,n){var r,i=0,o=e.parentNode,s=n.parentNode,a=[e],l=[n];if(e===n)return E=!0,0;if(!o||!s)return e===t?-1:n===t?1:o?-1:s?1:u?F.call(u,e)-F.call(u,n):0;if(o===s)return lt(e,n);r=e;while(r=r.parentNode)a.unshift(r);r=n;while(r=r.parentNode)l.unshift(r);while(a[i]===l[i])i++;return i?lt(a[i],l[i]):a[i]===v?-1:l[i]===v?1:0},c):c},ut.matches=function(e,t){return ut(e,null,null,t)},ut.matchesSelector=function(e,t){if((e.ownerDocument||e)!==c&&l(e),t=t.replace(U,"='$1']"),!(!b.matchesSelector||!p||d&&d.test(t)||h&&h.test(t)))try{var n=g.call(e,t);if(n||b.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return ut(t,c,null,[e]).length>0},ut.contains=function(e,t){return(e.ownerDocument||e)!==c&&l(e),m(e,t)},ut.attr=function(e,t){(e.ownerDocument||e)!==c&&l(e);var n=r.attrHandle[t.toLowerCase()],i=n&&n(e,t,!p);return i===undefined?b.attributes||!p?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null:i},ut.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},ut.uniqueSort=function(e){var t,n=[],r=0,i=0;if(E=!b.detectDuplicates,u=!b.sortStable&&e.slice(0),e.sort(S),E){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return e};function lt(e,t){var n=t&&e,r=n&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ct(e,t,n){var r;return n?undefined:(r=e.getAttributeNode(t))&&r.specified?r.value:e[t]===!0?t.toLowerCase():null}function ft(e,t,n){var r;return n?undefined:r=e.getAttribute(t,"type"===t.toLowerCase()?1:2)}function pt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ht(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function dt(e){return st(function(t){return t=+t,st(function(n,r){var i,o=e([],n.length,t),s=o.length;while(s--)n[i=o[s]]&&(n[i]=!(r[i]=n[i]))})})}i=ut.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[r];r++)n+=i(t);return n},r=ut.selectors={cacheLength:50,createPseudo:st,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(tt,nt),e[3]=(e[4]||e[5]||"").replace(tt,nt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ut.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ut.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return G.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&Y.test(n)&&(t=gt(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(tt,nt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=C[e+" "];return t||(t=RegExp("(^|"+R+")"+e+"("+R+"|$)"))&&C(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=ut.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,h,d,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),x=!u&&!a;if(m){if(o){while(g){f=t;while(f=f[g])if(a?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;d=g="only"===e&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&x){c=m[y]||(m[y]={}),l=c[e]||[],h=l[0]===w&&l[1],p=l[0]===w&&l[2],f=h&&m.childNodes[h];while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if(1===f.nodeType&&++p&&f===t){c[e]=[w,h,p];break}}else if(x&&(l=(t[y]||(t[y]={}))[e])&&l[0]===w)p=l[1];else while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if((a?f.nodeName.toLowerCase()===v:1===f.nodeType)&&++p&&(x&&((f[y]||(f[y]={}))[e]=[w,p]),f===t))break;return p-=i,p===r||0===p%r&&p/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||ut.error("unsupported pseudo: "+e);return i[y]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?st(function(e,n){var r,o=i(e,t),s=o.length;while(s--)r=F.call(e,o[s]),e[r]=!(n[r]=o[s])}):function(e){return i(e,0,n)}):i}},pseudos:{not:st(function(e){var t=[],n=[],r=s(e.replace(I,"$1"));return r[y]?st(function(e,t,n,i){var o,s=r(e,null,i,[]),a=e.length;while(a--)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:st(function(e){return function(t){return ut(e,t).length>0}}),contains:st(function(e){return function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:st(function(e){return V.test(e||"")||ut.error("unsupported lang: "+e),e=e.replace(tt,nt).toLowerCase(),function(t){var n;do if(n=p?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===c.activeElement&&(!c.hasFocus||c.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Z.test(e.nodeName)},input:function(e){return K.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:dt(function(){return[0]}),last:dt(function(e,t){return[t-1]}),eq:dt(function(e,t,n){return[0>n?n+t:n]}),even:dt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:dt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:dt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:dt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=pt(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=ht(t);function gt(e,t){var n,i,o,s,a,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);a=e,u=[],l=r.preFilter;while(a){(!n||(i=z.exec(a)))&&(i&&(a=a.slice(i[0].length)||a),u.push(o=[])),n=!1,(i=_.exec(a))&&(n=i.shift(),o.push({value:n,type:i[0].replace(I," ")}),a=a.slice(n.length));for(s in r.filter)!(i=G[s].exec(a))||l[s]&&!(i=l[s](i))||(n=i.shift(),o.push({value:n,type:s,matches:i}),a=a.slice(n.length));if(!n)break}return t?a.length:a?ut.error(e):k(e,u).slice(0)}function mt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function yt(e,t,r){var i=t.dir,o=r&&"parentNode"===i,s=T++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,r,a){var u,l,c,f=w+" "+s;if(a){while(t=t[i])if((1===t.nodeType||o)&&e(t,r,a))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[y]||(t[y]={}),(l=c[i])&&l[0]===f){if((u=l[1])===!0||u===n)return u===!0}else if(l=c[i]=[f],l[1]=e(t,r,a)||n,l[1]===!0)return!0}}function vt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,s=[],a=0,u=e.length,l=null!=t;for(;u>a;a++)(o=e[a])&&(!n||n(o,r,i))&&(s.push(o),l&&t.push(a));return s}function bt(e,t,n,r,i,o){return r&&!r[y]&&(r=bt(r)),i&&!i[y]&&(i=bt(i,o)),st(function(o,s,a,u){var l,c,f,p=[],h=[],d=s.length,g=o||Ct(t||"*",a.nodeType?[a]:a,[]),m=!e||!o&&t?g:xt(g,p,e,a,u),y=n?i||(o?e:d||r)?[]:s:m;if(n&&n(m,y,a,u),r){l=xt(y,h),r(l,[],a,u),c=l.length;while(c--)(f=l[c])&&(y[h[c]]=!(m[h[c]]=f))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(f=y[c])&&l.push(m[c]=f);i(null,y=[],l,u)}c=y.length;while(c--)(f=y[c])&&(l=i?F.call(o,f):p[c])>-1&&(o[l]=!(s[l]=f))}}else y=xt(y===s?y.splice(d,y.length):y),i?i(null,s,y,u):H.apply(s,y)})}function wt(e){var t,n,i,o=e.length,s=r.relative[e[0].type],u=s||r.relative[" "],l=s?1:0,c=yt(function(e){return e===t},u,!0),f=yt(function(e){return F.call(t,e)>-1},u,!0),p=[function(e,n,r){return!s&&(r||n!==a)||((t=n).nodeType?c(e,n,r):f(e,n,r))}];for(;o>l;l++)if(n=r.relative[e[l].type])p=[yt(vt(p),n)];else{if(n=r.filter[e[l].type].apply(null,e[l].matches),n[y]){for(i=++l;o>i;i++)if(r.relative[e[i].type])break;return bt(l>1&&vt(p),l>1&&mt(e.slice(0,l-1)).replace(I,"$1"),n,i>l&&wt(e.slice(l,i)),o>i&&wt(e=e.slice(i)),o>i&&mt(e))}p.push(n)}return vt(p)}function Tt(e,t){var i=0,o=t.length>0,s=e.length>0,u=function(u,l,f,p,h){var d,g,m,y=[],v=0,x="0",b=u&&[],T=null!=h,C=a,k=u||s&&r.find.TAG("*",h&&l.parentNode||l),N=w+=null==C?1:Math.random()||.1;for(T&&(a=l!==c&&l,n=i);null!=(d=k[x]);x++){if(s&&d){g=0;while(m=e[g++])if(m(d,l,f)){p.push(d);break}T&&(w=N,n=++i)}o&&((d=!m&&d)&&v--,u&&b.push(d))}if(v+=x,o&&x!==v){g=0;while(m=t[g++])m(b,y,l,f);if(u){if(v>0)while(x--)b[x]||y[x]||(y[x]=L.call(p));y=xt(y)}H.apply(p,y),T&&!u&&y.length>0&&v+t.length>1&&ut.uniqueSort(p)}return T&&(w=N,a=C),b};return o?st(u):u}s=ut.compile=function(e,t){var n,r=[],i=[],o=N[e+" "];if(!o){t||(t=gt(e)),n=t.length;while(n--)o=wt(t[n]),o[y]?r.push(o):i.push(o);o=N(e,Tt(i,r))}return o};function Ct(e,t,n){var r=0,i=t.length;for(;i>r;r++)ut(e,t[r],n);return n}function kt(e,t,n,i){var o,a,u,l,c,f=gt(e);if(!i&&1===f.length){if(a=f[0]=f[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&p&&r.relative[a[1].type]){if(t=(r.find.ID(u.matches[0].replace(tt,nt),t)||[])[0],!t)return n;e=e.slice(a.shift().value.length)}o=G.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],r.relative[l=u.type])break;if((c=r.find[l])&&(i=c(u.matches[0].replace(tt,nt),X.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=i.length&&mt(a),!e)return H.apply(n,i),n;break}}}return s(e,f)(i,t,!p,n,X.test(e)),n}r.pseudos.nth=r.pseudos.eq;function Nt(){}Nt.prototype=r.filters=r.pseudos,r.setFilters=new Nt,b.sortStable=y.split("").sort(S).join("")===y,l(),[0,0].sort(S),b.detectDuplicates=E,at(function(e){if(e.innerHTML="","#"!==e.firstChild.getAttribute("href")){var t="type|href|height|width".split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ft}}),at(function(e){if(null!=e.getAttribute("disabled")){var t=P.split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ct}}),x.find=ut,x.expr=ut.selectors,x.expr[":"]=x.expr.pseudos,x.unique=ut.uniqueSort,x.text=ut.getText,x.isXMLDoc=ut.isXML,x.contains=ut.contains}(e);var D={};function A(e){var t=D[e]={};return x.each(e.match(w)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?D[e]||A(e):x.extend({},e);var t,n,r,i,o,s,a=[],u=!e.once&&[],l=function(f){for(t=e.memory&&f,n=!0,s=i||0,i=0,o=a.length,r=!0;a&&o>s;s++)if(a[s].apply(f[0],f[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,a&&(u?u.length&&l(u.shift()):t?a=[]:c.disable())},c={add:function(){if(a){var n=a.length;(function s(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&c.has(n)||a.push(n):n&&n.length&&"string"!==r&&s(n)})})(arguments),r?o=a.length:t&&(i=n,l(t))}return this},remove:function(){return a&&x.each(arguments,function(e,t){var n;while((n=x.inArray(t,a,n))>-1)a.splice(n,1),r&&(o>=n&&o--,s>=n&&s--)}),this},has:function(e){return e?x.inArray(e,a)>-1:!(!a||!a.length)},empty:function(){return a=[],o=0,this},disable:function(){return a=u=t=undefined,this},disabled:function(){return!a},lock:function(){return u=undefined,t||c.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!a||n&&!u||(r?u.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!n}};return c},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var s=o[0],a=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=s.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=d.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),s=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?d.call(arguments):r,n===a?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},a,u,l;if(r>1)for(a=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(s(t,l,n)).fail(o.reject).progress(s(t,u,a)):--i;return i||o.resolveWith(l,n),o.promise()}}),x.support=function(t){var n=o.createElement("input"),r=o.createDocumentFragment(),i=o.createElement("div"),s=o.createElement("select"),a=s.appendChild(o.createElement("option"));return n.type?(n.type="checkbox",t.checkOn=""!==n.value,t.optSelected=a.selected,t.reliableMarginRight=!0,t.boxSizingReliable=!0,t.pixelPosition=!1,n.checked=!0,t.noCloneChecked=n.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!a.disabled,n=o.createElement("input"),n.value="t",n.type="radio",t.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),r.appendChild(n),t.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,t.focusinBubbles="onfocusin"in e,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===i.style.backgroundClip,x(function(){var n,r,s="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",a=o.getElementsByTagName("body")[0];a&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(i),i.innerHTML="",i.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",x.swap(a,null!=a.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===i.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(i,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(i,null)||{width:"4px"}).width,r=i.appendChild(o.createElement("div")),r.style.cssText=i.style.cssText=s,r.style.marginRight=r.style.width="0",i.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),a.removeChild(n))}),t):t}({});var L,q,H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,O=/([A-Z])/g;function F(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=x.expando+Math.random()}F.uid=1,F.accepts=function(e){return e.nodeType?1===e.nodeType||9===e.nodeType:!0},F.prototype={key:function(e){if(!F.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=F.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,x.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(x.isEmptyObject(o))this.cache[i]=t;else for(r in t)o[r]=t[r]},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){return t===undefined||t&&"string"==typeof t&&n===undefined?this.get(e,t):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i=this.key(e),o=this.cache[i];if(t===undefined)this.cache[i]={};else{x.isArray(t)?r=t.concat(t.map(x.camelCase)):t in o?r=[t]:(r=x.camelCase(t),r=r in o?[r]:r.match(w)||[]),n=r.length;while(n--)delete o[r[n]]}},hasData:function(e){return!x.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){delete this.cache[this.key(e)]}},L=new F,q=new F,x.extend({acceptData:F.accepts,hasData:function(e){return L.hasData(e)||q.hasData(e)},data:function(e,t,n){return L.access(e,t,n)},removeData:function(e,t){L.remove(e,t)},_data:function(e,t,n){return q.access(e,t,n)},_removeData:function(e,t){q.remove(e,t)}}),x.fn.extend({data:function(e,t){var n,r,i=this[0],o=0,s=null;if(e===undefined){if(this.length&&(s=L.get(i),1===i.nodeType&&!q.get(i,"hasDataAttrs"))){for(n=i.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=x.camelCase(r.substring(5)),P(i,r,s[r]));q.set(i,"hasDataAttrs",!0)}return s}return"object"==typeof e?this.each(function(){L.set(this,e)}):x.access(this,function(t){var n,r=x.camelCase(e);if(i&&t===undefined){if(n=L.get(i,e),n!==undefined)return n;if(n=L.get(i,r),n!==undefined)return n;if(n=P(i,r,undefined),n!==undefined)return n}else this.each(function(){var n=L.get(this,r);L.set(this,r,t),-1!==e.indexOf("-")&&n!==undefined&&L.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){L.remove(this,e)})}});function P(e,t,n){var r;if(n===undefined&&1===e.nodeType)if(r="data-"+t.replace(O,"-$1").toLowerCase(),n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:H.test(n)?JSON.parse(n):n}catch(i){}L.set(e,t,n)}else n=undefined;return n}x.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=q.get(e,t),n&&(!r||x.isArray(n)?r=q.access(e,t,x.makeArray(n)):r.push(n)),r||[]):undefined},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),s=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return q.get(e,n)||q.access(e,n,{empty:x.Callbacks("once memory").add(function(){q.remove(e,[t+"queue",n])})})}}),x.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),n>arguments.length?x.queue(this[0],e):t===undefined?this:this.each(function(){var n=x.queue(this,e,t); x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,s=0,a=x(this),u=t,l=e.match(w)||[];while(o=l[s++])u=i?u:!a.hasClass(o),a[u?"addClass":"removeClass"](o)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i,o=x(this);1===this.nodeType&&(i=r?e.call(this,n,o.val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.boolean.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.boolean.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.boolean.source.match(/\w+/g),function(e,t){var n=x.expr.attrHandle[t]||x.find.attr;x.expr.attrHandle[t]=function(e,t,r){var i=x.expr.attrHandle[t],o=r?undefined:(x.expr.attrHandle[t]=undefined)!=n(e,t,r)?t.toLowerCase():null;return x.expr.attrHandle[t]=i,o}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,t){return x.isArray(t)?e.checked=x.inArray(x(e).val(),t)>=0:undefined}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var I=/^key/,z=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,X=/^([^.]*)(?:\.(.+)|)$/;function U(){return!0}function Y(){return!1}function V(){try{return o.activeElement}catch(e){}}x.event={global:{},add:function(e,t,n,i,o){var s,a,u,l,c,f,p,h,d,g,m,y=q.get(e);if(y){n.handler&&(s=n,n=s.handler,o=s.selector),n.guid||(n.guid=x.guid++),(l=y.events)||(l=y.events={}),(a=y.handle)||(a=y.handle=function(e){return typeof x===r||e&&x.event.triggered===e.type?undefined:x.event.dispatch.apply(a.elem,arguments)},a.elem=e),t=(t||"").match(w)||[""],c=t.length;while(c--)u=X.exec(t[c])||[],d=m=u[1],g=(u[2]||"").split(".").sort(),d&&(p=x.event.special[d]||{},d=(o?p.delegateType:p.bindType)||d,p=x.event.special[d]||{},f=x.extend({type:d,origType:m,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&x.expr.match.needsContext.test(o),namespace:g.join(".")},s),(h=l[d])||(h=l[d]=[],h.delegateCount=0,p.setup&&p.setup.call(e,i,g,a)!==!1||e.addEventListener&&e.addEventListener(d,a,!1)),p.add&&(p.add.call(e,f),f.handler.guid||(f.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,f):h.push(f),x.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,s,a,u,l,c,f,p,h,d,g,m=q.hasData(e)&&q.get(e);if(m&&(u=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(a=X.exec(t[l])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h){f=x.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,p=u[h]||[],a=a[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));s&&!p.length&&(f.teardown&&f.teardown.call(e,d,m.handle)!==!1||x.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)x.event.remove(e,h+t[l],n,r,!0);x.isEmptyObject(u)&&(delete m.handle,q.remove(e,"events"))}},trigger:function(t,n,r,i){var s,a,u,l,c,f,p,h=[r||o],d=y.call(t,"type")?t.type:t,g=y.call(t,"namespace")?t.namespace.split("."):[];if(a=u=r=r||o,3!==r.nodeType&&8!==r.nodeType&&!_.test(d+x.event.triggered)&&(d.indexOf(".")>=0&&(g=d.split("."),d=g.shift(),g.sort()),c=0>d.indexOf(":")&&"on"+d,t=t[x.expando]?t:new x.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=g.join("."),t.namespace_re=t.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=undefined,t.target||(t.target=r),n=null==n?[t]:x.makeArray(n,[t]),p=x.event.special[d]||{},i||!p.trigger||p.trigger.apply(r,n)!==!1)){if(!i&&!p.noBubble&&!x.isWindow(r)){for(l=p.delegateType||d,_.test(l+d)||(a=a.parentNode);a;a=a.parentNode)h.push(a),u=a;u===(r.ownerDocument||o)&&h.push(u.defaultView||u.parentWindow||e)}s=0;while((a=h[s++])&&!t.isPropagationStopped())t.type=s>1?l:p.bindType||d,f=(q.get(a,"events")||{})[t.type]&&q.get(a,"handle"),f&&f.apply(a,n),f=c&&a[c],f&&x.acceptData(a)&&f.apply&&f.apply(a,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||p._default&&p._default.apply(h.pop(),n)!==!1||!x.acceptData(r)||c&&x.isFunction(r[d])&&!x.isWindow(r)&&(u=r[c],u&&(r[c]=null),x.event.triggered=d,r[d](),x.event.triggered=undefined,u&&(r[c]=u)),t.result}},dispatch:function(e){e=x.event.fix(e);var t,n,r,i,o,s=[],a=d.call(arguments),u=(q.get(this,"events")||{})[e.type]||[],l=x.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),t=0;while((i=s[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((x.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,a),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,s=[],a=t.delegateCount,u=e.target;if(a&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!==this;u=u.parentNode||this)if(u.disabled!==!0||"click"!==e.type){for(r=[],n=0;a>n;n++)o=t[n],i=o.selector+" ",r[i]===undefined&&(r[i]=o.needsContext?x(i,this).index(u)>=0:x.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&s.push({elem:u,handlers:r})}return t.length>a&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,s=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||o,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||s===undefined||(e.which=1&s?1:2&s?3:4&s?2:0),e}},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=z.test(i)?this.mouseHooks:I.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return 3===e.target.nodeType&&(e.target=e.target.parentNode),s.filter?s.filter(e,o):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==V()&&this.focus?(this.focus(),!1):undefined},delegateType:"focusin"},blur:{trigger:function(){return this===V()&&this.blur?(this.blur(),!1):undefined},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&x.nodeName(this,"input")?(this.click(),!1):undefined},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},x.Event=function(e,t){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.getPreventDefault&&e.getPreventDefault()?U:Y):this.type=e,t&&x.extend(this,t),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,undefined):new x.Event(e,t)},x.Event.prototype={isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=U,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=U,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=U,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,t,n,r,i){var o,s;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=undefined);for(s in e)this.on(s,t,n,e[s],i);return this}if(null==n&&null==r?(r=t,n=t=undefined):null==r&&("string"==typeof t?(r=n,n=undefined):(r=n,n=t,t=undefined)),r===!1)r=Y;else if(!r)return this;return 1===i&&(o=r,r=function(e){return x().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=x.guid++)),this.each(function(){x.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,x(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=undefined),n===!1&&(n=Y),this.each(function(){x.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?x.event.trigger(e,t,n,!0):undefined}});var G=/^.[^:#\[\.,]*$/,J=x.expr.match.needsContext,Q={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return t=this,this.pushStack(x(e).filter(function(){for(r=0;i>r;r++)if(x.contains(t[r],this))return!0}));for(n=[],r=0;i>r;r++)x.find(e,this[r],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t=x(e,this),n=t.length;return this.filter(function(){var e=0;for(;n>e;e++)if(x.contains(this,t[e]))return!0})},not:function(e){return this.pushStack(Z(this,e||[],!0))},filter:function(e){return this.pushStack(Z(this,e||[],!1))},is:function(e){return!!e&&("string"==typeof e?J.test(e)?x(e,this.context).index(this[0])>=0:x.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],s=J.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(s?s.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?g.call(x(e),this[0]):g.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function K(e,t){while((e=e[t])&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return K(e,"nextSibling")},prev:function(e){return K(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(Q[e]||x.unique(i),"p"===e[0]&&i.reverse()),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&x(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function Z(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(G.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return g.call(t,e)>=0!==n})}var et=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,tt=/<([\w:]+)/,nt=/<|&#?\w+;/,rt=/<(?:script|style|link)/i,it=/^(?:checkbox|radio)$/i,ot=/checked\s*(?:[^=]|=\s*.checked.)/i,st=/^$|\/(?:java|ecma)script/i,at=/^true\/(.*)/,ut=/^\s*\s*$/g,lt={option:[1,""],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};lt.optgroup=lt.option,lt.tbody=lt.tfoot=lt.colgroup=lt.caption=lt.col=lt.thead,lt.th=lt.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===undefined?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(gt(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&ht(gt(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++)1===e.nodeType&&(x.cleanData(gt(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!rt.test(e)&&!lt[(tt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(et,"<$1>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(x.cleanData(gt(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=p.apply([],e);var r,i,o,s,a,u,l=0,c=this.length,f=this,h=c-1,d=e[0],g=x.isFunction(d);if(g||!(1>=c||"string"!=typeof d||x.support.checkClone)&&ot.test(d))return this.each(function(r){var i=f.eq(r);g&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(r=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),i=r.firstChild,1===r.childNodes.length&&(r=i),i)){for(o=x.map(gt(r,"script"),ft),s=o.length;c>l;l++)a=r,l!==h&&(a=x.clone(a,!0,!0),s&&x.merge(o,gt(a,"script"))),t.call(this[l],a,l);if(s)for(u=o[o.length-1].ownerDocument,x.map(o,pt),l=0;s>l;l++)a=o[l],st.test(a.type||"")&&!q.access(a,"globalEval")&&x.contains(u,a)&&(a.src?x._evalUrl(a.src):x.globalEval(a.textContent.replace(ut,"")))}return this}}),x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=[],i=x(e),o=i.length-1,s=0;for(;o>=s;s++)n=s===o?this:this.clone(!0),x(i[s])[t](n),h.apply(r,n.get());return this.pushStack(r)}}),x.extend({clone:function(e,t,n){var r,i,o,s,a=e.cloneNode(!0),u=x.contains(e.ownerDocument,e);if(!(x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(s=gt(a),o=gt(e),r=0,i=o.length;i>r;r++)mt(o[r],s[r]);if(t)if(n)for(o=o||gt(e),s=s||gt(a),r=0,i=o.length;i>r;r++)dt(o[r],s[r]);else dt(e,a);return s=gt(a,"script"),s.length>0&&ht(s,!u&>(e,"script")),a},buildFragment:function(e,t,n,r){var i,o,s,a,u,l,c=0,f=e.length,p=t.createDocumentFragment(),h=[];for(;f>c;c++)if(i=e[c],i||0===i)if("object"===x.type(i))x.merge(h,i.nodeType?[i]:i);else if(nt.test(i)){o=o||p.appendChild(t.createElement("div")),s=(tt.exec(i)||["",""])[1].toLowerCase(),a=lt[s]||lt._default,o.innerHTML=a[1]+i.replace(et,"<$1>")+a[2],l=a[0];while(l--)o=o.firstChild;x.merge(h,o.childNodes),o=p.firstChild,o.textContent=""}else h.push(t.createTextNode(i));p.textContent="",c=0;while(i=h[c++])if((!r||-1===x.inArray(i,r))&&(u=x.contains(i.ownerDocument,i),o=gt(p.appendChild(i),"script"),u&&ht(o),n)){l=0;while(i=o[l++])st.test(i.type||"")&&n.push(i)}return p},cleanData:function(e){var t,n,r,i=e.length,o=0,s=x.event.special;for(;i>o;o++){if(n=e[o],x.acceptData(n)&&(t=q.access(n)))for(r in t.events)s[r]?x.event.remove(n,r):x.removeEvent(n,r,t.handle);L.discard(n),q.discard(n)}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"text",async:!1,global:!1,success:x.globalEval})}});function ct(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function pt(e){var t=at.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function ht(e,t){var n=e.length,r=0;for(;n>r;r++)q.set(e[r],"globalEval",!t||q.get(t[r],"globalEval"))}function dt(e,t){var n,r,i,o,s,a,u,l;if(1===t.nodeType){if(q.hasData(e)&&(o=q.access(e),s=x.extend({},o),l=o.events,q.set(t,s),l)){delete s.handle,s.events={};for(i in l)for(n=0,r=l[i].length;r>n;n++)x.event.add(t,i,l[i][n])}L.hasData(e)&&(a=L.access(e),u=x.extend({},a),L.set(t,u))}}function gt(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&x.nodeName(e,t)?x.merge([e],n):n}function mt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&it.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}x.fn.extend({wrapAll:function(e){var t;return x.isFunction(e)?this.each(function(t){x(this).wrapAll(e.call(this,t))}):(this[0]&&(t=x(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var yt,vt,xt=/^(none|table(?!-c[ea]).+)/,bt=/^margin/,wt=RegExp("^("+b+")(.*)$","i"),Tt=RegExp("^("+b+")(?!px)[a-z%]+$","i"),Ct=RegExp("^([+-])=("+b+")","i"),kt={BODY:"block"},Nt={position:"absolute",visibility:"hidden",display:"block"},Et={letterSpacing:0,fontWeight:400},St=["Top","Right","Bottom","Left"],jt=["Webkit","O","Moz","ms"];function Dt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=jt.length;while(i--)if(t=jt[i]+n,t in e)return t;return r}function At(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function Lt(t){return e.getComputedStyle(t,null)}function qt(e,t){var n,r,i,o=[],s=0,a=e.length;for(;a>s;s++)r=e[s],r.style&&(o[s]=q.get(r,"olddisplay"),n=r.style.display,t?(o[s]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[s]=q.access(r,"olddisplay",Pt(r.nodeName)))):o[s]||(i=At(r),(n&&"none"!==n||!i)&&q.set(r,"olddisplay",i?n:x.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}x.fn.extend({css:function(e,t){return x.access(this,function(e,t,n){var r,i,o={},s=0;if(x.isArray(t)){for(r=Lt(e),i=t.length;i>s;s++)o[t[s]]=x.css(e,t[s],!1,r);return o}return n!==undefined?x.style(e,t,n):x.css(e,t)},e,t,arguments.length>1)},show:function(){return qt(this,!0)},hide:function(){return qt(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:At(this))?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=yt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=x.camelCase(t),u=e.style;return t=x.cssProps[a]||(x.cssProps[a]=Dt(u,a)),s=x.cssHooks[t]||x.cssHooks[a],n===undefined?s&&"get"in s&&(i=s.get(e,!1,r))!==undefined?i:u[t]:(o=typeof n,"string"===o&&(i=Ct.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(x.css(e,t)),o="number"),null==n||"number"===o&&isNaN(n)||("number"!==o||x.cssNumber[a]||(n+="px"),x.support.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),s&&"set"in s&&(n=s.set(e,n,r))===undefined||(u[t]=n)),undefined)}},css:function(e,t,n,r){var i,o,s,a=x.camelCase(t);return t=x.cssProps[a]||(x.cssProps[a]=Dt(e.style,a)),s=x.cssHooks[t]||x.cssHooks[a],s&&"get"in s&&(i=s.get(e,!0,n)),i===undefined&&(i=yt(e,t,r)),"normal"===i&&t in Et&&(i=Et[t]),""===n||n?(o=parseFloat(i),n===!0||x.isNumeric(o)?o||0:i):i}}),yt=function(e,t,n){var r,i,o,s=n||Lt(e),a=s?s.getPropertyValue(t)||s[t]:undefined,u=e.style;return s&&(""!==a||x.contains(e.ownerDocument,e)||(a=x.style(e,t)),Tt.test(a)&&bt.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=s.width,u.width=r,u.minWidth=i,u.maxWidth=o)),a};function Ht(e,t,n){var r=wt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function Ot(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,s=0;for(;4>o;o+=2)"margin"===n&&(s+=x.css(e,n+St[o],!0,i)),r?("content"===n&&(s-=x.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(s-=x.css(e,"border"+St[o]+"Width",!0,i))):(s+=x.css(e,"padding"+St[o],!0,i),"padding"!==n&&(s+=x.css(e,"border"+St[o]+"Width",!0,i)));return s}function Ft(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Lt(e),s=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=yt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Tt.test(i))return i;r=s&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+Ot(e,t,n||(s?"border":"content"),r,o)+"px"}function Pt(e){var t=o,n=kt[e];return n||(n=Rt(e,t),"none"!==n&&n||(vt=(vt||x("',l=r.firstChild,n.appendChild(l),o.addEvent(l,"load",function(){var n;try{n=l.contentWindow.document||l.contentDocument||window.frames[l.id].document,/^4(0[0-9]|1[0-7]|2[2346])\s/.test(n.title)?u=n.title.replace(/^(\d+).*$/,"$1"):(u=200,c=t.trim(n.body.innerHTML),p.trigger({type:"progress",loaded:c.length,total:c.length}),w&&p.trigger({type:"uploadprogress",loaded:w.size||1025,total:w.size||1025}))}catch(r){if(!i.hasSameOrigin(d.url))return void e.call(p,function(){p.trigger("error")});u=404}e.call(p,function(){p.trigger("load")})},p.uid)}var p=this,m=p.getRuntime(),g,v,y,w;if(u=c=null,f instanceof s&&f.hasBlob()){if(w=f.getBlob(),g=w.uid,y=n.get(g),v=n.get(g+"_form"),!v)throw new r.DOMException(r.DOMException.NOT_FOUND_ERR)}else g=t.guid("uid_"),v=document.createElement("form"),v.setAttribute("id",g+"_form"),v.setAttribute("method",d.method),v.setAttribute("enctype","multipart/form-data"),v.setAttribute("encoding","multipart/form-data"),v.setAttribute("target",g+"_iframe"),m.getShimContainer().appendChild(v);f instanceof s&&f.each(function(e,n){if(e instanceof a)y&&y.setAttribute("name",n);else{var i=document.createElement("input");t.extend(i,{type:"hidden",name:n,value:e}),y?v.insertBefore(i,y):v.appendChild(i)}}),v.setAttribute("action",d.url),h(),v.submit(),p.trigger("loadstart")},getStatus:function(){return u},getResponse:function(e){if("json"===e&&"string"===t.typeOf(c)&&window.JSON)try{return JSON.parse(c.replace(/^\s*]*>/,"").replace(/<\/pre>\s*$/,""))}catch(n){return null}return c},abort:function(){var t=this;l&&l.contentWindow&&(l.contentWindow.stop?l.contentWindow.stop():l.contentWindow.document.execCommand?l.contentWindow.document.execCommand("Stop"):l.src="about:blank"),e.call(this,function(){t.dispatchEvent("abort")})}})}return e.XMLHttpRequest=u}),i(ft,[ut,X],function(e,t){return e.Image=t}),a([u,c,l,d,f,h,p,m,g,v,y,w,E,_,x,b,R,T,A,S,O,I,L])}(this);;(function(e){"use strict";var t={},n=e.moxie.core.utils.Basic.inArray;return function r(e){var i,s;for(i in e)s=typeof e[i],s==="object"&&!~n(i,["Exceptions","Env","Mime"])?r(e[i]):s==="function"&&(t[i]=e[i])}(e.moxie),t.Env=e.moxie.core.utils.Env,t.Mime=e.moxie.core.utils.Mime,t.Exceptions=e.moxie.core.Exceptions,e.mOxie=t,e.o||(e.o=t),t})(this); /** * Plupload - multi-runtime File Uploader * v2.1.2 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2014-05-14 */ ;(function(e,t,n){function s(e){function r(e,t,r){var i={chunks:"slice_blob",jpgresize:"send_binary_string",pngresize:"send_binary_string",progress:"report_upload_progress",multi_selection:"select_multiple",dragdrop:"drag_and_drop",drop_element:"drag_and_drop",headers:"send_custom_headers",urlstream_upload:"send_binary_string",canSendBinary:"send_binary",triggerDialog:"summon_file_dialog"};i[e]?n[i[e]]=t:r||(n[e]=t)}var t=e.required_features,n={};if(typeof t=="string")o.each(t.split(/\s*,\s*/),function(e){r(e,!0)});else if(typeof t=="object")o.each(t,function(e,t){r(t,e)});else if(t===!0){e.chunk_size>0&&(n.slice_blob=!0);if(e.resize.enabled||!e.multipart)n.send_binary_string=!0;o.each(e,function(e,t){r(t,!!e,!0)})}return n}var r=e.setTimeout,i={},o={VERSION:"2.1.2",STOPPED:1,STARTED:2,QUEUED:1,UPLOADING:2,FAILED:4,DONE:5,GENERIC_ERROR:-100,HTTP_ERROR:-200,IO_ERROR:-300,SECURITY_ERROR:-400,INIT_ERROR:-500,FILE_SIZE_ERROR:-600,FILE_EXTENSION_ERROR:-601,FILE_DUPLICATE_ERROR:-602,IMAGE_FORMAT_ERROR:-700,MEMORY_ERROR:-701,IMAGE_DIMENSIONS_ERROR:-702,mimeTypes:t.mimes,ua:t.ua,typeOf:t.typeOf,extend:t.extend,guid:t.guid,get:function(n){var r=[],i;t.typeOf(n)!=="array"&&(n=[n]);var s=n.length;while(s--)i=t.get(n[s]),i&&r.push(i);return r.length?r:null},each:t.each,getPos:t.getPos,getSize:t.getSize,xmlEncode:function(e){var t={"<":"lt",">":"gt","&":"amp",'"':"quot","'":"#39"},n=/[<>&\"\']/g;return e?(""+e).replace(n,function(e){return t[e]?"&"+t[e]+";":e}):e},toArray:t.toArray,inArray:t.inArray,addI18n:t.addI18n,translate:t.translate,isEmptyObj:t.isEmptyObj,hasClass:t.hasClass,addClass:t.addClass,removeClass:t.removeClass,getStyle:t.getStyle,addEvent:t.addEvent,removeEvent:t.removeEvent,removeAllEvents:t.removeAllEvents,cleanName:function(e){var t,n;n=[/[\300-\306]/g,"A",/[\340-\346]/g,"a",/\307/g,"C",/\347/g,"c",/[\310-\313]/g,"E",/[\350-\353]/g,"e",/[\314-\317]/g,"I",/[\354-\357]/g,"i",/\321/g,"N",/\361/g,"n",/[\322-\330]/g,"O",/[\362-\370]/g,"o",/[\331-\334]/g,"U",/[\371-\374]/g,"u"];for(t=0;t0?"&":"?")+n),e},formatSize:function(e){function t(e,t){return Math.round(e*Math.pow(10,t))/Math.pow(10,t)}if(e===n||/\D/.test(e))return o.translate("N/A");var r=Math.pow(1024,4);return e>r?t(e/r,1)+" "+o.translate("tb"):e>(r/=1024)?t(e/r,1)+" "+o.translate("gb"):e>(r/=1024)?t(e/r,1)+" "+o.translate("mb"):e>1024?Math.round(e/1024)+" "+o.translate("kb"):e+" "+o.translate("b")},parseSize:t.parseSizeStr,predictRuntime:function(e,n){var r,i;return r=new o.Uploader(e),i=t.Runtime.thatCan(r.getOption().required_features,n||e.runtimes),r.destroy(),i},addFileFilter:function(e,t){i[e]=t}};o.addFileFilter("mime_types",function(e,t,n){e.length&&!e.regexp.test(t.name)?(this.trigger("Error",{code:o.FILE_EXTENSION_ERROR,message:o.translate("File extension error."),file:t}),n(!1)):n(!0)}),o.addFileFilter("max_file_size",function(e,t,n){var r;e=o.parseSize(e),t.size!==r&&e&&t.size>e?(this.trigger("Error",{code:o.FILE_SIZE_ERROR,message:o.translate("File size error."),file:t}),n(!1)):n(!0)}),o.addFileFilter("prevent_duplicates",function(e,t,n){if(e){var r=this.files.length;while(r--)if(t.name===this.files[r].name&&t.size===this.files[r].size){this.trigger("Error",{code:o.FILE_DUPLICATE_ERROR,message:o.translate("Duplicate file error."),file:t}),n(!1);return}}n(!0)}),o.Uploader=function(e){function g(){var e,t=0,n;if(this.state==o.STARTED){for(n=0;n0?Math.ceil(e.loaded/e.size*100):100,b()}function b(){var e,t;d.reset();for(e=0;e0?Math.ceil(d.uploaded/f.length*100):0:(d.bytesPerSec=Math.ceil(d.loaded/((+(new Date)-p||1)/1e3)),d.percent=d.size>0?Math.ceil(d.loaded/d.size*100):0)}function w(){var e=c[0]||h[0];return e?e.getRuntime().uid:!1}function E(e,n){if(e.ruid){var r=t.Runtime.getInfo(e.ruid);if(r)return r.can(n)}return!1}function S(){this.bind("FilesAdded FilesRemoved",function(e){e.trigger("QueueChanged"),e.refresh()}),this.bind("CancelUpload",O),this.bind("BeforeUpload",C),this.bind("UploadFile",k),this.bind("UploadProgress",L),this.bind("StateChanged",A),this.bind("QueueChanged",b),this.bind("Error",_),this.bind("FileUploaded",M),this.bind("Destroy",D)}function x(e,n){var r=this,i=0,s=[],u={runtime_order:e.runtimes,required_caps:e.required_features,preferred_caps:l,swf_url:e.flash_swf_url,xap_url:e.silverlight_xap_url};o.each(e.runtimes.split(/\s*,\s*/),function(t){e[t]&&(u[t]=e[t])}),e.browse_button&&o.each(e.browse_button,function(n){s.push(function(s){var a=new t.FileInput(o.extend({},u,{accept:e.filters.mime_types,name:e.file_data_name,multiple:e.multi_selection,container:e.container,browse_button:n}));a.onready=function(){var e=t.Runtime.getInfo(this.ruid);t.extend(r.features,{chunks:e.can("slice_blob"),multipart:e.can("send_multipart"),multi_selection:e.can("select_multiple")}),i++,c.push(this),s()},a.onchange=function(){r.addFile(this.files)},a.bind("mouseenter mouseleave mousedown mouseup",function(r){v||(e.browse_button_hover&&("mouseenter"===r.type?t.addClass(n,e.browse_button_hover):"mouseleave"===r.type&&t.removeClass(n,e.browse_button_hover)),e.browse_button_active&&("mousedown"===r.type?t.addClass(n,e.browse_button_active):"mouseup"===r.type&&t.removeClass(n,e.browse_button_active)))}),a.bind("mousedown",function(){r.trigger("Browse")}),a.bind("error runtimeerror",function(){a=null,s()}),a.init()})}),e.drop_element&&o.each(e.drop_element,function(e){s.push(function(n){var s=new t.FileDrop(o.extend({},u,{drop_zone:e}));s.onready=function(){var e=t.Runtime.getInfo(this.ruid);r.features.dragdrop=e.can("drag_and_drop"),i++,h.push(this),n()},s.ondrop=function(){r.addFile(this.files)},s.bind("error runtimeerror",function(){s=null,n()}),s.init()})}),t.inSeries(s,function(){typeof n=="function"&&n(i)})}function T(e,r,i){var s=new t.Image;try{s.onload=function(){if(r.width>this.width&&r.height>this.height&&r.quality===n&&r.preserve_headers&&!r.crop)return this.destroy(),i(e);s.downsize(r.width,r.height,r.crop,r.preserve_headers)},s.onresize=function(){i(this.getAsBlob(e.type,r.quality)),this.destroy()},s.onerror=function(){i(e)},s.load(e)}catch(o){i(e)}}function N(e,n,r){function f(e,t,n){var r=a[e];switch(e){case"max_file_size":e==="max_file_size"&&(a.max_file_size=a.filters.max_file_size=t);break;case"chunk_size":if(t=o.parseSize(t))a[e]=t,a.send_file_name=!0;break;case"multipart":a[e]=t,t||(a.send_file_name=!0);break;case"unique_names":a[e]=t,t&&(a.send_file_name=!0);break;case"filters":o.typeOf(t)==="array"&&(t={mime_types:t}),n?o.extend(a.filters,t):a.filters=t,t.mime_types&&(a.filters.mime_types.regexp=function(e){var t=[];return o.each(e,function(e){o.each(e.extensions.split(/,/),function(e){/^\s*\*\s*$/.test(e)?t.push("\\.*"):t.push("\\."+e.replace(new RegExp("["+"/^$.*+?|()[]{}\\".replace(/./g,"\\$&")+"]","g"),"\\$&"))})}),new RegExp("("+t.join("|")+")$","i")}(a.filters.mime_types));break;case"resize":n?o.extend(a.resize,t,{enabled:!0}):a.resize=t;break;case"prevent_duplicates":a.prevent_duplicates=a.filters.prevent_duplicates=!!t;break;case"browse_button":case"drop_element":t=o.get(t);case"container":case"runtimes":case"multi_selection":case"flash_swf_url":case"silverlight_xap_url":a[e]=t,n||(u=!0);break;default:a[e]=t}n||i.trigger("OptionChanged",e,t,r)}var i=this,u=!1;typeof e=="object"?o.each(e,function(e,t){f(t,e,r)}):f(e,n,r),r?(a.required_features=s(o.extend({},a)),l=s(o.extend({},a,{required_features:!0}))):u&&(i.trigger("Destroy"),x.call(i,a,function(e){e?(i.runtime=t.Runtime.getInfo(w()).type,i.trigger("Init",{runtime:i.runtime}),i.trigger("PostInit")):i.trigger("Error",{code:o.INIT_ERROR,message:o.translate("Init error.")})}))}function C(e,t){if(e.settings.unique_names){var n=t.name.match(/\.([^.]+)$/),r="part";n&&(r=n[1]),t.target_name=t.id+"."+r}}function k(e,n){function h(){u-->0?r(p,1e3):(n.loaded=f,e.trigger("Error",{code:o.HTTP_ERROR,message:o.translate("HTTP Error."),file:n,response:m.responseText,status:m.status,responseHeaders:m.getAllResponseHeaders()}))}function p(){var d,v,g={},y;if(n.status!==o.UPLOADING||e.state===o.STOPPED)return;e.settings.send_file_name&&(g.name=n.target_name||n.name),s&&a.chunks&&c.size>s?(y=Math.min(s,c.size-f),d=c.slice(f,f+y)):(y=c.size,d=c),s&&a.chunks&&(e.settings.send_chunk_number?(g.chunk=Math.ceil(f/s),g.chunks=Math.ceil(c.size/s)):(g.offset=f,g.total=c.size)),m=new t.XMLHttpRequest,m.upload&&(m.upload.onprogress=function(t){n.loaded=Math.min(n.size,f+t.loaded),e.trigger("UploadProgress",n)}),m.onload=function(){if(m.status>=400){h();return}u=e.settings.max_retries,y=c.size?(n.size!=n.origSize&&(c.destroy(),c=null),e.trigger("UploadProgress",n),n.status=o.DONE,e.trigger("FileUploaded",n,{response:m.responseText,status:m.status,responseHeaders:m.getAllResponseHeaders()})):r(p,1)},m.onerror=function(){h()},m.onloadend=function(){this.destroy(),m=null},e.settings.multipart&&a.multipart?(m.open("post",i,!0),o.each(e.settings.headers,function(e,t){m.setRequestHeader(t,e)}),v=new t.FormData,o.each(o.extend(g,e.settings.multipart_params),function(e,t){v.append(t,e)}),v.append(e.settings.file_data_name,d),m.send(v,{runtime_order:e.settings.runtimes,required_caps:e.settings.required_features,preferred_caps:l,swf_url:e.settings.flash_swf_url,xap_url:e.settings.silverlight_xap_url})):(i=o.buildUrl(e.settings.url,o.extend(g,e.settings.multipart_params)),m.open("post",i,!0),m.setRequestHeader("Content-Type","application/octet-stream"),o.each(e.settings.headers,function(e,t){m.setRequestHeader(t,e)}),m.send(d,{runtime_order:e.settings.runtimes,required_caps:e.settings.required_features,preferred_caps:l,swf_url:e.settings.flash_swf_url,xap_url:e.settings.silverlight_xap_url}))}var i=e.settings.url,s=e.settings.chunk_size,u=e.settings.max_retries,a=e.features,f=0,c;n.loaded&&(f=n.loaded=s?s*Math.floor(n.loaded/s):0),c=n.getSource(),e.settings.resize.enabled&&E(c,"send_binary_string")&&!!~t.inArray(c.type,["image/jpeg","image/png"])?T.call(this,c,e.settings.resize,function(e){c=e,n.size=e.size,p()}):p()}function L(e,t){y(t)}function A(e){if(e.state==o.STARTED)p=+(new Date);else if(e.state==o.STOPPED)for(var t=e.files.length-1;t>=0;t--)e.files[t].status==o.UPLOADING&&(e.files[t].status=o.QUEUED,b())}function O(){m&&m.abort()}function M(e){b(),r(function(){g.call(e)},1)}function _(e,t){t.code===o.INIT_ERROR?e.destroy():t.file&&(t.file.status=o.FAILED,y(t.file),e.state==o.STARTED&&(e.trigger("CancelUpload"),r(function(){g.call(e)},1)))}function D(e){e.stop(),o.each(f,function(e){e.destroy()}),f=[],c.length&&(o.each(c,function(e){e.destroy()}),c=[]),h.length&&(o.each(h,function(e){e.destroy()}),h=[]),l={},v=!1,p=m=null,d.reset()}var u=o.guid(),a,f=[],l={},c=[],h=[],p,d,v=!1,m;a={runtimes:t.Runtime.order,max_retries:0,chunk_size:0,multipart:!0,multi_selection:!0,file_data_name:"file",flash_swf_url:"js/Moxie.swf",silverlight_xap_url:"js/Moxie.xap",filters:{mime_types:[],prevent_duplicates:!1,max_file_size:0},resize:{enabled:!1,preserve_headers:!0,crop:!1},send_file_name:!0,send_chunk_number:!0},N.call(this,e,null,!0),d=new o.QueueProgress,o.extend(this,{id:u,uid:u,state:o.STOPPED,features:{},runtime:null,files:f,settings:a,total:d,init:function(){var e=this;typeof a.preinit=="function"?a.preinit(e):o.each(a.preinit,function(t,n){e.bind(n,t)}),S.call(this);if(!a.browse_button||!a.url){this.trigger("Error",{code:o.INIT_ERROR,message:o.translate("Init error.")});return}x.call(this,a,function(n){typeof a.init=="function"?a.init(e):o.each(a.init,function(t,n){e.bind(n,t)}),n?(e.runtime=t.Runtime.getInfo(w()).type,e.trigger("Init",{runtime:e.runtime}),e.trigger("PostInit")):e.trigger("Error",{code:o.INIT_ERROR,message:o.translate("Init error.")})})},setOption:function(e,t){N.call(this,e,t,!this.runtime)},getOption:function(e){return e?a[e]:a},refresh:function(){c.length&&o.each(c,function(e){e.trigger("Refresh")}),this.trigger("Refresh")},start:function(){this.state!=o.STARTED&&(this.state=o.STARTED,this.trigger("StateChanged"),g.call(this))},stop:function(){this.state!=o.STOPPED&&(this.state=o.STOPPED,this.trigger("StateChanged"),this.trigger("CancelUpload"))},disableBrowse:function(){v=arguments[0]!==n?arguments[0]:!0,c.length&&o.each(c,function(e){e.disable(v)}),this.trigger("DisableBrowse",v)},getFile:function(e){var t;for(t=f.length-1;t>=0;t--)if(f[t].id===e)return f[t]},addFile:function(e,n){function c(e,n){var r=[];t.each(s.settings.filters,function(t,n){i[n]&&r.push(function(r){i[n].call(s,t,e,function(e){r(!e)})})}),t.inSeries(r,n)}function h(e){var i=t.typeOf(e);if(e instanceof t.File){if(!e.ruid&&!e.isDetached()){if(!l)return!1;e.ruid=l,e.connectRuntime(l)}h(new o.File(e))}else e instanceof t.Blob?(h(e.getSource()),e.destroy()):e instanceof o.File?(n&&(e.name=n),u.push(function(t){c(e,function(n){n||(f.push(e),a.push(e),s.trigger("FileFiltered",e)),r(t,1)})})):t.inArray(i,["file","blob"])!==-1?h(new t.File(null,e)):i==="node"&&t.typeOf(e.files)==="filelist"?t.each(e.files,h):i==="array"&&(n=null,t.each(e,h))}var s=this,u=[],a=[],l;l=w(),h(e),u.length&&t.inSeries(u,function(){a.length&&s.trigger("FilesAdded",a)})},removeFile:function(e){var t=typeof e=="string"?e:e.id;for(var n=f.length-1;n>=0;n--)if(f[n].id===t)return this.splice(n,1)[0]},splice:function(e,t){var r=f.splice(e===n?0:e,t===n?f.length:t),i=!1;return this.state==o.STARTED&&(o.each(r,function(e){if(e.status===o.UPLOADING)return i=!0,!1}),i&&this.stop()),this.trigger("FilesRemoved",r),o.each(r,function(e){e.destroy()}),i&&this.start(),r},bind:function(e,t,n){var r=this;o.Uploader.prototype.bind.call(this,e,function(){var e=[].slice.call(arguments);return e.splice(0,1,r),t.apply(this,e)},0,n)},destroy:function(){this.trigger("Destroy"),a=d=null,this.unbindAll()}})},o.Uploader.prototype=t.EventTarget.instance,o.File=function(){function n(n){o.extend(this,{id:o.guid(),name:n.name||n.fileName,type:n.type||"",size:n.size||n.fileSize,origSize:n.size||n.fileSize,loaded:0,percent:0,status:o.QUEUED,lastModifiedDate:n.lastModifiedDate||(new Date).toLocaleString(),getNative:function(){var e=this.getSource().getSource();return t.inArray(t.typeOf(e),["blob","file"])!==-1?e:null},getSource:function(){return e[this.id]?e[this.id]:null},destroy:function(){var t=this.getSource();t&&(t.destroy(),delete e[this.id])}}),e[this.id]=n}var e={};return n}(),o.QueueProgress=function(){var e=this;e.size=0,e.loaded=0,e.uploaded=0,e.failed=0,e.queued=0,e.percent=0,e.bytesPerSec=0,e.reset=function(){e.size=e.loaded=e.uploaded=e.failed=e.queued=e.percent=e.bytesPerSec=0}},e.plupload=o})(window,mOxie); /*! * ScrollMagic v2.0.5 (2015-04-29) * The javascript library for magical scroll interactions. * (c) 2015 Jan Paepke (@janpaepke) * Project Website: http://scrollmagic.io * * @version 2.0.5 * @license Dual licensed under MIT license and GPL. * @author Jan Paepke - e-mail@janpaepke.de * * @file ScrollMagic main library. */ /** * @namespace ScrollMagic */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // CommonJS module.exports = factory(); } else { // Browser global root.ScrollMagic = factory(); } }(this, function () { "use strict"; var ScrollMagic = function () { _util.log(2, '(COMPATIBILITY NOTICE) -> As of ScrollMagic 2.0.0 you need to use \'new ScrollMagic.Controller()\' to create a new controller instance. Use \'new ScrollMagic.Scene()\' to instance a scene.'); }; ScrollMagic.version = "2.0.5"; // TODO: temporary workaround for chrome's scroll jitter bug window.addEventListener("mousewheel", function () {}); // global const var PIN_SPACER_ATTRIBUTE = "data-scrollmagic-pin-spacer"; /** * The main class that is needed once per scroll container. * * @class * * @example * // basic initialization * var controller = new ScrollMagic.Controller(); * * // passing options * var controller = new ScrollMagic.Controller({container: "#myContainer", loglevel: 3}); * * @param {object} [options] - An object containing one or more options for the controller. * @param {(string|object)} [options.container=window] - A selector, DOM object that references the main container for scrolling. * @param {boolean} [options.vertical=true] - Sets the scroll mode to vertical (`true`) or horizontal (`false`) scrolling. * @param {object} [options.globalSceneOptions={}] - These options will be passed to every Scene that is added to the controller using the addScene method. For more information on Scene options see {@link ScrollMagic.Scene}. * @param {number} [options.loglevel=2] Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic. ** `0` => silent ** `1` => errors ** `2` => errors, warnings ** `3` => errors, warnings, debuginfo * @param {boolean} [options.refreshInterval=100] - Some changes don't call events by default, like changing the container size or moving a scene trigger element. This interval polls these parameters to fire the necessary events. If you don't use custom containers, trigger elements or have static layouts, where the positions of the trigger elements don't change, you can set this to 0 disable interval checking and improve performance. * */ ScrollMagic.Controller = function (options) { /* * ---------------------------------------------------------------- * settings * ---------------------------------------------------------------- */ var NAMESPACE = 'ScrollMagic.Controller', SCROLL_DIRECTION_FORWARD = 'FORWARD', SCROLL_DIRECTION_REVERSE = 'REVERSE', SCROLL_DIRECTION_PAUSED = 'PAUSED', DEFAULT_OPTIONS = CONTROLLER_OPTIONS.defaults; /* * ---------------------------------------------------------------- * private vars * ---------------------------------------------------------------- */ var Controller = this, _options = _util.extend({}, DEFAULT_OPTIONS, options), _sceneObjects = [], _updateScenesOnNextCycle = false, // can be boolean (true => all scenes) or an array of scenes to be updated _scrollPos = 0, _scrollDirection = SCROLL_DIRECTION_PAUSED, _isDocument = true, _viewPortSize = 0, _enabled = true, _updateTimeout, _refreshTimeout; /* * ---------------------------------------------------------------- * private functions * ---------------------------------------------------------------- */ /** * Internal constructor function of the ScrollMagic Controller * @private */ var construct = function () { for (var key in _options) { if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { log(2, "WARNING: Unknown option \"" + key + "\""); delete _options[key]; } } _options.container = _util.get.elements(_options.container)[0]; // check ScrollContainer if (!_options.container) { log(1, "ERROR creating object " + NAMESPACE + ": No valid scroll container supplied"); throw NAMESPACE + " init failed."; // cancel } _isDocument = _options.container === window || _options.container === document.body || !document.body.contains(_options.container); // normalize to window if (_isDocument) { _options.container = window; } // update container size immediately _viewPortSize = getViewportSize(); // set event handlers _options.container.addEventListener("resize", onChange); _options.container.addEventListener("scroll", onChange); _options.refreshInterval = parseInt(_options.refreshInterval) || DEFAULT_OPTIONS.refreshInterval; scheduleRefresh(); log(3, "added new " + NAMESPACE + " controller (v" + ScrollMagic.version + ")"); }; /** * Schedule the next execution of the refresh function * @private */ var scheduleRefresh = function () { if (_options.refreshInterval > 0) { _refreshTimeout = window.setTimeout(refresh, _options.refreshInterval); } }; /** * Default function to get scroll pos - overwriteable using `Controller.scrollPos(newFunction)` * @private */ var getScrollPos = function () { return _options.vertical ? _util.get.scrollTop(_options.container) : _util.get.scrollLeft(_options.container); }; /** * Returns the current viewport Size (width vor horizontal, height for vertical) * @private */ var getViewportSize = function () { return _options.vertical ? _util.get.height(_options.container) : _util.get.width(_options.container); }; /** * Default function to set scroll pos - overwriteable using `Controller.scrollTo(newFunction)` * Make available publicly for pinned mousewheel workaround. * @private */ var setScrollPos = this._setScrollPos = function (pos) { if (_options.vertical) { if (_isDocument) { window.scrollTo(_util.get.scrollLeft(), pos); } else { _options.container.scrollTop = pos; } } else { if (_isDocument) { window.scrollTo(pos, _util.get.scrollTop()); } else { _options.container.scrollLeft = pos; } } }; /** * Handle updates in cycles instead of on scroll (performance) * @private */ var updateScenes = function () { if (_enabled && _updateScenesOnNextCycle) { // determine scenes to update var scenesToUpdate = _util.type.Array(_updateScenesOnNextCycle) ? _updateScenesOnNextCycle : _sceneObjects.slice(0); // reset scenes _updateScenesOnNextCycle = false; var oldScrollPos = _scrollPos; // update scroll pos now instead of onChange, as it might have changed since scheduling (i.e. in-browser smooth scroll) _scrollPos = Controller.scrollPos(); var deltaScroll = _scrollPos - oldScrollPos; if (deltaScroll !== 0) { // scroll position changed? _scrollDirection = (deltaScroll > 0) ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_REVERSE; } // reverse order of scenes if scrolling reverse if (_scrollDirection === SCROLL_DIRECTION_REVERSE) { scenesToUpdate.reverse(); } // update scenes scenesToUpdate.forEach(function (scene, index) { log(3, "updating Scene " + (index + 1) + "/" + scenesToUpdate.length + " (" + _sceneObjects.length + " total)"); scene.update(true); }); if (scenesToUpdate.length === 0 && _options.loglevel >= 3) { log(3, "updating 0 Scenes (nothing added to controller)"); } } }; /** * Initializes rAF callback * @private */ var debounceUpdate = function () { _updateTimeout = _util.rAF(updateScenes); }; /** * Handles Container changes * @private */ var onChange = function (e) { log(3, "event fired causing an update:", e.type); if (e.type == "resize") { // resize _viewPortSize = getViewportSize(); _scrollDirection = SCROLL_DIRECTION_PAUSED; } // schedule update if (_updateScenesOnNextCycle !== true) { _updateScenesOnNextCycle = true; debounceUpdate(); } }; var refresh = function () { if (!_isDocument) { // simulate resize event. Only works for viewport relevant param (performance) if (_viewPortSize != getViewportSize()) { var resizeEvent; try { resizeEvent = new Event('resize', { bubbles: false, cancelable: false }); } catch (e) { // stupid IE resizeEvent = document.createEvent("Event"); resizeEvent.initEvent("resize", false, false); } _options.container.dispatchEvent(resizeEvent); } } _sceneObjects.forEach(function (scene, index) { // refresh all scenes scene.refresh(); }); scheduleRefresh(); }; /** * Send a debug message to the console. * provided publicly with _log for plugins * @private * * @param {number} loglevel - The loglevel required to initiate output for the message. * @param {...mixed} output - One or more variables that should be passed to the console. */ var log = this._log = function (loglevel, output) { if (_options.loglevel >= loglevel) { Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->"); _util.log.apply(window, arguments); } }; // for scenes we have getters for each option, but for the controller we don't, so we need to make it available externally for plugins this._options = _options; /** * Sort scenes in ascending order of their start offset. * @private * * @param {array} ScenesArray - an array of ScrollMagic Scenes that should be sorted * @return {array} The sorted array of Scenes. */ var sortScenes = function (ScenesArray) { if (ScenesArray.length <= 1) { return ScenesArray; } else { var scenes = ScenesArray.slice(0); scenes.sort(function (a, b) { return a.scrollOffset() > b.scrollOffset() ? 1 : -1; }); return scenes; } }; /** * ---------------------------------------------------------------- * public functions * ---------------------------------------------------------------- */ /** * Add one ore more scene(s) to the controller. * This is the equivalent to `Scene.addTo(controller)`. * @public * @example * // with a previously defined scene * controller.addScene(scene); * * // with a newly created scene. * controller.addScene(new ScrollMagic.Scene({duration : 0})); * * // adding multiple scenes * controller.addScene([scene, scene2, new ScrollMagic.Scene({duration : 0})]); * * @param {(ScrollMagic.Scene|array)} newScene - ScrollMagic Scene or Array of Scenes to be added to the controller. * @return {Controller} Parent object for chaining. */ this.addScene = function (newScene) { if (_util.type.Array(newScene)) { newScene.forEach(function (scene, index) { Controller.addScene(scene); }); } else if (newScene instanceof ScrollMagic.Scene) { if (newScene.controller() !== Controller) { newScene.addTo(Controller); } else if (_sceneObjects.indexOf(newScene) < 0) { // new scene _sceneObjects.push(newScene); // add to array _sceneObjects = sortScenes(_sceneObjects); // sort newScene.on("shift.controller_sort", function () { // resort whenever scene moves _sceneObjects = sortScenes(_sceneObjects); }); // insert Global defaults. for (var key in _options.globalSceneOptions) { if (newScene[key]) { newScene[key].call(newScene, _options.globalSceneOptions[key]); } } log(3, "adding Scene (now " + _sceneObjects.length + " total)"); } } else { log(1, "ERROR: invalid argument supplied for '.addScene()'"); } return Controller; }; /** * Remove one ore more scene(s) from the controller. * This is the equivalent to `Scene.remove()`. * @public * @example * // remove a scene from the controller * controller.removeScene(scene); * * // remove multiple scenes from the controller * controller.removeScene([scene, scene2, scene3]); * * @param {(ScrollMagic.Scene|array)} Scene - ScrollMagic Scene or Array of Scenes to be removed from the controller. * @returns {Controller} Parent object for chaining. */ this.removeScene = function (Scene) { if (_util.type.Array(Scene)) { Scene.forEach(function (scene, index) { Controller.removeScene(scene); }); } else { var index = _sceneObjects.indexOf(Scene); if (index > -1) { Scene.off("shift.controller_sort"); _sceneObjects.splice(index, 1); log(3, "removing Scene (now " + _sceneObjects.length + " left)"); Scene.remove(); } } return Controller; }; /** * Update one ore more scene(s) according to the scroll position of the container. * This is the equivalent to `Scene.update()`. * The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container. * It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress. * _**Note:** This method gets called constantly whenever Controller detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._ * @public * @example * // update a specific scene on next cycle * controller.updateScene(scene); * * // update a specific scene immediately * controller.updateScene(scene, true); * * // update multiple scenes scene on next cycle * controller.updateScene([scene1, scene2, scene3]); * * @param {ScrollMagic.Scene} Scene - ScrollMagic Scene or Array of Scenes that is/are supposed to be updated. * @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle. This is useful when changing multiple properties of the scene - this way it will only be updated once all new properties are set (updateScenes). * @return {Controller} Parent object for chaining. */ this.updateScene = function (Scene, immediately) { if (_util.type.Array(Scene)) { Scene.forEach(function (scene, index) { Controller.updateScene(scene, immediately); }); } else { if (immediately) { Scene.update(true); } else if (_updateScenesOnNextCycle !== true && Scene instanceof ScrollMagic.Scene) { // if _updateScenesOnNextCycle is true, all connected scenes are already scheduled for update // prep array for next update cycle _updateScenesOnNextCycle = _updateScenesOnNextCycle || []; if (_updateScenesOnNextCycle.indexOf(Scene) == -1) { _updateScenesOnNextCycle.push(Scene); } _updateScenesOnNextCycle = sortScenes(_updateScenesOnNextCycle); // sort debounceUpdate(); } } return Controller; }; /** * Updates the controller params and calls updateScene on every scene, that is attached to the controller. * See `Controller.updateScene()` for more information about what this means. * In most cases you will not need this function, as it is called constantly, whenever ScrollMagic detects a state change event, like resize or scroll. * The only application for this method is when ScrollMagic fails to detect these events. * One application is with some external scroll libraries (like iScroll) that move an internal container to a negative offset instead of actually scrolling. In this case the update on the controller needs to be called whenever the child container's position changes. * For this case there will also be the need to provide a custom function to calculate the correct scroll position. See `Controller.scrollPos()` for details. * @public * @example * // update the controller on next cycle (saves performance due to elimination of redundant updates) * controller.update(); * * // update the controller immediately * controller.update(true); * * @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance) * @return {Controller} Parent object for chaining. */ this.update = function (immediately) { onChange({ type: "resize" }); // will update size and set _updateScenesOnNextCycle to true if (immediately) { updateScenes(); } return Controller; }; /** * Scroll to a numeric scroll offset, a DOM element, the start of a scene or provide an alternate method for scrolling. * For vertical controllers it will change the top scroll offset and for horizontal applications it will change the left offset. * @public * * @since 1.1.0 * @example * // scroll to an offset of 100 * controller.scrollTo(100); * * // scroll to a DOM element * controller.scrollTo("#anchor"); * * // scroll to the beginning of a scene * var scene = new ScrollMagic.Scene({offset: 200}); * controller.scrollTo(scene); * * // define a new scroll position modification function (jQuery animate instead of jump) * controller.scrollTo(function (newScrollPos) { * $("html, body").animate({scrollTop: newScrollPos}); * }); * controller.scrollTo(100); // call as usual, but the new function will be used instead * * // define a new scroll function with an additional parameter * controller.scrollTo(function (newScrollPos, message) { * console.log(message); * $(this).animate({scrollTop: newScrollPos}); * }); * // call as usual, but supply an extra parameter to the defined custom function * controller.scrollTo(100, "my message"); * * // define a new scroll function with an additional parameter containing multiple variables * controller.scrollTo(function (newScrollPos, options) { * someGlobalVar = options.a + options.b; * $(this).animate({scrollTop: newScrollPos}); * }); * // call as usual, but supply an extra parameter containing multiple options * controller.scrollTo(100, {a: 1, b: 2}); * * // define a new scroll function with a callback supplied as an additional parameter * controller.scrollTo(function (newScrollPos, callback) { * $(this).animate({scrollTop: newScrollPos}, 400, "swing", callback); * }); * // call as usual, but supply an extra parameter, which is used as a callback in the previously defined custom scroll function * controller.scrollTo(100, function() { * console.log("scroll has finished."); * }); * * @param {mixed} scrollTarget - The supplied argument can be one of these types: * 1. `number` -> The container will scroll to this new scroll offset. * 2. `string` or `object` -> Can be a selector or a DOM object. * The container will scroll to the position of this element. * 3. `ScrollMagic Scene` -> The container will scroll to the start of this scene. * 4. `function` -> This function will be used for future scroll position modifications. * This provides a way for you to change the behaviour of scrolling and adding new behaviour like animation. The function receives the new scroll position as a parameter and a reference to the container element using `this`. * It may also optionally receive an optional additional parameter (see below) * _**NOTE:** * All other options will still work as expected, using the new function to scroll._ * @param {mixed} [additionalParameter] - If a custom scroll function was defined (see above 4.), you may want to supply additional parameters to it, when calling it. You can do this using this parameter – see examples for details. Please note, that this parameter will have no effect, if you use the default scrolling function. * @returns {Controller} Parent object for chaining. */ this.scrollTo = function (scrollTarget, additionalParameter) { if (_util.type.Number(scrollTarget)) { // excecute setScrollPos.call(_options.container, scrollTarget, additionalParameter); } else if (scrollTarget instanceof ScrollMagic.Scene) { // scroll to scene if (scrollTarget.controller() === Controller) { // check if the controller is associated with this scene Controller.scrollTo(scrollTarget.scrollOffset(), additionalParameter); } else { log(2, "scrollTo(): The supplied scene does not belong to this controller. Scroll cancelled.", scrollTarget); } } else if (_util.type.Function(scrollTarget)) { // assign new scroll function setScrollPos = scrollTarget; } else { // scroll to element var elem = _util.get.elements(scrollTarget)[0]; if (elem) { // if parent is pin spacer, use spacer position instead so correct start position is returned for pinned elements. while (elem.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) { elem = elem.parentNode; } var param = _options.vertical ? "top" : "left", // which param is of interest ? containerOffset = _util.get.offset(_options.container), // container position is needed because element offset is returned in relation to document, not in relation to container. elementOffset = _util.get.offset(elem); if (!_isDocument) { // container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent containerOffset[param] -= Controller.scrollPos(); } Controller.scrollTo(elementOffset[param] - containerOffset[param], additionalParameter); } else { log(2, "scrollTo(): The supplied argument is invalid. Scroll cancelled.", scrollTarget); } } return Controller; }; /** * **Get** the current scrollPosition or **Set** a new method to calculate it. * -> **GET**: * When used as a getter this function will return the current scroll position. * To get a cached value use Controller.info("scrollPos"), which will be updated in the update cycle. * For vertical controllers it will return the top scroll offset and for horizontal applications it will return the left offset. * * -> **SET**: * When used as a setter this method prodes a way to permanently overwrite the controller's scroll position calculation. * A typical usecase is when the scroll position is not reflected by the containers scrollTop or scrollLeft values, but for example by the inner offset of a child container. * Moving a child container inside a parent is a commonly used method for several scrolling frameworks, including iScroll. * By providing an alternate calculation function you can make sure ScrollMagic receives the correct scroll position. * Please also bear in mind that your function should return y values for vertical scrolls an x for horizontals. * * To change the current scroll position please use `Controller.scrollTo()`. * @public * * @example * // get the current scroll Position * var scrollPos = controller.scrollPos(); * * // set a new scroll position calculation method * controller.scrollPos(function () { * return this.info("vertical") ? -mychildcontainer.y : -mychildcontainer.x * }); * * @param {function} [scrollPosMethod] - The function to be used for the scroll position calculation of the container. * @returns {(number|Controller)} Current scroll position or parent object for chaining. */ this.scrollPos = function (scrollPosMethod) { if (!arguments.length) { // get return getScrollPos.call(Controller); } else { // set if (_util.type.Function(scrollPosMethod)) { getScrollPos = scrollPosMethod; } else { log(2, "Provided value for method 'scrollPos' is not a function. To change the current scroll position use 'scrollTo()'."); } } return Controller; }; /** * **Get** all infos or one in particular about the controller. * @public * @example * // returns the current scroll position (number) * var scrollPos = controller.info("scrollPos"); * * // returns all infos as an object * var infos = controller.info(); * * @param {string} [about] - If passed only this info will be returned instead of an object containing all. Valid options are: ** `"size"` => the current viewport size of the container ** `"vertical"` => true if vertical scrolling, otherwise false ** `"scrollPos"` => the current scroll position ** `"scrollDirection"` => the last known direction of the scroll ** `"container"` => the container element ** `"isDocument"` => true if container element is the document. * @returns {(mixed|object)} The requested info(s). */ this.info = function (about) { var values = { size: _viewPortSize, // contains height or width (in regard to orientation); vertical: _options.vertical, scrollPos: _scrollPos, scrollDirection: _scrollDirection, container: _options.container, isDocument: _isDocument }; if (!arguments.length) { // get all as an object return values; } else if (values[about] !== undefined) { return values[about]; } else { log(1, "ERROR: option \"" + about + "\" is not available"); return; } }; /** * **Get** or **Set** the current loglevel option value. * @public * * @example * // get the current value * var loglevel = controller.loglevel(); * * // set a new value * controller.loglevel(3); * * @param {number} [newLoglevel] - The new loglevel setting of the Controller. `[0-3]` * @returns {(number|Controller)} Current loglevel or parent object for chaining. */ this.loglevel = function (newLoglevel) { if (!arguments.length) { // get return _options.loglevel; } else if (_options.loglevel != newLoglevel) { // set _options.loglevel = newLoglevel; } return Controller; }; /** * **Get** or **Set** the current enabled state of the controller. * This can be used to disable all Scenes connected to the controller without destroying or removing them. * @public * * @example * // get the current value * var enabled = controller.enabled(); * * // disable the controller * controller.enabled(false); * * @param {boolean} [newState] - The new enabled state of the controller `true` or `false`. * @returns {(boolean|Controller)} Current enabled state or parent object for chaining. */ this.enabled = function (newState) { if (!arguments.length) { // get return _enabled; } else if (_enabled != newState) { // set _enabled = !! newState; Controller.updateScene(_sceneObjects, true); } return Controller; }; /** * Destroy the Controller, all Scenes and everything. * @public * * @example * // without resetting the scenes * controller = controller.destroy(); * * // with scene reset * controller = controller.destroy(true); * * @param {boolean} [resetScenes=false] - If `true` the pins and tweens (if existent) of all scenes will be reset. * @returns {null} Null to unset handler variables. */ this.destroy = function (resetScenes) { window.clearTimeout(_refreshTimeout); var i = _sceneObjects.length; while (i--) { _sceneObjects[i].destroy(resetScenes); } _options.container.removeEventListener("resize", onChange); _options.container.removeEventListener("scroll", onChange); _util.cAF(_updateTimeout); log(3, "destroyed " + NAMESPACE + " (reset: " + (resetScenes ? "true" : "false") + ")"); return null; }; // INIT construct(); return Controller; }; // store pagewide controller options var CONTROLLER_OPTIONS = { defaults: { container: window, vertical: true, globalSceneOptions: {}, loglevel: 2, refreshInterval: 100 } }; /* * method used to add an option to ScrollMagic Scenes. */ ScrollMagic.Controller.addOption = function (name, defaultValue) { CONTROLLER_OPTIONS.defaults[name] = defaultValue; }; // instance extension function for plugins ScrollMagic.Controller.extend = function (extension) { var oldClass = this; ScrollMagic.Controller = function () { oldClass.apply(this, arguments); this.$super = _util.extend({}, this); // copy parent state return extension.apply(this, arguments) || this; }; _util.extend(ScrollMagic.Controller, oldClass); // copy properties ScrollMagic.Controller.prototype = oldClass.prototype; // copy prototype ScrollMagic.Controller.prototype.constructor = ScrollMagic.Controller; // restore constructor }; /** * A Scene defines where the controller should react and how. * * @class * * @example * // create a standard scene and add it to a controller * new ScrollMagic.Scene() * .addTo(controller); * * // create a scene with custom options and assign a handler to it. * var scene = new ScrollMagic.Scene({ * duration: 100, * offset: 200, * triggerHook: "onEnter", * reverse: false * }); * * @param {object} [options] - Options for the Scene. The options can be updated at any time. Instead of setting the options for each scene individually you can also set them globally in the controller as the controllers `globalSceneOptions` option. The object accepts the same properties as the ones below. When a scene is added to the controller the options defined using the Scene constructor will be overwritten by those set in `globalSceneOptions`. * @param {(number|function)} [options.duration=0] - The duration of the scene. If `0` tweens will auto-play when reaching the scene start point, pins will be pinned indefinetly starting at the start position. A function retuning the duration value is also supported. Please see `Scene.duration()` for details. * @param {number} [options.offset=0] - Offset Value for the Trigger Position. If no triggerElement is defined this will be the scroll distance from the start of the page, after which the scene will start. * @param {(string|object)} [options.triggerElement=null] - Selector or DOM object that defines the start of the scene. If undefined the scene will start right at the start of the page (unless an offset is set). * @param {(number|string)} [options.triggerHook="onCenter"] - Can be a number between 0 and 1 defining the position of the trigger Hook in relation to the viewport. Can also be defined using a string: ** `"onEnter"` => `1` ** `"onCenter"` => `0.5` ** `"onLeave"` => `0` * @param {boolean} [options.reverse=true] - Should the scene reverse, when scrolling up? * @param {number} [options.loglevel=2] - Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic. ** `0` => silent ** `1` => errors ** `2` => errors, warnings ** `3` => errors, warnings, debuginfo * */ ScrollMagic.Scene = function (options) { /* * ---------------------------------------------------------------- * settings * ---------------------------------------------------------------- */ var NAMESPACE = 'ScrollMagic.Scene', SCENE_STATE_BEFORE = 'BEFORE', SCENE_STATE_DURING = 'DURING', SCENE_STATE_AFTER = 'AFTER', DEFAULT_OPTIONS = SCENE_OPTIONS.defaults; /* * ---------------------------------------------------------------- * private vars * ---------------------------------------------------------------- */ var Scene = this, _options = _util.extend({}, DEFAULT_OPTIONS, options), _state = SCENE_STATE_BEFORE, _progress = 0, _scrollOffset = { start: 0, end: 0 }, // reflects the controllers's scroll position for the start and end of the scene respectively _triggerPos = 0, _enabled = true, _durationUpdateMethod, _controller; /** * Internal constructor function of the ScrollMagic Scene * @private */ var construct = function () { for (var key in _options) { // check supplied options if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { log(2, "WARNING: Unknown option \"" + key + "\""); delete _options[key]; } } // add getters/setters for all possible options for (var optionName in DEFAULT_OPTIONS) { addSceneOption(optionName); } // validate all options validateOption(); }; /* * ---------------------------------------------------------------- * Event Management * ---------------------------------------------------------------- */ var _listeners = {}; /** * Scene start event. * Fires whenever the scroll position its the starting point of the scene. * It will also fire when scrolling back up going over the start position of the scene. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback. * * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. * * @event ScrollMagic.Scene#start * * @example * scene.on("start", function (event) { * console.log("Hit start point of scene."); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {number} event.progress - Reflects the current progress of the scene * @property {string} event.state - The current state of the scene `"BEFORE"` or `"DURING"` * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` */ /** * Scene end event. * Fires whenever the scroll position its the ending point of the scene. * It will also fire when scrolling back up from after the scene and going over its end position. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback. * * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. * * @event ScrollMagic.Scene#end * * @example * scene.on("end", function (event) { * console.log("Hit end point of scene."); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {number} event.progress - Reflects the current progress of the scene * @property {string} event.state - The current state of the scene `"DURING"` or `"AFTER"` * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` */ /** * Scene enter event. * Fires whenever the scene enters the "DURING" state. * Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene enters its active scroll timeframe, regardless of the scroll-direction. * * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. * * @event ScrollMagic.Scene#enter * * @example * scene.on("enter", function (event) { * console.log("Scene entered."); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {number} event.progress - Reflects the current progress of the scene * @property {string} event.state - The current state of the scene - always `"DURING"` * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` */ /** * Scene leave event. * Fires whenever the scene's state goes from "DURING" to either "BEFORE" or "AFTER". * Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene leaves its active scroll timeframe, regardless of the scroll-direction. * * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. * * @event ScrollMagic.Scene#leave * * @example * scene.on("leave", function (event) { * console.log("Scene left."); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {number} event.progress - Reflects the current progress of the scene * @property {string} event.state - The current state of the scene `"BEFORE"` or `"AFTER"` * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` */ /** * Scene update event. * Fires whenever the scene is updated (but not necessarily changes the progress). * * @event ScrollMagic.Scene#update * * @example * scene.on("update", function (event) { * console.log("Scene updated."); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {number} event.startPos - The starting position of the scene (in relation to the conainer) * @property {number} event.endPos - The ending position of the scene (in relation to the conainer) * @property {number} event.scrollPos - The current scroll position of the container */ /** * Scene progress event. * Fires whenever the progress of the scene changes. * * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. * * @event ScrollMagic.Scene#progress * * @example * scene.on("progress", function (event) { * console.log("Scene progress changed to " + event.progress); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {number} event.progress - Reflects the current progress of the scene * @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"` * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` */ /** * Scene change event. * Fires whenvever a property of the scene is changed. * * @event ScrollMagic.Scene#change * * @example * scene.on("change", function (event) { * console.log("Scene Property \"" + event.what + "\" changed to " + event.newval); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {string} event.what - Indicates what value has been changed * @property {mixed} event.newval - The new value of the changed property */ /** * Scene shift event. * Fires whenvever the start or end **scroll offset** of the scene change. * This happens explicitely, when one of these values change: `offset`, `duration` or `triggerHook`. * It will fire implicitly when the `triggerElement` changes, if the new element has a different position (most cases). * It will also fire implicitly when the size of the container changes and the triggerHook is anything other than `onLeave`. * * @event ScrollMagic.Scene#shift * @since 1.1.0 * * @example * scene.on("shift", function (event) { * console.log("Scene moved, because the " + event.reason + " has changed.)"); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {string} event.reason - Indicates why the scene has shifted */ /** * Scene destroy event. * Fires whenvever the scene is destroyed. * This can be used to tidy up custom behaviour used in events. * * @event ScrollMagic.Scene#destroy * @since 1.1.0 * * @example * scene.on("enter", function (event) { * // add custom action * $("#my-elem").left("200"); * }) * .on("destroy", function (event) { * // reset my element to start position * if (event.reset) { * $("#my-elem").left("0"); * } * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {boolean} event.reset - Indicates if the destroy method was called with reset `true` or `false`. */ /** * Scene add event. * Fires when the scene is added to a controller. * This is mostly used by plugins to know that change might be due. * * @event ScrollMagic.Scene#add * @since 2.0.0 * * @example * scene.on("add", function (event) { * console.log('Scene was added to a new controller.'); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event * @property {boolean} event.controller - The controller object the scene was added to. */ /** * Scene remove event. * Fires when the scene is removed from a controller. * This is mostly used by plugins to know that change might be due. * * @event ScrollMagic.Scene#remove * @since 2.0.0 * * @example * scene.on("remove", function (event) { * console.log('Scene was removed from its controller.'); * }); * * @property {object} event - The event Object passed to each callback * @property {string} event.type - The name of the event * @property {Scene} event.target - The Scene object that triggered this event */ /** * Add one ore more event listener. * The callback function will be fired at the respective event, and an object containing relevant data will be passed to the callback. * @method ScrollMagic.Scene#on * * @example * function callback (event) { * console.log("Event fired! (" + event.type + ")"); * } * // add listeners * scene.on("change update progress start end enter leave", callback); * * @param {string} names - The name or names of the event the callback should be attached to. * @param {function} callback - A function that should be executed, when the event is dispatched. An event object will be passed to the callback. * @returns {Scene} Parent object for chaining. */ this.on = function (names, callback) { if (_util.type.Function(callback)) { names = names.trim().split(' '); names.forEach(function (fullname) { var nameparts = fullname.split('.'), eventname = nameparts[0], namespace = nameparts[1]; if (eventname != "*") { // disallow wildcards if (!_listeners[eventname]) { _listeners[eventname] = []; } _listeners[eventname].push({ namespace: namespace || '', callback: callback }); } }); } else { log(1, "ERROR when calling '.on()': Supplied callback for '" + names + "' is not a valid function!"); } return Scene; }; /** * Remove one or more event listener. * @method ScrollMagic.Scene#off * * @example * function callback (event) { * console.log("Event fired! (" + event.type + ")"); * } * // add listeners * scene.on("change update", callback); * // remove listeners * scene.off("change update", callback); * * @param {string} names - The name or names of the event that should be removed. * @param {function} [callback] - A specific callback function that should be removed. If none is passed all callbacks to the event listener will be removed. * @returns {Scene} Parent object for chaining. */ this.off = function (names, callback) { if (!names) { log(1, "ERROR: Invalid event name supplied."); return Scene; } names = names.trim().split(' '); names.forEach(function (fullname, key) { var nameparts = fullname.split('.'), eventname = nameparts[0], namespace = nameparts[1] || '', removeList = eventname === '*' ? Object.keys(_listeners) : [eventname]; removeList.forEach(function (remove) { var list = _listeners[remove] || [], i = list.length; while (i--) { var listener = list[i]; if (listener && (namespace === listener.namespace || namespace === '*') && (!callback || callback == listener.callback)) { list.splice(i, 1); } } if (!list.length) { delete _listeners[remove]; } }); }); return Scene; }; /** * Trigger an event. * @method ScrollMagic.Scene#trigger * * @example * this.trigger("change"); * * @param {string} name - The name of the event that should be triggered. * @param {object} [vars] - An object containing info that should be passed to the callback. * @returns {Scene} Parent object for chaining. */ this.trigger = function (name, vars) { if (name) { var nameparts = name.trim().split('.'), eventname = nameparts[0], namespace = nameparts[1], listeners = _listeners[eventname]; log(3, 'event fired:', eventname, vars ? "->" : '', vars || ''); if (listeners) { listeners.forEach(function (listener, key) { if (!namespace || namespace === listener.namespace) { listener.callback.call(Scene, new ScrollMagic.Event(eventname, listener.namespace, Scene, vars)); } }); } } else { log(1, "ERROR: Invalid event name supplied."); } return Scene; }; // set event listeners Scene.on("change.internal", function (e) { if (e.what !== "loglevel" && e.what !== "tweenChanges") { // no need for a scene update scene with these options... if (e.what === "triggerElement") { updateTriggerElementPosition(); } else if (e.what === "reverse") { // the only property left that may have an impact on the current scene state. Everything else is handled by the shift event. Scene.update(); } } }).on("shift.internal", function (e) { updateScrollOffset(); Scene.update(); // update scene to reflect new position }); /** * Send a debug message to the console. * @private * but provided publicly with _log for plugins * * @param {number} loglevel - The loglevel required to initiate output for the message. * @param {...mixed} output - One or more variables that should be passed to the console. */ var log = this._log = function (loglevel, output) { if (_options.loglevel >= loglevel) { Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->"); _util.log.apply(window, arguments); } }; /** * Add the scene to a controller. * This is the equivalent to `Controller.addScene(scene)`. * @method ScrollMagic.Scene#addTo * * @example * // add a scene to a ScrollMagic Controller * scene.addTo(controller); * * @param {ScrollMagic.Controller} controller - The controller to which the scene should be added. * @returns {Scene} Parent object for chaining. */ this.addTo = function (controller) { if (!(controller instanceof ScrollMagic.Controller)) { log(1, "ERROR: supplied argument of 'addTo()' is not a valid ScrollMagic Controller"); } else if (_controller != controller) { // new controller if (_controller) { // was associated to a different controller before, so remove it... _controller.removeScene(Scene); } _controller = controller; validateOption(); updateDuration(true); updateTriggerElementPosition(true); updateScrollOffset(); _controller.info("container").addEventListener('resize', onContainerResize); controller.addScene(Scene); Scene.trigger("add", { controller: _controller }); log(3, "added " + NAMESPACE + " to controller"); Scene.update(); } return Scene; }; /** * **Get** or **Set** the current enabled state of the scene. * This can be used to disable this scene without removing or destroying it. * @method ScrollMagic.Scene#enabled * * @example * // get the current value * var enabled = scene.enabled(); * * // disable the scene * scene.enabled(false); * * @param {boolean} [newState] - The new enabled state of the scene `true` or `false`. * @returns {(boolean|Scene)} Current enabled state or parent object for chaining. */ this.enabled = function (newState) { if (!arguments.length) { // get return _enabled; } else if (_enabled != newState) { // set _enabled = !! newState; Scene.update(true); } return Scene; }; /** * Remove the scene from the controller. * This is the equivalent to `Controller.removeScene(scene)`. * The scene will not be updated anymore until you readd it to a controller. * To remove the pin or the tween you need to call removeTween() or removePin() respectively. * @method ScrollMagic.Scene#remove * @example * // remove the scene from its controller * scene.remove(); * * @returns {Scene} Parent object for chaining. */ this.remove = function () { if (_controller) { _controller.info("container").removeEventListener('resize', onContainerResize); var tmpParent = _controller; _controller = undefined; tmpParent.removeScene(Scene); Scene.trigger("remove"); log(3, "removed " + NAMESPACE + " from controller"); } return Scene; }; /** * Destroy the scene and everything. * @method ScrollMagic.Scene#destroy * @example * // destroy the scene without resetting the pin and tween to their initial positions * scene = scene.destroy(); * * // destroy the scene and reset the pin and tween * scene = scene.destroy(true); * * @param {boolean} [reset=false] - If `true` the pin and tween (if existent) will be reset. * @returns {null} Null to unset handler variables. */ this.destroy = function (reset) { Scene.trigger("destroy", { reset: reset }); Scene.remove(); Scene.off("*.*"); log(3, "destroyed " + NAMESPACE + " (reset: " + (reset ? "true" : "false") + ")"); return null; }; /** * Updates the Scene to reflect the current state. * This is the equivalent to `Controller.updateScene(scene, immediately)`. * The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container. * It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress. * This means an update doesn't necessarily result in a progress change. The `progress` event will be fired if the progress has indeed changed between this update and the last. * _**NOTE:** This method gets called constantly whenever ScrollMagic detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._ * @method ScrollMagic.Scene#update * @example * // update the scene on next tick * scene.update(); * * // update the scene immediately * scene.update(true); * * @fires Scene.update * * @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance). * @returns {Scene} Parent object for chaining. */ this.update = function (immediately) { if (_controller) { if (immediately) { if (_controller.enabled() && _enabled) { var scrollPos = _controller.info("scrollPos"), newProgress; if (_options.duration > 0) { newProgress = (scrollPos - _scrollOffset.start) / (_scrollOffset.end - _scrollOffset.start); } else { newProgress = scrollPos >= _scrollOffset.start ? 1 : 0; } Scene.trigger("update", { startPos: _scrollOffset.start, endPos: _scrollOffset.end, scrollPos: scrollPos }); Scene.progress(newProgress); } else if (_pin && _state === SCENE_STATE_DURING) { updatePinState(true); // unpin in position } } else { _controller.updateScene(Scene, false); } } return Scene; }; /** * Updates dynamic scene variables like the trigger element position or the duration. * This method is automatically called in regular intervals from the controller. See {@link ScrollMagic.Controller} option `refreshInterval`. * * You can call it to minimize lag, for example when you intentionally change the position of the triggerElement. * If you don't it will simply be updated in the next refresh interval of the container, which is usually sufficient. * * @method ScrollMagic.Scene#refresh * @since 1.1.0 * @example * scene = new ScrollMagic.Scene({triggerElement: "#trigger"}); * * // change the position of the trigger * $("#trigger").css("top", 500); * // immediately let the scene know of this change * scene.refresh(); * * @fires {@link Scene.shift}, if the trigger element position or the duration changed * @fires {@link Scene.change}, if the duration changed * * @returns {Scene} Parent object for chaining. */ this.refresh = function () { updateDuration(); updateTriggerElementPosition(); // update trigger element position return Scene; }; /** * **Get** or **Set** the scene's progress. * Usually it shouldn't be necessary to use this as a setter, as it is set automatically by scene.update(). * The order in which the events are fired depends on the duration of the scene: * 1. Scenes with `duration == 0`: * Scenes that have no duration by definition have no ending. Thus the `end` event will never be fired. * When the trigger position of the scene is passed the events are always fired in this order: * `enter`, `start`, `progress` when scrolling forward * and * `progress`, `start`, `leave` when scrolling in reverse * 2. Scenes with `duration > 0`: * Scenes with a set duration have a defined start and end point. * When scrolling past the start position of the scene it will fire these events in this order: * `enter`, `start`, `progress` * When continuing to scroll and passing the end point it will fire these events: * `progress`, `end`, `leave` * When reversing through the end point these events are fired: * `enter`, `end`, `progress` * And when continuing to scroll past the start position in reverse it will fire: * `progress`, `start`, `leave` * In between start and end the `progress` event will be called constantly, whenever the progress changes. * * In short: * `enter` events will always trigger **before** the progress update and `leave` envents will trigger **after** the progress update. * `start` and `end` will always trigger at their respective position. * * Please review the event descriptions for details on the events and the event object that is passed to the callback. * * @method ScrollMagic.Scene#progress * @example * // get the current scene progress * var progress = scene.progress(); * * // set new scene progress * scene.progress(0.3); * * @fires {@link Scene.enter}, when used as setter * @fires {@link Scene.start}, when used as setter * @fires {@link Scene.progress}, when used as setter * @fires {@link Scene.end}, when used as setter * @fires {@link Scene.leave}, when used as setter * * @param {number} [progress] - The new progress value of the scene `[0-1]`. * @returns {number} `get` - Current scene progress. * @returns {Scene} `set` - Parent object for chaining. */ this.progress = function (progress) { if (!arguments.length) { // get return _progress; } else { // set var doUpdate = false, oldState = _state, scrollDirection = _controller ? _controller.info("scrollDirection") : 'PAUSED', reverseOrForward = _options.reverse || progress >= _progress; if (_options.duration === 0) { // zero duration scenes doUpdate = _progress != progress; _progress = progress < 1 && reverseOrForward ? 0 : 1; _state = _progress === 0 ? SCENE_STATE_BEFORE : SCENE_STATE_DURING; } else { // scenes with start and end if (progress < 0 && _state !== SCENE_STATE_BEFORE && reverseOrForward) { // go back to initial state _progress = 0; _state = SCENE_STATE_BEFORE; doUpdate = true; } else if (progress >= 0 && progress < 1 && reverseOrForward) { _progress = progress; _state = SCENE_STATE_DURING; doUpdate = true; } else if (progress >= 1 && _state !== SCENE_STATE_AFTER) { _progress = 1; _state = SCENE_STATE_AFTER; doUpdate = true; } else if (_state === SCENE_STATE_DURING && !reverseOrForward) { updatePinState(); // in case we scrolled backwards mid-scene and reverse is disabled => update the pin position, so it doesn't move back as well. } } if (doUpdate) { // fire events var eventVars = { progress: _progress, state: _state, scrollDirection: scrollDirection }, stateChanged = _state != oldState; var trigger = function (eventName) { // tmp helper to simplify code Scene.trigger(eventName, eventVars); }; if (stateChanged) { // enter events if (oldState !== SCENE_STATE_DURING) { trigger("enter"); trigger(oldState === SCENE_STATE_BEFORE ? "start" : "end"); } } trigger("progress"); if (stateChanged) { // leave events if (_state !== SCENE_STATE_DURING) { trigger(_state === SCENE_STATE_BEFORE ? "start" : "end"); trigger("leave"); } } } return Scene; } }; /** * Update the start and end scrollOffset of the container. * The positions reflect what the controller's scroll position will be at the start and end respectively. * Is called, when: * - Scene event "change" is called with: offset, triggerHook, duration * - scroll container event "resize" is called * - the position of the triggerElement changes * - the controller changes -> addTo() * @private */ var updateScrollOffset = function () { _scrollOffset = { start: _triggerPos + _options.offset }; if (_controller && _options.triggerElement) { // take away triggerHook portion to get relative to top _scrollOffset.start -= _controller.info("size") * _options.triggerHook; } _scrollOffset.end = _scrollOffset.start + _options.duration; }; /** * Updates the duration if set to a dynamic function. * This method is called when the scene is added to a controller and in regular intervals from the controller through scene.refresh(). * * @fires {@link Scene.change}, if the duration changed * @fires {@link Scene.shift}, if the duration changed * * @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed. * @private */ var updateDuration = function (suppressEvents) { // update duration if (_durationUpdateMethod) { var varname = "duration"; if (changeOption(varname, _durationUpdateMethod.call(Scene)) && !suppressEvents) { // set Scene.trigger("change", { what: varname, newval: _options[varname] }); Scene.trigger("shift", { reason: varname }); } } }; /** * Updates the position of the triggerElement, if present. * This method is called ... * - ... when the triggerElement is changed * - ... when the scene is added to a (new) controller * - ... in regular intervals from the controller through scene.refresh(). * * @fires {@link Scene.shift}, if the position changed * * @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed. * @private */ var updateTriggerElementPosition = function (suppressEvents) { var elementPos = 0, telem = _options.triggerElement; if (_controller && telem) { var controllerInfo = _controller.info(), containerOffset = _util.get.offset(controllerInfo.container), // container position is needed because element offset is returned in relation to document, not in relation to container. param = controllerInfo.vertical ? "top" : "left"; // which param is of interest ? // if parent is spacer, use spacer position instead so correct start position is returned for pinned elements. while (telem.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) { telem = telem.parentNode; } var elementOffset = _util.get.offset(telem); if (!controllerInfo.isDocument) { // container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent containerOffset[param] -= _controller.scrollPos(); } elementPos = elementOffset[param] - containerOffset[param]; } var changed = elementPos != _triggerPos; _triggerPos = elementPos; if (changed && !suppressEvents) { Scene.trigger("shift", { reason: "triggerElementPosition" }); } }; /** * Trigger a shift event, when the container is resized and the triggerHook is > 1. * @private */ var onContainerResize = function (e) { if (_options.triggerHook > 0) { Scene.trigger("shift", { reason: "containerResize" }); } }; var _validate = _util.extend(SCENE_OPTIONS.validate, { // validation for duration handled internally for reference to private var _durationMethod duration: function (val) { if (_util.type.String(val) && val.match(/^(\.|\d)*\d+%$/)) { // percentage value var perc = parseFloat(val) / 100; val = function () { return _controller ? _controller.info("size") * perc : 0; }; } if (_util.type.Function(val)) { // function _durationUpdateMethod = val; try { val = parseFloat(_durationUpdateMethod()); } catch (e) { val = -1; // will cause error below } } // val has to be float val = parseFloat(val); if (!_util.type.Number(val) || val < 0) { if (_durationUpdateMethod) { _durationUpdateMethod = undefined; throw ["Invalid return value of supplied function for option \"duration\":", val]; } else { throw ["Invalid value for option \"duration\":", val]; } } return val; } }); /** * Checks the validity of a specific or all options and reset to default if neccessary. * @private */ var validateOption = function (check) { check = arguments.length ? [check] : Object.keys(_validate); check.forEach(function (optionName, key) { var value; if (_validate[optionName]) { // there is a validation method for this option try { // validate value value = _validate[optionName](_options[optionName]); } catch (e) { // validation failed -> reset to default value = DEFAULT_OPTIONS[optionName]; var logMSG = _util.type.String(e) ? [e] : e; if (_util.type.Array(logMSG)) { logMSG[0] = "ERROR: " + logMSG[0]; logMSG.unshift(1); // loglevel 1 for error msg log.apply(this, logMSG); } else { log(1, "ERROR: Problem executing validation callback for option '" + optionName + "':", e.message); } } finally { _options[optionName] = value; } } }); }; /** * Helper used by the setter/getters for scene options * @private */ var changeOption = function (varname, newval) { var changed = false, oldval = _options[varname]; if (_options[varname] != newval) { _options[varname] = newval; validateOption(varname); // resets to default if necessary changed = oldval != _options[varname]; } return changed; }; // generate getters/setters for all options var addSceneOption = function (optionName) { if (!Scene[optionName]) { Scene[optionName] = function (newVal) { if (!arguments.length) { // get return _options[optionName]; } else { if (optionName === "duration") { // new duration is set, so any previously set function must be unset _durationUpdateMethod = undefined; } if (changeOption(optionName, newVal)) { // set Scene.trigger("change", { what: optionName, newval: _options[optionName] }); if (SCENE_OPTIONS.shifts.indexOf(optionName) > -1) { Scene.trigger("shift", { reason: optionName }); } } } return Scene; }; } }; /** * **Get** or **Set** the duration option value. * As a setter it also accepts a function returning a numeric value. * This is particularly useful for responsive setups. * * The duration is updated using the supplied function every time `Scene.refresh()` is called, which happens periodically from the controller (see ScrollMagic.Controller option `refreshInterval`). * _**NOTE:** Be aware that it's an easy way to kill performance, if you supply a function that has high CPU demand. * Even for size and position calculations it is recommended to use a variable to cache the value. (see example) * This counts double if you use the same function for multiple scenes._ * * @method ScrollMagic.Scene#duration * @example * // get the current duration value * var duration = scene.duration(); * * // set a new duration * scene.duration(300); * * // use a function to automatically adjust the duration to the window height. * var durationValueCache; * function getDuration () { * return durationValueCache; * } * function updateDuration (e) { * durationValueCache = window.innerHeight; * } * $(window).on("resize", updateDuration); // update the duration when the window size changes * $(window).triggerHandler("resize"); // set to initial value * scene.duration(getDuration); // supply duration method * * @fires {@link Scene.change}, when used as setter * @fires {@link Scene.shift}, when used as setter * @param {(number|function)} [newDuration] - The new duration of the scene. * @returns {number} `get` - Current scene duration. * @returns {Scene} `set` - Parent object for chaining. */ /** * **Get** or **Set** the offset option value. * @method ScrollMagic.Scene#offset * @example * // get the current offset * var offset = scene.offset(); * * // set a new offset * scene.offset(100); * * @fires {@link Scene.change}, when used as setter * @fires {@link Scene.shift}, when used as setter * @param {number} [newOffset] - The new offset of the scene. * @returns {number} `get` - Current scene offset. * @returns {Scene} `set` - Parent object for chaining. */ /** * **Get** or **Set** the triggerElement option value. * Does **not** fire `Scene.shift`, because changing the trigger Element doesn't necessarily mean the start position changes. This will be determined in `Scene.refresh()`, which is automatically triggered. * @method ScrollMagic.Scene#triggerElement * @example * // get the current triggerElement * var triggerElement = scene.triggerElement(); * * // set a new triggerElement using a selector * scene.triggerElement("#trigger"); * // set a new triggerElement using a DOM object * scene.triggerElement(document.getElementById("trigger")); * * @fires {@link Scene.change}, when used as setter * @param {(string|object)} [newTriggerElement] - The new trigger element for the scene. * @returns {(string|object)} `get` - Current triggerElement. * @returns {Scene} `set` - Parent object for chaining. */ /** * **Get** or **Set** the triggerHook option value. * @method ScrollMagic.Scene#triggerHook * @example * // get the current triggerHook value * var triggerHook = scene.triggerHook(); * * // set a new triggerHook using a string * scene.triggerHook("onLeave"); * // set a new triggerHook using a number * scene.triggerHook(0.7); * * @fires {@link Scene.change}, when used as setter * @fires {@link Scene.shift}, when used as setter * @param {(number|string)} [newTriggerHook] - The new triggerHook of the scene. See {@link Scene} parameter description for value options. * @returns {number} `get` - Current triggerHook (ALWAYS numerical). * @returns {Scene} `set` - Parent object for chaining. */ /** * **Get** or **Set** the reverse option value. * @method ScrollMagic.Scene#reverse * @example * // get the current reverse option * var reverse = scene.reverse(); * * // set new reverse option * scene.reverse(false); * * @fires {@link Scene.change}, when used as setter * @param {boolean} [newReverse] - The new reverse setting of the scene. * @returns {boolean} `get` - Current reverse option value. * @returns {Scene} `set` - Parent object for chaining. */ /** * **Get** or **Set** the loglevel option value. * @method ScrollMagic.Scene#loglevel * @example * // get the current loglevel * var loglevel = scene.loglevel(); * * // set new loglevel * scene.loglevel(3); * * @fires {@link Scene.change}, when used as setter * @param {number} [newLoglevel] - The new loglevel setting of the scene. `[0-3]` * @returns {number} `get` - Current loglevel. * @returns {Scene} `set` - Parent object for chaining. */ /** * **Get** the associated controller. * @method ScrollMagic.Scene#controller * @example * // get the controller of a scene * var controller = scene.controller(); * * @returns {ScrollMagic.Controller} Parent controller or `undefined` */ this.controller = function () { return _controller; }; /** * **Get** the current state. * @method ScrollMagic.Scene#state * @example * // get the current state * var state = scene.state(); * * @returns {string} `"BEFORE"`, `"DURING"` or `"AFTER"` */ this.state = function () { return _state; }; /** * **Get** the current scroll offset for the start of the scene. * Mind, that the scrollOffset is related to the size of the container, if `triggerHook` is bigger than `0` (or `"onLeave"`). * This means, that resizing the container or changing the `triggerHook` will influence the scene's start offset. * @method ScrollMagic.Scene#scrollOffset * @example * // get the current scroll offset for the start and end of the scene. * var start = scene.scrollOffset(); * var end = scene.scrollOffset() + scene.duration(); * console.log("the scene starts at", start, "and ends at", end); * * @returns {number} The scroll offset (of the container) at which the scene will trigger. Y value for vertical and X value for horizontal scrolls. */ this.scrollOffset = function () { return _scrollOffset.start; }; /** * **Get** the trigger position of the scene (including the value of the `offset` option). * @method ScrollMagic.Scene#triggerPosition * @example * // get the scene's trigger position * var triggerPosition = scene.triggerPosition(); * * @returns {number} Start position of the scene. Top position value for vertical and left position value for horizontal scrolls. */ this.triggerPosition = function () { var pos = _options.offset; // the offset is the basis if (_controller) { // get the trigger position if (_options.triggerElement) { // Element as trigger pos += _triggerPos; } else { // return the height of the triggerHook to start at the beginning pos += _controller.info("size") * Scene.triggerHook(); } } return pos; }; var _pin, _pinOptions; Scene.on("shift.internal", function (e) { var durationChanged = e.reason === "duration"; if ((_state === SCENE_STATE_AFTER && durationChanged) || (_state === SCENE_STATE_DURING && _options.duration === 0)) { // if [duration changed after a scene (inside scene progress updates pin position)] or [duration is 0, we are in pin phase and some other value changed]. updatePinState(); } if (durationChanged) { updatePinDimensions(); } }).on("progress.internal", function (e) { updatePinState(); }).on("add.internal", function (e) { updatePinDimensions(); }).on("destroy.internal", function (e) { Scene.removePin(e.reset); }); /** * Update the pin state. * @private */ var updatePinState = function (forceUnpin) { if (_pin && _controller) { var containerInfo = _controller.info(), pinTarget = _pinOptions.spacer.firstChild; // may be pin element or another spacer, if cascading pins if (!forceUnpin && _state === SCENE_STATE_DURING) { // during scene or if duration is 0 and we are past the trigger // pinned state if (_util.css(pinTarget, "position") != "fixed") { // change state before updating pin spacer (position changes due to fixed collapsing might occur.) _util.css(pinTarget, { "position": "fixed" }); // update pin spacer updatePinDimensions(); } var fixedPos = _util.get.offset(_pinOptions.spacer, true), // get viewport position of spacer scrollDistance = _options.reverse || _options.duration === 0 ? containerInfo.scrollPos - _scrollOffset.start // quicker : Math.round(_progress * _options.duration * 10) / 10; // if no reverse and during pin the position needs to be recalculated using the progress // add scrollDistance fixedPos[containerInfo.vertical ? "top" : "left"] += scrollDistance; // set new values _util.css(_pinOptions.spacer.firstChild, { top: fixedPos.top, left: fixedPos.left }); } else { // unpinned state var newCSS = { position: _pinOptions.inFlow ? "relative" : "absolute", top: 0, left: 0 }, change = _util.css(pinTarget, "position") != newCSS.position; if (!_pinOptions.pushFollowers) { newCSS[containerInfo.vertical ? "top" : "left"] = _options.duration * _progress; } else if (_options.duration > 0) { // only concerns scenes with duration if (_state === SCENE_STATE_AFTER && parseFloat(_util.css(_pinOptions.spacer, "padding-top")) === 0) { change = true; // if in after state but havent updated spacer yet (jumped past pin) } else if (_state === SCENE_STATE_BEFORE && parseFloat(_util.css(_pinOptions.spacer, "padding-bottom")) === 0) { // before change = true; // jumped past fixed state upward direction } } // set new values _util.css(pinTarget, newCSS); if (change) { // update pin spacer if state changed updatePinDimensions(); } } } }; /** * Update the pin spacer and/or element size. * The size of the spacer needs to be updated whenever the duration of the scene changes, if it is to push down following elements. * @private */ var updatePinDimensions = function () { if (_pin && _controller && _pinOptions.inFlow) { // no spacerresize, if original position is absolute var after = (_state === SCENE_STATE_AFTER), before = (_state === SCENE_STATE_BEFORE), during = (_state === SCENE_STATE_DURING), vertical = _controller.info("vertical"), pinTarget = _pinOptions.spacer.firstChild, // usually the pined element but can also be another spacer (cascaded pins) marginCollapse = _util.isMarginCollapseType(_util.css(_pinOptions.spacer, "display")), css = {}; // set new size // if relsize: spacer -> pin | else: pin -> spacer if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) { if (during) { _util.css(_pin, { "width": _util.get.width(_pinOptions.spacer) }); } else { _util.css(_pin, { "width": "100%" }); } } else { // minwidth is needed for cascaded pins. css["min-width"] = _util.get.width(vertical ? _pin : pinTarget, true, true); css.width = during ? css["min-width"] : "auto"; } if (_pinOptions.relSize.height) { if (during) { // the only padding the spacer should ever include is the duration (if pushFollowers = true), so we need to substract that. _util.css(_pin, { "height": _util.get.height(_pinOptions.spacer) - (_pinOptions.pushFollowers ? _options.duration : 0) }); } else { _util.css(_pin, { "height": "100%" }); } } else { // margin is only included if it's a cascaded pin to resolve an IE9 bug css["min-height"] = _util.get.height(vertical ? pinTarget : _pin, true, !marginCollapse); // needed for cascading pins css.height = during ? css["min-height"] : "auto"; } // add space for duration if pushFollowers is true if (_pinOptions.pushFollowers) { css["padding" + (vertical ? "Top" : "Left")] = _options.duration * _progress; css["padding" + (vertical ? "Bottom" : "Right")] = _options.duration * (1 - _progress); } _util.css(_pinOptions.spacer, css); } }; /** * Updates the Pin state (in certain scenarios) * If the controller container is not the document and we are mid-pin-phase scrolling or resizing the main document can result to wrong pin positions. * So this function is called on resize and scroll of the document. * @private */ var updatePinInContainer = function () { if (_controller && _pin && _state === SCENE_STATE_DURING && !_controller.info("isDocument")) { updatePinState(); } }; /** * Updates the Pin spacer size state (in certain scenarios) * If container is resized during pin and relatively sized the size of the pin might need to be updated... * So this function is called on resize of the container. * @private */ var updateRelativePinSpacer = function () { if (_controller && _pin && // well, duh _state === SCENE_STATE_DURING && // element in pinned state? ( // is width or height relatively sized, but not in relation to body? then we need to recalc. ((_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) && _util.get.width(window) != _util.get.width(_pinOptions.spacer.parentNode)) || (_pinOptions.relSize.height && _util.get.height(window) != _util.get.height(_pinOptions.spacer.parentNode)))) { updatePinDimensions(); } }; /** * Is called, when the mousewhel is used while over a pinned element inside a div container. * If the scene is in fixed state scroll events would be counted towards the body. This forwards the event to the scroll container. * @private */ var onMousewheelOverPin = function (e) { if (_controller && _pin && _state === SCENE_STATE_DURING && !_controller.info("isDocument")) { // in pin state e.preventDefault(); _controller._setScrollPos(_controller.info("scrollPos") - ((e.wheelDelta || e[_controller.info("vertical") ? "wheelDeltaY" : "wheelDeltaX"]) / 3 || -e.detail * 30)); } }; /** * Pin an element for the duration of the tween. * If the scene duration is 0 the element will only be unpinned, if the user scrolls back past the start position. * Make sure only one pin is applied to an element at the same time. * An element can be pinned multiple times, but only successively. * _**NOTE:** The option `pushFollowers` has no effect, when the scene duration is 0._ * @method ScrollMagic.Scene#setPin * @example * // pin element and push all following elements down by the amount of the pin duration. * scene.setPin("#pin"); * * // pin element and keeping all following elements in their place. The pinned element will move past them. * scene.setPin("#pin", {pushFollowers: false}); * * @param {(string|object)} element - A Selector targeting an element or a DOM object that is supposed to be pinned. * @param {object} [settings] - settings for the pin * @param {boolean} [settings.pushFollowers=true] - If `true` following elements will be "pushed" down for the duration of the pin, if `false` the pinned element will just scroll past them. Ignored, when duration is `0`. * @param {string} [settings.spacerClass="scrollmagic-pin-spacer"] - Classname of the pin spacer element, which is used to replace the element. * * @returns {Scene} Parent object for chaining. */ this.setPin = function (element, settings) { var defaultSettings = { pushFollowers: true, spacerClass: "scrollmagic-pin-spacer" }; settings = _util.extend({}, defaultSettings, settings); // validate Element element = _util.get.elements(element)[0]; if (!element) { log(1, "ERROR calling method 'setPin()': Invalid pin element supplied."); return Scene; // cancel } else if (_util.css(element, "position") === "fixed") { log(1, "ERROR calling method 'setPin()': Pin does not work with elements that are positioned 'fixed'."); return Scene; // cancel } if (_pin) { // preexisting pin? if (_pin === element) { // same pin we already have -> do nothing return Scene; // cancel } else { // kill old pin Scene.removePin(); } } _pin = element; var parentDisplay = _pin.parentNode.style.display, boundsParams = ["top", "left", "bottom", "right", "margin", "marginLeft", "marginRight", "marginTop", "marginBottom"]; _pin.parentNode.style.display = 'none'; // hack start to force css to return stylesheet values instead of calculated px values. var inFlow = _util.css(_pin, "position") != "absolute", pinCSS = _util.css(_pin, boundsParams.concat(["display"])), sizeCSS = _util.css(_pin, ["width", "height"]); _pin.parentNode.style.display = parentDisplay; // hack end. if (!inFlow && settings.pushFollowers) { log(2, "WARNING: If the pinned element is positioned absolutely pushFollowers will be disabled."); settings.pushFollowers = false; } window.setTimeout(function () { // wait until all finished, because with responsive duration it will only be set after scene is added to controller if (_pin && _options.duration === 0 && settings.pushFollowers) { log(2, "WARNING: pushFollowers =", true, "has no effect, when scene duration is 0."); } }, 0); // create spacer and insert var spacer = _pin.parentNode.insertBefore(document.createElement('div'), _pin), spacerCSS = _util.extend(pinCSS, { position: inFlow ? "relative" : "absolute", boxSizing: "content-box", mozBoxSizing: "content-box", webkitBoxSizing: "content-box" }); if (!inFlow) { // copy size if positioned absolutely, to work for bottom/right positioned elements. _util.extend(spacerCSS, _util.css(_pin, ["width", "height"])); } _util.css(spacer, spacerCSS); spacer.setAttribute(PIN_SPACER_ATTRIBUTE, ""); _util.addClass(spacer, settings.spacerClass); // set the pin Options _pinOptions = { spacer: spacer, relSize: { // save if size is defined using % values. if so, handle spacer resize differently... width: sizeCSS.width.slice(-1) === "%", height: sizeCSS.height.slice(-1) === "%", autoFullWidth: sizeCSS.width === "auto" && inFlow && _util.isMarginCollapseType(pinCSS.display) }, pushFollowers: settings.pushFollowers, inFlow: inFlow, // stores if the element takes up space in the document flow }; if (!_pin.___origStyle) { _pin.___origStyle = {}; var pinInlineCSS = _pin.style, copyStyles = boundsParams.concat(["width", "height", "position", "boxSizing", "mozBoxSizing", "webkitBoxSizing"]); copyStyles.forEach(function (val) { _pin.___origStyle[val] = pinInlineCSS[val] || ""; }); } // if relative size, transfer it to spacer and make pin calculate it... if (_pinOptions.relSize.width) { _util.css(spacer, { width: sizeCSS.width }); } if (_pinOptions.relSize.height) { _util.css(spacer, { height: sizeCSS.height }); } // now place the pin element inside the spacer spacer.appendChild(_pin); // and set new css _util.css(_pin, { position: inFlow ? "relative" : "absolute", margin: "auto", top: "auto", left: "auto", bottom: "auto", right: "auto" }); if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) { _util.css(_pin, { boxSizing: "border-box", mozBoxSizing: "border-box", webkitBoxSizing: "border-box" }); } // add listener to document to update pin position in case controller is not the document. window.addEventListener('scroll', updatePinInContainer); window.addEventListener('resize', updatePinInContainer); window.addEventListener('resize', updateRelativePinSpacer); // add mousewheel listener to catch scrolls over fixed elements _pin.addEventListener("mousewheel", onMousewheelOverPin); _pin.addEventListener("DOMMouseScroll", onMousewheelOverPin); log(3, "added pin"); // finally update the pin to init updatePinState(); return Scene; }; /** * Remove the pin from the scene. * @method ScrollMagic.Scene#removePin * @example * // remove the pin from the scene without resetting it (the spacer is not removed) * scene.removePin(); * * // remove the pin from the scene and reset the pin element to its initial position (spacer is removed) * scene.removePin(true); * * @param {boolean} [reset=false] - If `false` the spacer will not be removed and the element's position will not be reset. * @returns {Scene} Parent object for chaining. */ this.removePin = function (reset) { if (_pin) { if (_state === SCENE_STATE_DURING) { updatePinState(true); // force unpin at position } if (reset || !_controller) { // if there's no controller no progress was made anyway... var pinTarget = _pinOptions.spacer.firstChild; // usually the pin element, but may be another spacer (cascaded pins)... if (pinTarget.hasAttribute(PIN_SPACER_ATTRIBUTE)) { // copy margins to child spacer var style = _pinOptions.spacer.style, values = ["margin", "marginLeft", "marginRight", "marginTop", "marginBottom"]; margins = {}; values.forEach(function (val) { margins[val] = style[val] || ""; }); _util.css(pinTarget, margins); } _pinOptions.spacer.parentNode.insertBefore(pinTarget, _pinOptions.spacer); _pinOptions.spacer.parentNode.removeChild(_pinOptions.spacer); if (!_pin.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) { // if it's the last pin for this element -> restore inline styles // TODO: only correctly set for first pin (when cascading) - how to fix? _util.css(_pin, _pin.___origStyle); delete _pin.___origStyle; } } window.removeEventListener('scroll', updatePinInContainer); window.removeEventListener('resize', updatePinInContainer); window.removeEventListener('resize', updateRelativePinSpacer); _pin.removeEventListener("mousewheel", onMousewheelOverPin); _pin.removeEventListener("DOMMouseScroll", onMousewheelOverPin); _pin = undefined; log(3, "removed pin (reset: " + (reset ? "true" : "false") + ")"); } return Scene; }; var _cssClasses, _cssClassElems = []; Scene.on("destroy.internal", function (e) { Scene.removeClassToggle(e.reset); }); /** * Define a css class modification while the scene is active. * When the scene triggers the classes will be added to the supplied element and removed, when the scene is over. * If the scene duration is 0 the classes will only be removed if the user scrolls back past the start position. * @method ScrollMagic.Scene#setClassToggle * @example * // add the class 'myclass' to the element with the id 'my-elem' for the duration of the scene * scene.setClassToggle("#my-elem", "myclass"); * * // add multiple classes to multiple elements defined by the selector '.classChange' * scene.setClassToggle(".classChange", "class1 class2 class3"); * * @param {(string|object)} element - A Selector targeting one or more elements or a DOM object that is supposed to be modified. * @param {string} classes - One or more Classnames (separated by space) that should be added to the element during the scene. * * @returns {Scene} Parent object for chaining. */ this.setClassToggle = function (element, classes) { var elems = _util.get.elements(element); if (elems.length === 0 || !_util.type.String(classes)) { log(1, "ERROR calling method 'setClassToggle()': Invalid " + (elems.length === 0 ? "element" : "classes") + " supplied."); return Scene; } if (_cssClassElems.length > 0) { // remove old ones Scene.removeClassToggle(); } _cssClasses = classes; _cssClassElems = elems; Scene.on("enter.internal_class leave.internal_class", function (e) { var toggle = e.type === "enter" ? _util.addClass : _util.removeClass; _cssClassElems.forEach(function (elem, key) { toggle(elem, _cssClasses); }); }); return Scene; }; /** * Remove the class binding from the scene. * @method ScrollMagic.Scene#removeClassToggle * @example * // remove class binding from the scene without reset * scene.removeClassToggle(); * * // remove class binding and remove the changes it caused * scene.removeClassToggle(true); * * @param {boolean} [reset=false] - If `false` and the classes are currently active, they will remain on the element. If `true` they will be removed. * @returns {Scene} Parent object for chaining. */ this.removeClassToggle = function (reset) { if (reset) { _cssClassElems.forEach(function (elem, key) { _util.removeClass(elem, _cssClasses); }); } Scene.off("start.internal_class end.internal_class"); _cssClasses = undefined; _cssClassElems = []; return Scene; }; // INIT construct(); return Scene; }; // store pagewide scene options var SCENE_OPTIONS = { defaults: { duration: 0, offset: 0, triggerElement: undefined, triggerHook: 0.5, reverse: true, loglevel: 2 }, validate: { offset: function (val) { val = parseFloat(val); if (!_util.type.Number(val)) { throw ["Invalid value for option \"offset\":", val]; } return val; }, triggerElement: function (val) { val = val || undefined; if (val) { var elem = _util.get.elements(val)[0]; if (elem) { val = elem; } else { throw ["Element defined in option \"triggerElement\" was not found:", val]; } } return val; }, triggerHook: function (val) { var translate = { "onCenter": 0.5, "onEnter": 1, "onLeave": 0 }; if (_util.type.Number(val)) { val = Math.max(0, Math.min(parseFloat(val), 1)); // make sure its betweeen 0 and 1 } else if (val in translate) { val = translate[val]; } else { throw ["Invalid value for option \"triggerHook\": ", val]; } return val; }, reverse: function (val) { return !!val; // force boolean }, loglevel: function (val) { val = parseInt(val); if (!_util.type.Number(val) || val < 0 || val > 3) { throw ["Invalid value for option \"loglevel\":", val]; } return val; } }, // holder for validation methods. duration validation is handled in 'getters-setters.js' shifts: ["duration", "offset", "triggerHook"], // list of options that trigger a `shift` event }; /* * method used to add an option to ScrollMagic Scenes. * TODO: DOC (private for dev) */ ScrollMagic.Scene.addOption = function (name, defaultValue, validationCallback, shifts) { if (!(name in SCENE_OPTIONS.defaults)) { SCENE_OPTIONS.defaults[name] = defaultValue; SCENE_OPTIONS.validate[name] = validationCallback; if (shifts) { SCENE_OPTIONS.shifts.push(name); } } else { ScrollMagic._util.log(1, "[static] ScrollMagic.Scene -> Cannot add Scene option '" + name + "', because it already exists."); } }; // instance extension function for plugins // TODO: DOC (private for dev) ScrollMagic.Scene.extend = function (extension) { var oldClass = this; ScrollMagic.Scene = function () { oldClass.apply(this, arguments); this.$super = _util.extend({}, this); // copy parent state return extension.apply(this, arguments) || this; }; _util.extend(ScrollMagic.Scene, oldClass); // copy properties ScrollMagic.Scene.prototype = oldClass.prototype; // copy prototype ScrollMagic.Scene.prototype.constructor = ScrollMagic.Scene; // restore constructor }; /** * TODO: DOCS (private for dev) * @class * @private */ ScrollMagic.Event = function (type, namespace, target, vars) { vars = vars || {}; for (var key in vars) { this[key] = vars[key]; } this.type = type; this.target = this.currentTarget = target; this.namespace = namespace || ''; this.timeStamp = this.timestamp = Date.now(); return this; }; /* * TODO: DOCS (private for dev) */ var _util = ScrollMagic._util = (function (window) { var U = {}, i; /** * ------------------------------ * internal helpers * ------------------------------ */ // parse float and fall back to 0. var floatval = function (number) { return parseFloat(number) || 0; }; // get current style IE safe (otherwise IE would return calculated values for 'auto') var _getComputedStyle = function (elem) { return elem.currentStyle ? elem.currentStyle : window.getComputedStyle(elem); }; // get element dimension (width or height) var _dimension = function (which, elem, outer, includeMargin) { elem = (elem === document) ? window : elem; if (elem === window) { includeMargin = false; } else if (!_type.DomElement(elem)) { return 0; } which = which.charAt(0).toUpperCase() + which.substr(1).toLowerCase(); var dimension = (outer ? elem['offset' + which] || elem['outer' + which] : elem['client' + which] || elem['inner' + which]) || 0; if (outer && includeMargin) { var style = _getComputedStyle(elem); dimension += which === 'Height' ? floatval(style.marginTop) + floatval(style.marginBottom) : floatval(style.marginLeft) + floatval(style.marginRight); } return dimension; }; // converts 'margin-top' into 'marginTop' var _camelCase = function (str) { return str.replace(/^[^a-z]+([a-z])/g, '$1').replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); }; /** * ------------------------------ * external helpers * ------------------------------ */ // extend obj – same as jQuery.extend({}, objA, objB) U.extend = function (obj) { obj = obj || {}; for (i = 1; i < arguments.length; i++) { if (!arguments[i]) { continue; } for (var key in arguments[i]) { if (arguments[i].hasOwnProperty(key)) { obj[key] = arguments[i][key]; } } } return obj; }; // check if a css display type results in margin-collapse or not U.isMarginCollapseType = function (str) { return ["block", "flex", "list-item", "table", "-webkit-box"].indexOf(str) > -1; }; // implementation of requestAnimationFrame // based on https://gist.github.com/paulirish/1579671 var lastTime = 0, vendors = ['ms', 'moz', 'webkit', 'o']; var _requestAnimationFrame = window.requestAnimationFrame; var _cancelAnimationFrame = window.cancelAnimationFrame; // try vendor prefixes if the above doesn't work for (i = 0; !_requestAnimationFrame && i < vendors.length; ++i) { _requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame']; _cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'] || window[vendors[i] + 'CancelRequestAnimationFrame']; } // fallbacks if (!_requestAnimationFrame) { _requestAnimationFrame = function (callback) { var currTime = new Date().getTime(), timeToCall = Math.max(0, 16 - (currTime - lastTime)), id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!_cancelAnimationFrame) { _cancelAnimationFrame = function (id) { window.clearTimeout(id); }; } U.rAF = _requestAnimationFrame.bind(window); U.cAF = _cancelAnimationFrame.bind(window); var loglevels = ["error", "warn", "log"], console = window.console || {}; console.log = console.log || function () {}; // no console log, well - do nothing then... // make sure methods for all levels exist. for (i = 0; i < loglevels.length; i++) { var method = loglevels[i]; if (!console[method]) { console[method] = console.log; // prefer .log over nothing } } U.log = function (loglevel) { if (loglevel > loglevels.length || loglevel <= 0) loglevel = loglevels.length; var now = new Date(), time = ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2) + ":" + ("0" + now.getSeconds()).slice(-2) + ":" + ("00" + now.getMilliseconds()).slice(-3), method = loglevels[loglevel - 1], args = Array.prototype.splice.call(arguments, 1), func = Function.prototype.bind.call(console[method], console); args.unshift(time); func.apply(console, args); }; /** * ------------------------------ * type testing * ------------------------------ */ var _type = U.type = function (v) { return Object.prototype.toString.call(v).replace(/^\[object (.+)\]$/, "$1").toLowerCase(); }; _type.String = function (v) { return _type(v) === 'string'; }; _type.Function = function (v) { return _type(v) === 'function'; }; _type.Array = function (v) { return Array.isArray(v); }; _type.Number = function (v) { return !_type.Array(v) && (v - parseFloat(v) + 1) >= 0; }; _type.DomElement = function (o) { return ( typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2 o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"); }; /** * ------------------------------ * DOM Element info * ------------------------------ */ // always returns a list of matching DOM elements, from a selector, a DOM element or an list of elements or even an array of selectors var _get = U.get = {}; _get.elements = function (selector) { var arr = []; if (_type.String(selector)) { try { selector = document.querySelectorAll(selector); } catch (e) { // invalid selector return arr; } } if (_type(selector) === 'nodelist' || _type.Array(selector)) { for (var i = 0, ref = arr.length = selector.length; i < ref; i++) { // list of elements var elem = selector[i]; arr[i] = _type.DomElement(elem) ? elem : _get.elements(elem); // if not an element, try to resolve recursively } } else if (_type.DomElement(selector) || selector === document || selector === window) { arr = [selector]; // only the element } return arr; }; // get scroll top value _get.scrollTop = function (elem) { return (elem && typeof elem.scrollTop === 'number') ? elem.scrollTop : window.pageYOffset || 0; }; // get scroll left value _get.scrollLeft = function (elem) { return (elem && typeof elem.scrollLeft === 'number') ? elem.scrollLeft : window.pageXOffset || 0; }; // get element height _get.width = function (elem, outer, includeMargin) { return _dimension('width', elem, outer, includeMargin); }; // get element width _get.height = function (elem, outer, includeMargin) { return _dimension('height', elem, outer, includeMargin); }; // get element position (optionally relative to viewport) _get.offset = function (elem, relativeToViewport) { var offset = { top: 0, left: 0 }; if (elem && elem.getBoundingClientRect) { // check if available var rect = elem.getBoundingClientRect(); offset.top = rect.top; offset.left = rect.left; if (!relativeToViewport) { // clientRect is by default relative to viewport... offset.top += _get.scrollTop(); offset.left += _get.scrollLeft(); } } return offset; }; /** * ------------------------------ * DOM Element manipulation * ------------------------------ */ U.addClass = function (elem, classname) { if (classname) { if (elem.classList) elem.classList.add(classname); else elem.className += ' ' + classname; } }; U.removeClass = function (elem, classname) { if (classname) { if (elem.classList) elem.classList.remove(classname); else elem.className = elem.className.replace(new RegExp('(^|\\b)' + classname.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } }; // if options is string -> returns css value // if options is array -> returns object with css value pairs // if options is object -> set new css values U.css = function (elem, options) { if (_type.String(options)) { return _getComputedStyle(elem)[_camelCase(options)]; } else if (_type.Array(options)) { var obj = {}, style = _getComputedStyle(elem); options.forEach(function (option, key) { obj[option] = style[_camelCase(option)]; }); return obj; } else { for (var option in options) { var val = options[option]; if (val == parseFloat(val)) { // assume pixel for seemingly numerical values val += 'px'; } elem.style[_camelCase(option)] = val; } } }; return U; }(window || {})); ScrollMagic.Scene.prototype.addIndicators = function () { ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling addIndicators() due to missing Plugin \'debug.addIndicators\'. Please make sure to include plugins/debug.addIndicators.js'); return this; } ScrollMagic.Scene.prototype.removeIndicators = function () { ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeIndicators() due to missing Plugin \'debug.addIndicators\'. Please make sure to include plugins/debug.addIndicators.js'); return this; } ScrollMagic.Scene.prototype.setTween = function () { ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling setTween() due to missing Plugin \'animation.gsap\'. Please make sure to include plugins/animation.gsap.js'); return this; } ScrollMagic.Scene.prototype.removeTween = function () { ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeTween() due to missing Plugin \'animation.gsap\'. Please make sure to include plugins/animation.gsap.js'); return this; } ScrollMagic.Scene.prototype.setVelocity = function () { ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling setVelocity() due to missing Plugin \'animation.velocity\'. Please make sure to include plugins/animation.velocity.js'); return this; } ScrollMagic.Scene.prototype.removeVelocity = function () { ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeVelocity() due to missing Plugin \'animation.velocity\'. Please make sure to include plugins/animation.velocity.js'); return this; } return ScrollMagic; })); // Copyright (c) 2015 Florian Hartmann, https://github.com/florian https://github.com/florian/cookie.js !function (document, undefined) { var cookie = function () { return cookie.get.apply(cookie, arguments); }; var utils = cookie.utils = { // Is the given value an array? Use ES5 Array.isArray if it's available. isArray: Array.isArray || function (value) { return Object.prototype.toString.call(value) === '[object Array]'; }, // Is the given value a plain object / an object whose constructor is `Object`? isPlainObject: function (value) { return !!value && Object.prototype.toString.call(value) === '[object Object]'; }, // Convert an array-like object to an array – for example `arguments`. toArray: function (value) { return Array.prototype.slice.call(value); }, // Get the keys of an object. Use ES5 Object.keys if it's available. getKeys: Object.keys || function (obj) { var keys = [], key = ''; for (key in obj) { if (obj.hasOwnProperty(key)) keys.push(key); } return keys; }, // Unlike JavaScript's built-in escape functions, this method // only escapes characters that are not allowed in cookies. encode: function (value) { return String(value).replace(/[,;"\\=\s%]/g, function (character) { return encodeURIComponent(character); }); }, decode: function (value) { return decodeURIComponent(value); }, // Return fallback if the value is not defined, otherwise return value. retrieve: function (value, fallback) { return value == null ? fallback : value; } }; cookie.defaults = {}; cookie.expiresMultiplier = 60 * 60 * 24; cookie.set = function (key, value, options) { if (utils.isPlainObject(key)) { // `key` contains an object with keys and values for cookies, `value` contains the options object. for (var k in key) { if (key.hasOwnProperty(k)) this.set(k, key[k], value); } } else { options = utils.isPlainObject(options) ? options : { expires: options }; // Empty string for session cookies. var expires = options.expires !== undefined ? options.expires : (this.defaults.expires || ''), expiresType = typeof(expires); if (expiresType === 'string' && expires !== '') expires = new Date(expires); else if (expiresType === 'number') expires = new Date(+new Date + 1000 * this.expiresMultiplier * expires); // This is needed because IE does not support the `max-age` cookie attribute. if (expires !== '' && 'toGMTString' in expires) expires = ';expires=' + expires.toGMTString(); var path = options.path || this.defaults.path; path = path ? ';path=' + path : ''; var domain = options.domain || this.defaults.domain; domain = domain ? ';domain=' + domain : ''; var secure = options.secure || this.defaults.secure ? ';secure' : ''; if (options.secure === false) secure = ''; document.cookie = utils.encode(key) + '=' + utils.encode(value) + expires + path + domain + secure; } return this; // Return the `cookie` object to make chaining possible. }; cookie.setDefault = function (key, value, options) { if (utils.isPlainObject(key)) { for (var k in key) { if (this.get(k) === undefined) this.set(k, key[k], value); } return cookie; } else { if (this.get(key) === undefined) return this.set.apply(this, arguments); } }, cookie.remove = function (keys) { keys = utils.isArray(keys) ? keys : utils.toArray(arguments); for (var i = 0, l = keys.length; i < l; i++) { this.set(keys[i], '', -1); } return this; // Return the `cookie` object to make chaining possible. }; cookie.removeSpecific = function (keys, options) { if (!options) return this.remove(keys); keys = utils.isArray(keys) ? keys : [keys]; options.expires = -1; for (var i = 0, l = keys.length; i < l; i++) { this.set(keys[i], '', options); } return this; // Return the `cookie` object to make chaining possible. }; cookie.empty = function () { return this.remove(utils.getKeys(this.all())); }; cookie.get = function (keys, fallback) { var cookies = this.all(); if (utils.isArray(keys)) { var result = {}; for (var i = 0, l = keys.length; i < l; i++) { var value = keys[i]; result[value] = utils.retrieve(cookies[value], fallback); } return result; } else return utils.retrieve(cookies[keys], fallback); }; cookie.all = function () { if (document.cookie === '') return {}; var cookies = document.cookie.split('; '), result = {}; for (var i = 0, l = cookies.length; i < l; i++) { var item = cookies[i].split('='); var key = utils.decode(item.shift()); var value = utils.decode(item.join('=')); result[key] = value; } return result; }; cookie.enabled = function () { if (navigator.cookieEnabled) return true; var ret = cookie.set('_', '_').get('_') === '_'; cookie.remove('_'); return ret; }; // If an AMD loader is present use AMD. // If a CommonJS loader is present use CommonJS. // Otherwise assign the `cookie` object to the global scope. if (typeof define === 'function' && define.amd) { define(function () { return {cookie: cookie}; }); } else if (typeof exports !== 'undefined') { exports.cookie = cookie; } else window.cookie = cookie; // If used e.g. with Browserify and CommonJS, document is not declared. }(typeof document === 'undefined' ? null : document); 'use strict'; //utilities var Mediator = (function () { var options = { allowDuplicate: false //allow duplicated subscribe channel for identical object }; var channels = {}; var subscribe = function(channel, fn) { //avoid duplicate sub for identical object //un-subscribe before add new callback if ( !options.allowDuplicate && channels[channel] ) { unSubscribe.apply(this, [channel]); } if ( !channels[channel] ) { channels[channel] = []; } channels[channel].push({ context: this, callback: fn }); return this; } var unSubscribe = function(channel) { if ( !channels[channel] ) { return false; } for (var i = 0, l = channels[channel].length; i < l; i++) { if ( channels[channel][i].context === this ) { channels[channel].splice(i, 1); break; } } return this; } var publish = function(channel) { if ( !channels[channel] ) { return false; } var args = Array.prototype.slice.call(arguments, 1); for (var i = 0, l = channels[channel].length; i < l; i++) { var subscription = channels[channel][i]; subscription.callback.apply(subscription.context, args); } return this; } var setOpts = function(name, value) { if ( !options[name] ) { return false; } options[name] = value; } return { pub: publish, sub: subscribe, unsub: unSubscribe, installTo: function(obj) { obj.pub = publish; obj.sub = subscribe; obj.unsub = unSubscribe; obj.setOpts = setOpts; } } })(); var Helpers = { throttle: function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; var now = Date.now || function() { return new Date().getTime(); } if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var _now = now(); if (!previous && options.leading === false) previous = _now; var remaining = wait - (_now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; } }, debounce: function(func, wait, immediate) { var timeout, args, context, timestamp, result; var now = Date.now || function() { return new Date().getTime(); } var later = function() { var last = now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) { context = args = null; } } } } return function() { context = this; args = arguments; timestamp = now(); var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { result = func.apply(context, args); context = args = null; } return result; } }, prefixMethod: function(obj, method) { var pfx = ['webkit', 'moz', 'ms', 'o', '']; var p = 0, m, t; while (p < pfx.length && !obj[m]) { m = method; if (pfx[p] == '') { m = m.substr(0,1).toLowerCase() + m.substr(1); } m = pfx[p] + m; t = typeof obj[m]; if (t != 'undefined') { pfx = [pfx[p]]; return (t == 'function' ? obj[m]() : obj[m]); } p++; } }, isFullscreen: function() { return Helpers.prefixMethod(document, 'FullScreen') || Helpers.prefixMethod(document, 'IsFullScreen'); }, setFullscreen: function(el) { Helpers.prefixMethod(el, 'RequestFullScreen'); }, closeFullscreen: function() { return Helpers.prefixMethod(document, 'CancelFullScreen'); } }; var modalConfig = { theme: 'jconfirm-festivefolks', boxWidth: '426px', animation: 'top', closeAnimation: 'zoom', closeIcon: true, useBootstrap: false, backgroundDismiss: true, animationBounce: 1.5 }; window.alert = function(msg, title, autoClose) { var o = $.alert( $.extend({}, modalConfig, { title: title !== undefined ? title : 'Oops!', content: msg }) ); if ( autoClose !== undefined ) { setTimeout(function() { o.close(); }, autoClose); } }; window.REMODAL_GLOBALS = { NAMESPACE: 'modal', DEFAULTS: { hashTracking: false } }; (function($, _, mediator, helpers) { $(document).ready(function() { var $htmlBody = $('html,body'); var $main = $('#wrapper'); var $document = $(this); var $window = $(window); var $body = $('body').eq(0); var $header = $('header').eq(0); var $footer = $('footer').eq(0); var $topBar = $('.top-bar').eq(0); var $topBtn = $('.top-btn'); var isTouch = ('ontouchstart' in document.documentElement); //scroll throttle var windowScrollThrottle = helpers.throttle(function() { $body.toggleClass( 'onscroll', $window.scrollTop() > 0 ); $body.toggleClass( 'above-the-fold', $window.scrollTop() < $window.height() ); }, 500); $window.on( 'scroll', windowScrollThrottle ); //image cover func facade var imgCoverFunc = function(imgs) { imgs.each(function() { var $this = $(this); var wrapper = $this.parent(); var src = $this.attr('src'); if ( src != '' ) { var img = new Image; img.onerror = function() { } img.onload = function() { wrapper.css({ 'background-image': 'url(' + src +')', 'background-repeat': 'no-repeat', 'background-position': 'center center', 'background-size': 'cover' }); } img.src = src; } }); } imgCoverFunc( $('.img-cover') ); //prevent right-click $document.on('contextmenu', 'img', function() { return false; }); //loading page callback var scaleElementFunc = function(scale) { var $this = $(this).removeClass('hidden'); var xy = $this.attr('data-xy').split(' '); var transX = parseFloat( xy[0] ); var transY = parseFloat( xy[1] ); var offsetX = $this.width() - $window.width(); var offsetY = $this.height() - $window.height(); if ( offsetX > 0 ) { transX += (-offsetX/2)/scale; } $this.css({ 'transform': 'scale(' + scale + ') translate( ' + transX + 'px,' + transY + 'px)', '-webkit-transform': 'scale(' + scale + ') translate( ' + transX + 'px,' + transY + 'px)', 'moz-transform': 'scale(' + scale + ') translate( ' + transX + 'px,' + transY + 'px)', }); } var clearForm = function(form) { form.find('.feeling-happy').removeClass('feeling-happy'); form.find('.unhappy').removeClass('unhappy'); form.find('.unhappyMessage').remove(); form.find('input, textarea, select').val(''); form.find('select').addClass('default'); form.find('input[type="checkbox"], input[type="radio"]').removeAttr('checked'); } var onPageLoaded = function() { //page init var offsetTop = $header.height() + $topBar.height(); var onScrolling = false; $document.on('click', '.scroll-down', function(e) { if ( onScrolling ) { return false; } onScrolling = true; var $this = $(this); var target = $( $this.attr('href') ); $htmlBody.animate({ scrollTop: target.offset().top - offsetTop }, 1000, function(e) { onScrolling = false; }); return false; }); $document.on('click', 'a[href="#top-bar-close"]', function(e) { $body.addClass('no-top-bar'); return false; }); //select dropdown $document.on('change', 'select', function() { $(this).toggleClass( 'default', this.value == '' ) .parent().toggleClass( 'default', this.value == '' ); }); $document.on('focus', 'select', function() { $(this).parent().addClass('focus'); }); $document.on('blur', 'select', function() { $(this).parent().removeClass('focus'); }); //Popover var popoverWrapper = $('.popover-wrapper'); // if ( cookie.get('popover-visible') === undefined || !cookie.get('popover-visible') ) { // popoverWrapper.removeClass('hidden'); // } $document.on('click', '.dismiss-popover, .popover-overlay', function(e) { // if ( $('#popover-dismiss-checkbox').is(':checked') ) { // cookie.set('popover-visible', false); // } popoverWrapper.remove(); return false; }); //Landing if ( $body.hasClass('landing') ) { //normal, retina size, triple size, 4 times size ... var pxSize = 1; var mqCond = 'screen and (orientation: portrait)'; var landingWrapper = $('#landing-wrapper'); var landingBg = new Image; landingBg.onload = function(e) { // console.log( landingBg.width, landingBg.height ); // console.log( landingWrapper.width(), landingWrapper.height() ); var scaleX = landingWrapper.width()*pxSize/landingBg.width; var scaleY = landingWrapper.height()*pxSize/landingBg.height; var scale = scaleX > scaleY ? scaleX : scaleY; $('.landing-content > div:not(".hidden") .scale-element').each(function() { scaleElementFunc.call(this, scale); }); setTimeout(function() { landingWrapper.addClass('done'); setTimeout(function() { landingWrapper.addClass('ready'); landingWrapper.find('.page-loading').remove(); }, 500); }, 1000); } var fullpageContentDebounce = Helpers.debounce(function() { //on resize callback if ( Modernizr.mq(mqCond) ) { $('.landing-content .landing-full').addClass('hidden'); $('.landing-content .landing-compact').removeClass('hidden'); } else { $('.landing-content .landing-full').removeClass('hidden'); $('.landing-content .landing-compact').addClass('hidden'); } landingBg.src = landingWrapper.attr( Modernizr.mq(mqCond) ? 'data-bg-compact' : 'data-bg-full' ); }); $window.on( 'resize', fullpageContentDebounce ); fullpageContentDebounce(); } //Homepage if ( $body.hasClass('homepage') ) { //scroll to load content $window.on('scroll', function() { return $body.hasClass('scrolled'); }); var scrollHomepage = false; var scrollDownWheel = function(e) { if ( !$body.hasClass('loading') && !scrollHomepage ) { if ( e.deltaY < 0 ) { $('.homepage-scroll-down').eq(0).trigger('click'); } else { if ( $window.scrollTop() == 0 ) { $body.removeClass('scrolling'); setTimeout(function() { $body.removeClass('scrolled'); scrollHomepage = false; }, 1000); } } } } $document.on('mousewheel', function(e) { scrollDownWheel(e); }); try { $document.touchwipe({ wipeDown: function() { if ( !$body.hasClass('loading') && !scrollHomepage ) { $('.homepage-scroll-down').eq(0).trigger('click'); } }, wipeUp: function() { if ( !$body.hasClass('loading') && !scrollHomepage ) { if ( $window.scrollTop() == 0 ) { $body.removeClass('scrolling'); setTimeout(function() { $body.removeClass('scrolled'); scrollHomepage = false; }, 1000); } } }, min_move_x: 10, min_move_y: 10, preventDefaultEvents: false }); } catch(exp) {} var homepageHeaderContainer = $('#homepage-header-container'); var homepageContent = $('#homepage-content'); $document.on('click', '.homepage-scroll-down', function(e) { if ( scrollHomepage ) { return false; } scrollHomepage = true; $body.addClass('scrolling'); setTimeout(function() { $body.addClass('scrolled'); scrollHomepage = false; }, 1000); return false; }); //set page to top position var currentScrollTop = 0; setTimeout(function() { onScrolling = true; $htmlBody.animate({ scrollTop: 0 }, 0, function() { onScrolling = false; }); }, 300); //Browsers tend to jump back to their last scroll position on a reload, which makes sense in many cases. It seems that this automatic jump gets triggered right after the onload event (but we don't know the exact moment when this happens), so it makes sense to either use some delay, or have the browser scroll to the top before the page reloads. //normal, retina size, triple size, 4 times size ... var pxSize = 2; var mqCond = 'screen and (orientation: portrait)'; var homepageHeaderBg = new Image; var homepageHeaderWrapper = $('#homepage-header-wrapper'); homepageHeaderBg.onload = function(e) { // console.log( homepageHeaderBg.width, homepageHeaderBg.height ); // console.log( homepageHeaderWrapper.width(), homepageHeaderWrapper.height() ); var scale = homepageHeaderWrapper.height()*pxSize/homepageHeaderBg.height; $('.landing-content > div:not(".hidden") .scale-element').each(function() { scaleElementFunc.call(this, scale); }); setTimeout(function() { //page loading start fade out 1s homepageHeaderWrapper.addClass('done'); //page content start fade in 1s homepageHeaderWrapper.addClass('ready'); setTimeout(function() { homepageHeaderWrapper.find('.page-loading').remove(); $body.removeClass('loading'); }, 1000); }, 500); } var fullpageContentDebounce = Helpers.debounce(function() { //on resize callback if ( Modernizr.mq(mqCond) ) { $('.landing-content .landing-full').addClass('hidden'); $('.landing-content .landing-compact').removeClass('hidden'); } else { $('.landing-content .landing-full').removeClass('hidden'); $('.landing-content .landing-compact').addClass('hidden'); } homepageHeaderBg.src = homepageHeaderWrapper.attr( Modernizr.mq(mqCond) ? 'data-bg-compact' : 'data-bg-full' ); }); $window.on( 'resize', fullpageContentDebounce ); fullpageContentDebounce(); } //Character if ( $body.hasClass('character') ) { var scale = 1; //Character editor(get scale) var characterCreationWrapper = $('#character-creation-wrapper');//.css({ opacity: 0 }); var characterCreationBg = $('#character-creation-bg'); var characterCreationEditor = $('#character-creation-editor'); var elementsLoading = function(selector) { $(selector).each(function() { var $this = $(this); var loaded = 0; var checkLoaded = function() { if ( imgs.length == ++loaded ) { $this.addClass('loaded'); } } var imgs = $this.find('> img'); if ( imgs.length == 0 ) { $this.addClass('loaded'); } else { imgs.each(function() { var img = new Image; img.onload = function(e) { checkLoaded(); } img.onerror = function(e) { checkLoaded(); } img.src = this.src; }); } }); } //character tools var confirmTmpl = _.template('
<%= content %>
'); $document.on('click', '.confirmation', function(e) { var $target = $(this).addClass('active'); $( $target.attr('data-tooltip-wrapper') ).addClass('active'); if ( $target.hasClass('disabled') ) { return false; } var tooltip = $( confirmTmpl({content: 'Confirm?'}) ).appendTo('body'); tooltip .addClass( $target.attr('data-tooltip-style') ) .css({ top: $target.offset().top - tooltip.outerHeight() - 10, left: $target.offset().left - ( tooltip.outerWidth() - $target.outerWidth()*scale )/2 }); return false; }); $document.on('click', function(e) { $( $('.confirmation.active').removeClass('active').attr('data-tooltip-wrapper') ).removeClass('active'); $('.tooltip').fadeOut('fast', function() { $(this).remove(); }); }); var setCharacterElementsLayout = function() { if ( $body.width() <= 768 ) { var itemPerPage = 4; var elementWidth = $('#character-elements-scrollable').width()/itemPerPage; var characterElements = $('ul.character-elements li:not(".hidden")'); //set
    width characterElements.parent().css({ width: elementWidth*characterElements.length }); //set
  • width characterElements.each(function() { $(this).css({ width: elementWidth }) }); characterElements.filter(':not(".hidden")').eq(0).addClass('first-child'); $('ul.character-elements').removeClass('loading'); } } //Step 1 if ( $body.hasClass('character-step-1') ) { elementsLoading('.character-elements-item, .character-bg-content, .droppable-content'); var maxChars = parseInt( $('#droppable-chars-max').val() ); var droppableZone = $('#character-droppable-zone'); var droppableChars = droppableZone.find('> .char > .droppable > .droppable-content'); //Textboxes $('.artwork-textbox').each(function() { var $this = $(this); var size = $this.attr('data-size').split(','); var translate = $this.attr('data-translate').split(','); var rotate = $this.attr('data-rotate'); var scale = $this.attr('data-scale').split(','); size[0] = size[0]*droppableZone.width(); size[1] = size[1]*droppableZone.height(); var offsetX = size[0]*(scale[0] - 1)/2; var offsetY = size[1]*(scale[1] - 1)/2; var transform = 'translate(' + (translate[0]*size[0] - offsetX) + 'px,' + (translate[1]*size[1] - offsetY) + 'px) rotate(' + rotate + 'deg)'; $this.css({ 'color': $this.attr('data-text-color'), 'width': size[0]*scale[0], 'height': size[1]*scale[1], 'transform': transform, '-moz-transform': transform, '-webkit-transform': transform }); //input text // $this.find('> div').eq(0).textfill(); $.get( $('#root_url').val() + '/storage/app/media/artwork-font.ttf', function(data, status, jqXhr) { $this.find('> div').eq(0).fitTextBox(); } ); }); $document.on('keyup', '.artwork-textbox > div', function() { clearSavedState(); }); //Helpers var clearSavedState = function() { $('.flipper').removeClass('animate'); } var hideCharOptions = function() { $('body > .char-options') .addClass('hidden') .appendTo('.char .droppable.focus'); $('.char .droppable.focus').removeClass('focus'); } var putCharIn = function(char, droppable) { var charDroppable = char.parent(); var charWrapper = charDroppable.parent(); var chardata = JSON.parse( char.attr('data-chardata') ).poses[ droppable.attr('data-pose')-1 ]; //update droppable zone of new dropped var charDroppableCoords = chardata.coords; var charDoppableHeight = 100 - charDroppableCoords[3] - charDroppableCoords[1]; var targetCoords = JSON.parse( droppable.attr('data-coords') ); var targetHeight = 100 - targetCoords[3] - targetCoords[1]; var offsetY = droppable.attr('data-baseline') == 'foot' ? 0 : ( charDoppableHeight - targetHeight ); offsetY = offsetY <= 0 ? offsetY : 0; droppable.css({ left: charDroppableCoords[0] + '%', top: charDroppableCoords[1] + offsetY + '%', width: ( 100 - charDroppableCoords[2] - charDroppableCoords[0] ) + '%', height: charDoppableHeight + '%', }); //update pos char .attr( 'src', chardata.thumb_crop ) .attr( 'data-char', droppable.attr('data-char') ) .attr( 'data-offset-y', offsetY + '%' ); } var getEditLink = function(href, data) { //update edit link var editLinkUrl = href.split('?'); var editLinkQueries = editLinkUrl[1]; editLinkQueries = editLinkQueries == '' ? '' : editLinkQueries.split('&'); editLinkQueries = $.map(editLinkQueries, function(value, index) { var params = value.split('='); return params[0] + '=' + ( data[ params[0] ] !== undefined ? data[ params[0] ] : params[1] ); }); return editLinkUrl[0] + '?' + editLinkQueries.join('&'); } var checkMaxChars = function() { droppableChars.parent().removeClass('disabled'); // if ( droppableZone.find('> .char > .droppable > .droppable-content > img.primary').length == maxChars ) { // droppableChars.filter(function() { // return $(this).find('> *').length == 0; // }).parent().addClass('disabled'); // } } var autoSave = function() { //fetch data var postData = []; $('.char .primary').each(function() { var $this = $(this); postData.push({ char: $this.attr('data-char'), id: $this.attr('data-char-id'), chardata: $this.attr('data-chardata'), offsetY: $this.attr('data-offset-y') }); }); $.request('charactereditor::onSaveCanvasSession', { data: { data: postData }, success: function(response) { // console.log( response ); } }); } /* Jquery droppable area wrong if zoomed, SOLVED: http://stackoverflow.com/questions/27266009/jquery-droppable-area-wrong-if-zoomed-solved */ $.ui.ddmanager.prepareOffsets = function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { // No disabled and non-accepted if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } // Filter out elements in the current dragged item for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } // Activate the droppable if used directly from draggables if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth * scale, height: m[ i ].element[ 0 ].offsetHeight * scale }); } }; /* end. SOLVED */ //drag/drop elements $('.draggable').draggable({ addClasses: false, appendTo: 'body', helper: 'clone', revert: true, revertDuration: 0, cursor: 'move', start: function(e, ui) { hideCharOptions(); droppableZone.addClass('active'); var element = $(e.target).addClass('on-dragging'); ui.helper .css({ height: element.height()*scale, }); }, drag: function(e, ui) { ui.position.top = e.clientY - ui.helper.height()/2; ui.position.left = e.clientX - ui.helper.width()/2; }, stop: function(e, ui) { $(e.target).removeClass('on-dragging'); droppableZone.removeClass('active'); } }); $('.droppable').droppable({ addClasses: false, accept: '.draggable', tolerance: 'pointer', // "fit": Draggable overlaps the droppable entirely. // "intersect": Draggable overlaps the droppable at least 50% in both directions. // "pointer": Mouse pointer overlaps the droppable. // "touch": Draggable overlaps the droppable any amount. drop: function(e, ui) { var target = $(e.target); var oldDroppable = ui.draggable.parent().parent(); if ( !ui.draggable.hasClass('dropped') && oldDroppable.attr('id') != target.attr('id') ) { if ( ui.draggable.parent().hasClass('character-elements-item') & target.hasClass('disabled') ) { return false; } ui.draggable.addClass('dropped'); var wrapper = target.parent(); var char = target.find('.draggable.primary'); if ( oldDroppable.length > 0 ) { if ( oldDroppable.hasClass('droppable') ) { //swap char if exists if ( char.length > 0 ) { //swap chars ui.draggable.parent().append(char); //must append to keep original draggable exists until "//update droppable zone of new dropped" putCharIn(char, oldDroppable); } else { var oldDroppableCoords = JSON.parse( oldDroppable.attr('data-coords') ); oldDroppable.css({ left: oldDroppableCoords[0] + '%', top: oldDroppableCoords[1] + '%', width: ( 100 - oldDroppableCoords[2] - oldDroppableCoords[0] ) + '%', height: ( 100 - oldDroppableCoords[3] - oldDroppableCoords[1] ) + '%', }); //show silhouette oldDroppable.parent().find('img.silhouette').removeClass('hidden'); } } else { //drag from mychars to artwork var editLink = target.find('.char-options .edit').eq(0); editLink.attr( 'href', getEditLink( editLink.attr('href'), { charid: ui.draggable.attr('data-char-id') } ) ); // prepend exists char back to mychars list if ( char.length > 0 ) { $('[data-id=' + char.attr('data-char-id') + ']').eq(0).prepend( char .attr( 'src', char.attr('data-thumb-crop') ) .css({ top: parseFloat( char.attr('data-top') ) + '%', height: parseFloat( char.attr('data-height' ) ) + '%' }) ); } } } wrapper.find('img.silhouette').addClass('hidden'); target.find('.droppable-content').eq(0).html( ui.draggable .removeAttr('style') .attr('src', ui.draggable.attr('data-thumb-crop')) ); //update droppable zone of new dropped putCharIn(ui.draggable, target); //clear save state clearSavedState(); //little trick prevent drop 1 element on multi-overlap droppable setTimeout(function() { ui.draggable.removeClass('dropped'); }, 500); checkMaxChars(); //auto save autoSave(); } else { ui.draggable.removeClass('dropped'); } } }); //click to add mychar to artwork(same as drag & drop) $document.on('click', '.character-elements-item .draggable', function(e) { var $this = $(this); var target = $('.droppable:not(".disabled") .droppable-content').filter(function() { return $(this).find('> *').length == 0; }).eq(0); if ( target.length > 0 ) { var wrapper = target.parent().parent(); var char = target.find('.draggable.primary'); wrapper.find('img.silhouette').addClass('hidden'); target.html( $this .removeAttr('style') .attr('src', $this.attr('data-thumb-crop')) ); //update droppable zone of new dropped var droppable = target.parent(); putCharIn($this, droppable); var editLink = droppable.find('.char-options .edit').eq(0); editLink.attr( 'href', getEditLink( editLink.attr('href'), { charid: $this.attr('data-char-id') } ) ); // prepend exists char back to mychars list if ( char.length > 0 ) { $('[data-id=' + char.attr('data-char-id') + ']').eq(0).prepend( char .css({ top: parseFloat( char.attr('data-top') ) + '%', height: parseFloat( char.attr('data-height' ) ) + '%' }) ); } //clear save state clearSavedState(); checkMaxChars(); //auto save autoSave(); } }); $document.on('mouseenter', '.char .droppable', function(e) { e.stopPropagation(); hideCharOptions(); if ( $(this).find('img.primary').length == 0 ) { return false; } var $this = $(this); if ( !$this.hasClass('focus') ) { $this.addClass('focus'); var charOptions = $this.find('.char-options'); var offset = $this.offset(); charOptions .css({ left: offset.left + ( $this.width()*scale - charOptions.width() )/2, top: offset.top }) .appendTo('body') .removeClass('hidden'); } }); $document.on('mouseover', function(e) { hideCharOptions(); }); $document.on('mouseover', '.char-options', function(e) { e.stopPropagation(); }); $document.on('click', '.char-options .delete', function(e) { var $this = $(this); var target = $( '#' + $this.attr('data-target') ); var oldTargetCoords = JSON.parse( target.attr('data-coords') ); target .css({ left: oldTargetCoords[0] + '%', top: oldTargetCoords[1] + '%', width: ( 100 - oldTargetCoords[2] - oldTargetCoords[0] ) + '%', height: ( 100 - oldTargetCoords[3] - oldTargetCoords[1] ) + '%', }) .next('img.silhouette').removeClass('hidden'); //prepend char back to mychars list var char = target.find('img.primary'); if ( char.length > 0 ) { var chardata = JSON.parse( char.attr('data-chardata') ).poses[3]; $('[data-id=' + char.attr('data-char-id') + ']').eq(0).prepend( char .attr('src', chardata.thumb_crop) .css({ top: parseFloat( char.attr('data-top') ) + '%', height: parseFloat( char.attr('data-height' ) ) + '%' }) ); } //update edit link var editLink = $this.parent().find('.edit').eq(0); editLink.attr( 'href', getEditLink( editLink.attr('href'), { charid: '' } ) ); hideCharOptions(); //clear save state clearSavedState(); checkMaxChars(); //auto save autoSave(); return false; }); var resizeThrottle = helpers.debounce(function() { hideCharOptions(); }, 250); $window.on('resize', resizeThrottle); //saving $('.character-result').on('ajaxUpdate', function(e, context, response, status, jqXhr) { $(this).parent().parent().addClass('animate'); }); $document.on('ajaxAlways', function(e, context, response) { if ( response.redirect ) { window.open( response.redirect, '_blank' ); } }); $document.on('ajaxSetup', function(e, context) { if ( context.handler == 'charactereditor::onSaveCanvas' || context.handler == 'charactereditor::onSaveReviewCanvas' ) { //fetch data var postData = { chars: [], textboxes: [] }; $('.char .primary').each(function() { var $this = $(this); postData.chars.push({ char: $this.attr('data-char'), id: $this.attr('data-char-id'), chardata: $this.attr('data-chardata'), offsetY: $this.attr('data-offset-y') }); }); $('.artwork-textbox').each(function() { var $this = $(this); var field = $this.find('> div').eq(0); postData.textboxes.push({ 'id': $this.attr('data-id'), 'size': $this.attr('data-size'), 'translate': $this.attr('data-translate'), 'rotate': $this.attr('data-rotate'), 'scale': $this.attr('data-scale'), 'text': field.text(), 'font_size': Math.floor( parseFloat(field.css('font-size'))*100/field.height() )/100 }); }); context.options.data = { data: postData }; } }); $document.on('ajaxSuccess', function(e, context, response, status, jqXhr) { if ( context.handler == 'charactereditor::onSaveCanvas') { $.oc.flashMsg({ text: response.message, class: 'success' }); } }); var doSaveReview = function(dataRequest) { $.request( dataRequest.attr('data-custom-request'), { loading: dataRequest.attr('data-custom-request-loading') } ); } //check warning empty textarea in artwork $document.on('click', '#save-review-btn', function(e) { var $this = $(this); var textareaBoxes = $('.artwork-textbox > div'); var isValid = textareaBoxes.length == 0 ? true : false; if ( !isValid ) { textareaBoxes.each(function() { if ( $(this).text() == '' ) { isValid = false; return false; //break } isValid = true; }); } if ( !isValid ) { $.confirm( $.extend({}, modalConfig, { title: $this.attr('data-custom-confirm-title'), content: $this.attr('data-custom-confirm-content'), buttons: { cancel: { text: $this.attr('data-custom-cancel-button'), btnClass: 'btn-alt' }, confirm: { text: $this.attr('data-custom-confirm-button'), action: function() { this.close(); doSaveReview($this); } } } }) ); } else { doSaveReview($this); } return false; }); //clear changes in artwork $('#clear-canvas-btn').on('click', function(e) { var $this = $(this); $.confirm( $.extend({}, modalConfig, { title: 'Be careful!', content: 'Confirm to clear all characters in artwork. Can not be undone!', buttons: { cancel: { btnClass: 'btn-alt', }, confirm: function () { $.request($this.attr('data-form-request'), { loading: '#character-clear-loading' }); return true; }, } }) ); return false; }); //set character elements list layout setCharacterElementsLayout(); //scroll $('#character-elements-scrollable').perfectScrollbar({ theme: 'festivefolks' }); } //Step 2 if ( $body.hasClass('character-step-2') ) { ///////////////////////////////////////////// var undoBtn = $('a[href="#undo"]'); var redoBtn = $('a[href="#redo"]'); //History helper var historyStack = []; var forwardStack = []; var historyIndex = -1; var pushHistoryStack = function(stateObj) { // //@chardata has name="character-edit-{charStype}" var newStateObj = stateObj; if ( newStateObj === undefined ) { newStateObj = { '#character-styles': $('#character-styles').html(), '#character-form-data': $('#character-form-data').html(), '#character-model': $('#character-model').html(), '#character-elements': $('#character-elements').html() }; } historyStack[++historyIndex] = newStateObj; forwardStack = []; undoBtn.toggleClass('disabled', historyIndex <= 0); redoBtn.addClass('disabled'); } var undo = function() { forwardStack.push( historyStack[historyIndex] ); doAction( historyStack[--historyIndex] ); undoBtn.toggleClass('disabled', historyIndex <= 0); redoBtn.removeClass('disabled'); } var redo = function() { var stateObj = forwardStack.pop(); doAction( stateObj ); historyIndex++; undoBtn.removeClass('disabled'); redoBtn.toggleClass('disabled', forwardStack.length == 0); } var updateView = function(elements, charStyle, newState) { //update field var elementPaths = {}; elements.each(function() { var $this = $(this); var key = $this.attr('data-role'); if ( key !== undefined ) { elementPaths[key] = $this.attr('src'); } }); elementPaths['id'] = elements.eq(0).attr('data-id'); //update character model data $('#character-edit-' + charStyle).val( JSON.stringify( elementPaths ) ); //update character model $('#character-' + charStyle).html( elements ); //update active state if ( charStyle !== 'built' ) { $('a.character-elements-item.active').removeClass('active'); $('a.character-elements-item[data-id="' + elements.eq(0).attr('data-id') + '"]').addClass('active'); } newState = newState === undefined ? false : newState; //push history if ( newState ) { pushHistoryStack(); } } var updateViewSrc = function(target, elementPath, newState) { //update character model target.parent().removeClass('loading'); target.attr('src', elementPath); //update field var charStyle = target.attr('data-charstyle'); var elements = target.parent().find('> img'); var elementPaths = {}; elements.each(function() { var $this = $(this); var key = $this.attr('data-role'); if ( key !== undefined ) { elementPaths[key] = $this.attr('src'); } }); var elementId = elements.eq(0).attr('data-id'); if ( elementId === undefined ) { var oldInputVal = JSON.parse( $( '#character-edit-' + charStyle ).val() ); elementPaths['id'] = oldInputVal.id; } else { elementPaths['id'] = elementId; } //update character model data $( '#character-edit-' + charStyle ).val( JSON.stringify( elementPaths ) ); newState = newState === undefined ? false : newState; //push history if ( newState ) { pushHistoryStack(); } } var doAction = function(stateObj) { $.each(stateObj, function(key, obj) { var $dom = $(key); if ( $dom.prop('tagName').toLowerCase() == 'input' ) { $(key).val(obj); } else { $(key).html(obj); } }); elementsLoading('.character-elements-item'); elementsLoading('#character-model > div'); $('#character-elements-scrollable').perfectScrollbar({ theme: 'festivefolks' }); } undoBtn.on('click', function(e) { if ( $(this).hasClass('disabled') ) { return false; } undo(); return false; }); redoBtn.on('click', function(e) { if ( $(this).hasClass('disabled') ) { return false; } redo(); return false; }); //Helpers var clearSavedState = function() { $('.flipper').removeClass('animate'); $('.character-save-result').remove(); } var clearAllFields = function() { $( '#character-edit-built').val(''); $( '#character-edit-hairstyle').val(''); $( '#character-edit-top').val(''); $( '#character-edit-bottom').val(''); $( '#character-edit-onepiece').val(''); $( '#character-edit-extras-eyewear').val(''); $( '#character-edit-extras-head-gear').val(''); $( '#character-edit-extras-facial-hair').val(''); } var clearAllStyles = function() { $( '#character-built').empty(); $( '#character-hairstyle').empty(); $( '#character-top').empty(); $( '#character-bottom').empty(); $( '#character-onepiece').empty(); $( '#character-extras-eyewear').empty(); $( '#character-extras-head-gear').empty(); $( '#character-extras-facial-hair').empty(); } var discardChanges = function(confirmCb, cancelCb) { $.confirm( $.extend({}, modalConfig, { title: 'Confirm?', content: 'Clear all style? Can not undo.', buttons: { cancel: { btnClass: 'btn-alt', action: function() { if ( cancelCb !== undefined ) { cancelCb(); } } }, confirm: function () { //clear fields clearAllFields(); //clear all styles clearAllStyles(); if ( confirmCb !== undefined ) { confirmCb(); } }, } }) ); } //initLoad var initLoad = false; //Load Body as Initial var loadDefaultState = $('#character-edit-id').val() > 0 ? true : false; var loadBuiltStyles = false; //'false' mean click other button, 'true' mean click on "Body" button $('.character-styles a.active').eq(0).trigger('click'); //load style 'Body' by default(left panel - main categories) //Character styles list: Body, Hairstyle... $document.on('click', '.character-styles a', function(e) { $('.character-styles a.active').removeClass('active'); $(this).addClass('active'); }); $document.on('click', '.character-built-trigger', function(e) { $('.character-styles a[href=#built]').trigger('click'); return false; }); //Character editor(control) var characterModel = $('#character-model'); var characterBody = $('#character-built').get(0); characterModel.css({ width: characterBody.width }); var generateColorset = function(colors) { var colorOptionTmpl = _.template( $('#character-color-option').text() ); ////#character-color-option re-create when change Body, Top, Bottoms... var colorPicker = $('#character-color-picker'); //#character-color-picker re-create when change Body, Top, Bottoms... colorPicker.empty(); if ( colors != '' ) { $.each(colors.split(','), function() { colorPicker.append( colorOptionTmpl({ hex: this, hexPath: this.replace('#', '') }) ); }); } colorListStyling(); } //Click on character elements on right pane var changeElementsItemAction = function(state) { try { var $this = $(this); //clear 'saved' state clearSavedState(); var charStyle = $this.attr('data-charstyle'); var characterStyles = $('#character-styles'); //left panel var elements = $this.find('img:not(".thumb"):not(".default")').clone().attr({ 'data-charstyle': charStyle, }); var changeElementsCallback = function() { //update element selected $('.character-elements-item.active').removeClass('active'); $this.addClass('active'); if ( !loadBuiltStyles ) { //not click on 'Body' button $('.character-color-options').removeClass('hidden'); if ( $this.attr('data-id') == 0 ) { //'none' option $( '#' + $this.attr('data-type') ).empty(); } else { //active color var defaultColorPath = $this.find('img.primary').eq(0).attr('src').split('/'); defaultColorPath.pop(); $('#character-color-picker a[href="' + defaultColorPath.join('/') + '"]').addClass('active'); //append default set // console.log('append default set'); $this.find('img.default').each(function(e) { var $this = $(this); $( '#' + $this.attr('data-type') ).html( $this.attr('data-role', 'primary').clone() ); }); } //must go after default set. update character model updateView( elements, charStyle, state ); } else { loadBuiltStyles = false; } } if ( charStyle == 'built' ) { if ( state ) { //clear fields clearAllFields(); //clear all styles clearAllStyles(); } //Reload character element styles: Hairstyle, Onepiece, Top, Bottom, Extras var charStyleOptionTmpl = _.template( $('#character-style-option').text() ); characterStyles.find('li:not(".pinned")').remove(); var cates = $this.attr('data-cates'); if ( cates != '' ) { $.each(JSON.parse(cates), function(key, obj) { characterStyles.append( charStyleOptionTmpl({ charStyleAlias: obj.name, charStyle: obj.value }) ); }); } //set default values if ( !loadBuiltStyles ) { $this.find('img.default').each(function(e) { var $this = $(this); $( '#character-edit-' + $this.attr('data-charstyle') ).val( JSON.stringify({ photo: $this.attr('src'), supplement:'' }) ); }); } } if ( charStyle == 'onepiece' ) { $( '#character-edit-top' ).val(''); $( '#character-edit-bottom' ).val(''); $('#character-top, #character-bottom').empty(); } if ( charStyle == 'top' || charStyle == 'bottom' ) { $( '#character-edit-onepiece' ).val(''); $('#character-onepiece').empty(); } changeElementsCallback(); } catch(e) { // console.log(e); } finally {} } $document.on('click', '.character-elements-item', function(e) { if ( $(this).hasClass('active') ) { return false; } changeElementsItemAction.call(this, true); return false; }); //Colors variant var imgColor = new Image; $document.on('click', '.character-elements-color-picker a', function(e) { try { imgColor.src = ''; //clear 'saved' state clearSavedState(); $('.character-elements-color-picker a.active').removeClass('active'); var $this = $(this).addClass('active'); var target = $( '#' + $this.attr('data-target') + ' > img.primary').eq(0); if ( target.length > 0 ) { target.parent().addClass('loading'); var targetSrc = target.attr('src').split('/').pop(); var elementPath = $this.attr('href') + '/' + targetSrc; imgColor.onload = function() { // setTimeout(function() { //for local debug/test only updateViewSrc( target, elementPath, true ); // }, 200000); } imgColor.src = elementPath; } //update elements color on right panel var photos = $('.character-elements > :not(".hidden") img[data-role="photo"]'); if ( currentCharStyle == 'built' ) { photos = $('.character-elements img[data-role="photo"]'); } photos.each(function() { var _self = $(this); var _selfSrc = _self.attr('src').split('/').pop(); var _selfElementPath = $this.attr('href') + '/' + _selfSrc; var _imgColor = new Image; _imgColor.onload = function() { // setTimeout(function() { //for local debug/test only _self.attr( 'src', _selfElementPath ); // }, 200000); } _imgColor.src = _selfElementPath; }); return false; } catch(e) { // console.log(e); } finally { return false; } }); //add colors list styling function var colorListStyling = function() { var colorsList = $('#character-color-picker').removeAttr('style'); if ( $body.width() > 768 ) { var colorsListWrapper = colorsList.parent(); var colors = colorsList.find('li').removeClass('break'); var colorItemWidth = colors.eq(0).outerWidth(true); var maxItemsPerRow = Math.floor( colorsListWrapper.width()/colorItemWidth ); if ( maxItemsPerRow < colors.length ) { colorsList.css({ width: colorItemWidth*Math.ceil(colors.length/2) }); colors.eq( Math.ceil(colors.length/2) ).addClass('break'); } } $('.character-color-options').perfectScrollbar({ theme: 'festivefolks', suppressScrollY: true, }); } //Saving $('.character-result').on('ajaxUpdate', function(e, context, response, status, jqXhr) { $(this).parent().parent().addClass('animate'); }); //Loading callback for elements list on the right pane //All needed components are loaded var elementContent = $('#character-elements-wrapper'); var currentCharStyle; $document.on('ajaxUpdate', '#character-elements-wrapper', function() { //check loading img then fade-in elementsLoading('.character-elements-item'); currentCharStyle = $('#character-current-style').val(); var filters = $('.elements-filter a'); //hide filter if there's only 1 $( '.elements-filter-wrapper' ).toggleClass( 'hidden', filters.length == 1 ); //hide empty filter var notEmptyFilters = []; $('.character-elements li').each(function() { var filter = $(this).attr('data-filter'); if ( notEmptyFilters.indexOf(filter) == -1 ) { notEmptyFilters.push(filter); } }); $('.elements-filter a').each(function() { if ( notEmptyFilters.indexOf( $(this).attr('href') ) > -1 ) { $(this).parent().removeClass('hidden'); } }); $('.elements-filter').addClass( 'grid-' + $('.elements-filter > li:not(".hidden")').length ); if ( !loadDefaultState ) { //new loadDefaultState = true; //show elements base on filter, eg. show built type base on age group $( '.character-elements li[data-filter="' + $('.elements-filter a').eq(0).addClass('active').attr('href') + '"]' ).removeClass('hidden'); //trigger click on first visible element // elementContent.find('.character-elements li:visible:eq(0) > a').trigger('click'); } else { //edit var activeColor = $('.character-elements-color-picker a').removeClass('active').eq(0); $( '#character-edit-' + (currentCharStyle == 'extras' ? currentCharStyle + '-eyewear' : currentCharStyle) ).each(function() { if ( this.value == '' ) { $( '.character-elements li[data-filter="' + $('.elements-filter a').eq(0).addClass('active').attr('href') + '"]' ).removeClass('hidden'); return true; } var photo = JSON.parse(this.value); photo = photo.photo ? photo.photo : ''; if ( photo ) { var photoPath = photo.split('/'); var element = $('.character-elements-item img.primary[src$="' + photoPath.pop() + '"]').parent().addClass('active'); if ( element.length > 0 ) { $('.character-color-options').removeClass('hidden'); } if ( element.attr('data-charstyle') == 'built' ) { loadBuiltStyles = true; changeElementsItemAction.call( element, false ); } //if elements has filter, trigger filter(eg. built age group) var filter = element.parent().attr('data-filter'); $('.elements-filter a[href="' + filter + '"]').addClass('active'); $('.character-elements li[data-filter="' + filter + '"]').removeClass('hidden'); //active the selected color(excluded 'built') activeColor = $('.character-elements-color-picker a[href="' + photoPath.join('/') + '"]'); if ( activeColor.length == 0 ) { activeColor = $('.character-elements-color-picker a').eq(0); activeColor.addClass('active'); } //update elements color on right panel $('.character-elements img[data-role="photo"]').each(function() { var _self = $(this); var _selfSrc = _self.attr('src').split('/').pop(); var _selfElementPath = activeColor.attr('href') + '/' + _selfSrc; var _imgColor = new Image; _imgColor.onload = function() { // setTimeout(function() { //for local debug/test only _self.attr( 'src', _selfElementPath ); // }, 200000); } _imgColor.src = _selfElementPath; }); } }); if ( activeColor.length > 0 ) { activeColor.addClass('active'); } if ( !initLoad ) { //1st time loading initLoad = true; pushHistoryStack(); } } //check loading img then fade-in elementsLoading('#character-model > div'); //set character elements list layout setCharacterElementsLayout(); //update colorset to right target, apply for 'extras' only if ( currentCharStyle == 'extras' ) { $( '.character-elements-color-picker li a' ).attr( 'data-target', filters.length > 1 ? filters.filter('.active').eq(0).attr('data-charstyle') : filters.eq(0).attr('data-charstyle') ); } //add colors list styling colorListStyling(); $('#character-elements-scrollable').perfectScrollbar({ theme: 'festivefolks' }); }); $document.on('click', '.elements-filter a', function(e) { $( '.character-elements li').addClass('hidden'); $('.elements-filter a.active').removeClass('active'); $( '.character-elements li[data-filter="' + $(this).addClass('active').attr('href') + '"]' ).removeClass('hidden'); if ( currentCharStyle != 'built' ) { generateColorset( $(this).attr('data-pallete') ); //must go after 'generateColorset' var charStyle = $(this).attr('data-charstyle'); $( '.character-elements-color-picker li a').attr( 'data-target', charStyle ); //active the selected color(excluded 'built') var photoPath = $('#' + charStyle + ' img.primary').eq(0).attr('src'); var activeColor = $('.character-elements-color-picker a').eq(0); if ( photoPath !== undefined ) { photoPath = photoPath.split('/') photoPath.pop(); photoPath = photoPath.join('/'); activeColor = $('.character-elements-color-picker a[href="' + photoPath + '"]'); } activeColor.addClass('active'); } setCharacterElementsLayout(); return false; }); $document.on('change', '#character-edit-name-field', function(e) { pushHistoryStack({ '#character-edit-name-field': $('#character-edit-name-field').val() }); clearSavedState(); }); } //Step 3 if ( $body.hasClass('character-step-3') ) { $document.on('click', '.add-cart-btn', function(e) { var $this = $(this).addClass('loading'); $.request( $this.attr('data-form-request'), { data: { message: { subject: $('#artwork-subject').val(), content: $('#artwork-content').val(), sign: $('#artwork-sign').val() } }, success: function(response) { if ( response.X_OCTOBER_REDIRECT ) { window.location = response.X_OCTOBER_REDIRECT; } // $('.cart').addClass('active'); // $this.removeClass('loading').blur(); // alert( response.message ); // $.oc.flashMsg({ text: response.message, class: 'success' }); } } ); return false; }); $document.on('click', '.add-msg-btn', function() { $('.character-creation-editor').addClass('on-edit-message'); return false; }); $document.on('click', '.artwork-message .close-message-box', function() { $('.character-creation-editor').removeClass('on-edit-message'); return false; }); var messageCharsCount = $('#message-chars-count-value'); $('#artwork-content').on('keyup', function(e) { var $this = $(this); var limit = $this.attr('data-limit'); if ( this.value.length >= limit ) { this.value = this.value.substr(0, limit); } messageCharsCount.text( this.value.length ); }); } $document.on('click', '.character .logo', function() { var $this = $(this); var href = $this.attr('href'); $.confirm( $.extend({}, modalConfig, { title: $this.attr('data-title'), content: $this.attr('data-content'), buttons: { cancel: { text: $this.attr('data-cancel'), btnClass: 'btn-alt', action: function() { this.close(); } }, confirm: { text: $this.attr('data-confirm'), action: function() { window.location = href; } } } }) ); return false; }); $document.on('click', '.close-btn', function() { var $this = $(this); var href = $this.attr('href'); $.confirm( $.extend({}, modalConfig, { title: $this.attr('data-title'), content: $this.attr('data-content'), buttons: { cancel: { text: $this.attr('data-cancel'), btnClass: 'btn-alt', action: function() { this.close(); } }, confirm: { text: $this.attr('data-confirm'), action: function() { window.location = href; } } } }) ); return false; }); } //Character if ( $body.hasClass('product') || $body.hasClass('favorites') ) { // $('html,body').animate({ // scrollTop: 0 // }); $document.on('click', '.filter-label-group', function(e) { if ( $(this).hasClass('no-child') ) { return true; } if ( $(this).hasClass('disabled') ) { return false; } $(this).toggleClass('collapsed'); return false; }); //product loader / scroll loader var productListLoader = $('#product-list'); var productListFilterForm = $('#product-list-filter-form'); var controller = new ScrollMagic.Controller(); var infiniteLoader = $('#infinite-loader'); var pageCount = 1; var scene = new ScrollMagic.Scene({ triggerElement: '#infinite-loader', triggerHook: 'onEnter' }) .addTo(controller) .on('enter', function (e) { if ( !infiniteLoader.hasClass('active') ) { infiniteLoader.addClass('active'); $.request('shop::onGetItems', { data: { page: ++pageCount, filters: productListFilterForm.serializeArray() }, success: function(response) { infiniteLoader.removeClass('active'); if ( response.success ) { //append new items productListLoader.append( response.data ); // 'loading' done -> revert to normal state scene.update(); // make sure the scene gets the new start position //no more page message if ( !response.hasMorePages ) { // controller.destroy(true); infiniteLoader .attr( 'class', 'infinite-no-more' ); // .text( response.noMoreMessage ); } } } }); } }); productListFilterForm.find('input').on('change', function() { // console.log(productListFilterForm.serialize()); productListFilterForm.submit(); }); var checkLoadedProductItem = function() { $('.canvas-wrapper').each(function() { var $this = $(this); var imgs = $this.find('img'); var imgsLoaded = 0; var onLoaded = function() { ++imgsLoaded; if ( imgsLoaded == imgs.length ) { $this.addClass('loaded'); } } imgs.each(function() { var img = new Image; img.onload = function() { onLoaded(); } img.onerror = function() { onLoaded(); } img.src = $(this).attr('src'); }); }); } checkLoadedProductItem(); //filter response productListFilterForm.on('ajaxSuccess', function(e, context, response, status, jqXhr) { pageCount = 1; productListLoader.html( response.data ); checkLoadedProductItem(); if ( response.total == 0 ) { infiniteLoader.text( response.noItemsMessage ); } else { infiniteLoader.empty(); } //no more page message if ( !response.hasMorePages ) { // controller.destroy(true); infiniteLoader .attr( 'class', 'infinite-no-more' ) .addClass('active') } else { infiniteLoader .attr( 'class', 'infinite-loader' ) .empty(); } }); //artwork thumbs $document.on('mouseenter', '.artwork-thumbs', function() { $('.artwork-thumbs.active').removeClass('active'); var activeThumb = $(this).addClass('active'); var mainPhoto = $('.canvas-opt:visible .main-photo-img').eq(0).attr( 'src', activeThumb.attr('href') ); var container = mainPhoto.parent(); container.find('img.mask').remove(); var mask = activeThumb.attr('data-mask'); if ( mask !== undefined ) { container.append(''); } return false; }); $document.on('click', '.artwork-thumbs', function() { return false; }); //artwork options var defaultQuery = { artwork: '', variant: '', numchars: '', size: '' }; var customizeQuery = $.extend({}, defaultQuery); var updateArtworkOptions = function(options) { $.extend( customizeQuery, options ); // history.pushState([data], [title], [url]); history.pushState( null, null, '?' + $.param(customizeQuery) ); }; var getArtworkDetails = function(params) { var tryFindLastElementInRow = 2; var $this = $(this); var lastElementInRow = $this.parent().parent(); while( tryFindLastElementInRow > 0 && lastElementInRow.next().length > 0 && Math.round( lastElementInRow.position().left + lastElementInRow.width() ) != Math.round( productListLoader.width() ) ) { tryFindLastElementInRow--; lastElementInRow = lastElementInRow.next(); } //get details artwork var code = $this.attr('data-artwork'); $.request('shop::onGetSingleItem', { data: { code: code, params: params }, success: function(response) { // console.log(response.data); if ( response.success ) { $('#artwork-details').remove(); var artworkDetails = $(response.data); lastElementInRow.after( artworkDetails ); imgCoverFunc( artworkDetails.find('.img-cover') ); $('html,body').animate({ scrollTop: artworkDetails.offset().top - $topBar.height() - $header.height() - 20 }); updateArtworkOptions( $.extend( {}, defaultQuery, { artwork: code, numchars: artworkDetails.find('.numchars-options').eq(0).val(), size: artworkDetails.find('.price-opt.active').eq(0).attr('data-size') }, params ) ); } } }); } //trigger artwork query(initial state) var query = window.location.search; if ( query ) { query = query.substr(1).split('&'); $.each(query, function() { var param = this.split('='); customizeQuery[ param[0] ] = param[1]; }); var selectedArtwork = $('a.artwork-canvas[data-artwork="' + customizeQuery.artwork + '"]'); if ( selectedArtwork.length > 0 ) { getArtworkDetails.call( selectedArtwork, customizeQuery ); } else { // $('html,body').animate({ // scrollTop: productListLoader.offset().top - $header.height() - $topBar.height() // }); } } //artwork details $document.on('click', '#artwork-details .price-opt', function(e) { var sizeOpt = $(this); $('.artwork-info .price-opt.active').removeClass('active'); sizeOpt.addClass('active'); $('#artwork-pricing-value').eq(0).text( sizeOpt.attr('href') ); updateArtworkOptions({ size: sizeOpt.attr('data-size') }); return false; }); $document.on('click', '#artwork-details .colors-block', function(e) { $('.colors-block.active').removeClass('active'); var $this = $(this); var variantOpt = $this.addClass('active'); var artworkID = variantOpt.attr('data-artwork'); var variantID = variantOpt.attr('data-variant'); $('.artwork-name').text( variantOpt.attr('data-name') ); var listArtworkColorBlock = $('.artwork-item .colors-block[data-artwork="' + artworkID + '"][data-variant="' + variantID + '"]'); listArtworkColorBlock.parent().find('.colors-block.active').removeClass('active'); listArtworkColorBlock.addClass('active'); $('.price-opt').addClass('hidden'); //is variant if ( variantID != undefined && variantID != '' ) { $('.artwork-thumbs[data-gallery="variant-gallery-' + variantID + '"]').eq(0).trigger('mouseenter'); $('.price-opt[data-variant="' + variantID + '"]').removeClass('hidden').filter('[data-size="' + customizeQuery.size + '"]').trigger('click'); } else { $('.artwork-thumbs[data-gallery="item-gallery-' + artworkID + '"]').eq(0).trigger('mouseenter'); $('.price-opt[data-artwork="' + artworkID + '"]').removeClass('hidden').filter('[data-size="' + customizeQuery.size + '"]').trigger('click'); } updateArtworkOptions({ variant: variantID }); return false; }); $document.on('change', '.numchars-options', function(e) { updateArtworkOptions({ numchars: this.value }); }); $document.on('click', '.artwork-canvas', function(e) { getArtworkDetails.call(this); return false; }); $document.on('click', '.artwork-item .colors-block', function() { var $this = $(this); $this.parent().find('.colors-block.active').removeClass('active'); $this.addClass('active'); getArtworkDetails.call( $('.artwork-canvas[data-artwork="' + $this.attr('data-artwork') + '"]').eq(0), { variant: $this.attr('data-variant') } ); return false; }); $document.on('click', 'a[href="#artwork-details-close"]', function(e) { $('.artwork-item .colors-block.active').removeClass('active'); var panel = $('#artwork-details').addClass('removing'); setTimeout(function() { panel.remove(); }, 500); updateArtworkOptions(defaultQuery); return false; }); var photoZoomModal = $('[data-remodal-target="photo-zoom-modal"]').remodal(); $document.on('click', 'a[href="#zoom"]', function(e) { var $this = $(this); var img = new Image; img.onload = function() { photoZoomModal.$modal.toggleClass( 'portrait', img.width < img.height ) } img.src = $this.parent().find('img.main-photo-img').eq(0).attr('src'); photoZoomModal.open(); photoZoomModal.$modal.find('.photo-zoom') .html(img) .append( $this.parent().find('img.mask') ); return false; }); $document.on('click', 'a[href="#love"]', function(e) { $('[data-artwork-id="' + $(this).attr('data-artwork-id') + '"]').toggleClass('active'); return false; }); $document.on('ajaxSuccess', function(e, context, response, status, jqXhr) { if( context.handler == 'shop::onAddFavorites' ) { $('.favorites-link').toggleClass( 'active', response.data !== '' ); } }); //customize button $document.on('click', '.customize-btn', function(e) { this.href = $(this).attr('href') + '?' + $.param(customizeQuery); return true; }); //add cart btn $document.on('click', '.add-cart-btn', function(e) { var $this = $(this); if ( $this.hasClass('loading') ) { return false; } $this.addClass('loading'); $.request( $this.attr('data-form-request') , { data: customizeQuery, success: function(response) { if ( response.success ) { $('.cart').addClass('active'); } }, complete: function() { $this.removeClass('loading'); } }); alert( 'This item has been added to cart!', 'Hooray!', 2000 ) return false; }); } //Profile if ( $body.hasClass('profile') ) { //My account if ( $body.hasClass('account') ) { //profile var profileForm = $('#profile-form'); if ( $.fn.isHappy !== undefined ) { profileForm.isHappy({ fields: { '#profile-firstname': { required: true, }, '#profile-lastname': { required: true, }, '#profile-email': { required: true, test: happy.email }, // '#profile-password': { // required: true, // message: $('#profile-password').attr('data-message'), // test: function(val) { // return happy.minLength(val, 6); // } // }, // '#profile-re-password': { // required: true, // test: function(value) { // if ( value != $('#profile-password').val() ) { // return false; // } // return true; // } // }, }, happy: function() { profileForm.addClass('processing'); }, unHappy: function() {} }); //update 'auth' UI $document.on('ajaxSuccess', '#profile-form', function(e, context, response, status, jqXHR) { profileForm.removeClass('processing'); profileForm.find(':focus').blur(); if ( response.success ) { alert( response.message, 'Great!' ); $('#auth-name').text( response.name ); } else { $('#' + response.field + '_unhappy').remove(); profileForm.find( 'input[name="' + response.field + '"]' ) .addClass('unhappy') .after( '' + response.message + '' ); } }); } } if ( $body.hasClass('characters-drafts') ) { //Characters $document.on('click', '.select-all', function(e) { var checkAllBtn = $(this).toggleClass('checked'); $('#' + $(this).attr('data-select-scope')).find('.char-selection-checkbox').each(function() { var $this = $(this); if ( checkAllBtn.hasClass('checked') ) { $this.prop('checked', true); } else { $this.prop('checked', false); } }); return false; }); $document.on('click', '.remove-selected', function(e) { var $this = $(this); $.confirm( $.extend({}, modalConfig, { title: $this.attr('data-confirm-title'), content: $this.attr('data-confirm-text'), buttons: { cancel: { text: 'Cancel', btnClass: 'btn-alt', action: function() {} }, confirm: function () { var deleteIds = []; $('#' + $this.attr('data-select-scope')).find('.char-selection-checkbox:checked').each(function() { deleteIds.push( this.value ); }); $.request($this.attr('data-form-request'), { data: { 'ids': deleteIds }, success: function(response) { if ( response.success ) { $.each(deleteIds, function() { $(response.target + this).remove(); }); } } }); }, } }) ); return false; }); $document.on('click', '.remove-selected-trigger', function(e) { var $this = $(this); $.confirm( $.extend({}, modalConfig, { title: 'Watch out!', content: 'Confirm delete?', buttons: { cancel: { text: 'Cancel', btnClass: 'btn-alt', action: function() {} }, confirm: function () { var target = $( $this.attr('data-target') ).addClass('pending-delete'); $.request($this.attr('data-form-request'), { data: { 'ids': [ $this.attr('data-delete-id') ] }, success: function(response) { if ( response ) { target.remove(); } } }); }, } }) ); return false; }); //Draft Textboxes $('.artwork-textbox').each(function() { var $this = $(this); var container = $this.parent(); var primaryImgLoader = new Image; primaryImgLoader.onload = function() { var size = $this.attr('data-size').split(','); var translate = $this.attr('data-translate').split(','); var rotate = $this.attr('data-rotate'); var scale = $this.attr('data-scale').split(','); size[0] = size[0]*container.width(); size[1] = size[1]*container.height(); var offsetX = size[0]*(scale[0] - 1)/2; var offsetY = size[1]*(scale[1] - 1)/2; var transform = 'translate(' + (translate[0]*size[0] - offsetX) + 'px,' + (translate[1]*size[1] - offsetY) + 'px) rotate(' + rotate + 'deg)'; $this.css({ 'color': $this.attr('data-text-color'), 'width': size[0]*scale[0], 'height': size[1]*scale[1], 'transform': transform, '-moz-transform': transform, '-webkit-transform': transform }); // $this.find('> div').eq(0) // .css({ // 'font-size': $this.attr('data-font-size')*$this.height() // }); $.get( $('#root_url').val() + '/storage/app/media/artwork-font.ttf', function(data, status, jqXhr) { $this.find('> div').eq(0).fitTextBox(); } ); } primaryImgLoader.src = container.find('.primary').eq(0).attr('src'); }); } } var shippingAddressForm = $('#shipping-info-form'); var updateShippingAddressCart = function(data) { var shippingListCart = $('#shipping-list-cart') if ( shippingListCart.length > 0 ) { shippingListCart.html( data ) } } if ( shippingAddressForm.length > 0 ) { //shipping info if ( $.fn.isHappy !== undefined ) { shippingAddressForm.isHappy({ fields: { '#shipping-firstname': { required: true, }, '#shipping-lastname': { required: true, }, '#shipping-address-1': { required: true, }, '#shipping-postal-code': { required: true, test: happy.number }, '#shipping-city': { required: true, }, '#shipping-country': { required: true, errorTarget: '#shipping-country-wrapper' }, }, happy: function() { shippingAddressForm.addClass('processing'); }, unHappy: function() {} }); //update 'shipping address list' UI $document.on('ajaxSuccess', '#shipping-info-form', function(e, context, response, status, jqXHR) { shippingAddressForm.removeClass('processing'); shippingAddressForm.find(':focus').blur(); if ( response.success ) { if ( $(response.data).hasClass('default') ) { $('.shipping-address.default').removeClass('default') .find('.default-text').remove(); } if ( response.id ) { $('#' + response.id).replaceWith( response.data ); var updatedItem = $('#' + response.id); if ( updatedItem.hasClass('default') ) { $('#shipping-list').prepend( updatedItem ); } } else { var defaultItem = $('#shipping-list .shipping-address.default').eq(0); if ( defaultItem.length > 0 ) { defaultItem.after( response.data ); } else { $('#shipping-list').prepend( response.data ); } } clearForm( shippingAddressForm ); //update shipping address options on cart page(if exists) updateShippingAddressCart( response.shipping_addresses ); } else { $('#' + response.field + '_unhappy').remove(); profileForm.find( 'input[name="' + response.field + '"]' ) .addClass('unhappy') .after( '' + response.message + '' ); } }); } $document.on('click', '.shipping-edit-btn', function(e) { $( $(this).attr('data-target') ).find('[data-name]').each(function() { var $this = $(this); var field = $('[name="' + $this.attr('data-name') + '"]'); if ( field.attr('type') == 'checkbox' ) { if ( $this.text() == 1 ) { field.attr('checked', 'checked'); } else { field.removeAttr('checked'); } } else { field.val( $this.text() ); } }); $('html,body').animate({ scrollTop: $('.shipping-info').eq(0).offset().top - $header.height() - ( $('.top-bar').eq(0).position().top >= 0 ? $topBar.height() : 0 ) }) return false; }); $document.on('click', '.shipping-delete-btn', function(e) { var $this = $(this); $.confirm( $.extend({}, modalConfig, { title: 'Watch out!', content: 'Confirm delete?', buttons: { cancel: { text: 'Cancel', btnClass: 'btn-alt', }, confirm: function () { var target = $( $this.attr('data-target') ).addClass('pending-delete'); $.request('members::onDeleteShippingAddress', { data: { 'shipping-id': $this.attr('data-shipping-id') }, success: function(response) { if ( response ) { var sid = target.find('[data-name="shipping-id"]').eq(0).text(); target.remove(); $('#shipping-address-info-view-' + sid).remove(); } } }); }, } }) ); return false; }); $document.on('click', '.cancel-form', function() { clearForm( shippingAddressForm ); return false; }); } //Cart if ( $body.hasClass('cart') ) { var cartSubTotal = $('#cart-subtotal'); var cartSubTotalPromo = $('#cart-subtotal-promo'); var promoValue = $('#promo-code-value'); //cart list form var cartListForm = $('#cart-list-form'); $document.on('click', 'a[href="#update-cart"]', function() { cartListForm.submit(); return false; }); cartListForm.on('ajaxSuccess', function(e, context, response, status, jqXhr) { if ( response.success ) { $.oc.flashMsg({ text: response.message, class: 'success', }); } }); var getSubtotal = function() { var subtotal = 0; $('.cart-options').each(function() { var $this = $(this); var pricing = $this.find('.pricing').eq(0).text(); var quantity = $this.find('input.quantity').eq(0).val(); subtotal += pricing*quantity; }); cartSubTotal.text( subtotal.toFixed(2) ); var _promo = promoValue.text(); var isPercentage = (/%$/).test(_promo); _promo = _promo != '' ? parseFloat(_promo) : 0; cartSubTotalPromo.text( isPercentage ? subtotal*( 100 - _promo )/100 : subtotal >= _promo ? subtotal - _promo : 0 ); //save changes cartListForm.submit(); } $('.cart-options input.quantity').on('change', function() { if ( this.value < 0 ) { this.value = 0; } getSubtotal(); }); $('.size-options-select').on('change', function() { var $this = $(this); $( $this.attr('data-target') ).text( this.value ); $( '[data-source="' + $this.attr('id') + '"]' ).eq(0).val( $this.find('option[value="' + this.value + '"]').eq(0).attr('data-size') ); getSubtotal(); }); getSubtotal(); $document.on('click', '.quantity-wrapper button', function(e) { var $this = $(this); var quantityField = $this.parent().parent().find('input.quantity').eq(0); var quantity = quantityField.val(); switch( $this.attr('data-value') ) { case 'increase': quantityField.val( ++quantity ); break; case 'decrease': quantityField.val( --quantity < 1 ? 1 : quantity ); break; } getSubtotal(); return false; }); //remove cart item handler var cartList = $('#cart-list'); $document.on('click', 'a[href="#remove-cart"]', function(e) { var $this = $(this); $.confirm( $.extend({}, modalConfig, { title: $this.attr('data-confirm-title'), content: $this.attr('data-confirm-content'), buttons: { cancel: { btnClass: 'btn-alt', }, confirm: function () { $.request( $this.attr('data-form-request'), { data: { cart_id: $this.attr('data-cart-id') }, success: function(response) { if ( response.success ) { $('#cart-item-' + response.id).remove(); if ( $('.cart-item').length == 0 ) { cartList.html('

    ' + cartList.attr('data-empty-message') + '


    '); } getSubtotal(); } } } ); return true; } } }) ); return false; }); //selection $document.on('click', '#payment-methods .payment-list a', function(e) { $('#payment-methods .payment-list a.active').removeClass('active'); $(this).addClass('active'); $('#shipping-info h4').addClass('active'); return false; }); $document.on('click', '#shipping-info .shipping-address', function(e) { $('#shipping-info .shipping-address.active').removeClass('active'); $(this).addClass('active'); return false; }); $document.on('click', '.checkout-steps section h4', function(e) { $(this).toggleClass('active'); return false; }); var preparePaymentData = function() { // Prepare data for create payment var shippingAdress = $('#shipping-info .shipping-address.active').eq(0); var quantity = {}; $('.quantity').each(function() { var $this = $(this); quantity[$this.attr('data-cart-id')] = $this.val(); }); return paymentData = { 'payment': $('#payment-methods .payment-list a.active').eq(0).attr('data-value'), 'shipping': shippingAdress.length == 0 ? undefined : { 'recipient_name': shippingAdress.find('[data-name="recipient"]').eq(0).val(), 'line1': shippingAdress.find('[data-name="address-1"]').eq(0).text(), 'line2': shippingAdress.find('[data-name="address-2"]').eq(0).text(), 'city': shippingAdress.find('[data-name="city"]').eq(0).text(), 'postal_code': shippingAdress.find('[data-name="postal-code"]').eq(0).text(), 'country_code': shippingAdress.find('[data-name="country"]').eq(0).text(), 'phone': shippingAdress.find('[data-name="phone"]').eq(0).text() }, 'promo': $('#promo-code').val(), 'quantity': quantity }; } //init checkout popup var checkoutModal = $('#checkout-modal').remodal({ hashTracking: false }); $document.on('opened', '#checkout-modal', function(e) { $(this).toggleClass( 'zero-payment', parseFloat( cartSubTotalPromo.text() ) == 0 ); }); $document.on('click', '[href="#checkout"]', function(e) { checkoutModal.open(); return false; }); //prepare form before submit var paymentData; var validatePaymentForm = function(actions) { paymentData = preparePaymentData(); if ( paymentData.payment == '' || paymentData.shipping == undefined ) { if ( actions !== undefined ) { actions.disable(); } if ( parseFloat( cartSubTotalPromo.text() ) > 0 && paymentData.payment == undefined ) { alert( 'Please select a payment method!', 'Hola!'); } if ( paymentData.shipping == undefined ) { alert( 'Please select a shipping address!', 'Hola!'); } return false; } if ( actions !== undefined ) { actions.enable(); } return true; } if ( $('#paypal-button-container').length > 0 ) { paypal.Button.render({ env: $('#paypal-env').val(), // sandbox | production client: { sandbox: 'AaNGE1q4HtQCs-Q-dEGhEnIHqbkg9ch7gRC0lzGA3_CVgBPMe8KL43dPJnGyH8RcmAtv9nPWyN9sDFpv', production: 'Ad6Z_kiBNw6Ysq1OEEkQv7tT0RkqXRjU0Cy5_BCkE_YlqoW3K8OxUbtz5Xcu9jXaTunxrTAYqoSRSy06' }, // Show the buyer a 'Pay Now' button in the checkout flow commit: true, validate: function(actions) { $document.on('click', '.payment-list a', function(e) { validatePaymentForm(actions); }); $document.on('click', '#shipping-list-cart .shipping-address', function(e) { validatePaymentForm(actions); }); }, // payment() is called when the button is clicked payment: function() { // Set up a url on your server to create the payment var CREATE_URL = '/payment/create'; return paypal.request({ method: 'post', url: CREATE_URL, json: paymentData }) .then(function(res) { return res.paymentID; }); }, // onAuthorize() is called when the buyer approves the payment onAuthorize: function(data, actions) { // Set up a url on your server to execute the payment var EXECUTE_URL = '/payment/execute'; // Set up the data you need to pass to your server var data = { paymentID: data.paymentID, payerID: data.payerID }; // console.log(data); // Make a call to your server to execute the payment return paypal.request.post( EXECUTE_URL, data ) .then(function (res) { checkoutModal.close(); $.alert( $.extend( {}, modalConfig, { title: 'Congrats!', content: 'Payment Complete!
    Please check your order in Orders page.', onClose: function() { // window.location.reload(); window.location = '/profile/orders'; } }) ); }); }, onCancel: function() { console.log('Cancel'); }, onError: function(err) { console.log(err); } }, '#paypal-button-container'); } var zeroPayment = function() { $.request( 'shop::onPayment', { data: preparePaymentData(), success: function(data, status, jqXhr) { $(this).removeClass('loading'); if ( data.success ) { $.alert( $.extend( {}, modalConfig, { title: 'Congrats!', content: 'Payment Complete!
    Please check your order in Orders page.', onClose: function() { // window.location.reload(); window.location = '/profile/orders'; } }) ); } } } ); } //checkout with zero amount $document.on('click', '#zero-payment-btn', function(e) { var $this = $(this); if ( $this.hasClass('loading') ) { return false; } $this.addClass('loading') validatePaymentForm() ? zeroPayment() : (function() { $this.removeClass('loading'); })(); return false; }); //promo code var promoForm = $('#promo-form'); if ( $.fn.isHappy !== undefined ) { promoForm.isHappy({ fields: { '#promo-code': { required: true, }, }, happy: function() { promoForm.addClass('processing'); }, unHappy: function() {} }); //update 'auth' UI promoForm.on('ajaxSuccess', function(e, context, response, status, jqXhr) { if ( response.results == 0 ) { // alert('The code "' + $('#promo-code').val() + '" is not valid'); alert( response.message ) } else { var isPercentage = (/%$/).test(response.results); $('.cart-subtotal').addClass('promo'); cartSubTotalPromo.text( (isPercentage ? ( cartSubTotal.text() * ( 100 - parseFloat(response.results) )/100 ) : ( cartSubTotal.text() >= parseFloat(response.results) ? cartSubTotal.text() - parseFloat(response.results) : 0 ) ).toFixed(2) ); promoValue.text( isPercentage ? response.results : parseFloat(response.results).toFixed(2) ); } }); } } //Orders if ( $body.hasClass('orders') ) { //get url query params var params = _.chain( window.location.search.slice(1).split('&') ) // Split each array item into [key, value] // ignore empty string if search is empty .map(function(item) { if (item) { return item.split('=').map(function (value) { return decodeURIComponent( value.replace( /\+/g, ' ' ) ); }); } }) // Remove undefined in the case the search is empty .compact() // Turn [key, value] arrays into object parameters .object() // Return the value of the chain operation .value(); if ( params.code ) { $('[data-order-code="' + params.code + '"]').trigger('click'); } $document.on('ajaxUpdate', '.order-review', function(e, context, response, status, jqXhr) { $( $(e.target).attr('data-trigger') ).addClass('hidden'); }); $document.on('click', '.close-order-review-btn', function(e) { var $this = $(this); $( $this.attr('data-target') ).toggleClass('hidden'); var text = $this.text(); $this.text( $this.attr('data-text') ); $this.attr( 'data-text', text ); return false; }); } //Contact if ( $body.hasClass('contact') ) { var contactForm = $('#contact-form'); if ( $.fn.isHappy ) { contactForm.isHappy({ fields: { '#contact-name': { 'required': true, }, '#contact-email': { 'required': true, }, // '#contact-number': { // 'required': true, // }, '#contact-topic': { 'required': true, // errorTarget: '#contact-topic-wrapper' }, '#contact-comments': { 'required': true, } }, unHappy: function() { }, happy: function() { contactForm.addClass('processing'); } }); } var uploadContactFiles = $('#contact-upload-photo'); var maxUploads = 3; var uploader = new plupload.Uploader({ runtimes : 'html5,flash,silverlight', browse_button: 'contact-upload-photo', //id or DOM drop_element: 'contact-upload-photo', filters: { mime_types : [ { extensions: 'jpg,jpeg,gif,png' } ], max_file_size: '3mb', prevent_duplicates: true }, url: '/ajax/contact-upload', init: { FilesAdded: function(up, files) { if ( files.length > maxUploads - $('.upload-files').length ) { alert( uploadContactFiles.attr('data-error-message'), uploadContactFiles.attr('data-error-title') ); uploader.splice(); // reset the queue to zero return false; } plupload.each(files, function(file) { var img = new o.Image(); img.onload = function() { var div = $('
    '); $('#contact-upload-files').append(div); // embed the actual thumbnail this.embed(div.get(0).id, { width: 150, height: 150, crop: false, }); //bind event div.on('click', function() { $.confirm( $.extend({}, modalConfig, { title: 'Delete?', content: 'Your file will be removed.', buttons: { cancel: { btnClass: 'btn-alt', }, confirm: function () { uploader.removeFile(file); div.remove(); return true; }, } }) ); return false; }); }; img.load( file.getSource() ); }); }, Error: function(up, error) { $.oc.flashMsg({ text: error.message, class: 'error' }); }, FileUploaded: function(up, file, result) {}, UploadComplete: function(up, files) { //clear form $('.upload-files').remove(); contactForm.find('input, textarea, select').val(''); $('#contact-form select').addClass('default'); //notify alert( contactForm.attr('data-success-message'), contactForm.attr('data-success-title') ); } } }); uploader.init(); contactForm.on('ajaxSuccess', function(e, context, response, status, jqXhr) { uploader.setOption( 'url', uploader.getOption('url') + '/' + response.data ); uploader.start(); }); } //FAQ if ( $body.hasClass('faq') ) { $document.on('click', '.faq-wrapper h3', function(e) { $(this).toggleClass('collapsed'); return false; }); } //Auth try { //Google login var googleUser = {}; var auth2; gapi.load('auth2', function() { // Retrieve the singleton for the GoogleAuth library and set up the client. auth2 = gapi.auth2.init({ client_id: $('#google-app-id').val(), cookiepolicy: 'single_host_origin', // Request scopes in addition to 'profile' and 'email' // scope: 'additional_scope' }); $('.google-login').each(function(e) { var $this = $(this); auth2.attachClickHandler(this, {}, function(googleUser) { $.request($this.attr('data-login-request'), { data: { brand: 'google', access_token: googleUser.getAuthResponse().id_token, }, success: function(response) { window.location.replace( response.X_OCTOBER_REDIRECT ); } }); }, function(error) { // console.log( error ); } ); }); }); $document.on('click', '.google-login', function(e) { return false; }); var authBox = $('#auth-box'); //register var signupForm = $('#signup-form'); if ( $.fn.isHappy !== undefined ) { signupForm.isHappy({ fields: { '#signup-firstname': { required: true, }, '#signup-lastname': { required: true, }, '#signup-email': { required: true, test: happy.email }, '#signup-passwd': { required: true, message: $('#signup-passwd').attr('data-message'), test: function(val) { return happy.minLength(val, 6); } }, '#signup-re-passwd': { required: true, test: function(value) { if ( value != $('#signup-passwd').val() ) { return false; } return true; } }, }, happy: function() { signupForm.addClass('processing'); }, unHappy: function() {} }); //update 'auth' UI $document.on('ajaxSuccess', '#signup-form', function(e, context, response, status, jqXHR) { if ( response.success ) { authBox.html( response.data ); if ( response.redirect ) { if ( (/^!/).test(response.redirect) ) { window.location = window.location.href.split('?')[0] + '#' + response.redirect.substr(1); } } else { $('[data-remodal-id="signup"]').remodal().destroy(); history.pushState('', document.title, window.location.pathname + window.location.search); } } else { $('#signup-email_unhappy').remove(); signupForm.find( 'input[name="' + response.field + '"]' ) .addClass('unhappy') .after( '' + response.message + '' ); } }); } //login var loginForm = $('#login-form'); if ( $.fn.isHappy !== undefined ) { loginForm.isHappy({ fields: { '#signin-email': { required: true, test: happy.email }, '#signin-passwd': { required: true, }, }, happy: function() { loginForm.addClass('processing'); $('#login-error').addClass('hidden').empty(); }, unHappy: function() {} }); //update 'auth' UI $document.on('ajaxSuccess', '#login-form', function(e, context, response, status, jqXHR) { if ( response.success ) { authBox.html( response.data ); if ( response.redirect ) { if ( (/^!/).test(response.redirect) ) { window.location = window.location.href.split('?')[0] + '#' + response.redirect.substr(1); } } else { $('[data-remodal-id="login"]').remodal().destroy(); history.pushState('', document.title, window.location.pathname + window.location.search); } } else { $('#login-error').removeClass('hidden').html( response.message ); } }); $document.on('closing', '[data-remodal-id="login"]', function(e) { window.location.href = '/shop'; }); } //social merge var socialLoginForm = $('#social-login-form'); if ( $.fn.isHappy !== undefined ) { socialLoginForm.isHappy({ fields: { '#social-signin-passwd': { required: true, }, }, happy: function() { socialLoginForm.addClass('processing'); $('#social-login-error').addClass('hidden').empty(); }, unHappy: function() {} }); //update 'auth' UI $document.on('ajaxSuccess', '#social-login-form', function(e, context, response, status, jqXHR) { resetPasswdMsg.removeClass('success error'); if ( response.success ) { authBox.html( response.data ); if ( response.redirect ) { if ( (/^!/).test(response.redirect) ) { window.location = window.location.href.split('?')[0] + '#' + response.redirect.substr(1); } } else { $('[data-remodal-id="social-login"]').remodal().destroy(); history.pushState('', document.title, window.location.pathname + window.location.search); } } else { $('#social-login-error').removeClass('hidden').html( response.message ); } }); } //forgot var forgotPasswdForm = $('#forgot-password-form'); var forgotPasswdMsg = $('#forgot-password-msg'); if ( $.fn.isHappy !== undefined ) { forgotPasswdForm.isHappy({ fields: { '#forgot-email': { required: true, test: happy.email }, }, happy: function() { forgotPasswdForm.addClass('processing'); $('#forgot-password-error').addClass('hidden').empty(); }, unHappy: function() {} }); //update 'auth' UI $document.on('ajaxSuccess', '#forgot-password-form', function(e, context, response, status, jqXHR) { forgotPasswdMsg.removeClass('success error'); if ( response.success ) { // $('[data-remodal-id="forgot-password"]').remodal().destroy(); // history.pushState('', document.title, window.location.pathname + window.location.search); forgotPasswdMsg.addClass('success'); } else { forgotPasswdMsg.addClass('error'); } $('#forgot-password-msg').removeClass('hidden').html( response.message ); }); } //clear form when close the modal $document.on('closed', '.remodal[data-remodal-id="forgot-password"]', function () { $('#forgot-email').val(''); forgotPasswdMsg.removeClass('error success').addClass('hidden').empty(); }); //reset var resetPasswdForm = $('#reset-password-form'); var resetPasswdMsg = $('#reset-password-msg'); if ( $.fn.isHappy !== undefined ) { resetPasswdForm.isHappy({ fields: { '#new-passwd': { required: true, message: $('#new-passwd').attr('data-message'), test: function(val) { return happy.minLength(val, 6); } }, '#new-re-passwd': { required: true, test: function(value) { if ( value != $('#new-passwd').val() ) { return false; } return true; } }, }, happy: function() { resetPasswdForm.addClass('processing'); $('#reset-password-error').addClass('hidden').empty(); }, unHappy: function() {} }); //update 'auth' UI $document.on('ajaxSuccess', '#reset-password-form', function(e, context, response, status, jqXHR) { resetPasswdMsg.removeClass('success error'); if ( response.success ) { resetPasswdMsg.addClass('success'); resetPasswdForm .after( response.data ) .remove(); } else { resetPasswdMsg.addClass('error'); } resetPasswdMsg.removeClass('hidden').html( response.message ); }); } $document.on('ajaxAlways', function(e, context) { $('form').removeClass('processing'); }); } catch(e) {} //subscribe newsletter var subscribeForm = $('#subscribe-newsletter'); var subscribeFormAlert = $('#subscribe-newsletter-alert'); var subscribeFormBtn = subscribeForm.find('.btn'); if ( $.fn.isHappy ) { subscribeForm.isHappy({ fields: { '#mce-FNAME': { required: true }, '#mce-LNAME': { required: true }, '#mce-EMAIL': { required: true, test: happy.email }, }, unHappy: function() {}, happy: function() { if ( !subscribeForm.hasClass('processing') ) { subscribeForm.addClass('processing'); var data = {}; var dataArray = subscribeForm.serializeArray(); $.each(dataArray, function (index, item) { data[item.name] = item.value; }); var url = subscribeForm.attr('action').replace('/post?', '/post-json?').concat('&c=?'); //post $.ajax({ url: url, data: data, dataType: 'json', error: function (response, text) {}, success: function(response) { subscribeFormAlert.removeClass('hidden success error'); if( response.result == 'success' ) { subscribeFormAlert.addClass('success'); } else { subscribeFormAlert .addClass('error') .html( response.msg ); } subscribeForm.addClass('hidden'); }, complete: function() { subscribeForm.removeClass('processing'); } }); } return false; }, }); } //img svg $('img.svg').each(function(){ var $img = $(this).removeClass('invisible'); var imgID = $img.attr('id'); var imgClass = $img.attr('class'); $img.addClass('invisible'); var imgURL = $img.attr('src'); $.get(imgURL, function(data) { // Get the SVG tag, ignore the rest var $svg = $(data).find('svg'); // Add replaced image's ID to the new SVG if(typeof imgID !== 'undefined') { $svg = $svg.attr('id', imgID); } // Add replaced image's classes to the new SVG if(typeof imgClass !== 'undefined') { $svg = $svg.attr('class', imgClass+' replaced-svg'); } // Remove any invalid XML tags as per http://validator.w3.org $svg = $svg.removeAttr('xmlns:a'); // Check if the viewport is set, if the viewport is not set the SVG wont't scale. if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) { $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width')) } // Replace image with new SVG $img.replaceWith($svg).removeClass('invisible'); }, 'xml'); }); //autoresize textarea try { autosize( $('textarea:not(".fixed")') ); } catch(exp) {} //make sure call be called by click //remove all spaces between number $('a[href^="tel:"]').each(function() { var $this = $(this); var tel = $this.attr('href').substr(4); tel = tel.replace(/[\s\(\)]/g, ''); $this.attr('href', 'tel:' + tel); }); } //events onPageLoaded(); }); })(jQuery, _, Mediator, Helpers);