
if (typeof classes == "undefined") classes = new Object();
if (typeof classes.content == "undefined") classes.content = new Object();
if (typeof classes.helpers == "undefined") classes.helpers = new Object();
if (typeof classes.elements == "undefined") classes.elements = new Object();
if (typeof classes.overlay == "undefined") classes.overlay = new Object();

var NAMESPACE = 			"vend-proofing";
var APP_ROOT = 				"./";
var APP_ROOT_ABSOLUTE = 	"http://www.createurdemotions.eu";
var URI_PAGE_PREFIX = 		"set";
var URI_SPECIAL_PREFIX = 	"action";
var URI_SPLASH_LABEL = 		"home";
var URI_CONTACT_LABEL = 	"contact";

var VEND_GRAPHIC_QUALITY = 90;
var VEND_GRAPHIC_SHARPEN = true;
var VEND_GRAPHIC_IMAGIC = false;
var VEND_GRAPHIC_WATERMARK = true;
var VEND_GRAPHIC_WATERMARK_ASSET = "tete200px-b2ad.png";
var VEND_GRAPHIC_WATERMARK_X = 50;
var VEND_GRAPHIC_WATERMARK_Y = 70;
var VEND_GRAPHIC_WATERMARK_ALPHA = 29;
var VEND_GRAPHIC_CROSSHAIRS = true;
var VEND_GRAPHIC_CROSSHAIRS_COLOR = "ffffff";
var VEND_GRAPHIC_CROSSHAIRS_ALPHA = 100;

function trace (str) {
	if (window.console != undefined) {
		console.log(str);
	}
}

/* Modernizr 2.5.3 (Custom Build) | MIT & BSD
 * Build: http://www.modernizr.com/download/#-fontface-backgroundsize-boxshadow-opacity-cssanimations-csscolumns-cssgradients-csstransforms-csstransforms3d-csstransitions-canvas-audio-video-input-inputtypes-touch-shiv-mq-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load
 */
;window.Modernizr=function(a,b,c){function B(a){j.cssText=a}function C(a,b){return B(n.join(a+";")+(b||""))}function D(a,b){return typeof a===b}function E(a,b){return!!~(""+a).indexOf(b)}function F(a,b){for(var d in a)if(j[a[d]]!==c)return b=="pfx"?a[d]:!0;return!1}function G(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:D(f,"function")?f.bind(d||b):f}return!1}function H(a,b,c){var d=a.charAt(0).toUpperCase()+a.substr(1),e=(a+" "+p.join(d+" ")+d).split(" ");return D(b,"string")||D(b,"undefined")?F(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),G(e,b,c))}function J(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)t[c[d]]=c[d]in k;return t.list&&(t.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),t}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:/^color$/.test(f)?(g.appendChild(k),g.offsetWidth,e=k.value!=l,g.removeChild(k)):e=k.value!=l)),s[a[d]]=!!e;return s}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.5.3",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={},s={},t={},u=[],v=u.slice,w,x=function(a,c,d,e){var f,i,j,k=b.createElement("div"),l=b.body,m=l?l:b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),k.appendChild(j);return f=["&#173;","<style>",a,"</style>"].join(""),k.id=h,(l?k:m).innerHTML+=f,m.appendChild(k),l||(m.style.background="",g.appendChild(m)),i=c(k,a),l?k.parentNode.removeChild(k):m.parentNode.removeChild(m),!!i},y=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return x("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},z={}.hasOwnProperty,A;!D(z,"undefined")&&!D(z.call,"undefined")?A=function(a,b){return z.call(a,b)}:A=function(a,b){return b in a&&D(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=v.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(v.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(v.call(arguments)))};return e});var I=function(c,d){var f=c.join(""),g=d.length;x(f,function(c,d){var f=b.styleSheets[b.styleSheets.length-1],h=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"",i=c.childNodes,j={};while(g--)j[i[g].id]=i[g];e.touch="ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch||(j.touch&&j.touch.offsetTop)===9,e.csstransforms3d=(j.csstransforms3d&&j.csstransforms3d.offsetLeft)===9&&j.csstransforms3d.offsetHeight===3,e.fontface=/src/i.test(h)&&h.indexOf(d.split(" ")[0])===0},g,d)}(['@font-face {font-family:"font";src:url("https://")}',["@media (",n.join("touch-enabled),("),h,")","{#touch{top:9px;position:absolute}}"].join(""),["@media (",n.join("transform-3d),("),h,")","{#csstransforms3d{left:9px;position:absolute;height:3px;}}"].join("")],["fontface","touch","csstransforms3d"]);r.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},r.touch=function(){return e.touch},r.backgroundsize=function(){return H("backgroundSize")},r.boxshadow=function(){return H("boxShadow")},r.opacity=function(){return C("opacity:.55"),/^0.55$/.test(j.opacity)},r.cssanimations=function(){return H("animationName")},r.csscolumns=function(){return H("columnCount")},r.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return B((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),E(j.backgroundImage,"gradient")},r.csstransforms=function(){return!!H("transform")},r.csstransforms3d=function(){var a=!!H("perspective");return a&&"webkitPerspective"in g.style&&(a=e.csstransforms3d),a},r.csstransitions=function(){return H("transition")},r.fontface=function(){return e.fontface},r.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},r.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c};for(var K in r)A(r,K)&&(w=K.toLowerCase(),e[w]=r[K](),u.push((e[w]?"":"no-")+w));return e.input||J(),B(""),i=k=null,function(a,b){function g(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function h(){var a=k.elements;return typeof a=="string"?a.split(" "):a}function i(a){var b={},c=a.createElement,e=a.createDocumentFragment,f=e();a.createElement=function(a){var e=(b[a]||(b[a]=c(a))).cloneNode();return k.shivMethods&&e.canHaveChildren&&!d.test(a)?f.appendChild(e):e},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+h().join().replace(/\w+/g,function(a){return b[a]=c(a),f.createElement(a),'c("'+a+'")'})+");return n}")(k,f)}function j(a){var b;return a.documentShived?a:(k.shivCSS&&!e&&(b=!!g(a,"article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio{display:none}canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}mark{background:#FF0;color:#000}")),f||(b=!i(a)),b&&(a.documentShived=b),a)}var c=a.html5||{},d=/^<|^(?:button|form|map|select|textarea)$/i,e,f;(function(){var a=b.createElement("a");a.innerHTML="<xyz></xyz>",e="hidden"in a,f=a.childNodes.length==1||function(){try{b.createElement("a")}catch(a){return!0}var c=b.createDocumentFragment();return typeof c.cloneNode=="undefined"||typeof c.createDocumentFragment=="undefined"||typeof c.createElement=="undefined"}()})();var k={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:j};a.html5=k,j(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=y,e.testProp=function(a){return F([a])},e.testAllProps=H,e.testStyles=x,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+u.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return o.call(a)=="[object Function]"}function e(a){return typeof a=="string"}function f(){}function g(a){return!a||a=="loaded"||a=="complete"||a=="uninitialized"}function h(){var a=p.shift();q=1,a?a.t?m(function(){(a.t=="c"?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){a!="img"&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l={},o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};y[c]===1&&(r=1,y[c]=[],l=b.createElement(a)),a=="object"?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),a!="img"&&(r||y[c]===2?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i(b=="c"?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),p.length==1&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&o.call(a.opera)=="[object Opera]",l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return o.call(a)=="[object Array]"},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,i){var j=b(a),l=j.autoCallback;j.url.split(".").pop().split("?").shift(),j.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]||h),j.instead?j.instead(a,e,f,g,i):(y[j.url]?j.noexec=!0:y[j.url]=1,f.load(j.url,j.forceCSS||!j.forceJS&&"css"==j.url.split(".").pop().split("?").shift()?"c":c,j.noexec,j.attrs,j.timeout),(d(e)||d(l))&&f.load(function(){k(),e&&e(j.origUrl,i,g),l&&l(j.origUrl,i,g),y[j.url]=2})))}function i(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var j,l,m=this.yepnope.loader;if(e(a))g(a,0,m,0);else if(w(a))for(j=0;j<a.length;j++)l=a[j],e(l)?g(l,0,m,0):w(l)?B(l):Object(l)===l&&i(l,m);else Object(a)===a&&i(a,m)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,b.readyState==null&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-2.0.3.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=[],p="2.0.3",f=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:\s*(<[\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:p,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"+(p+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 f.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,p,f,h,d,g,m,y,v="sizzle"+-new Date,b=e.document,w=0,T=0,C=st(),k=st(),N=st(),E=!1,S=function(e,t){return e===t?(E=!0,0):0},j=typeof undefined,D=1<<31,A={}.hasOwnProperty,L=[],q=L.pop,H=L.push,O=L.push,F=L.slice,P=L.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",W="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",$=W.replace("w","w#"),B="\\["+M+"*("+W+")"+M+"*(?:([*^$|!~]?=)"+M+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+$+")|)|)"+M+"*\\]",I=":("+W+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+B.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=RegExp("^"+M+"*,"+M+"*"),X=RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=RegExp(M+"*[+~]"),Y=RegExp("="+M+"*([^\\]'\"]*)"+M+"*\\]","g"),V=RegExp(I),G=RegExp("^"+$+"$"),J={ID:RegExp("^#("+W+")"),CLASS:RegExp("^\\.("+W+")"),TAG:RegExp("^("+W.replace("w","w*")+")"),ATTR:RegExp("^"+B),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:RegExp("^(?:"+R+")$","i"),needsContext:RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/^[^{]+\{\s*\[native \w/,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Z=/^(?:input|select|textarea|button)$/i,et=/^h\d$/i,tt=/'|\\/g,nt=RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),rt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{O.apply(L=F.call(b.childNodes),b.childNodes),L[b.childNodes.length].nodeType}catch(it){O={apply:L.length?function(e,t){H.apply(e,F.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function ot(e,t,r,i){var o,s,a,u,l,f,g,m,x,w;if((t?t.ownerDocument||t:b)!==p&&c(t),t=t||p,r=r||[],!e||"string"!=typeof e)return r;if(1!==(u=t.nodeType)&&9!==u)return[];if(h&&!i){if(o=K.exec(e))if(a=o[1]){if(9===u){if(s=t.getElementById(a),!s||!s.parentNode)return r;if(s.id===a)return r.push(s),r}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(a))&&y(t,s)&&s.id===a)return r.push(s),r}else{if(o[2])return O.apply(r,t.getElementsByTagName(e)),r;if((a=o[3])&&n.getElementsByClassName&&t.getElementsByClassName)return O.apply(r,t.getElementsByClassName(a)),r}if(n.qsa&&(!d||!d.test(e))){if(m=g=v,x=t,w=9===u&&e,1===u&&"object"!==t.nodeName.toLowerCase()){f=gt(e),(g=t.getAttribute("id"))?m=g.replace(tt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",l=f.length;while(l--)f[l]=m+mt(f[l]);x=U.test(e)&&t.parentNode||t,w=f.join(",")}if(w)try{return O.apply(r,x.querySelectorAll(w)),r}catch(T){}finally{g||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,r,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>i.cacheLength&&delete t[e.shift()],t[n]=r}return t}function at(e){return e[v]=!0,e}function ut(e){var t=p.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function lt(e,t){var n=e.split("|"),r=e.length;while(r--)i.attrHandle[n[r]]=t}function ct(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~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 pt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return at(function(t){return t=+t,at(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]))})})}s=ot.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},n=ot.support={},c=ot.setDocument=function(e){var t=e?e.ownerDocument||e:b,r=t.defaultView;return t!==p&&9===t.nodeType&&t.documentElement?(p=t,f=t.documentElement,h=!s(t),r&&r.attachEvent&&r!==r.top&&r.attachEvent("onbeforeunload",function(){c()}),n.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ut(function(e){return e.appendChild(t.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),n.getById=ut(function(e){return f.appendChild(e).id=v,!t.getElementsByName||!t.getElementsByName(v).length}),n.getById?(i.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(nt,rt);return function(e){return e.getAttribute("id")===t}}):(delete i.find.ID,i.filter.ID=function(e){var t=e.replace(nt,rt);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=n.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},i.find.CLASS=n.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==j&&h?t.getElementsByClassName(e):undefined},g=[],d=[],(n.qsa=Q.test(t.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||d.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll(":checked").length||d.push(":checked")}),ut(function(e){var n=t.createElement("input");n.setAttribute("type","hidden"),e.appendChild(n).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&d.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||d.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),d.push(",.*:")})),(n.matchesSelector=Q.test(m=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&ut(function(e){n.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",I)}),d=d.length&&RegExp(d.join("|")),g=g.length&&RegExp(g.join("|")),y=Q.test(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,r){if(e===r)return E=!0,0;var i=r.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(r);return i?1&i||!n.sortDetached&&r.compareDocumentPosition(e)===i?e===t||y(b,e)?-1:r===t||y(b,r)?1:l?P.call(l,e)-P.call(l,r):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,n){var r,i=0,o=e.parentNode,s=n.parentNode,a=[e],u=[n];if(e===n)return E=!0,0;if(!o||!s)return e===t?-1:n===t?1:o?-1:s?1:l?P.call(l,e)-P.call(l,n):0;if(o===s)return ct(e,n);r=e;while(r=r.parentNode)a.unshift(r);r=n;while(r=r.parentNode)u.unshift(r);while(a[i]===u[i])i++;return i?ct(a[i],u[i]):a[i]===b?-1:u[i]===b?1:0},t):p},ot.matches=function(e,t){return ot(e,null,null,t)},ot.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Y,"='$1']"),!(!n.matchesSelector||!h||g&&g.test(t)||d&&d.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return ot(t,p,null,[e]).length>0},ot.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},ot.attr=function(e,t){(e.ownerDocument||e)!==p&&c(e);var r=i.attrHandle[t.toLowerCase()],o=r&&A.call(i.attrHandle,t.toLowerCase())?r(e,t,!h):undefined;return o===undefined?n.attributes||!h?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null:o},ot.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},ot.uniqueSort=function(e){var t,r=[],i=0,o=0;if(E=!n.detectDuplicates,l=!n.sortStable&&e.slice(0),e.sort(S),E){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return e},o=ot.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=ot.selectors={cacheLength:50,createPseudo:at,match:J,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(nt,rt),e[3]=(e[4]||e[5]||"").replace(nt,rt),"~="===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]||ot.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]&&ot.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return J.CHILD.test(e[0])?null:(e[3]&&e[4]!==undefined?e[2]=e[4]:n&&V.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(nt,rt).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("(^|"+M+")"+e+"("+M+"|$)"))&&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=ot.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,p,f,h,d,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,y=a&&t.nodeName.toLowerCase(),x=!u&&!a;if(m){if(o){while(g){p=t;while(p=p[g])if(a?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;d=g="only"===e&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&x){c=m[v]||(m[v]={}),l=c[e]||[],h=l[0]===w&&l[1],f=l[0]===w&&l[2],p=h&&m.childNodes[h];while(p=++h&&p&&p[g]||(f=h=0)||d.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[w,h,f];break}}else if(x&&(l=(t[v]||(t[v]={}))[e])&&l[0]===w)f=l[1];else while(p=++h&&p&&p[g]||(f=h=0)||d.pop())if((a?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(x&&((p[v]||(p[v]={}))[e]=[w,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||ot.error("unsupported pseudo: "+e);return r[v]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?at(function(e,n){var i,o=r(e,t),s=o.length;while(s--)i=P.call(e,o[s]),e[i]=!(n[i]=o[s])}):function(e){return r(e,0,n)}):r}},pseudos:{not:at(function(e){var t=[],n=[],r=a(e.replace(z,"$1"));return r[v]?at(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:at(function(e){return function(t){return ot(e,t).length>0}}),contains:at(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:at(function(e){return G.test(e||"")||ot.error("unsupported lang: "+e),e=e.replace(nt,rt).toLowerCase(),function(t){var n;do if(n=h?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===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return et.test(e.nodeName)},input:function(e){return Z.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:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},i.pseudos.nth=i.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[t]=pt(t);for(t in{submit:!0,reset:!0})i.pseudos[t]=ft(t);function dt(){}dt.prototype=i.filters=i.pseudos,i.setFilters=new dt;function gt(e,t){var n,r,o,s,a,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);a=e,u=[],l=i.preFilter;while(a){(!n||(r=_.exec(a)))&&(r&&(a=a.slice(r[0].length)||a),u.push(o=[])),n=!1,(r=X.exec(a))&&(n=r.shift(),o.push({value:n,type:r[0].replace(z," ")}),a=a.slice(n.length));for(s in i.filter)!(r=J[s].exec(a))||l[s]&&!(r=l[s](r))||(n=r.shift(),o.push({value:n,type:s,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?ot.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,n){var i=t.dir,o=n&&"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,n,a){var u,l,c,p=w+" "+s;if(a){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,a))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[v]||(t[v]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,a)||r,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[v]&&(r=bt(r)),i&&!i[v]&&(i=bt(i,o)),at(function(o,s,a,u){var l,c,p,f=[],h=[],d=s.length,g=o||Ct(t||"*",a.nodeType?[a]:a,[]),m=!e||!o&&t?g:xt(g,f,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--)(p=l[c])&&(y[h[c]]=!(m[h[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?P.call(o,p):f[c])>-1&&(o[l]=!(s[l]=p))}}else y=xt(y===s?y.splice(d,y.length):y),i?i(null,s,y,u):O.apply(s,y)})}function wt(e){var t,n,r,o=e.length,s=i.relative[e[0].type],a=s||i.relative[" "],l=s?1:0,c=yt(function(e){return e===t},a,!0),p=yt(function(e){return P.call(t,e)>-1},a,!0),f=[function(e,n,r){return!s&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>l;l++)if(n=i.relative[e[l].type])f=[yt(vt(f),n)];else{if(n=i.filter[e[l].type].apply(null,e[l].matches),n[v]){for(r=++l;o>r;r++)if(i.relative[e[r].type])break;return bt(l>1&&vt(f),l>1&&mt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&wt(e.slice(l,r)),o>r&&wt(e=e.slice(r)),o>r&&mt(e))}f.push(n)}return vt(f)}function Tt(e,t){var n=0,o=t.length>0,s=e.length>0,a=function(a,l,c,f,h){var d,g,m,y=[],v=0,x="0",b=a&&[],T=null!=h,C=u,k=a||s&&i.find.TAG("*",h&&l.parentNode||l),N=w+=null==C?1:Math.random()||.1;for(T&&(u=l!==p&&l,r=n);null!=(d=k[x]);x++){if(s&&d){g=0;while(m=e[g++])if(m(d,l,c)){f.push(d);break}T&&(w=N,r=++n)}o&&((d=!m&&d)&&v--,a&&b.push(d))}if(v+=x,o&&x!==v){g=0;while(m=t[g++])m(b,y,l,c);if(a){if(v>0)while(x--)b[x]||y[x]||(y[x]=q.call(f));y=xt(y)}O.apply(f,y),T&&!a&&y.length>0&&v+t.length>1&&ot.uniqueSort(f)}return T&&(w=N,u=C),b};return o?at(a):a}a=ot.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[v]?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++)ot(e,t[r],n);return n}function kt(e,t,r,o){var s,u,l,c,p,f=gt(e);if(!o&&1===f.length){if(u=f[0]=f[0].slice(0),u.length>2&&"ID"===(l=u[0]).type&&n.getById&&9===t.nodeType&&h&&i.relative[u[1].type]){if(t=(i.find.ID(l.matches[0].replace(nt,rt),t)||[])[0],!t)return r;e=e.slice(u.shift().value.length)}s=J.needsContext.test(e)?0:u.length;while(s--){if(l=u[s],i.relative[c=l.type])break;if((p=i.find[c])&&(o=p(l.matches[0].replace(nt,rt),U.test(u[0].type)&&t.parentNode||t))){if(u.splice(s,1),e=o.length&&mt(u),!e)return O.apply(r,o),r;break}}}return a(e,f)(o,t,!h,r,U.test(e)),r}n.sortStable=v.split("").sort(S).join("")===v,n.detectDuplicates=E,c(),n.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(p.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||lt("type|href|height|width",function(e,t,n){return n?undefined:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||lt("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?undefined:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||lt(R,function(e,t,n){var r;return n?undefined:(r=e.getAttributeNode(t))&&r.specified?r.value:e[t]===!0?t.toLowerCase():null}),x.find=ot,x.expr=ot.selectors,x.expr[":"]=x.expr.pseudos,x.unique=ot.uniqueSort,x.text=ot.getText,x.isXMLDoc=ot.isXML,x.contains=ot.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(p){for(t=e.memory&&p,n=!0,s=i||0,i=0,o=a.length,r=!0;a&&o>s;s++)if(a[s].apply(p[0],p[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!a||n&&!u||(t=t||[],t=[e,t.slice?t.slice():t],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))x.extend(this.cache[i],t);else for(r in t)o[r]=t[r];return o},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){var r;return t===undefined||t&&"string"==typeof t&&n===undefined?(r=this.get(e,t),r!==undefined?r:this.get(e,x.camelCase(t))):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i,o=this.key(e),s=this.cache[o];if(t===undefined)this.cache[o]={};else{x.isArray(t)?r=t.concat(t.map(x.camelCase)):(i=x.camelCase(t),t in s?r=[t,i]:(r=i,r=r in s?[r]:r.match(w)||[])),n=r.length;while(n--)delete s[r[n]]}},hasData:function(e){return!x.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){e[this.expando]&&delete this.cache[e[this.expando]]}},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.slice(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--),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\f]/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;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):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 t,i=0,o=x(this),s=e.match(w)||[];while(t=s[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}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;1===this.nodeType&&(i=r?e.call(this,n,x(this).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.bool.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.bool.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.bool.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,p,f,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&&(f=x.event.special[d]||{},d=(o?f.delegateType:f.bindType)||d,f=x.event.special[d]||{},p=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,f.setup&&f.setup.call(e,i,g,a)!==!1||e.addEventListener&&e.addEventListener(d,a,!1)),f.add&&(f.add.call(e,p),p.handler.guid||(p.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,p):h.push(p),x.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,s,a,u,l,c,p,f,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){p=x.event.special[h]||{},h=(r?p.delegateType:p.bindType)||h,f=u[h]||[],a=a[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=f.length;while(o--)c=f[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(f.splice(o,1),c.selector&&f.delegateCount--,p.remove&&p.remove.call(e,c));s&&!f.length&&(p.teardown&&p.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,p,f,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]),f=x.event.special[d]||{},i||!f.trigger||f.trigger.apply(r,n)!==!1)){if(!i&&!f.noBubble&&!x.isWindow(r)){for(l=f.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:f.bindType||d,p=(q.get(a,"events")||{})[t.type]&&q.get(a,"handle"),p&&p.apply(a,n),p=c&&a[c],p&&x.acceptData(a)&&p.apply&&p.apply(a,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||f._default&&f._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,s=e,a=this.fixHooks[i];a||(this.fixHooks[i]=a=z.test(i)?this.mouseHooks:I.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new x.Event(s),t=r.length;while(t--)n=r[t],e[n]=s[n];return e.target||(e.target=o),3===e.target.nodeType&&(e.target=e.target.parentNode),a.filter?a.filter(e,s):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=/^(?:parents|prev(?:Until|All))/,Q=x.expr.match.needsContext,K={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e: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(et(this,e||[],!0))},filter:function(e){return this.pushStack(et(this,e||[],!1))},is:function(e){return!!et(this,"string"==typeof e&&Q.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],s=Q.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 Z(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 Z(e,"nextSibling")},prev:function(e){return Z(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 e.contentDocument||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&&(K[e]||x.unique(i),J.test(e)&&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 et(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 tt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,nt=/<([\w:]+)/,rt=/<|&#?\w+;/,it=/<(?:script|style|link)/i,ot=/^(?:checkbox|radio)$/i,st=/checked\s*(?:[^=]|=\s*.checked.)/i,at=/^$|\/(?:java|ecma)script/i,ut=/^true\/(.*)/,lt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ct={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ct.optgroup=ct.option,ct.tbody=ct.tfoot=ct.colgroup=ct.caption=ct.thead,ct.th=ct.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=pt(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=pt(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(mt(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&dt(mt(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(mt(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&&!it.test(e)&&!ct[(nt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(tt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(x.cleanData(mt(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&&(r&&r.parentNode!==i&&(r=this.nextSibling),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=f.apply([],e);var r,i,o,s,a,u,l=0,c=this.length,p=this,h=c-1,d=e[0],g=x.isFunction(d);if(g||!(1>=c||"string"!=typeof d||x.support.checkClone)&&st.test(d))return this.each(function(r){var i=p.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(mt(r,"script"),ft),s=o.length;c>l;l++)a=r,l!==h&&(a=x.clone(a,!0,!0),s&&x.merge(o,mt(a,"script"))),t.call(this[l],a,l);if(s)for(u=o[o.length-1].ownerDocument,x.map(o,ht),l=0;s>l;l++)a=o[l],at.test(a.type||"")&&!q.access(a,"globalEval")&&x.contains(u,a)&&(a.src?x._evalUrl(a.src):x.globalEval(a.textContent.replace(lt,"")))}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=mt(a),o=mt(e),r=0,i=o.length;i>r;r++)yt(o[r],s[r]);if(t)if(n)for(o=o||mt(e),s=s||mt(a),r=0,i=o.length;i>r;r++)gt(o[r],s[r]);else gt(e,a);return s=mt(a,"script"),s.length>0&&dt(s,!u&&mt(e,"script")),a},buildFragment:function(e,t,n,r){var i,o,s,a,u,l,c=0,p=e.length,f=t.createDocumentFragment(),h=[];for(;p>c;c++)if(i=e[c],i||0===i)if("object"===x.type(i))x.merge(h,i.nodeType?[i]:i);else if(rt.test(i)){o=o||f.appendChild(t.createElement("div")),s=(nt.exec(i)||["",""])[1].toLowerCase(),a=ct[s]||ct._default,o.innerHTML=a[1]+i.replace(tt,"<$1></$2>")+a[2],l=a[0];while(l--)o=o.lastChild;x.merge(h,o.childNodes),o=f.firstChild,o.textContent=""}else h.push(t.createTextNode(i));f.textContent="",c=0;while(i=h[c++])if((!r||-1===x.inArray(i,r))&&(u=x.contains(i.ownerDocument,i),o=mt(f.appendChild(i),"script"),u&&dt(o),n)){l=0;while(i=o[l++])at.test(i.type||"")&&n.push(i)}return f},cleanData:function(e){var t,n,r,i,o,s,a=x.event.special,u=0;for(;(n=e[u])!==undefined;u++){if(F.accepts(n)&&(o=n[q.expando],o&&(t=q.cache[o]))){if(r=Object.keys(t.events||{}),r.length)for(s=0;(i=r[s])!==undefined;s++)a[i]?x.event.remove(n,i):x.removeEvent(n,i,t.handle);q.cache[o]&&delete q.cache[o]}delete L.cache[n[L.expando]]}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}});function pt(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 ht(e){var t=ut.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function dt(e,t){var n=e.length,r=0;for(;n>r;r++)q.set(e[r],"globalEval",!t||q.get(t[r],"globalEval"))}function gt(e,t){var n,r,i,o,s,a,u,l;if(1===t.nodeType){if(q.hasData(e)&&(o=q.access(e),s=q.set(t,o),l=o.events)){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 mt(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 yt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&ot.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 vt,xt,bt=/^(none|table(?!-c[ea]).+)/,wt=/^margin/,Tt=RegExp("^("+b+")(.*)$","i"),Ct=RegExp("^("+b+")(?!px)[a-z%]+$","i"),kt=RegExp("^([+-])=("+b+")","i"),Nt={BODY:"block"},Et={position:"absolute",visibility:"hidden",display:"block"},St={letterSpacing:0,fontWeight:400},jt=["Top","Right","Bottom","Left"],Dt=["Webkit","O","Moz","ms"];function At(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Dt.length;while(i--)if(t=Dt[i]+n,t in e)return t;return r}function Lt(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function qt(t){return e.getComputedStyle(t,null)}function Ht(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&&Lt(r)&&(o[s]=q.access(r,"olddisplay",Rt(r.nodeName)))):o[s]||(i=Lt(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=qt(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 Ht(this,!0)},hide:function(){return Ht(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Lt(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=vt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!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]=At(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=kt.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]=At(e.style,a)),s=x.cssHooks[t]||x.cssHooks[a],s&&"get"in s&&(i=s.get(e,!0,n)),i===undefined&&(i=vt(e,t,r)),"normal"===i&&t in St&&(i=St[t]),""===n||n?(o=parseFloat(i),n===!0||x.isNumeric(o)?o||0:i):i}}),vt=function(e,t,n){var r,i,o,s=n||qt(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)),Ct.test(a)&&wt.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 Ot(e,t,n){var r=Tt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function Ft(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+jt[o],!0,i)),r?("content"===n&&(s-=x.css(e,"padding"+jt[o],!0,i)),"margin"!==n&&(s-=x.css(e,"border"+jt[o]+"Width",!0,i))):(s+=x.css(e,"padding"+jt[o],!0,i),"padding"!==n&&(s+=x.css(e,"border"+jt[o]+"Width",!0,i)));return s}function Pt(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=qt(e),s=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=vt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Ct.test(i))return i;r=s&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+Ft(e,t,n||(s?"border":"content"),r,o)+"px"}function Rt(e){var t=o,n=Nt[e];return n||(n=Mt(e,t),"none"!==n&&n||(xt=(xt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(xt[0].contentWindow||xt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=Mt(e,t),xt.detach()),Nt[e]=n),n}function Mt(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,t){x.cssHooks[t]={get:function(e,n,r){return n?0===e.offsetWidth&&bt.test(x.css(e,"display"))?x.swap(e,Et,function(){return Pt(e,t,r)}):Pt(e,t,r):undefined},set:function(e,n,r){var i=r&&qt(e);return Ot(e,n,r?Ft(e,t,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,t){return t?x.swap(e,{display:"inline-block"},vt,[e,"marginRight"]):undefined}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,t){x.cssHooks[t]={get:function(e,n){return n?(n=vt(e,t),Ct.test(n)?x(e).position()[t]+"px":n):undefined}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+jt[r]+t]=o[r]||o[r-2]||o[0];return i}},wt.test(e)||(x.cssHooks[e+t].set=Ot)});var Wt=/%20/g,$t=/\[\]$/,Bt=/\r?\n/g,It=/^(?:submit|button|image|reset|file)$/i,zt=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&zt.test(this.nodeName)&&!It.test(e)&&(this.checked||!ot.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(Bt,"\r\n")}}):{name:t.name,value:n.replace(Bt,"\r\n")}}).get()}}),x.param=function(e,t){var n,r=[],i=function(e,t){t=x.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(t===undefined&&(t=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){i(this.name,this.value)});else for(n in e)_t(n,e[n],t,i);return r.join("&").replace(Wt,"+")};function _t(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||$t.test(e)?r(e,i):_t(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)_t(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)
},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var Xt,Ut,Yt=x.now(),Vt=/\?/,Gt=/#.*$/,Jt=/([?&])_=[^&]*/,Qt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Kt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Zt=/^(?:GET|HEAD)$/,en=/^\/\//,tn=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,nn=x.fn.load,rn={},on={},sn="*/".concat("*");try{Ut=i.href}catch(an){Ut=o.createElement("a"),Ut.href="",Ut=Ut.href}Xt=tn.exec(Ut.toLowerCase())||[];function un(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function ln(e,t,n,r){var i={},o=e===on;function s(a){var u;return i[a]=!0,x.each(e[a]||[],function(e,a){var l=a(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):undefined:(t.dataTypes.unshift(l),s(l),!1)}),u}return s(t.dataTypes[0])||!i["*"]&&s("*")}function cn(e,t){var n,r,i=x.ajaxSettings.flatOptions||{};for(n in t)t[n]!==undefined&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,t,n){if("string"!=typeof e&&nn)return nn.apply(this,arguments);var r,i,o,s=this,a=e.indexOf(" ");return a>=0&&(r=e.slice(a),e=e.slice(0,a)),x.isFunction(t)?(n=t,t=undefined):t&&"object"==typeof t&&(i="POST"),s.length>0&&x.ajax({url:e,type:i,dataType:"html",data:t}).done(function(e){o=arguments,s.html(r?x("<div>").append(x.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){s.each(n,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ut,type:"GET",isLocal:Kt.test(Xt[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":sn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?cn(cn(e,x.ajaxSettings),t):cn(x.ajaxSettings,e)},ajaxPrefilter:un(rn),ajaxTransport:un(on),ajax:function(e,t){"object"==typeof e&&(t=e,e=undefined),t=t||{};var n,r,i,o,s,a,u,l,c=x.ajaxSetup({},t),p=c.context||c,f=c.context&&(p.nodeType||p.jquery)?x(p):x.event,h=x.Deferred(),d=x.Callbacks("once memory"),g=c.statusCode||{},m={},y={},v=0,b="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===v){if(!o){o={};while(t=Qt.exec(i))o[t[1].toLowerCase()]=t[2]}t=o[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===v?i:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return v||(e=y[n]=y[n]||e,m[e]=t),this},overrideMimeType:function(e){return v||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>v)for(t in e)g[t]=[g[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||b;return n&&n.abort(t),k(0,t),this}};if(h.promise(T).complete=d.add,T.success=T.done,T.error=T.fail,c.url=((e||c.url||Ut)+"").replace(Gt,"").replace(en,Xt[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=x.trim(c.dataType||"*").toLowerCase().match(w)||[""],null==c.crossDomain&&(a=tn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===Xt[1]&&a[2]===Xt[2]&&(a[3]||("http:"===a[1]?"80":"443"))===(Xt[3]||("http:"===Xt[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=x.param(c.data,c.traditional)),ln(rn,c,t,T),2===v)return T;u=c.global,u&&0===x.active++&&x.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Zt.test(c.type),r=c.url,c.hasContent||(c.data&&(r=c.url+=(Vt.test(r)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=Jt.test(r)?r.replace(Jt,"$1_="+Yt++):r+(Vt.test(r)?"&":"?")+"_="+Yt++)),c.ifModified&&(x.lastModified[r]&&T.setRequestHeader("If-Modified-Since",x.lastModified[r]),x.etag[r]&&T.setRequestHeader("If-None-Match",x.etag[r])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType),T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+sn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)T.setRequestHeader(l,c.headers[l]);if(c.beforeSend&&(c.beforeSend.call(p,T,c)===!1||2===v))return T.abort();b="abort";for(l in{success:1,error:1,complete:1})T[l](c[l]);if(n=ln(on,c,t,T)){T.readyState=1,u&&f.trigger("ajaxSend",[T,c]),c.async&&c.timeout>0&&(s=setTimeout(function(){T.abort("timeout")},c.timeout));try{v=1,n.send(m,k)}catch(C){if(!(2>v))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,t,o,a){var l,m,y,b,w,C=t;2!==v&&(v=2,s&&clearTimeout(s),n=undefined,i=a||"",T.readyState=e>0?4:0,l=e>=200&&300>e||304===e,o&&(b=pn(c,T,o)),b=fn(c,b,T,l),l?(c.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(x.lastModified[r]=w),w=T.getResponseHeader("etag"),w&&(x.etag[r]=w)),204===e||"HEAD"===c.type?C="nocontent":304===e?C="notmodified":(C=b.state,m=b.data,y=b.error,l=!y)):(y=C,(e||!C)&&(C="error",0>e&&(e=0))),T.status=e,T.statusText=(t||C)+"",l?h.resolveWith(p,[m,C,T]):h.rejectWith(p,[T,C,y]),T.statusCode(g),g=undefined,u&&f.trigger(l?"ajaxSuccess":"ajaxError",[T,c,l?m:y]),d.fireWith(p,[T,C]),u&&(f.trigger("ajaxComplete",[T,c]),--x.active||x.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,t){return x.get(e,undefined,t,"script")}}),x.each(["get","post"],function(e,t){x[t]=function(e,n,r,i){return x.isFunction(n)&&(i=i||r,r=n,n=undefined),x.ajax({url:e,type:t,dataType:i,data:n,success:r})}});function pn(e,t,n){var r,i,o,s,a=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),r===undefined&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in a)if(a[i]&&a[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}s||(s=i)}o=o||s}return o?(o!==u[0]&&u.unshift(o),n[o]):undefined}function fn(e,t,n,r){var i,o,s,a,u,l={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)l[s.toLowerCase()]=e.converters[s];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(s=l[u+" "+o]||l["* "+o],!s)for(i in l)if(a=i.split(" "),a[1]===o&&(s=l[u+" "+a[0]]||l["* "+a[0]])){s===!0?s=l[i]:l[i]!==!0&&(o=a[0],c.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(p){return{state:"parsererror",error:s?p:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===undefined&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),x.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(r,i){t=x("<script>").prop({async:!0,charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&i("error"===e.type?404:200,e.type)}),o.head.appendChild(t[0])},abort:function(){n&&n()}}}});var hn=[],dn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=hn.pop()||x.expando+"_"+Yt++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,s,a=t.jsonp!==!1&&(dn.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&dn.test(t.data)&&"data");return a||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=x.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,a?t[a]=t[a].replace(dn,"$1"+i):t.jsonp!==!1&&(t.url+=(Vt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return s||x.error(i+" was not called"),s[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){s=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,hn.push(i)),s&&x.isFunction(o)&&o(s[0]),s=o=undefined}),"script"):undefined}),x.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(e){}};var gn=x.ajaxSettings.xhr(),mn={0:200,1223:204},yn=0,vn={};e.ActiveXObject&&x(e).on("unload",function(){for(var e in vn)vn[e]();vn=undefined}),x.support.cors=!!gn&&"withCredentials"in gn,x.support.ajax=gn=!!gn,x.ajaxTransport(function(e){var t;return x.support.cors||gn&&!e.crossDomain?{send:function(n,r){var i,o,s=e.xhr();if(s.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)s[i]=e.xhrFields[i];e.mimeType&&s.overrideMimeType&&s.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)s.setRequestHeader(i,n[i]);t=function(e){return function(){t&&(delete vn[o],t=s.onload=s.onerror=null,"abort"===e?s.abort():"error"===e?r(s.status||404,s.statusText):r(mn[s.status]||s.status,s.statusText,"string"==typeof s.responseText?{text:s.responseText}:undefined,s.getAllResponseHeaders()))}},s.onload=t(),s.onerror=t("error"),t=vn[o=yn++]=t("abort"),s.send(e.hasContent&&e.data||null)},abort:function(){t&&t()}}:undefined});var xn,bn,wn=/^(?:toggle|show|hide)$/,Tn=RegExp("^(?:([+-])=|)("+b+")([a-z%]*)$","i"),Cn=/queueHooks$/,kn=[An],Nn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Tn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),s=(x.cssNumber[e]||"px"!==o&&+r)&&Tn.exec(x.css(n.elem,e)),a=1,u=20;if(s&&s[3]!==o){o=o||s[3],i=i||[],s=+r||1;do a=a||".5",s/=a,x.style(n.elem,e,s+o);while(a!==(a=n.cur()/r)&&1!==a&&--u)}return i&&(s=n.start=+s||+r||0,n.unit=o,n.end=i[1]?s+(i[1]+1)*i[2]:+i[2]),n}]};function En(){return setTimeout(function(){xn=undefined}),xn=x.now()}function Sn(e,t,n){var r,i=(Nn[t]||[]).concat(Nn["*"]),o=0,s=i.length;for(;s>o;o++)if(r=i[o].call(n,t,e))return r}function jn(e,t,n){var r,i,o=0,s=kn.length,a=x.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=xn||En(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,s=0,u=l.tweens.length;for(;u>s;s++)l.tweens[s].run(o);return a.notifyWith(e,[l,o,n]),1>o&&u?n:(a.resolveWith(e,[l]),!1)},l=a.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:xn||En(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?a.resolveWith(e,[l,t]):a.rejectWith(e,[l,t]),this}}),c=l.props;for(Dn(c,l.opts.specialEasing);s>o;o++)if(r=kn[o].call(l,e,c,l.opts))return r;return x.map(c,Sn,l),x.isFunction(l.opts.start)&&l.opts.start.call(e,l),x.fx.timer(x.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function Dn(e,t){var n,r,i,o,s;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),s=x.cssHooks[r],s&&"expand"in s){o=s.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(jn,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Nn[n]=Nn[n]||[],Nn[n].unshift(t)},prefilter:function(e,t){t?kn.unshift(e):kn.push(e)}});function An(e,t,n){var r,i,o,s,a,u,l=this,c={},p=e.style,f=e.nodeType&&Lt(e),h=q.get(e,"fxshow");n.queue||(a=x._queueHooks(e,"fx"),null==a.unqueued&&(a.unqueued=0,u=a.empty.fire,a.empty.fire=function(){a.unqueued||u()}),a.unqueued++,l.always(function(){l.always(function(){a.unqueued--,x.queue(e,"fx").length||a.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(p.display="inline-block")),n.overflow&&(p.overflow="hidden",l.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],wn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show")){if("show"!==i||!h||h[r]===undefined)continue;f=!0}c[r]=h&&h[r]||x.style(e,r)}if(!x.isEmptyObject(c)){h?"hidden"in h&&(f=h.hidden):h=q.access(e,"fxshow",{}),o&&(h.hidden=!f),f?x(e).show():l.done(function(){x(e).hide()}),l.done(function(){var t;q.remove(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)s=Sn(f?h[r]:0,r,l),r in h||(h[r]=s.start,f&&(s.end=s.start,s.start="width"===r||"height"===r?1:0))}}function Ln(e,t,n,r,i){return new Ln.prototype.init(e,t,n,r,i)}x.Tween=Ln,Ln.prototype={constructor:Ln,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=Ln.propHooks[this.prop];return e&&e.get?e.get(this):Ln.propHooks._default.get(this)},run:function(e){var t,n=Ln.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Ln.propHooks._default.set(this),this}},Ln.prototype.init.prototype=Ln.prototype,Ln.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Ln.propHooks.scrollTop=Ln.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(qn(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Lt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),s=function(){var t=jn(this,x.extend({},e),o);(i||q.get(this,"finish"))&&t.stop(!0)};return s.finish=s,i||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=undefined),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=x.timers,s=q.get(this);if(i)s[i]&&s[i].stop&&r(s[i]);else for(i in s)s[i]&&s[i].stop&&Cn.test(i)&&r(s[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=q.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,s=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function qn(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=jt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:qn("show"),slideUp:qn("hide"),slideToggle:qn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=Ln.prototype.init,x.fx.tick=function(){var e,t=x.timers,n=0;for(xn=x.now();t.length>n;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||x.fx.stop(),xn=undefined},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){bn||(bn=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(bn),bn=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===undefined?this:this.each(function(t){x.offset.setOffset(this,e,t)});var t,n,i=this[0],o={top:0,left:0},s=i&&i.ownerDocument;if(s)return t=s.documentElement,x.contains(t,i)?(typeof i.getBoundingClientRect!==r&&(o=i.getBoundingClientRect()),n=Hn(s),{top:o.top+n.pageYOffset-t.clientTop,left:o.left+n.pageXOffset-t.clientLeft}):o},x.offset={setOffset:function(e,t,n){var r,i,o,s,a,u,l,c=x.css(e,"position"),p=x(e),f={};"static"===c&&(e.style.position="relative"),a=p.offset(),o=x.css(e,"top"),u=x.css(e,"left"),l=("absolute"===c||"fixed"===c)&&(o+u).indexOf("auto")>-1,l?(r=p.position(),s=r.top,i=r.left):(s=parseFloat(o)||0,i=parseFloat(u)||0),x.isFunction(t)&&(t=t.call(e,n,a)),null!=t.top&&(f.top=t.top-a.top+s),null!=t.left&&(f.left=t.left-a.left+i),"using"in t?t.using.call(e,f):p.css(f)}},x.fn.extend({position:function(){if(this[0]){var e,t,n=this[0],r={top:0,left:0};return"fixed"===x.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(r=e.offset()),r.top+=x.css(e[0],"borderTopWidth",!0),r.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-r.top-x.css(n,"marginTop",!0),left:t.left-r.left-x.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,n){var r="pageYOffset"===n;x.fn[t]=function(i){return x.access(this,function(t,i,o){var s=Hn(t);return o===undefined?s?s[n]:t[i]:(s?s.scrollTo(r?e.pageXOffset:o,r?o:e.pageYOffset):t[i]=o,undefined)},t,i,arguments.length,null)}});function Hn(e){return x.isWindow(e)?e:9===e.nodeType&&e.defaultView}x.each({Height:"height",Width:"width"},function(e,t){x.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){x.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),s=n||(r===!0||i===!0?"margin":"border");return x.access(this,function(t,n,r){var i;return x.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):r===undefined?x.css(t,n,s):x.style(t,n,r,s)},t,o?r:undefined,o,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}),"object"==typeof e&&"object"==typeof e.document&&(e.jQuery=e.$=x)})(window);/*! jPlayer 2.9.2 for jQuery ~ (c) 2009-2014 Happyworm Ltd ~ MIT License */
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],b):b("object"==typeof exports?require("jquery"):a.jQuery?a.jQuery:a.Zepto)}(this,function(a,b){a.fn.jPlayer=function(c){var d="jPlayer",e="string"==typeof c,f=Array.prototype.slice.call(arguments,1),g=this;return c=!e&&f.length?a.extend.apply(null,[!0,c].concat(f)):c,e&&"_"===c.charAt(0)?g:(this.each(e?function(){var e=a(this).data(d),h=e&&a.isFunction(e[c])?e[c].apply(e,f):e;return h!==e&&h!==b?(g=h,!1):void 0}:function(){var b=a(this).data(d);b?b.option(c||{}):a(this).data(d,new a.jPlayer(c,this))}),g)},a.jPlayer=function(b,c){if(arguments.length){this.element=a(c),this.options=a.extend(!0,{},this.options,b);var d=this;this.element.bind("remove.jPlayer",function(){d.destroy()}),this._init()}},"function"!=typeof a.fn.stop&&(a.fn.stop=function(){}),a.jPlayer.emulateMethods="load play pause",a.jPlayer.emulateStatus="src readyState networkState currentTime duration paused ended playbackRate",a.jPlayer.emulateOptions="muted volume",a.jPlayer.reservedEvent="ready flashreset resize repeat error warning",a.jPlayer.event={},a.each(["ready","setmedia","flashreset","resize","repeat","click","error","warning","loadstart","progress","suspend","abort","emptied","stalled","play","pause","loadedmetadata","loadeddata","waiting","playing","canplay","canplaythrough","seeking","seeked","timeupdate","ended","ratechange","durationchange","volumechange"],function(){a.jPlayer.event[this]="jPlayer_"+this}),a.jPlayer.htmlEvent=["loadstart","abort","emptied","stalled","loadedmetadata","canplay","canplaythrough"],a.jPlayer.pause=function(){a.jPlayer.prototype.destroyRemoved(),a.each(a.jPlayer.prototype.instances,function(a,b){b.data("jPlayer").status.srcSet&&b.jPlayer("pause")})},a.jPlayer.timeFormat={showHour:!1,showMin:!0,showSec:!0,padHour:!1,padMin:!0,padSec:!0,sepHour:":",sepMin:":",sepSec:""};var c=function(){this.init()};c.prototype={init:function(){this.options={timeFormat:a.jPlayer.timeFormat}},time:function(a){a=a&&"number"==typeof a?a:0;var b=new Date(1e3*a),c=b.getUTCHours(),d=this.options.timeFormat.showHour?b.getUTCMinutes():b.getUTCMinutes()+60*c,e=this.options.timeFormat.showMin?b.getUTCSeconds():b.getUTCSeconds()+60*d,f=this.options.timeFormat.padHour&&10>c?"0"+c:c,g=this.options.timeFormat.padMin&&10>d?"0"+d:d,h=this.options.timeFormat.padSec&&10>e?"0"+e:e,i="";return i+=this.options.timeFormat.showHour?f+this.options.timeFormat.sepHour:"",i+=this.options.timeFormat.showMin?g+this.options.timeFormat.sepMin:"",i+=this.options.timeFormat.showSec?h+this.options.timeFormat.sepSec:""}};var d=new c;a.jPlayer.convertTime=function(a){return d.time(a)},a.jPlayer.uaBrowser=function(a){var b=a.toLowerCase(),c=/(webkit)[ \/]([\w.]+)/,d=/(opera)(?:.*version)?[ \/]([\w.]+)/,e=/(msie) ([\w.]+)/,f=/(mozilla)(?:.*? rv:([\w.]+))?/,g=c.exec(b)||d.exec(b)||e.exec(b)||b.indexOf("compatible")<0&&f.exec(b)||[];return{browser:g[1]||"",version:g[2]||"0"}},a.jPlayer.uaPlatform=function(a){var b=a.toLowerCase(),c=/(ipad|iphone|ipod|android|blackberry|playbook|windows ce|webos)/,d=/(ipad|playbook)/,e=/(android)/,f=/(mobile)/,g=c.exec(b)||[],h=d.exec(b)||!f.exec(b)&&e.exec(b)||[];return g[1]&&(g[1]=g[1].replace(/\s/g,"_")),{platform:g[1]||"",tablet:h[1]||""}},a.jPlayer.browser={},a.jPlayer.platform={};var e=a.jPlayer.uaBrowser(navigator.userAgent);e.browser&&(a.jPlayer.browser[e.browser]=!0,a.jPlayer.browser.version=e.version);var f=a.jPlayer.uaPlatform(navigator.userAgent);f.platform&&(a.jPlayer.platform[f.platform]=!0,a.jPlayer.platform.mobile=!f.tablet,a.jPlayer.platform.tablet=!!f.tablet),a.jPlayer.getDocMode=function(){var b;return a.jPlayer.browser.msie&&(document.documentMode?b=document.documentMode:(b=5,document.compatMode&&"CSS1Compat"===document.compatMode&&(b=7))),b},a.jPlayer.browser.documentMode=a.jPlayer.getDocMode(),a.jPlayer.nativeFeatures={init:function(){var a,b,c,d=document,e=d.createElement("video"),f={w3c:["fullscreenEnabled","fullscreenElement","requestFullscreen","exitFullscreen","fullscreenchange","fullscreenerror"],moz:["mozFullScreenEnabled","mozFullScreenElement","mozRequestFullScreen","mozCancelFullScreen","mozfullscreenchange","mozfullscreenerror"],webkit:["","webkitCurrentFullScreenElement","webkitRequestFullScreen","webkitCancelFullScreen","webkitfullscreenchange",""],webkitVideo:["webkitSupportsFullscreen","webkitDisplayingFullscreen","webkitEnterFullscreen","webkitExitFullscreen","",""],ms:["","msFullscreenElement","msRequestFullscreen","msExitFullscreen","MSFullscreenChange","MSFullscreenError"]},g=["w3c","moz","webkit","webkitVideo","ms"];for(this.fullscreen=a={support:{w3c:!!d[f.w3c[0]],moz:!!d[f.moz[0]],webkit:"function"==typeof d[f.webkit[3]],webkitVideo:"function"==typeof e[f.webkitVideo[2]],ms:"function"==typeof e[f.ms[2]]},used:{}},b=0,c=g.length;c>b;b++){var h=g[b];if(a.support[h]){a.spec=h,a.used[h]=!0;break}}if(a.spec){var i=f[a.spec];a.api={fullscreenEnabled:!0,fullscreenElement:function(a){return a=a?a:d,a[i[1]]},requestFullscreen:function(a){return a[i[2]]()},exitFullscreen:function(a){return a=a?a:d,a[i[3]]()}},a.event={fullscreenchange:i[4],fullscreenerror:i[5]}}else a.api={fullscreenEnabled:!1,fullscreenElement:function(){return null},requestFullscreen:function(){},exitFullscreen:function(){}},a.event={}}},a.jPlayer.nativeFeatures.init(),a.jPlayer.focus=null,a.jPlayer.keyIgnoreElementNames="A INPUT TEXTAREA SELECT BUTTON";var g=function(b){var c,d=a.jPlayer.focus;d&&(a.each(a.jPlayer.keyIgnoreElementNames.split(/\s+/g),function(a,d){return b.target.nodeName.toUpperCase()===d.toUpperCase()?(c=!0,!1):void 0}),c||a.each(d.options.keyBindings,function(c,e){return e&&a.isFunction(e.fn)&&("number"==typeof e.key&&b.which===e.key||"string"==typeof e.key&&b.key===e.key)?(b.preventDefault(),e.fn(d),!1):void 0}))};a.jPlayer.keys=function(b){var c="keydown.jPlayer";a(document.documentElement).unbind(c),b&&a(document.documentElement).bind(c,g)},a.jPlayer.keys(!0),a.jPlayer.prototype={count:0,version:{script:"2.9.2",needFlash:"2.9.0",flash:"unknown"},options:{swfPath:"js",solution:"html, flash",supplied:"mp3",auroraFormats:"wav",preload:"metadata",volume:.8,muted:!1,remainingDuration:!1,toggleDuration:!1,captureDuration:!0,playbackRate:1,defaultPlaybackRate:1,minPlaybackRate:.5,maxPlaybackRate:4,wmode:"opaque",backgroundColor:"#000000",cssSelectorAncestor:"#jp_container_1",cssSelector:{videoPlay:".jp-video-play",play:".jp-play",pause:".jp-pause",stop:".jp-stop",seekBar:".jp-seek-bar",playBar:".jp-play-bar",mute:".jp-mute",unmute:".jp-unmute",volumeBar:".jp-volume-bar",volumeBarValue:".jp-volume-bar-value",volumeMax:".jp-volume-max",playbackRateBar:".jp-playback-rate-bar",playbackRateBarValue:".jp-playback-rate-bar-value",currentTime:".jp-current-time",duration:".jp-duration",title:".jp-title",fullScreen:".jp-full-screen",restoreScreen:".jp-restore-screen",repeat:".jp-repeat",repeatOff:".jp-repeat-off",gui:".jp-gui",noSolution:".jp-no-solution"},stateClass:{playing:"jp-state-playing",seeking:"jp-state-seeking",muted:"jp-state-muted",looped:"jp-state-looped",fullScreen:"jp-state-full-screen",noVolume:"jp-state-no-volume"},useStateClassSkin:!1,autoBlur:!0,smoothPlayBar:!1,fullScreen:!1,fullWindow:!1,autohide:{restored:!1,full:!0,fadeIn:200,fadeOut:600,hold:1e3},loop:!1,repeat:function(b){b.jPlayer.options.loop?a(this).unbind(".jPlayerRepeat").bind(a.jPlayer.event.ended+".jPlayer.jPlayerRepeat",function(){a(this).jPlayer("play")}):a(this).unbind(".jPlayerRepeat")},nativeVideoControls:{},noFullWindow:{msie:/msie [0-6]\./,ipad:/ipad.*?os [0-4]\./,iphone:/iphone/,ipod:/ipod/,android_pad:/android [0-3]\.(?!.*?mobile)/,android_phone:/(?=.*android)(?!.*chrome)(?=.*mobile)/,blackberry:/blackberry/,windows_ce:/windows ce/,iemobile:/iemobile/,webos:/webos/},noVolume:{ipad:/ipad/,iphone:/iphone/,ipod:/ipod/,android_pad:/android(?!.*?mobile)/,android_phone:/android.*?mobile/,blackberry:/blackberry/,windows_ce:/windows ce/,iemobile:/iemobile/,webos:/webos/,playbook:/playbook/},timeFormat:{},keyEnabled:!1,audioFullScreen:!1,keyBindings:{play:{key:80,fn:function(a){a.status.paused?a.play():a.pause()}},fullScreen:{key:70,fn:function(a){(a.status.video||a.options.audioFullScreen)&&a._setOption("fullScreen",!a.options.fullScreen)}},muted:{key:77,fn:function(a){a._muted(!a.options.muted)}},volumeUp:{key:190,fn:function(a){a.volume(a.options.volume+.1)}},volumeDown:{key:188,fn:function(a){a.volume(a.options.volume-.1)}},loop:{key:76,fn:function(a){a._loop(!a.options.loop)}}},verticalVolume:!1,verticalPlaybackRate:!1,globalVolume:!1,idPrefix:"jp",noConflict:"jQuery",emulateHtml:!1,consoleAlerts:!0,errorAlerts:!1,warningAlerts:!1},optionsAudio:{size:{width:"0px",height:"0px",cssClass:""},sizeFull:{width:"0px",height:"0px",cssClass:""}},optionsVideo:{size:{width:"480px",height:"270px",cssClass:"jp-video-270p"},sizeFull:{width:"100%",height:"100%",cssClass:"jp-video-full"}},instances:{},status:{src:"",media:{},paused:!0,format:{},formatType:"",waitForPlay:!0,waitForLoad:!0,srcSet:!1,video:!1,seekPercent:0,currentPercentRelative:0,currentPercentAbsolute:0,currentTime:0,duration:0,remaining:0,videoWidth:0,videoHeight:0,readyState:0,networkState:0,playbackRate:1,ended:0},internal:{ready:!1},solution:{html:!0,aurora:!0,flash:!0},format:{mp3:{codec:"audio/mpeg",flashCanPlay:!0,media:"audio"},m4a:{codec:'audio/mp4; codecs="mp4a.40.2"',flashCanPlay:!0,media:"audio"},m3u8a:{codec:'application/vnd.apple.mpegurl; codecs="mp4a.40.2"',flashCanPlay:!1,media:"audio"},m3ua:{codec:"audio/mpegurl",flashCanPlay:!1,media:"audio"},oga:{codec:'audio/ogg; codecs="vorbis, opus"',flashCanPlay:!1,media:"audio"},flac:{codec:"audio/x-flac",flashCanPlay:!1,media:"audio"},wav:{codec:'audio/wav; codecs="1"',flashCanPlay:!1,media:"audio"},webma:{codec:'audio/webm; codecs="vorbis"',flashCanPlay:!1,media:"audio"},fla:{codec:"audio/x-flv",flashCanPlay:!0,media:"audio"},rtmpa:{codec:'audio/rtmp; codecs="rtmp"',flashCanPlay:!0,media:"audio"},m4v:{codec:'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',flashCanPlay:!0,media:"video"},m3u8v:{codec:'application/vnd.apple.mpegurl; codecs="avc1.42E01E, mp4a.40.2"',flashCanPlay:!1,media:"video"},m3uv:{codec:"audio/mpegurl",flashCanPlay:!1,media:"video"},ogv:{codec:'video/ogg; codecs="theora, vorbis"',flashCanPlay:!1,media:"video"},webmv:{codec:'video/webm; codecs="vorbis, vp8"',flashCanPlay:!1,media:"video"},flv:{codec:"video/x-flv",flashCanPlay:!0,media:"video"},rtmpv:{codec:'video/rtmp; codecs="rtmp"',flashCanPlay:!0,media:"video"}},_init:function(){var c=this;if(this.element.empty(),this.status=a.extend({},this.status),this.internal=a.extend({},this.internal),this.options.timeFormat=a.extend({},a.jPlayer.timeFormat,this.options.timeFormat),this.internal.cmdsIgnored=a.jPlayer.platform.ipad||a.jPlayer.platform.iphone||a.jPlayer.platform.ipod,this.internal.domNode=this.element.get(0),this.options.keyEnabled&&!a.jPlayer.focus&&(a.jPlayer.focus=this),this.androidFix={setMedia:!1,play:!1,pause:!1,time:0/0},a.jPlayer.platform.android&&(this.options.preload="auto"!==this.options.preload?"metadata":"auto"),this.formats=[],this.solutions=[],this.require={},this.htmlElement={},this.html={},this.html.audio={},this.html.video={},this.aurora={},this.aurora.formats=[],this.aurora.properties=[],this.flash={},this.css={},this.css.cs={},this.css.jq={},this.ancestorJq=[],this.options.volume=this._limitValue(this.options.volume,0,1),a.each(this.options.supplied.toLowerCase().split(","),function(b,d){var e=d.replace(/^\s+|\s+$/g,"");if(c.format[e]){var f=!1;a.each(c.formats,function(a,b){return e===b?(f=!0,!1):void 0}),f||c.formats.push(e)}}),a.each(this.options.solution.toLowerCase().split(","),function(b,d){var e=d.replace(/^\s+|\s+$/g,"");if(c.solution[e]){var f=!1;a.each(c.solutions,function(a,b){return e===b?(f=!0,!1):void 0}),f||c.solutions.push(e)}}),a.each(this.options.auroraFormats.toLowerCase().split(","),function(b,d){var e=d.replace(/^\s+|\s+$/g,"");if(c.format[e]){var f=!1;a.each(c.aurora.formats,function(a,b){return e===b?(f=!0,!1):void 0}),f||c.aurora.formats.push(e)}}),this.internal.instance="jp_"+this.count,this.instances[this.internal.instance]=this.element,this.element.attr("id")||this.element.attr("id",this.options.idPrefix+"_jplayer_"+this.count),this.internal.self=a.extend({},{id:this.element.attr("id"),jq:this.element}),this.internal.audio=a.extend({},{id:this.options.idPrefix+"_audio_"+this.count,jq:b}),this.internal.video=a.extend({},{id:this.options.idPrefix+"_video_"+this.count,jq:b}),this.internal.flash=a.extend({},{id:this.options.idPrefix+"_flash_"+this.count,jq:b,swf:this.options.swfPath+(".swf"!==this.options.swfPath.toLowerCase().slice(-4)?(this.options.swfPath&&"/"!==this.options.swfPath.slice(-1)?"/":"")+"jquery.jplayer.swf":"")}),this.internal.poster=a.extend({},{id:this.options.idPrefix+"_poster_"+this.count,jq:b}),a.each(a.jPlayer.event,function(a,d){c.options[a]!==b&&(c.element.bind(d+".jPlayer",c.options[a]),c.options[a]=b)}),this.require.audio=!1,this.require.video=!1,a.each(this.formats,function(a,b){c.require[c.format[b].media]=!0}),this.options=this.require.video?a.extend(!0,{},this.optionsVideo,this.options):a.extend(!0,{},this.optionsAudio,this.options),this._setSize(),this.status.nativeVideoControls=this._uaBlocklist(this.options.nativeVideoControls),this.status.noFullWindow=this._uaBlocklist(this.options.noFullWindow),this.status.noVolume=this._uaBlocklist(this.options.noVolume),a.jPlayer.nativeFeatures.fullscreen.api.fullscreenEnabled&&this._fullscreenAddEventListeners(),this._restrictNativeVideoControls(),this.htmlElement.poster=document.createElement("img"),this.htmlElement.poster.id=this.internal.poster.id,this.htmlElement.poster.onload=function(){(!c.status.video||c.status.waitForPlay)&&c.internal.poster.jq.show()},this.element.append(this.htmlElement.poster),this.internal.poster.jq=a("#"+this.internal.poster.id),this.internal.poster.jq.css({width:this.status.width,height:this.status.height}),this.internal.poster.jq.hide(),this.internal.poster.jq.bind("click.jPlayer",function(){c._trigger(a.jPlayer.event.click)}),this.html.audio.available=!1,this.require.audio&&(this.htmlElement.audio=document.createElement("audio"),this.htmlElement.audio.id=this.internal.audio.id,this.html.audio.available=!!this.htmlElement.audio.canPlayType&&this._testCanPlayType(this.htmlElement.audio)),this.html.video.available=!1,this.require.video&&(this.htmlElement.video=document.createElement("video"),this.htmlElement.video.id=this.internal.video.id,this.html.video.available=!!this.htmlElement.video.canPlayType&&this._testCanPlayType(this.htmlElement.video)),this.flash.available=this._checkForFlash(10.1),this.html.canPlay={},this.aurora.canPlay={},this.flash.canPlay={},a.each(this.formats,function(b,d){c.html.canPlay[d]=c.html[c.format[d].media].available&&""!==c.htmlElement[c.format[d].media].canPlayType(c.format[d].codec),c.aurora.canPlay[d]=a.inArray(d,c.aurora.formats)>-1,c.flash.canPlay[d]=c.format[d].flashCanPlay&&c.flash.available}),this.html.desired=!1,this.aurora.desired=!1,this.flash.desired=!1,a.each(this.solutions,function(b,d){if(0===b)c[d].desired=!0;else{var e=!1,f=!1;a.each(c.formats,function(a,b){c[c.solutions[0]].canPlay[b]&&("video"===c.format[b].media?f=!0:e=!0)}),c[d].desired=c.require.audio&&!e||c.require.video&&!f}}),this.html.support={},this.aurora.support={},this.flash.support={},a.each(this.formats,function(a,b){c.html.support[b]=c.html.canPlay[b]&&c.html.desired,c.aurora.support[b]=c.aurora.canPlay[b]&&c.aurora.desired,c.flash.support[b]=c.flash.canPlay[b]&&c.flash.desired}),this.html.used=!1,this.aurora.used=!1,this.flash.used=!1,a.each(this.solutions,function(b,d){a.each(c.formats,function(a,b){return c[d].support[b]?(c[d].used=!0,!1):void 0})}),this._resetActive(),this._resetGate(),this._cssSelectorAncestor(this.options.cssSelectorAncestor),this.html.used||this.aurora.used||this.flash.used?this.css.jq.noSolution.length&&this.css.jq.noSolution.hide():(this._error({type:a.jPlayer.error.NO_SOLUTION,context:"{solution:'"+this.options.solution+"', supplied:'"+this.options.supplied+"'}",message:a.jPlayer.errorMsg.NO_SOLUTION,hint:a.jPlayer.errorHint.NO_SOLUTION}),this.css.jq.noSolution.length&&this.css.jq.noSolution.show()),this.flash.used){var d,e="jQuery="+encodeURI(this.options.noConflict)+"&id="+encodeURI(this.internal.self.id)+"&vol="+this.options.volume+"&muted="+this.options.muted;if(a.jPlayer.browser.msie&&(Number(a.jPlayer.browser.version)<9||a.jPlayer.browser.documentMode<9)){var f='<object id="'+this.internal.flash.id+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="0" height="0" tabindex="-1"></object>',g=['<param name="movie" value="'+this.internal.flash.swf+'" />','<param name="FlashVars" value="'+e+'" />','<param name="allowScriptAccess" value="always" />','<param name="bgcolor" value="'+this.options.backgroundColor+'" />','<param name="wmode" value="'+this.options.wmode+'" />'];d=document.createElement(f);for(var h=0;h<g.length;h++)d.appendChild(document.createElement(g[h]))}else{var i=function(a,b,c){var d=document.createElement("param");d.setAttribute("name",b),d.setAttribute("value",c),a.appendChild(d)};d=document.createElement("object"),d.setAttribute("id",this.internal.flash.id),d.setAttribute("name",this.internal.flash.id),d.setAttribute("data",this.internal.flash.swf),d.setAttribute("type","application/x-shockwave-flash"),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("tabindex","-1"),i(d,"flashvars",e),i(d,"allowscriptaccess","always"),i(d,"bgcolor",this.options.backgroundColor),i(d,"wmode",this.options.wmode)}this.element.append(d),this.internal.flash.jq=a(d)}this.status.playbackRateEnabled=this.html.used&&!this.flash.used?this._testPlaybackRate("audio"):!1,this._updatePlaybackRate(),this.html.used&&(this.html.audio.available&&(this._addHtmlEventListeners(this.htmlElement.audio,this.html.audio),this.element.append(this.htmlElement.audio),this.internal.audio.jq=a("#"+this.internal.audio.id)),this.html.video.available&&(this._addHtmlEventListeners(this.htmlElement.video,this.html.video),this.element.append(this.htmlElement.video),this.internal.video.jq=a("#"+this.internal.video.id),this.internal.video.jq.css(this.status.nativeVideoControls?{width:this.status.width,height:this.status.height}:{width:"0px",height:"0px"}),this.internal.video.jq.bind("click.jPlayer",function(){c._trigger(a.jPlayer.event.click)}))),this.aurora.used,this.options.emulateHtml&&this._emulateHtmlBridge(),!this.html.used&&!this.aurora.used||this.flash.used||setTimeout(function(){c.internal.ready=!0,c.version.flash="n/a",c._trigger(a.jPlayer.event.repeat),c._trigger(a.jPlayer.event.ready)},100),this._updateNativeVideoControls(),this.css.jq.videoPlay.length&&this.css.jq.videoPlay.hide(),a.jPlayer.prototype.count++},destroy:function(){this.clearMedia(),this._removeUiClass(),this.css.jq.currentTime.length&&this.css.jq.currentTime.text(""),this.css.jq.duration.length&&this.css.jq.duration.text(""),a.each(this.css.jq,function(a,b){b.length&&b.unbind(".jPlayer")}),this.internal.poster.jq.unbind(".jPlayer"),this.internal.video.jq&&this.internal.video.jq.unbind(".jPlayer"),this._fullscreenRemoveEventListeners(),this===a.jPlayer.focus&&(a.jPlayer.focus=null),this.options.emulateHtml&&this._destroyHtmlBridge(),this.element.removeData("jPlayer"),this.element.unbind(".jPlayer"),this.element.empty(),delete this.instances[this.internal.instance]},destroyRemoved:function(){var b=this;a.each(this.instances,function(a,c){b.element!==c&&(c.data("jPlayer")||(c.jPlayer("destroy"),delete b.instances[a]))})},enable:function(){},disable:function(){},_testCanPlayType:function(a){try{return a.canPlayType(this.format.mp3.codec),!0}catch(b){return!1}},_testPlaybackRate:function(a){var b,c=.5;a="string"==typeof a?a:"audio",b=document.createElement(a);try{return"playbackRate"in b?(b.playbackRate=c,b.playbackRate===c):!1}catch(d){return!1}},_uaBlocklist:function(b){var c=navigator.userAgent.toLowerCase(),d=!1;return a.each(b,function(a,b){return b&&b.test(c)?(d=!0,!1):void 0}),d},_restrictNativeVideoControls:function(){this.require.audio&&this.status.nativeVideoControls&&(this.status.nativeVideoControls=!1,this.status.noFullWindow=!0)},_updateNativeVideoControls:function(){this.html.video.available&&this.html.used&&(this.htmlElement.video.controls=this.status.nativeVideoControls,this._updateAutohide(),this.status.nativeVideoControls&&this.require.video?(this.internal.poster.jq.hide(),this.internal.video.jq.css({width:this.status.width,height:this.status.height})):this.status.waitForPlay&&this.status.video&&(this.internal.poster.jq.show(),this.internal.video.jq.css({width:"0px",height:"0px"})))},_addHtmlEventListeners:function(b,c){var d=this;b.preload=this.options.preload,b.muted=this.options.muted,b.volume=this.options.volume,this.status.playbackRateEnabled&&(b.defaultPlaybackRate=this.options.defaultPlaybackRate,b.playbackRate=this.options.playbackRate),b.addEventListener("progress",function(){c.gate&&(d.internal.cmdsIgnored&&this.readyState>0&&(d.internal.cmdsIgnored=!1),d._getHtmlStatus(b),d._updateInterface(),d._trigger(a.jPlayer.event.progress))},!1),b.addEventListener("loadeddata",function(){c.gate&&(d.androidFix.setMedia=!1,d.androidFix.play&&(d.androidFix.play=!1,d.play(d.androidFix.time)),d.androidFix.pause&&(d.androidFix.pause=!1,d.pause(d.androidFix.time)),d._trigger(a.jPlayer.event.loadeddata))},!1),b.addEventListener("timeupdate",function(){c.gate&&(d._getHtmlStatus(b),d._updateInterface(),d._trigger(a.jPlayer.event.timeupdate))},!1),b.addEventListener("durationchange",function(){c.gate&&(d._getHtmlStatus(b),d._updateInterface(),d._trigger(a.jPlayer.event.durationchange))},!1),b.addEventListener("play",function(){c.gate&&(d._updateButtons(!0),d._html_checkWaitForPlay(),d._trigger(a.jPlayer.event.play))},!1),b.addEventListener("playing",function(){c.gate&&(d._updateButtons(!0),d._seeked(),d._trigger(a.jPlayer.event.playing))},!1),b.addEventListener("pause",function(){c.gate&&(d._updateButtons(!1),d._trigger(a.jPlayer.event.pause))},!1),b.addEventListener("waiting",function(){c.gate&&(d._seeking(),d._trigger(a.jPlayer.event.waiting))},!1),b.addEventListener("seeking",function(){c.gate&&(d._seeking(),d._trigger(a.jPlayer.event.seeking))},!1),b.addEventListener("seeked",function(){c.gate&&(d._seeked(),d._trigger(a.jPlayer.event.seeked))},!1),b.addEventListener("volumechange",function(){c.gate&&(d.options.volume=b.volume,d.options.muted=b.muted,d._updateMute(),d._updateVolume(),d._trigger(a.jPlayer.event.volumechange))},!1),b.addEventListener("ratechange",function(){c.gate&&(d.options.defaultPlaybackRate=b.defaultPlaybackRate,d.options.playbackRate=b.playbackRate,d._updatePlaybackRate(),d._trigger(a.jPlayer.event.ratechange))},!1),b.addEventListener("suspend",function(){c.gate&&(d._seeked(),d._trigger(a.jPlayer.event.suspend))},!1),b.addEventListener("ended",function(){c.gate&&(a.jPlayer.browser.webkit||(d.htmlElement.media.currentTime=0),d.htmlElement.media.pause(),d._updateButtons(!1),d._getHtmlStatus(b,!0),d._updateInterface(),d._trigger(a.jPlayer.event.ended))},!1),b.addEventListener("error",function(){c.gate&&(d._updateButtons(!1),d._seeked(),d.status.srcSet&&(clearTimeout(d.internal.htmlDlyCmdId),d.status.waitForLoad=!0,d.status.waitForPlay=!0,d.status.video&&!d.status.nativeVideoControls&&d.internal.video.jq.css({width:"0px",height:"0px"}),d._validString(d.status.media.poster)&&!d.status.nativeVideoControls&&d.internal.poster.jq.show(),d.css.jq.videoPlay.length&&d.css.jq.videoPlay.show(),d._error({type:a.jPlayer.error.URL,context:d.status.src,message:a.jPlayer.errorMsg.URL,hint:a.jPlayer.errorHint.URL})))},!1),a.each(a.jPlayer.htmlEvent,function(e,f){b.addEventListener(this,function(){c.gate&&d._trigger(a.jPlayer.event[f])},!1)})},_addAuroraEventListeners:function(b,c){var d=this;b.volume=100*this.options.volume,b.on("progress",function(){c.gate&&(d.internal.cmdsIgnored&&this.readyState>0&&(d.internal.cmdsIgnored=!1),d._getAuroraStatus(b),d._updateInterface(),d._trigger(a.jPlayer.event.progress),b.duration>0&&d._trigger(a.jPlayer.event.timeupdate))},!1),b.on("ready",function(){c.gate&&d._trigger(a.jPlayer.event.loadeddata)},!1),b.on("duration",function(){c.gate&&(d._getAuroraStatus(b),d._updateInterface(),d._trigger(a.jPlayer.event.durationchange))},!1),b.on("end",function(){c.gate&&(d._updateButtons(!1),d._getAuroraStatus(b,!0),d._updateInterface(),d._trigger(a.jPlayer.event.ended))},!1),b.on("error",function(){c.gate&&(d._updateButtons(!1),d._seeked(),d.status.srcSet&&(d.status.waitForLoad=!0,d.status.waitForPlay=!0,d.status.video&&!d.status.nativeVideoControls&&d.internal.video.jq.css({width:"0px",height:"0px"}),d._validString(d.status.media.poster)&&!d.status.nativeVideoControls&&d.internal.poster.jq.show(),d.css.jq.videoPlay.length&&d.css.jq.videoPlay.show(),d._error({type:a.jPlayer.error.URL,context:d.status.src,message:a.jPlayer.errorMsg.URL,hint:a.jPlayer.errorHint.URL})))},!1)},_getHtmlStatus:function(a,b){var c=0,d=0,e=0,f=0;isFinite(a.duration)&&(this.status.duration=a.duration),c=a.currentTime,d=this.status.duration>0?100*c/this.status.duration:0,"object"==typeof a.seekable&&a.seekable.length>0?(e=this.status.duration>0?100*a.seekable.end(a.seekable.length-1)/this.status.duration:100,f=this.status.duration>0?100*a.currentTime/a.seekable.end(a.seekable.length-1):0):(e=100,f=d),b&&(c=0,f=0,d=0),this.status.seekPercent=e,this.status.currentPercentRelative=f,this.status.currentPercentAbsolute=d,this.status.currentTime=c,this.status.remaining=this.status.duration-this.status.currentTime,this.status.videoWidth=a.videoWidth,this.status.videoHeight=a.videoHeight,this.status.readyState=a.readyState,this.status.networkState=a.networkState,this.status.playbackRate=a.playbackRate,this.status.ended=a.ended},_getAuroraStatus:function(a,b){var c=0,d=0,e=0,f=0;this.status.duration=a.duration/1e3,c=a.currentTime/1e3,d=this.status.duration>0?100*c/this.status.duration:0,a.buffered>0?(e=this.status.duration>0?a.buffered*this.status.duration/this.status.duration:100,f=this.status.duration>0?c/(a.buffered*this.status.duration):0):(e=100,f=d),b&&(c=0,f=0,d=0),this.status.seekPercent=e,this.status.currentPercentRelative=f,this.status.currentPercentAbsolute=d,this.status.currentTime=c,this.status.remaining=this.status.duration-this.status.currentTime,this.status.readyState=4,this.status.networkState=0,this.status.playbackRate=1,this.status.ended=!1},_resetStatus:function(){this.status=a.extend({},this.status,a.jPlayer.prototype.status)},_trigger:function(b,c,d){var e=a.Event(b);e.jPlayer={},e.jPlayer.version=a.extend({},this.version),e.jPlayer.options=a.extend(!0,{},this.options),e.jPlayer.status=a.extend(!0,{},this.status),e.jPlayer.html=a.extend(!0,{},this.html),e.jPlayer.aurora=a.extend(!0,{},this.aurora),e.jPlayer.flash=a.extend(!0,{},this.flash),c&&(e.jPlayer.error=a.extend({},c)),d&&(e.jPlayer.warning=a.extend({},d)),this.element.trigger(e)},jPlayerFlashEvent:function(b,c){if(b===a.jPlayer.event.ready)if(this.internal.ready){if(this.flash.gate){if(this.status.srcSet){var d=this.status.currentTime,e=this.status.paused;this.setMedia(this.status.media),this.volumeWorker(this.options.volume),d>0&&(e?this.pause(d):this.play(d))}this._trigger(a.jPlayer.event.flashreset)}}else this.internal.ready=!0,this.internal.flash.jq.css({width:"0px",height:"0px"}),this.version.flash=c.version,this.version.needFlash!==this.version.flash&&this._error({type:a.jPlayer.error.VERSION,context:this.version.flash,message:a.jPlayer.errorMsg.VERSION+this.version.flash,hint:a.jPlayer.errorHint.VERSION}),this._trigger(a.jPlayer.event.repeat),this._trigger(b);if(this.flash.gate)switch(b){case a.jPlayer.event.progress:this._getFlashStatus(c),this._updateInterface(),this._trigger(b);break;case a.jPlayer.event.timeupdate:this._getFlashStatus(c),this._updateInterface(),this._trigger(b);break;case a.jPlayer.event.play:this._seeked(),this._updateButtons(!0),this._trigger(b);break;case a.jPlayer.event.pause:this._updateButtons(!1),this._trigger(b);break;case a.jPlayer.event.ended:this._updateButtons(!1),this._trigger(b);break;case a.jPlayer.event.click:this._trigger(b);break;case a.jPlayer.event.error:this.status.waitForLoad=!0,this.status.waitForPlay=!0,this.status.video&&this.internal.flash.jq.css({width:"0px",height:"0px"}),this._validString(this.status.media.poster)&&this.internal.poster.jq.show(),this.css.jq.videoPlay.length&&this.status.video&&this.css.jq.videoPlay.show(),this.status.video?this._flash_setVideo(this.status.media):this._flash_setAudio(this.status.media),this._updateButtons(!1),this._error({type:a.jPlayer.error.URL,context:c.src,message:a.jPlayer.errorMsg.URL,hint:a.jPlayer.errorHint.URL});break;case a.jPlayer.event.seeking:this._seeking(),this._trigger(b);break;case a.jPlayer.event.seeked:this._seeked(),this._trigger(b);break;case a.jPlayer.event.ready:break;default:this._trigger(b)}return!1},_getFlashStatus:function(a){this.status.seekPercent=a.seekPercent,this.status.currentPercentRelative=a.currentPercentRelative,this.status.currentPercentAbsolute=a.currentPercentAbsolute,this.status.currentTime=a.currentTime,this.status.duration=a.duration,this.status.remaining=a.duration-a.currentTime,this.status.videoWidth=a.videoWidth,this.status.videoHeight=a.videoHeight,this.status.readyState=4,this.status.networkState=0,this.status.playbackRate=1,this.status.ended=!1},_updateButtons:function(a){a===b?a=!this.status.paused:this.status.paused=!a,a?this.addStateClass("playing"):this.removeStateClass("playing"),!this.status.noFullWindow&&this.options.fullWindow?this.addStateClass("fullScreen"):this.removeStateClass("fullScreen"),this.options.loop?this.addStateClass("looped"):this.removeStateClass("looped"),this.css.jq.play.length&&this.css.jq.pause.length&&(a?(this.css.jq.play.hide(),this.css.jq.pause.show()):(this.css.jq.play.show(),this.css.jq.pause.hide())),this.css.jq.restoreScreen.length&&this.css.jq.fullScreen.length&&(this.status.noFullWindow?(this.css.jq.fullScreen.hide(),this.css.jq.restoreScreen.hide()):this.options.fullWindow?(this.css.jq.fullScreen.hide(),this.css.jq.restoreScreen.show()):(this.css.jq.fullScreen.show(),this.css.jq.restoreScreen.hide())),this.css.jq.repeat.length&&this.css.jq.repeatOff.length&&(this.options.loop?(this.css.jq.repeat.hide(),this.css.jq.repeatOff.show()):(this.css.jq.repeat.show(),this.css.jq.repeatOff.hide()))},_updateInterface:function(){this.css.jq.seekBar.length&&this.css.jq.seekBar.width(this.status.seekPercent+"%"),this.css.jq.playBar.length&&(this.options.smoothPlayBar?this.css.jq.playBar.stop().animate({width:this.status.currentPercentAbsolute+"%"},250,"linear"):this.css.jq.playBar.width(this.status.currentPercentRelative+"%"));var a="";this.css.jq.currentTime.length&&(a=this._convertTime(this.status.currentTime),a!==this.css.jq.currentTime.text()&&this.css.jq.currentTime.text(this._convertTime(this.status.currentTime)));var b="",c=this.status.duration,d=this.status.remaining;this.css.jq.duration.length&&("string"==typeof this.status.media.duration?b=this.status.media.duration:("number"==typeof this.status.media.duration&&(c=this.status.media.duration,d=c-this.status.currentTime),b=this.options.remainingDuration?(d>0?"-":"")+this._convertTime(d):this._convertTime(c)),b!==this.css.jq.duration.text()&&this.css.jq.duration.text(b))},_convertTime:c.prototype.time,_seeking:function(){this.css.jq.seekBar.length&&this.css.jq.seekBar.addClass("jp-seeking-bg"),this.addStateClass("seeking")},_seeked:function(){this.css.jq.seekBar.length&&this.css.jq.seekBar.removeClass("jp-seeking-bg"),this.removeStateClass("seeking")},_resetGate:function(){this.html.audio.gate=!1,this.html.video.gate=!1,this.aurora.gate=!1,this.flash.gate=!1},_resetActive:function(){this.html.active=!1,this.aurora.active=!1,this.flash.active=!1},_escapeHtml:function(a){return a.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;").split('"').join("&quot;")},_qualifyURL:function(a){var b=document.createElement("div");
return b.innerHTML='<a href="'+this._escapeHtml(a)+'">x</a>',b.firstChild.href},_absoluteMediaUrls:function(b){var c=this;return a.each(b,function(a,d){d&&c.format[a]&&"data:"!==d.substr(0,5)&&(b[a]=c._qualifyURL(d))}),b},addStateClass:function(a){this.ancestorJq.length&&this.ancestorJq.addClass(this.options.stateClass[a])},removeStateClass:function(a){this.ancestorJq.length&&this.ancestorJq.removeClass(this.options.stateClass[a])},setMedia:function(b){var c=this,d=!1,e=this.status.media.poster!==b.poster;this._resetMedia(),this._resetGate(),this._resetActive(),this.androidFix.setMedia=!1,this.androidFix.play=!1,this.androidFix.pause=!1,b=this._absoluteMediaUrls(b),a.each(this.formats,function(e,f){var g="video"===c.format[f].media;return a.each(c.solutions,function(e,h){if(c[h].support[f]&&c._validString(b[f])){var i="html"===h,j="aurora"===h;return g?(i?(c.html.video.gate=!0,c._html_setVideo(b),c.html.active=!0):(c.flash.gate=!0,c._flash_setVideo(b),c.flash.active=!0),c.css.jq.videoPlay.length&&c.css.jq.videoPlay.show(),c.status.video=!0):(i?(c.html.audio.gate=!0,c._html_setAudio(b),c.html.active=!0,a.jPlayer.platform.android&&(c.androidFix.setMedia=!0)):j?(c.aurora.gate=!0,c._aurora_setAudio(b),c.aurora.active=!0):(c.flash.gate=!0,c._flash_setAudio(b),c.flash.active=!0),c.css.jq.videoPlay.length&&c.css.jq.videoPlay.hide(),c.status.video=!1),d=!0,!1}}),d?!1:void 0}),d?(this.status.nativeVideoControls&&this.html.video.gate||this._validString(b.poster)&&(e?this.htmlElement.poster.src=b.poster:this.internal.poster.jq.show()),"string"==typeof b.title&&(this.css.jq.title.length&&this.css.jq.title.html(b.title),this.htmlElement.audio&&this.htmlElement.audio.setAttribute("title",b.title),this.htmlElement.video&&this.htmlElement.video.setAttribute("title",b.title)),this.status.srcSet=!0,this.status.media=a.extend({},b),this._updateButtons(!1),this._updateInterface(),this._trigger(a.jPlayer.event.setmedia)):this._error({type:a.jPlayer.error.NO_SUPPORT,context:"{supplied:'"+this.options.supplied+"'}",message:a.jPlayer.errorMsg.NO_SUPPORT,hint:a.jPlayer.errorHint.NO_SUPPORT})},_resetMedia:function(){this._resetStatus(),this._updateButtons(!1),this._updateInterface(),this._seeked(),this.internal.poster.jq.hide(),clearTimeout(this.internal.htmlDlyCmdId),this.html.active?this._html_resetMedia():this.aurora.active?this._aurora_resetMedia():this.flash.active&&this._flash_resetMedia()},clearMedia:function(){this._resetMedia(),this.html.active?this._html_clearMedia():this.aurora.active?this._aurora_clearMedia():this.flash.active&&this._flash_clearMedia(),this._resetGate(),this._resetActive()},load:function(){this.status.srcSet?this.html.active?this._html_load():this.aurora.active?this._aurora_load():this.flash.active&&this._flash_load():this._urlNotSetError("load")},focus:function(){this.options.keyEnabled&&(a.jPlayer.focus=this)},play:function(a){var b="object"==typeof a;b&&this.options.useStateClassSkin&&!this.status.paused?this.pause(a):(a="number"==typeof a?a:0/0,this.status.srcSet?(this.focus(),this.html.active?this._html_play(a):this.aurora.active?this._aurora_play(a):this.flash.active&&this._flash_play(a)):this._urlNotSetError("play"))},videoPlay:function(){this.play()},pause:function(a){a="number"==typeof a?a:0/0,this.status.srcSet?this.html.active?this._html_pause(a):this.aurora.active?this._aurora_pause(a):this.flash.active&&this._flash_pause(a):this._urlNotSetError("pause")},tellOthers:function(b,c){var d=this,e="function"==typeof c,f=Array.prototype.slice.call(arguments);"string"==typeof b&&(e&&f.splice(1,1),a.jPlayer.prototype.destroyRemoved(),a.each(this.instances,function(){d.element!==this&&(!e||c.call(this.data("jPlayer"),d))&&this.jPlayer.apply(this,f)}))},pauseOthers:function(a){this.tellOthers("pause",function(){return this.status.srcSet},a)},stop:function(){this.status.srcSet?this.html.active?this._html_pause(0):this.aurora.active?this._aurora_pause(0):this.flash.active&&this._flash_pause(0):this._urlNotSetError("stop")},playHead:function(a){a=this._limitValue(a,0,100),this.status.srcSet?this.html.active?this._html_playHead(a):this.aurora.active?this._aurora_playHead(a):this.flash.active&&this._flash_playHead(a):this._urlNotSetError("playHead")},_muted:function(a){this.mutedWorker(a),this.options.globalVolume&&this.tellOthers("mutedWorker",function(){return this.options.globalVolume},a)},mutedWorker:function(b){this.options.muted=b,this.html.used&&this._html_setProperty("muted",b),this.aurora.used&&this._aurora_mute(b),this.flash.used&&this._flash_mute(b),this.html.video.gate||this.html.audio.gate||(this._updateMute(b),this._updateVolume(this.options.volume),this._trigger(a.jPlayer.event.volumechange))},mute:function(a){var c="object"==typeof a;c&&this.options.useStateClassSkin&&this.options.muted?this._muted(!1):(a=a===b?!0:!!a,this._muted(a))},unmute:function(a){a=a===b?!0:!!a,this._muted(!a)},_updateMute:function(a){a===b&&(a=this.options.muted),a?this.addStateClass("muted"):this.removeStateClass("muted"),this.css.jq.mute.length&&this.css.jq.unmute.length&&(this.status.noVolume?(this.css.jq.mute.hide(),this.css.jq.unmute.hide()):a?(this.css.jq.mute.hide(),this.css.jq.unmute.show()):(this.css.jq.mute.show(),this.css.jq.unmute.hide()))},volume:function(a){this.volumeWorker(a),this.options.globalVolume&&this.tellOthers("volumeWorker",function(){return this.options.globalVolume},a)},volumeWorker:function(b){b=this._limitValue(b,0,1),this.options.volume=b,this.html.used&&this._html_setProperty("volume",b),this.aurora.used&&this._aurora_volume(b),this.flash.used&&this._flash_volume(b),this.html.video.gate||this.html.audio.gate||(this._updateVolume(b),this._trigger(a.jPlayer.event.volumechange))},volumeBar:function(b){if(this.css.jq.volumeBar.length){var c=a(b.currentTarget),d=c.offset(),e=b.pageX-d.left,f=c.width(),g=c.height()-b.pageY+d.top,h=c.height();this.volume(this.options.verticalVolume?g/h:e/f)}this.options.muted&&this._muted(!1)},_updateVolume:function(a){a===b&&(a=this.options.volume),a=this.options.muted?0:a,this.status.noVolume?(this.addStateClass("noVolume"),this.css.jq.volumeBar.length&&this.css.jq.volumeBar.hide(),this.css.jq.volumeBarValue.length&&this.css.jq.volumeBarValue.hide(),this.css.jq.volumeMax.length&&this.css.jq.volumeMax.hide()):(this.removeStateClass("noVolume"),this.css.jq.volumeBar.length&&this.css.jq.volumeBar.show(),this.css.jq.volumeBarValue.length&&(this.css.jq.volumeBarValue.show(),this.css.jq.volumeBarValue[this.options.verticalVolume?"height":"width"](100*a+"%")),this.css.jq.volumeMax.length&&this.css.jq.volumeMax.show())},volumeMax:function(){this.volume(1),this.options.muted&&this._muted(!1)},_cssSelectorAncestor:function(b){var c=this;this.options.cssSelectorAncestor=b,this._removeUiClass(),this.ancestorJq=b?a(b):[],b&&1!==this.ancestorJq.length&&this._warning({type:a.jPlayer.warning.CSS_SELECTOR_COUNT,context:b,message:a.jPlayer.warningMsg.CSS_SELECTOR_COUNT+this.ancestorJq.length+" found for cssSelectorAncestor.",hint:a.jPlayer.warningHint.CSS_SELECTOR_COUNT}),this._addUiClass(),a.each(this.options.cssSelector,function(a,b){c._cssSelector(a,b)}),this._updateInterface(),this._updateButtons(),this._updateAutohide(),this._updateVolume(),this._updateMute()},_cssSelector:function(b,c){var d=this;if("string"==typeof c)if(a.jPlayer.prototype.options.cssSelector[b]){if(this.css.jq[b]&&this.css.jq[b].length&&this.css.jq[b].unbind(".jPlayer"),this.options.cssSelector[b]=c,this.css.cs[b]=this.options.cssSelectorAncestor+" "+c,this.css.jq[b]=c?a(this.css.cs[b]):[],this.css.jq[b].length&&this[b]){var e=function(c){c.preventDefault(),d[b](c),d.options.autoBlur?a(this).blur():a(this).focus()};this.css.jq[b].bind("click.jPlayer",e)}c&&1!==this.css.jq[b].length&&this._warning({type:a.jPlayer.warning.CSS_SELECTOR_COUNT,context:this.css.cs[b],message:a.jPlayer.warningMsg.CSS_SELECTOR_COUNT+this.css.jq[b].length+" found for "+b+" method.",hint:a.jPlayer.warningHint.CSS_SELECTOR_COUNT})}else this._warning({type:a.jPlayer.warning.CSS_SELECTOR_METHOD,context:b,message:a.jPlayer.warningMsg.CSS_SELECTOR_METHOD,hint:a.jPlayer.warningHint.CSS_SELECTOR_METHOD});else this._warning({type:a.jPlayer.warning.CSS_SELECTOR_STRING,context:c,message:a.jPlayer.warningMsg.CSS_SELECTOR_STRING,hint:a.jPlayer.warningHint.CSS_SELECTOR_STRING})},duration:function(a){this.options.toggleDuration&&(this.options.captureDuration&&a.stopPropagation(),this._setOption("remainingDuration",!this.options.remainingDuration))},seekBar:function(b){if(this.css.jq.seekBar.length){var c=a(b.currentTarget),d=c.offset(),e=b.pageX-d.left,f=c.width(),g=100*e/f;this.playHead(g)}},playbackRate:function(a){this._setOption("playbackRate",a)},playbackRateBar:function(b){if(this.css.jq.playbackRateBar.length){var c,d,e=a(b.currentTarget),f=e.offset(),g=b.pageX-f.left,h=e.width(),i=e.height()-b.pageY+f.top,j=e.height();c=this.options.verticalPlaybackRate?i/j:g/h,d=c*(this.options.maxPlaybackRate-this.options.minPlaybackRate)+this.options.minPlaybackRate,this.playbackRate(d)}},_updatePlaybackRate:function(){var a=this.options.playbackRate,b=(a-this.options.minPlaybackRate)/(this.options.maxPlaybackRate-this.options.minPlaybackRate);this.status.playbackRateEnabled?(this.css.jq.playbackRateBar.length&&this.css.jq.playbackRateBar.show(),this.css.jq.playbackRateBarValue.length&&(this.css.jq.playbackRateBarValue.show(),this.css.jq.playbackRateBarValue[this.options.verticalPlaybackRate?"height":"width"](100*b+"%"))):(this.css.jq.playbackRateBar.length&&this.css.jq.playbackRateBar.hide(),this.css.jq.playbackRateBarValue.length&&this.css.jq.playbackRateBarValue.hide())},repeat:function(a){var b="object"==typeof a;this._loop(b&&this.options.useStateClassSkin&&this.options.loop?!1:!0)},repeatOff:function(){this._loop(!1)},_loop:function(b){this.options.loop!==b&&(this.options.loop=b,this._updateButtons(),this._trigger(a.jPlayer.event.repeat))},option:function(c,d){var e=c;if(0===arguments.length)return a.extend(!0,{},this.options);if("string"==typeof c){var f=c.split(".");if(d===b){for(var g=a.extend(!0,{},this.options),h=0;h<f.length;h++){if(g[f[h]]===b)return this._warning({type:a.jPlayer.warning.OPTION_KEY,context:c,message:a.jPlayer.warningMsg.OPTION_KEY,hint:a.jPlayer.warningHint.OPTION_KEY}),b;g=g[f[h]]}return g}e={};for(var i=e,j=0;j<f.length;j++)j<f.length-1?(i[f[j]]={},i=i[f[j]]):i[f[j]]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(b,c){var d=this;switch(b){case"volume":this.volume(c);break;case"muted":this._muted(c);break;case"globalVolume":this.options[b]=c;break;case"cssSelectorAncestor":this._cssSelectorAncestor(c);break;case"cssSelector":a.each(c,function(a,b){d._cssSelector(a,b)});break;case"playbackRate":this.options[b]=c=this._limitValue(c,this.options.minPlaybackRate,this.options.maxPlaybackRate),this.html.used&&this._html_setProperty("playbackRate",c),this._updatePlaybackRate();break;case"defaultPlaybackRate":this.options[b]=c=this._limitValue(c,this.options.minPlaybackRate,this.options.maxPlaybackRate),this.html.used&&this._html_setProperty("defaultPlaybackRate",c),this._updatePlaybackRate();break;case"minPlaybackRate":this.options[b]=c=this._limitValue(c,.1,this.options.maxPlaybackRate-.1),this._updatePlaybackRate();break;case"maxPlaybackRate":this.options[b]=c=this._limitValue(c,this.options.minPlaybackRate+.1,16),this._updatePlaybackRate();break;case"fullScreen":if(this.options[b]!==c){var e=a.jPlayer.nativeFeatures.fullscreen.used.webkitVideo;(!e||e&&!this.status.waitForPlay)&&(e||(this.options[b]=c),c?this._requestFullscreen():this._exitFullscreen(),e||this._setOption("fullWindow",c))}break;case"fullWindow":this.options[b]!==c&&(this._removeUiClass(),this.options[b]=c,this._refreshSize());break;case"size":this.options.fullWindow||this.options[b].cssClass===c.cssClass||this._removeUiClass(),this.options[b]=a.extend({},this.options[b],c),this._refreshSize();break;case"sizeFull":this.options.fullWindow&&this.options[b].cssClass!==c.cssClass&&this._removeUiClass(),this.options[b]=a.extend({},this.options[b],c),this._refreshSize();break;case"autohide":this.options[b]=a.extend({},this.options[b],c),this._updateAutohide();break;case"loop":this._loop(c);break;case"remainingDuration":this.options[b]=c,this._updateInterface();break;case"toggleDuration":this.options[b]=c;break;case"nativeVideoControls":this.options[b]=a.extend({},this.options[b],c),this.status.nativeVideoControls=this._uaBlocklist(this.options.nativeVideoControls),this._restrictNativeVideoControls(),this._updateNativeVideoControls();break;case"noFullWindow":this.options[b]=a.extend({},this.options[b],c),this.status.nativeVideoControls=this._uaBlocklist(this.options.nativeVideoControls),this.status.noFullWindow=this._uaBlocklist(this.options.noFullWindow),this._restrictNativeVideoControls(),this._updateButtons();break;case"noVolume":this.options[b]=a.extend({},this.options[b],c),this.status.noVolume=this._uaBlocklist(this.options.noVolume),this._updateVolume(),this._updateMute();break;case"emulateHtml":this.options[b]!==c&&(this.options[b]=c,c?this._emulateHtmlBridge():this._destroyHtmlBridge());break;case"timeFormat":this.options[b]=a.extend({},this.options[b],c);break;case"keyEnabled":this.options[b]=c,c||this!==a.jPlayer.focus||(a.jPlayer.focus=null);break;case"keyBindings":this.options[b]=a.extend(!0,{},this.options[b],c);break;case"audioFullScreen":this.options[b]=c;break;case"autoBlur":this.options[b]=c}return this},_refreshSize:function(){this._setSize(),this._addUiClass(),this._updateSize(),this._updateButtons(),this._updateAutohide(),this._trigger(a.jPlayer.event.resize)},_setSize:function(){this.options.fullWindow?(this.status.width=this.options.sizeFull.width,this.status.height=this.options.sizeFull.height,this.status.cssClass=this.options.sizeFull.cssClass):(this.status.width=this.options.size.width,this.status.height=this.options.size.height,this.status.cssClass=this.options.size.cssClass),this.element.css({width:this.status.width,height:this.status.height})},_addUiClass:function(){this.ancestorJq.length&&this.ancestorJq.addClass(this.status.cssClass)},_removeUiClass:function(){this.ancestorJq.length&&this.ancestorJq.removeClass(this.status.cssClass)},_updateSize:function(){this.internal.poster.jq.css({width:this.status.width,height:this.status.height}),!this.status.waitForPlay&&this.html.active&&this.status.video||this.html.video.available&&this.html.used&&this.status.nativeVideoControls?this.internal.video.jq.css({width:this.status.width,height:this.status.height}):!this.status.waitForPlay&&this.flash.active&&this.status.video&&this.internal.flash.jq.css({width:this.status.width,height:this.status.height})},_updateAutohide:function(){var a=this,b="mousemove.jPlayer",c=".jPlayerAutohide",d=b+c,e=function(b){var c,d,e=!1;"undefined"!=typeof a.internal.mouse?(c=a.internal.mouse.x-b.pageX,d=a.internal.mouse.y-b.pageY,e=Math.floor(c)>0||Math.floor(d)>0):e=!0,a.internal.mouse={x:b.pageX,y:b.pageY},e&&a.css.jq.gui.fadeIn(a.options.autohide.fadeIn,function(){clearTimeout(a.internal.autohideId),a.internal.autohideId=setTimeout(function(){a.css.jq.gui.fadeOut(a.options.autohide.fadeOut)},a.options.autohide.hold)})};this.css.jq.gui.length&&(this.css.jq.gui.stop(!0,!0),clearTimeout(this.internal.autohideId),delete this.internal.mouse,this.element.unbind(c),this.css.jq.gui.unbind(c),this.status.nativeVideoControls?this.css.jq.gui.hide():this.options.fullWindow&&this.options.autohide.full||!this.options.fullWindow&&this.options.autohide.restored?(this.element.bind(d,e),this.css.jq.gui.bind(d,e),this.css.jq.gui.hide()):this.css.jq.gui.show())},fullScreen:function(a){var b="object"==typeof a;b&&this.options.useStateClassSkin&&this.options.fullScreen?this._setOption("fullScreen",!1):this._setOption("fullScreen",!0)},restoreScreen:function(){this._setOption("fullScreen",!1)},_fullscreenAddEventListeners:function(){var b=this,c=a.jPlayer.nativeFeatures.fullscreen;c.api.fullscreenEnabled&&c.event.fullscreenchange&&("function"!=typeof this.internal.fullscreenchangeHandler&&(this.internal.fullscreenchangeHandler=function(){b._fullscreenchange()}),document.addEventListener(c.event.fullscreenchange,this.internal.fullscreenchangeHandler,!1))},_fullscreenRemoveEventListeners:function(){var b=a.jPlayer.nativeFeatures.fullscreen;this.internal.fullscreenchangeHandler&&document.removeEventListener(b.event.fullscreenchange,this.internal.fullscreenchangeHandler,!1)},_fullscreenchange:function(){this.options.fullScreen&&!a.jPlayer.nativeFeatures.fullscreen.api.fullscreenElement()&&this._setOption("fullScreen",!1)},_requestFullscreen:function(){var b=this.ancestorJq.length?this.ancestorJq[0]:this.element[0],c=a.jPlayer.nativeFeatures.fullscreen;c.used.webkitVideo&&(b=this.htmlElement.video),c.api.fullscreenEnabled&&c.api.requestFullscreen(b)},_exitFullscreen:function(){var b,c=a.jPlayer.nativeFeatures.fullscreen;c.used.webkitVideo&&(b=this.htmlElement.video),c.api.fullscreenEnabled&&c.api.exitFullscreen(b)},_html_initMedia:function(b){var c=a(this.htmlElement.media).empty();a.each(b.track||[],function(a,b){var d=document.createElement("track");d.setAttribute("kind",b.kind?b.kind:""),d.setAttribute("src",b.src?b.src:""),d.setAttribute("srclang",b.srclang?b.srclang:""),d.setAttribute("label",b.label?b.label:""),b.def&&d.setAttribute("default",b.def),c.append(d)}),this.htmlElement.media.src=this.status.src,"none"!==this.options.preload&&this._html_load(),this._trigger(a.jPlayer.event.timeupdate)},_html_setFormat:function(b){var c=this;a.each(this.formats,function(a,d){return c.html.support[d]&&b[d]?(c.status.src=b[d],c.status.format[d]=!0,c.status.formatType=d,!1):void 0})},_html_setAudio:function(a){this._html_setFormat(a),this.htmlElement.media=this.htmlElement.audio,this._html_initMedia(a)},_html_setVideo:function(a){this._html_setFormat(a),this.status.nativeVideoControls&&(this.htmlElement.video.poster=this._validString(a.poster)?a.poster:""),this.htmlElement.media=this.htmlElement.video,this._html_initMedia(a)},_html_resetMedia:function(){this.htmlElement.media&&(this.htmlElement.media.id!==this.internal.video.id||this.status.nativeVideoControls||this.internal.video.jq.css({width:"0px",height:"0px"}),this.htmlElement.media.pause())},_html_clearMedia:function(){this.htmlElement.media&&(this.htmlElement.media.src="about:blank",this.htmlElement.media.load())},_html_load:function(){this.status.waitForLoad&&(this.status.waitForLoad=!1,this.htmlElement.media.load()),clearTimeout(this.internal.htmlDlyCmdId)},_html_play:function(a){var b=this,c=this.htmlElement.media;if(this.androidFix.pause=!1,this._html_load(),this.androidFix.setMedia)this.androidFix.play=!0,this.androidFix.time=a;else if(isNaN(a))c.play();else{this.internal.cmdsIgnored&&c.play();try{if(c.seekable&&!("object"==typeof c.seekable&&c.seekable.length>0))throw 1;c.currentTime=a,c.play()}catch(d){return void(this.internal.htmlDlyCmdId=setTimeout(function(){b.play(a)},250))}}this._html_checkWaitForPlay()},_html_pause:function(a){var b=this,c=this.htmlElement.media;if(this.androidFix.play=!1,a>0?this._html_load():clearTimeout(this.internal.htmlDlyCmdId),c.pause(),this.androidFix.setMedia)this.androidFix.pause=!0,this.androidFix.time=a;else if(!isNaN(a))try{if(c.seekable&&!("object"==typeof c.seekable&&c.seekable.length>0))throw 1;c.currentTime=a}catch(d){return void(this.internal.htmlDlyCmdId=setTimeout(function(){b.pause(a)},250))}a>0&&this._html_checkWaitForPlay()},_html_playHead:function(a){var b=this,c=this.htmlElement.media;this._html_load();try{if("object"==typeof c.seekable&&c.seekable.length>0)c.currentTime=a*c.seekable.end(c.seekable.length-1)/100;else{if(!(c.duration>0)||isNaN(c.duration))throw"e";c.currentTime=a*c.duration/100}}catch(d){return void(this.internal.htmlDlyCmdId=setTimeout(function(){b.playHead(a)},250))}this.status.waitForLoad||this._html_checkWaitForPlay()},_html_checkWaitForPlay:function(){this.status.waitForPlay&&(this.status.waitForPlay=!1,this.css.jq.videoPlay.length&&this.css.jq.videoPlay.hide(),this.status.video&&(this.internal.poster.jq.hide(),this.internal.video.jq.css({width:this.status.width,height:this.status.height})))},_html_setProperty:function(a,b){this.html.audio.available&&(this.htmlElement.audio[a]=b),this.html.video.available&&(this.htmlElement.video[a]=b)},_aurora_setAudio:function(b){var c=this;a.each(this.formats,function(a,d){return c.aurora.support[d]&&b[d]?(c.status.src=b[d],c.status.format[d]=!0,c.status.formatType=d,!1):void 0}),this.aurora.player=new AV.Player.fromURL(this.status.src),this._addAuroraEventListeners(this.aurora.player,this.aurora),"auto"===this.options.preload&&(this._aurora_load(),this.status.waitForLoad=!1)},_aurora_resetMedia:function(){this.aurora.player&&this.aurora.player.stop()},_aurora_clearMedia:function(){},_aurora_load:function(){this.status.waitForLoad&&(this.status.waitForLoad=!1,this.aurora.player.preload())},_aurora_play:function(b){this.status.waitForLoad||isNaN(b)||this.aurora.player.seek(b),this.aurora.player.playing||this.aurora.player.play(),this.status.waitForLoad=!1,this._aurora_checkWaitForPlay(),this._updateButtons(!0),this._trigger(a.jPlayer.event.play)},_aurora_pause:function(b){isNaN(b)||this.aurora.player.seek(1e3*b),this.aurora.player.pause(),b>0&&this._aurora_checkWaitForPlay(),this._updateButtons(!1),this._trigger(a.jPlayer.event.pause)},_aurora_playHead:function(a){this.aurora.player.duration>0&&this.aurora.player.seek(a*this.aurora.player.duration/100),this.status.waitForLoad||this._aurora_checkWaitForPlay()},_aurora_checkWaitForPlay:function(){this.status.waitForPlay&&(this.status.waitForPlay=!1)},_aurora_volume:function(a){this.aurora.player.volume=100*a},_aurora_mute:function(a){a?(this.aurora.properties.lastvolume=this.aurora.player.volume,this.aurora.player.volume=0):this.aurora.player.volume=this.aurora.properties.lastvolume,this.aurora.properties.muted=a},_flash_setAudio:function(b){var c=this;try{a.each(this.formats,function(a,d){if(c.flash.support[d]&&b[d]){switch(d){case"m4a":case"fla":c._getMovie().fl_setAudio_m4a(b[d]);break;case"mp3":c._getMovie().fl_setAudio_mp3(b[d]);break;case"rtmpa":c._getMovie().fl_setAudio_rtmp(b[d])}return c.status.src=b[d],c.status.format[d]=!0,c.status.formatType=d,!1}}),"auto"===this.options.preload&&(this._flash_load(),this.status.waitForLoad=!1)}catch(d){this._flashError(d)}},_flash_setVideo:function(b){var c=this;try{a.each(this.formats,function(a,d){if(c.flash.support[d]&&b[d]){switch(d){case"m4v":case"flv":c._getMovie().fl_setVideo_m4v(b[d]);break;case"rtmpv":c._getMovie().fl_setVideo_rtmp(b[d])}return c.status.src=b[d],c.status.format[d]=!0,c.status.formatType=d,!1}}),"auto"===this.options.preload&&(this._flash_load(),this.status.waitForLoad=!1)}catch(d){this._flashError(d)}},_flash_resetMedia:function(){this.internal.flash.jq.css({width:"0px",height:"0px"}),this._flash_pause(0/0)},_flash_clearMedia:function(){try{this._getMovie().fl_clearMedia()}catch(a){this._flashError(a)}},_flash_load:function(){try{this._getMovie().fl_load()}catch(a){this._flashError(a)}this.status.waitForLoad=!1},_flash_play:function(a){try{this._getMovie().fl_play(a)}catch(b){this._flashError(b)}this.status.waitForLoad=!1,this._flash_checkWaitForPlay()},_flash_pause:function(a){try{this._getMovie().fl_pause(a)}catch(b){this._flashError(b)}a>0&&(this.status.waitForLoad=!1,this._flash_checkWaitForPlay())},_flash_playHead:function(a){try{this._getMovie().fl_play_head(a)}catch(b){this._flashError(b)}this.status.waitForLoad||this._flash_checkWaitForPlay()},_flash_checkWaitForPlay:function(){this.status.waitForPlay&&(this.status.waitForPlay=!1,this.css.jq.videoPlay.length&&this.css.jq.videoPlay.hide(),this.status.video&&(this.internal.poster.jq.hide(),this.internal.flash.jq.css({width:this.status.width,height:this.status.height})))},_flash_volume:function(a){try{this._getMovie().fl_volume(a)}catch(b){this._flashError(b)}},_flash_mute:function(a){try{this._getMovie().fl_mute(a)}catch(b){this._flashError(b)}},_getMovie:function(){return document[this.internal.flash.id]},_getFlashPluginVersion:function(){var a,b=0;if(window.ActiveXObject)try{if(a=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")){var c=a.GetVariable("$version");c&&(c=c.split(" ")[1].split(","),b=parseInt(c[0],10)+"."+parseInt(c[1],10))}}catch(d){}else navigator.plugins&&navigator.mimeTypes.length>0&&(a=navigator.plugins["Shockwave Flash"],a&&(b=navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/,"$1")));return 1*b},_checkForFlash:function(a){var b=!1;return this._getFlashPluginVersion()>=a&&(b=!0),b},_validString:function(a){return a&&"string"==typeof a},_limitValue:function(a,b,c){return b>a?b:a>c?c:a},_urlNotSetError:function(b){this._error({type:a.jPlayer.error.URL_NOT_SET,context:b,message:a.jPlayer.errorMsg.URL_NOT_SET,hint:a.jPlayer.errorHint.URL_NOT_SET})},_flashError:function(b){var c;c=this.internal.ready?"FLASH_DISABLED":"FLASH",this._error({type:a.jPlayer.error[c],context:this.internal.flash.swf,message:a.jPlayer.errorMsg[c]+b.message,hint:a.jPlayer.errorHint[c]}),this.internal.flash.jq.css({width:"1px",height:"1px"})},_error:function(b){this._trigger(a.jPlayer.event.error,b),this.options.errorAlerts&&this._alert("Error!"+(b.message?"\n"+b.message:"")+(b.hint?"\n"+b.hint:"")+"\nContext: "+b.context)},_warning:function(c){this._trigger(a.jPlayer.event.warning,b,c),this.options.warningAlerts&&this._alert("Warning!"+(c.message?"\n"+c.message:"")+(c.hint?"\n"+c.hint:"")+"\nContext: "+c.context)},_alert:function(a){var b="jPlayer "+this.version.script+" : id='"+this.internal.self.id+"' : "+a;this.options.consoleAlerts?window.console&&window.console.log&&window.console.log(b):alert(b)},_emulateHtmlBridge:function(){var b=this;a.each(a.jPlayer.emulateMethods.split(/\s+/g),function(a,c){b.internal.domNode[c]=function(a){b[c](a)}}),a.each(a.jPlayer.event,function(c,d){var e=!0;a.each(a.jPlayer.reservedEvent.split(/\s+/g),function(a,b){return b===c?(e=!1,!1):void 0}),e&&b.element.bind(d+".jPlayer.jPlayerHtml",function(){b._emulateHtmlUpdate();var a=document.createEvent("Event");a.initEvent(c,!1,!0),b.internal.domNode.dispatchEvent(a)})})},_emulateHtmlUpdate:function(){var b=this;a.each(a.jPlayer.emulateStatus.split(/\s+/g),function(a,c){b.internal.domNode[c]=b.status[c]}),a.each(a.jPlayer.emulateOptions.split(/\s+/g),function(a,c){b.internal.domNode[c]=b.options[c]})},_destroyHtmlBridge:function(){var b=this;this.element.unbind(".jPlayerHtml");var c=a.jPlayer.emulateMethods+" "+a.jPlayer.emulateStatus+" "+a.jPlayer.emulateOptions;a.each(c.split(/\s+/g),function(a,c){delete b.internal.domNode[c]})}},a.jPlayer.error={FLASH:"e_flash",FLASH_DISABLED:"e_flash_disabled",NO_SOLUTION:"e_no_solution",NO_SUPPORT:"e_no_support",URL:"e_url",URL_NOT_SET:"e_url_not_set",VERSION:"e_version"},a.jPlayer.errorMsg={FLASH:"jPlayer's Flash fallback is not configured correctly, or a command was issued before the jPlayer Ready event. Details: ",FLASH_DISABLED:"jPlayer's Flash fallback has been disabled by the browser due to the CSS rules you have used. Details: ",NO_SOLUTION:"No solution can be found by jPlayer in this browser. Neither HTML nor Flash can be used.",NO_SUPPORT:"It is not possible to play any media format provided in setMedia() on this browser using your current options.",URL:"Media URL could not be loaded.",URL_NOT_SET:"Attempt to issue media playback commands, while no media url is set.",VERSION:"jPlayer "+a.jPlayer.prototype.version.script+" needs Jplayer.swf version "+a.jPlayer.prototype.version.needFlash+" but found "},a.jPlayer.errorHint={FLASH:"Check your swfPath option and that Jplayer.swf is there.",FLASH_DISABLED:"Check that you have not display:none; the jPlayer entity or any ancestor.",NO_SOLUTION:"Review the jPlayer options: support and supplied.",NO_SUPPORT:"Video or audio formats defined in the supplied option are missing.",URL:"Check media URL is valid.",URL_NOT_SET:"Use setMedia() to set the media URL.",VERSION:"Update jPlayer files."},a.jPlayer.warning={CSS_SELECTOR_COUNT:"e_css_selector_count",CSS_SELECTOR_METHOD:"e_css_selector_method",CSS_SELECTOR_STRING:"e_css_selector_string",OPTION_KEY:"e_option_key"},a.jPlayer.warningMsg={CSS_SELECTOR_COUNT:"The number of css selectors found did not equal one: ",CSS_SELECTOR_METHOD:"The methodName given in jPlayer('cssSelector') is not a valid jPlayer method.",CSS_SELECTOR_STRING:"The methodCssSelector given in jPlayer('cssSelector') is not a String or is empty.",OPTION_KEY:"The option requested in jPlayer('option') is undefined."},a.jPlayer.warningHint={CSS_SELECTOR_COUNT:"Check your css selector and the ancestor.",CSS_SELECTOR_METHOD:"Check your method name.",CSS_SELECTOR_STRING:"Check your css selector is a string.",OPTION_KEY:"Check your option name."}});"use strict";jQuery.base64=(function($){var _PADCHAR="=",_ALPHA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_VERSION="1.0";function _getbyte64(s,i){var idx=_ALPHA.indexOf(s.charAt(i));if(idx===-1){throw"Cannot decode base64"}return idx}function _decode(s){var pads=0,i,b10,imax=s.length,x=[];s=String(s);if(imax===0){return s}if(imax%4!==0){throw"Cannot decode base64"}if(s.charAt(imax-1)===_PADCHAR){pads=1;if(s.charAt(imax-2)===_PADCHAR){pads=2}imax-=4}for(i=0;i<imax;i+=4){b10=(_getbyte64(s,i)<<18)|(_getbyte64(s,i+1)<<12)|(_getbyte64(s,i+2)<<6)|_getbyte64(s,i+3);x.push(String.fromCharCode(b10>>16,(b10>>8)&255,b10&255))}switch(pads){case 1:b10=(_getbyte64(s,i)<<18)|(_getbyte64(s,i+1)<<12)|(_getbyte64(s,i+2)<<6);x.push(String.fromCharCode(b10>>16,(b10>>8)&255));break;case 2:b10=(_getbyte64(s,i)<<18)|(_getbyte64(s,i+1)<<12);x.push(String.fromCharCode(b10>>16));break}return x.join("")}function _getbyte(s,i){var x=s.charCodeAt(i);if(x>255){throw"INVALID_CHARACTER_ERR: DOM Exception 5"}return x}function _encode(s){if(arguments.length!==1){throw"SyntaxError: exactly one argument required"}s=String(s);var i,b10,x=[],imax=s.length-s.length%3;if(s.length===0){return s}for(i=0;i<imax;i+=3){b10=(_getbyte(s,i)<<16)|(_getbyte(s,i+1)<<8)|_getbyte(s,i+2);x.push(_ALPHA.charAt(b10>>18));x.push(_ALPHA.charAt((b10>>12)&63));x.push(_ALPHA.charAt((b10>>6)&63));x.push(_ALPHA.charAt(b10&63))}switch(s.length-imax){case 1:b10=_getbyte(s,i)<<16;x.push(_ALPHA.charAt(b10>>18)+_ALPHA.charAt((b10>>12)&63)+_PADCHAR+_PADCHAR);break;case 2:b10=(_getbyte(s,i)<<16)|(_getbyte(s,i+1)<<8);x.push(_ALPHA.charAt(b10>>18)+_ALPHA.charAt((b10>>12)&63)+_ALPHA.charAt((b10>>6)&63)+_PADCHAR);break}return x.join("")}return{decode:_decode,encode:_encode,VERSION:_VERSION}}(jQuery));/*!
 * jQuery Browser Plugin 0.1.0
 * https://github.com/gabceb/jquery-browser-plugin
 *
 * Original jquery-browser code Copyright 2005, 2015 jQuery Foundation, Inc. and other contributors
 * http://jquery.org/license
 *
 * Modifications Copyright 2015 Gabriel Cebrian
 * https://github.com/gabceb
 *
 * Released under the MIT license
 *
 * Date: 23-11-2015
 */!function(a){"function"==typeof define&&define.amd?define(["jquery"],function(b){return a(b)}):"object"==typeof module&&"object"==typeof module.exports?module.exports=a(require("jquery")):a(window.jQuery)}(function(a){"use strict";function b(a){void 0===a&&(a=window.navigator.userAgent),a=a.toLowerCase();var b=/(edge)\/([\w.]+)/.exec(a)||/(opr)[\/]([\w.]+)/.exec(a)||/(chrome)[ \/]([\w.]+)/.exec(a)||/(iemobile)[\/]([\w.]+)/.exec(a)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[],c=/(ipad)/.exec(a)||/(ipod)/.exec(a)||/(windows phone)/.exec(a)||/(iphone)/.exec(a)||/(kindle)/.exec(a)||/(silk)/.exec(a)||/(android)/.exec(a)||/(win)/.exec(a)||/(mac)/.exec(a)||/(linux)/.exec(a)||/(cros)/.exec(a)||/(playbook)/.exec(a)||/(bb)/.exec(a)||/(blackberry)/.exec(a)||[],d={},e={browser:b[5]||b[3]||b[1]||"",version:b[2]||b[4]||"0",versionNumber:b[4]||b[2]||"0",platform:c[0]||""};if(e.browser&&(d[e.browser]=!0,d.version=e.version,d.versionNumber=parseInt(e.versionNumber,10)),e.platform&&(d[e.platform]=!0),(d.android||d.bb||d.blackberry||d.ipad||d.iphone||d.ipod||d.kindle||d.playbook||d.silk||d["windows phone"])&&(d.mobile=!0),(d.cros||d.mac||d.linux||d.win)&&(d.desktop=!0),(d.chrome||d.opr||d.safari)&&(d.webkit=!0),d.rv||d.iemobile){var f="msie";e.browser=f,d[f]=!0}if(d.edge){delete d.edge;var g="msedge";e.browser=g,d[g]=!0}if(d.safari&&d.blackberry){var h="blackberry";e.browser=h,d[h]=!0}if(d.safari&&d.playbook){var i="playbook";e.browser=i,d[i]=!0}if(d.bb){var j="blackberry";e.browser=j,d[j]=!0}if(d.opr){var k="opera";e.browser=k,d[k]=!0}if(d.safari&&d.android){var l="android";e.browser=l,d[l]=!0}if(d.safari&&d.kindle){var m="kindle";e.browser=m,d[m]=!0}if(d.safari&&d.silk){var n="silk";e.browser=n,d[n]=!0}return d.name=e.browser,d.platform=e.platform,d}return window.jQBrowser=b(window.navigator.userAgent),window.jQBrowser.uaMatch=b,a&&(a.browser=window.jQBrowser),window.jQBrowser});/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);/*! 
 * jquery.event.drag - v 2.2
 * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com
 * Open Source MIT License - http://threedubmedia.com/code/license
 */
// Created: 2008-06-04 
// Updated: 2012-05-21
// REQUIRES: jquery 1.7.x

;(function( $ ){

// add the jquery instance method
$.fn.drag = function( str, arg, opts ){
	// figure out the event type
	var type = typeof str == "string" ? str : "",
	// figure out the event handler...
	fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null;
	// fix the event type
	if ( type.indexOf("drag") !== 0 ) 
		type = "drag"+ type;
	// were options passed
	opts = ( str == fn ? arg : opts ) || {};
	// trigger or bind event handler
	return fn ? this.bind( type, opts, fn ) : this.trigger( type );
};

// local refs (increase compression)
var $event = $.event, 
$special = $event.special,
// configure the drag special event 
drag = $special.drag = {
	
	// these are the default settings
	defaults: {
		which: 1, // mouse button pressed to start drag sequence
		distance: 0, // distance dragged before dragstart
		not: ':input', // selector to suppress dragging on target elements
		handle: null, // selector to match handle target elements
		relative: false, // true to use "position", false to use "offset"
		drop: true, // false to suppress drop events, true or selector to allow
		click: false // false to suppress click events after dragend (no proxy)
	},
	
	// the key name for stored drag data
	datakey: "dragdata",
	
	// prevent bubbling for better performance
	noBubble: true,
	
	// count bound related events
	add: function( obj ){ 
		// read the interaction data
		var data = $.data( this, drag.datakey ),
		// read any passed options 
		opts = obj.data || {};
		// count another realted event
		data.related += 1;
		// extend data options bound with this event
		// don't iterate "opts" in case it is a node 
		$.each( drag.defaults, function( key, def ){
			if ( opts[ key ] !== undefined )
				data[ key ] = opts[ key ];
		});
	},
	
	// forget unbound related events
	remove: function(){
		$.data( this, drag.datakey ).related -= 1;
	},
	
	// configure interaction, capture settings
	setup: function(){
		// check for related events
		if ( $.data( this, drag.datakey ) ) 
			return;
		// initialize the drag data with copied defaults
		var data = $.extend({ related:0 }, drag.defaults );
		// store the interaction data
		$.data( this, drag.datakey, data );
		// bind the mousedown event, which starts drag interactions
		$event.add( this, "touchstart mousedown", drag.init, data );
		// prevent image dragging in IE...
		if ( this.attachEvent ) 
			this.attachEvent("ondragstart", drag.dontstart ); 
	},
	
	// destroy configured interaction
	teardown: function(){
		var data = $.data( this, drag.datakey ) || {};
		// check for related events
		if ( data.related ) 
			return;
		// remove the stored data
		$.removeData( this, drag.datakey );
		// remove the mousedown event
		$event.remove( this, "touchstart mousedown", drag.init );
		// enable text selection
		drag.textselect( true ); 
		// un-prevent image dragging in IE...
		if ( this.detachEvent ) 
			this.detachEvent("ondragstart", drag.dontstart ); 
	},
		
	// initialize the interaction
	init: function( event ){ 
		// sorry, only one touch at a time
		if ( drag.touched ) 
			return;
		// the drag/drop interaction data
		var dd = event.data, results;
		// check the which directive
		if ( event.which != 0 && dd.which > 0 && event.which != dd.which ) 
			return; 
		// check for suppressed selector
		if ( $( event.target ).is( dd.not ) ) 
			return;
		// check for handle selector
		if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length ) 
			return;

		drag.touched = event.type == 'touchstart' ? this : null;
		dd.propagates = 1;
		dd.mousedown = this;
		dd.interactions = [ drag.interaction( this, dd ) ];
		dd.target = event.target;
		dd.pageX = event.pageX;
		dd.pageY = event.pageY;
		dd.dragging = null;
		// handle draginit event... 
		results = drag.hijack( event, "draginit", dd );
		// early cancel
		if ( !dd.propagates )
			return;
		// flatten the result set
		results = drag.flatten( results );
		// insert new interaction elements
		if ( results && results.length ){
			dd.interactions = [];
			$.each( results, function(){
				dd.interactions.push( drag.interaction( this, dd ) );
			});
		}
		// remember how many interactions are propagating
		dd.propagates = dd.interactions.length;
		// locate and init the drop targets
		if ( dd.drop !== false && $special.drop ) 
			$special.drop.handler( event, dd );
		// disable text selection
		drag.textselect( false ); 
		// bind additional events...
		if ( drag.touched )
			$event.add( drag.touched, "touchmove touchend", drag.handler, dd );
		else 
			$event.add( document, "mousemove mouseup", drag.handler, dd );
		// helps prevent text selection or scrolling
		if ( !drag.touched || dd.live )
			return false;
	},	
	
	// returns an interaction object
	interaction: function( elem, dd ){
		var offset = $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 };
		return {
			drag: elem, 
			callback: new drag.callback(), 
			droppable: [],
			offset: offset
		};
	},
	
	// handle drag-releatd DOM events
	handler: function( event ){ 
		// read the data before hijacking anything
		var dd = event.data;	
		// handle various events
		switch ( event.type ){
			// mousemove, check distance, start dragging
			case !dd.dragging && 'touchmove': 
				event.preventDefault();
			case !dd.dragging && 'mousemove':
				//  drag tolerance, x² + y² = distance²
				if ( Math.pow(  event.pageX-dd.pageX, 2 ) + Math.pow(  event.pageY-dd.pageY, 2 ) < Math.pow( dd.distance, 2 ) ) 
					break; // distance tolerance not reached
				event.target = dd.target; // force target from "mousedown" event (fix distance issue)
				drag.hijack( event, "dragstart", dd ); // trigger "dragstart"
				if ( dd.propagates ) // "dragstart" not rejected
					dd.dragging = true; // activate interaction
			// mousemove, dragging
			case 'touchmove':
				event.preventDefault();
			case 'mousemove':
				if ( dd.dragging ){
					// trigger "drag"		
					drag.hijack( event, "drag", dd );
					if ( dd.propagates ){
						// manage drop events
						if ( dd.drop !== false && $special.drop )
							$special.drop.handler( event, dd ); // "dropstart", "dropend"							
						break; // "drag" not rejected, stop		
					}
					event.type = "mouseup"; // helps "drop" handler behave
				}
			// mouseup, stop dragging
			case 'touchend': 
			case 'mouseup': 
			default:
				if ( drag.touched )
					$event.remove( drag.touched, "touchmove touchend", drag.handler ); // remove touch events
				else 
					$event.remove( document, "mousemove mouseup", drag.handler ); // remove page events	
				if ( dd.dragging ){
					if ( dd.drop !== false && $special.drop )
						$special.drop.handler( event, dd ); // "drop"
					drag.hijack( event, "dragend", dd ); // trigger "dragend"	
				}
				drag.textselect( true ); // enable text selection
				// if suppressing click events...
				if ( dd.click === false && dd.dragging )
					$.data( dd.mousedown, "suppress.click", new Date().getTime() + 5 );
				dd.dragging = drag.touched = false; // deactivate element	
				break;
		}
	},
		
	// re-use event object for custom events
	hijack: function( event, type, dd, x, elem ){
		// not configured
		if ( !dd ) 
			return;
		// remember the original event and type
		var orig = { event:event.originalEvent, type:event.type },
		// is the event drag related or drog related?
		mode = type.indexOf("drop") ? "drag" : "drop",
		// iteration vars
		result, i = x || 0, ia, $elems, callback,
		len = !isNaN( x ) ? x : dd.interactions.length;
		// modify the event type
		event.type = type;
		// remove the original event
		event.originalEvent = null;
		// initialize the results
		dd.results = [];
		// handle each interacted element
		do if ( ia = dd.interactions[ i ] ){
			// validate the interaction
			if ( type !== "dragend" && ia.cancelled )
				continue;
			// set the dragdrop properties on the event object
			callback = drag.properties( event, dd, ia );
			// prepare for more results
			ia.results = [];
			// handle each element
			$( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){
				// identify drag or drop targets individually
				callback.target = subject;
				// force propagtion of the custom event
				event.isPropagationStopped = function(){ return false; };
				// handle the event	
				result = subject ? $event.dispatch.call( subject, event, callback ) : null;
				// stop the drag interaction for this element
				if ( result === false ){
					if ( mode == "drag" ){
						ia.cancelled = true;
						dd.propagates -= 1;
					}
					if ( type == "drop" ){
						ia[ mode ][p] = null;
					}
				}
				// assign any dropinit elements
				else if ( type == "dropinit" )
					ia.droppable.push( drag.element( result ) || subject );
				// accept a returned proxy element 
				if ( type == "dragstart" )
					ia.proxy = $( drag.element( result ) || ia.drag )[0];
				// remember this result	
				ia.results.push( result );
				// forget the event result, for recycling
				delete event.result;
				// break on cancelled handler
				if ( type !== "dropinit" )
					return result;
			});	
			// flatten the results	
			dd.results[ i ] = drag.flatten( ia.results );	
			// accept a set of valid drop targets
			if ( type == "dropinit" )
				ia.droppable = drag.flatten( ia.droppable );
			// locate drop targets
			if ( type == "dragstart" && !ia.cancelled )
				callback.update(); 
		}
		while ( ++i < len )
		// restore the original event & type
		event.type = orig.type;
		event.originalEvent = orig.event;
		// return all handler results
		return drag.flatten( dd.results );
	},
		
	// extend the callback object with drag/drop properties...
	properties: function( event, dd, ia ){		
		var obj = ia.callback;
		// elements
		obj.drag = ia.drag;
		obj.proxy = ia.proxy || ia.drag;
		// starting mouse position
		obj.startX = dd.pageX;
		obj.startY = dd.pageY;
		// current distance dragged
		obj.deltaX = event.pageX - dd.pageX;
		obj.deltaY = event.pageY - dd.pageY;
		// original element position
		obj.originalX = ia.offset.left;
		obj.originalY = ia.offset.top;
		// adjusted element position
		obj.offsetX = obj.originalX + obj.deltaX; 
		obj.offsetY = obj.originalY + obj.deltaY;
		// assign the drop targets information
		obj.drop = drag.flatten( ( ia.drop || [] ).slice() );
		obj.available = drag.flatten( ( ia.droppable || [] ).slice() );
		return obj;	
	},
	
	// determine is the argument is an element or jquery instance
	element: function( arg ){
		if ( arg && ( arg.jquery || arg.nodeType == 1 ) )
			return arg;
	},
	
	// flatten nested jquery objects and arrays into a single dimension array
	flatten: function( arr ){
		return $.map( arr, function( member ){
			return member && member.jquery ? $.makeArray( member ) : 
				member && member.length ? drag.flatten( member ) : member;
		});
	},
	
	// toggles text selection attributes ON (true) or OFF (false)
	textselect: function( bool ){ 
		$( document )[ bool ? "unbind" : "bind" ]("selectstart", drag.dontstart )
			.css("MozUserSelect", bool ? "" : "none" );
		// .attr("unselectable", bool ? "off" : "on" )
		document.unselectable = bool ? "off" : "on"; 
	},
	
	// suppress "selectstart" and "ondragstart" events
	dontstart: function(){ 
		return false; 
	},
	
	// a callback instance contructor
	callback: function(){}
	
};

// callback methods
drag.callback.prototype = {
	update: function(){
		if ( $special.drop && this.available.length )
			$.each( this.available, function( i ){
				$special.drop.locate( this, i );
			});
	}
};

// patch $.event.$dispatch to allow suppressing clicks
var $dispatch = $event.dispatch;
$event.dispatch = function( event ){
	if ( $.data( this, "suppress."+ event.type ) - new Date().getTime() > 0 ){
		$.removeData( this, "suppress."+ event.type );
		return;
	}
	return $dispatch.apply( this, arguments );
};

// event fix hooks for touch events...
var touchHooks = 
$event.fixHooks.touchstart = 
$event.fixHooks.touchmove = 
$event.fixHooks.touchend =
$event.fixHooks.touchcancel = {
	props: "clientX clientY pageX pageY screenX screenY".split( " " ),
	filter: function( event, orig ) {
		if ( orig ){
			var touched = ( orig.touches && orig.touches[0] )
				|| ( orig.changedTouches && orig.changedTouches[0] )
				|| null; 
			// iOS webkit: touchstart, touchmove, touchend
			if ( touched ) 
				$.each( touchHooks.props, function( i, prop ){
					event[ prop ] = touched[ prop ];
				});
		}
		return event;
	}
};

// share the same special event configuration with related events...
$special.draginit = $special.dragstart = $special.dragend = drag;

})( jQuery );/*! jPlayerPlaylist for jPlayer 2.9.2 ~ (c) 2009-2014 Happyworm Ltd ~ MIT License */
!function(a,b){jPlayerPlaylist=function(b,c,d){var e=this;this.current=0,this.loop=!1,this.shuffled=!1,this.removing=!1,this.cssSelector=a.extend({},this._cssSelector,b),this.options=a.extend(!0,{keyBindings:{next:{key:221,fn:function(){e.next()}},previous:{key:219,fn:function(){e.previous()}},shuffle:{key:83,fn:function(){e.shuffle()}}},stateClass:{shuffled:"jp-state-shuffled"}},this._options,d),this.playlist=[],this.original=[],this._initPlaylist(c),this.cssSelector.details=this.cssSelector.cssSelectorAncestor+" .jp-details",this.cssSelector.playlist=this.cssSelector.cssSelectorAncestor+" .jp-playlist",this.cssSelector.next=this.cssSelector.cssSelectorAncestor+" .jp-next",this.cssSelector.previous=this.cssSelector.cssSelectorAncestor+" .jp-previous",this.cssSelector.shuffle=this.cssSelector.cssSelectorAncestor+" .jp-shuffle",this.cssSelector.shuffleOff=this.cssSelector.cssSelectorAncestor+" .jp-shuffle-off",this.options.cssSelectorAncestor=this.cssSelector.cssSelectorAncestor,this.options.repeat=function(a){e.loop=a.jPlayer.options.loop},a(this.cssSelector.jPlayer).bind(a.jPlayer.event.ready,function(){e._init()}),a(this.cssSelector.jPlayer).bind(a.jPlayer.event.ended,function(){e.next()}),a(this.cssSelector.jPlayer).bind(a.jPlayer.event.play,function(){a(this).jPlayer("pauseOthers")}),a(this.cssSelector.jPlayer).bind(a.jPlayer.event.resize,function(b){b.jPlayer.options.fullScreen?a(e.cssSelector.details).show():a(e.cssSelector.details).hide()}),a(this.cssSelector.previous).click(function(a){a.preventDefault(),e.previous(),e.blur(this)}),a(this.cssSelector.next).click(function(a){a.preventDefault(),e.next(),e.blur(this)}),a(this.cssSelector.shuffle).click(function(b){b.preventDefault(),e.shuffle(e.shuffled&&a(e.cssSelector.jPlayer).jPlayer("option","useStateClassSkin")?!1:!0),e.blur(this)}),a(this.cssSelector.shuffleOff).click(function(a){a.preventDefault(),e.shuffle(!1),e.blur(this)}).hide(),this.options.fullScreen||a(this.cssSelector.details).hide(),a(this.cssSelector.playlist+" ul").empty(),this._createItemHandlers(),a(this.cssSelector.jPlayer).jPlayer(this.options)},jPlayerPlaylist.prototype={_cssSelector:{jPlayer:"#jquery_jplayer_1",cssSelectorAncestor:"#jp_container_1"},_options:{playlistOptions:{autoPlay:!1,loopOnPrevious:!1,shuffleOnLoop:!0,enableRemoveControls:!1,displayTime:"slow",addTime:"fast",removeTime:"fast",shuffleTime:"slow",itemClass:"jp-playlist-item",freeGroupClass:"jp-free-media",freeItemClass:"jp-playlist-item-free",removeItemClass:"jp-playlist-item-remove"}},option:function(a,c){if(c===b)return this.options.playlistOptions[a];switch(this.options.playlistOptions[a]=c,a){case"enableRemoveControls":this._updateControls();break;case"itemClass":case"freeGroupClass":case"freeItemClass":case"removeItemClass":this._refresh(!0),this._createItemHandlers()}return this},_init:function(){var a=this;this._refresh(function(){a.options.playlistOptions.autoPlay?a.play(a.current):a.select(a.current)})},_initPlaylist:function(b){this.current=0,this.shuffled=!1,this.removing=!1,this.original=a.extend(!0,[],b),this._originalPlaylist()},_originalPlaylist:function(){var b=this;this.playlist=[],a.each(this.original,function(a){b.playlist[a]=b.original[a]})},_refresh:function(b){var c=this;if(b&&!a.isFunction(b))a(this.cssSelector.playlist+" ul").empty(),a.each(this.playlist,function(b){a(c.cssSelector.playlist+" ul").append(c._createListItem(c.playlist[b]))}),this._updateControls();else{var d=a(this.cssSelector.playlist+" ul").children().length?this.options.playlistOptions.displayTime:0;a(this.cssSelector.playlist+" ul").slideUp(d,function(){var d=a(this);a(this).empty(),a.each(c.playlist,function(a){d.append(c._createListItem(c.playlist[a]))}),c._updateControls(),a.isFunction(b)&&b(),c.playlist.length?a(this).slideDown(c.options.playlistOptions.displayTime):a(this).show()})}},_createListItem:function(b){var c=this,d="<li><div>";if(d+="<a href='javascript:;' class='"+this.options.playlistOptions.removeItemClass+"'>&times;</a>",b.free){var e=!0;d+="<span class='"+this.options.playlistOptions.freeGroupClass+"'>(",a.each(b,function(b,f){a.jPlayer.prototype.format[b]&&(e?e=!1:d+=" | ",d+="<a class='"+c.options.playlistOptions.freeItemClass+"' href='"+f+"' tabindex='-1'>"+b+"</a>")}),d+=")</span>"}return d+="<a href='javascript:;' class='"+this.options.playlistOptions.itemClass+"' tabindex='0'>"+b.title+(b.artist?" <span class='jp-artist'>by "+b.artist+"</span>":"")+"</a>",d+="</div></li>"},_createItemHandlers:function(){var b=this;a(this.cssSelector.playlist).off("click","a."+this.options.playlistOptions.itemClass).on("click","a."+this.options.playlistOptions.itemClass,function(c){c.preventDefault();var d=a(this).parent().parent().index();b.current!==d?b.play(d):a(b.cssSelector.jPlayer).jPlayer("play"),b.blur(this)}),a(this.cssSelector.playlist).off("click","a."+this.options.playlistOptions.freeItemClass).on("click","a."+this.options.playlistOptions.freeItemClass,function(c){c.preventDefault(),a(this).parent().parent().find("."+b.options.playlistOptions.itemClass).click(),b.blur(this)}),a(this.cssSelector.playlist).off("click","a."+this.options.playlistOptions.removeItemClass).on("click","a."+this.options.playlistOptions.removeItemClass,function(c){c.preventDefault();var d=a(this).parent().parent().index();b.remove(d),b.blur(this)})},_updateControls:function(){this.options.playlistOptions.enableRemoveControls?a(this.cssSelector.playlist+" ."+this.options.playlistOptions.removeItemClass).show():a(this.cssSelector.playlist+" ."+this.options.playlistOptions.removeItemClass).hide(),this.shuffled?a(this.cssSelector.jPlayer).jPlayer("addStateClass","shuffled"):a(this.cssSelector.jPlayer).jPlayer("removeStateClass","shuffled"),a(this.cssSelector.shuffle).length&&a(this.cssSelector.shuffleOff).length&&(this.shuffled?(a(this.cssSelector.shuffleOff).show(),a(this.cssSelector.shuffle).hide()):(a(this.cssSelector.shuffleOff).hide(),a(this.cssSelector.shuffle).show()))},_highlight:function(c){this.playlist.length&&c!==b&&(a(this.cssSelector.playlist+" .jp-playlist-current").removeClass("jp-playlist-current"),a(this.cssSelector.playlist+" li:nth-child("+(c+1)+")").addClass("jp-playlist-current").find(".jp-playlist-item").addClass("jp-playlist-current"))},setPlaylist:function(a){this._initPlaylist(a),this._init()},add:function(b,c){a(this.cssSelector.playlist+" ul").append(this._createListItem(b)).find("li:last-child").hide().slideDown(this.options.playlistOptions.addTime),this._updateControls(),this.original.push(b),this.playlist.push(b),c?this.play(this.playlist.length-1):1===this.original.length&&this.select(0)},remove:function(c){var d=this;return c===b?(this._initPlaylist([]),this._refresh(function(){a(d.cssSelector.jPlayer).jPlayer("clearMedia")}),!0):this.removing?!1:(c=0>c?d.original.length+c:c,c>=0&&c<this.playlist.length&&(this.removing=!0,a(this.cssSelector.playlist+" li:nth-child("+(c+1)+")").slideUp(this.options.playlistOptions.removeTime,function(){if(a(this).remove(),d.shuffled){var b=d.playlist[c];a.each(d.original,function(a){return d.original[a]===b?(d.original.splice(a,1),!1):void 0}),d.playlist.splice(c,1)}else d.original.splice(c,1),d.playlist.splice(c,1);d.original.length?c===d.current?(d.current=c<d.original.length?d.current:d.original.length-1,d.select(d.current)):c<d.current&&d.current--:(a(d.cssSelector.jPlayer).jPlayer("clearMedia"),d.current=0,d.shuffled=!1,d._updateControls()),d.removing=!1})),!0)},select:function(b){b=0>b?this.original.length+b:b,b>=0&&b<this.playlist.length?(this.current=b,this._highlight(b),a(this.cssSelector.jPlayer).jPlayer("setMedia",this.playlist[this.current])):this.current=0},play:function(c){c=0>c?this.original.length+c:c,c>=0&&c<this.playlist.length?this.playlist.length&&(this.select(c),a(this.cssSelector.jPlayer).jPlayer("play")):c===b&&a(this.cssSelector.jPlayer).jPlayer("play")},pause:function(){a(this.cssSelector.jPlayer).jPlayer("pause")},next:function(){var a=this.current+1<this.playlist.length?this.current+1:0;this.loop?0===a&&this.shuffled&&this.options.playlistOptions.shuffleOnLoop&&this.playlist.length>1?this.shuffle(!0,!0):this.play(a):a>0&&this.play(a)},previous:function(){var a=this.current-1>=0?this.current-1:this.playlist.length-1;(this.loop&&this.options.playlistOptions.loopOnPrevious||a<this.playlist.length-1)&&this.play(a)},shuffle:function(c,d){var e=this;c===b&&(c=!this.shuffled),(c||c!==this.shuffled)&&a(this.cssSelector.playlist+" ul").slideUp(this.options.playlistOptions.shuffleTime,function(){e.shuffled=c,c?e.playlist.sort(function(){return.5-Math.random()}):e._originalPlaylist(),e._refresh(!0),d||!a(e.cssSelector.jPlayer).data("jPlayer").status.paused?e.play(0):e.select(0),a(this).slideDown(e.options.playlistOptions.shuffleTime)})},blur:function(b){a(this.cssSelector.jPlayer).jPlayer("option","autoBlur")&&a(b).blur()}}}(jQuery);/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.1.3
 *
 * Requires: 1.2.2+
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
    var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
    var lowestDelta, lowestDeltaXY;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    $.event.special.mousewheel = {
        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
        },

        unmousewheel: function(fn) {
            return this.unbind("mousewheel", fn);
        }
    });


    function handler(event) {
        var orgEvent = event || window.event,
            args = [].slice.call(arguments, 1),
            delta = 0,
            deltaX = 0,
            deltaY = 0,
            absDelta = 0,
            absDeltaXY = 0,
            fn;
        event = $.event.fix(orgEvent);
        event.type = "mousewheel";

        // Old school scrollwheel delta
        if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
        if ( orgEvent.detail )     { delta = orgEvent.detail * -1; }

        // New school wheel delta (wheel event)
        if ( orgEvent.deltaY ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( orgEvent.deltaX ) {
            deltaX = orgEvent.deltaX;
            delta  = deltaX * -1;
        }

        // Webkit
        if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
        if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Look for lowest delta to normalize the delta values
        absDelta = Math.abs(delta);
        if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
        absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
        if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }

        // Get a whole value for the deltas
        fn = delta > 0 ? 'floor' : 'ceil';
        delta  = Math[fn](delta / lowestDelta);
        deltaX = Math[fn](deltaX / lowestDeltaXY);
        deltaY = Math[fn](deltaY / lowestDeltaXY);

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

}));
/**
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!)
 * Common usage: wipe images (left and right to show the previous or next image)
 * 
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.1.1 (9th December 2010) - fix bug (older IE's had problems)
 * @version 1.1 (1st September 2010) - support wipe up and wipe down
 * @version 1.0 (15th July 2010)
 */
(function($){$.fn.touchwipe=function(settings){var config={min_move_x:20,min_move_y:20,wipeLeft:function(){},wipeRight:function(){},wipeUp:function(){},wipeDown:function(){},preventDefaultEvents:true};if(settings)$.extend(config,settings);this.each(function(){var startX;var startY;var isMoving=false;function cancelTouch(){this.removeEventListener('touchmove',onTouchMove);startX=null;isMoving=false}function onTouchMove(e){if(config.preventDefaultEvents){e.preventDefault()}if(isMoving){var x=e.touches[0].pageX;var y=e.touches[0].pageY;var dx=startX-x;var dy=startY-y;if(Math.abs(dx)>=config.min_move_x){cancelTouch();if(dx>0){config.wipeLeft()}else{config.wipeRight()}}else if(Math.abs(dy)>=config.min_move_y){cancelTouch();if(dy>0){config.wipeDown()}else{config.wipeUp()}}}}function onTouchStart(e){if(e.touches.length==1){startX=e.touches[0].pageX;startY=e.touches[0].pageY;isMoving=true;this.addEventListener('touchmove',onTouchMove,false)}}if('ontouchstart'in document.documentElement){this.addEventListener('touchstart',onTouchStart,false)}});return this}})(jQuery);
/*
 * JavaScript MD5 1.0
 * https://github.com/blueimp/JavaScript-MD5
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 *
 * Based on
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */
(function(a){function b(a,b){var c=(a&65535)+(b&65535),d=(a>>16)+(b>>16)+(c>>16);return d<<16|c&65535}function c(a,b){return a<<b|a>>>32-b}function d(a,d,e,f,g,h){return b(c(b(b(d,a),b(f,h)),g),e)}function e(a,b,c,e,f,g,h){return d(b&c|~b&e,a,b,f,g,h)}function f(a,b,c,e,f,g,h){return d(b&e|c&~e,a,b,f,g,h)}function g(a,b,c,e,f,g,h){return d(b^c^e,a,b,f,g,h)}function h(a,b,c,e,f,g,h){return d(c^(b|~e),a,b,f,g,h)}function i(a,c){a[c>>5]|=128<<c%32,a[(c+64>>>9<<4)+14]=c;var d,i,j,k,l,m=1732584193,n=-271733879,o=-1732584194,p=271733878;for(d=0;d<a.length;d+=16)i=m,j=n,k=o,l=p,m=e(m,n,o,p,a[d],7,-680876936),p=e(p,m,n,o,a[d+1],12,-389564586),o=e(o,p,m,n,a[d+2],17,606105819),n=e(n,o,p,m,a[d+3],22,-1044525330),m=e(m,n,o,p,a[d+4],7,-176418897),p=e(p,m,n,o,a[d+5],12,1200080426),o=e(o,p,m,n,a[d+6],17,-1473231341),n=e(n,o,p,m,a[d+7],22,-45705983),m=e(m,n,o,p,a[d+8],7,1770035416),p=e(p,m,n,o,a[d+9],12,-1958414417),o=e(o,p,m,n,a[d+10],17,-42063),n=e(n,o,p,m,a[d+11],22,-1990404162),m=e(m,n,o,p,a[d+12],7,1804603682),p=e(p,m,n,o,a[d+13],12,-40341101),o=e(o,p,m,n,a[d+14],17,-1502002290),n=e(n,o,p,m,a[d+15],22,1236535329),m=f(m,n,o,p,a[d+1],5,-165796510),p=f(p,m,n,o,a[d+6],9,-1069501632),o=f(o,p,m,n,a[d+11],14,643717713),n=f(n,o,p,m,a[d],20,-373897302),m=f(m,n,o,p,a[d+5],5,-701558691),p=f(p,m,n,o,a[d+10],9,38016083),o=f(o,p,m,n,a[d+15],14,-660478335),n=f(n,o,p,m,a[d+4],20,-405537848),m=f(m,n,o,p,a[d+9],5,568446438),p=f(p,m,n,o,a[d+14],9,-1019803690),o=f(o,p,m,n,a[d+3],14,-187363961),n=f(n,o,p,m,a[d+8],20,1163531501),m=f(m,n,o,p,a[d+13],5,-1444681467),p=f(p,m,n,o,a[d+2],9,-51403784),o=f(o,p,m,n,a[d+7],14,1735328473),n=f(n,o,p,m,a[d+12],20,-1926607734),m=g(m,n,o,p,a[d+5],4,-378558),p=g(p,m,n,o,a[d+8],11,-2022574463),o=g(o,p,m,n,a[d+11],16,1839030562),n=g(n,o,p,m,a[d+14],23,-35309556),m=g(m,n,o,p,a[d+1],4,-1530992060),p=g(p,m,n,o,a[d+4],11,1272893353),o=g(o,p,m,n,a[d+7],16,-155497632),n=g(n,o,p,m,a[d+10],23,-1094730640),m=g(m,n,o,p,a[d+13],4,681279174),p=g(p,m,n,o,a[d],11,-358537222),o=g(o,p,m,n,a[d+3],16,-722521979),n=g(n,o,p,m,a[d+6],23,76029189),m=g(m,n,o,p,a[d+9],4,-640364487),p=g(p,m,n,o,a[d+12],11,-421815835),o=g(o,p,m,n,a[d+15],16,530742520),n=g(n,o,p,m,a[d+2],23,-995338651),m=h(m,n,o,p,a[d],6,-198630844),p=h(p,m,n,o,a[d+7],10,1126891415),o=h(o,p,m,n,a[d+14],15,-1416354905),n=h(n,o,p,m,a[d+5],21,-57434055),m=h(m,n,o,p,a[d+12],6,1700485571),p=h(p,m,n,o,a[d+3],10,-1894986606),o=h(o,p,m,n,a[d+10],15,-1051523),n=h(n,o,p,m,a[d+1],21,-2054922799),m=h(m,n,o,p,a[d+8],6,1873313359),p=h(p,m,n,o,a[d+15],10,-30611744),o=h(o,p,m,n,a[d+6],15,-1560198380),n=h(n,o,p,m,a[d+13],21,1309151649),m=h(m,n,o,p,a[d+4],6,-145523070),p=h(p,m,n,o,a[d+11],10,-1120210379),o=h(o,p,m,n,a[d+2],15,718787259),n=h(n,o,p,m,a[d+9],21,-343485551),m=b(m,i),n=b(n,j),o=b(o,k),p=b(p,l);return[m,n,o,p]}function j(a){var b,c="";for(b=0;b<a.length*32;b+=8)c+=String.fromCharCode(a[b>>5]>>>b%32&255);return c}function k(a){var b,c=[];c[(a.length>>2)-1]=undefined;for(b=0;b<c.length;b+=1)c[b]=0;for(b=0;b<a.length*8;b+=8)c[b>>5]|=(a.charCodeAt(b/8)&255)<<b%32;return c}function l(a){return j(i(k(a),a.length*8))}function m(a,b){var c,d=k(a),e=[],f=[],g;e[15]=f[15]=undefined,d.length>16&&(d=i(d,a.length*8));for(c=0;c<16;c+=1)e[c]=d[c]^909522486,f[c]=d[c]^1549556828;return g=i(e.concat(k(b)),512+b.length*8),j(i(f.concat(g),640))}function n(a){var b="0123456789abcdef",c="",d,e;for(e=0;e<a.length;e+=1)d=a.charCodeAt(e),c+=b.charAt(d>>>4&15)+b.charAt(d&15);return c}function o(a){return unescape(encodeURIComponent(a))}function p(a){return l(o(a))}function q(a){return n(p(a))}function r(a,b){return m(o(a),o(b))}function s(a,b){return n(r(a,b))}function t(a,b,c){return b?c?r(b,a):s(b,a):c?p(a):q(a)}"use strict",typeof define=="function"&&define.amd?define(function(){return t}):a.md5=t})(this);
/*! mousewheelStopPropagation.js v1.3.0
 * (c) 2014, Benoit Asselin contact(at)ab-d.fr
 * MIT License
 */
!function(a,b,c){"use strict";var d={duration:200,easing:"linear"};a.fn.mousewheelStopPropagation=function(b){function c(a){a.preventDefault(),a.stopPropagation(),"function"==typeof b.wheelstop&&b.wheelstop(a)}function e(a,c){b.emulateNaturalScrolling?a.stop(!0).animate({scrollTop:c},d):a.get(0).scrollTop=c}b=a.extend({wheelstop:null,emulateNaturalScrolling:!0},b);var f=navigator.userAgent.toLowerCase(),g=/(trident|msie)/.test(f),h=document.documentElement,i="mousewheel";return"onmousewheel"in h?i="mousewheel":"onwheel"in h?i="wheel":"DOMMouseScroll"in h&&(i="DOMMouseScroll"),i?this.each(function(){var b=this,d=a(b);d.on(i,function(a){var f=a.originalEvent,h=b.scrollTop,i=b.scrollHeight-d.outerHeight(),j=-f.wheelDelta;isNaN(j)&&(j=f.deltaY);var k=0>j;k&&0>=h||!k&&h>=i?c(a):g&&(k&&-j>h?(e(d,0),c(a)):!k&&j>i-h&&(e(d,i),c(a)))})}):this}}(jQuery,window);

$.fn.progress = function(kill) {
	this.each(function() {
		var $this = $(this),
			data = $this.data(),
			opts = {
				lines: 12,
				length: 5,
				width: 2,
				radius: 5,
				corners: .5,
				rotate: 2,
				color: $this.css('color')
			};
		if (data.spinner) {
			data.spinner.stop();
			delete data.spinner;
			if (kill===true) return;
		}
		if (kill===true) return;
		data.spinner = new Spinner(opts).spin(this);
	});
	return this;
};// http://spin.js.org/#v2.3.2
!function(a,b){"object"==typeof module&&module.exports?module.exports=b():"function"==typeof define&&define.amd?define(b):a.Spinner=b()}(this,function(){"use strict";function a(a,b){var c,d=document.createElement(a||"div");for(c in b)d[c]=b[c];return d}function b(a){for(var b=1,c=arguments.length;c>b;b++)a.appendChild(arguments[b]);return a}function c(a,b,c,d){var e=["opacity",b,~~(100*a),c,d].join("-"),f=.01+c/d*100,g=Math.max(1-(1-a)/b*(100-f),a),h=j.substring(0,j.indexOf("Animation")).toLowerCase(),i=h&&"-"+h+"-"||"";return m[e]||(k.insertRule("@"+i+"keyframes "+e+"{0%{opacity:"+g+"}"+f+"%{opacity:"+a+"}"+(f+.01)+"%{opacity:1}"+(f+b)%100+"%{opacity:"+a+"}100%{opacity:"+g+"}}",k.cssRules.length),m[e]=1),e}function d(a,b){var c,d,e=a.style;if(b=b.charAt(0).toUpperCase()+b.slice(1),void 0!==e[b])return b;for(d=0;d<l.length;d++)if(c=l[d]+b,void 0!==e[c])return c}function e(a,b){for(var c in b)a.style[d(a,c)||c]=b[c];return a}function f(a){for(var b=1;b<arguments.length;b++){var c=arguments[b];for(var d in c)void 0===a[d]&&(a[d]=c[d])}return a}function g(a,b){return"string"==typeof a?a:a[b%a.length]}function h(a){this.opts=f(a||{},h.defaults,n)}function i(){function c(b,c){return a("<"+b+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',c)}k.addRule(".spin-vml","behavior:url(#default#VML)"),h.prototype.lines=function(a,d){function f(){return e(c("group",{coordsize:k+" "+k,coordorigin:-j+" "+-j}),{width:k,height:k})}function h(a,h,i){b(m,b(e(f(),{rotation:360/d.lines*a+"deg",left:~~h}),b(e(c("roundrect",{arcsize:d.corners}),{width:j,height:d.scale*d.width,left:d.scale*d.radius,top:-d.scale*d.width>>1,filter:i}),c("fill",{color:g(d.color,a),opacity:d.opacity}),c("stroke",{opacity:0}))))}var i,j=d.scale*(d.length+d.width),k=2*d.scale*j,l=-(d.width+d.length)*d.scale*2+"px",m=e(f(),{position:"absolute",top:l,left:l});if(d.shadow)for(i=1;i<=d.lines;i++)h(i,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(i=1;i<=d.lines;i++)h(i);return b(a,m)},h.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}}var j,k,l=["webkit","Moz","ms","O"],m={},n={lines:12,length:7,width:5,radius:10,scale:1,corners:1,color:"#000",opacity:.25,rotate:0,direction:1,speed:1,trail:100,fps:20,zIndex:2e9,className:"spinner",top:"50%",left:"50%",shadow:!1,hwaccel:!1,position:"absolute"};if(h.defaults={},f(h.prototype,{spin:function(b){this.stop();var c=this,d=c.opts,f=c.el=a(null,{className:d.className});if(e(f,{position:d.position,width:0,zIndex:d.zIndex,left:d.left,top:d.top}),b&&b.insertBefore(f,b.firstChild||null),f.setAttribute("role","progressbar"),c.lines(f,c.opts),!j){var g,h=0,i=(d.lines-1)*(1-d.direction)/2,k=d.fps,l=k/d.speed,m=(1-d.opacity)/(l*d.trail/100),n=l/d.lines;!function o(){h++;for(var a=0;a<d.lines;a++)g=Math.max(1-(h+(d.lines-a)*n)%l*m,d.opacity),c.opacity(f,a*d.direction+i,g,d);c.timeout=c.el&&setTimeout(o,~~(1e3/k))}()}return c},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=void 0),this},lines:function(d,f){function h(b,c){return e(a(),{position:"absolute",width:f.scale*(f.length+f.width)+"px",height:f.scale*f.width+"px",background:b,boxShadow:c,transformOrigin:"left",transform:"rotate("+~~(360/f.lines*k+f.rotate)+"deg) translate("+f.scale*f.radius+"px,0)",borderRadius:(f.corners*f.scale*f.width>>1)+"px"})}for(var i,k=0,l=(f.lines-1)*(1-f.direction)/2;k<f.lines;k++)i=e(a(),{position:"absolute",top:1+~(f.scale*f.width/2)+"px",transform:f.hwaccel?"translate3d(0,0,0)":"",opacity:f.opacity,animation:j&&c(f.opacity,f.trail,l+k*f.direction,f.lines)+" "+1/f.speed+"s linear infinite"}),f.shadow&&b(i,e(h("#000","0 0 4px #000"),{top:"2px"})),b(d,b(i,h(g(f.color,k),"0 0 1px rgba(0,0,0,.1)")));return d},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}}),"undefined"!=typeof document){k=function(){var c=a("style",{type:"text/css"});return b(document.getElementsByTagName("head")[0],c),c.sheet||c.styleSheet}();var o=e(a("group"),{behavior:"url(#default#VML)"});!d(o,"transform")&&o.adj?i():j=d(o,"animation")}return h});


/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.helpers.Cookie = (function () {
	function Constructor () {
		/* public methods
			*/
		this.set = function(name, value, days, path) {
			if (!path) {
				path = location.pathname.split("/");
				path.pop();
				path = path.join("/") + "/";
			}
			var expires = "";
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				expires = "; expires="+date.toGMTString();
			}
			document.cookie = name+"="+value+expires+"; path=" + path;
		};
		this.get = function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			var i, c;
			for(i=0; i< ca.length; i++) {
				c = ca[i];
				while (c.charAt(0)==' ') {
					c = c.substring(1, c.length);
				}
				if (c.indexOf(nameEQ) == 0) {
					return c.substring(nameEQ.length, c.length);
				}
			}
			return "";
		};
		this.kill = function(name, path) {
			if (!path) {
				path = location.pathname.split("/");
				path.pop();
				path = path.join("/") + "/";
			}
			this.set(name,"",-1, path);
		};
	}
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

// http://www.nonobtrusive.com/2009/07/24/custom-events-in-javascript-by-making-your-own-dispatcher-class/

function EventDispatcher() {
	this.events=[];
}
EventDispatcher.prototype.addEventListener = function(event, callback, caller) {
	this.events[event] = this.events[event] || [];
	if ( this.events[event] ) {
		this.events[event].push({
			callback : callback,
			caller : caller
		});
	}
};
EventDispatcher.prototype.removeEventListener = function(event, callback) {
	if ( this.events[event] ) {
		var listeners = this.events[event];
		var i;
		for ( i = listeners.length-1; i>=0; --i ){
			//console.log(listeners[i]);
			if ( listeners[i].callback === callback ) {
				listeners.splice( i, 1 );
				return true;
			}
		}
	}
	return false;
};
EventDispatcher.prototype.dispatch = function(event, data) {
	data = data || {};
	if(this.events[event]) {
		var listeners = this.events[event];
		var len = listeners.length;
		while(len--) {
			listeners[len].callback(data, listeners[len].caller);
		}
	}
};

/*jslint browser: true, continue: true, eqeq: true, evil: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.helpers.Func = (function () {
	function Constructor () {
		/* private properites
			*/
		var browser_title_pattern = "";
		var filtersepia = {
			r: [0.211836996078431,0.712355450980392,0.0718859843137255],
			g: [0.198492933333333,0.667482666666667,0.0673577333333333],
			b: [0.190986898039216,0.642241725490196,0.0648105921568627]
		};
		var filtermono = {
			r: [0.212671,0.71516,0.072169],
			g: [0.212671,0.71516,0.072169],
			b: [0.212671,0.71516,0.072169]
		};
		/* private methods
			*/
		function filterexec (img, tone) {
			if ( img.width==0 || img.height==0 ) {
				return;
			}
			var canvas = document.createElement('canvas');
			var context = canvas.getContext('2d');
			canvas.width = img.width;
			canvas.height = img.height;
			context.drawImage(img, 0, 0);
			var imgdata = context.getImageData(0, 0, canvas.width, canvas.height);
			var matrix = tone=="sepia" ? filtersepia : filtermono;
			var pixels = imgdata.data;
			var i, n, shift_r, shift_g, shift_b;
			for (i = 0, n = pixels.length; i < n; i += 4) {
				shift_r = pixels[i] * matrix.r[0] + pixels[i+1] * matrix.r[1] + pixels[i+2] * matrix.r[2];
				shift_g = pixels[i] * matrix.g[0] + pixels[i+1] * matrix.g[1] + pixels[i+2] * matrix.g[2];
				shift_b = pixels[i] * matrix.b[0] + pixels[i+1] * matrix.b[1] + pixels[i+2] * matrix.b[2];
				pixels[i] = shift_r;
				pixels[i+1] = shift_g;
				pixels[i+2] = shift_b;
			}
			context.putImageData(imgdata, 0, 0);
			return canvas.toDataURL();
		}
		/* public methods
			*/
		this.array_chunk = function(arr, len) {
			var chunks = [],
				i = 0,
				n = arr.length,
				start, end;
			while (i < n) {
				start = i;
				end = i + len;
				chunks.push(arr.slice(start, end));
				i += len;
			}
			return chunks;
		};
		this.setDocumentTitlePattern = function(str) {
			browser_title_pattern = str;
		};
		this.setDocumentTitle = function(title) {
			if (!title) {
				title = "";
			}
			var browser_title = browser_title_pattern.split("{PAGE_NAME}").join(title);
			document.title = browser_title;
		};
		this.getEmptyImgSrc = function() {
			return "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
		};
		this.addSalesTax = function(taxable_amount) {
			var default_country = classes.overlay.Checkout.settings().country;
			var taxes = classes.overlay.Checkout.getTaxRate();
			var tax_value;
			if (default_country=="US") {
				tax_value = taxable_amount*(taxes[0]/100);
				return taxable_amount + tax_value;
			}
			if (default_country=="CA") {
				var hst_value = taxable_amount*(taxes[0]/100);
				var gst_value = taxable_amount*(taxes[1]/100);
					if (taxes[3]==true) {
						taxable_amount += gst_value;
					}
				var pst_value = taxable_amount*(taxes[2]/100);
				return taxable_amount + hst_value + gst_value + pst_value;
			}
			tax_value = taxable_amount*(taxes[0]/100);
			return taxable_amount + tax_value;
		};
		this.getFormattedPrice = function(value) {
			var isNegative = value<0;
			value = Math.abs(value);
			var digitsAfterDecimal = classes.helpers.L10N.get("localization", "currency_digits_after_decimal_num");
			var displayLeadingZeros = classes.helpers.L10N.get("localization", "currency_display_leading_zeros_bool");
			var leadingZeroDigits = classes.helpers.L10N.get("localization", "currency_leading_zero_digits_num");
			var digitsPerGroup = classes.helpers.L10N.get("localization", "currency_digits_per_group_num");
			var groupingSymbol = classes.helpers.L10N.get("localization", "currency_grouping_symbol");
			var decimalSymbol = classes.helpers.L10N.get("localization", "currency_decimal_symbol");
			var negativePattern = classes.helpers.L10N.get("localization", "currency_negative_pattern");
			var currencyPattern = classes.helpers.L10N.get("localization", "currency_currency_pattern");
			var vstr = value.toFixed(digitsAfterDecimal);
			var sides = vstr.split(".");
			var digits;
			var length;
			var i;
			digits = sides[0].split("");
			if (displayLeadingZeros) {
				length = leadingZeroDigits-digits.length;
				if (length>0) {
					for (i=0; i<length; ++i) {
						digits.unshift("0");
					}
				}
			}
			var groups = [];
			var chunk = digits.splice(-3).reverse().join("");
			groups.push(chunk);
			length = digitsPerGroup;
			chunk = "";
			var empty = digits.length==0;
			while (!empty) {
				if (digits.length<length) {
					length = digits.length;
				}
				for (i=0; i<length; ++i) {
					if (i>=0) {
						chunk += digits.pop();
					}
				}
				if (chunk.length==length) {
					groups.push(chunk);
					chunk = "";
				}
				empty = digits.length==0;
			}
			groups = groups.join(groupingSymbol);
			groups = groups.split("");
			groups.reverse();
			sides[0] = groups.join("");
			var result = sides.join(decimalSymbol);
			if (isNegative) {
				result = negativePattern.split("#").join(result);
			}
			result = currencyPattern.split("#").join(result);
			return result;
		};
		this.filter = function(obj, tone) {
			if (tone=="") {
				if (obj.data("original-src")) {
					obj.attr("src", obj.data("original-src"));
					obj.removeAttr("original-src");
				}
				return;
			}
			var imgsrc = obj.data("original-src") || obj.attr("src");
			var img = new Image();
			img.src = imgsrc;
			if (img.width==0||img.height==0) {
				img.onload = function () {
					obj.data("original-src", this.src);
					obj.attr("src", filterexec(this, tone));
				};
			} else {
				obj.data("original-src", imgsrc);
				obj.attr("src", filterexec(img, tone));
			}
		};
		this.stop = function(event) {
			event.stopPropagation();
			event.preventDefault();
		};
		this.prevent = function(event) {
			event.preventDefault();
		};
		this.empty = function() {
			return null;
		};
		this.imgonload = function() {
			if(this.complete) {
				$(this).load();
			}
		};
		this.touchboundsstart = function(event) {
			this.allowUp = (this.scrollTop > 0);
			this.allowDown = (this.scrollTop < this.scrollHeight - this.clientHeight);
			this.prevTop = null; this.prevBot = null;
			this.lastY = event.pageY;
		};
		this.touchboundsmove = function(event) {
			var up = (event.pageY > this.lastY), down = !up;
			this.lastY = event.pageY;
			if ((up && this.allowUp) || (down && this.allowDown)) event.stopPropagation();
			else event.preventDefault();
		};
	}
	return new Constructor();
}());

	classes.helpers.ResampledImageQueue = new function () {
		var _multiplier = 			Math.min(3, Math.ceil(window.devicePixelRatio ? window.devicePixelRatio : 1)) + "x";
		var _use_srcset = 			false;
		var _image_list = 			[];
		var _image_loader = 		null;
		var _image_loader_index = 	-1;
		var _image_loader_loading = false;
		var _image_offset = 		null;
		var _image_offset_timer = 	0;
		function cancelLazyLoading () {
			var img = _image_list[_image_loader_index];
			if (img) {
				img.off();
				clearInterval(_image_loader);
			}
		}
		function lazyError () {
			var img = _image_list[_image_loader_index];
			img.attr("src", img.data("blank"));
		}
		function lazyLoaded () {
			clearInterval(_image_loader);
			_image_loader = setTimeout(lazyLoadNext, 1);
		}
		function offsetLoaded () {
			_image_offset_timer += 1;
			clearInterval(_image_offset);
			_image_offset = setTimeout(lazyLoadNext, _image_offset_timer);
		}
		function lazyComplete () {
			if( this.complete ) {
				$(this).load();
			}
		}
		function getProbableSrc (img) {
			if (_use_srcset) {
				var lookup = [];
				var srcs = img.attr("data-srcset").split(", ");
				for (var i=0; i<srcs.length; ++i) {
					var set = srcs[i].split(" ");
					lookup[set[1]] = set[0];
				}
				return lookup[_multiplier];
			} else {
				return img.attr("data-src");
			}
		}
		function lazyLoadNext () {
			_image_loader_index = _image_loader_index + 1;
			if (_image_loader_index==_image_list.length) {
				_image_loader_index = _image_loader_index - 1
				_image_loader_loading = false;
				return;
			}
			_image_loader_loading = true;
			var img = _image_list[_image_loader_index];
			var blank = img.attr("src");
			var srcset = img.attr("data-srcset");
			var src = getProbableSrc(img);
			var lazyload = src.indexOf("resample.php")!=-1;
			img
				.removeProp("src")
				.data("blank", blank)
				.one('error', lazyError);
			if (lazyload) {
				if (_use_srcset) {
					img
						.attr("srcset", srcset)
						.one('load', lazyLoaded)
						.each(lazyComplete);
				} else {
					img
						.attr("src", src)
						.one('load', lazyLoaded)
						.each(lazyComplete);
				}
			} else {
				if (_use_srcset) {
					img.attr("srcset", srcset);
				} else {
					img.attr("src", src);
				}
				offsetLoaded();
			}
		}
		function lazyLoad (img) {
			if ( img.attr("data-src")!=undefined ) {
				_image_list.push(img);
				if (_image_loader_loading==false) {
					lazyLoadNext();
				}
			}
		}
		this.addObject = function (obj) {
			obj.each(function () {
				lazyLoad($(this));
			});
		};
		this.start = function () {
			var img = new Image();
			_use_srcset = 'srcset' in img;
		};
	};
	
/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.Dialog = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy;
		var L10N;
		var Shell;
		var Func;
		/* private properites
			*/
		var defaults = {
			unique: 			"",
			modal: 				true,
			title: 				"",
			description: 		"",
			confim: 			classes.helpers.Func.empty,
			cancel: 			classes.helpers.Func.empty,
			args: 				[]
		};
		var opt = {};
		var instance = this;
		var open = false;
		var noremind = {};
		// jquery cache
		var container;
		var screen;
		var dialog;
		var title;
		var description;
		var accept_obj;
		var cancel_obj;
		var noremind_obj;
		/* private methods
			*/
		function confirm () {
			opt.confim.apply(null, opt.args);
		}
		function cancel () {
			opt.cancel.apply(null, opt.args);
		}
		function remeber (bool) {
			if (bool) {
				noremind[opt.unique] = true;
			} else {
				noremind[opt.unique] = false;
			}
		}
		function keyevent (event) {
			if (open) {
				switch (event.which) {
					case 13 : // Key.ENTER :
						confirm();
						Func.stop(event);
						return false;
				}
			}
		}
		function ondestroy () {
			open = false;
			instance.dispatch("onClose");
		}
		function destroy () {
			// ditch the options
			opt = {};
			// and bye bye
			container.fadeOut("fast", ondestroy);
		}
		function click (event) {
			switch ($(this).attr("id")) {
				case noremind_obj.attr("id") :
					remeber(noremind_obj.is(':checked'));
					break;
				case accept_obj.attr("id") :
					confirm();
					destroy();
					break;
				case screen.attr("id") :
					break;
				case cancel_obj.attr("id") :
					cancel();
					destroy();
					break;
			}
			Func.stop(event);
			return false;
		}
		function resize () {
			if (!open) {
				container.show();
			}
			var sw = StageProxy.width();
			var sh = StageProxy.height();
			var dw = dialog.width();
			var dh = dialog.outerHeight();
			dialog.css({
				top: (sh-dh)/2,
				left: (sw-dw)/2
			});
			if (!open) {
				container.hide();
			}
		}
		function create () {
			// title
			title
				.html(opt.title)
				.toggle(opt.title!="");
			// description
			description
				.html(opt.description)
				.toggle(opt.description!="");
			// modal means there is a true/false
			if (opt.modal) {
				accept_obj.html(L10N.get("general", "dialog_approve"));
				cancel_obj.show();
			} else { // only confirm
				accept_obj.html(L10N.get("general", "dialog_confim"));
				cancel_obj.hide();
			}
			noremind_obj.toggle(opt.unique!="");
			noremind_label_obj.toggle(opt.unique!="");
			// display it's initial state
			open = true;
			container.fadeIn("fast");
			// resize
			resize();
			instance.dispatch("onOpen");
		}
		function render () {
			// assign jquery selectors
			container = 	$("#dialog-container");
			screen = 		$("#dialog-screen");
			dialog = 		$("#dialog");
			title = 		$("#dialog-title");
			description = 	$("#dialog-description");
			accept_obj = 	$("#dialog-accept");
			cancel_obj = 	$("#dialog-cancel");
			noremind_obj = 	$("#dialog-noremind");
			noremind_label_obj = 	$("#dialog-noremind-label");
			// submit
			screen.click(click);
			accept_obj.click(click);
			cancel_obj.click(click);
			noremind_obj.change(click);
			// listen to stage
			if (!Shell.device().touch) {
				container.mousewheel(Func.stop);
			} else {
				container.bind("touchmove", Func.stop);
			}
			$("body").keyup(keyevent);
			StageProxy.addEventListener("onResize", resize);
		}
		/* public methods
			*/
		this.options = function(obj) {
			var prop;
			for (prop in defaults) {
				if (defaults.hasOwnProperty(prop)) {
					opt[prop] = defaults[prop];
				}
			}
			for (prop in obj) {
				if (obj.hasOwnProperty(prop)) {
					opt[prop] = obj[prop];
				}
			}
		};
		this.draw = function() {
			if (noremind[opt.unique]==true) {
				confirm();
				return;
			}
			create();
		};
		this.initialize = function () {
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			StageProxy = classes.StageProxy;
			Shell = classes.Shell;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.Overlay = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy;
		var Session;
		var Shell;
		var Browser;
		var Clickwrap;
		var Sidebar;
		var Overview;
		var Packages;
		var Package;
		var Cart;
		var Controlbar;
		var Checkout;
		var Display;
		var ContactForm;
		var Func;
		/* private properites
			*/
		var instance = 		this;
		var suid = 			"";
		var classid = 		"";
		var status = 		"closed";
		var index = 		0;
		var browseindex = 	0;
		var browseview = 	"wall";
		var wallview = 		"set";
		var lastwidth = 	0;
		var lastheight = 	0;
		var tracks = [];
		var images = {};
		var groups = [];
		// jquery selectors
		var container;
		var screen;
		var skirt;
		/* private methods
			*/
		function closeOverlay () {
			status = "closed";
			container.hide();
			Browser.clearStage();
			Display.showWall();
			Shell.killToolTip();
			instance.dispatch("onClose");
		}
		function openOverlay () {
			status = "open";
			container.show();
			resize();
			Display.hideWall();
			instance.dispatch("onOpen");
		}
		function resize () {
			// set the height of the overlay depending on the available width
			var sw = StageProxy.width();
			var sh = StageProxy.height();
			if ( sw==lastwidth && lastheight==sh ) {
				return; // no need for resize
			}
			lastwidth = StageProxy.width();
			lastheight = StageProxy.height();
			// if it's hidden, unhide
			if (status=="closed") {
				container.show();
			}
			var ch = sw<=800 ? sh : sh-65;
			if ( $.browser.safari && $.browser.mobile ) {
				if ( window.orientation==90 || window.orientation==-90 ) {
					ch -= 44;
					if (sw<=480) ch -= 44;
				}
			}
			var innerwidth = sw;
			var innerheight = ch;
			container.width(innerwidth).height(innerheight);
			if (Shell.device().touch) {
				screen.width(innerwidth+100).height(innerheight+100);
			}
			skirt.css({
				top: innerheight
			});
			var sidebartop = 0;
			var sidebarheight = innerheight;
			var browsertop = 0;
			var browserheight = innerheight;
			var sidebarwidth = 0;
			var sidebarleft = innerwidth*-1;
			if (Sidebar.available()) {
				sidebarwidth = innerwidth-1024;
				if (sidebarwidth<350) {
					sidebarwidth = 350;
				}
				if (sidebarwidth>600) {
					sidebarwidth = 600;
				}
				sidebarleft = 0;
			}
			var browserleft = sidebarwidth;
			var browserwidth = innerwidth - sidebarwidth;
			if (innerwidth<=800) {
				sidebarwidth = innerwidth;
				sidebarleft = innerwidth*-1;
				browserwidth = innerwidth;
				browserleft = 0;
			}
			Sidebar.move(sidebarleft, sidebartop);
			Sidebar.setSize(sidebarwidth, sidebarheight);
			Browser.move(browserleft, browsertop);
			Browser.setSize(browserwidth, browserheight);
			if (status=="closed") {
				container.hide();
			}
		}
		function start () {
			lastwidth = 0;
			lastheight = 0;
			resize();
		}
		function render () {
			// assign all our jquery containers
			classid = 		$("#container").attr("class");
			suid = 			$("#container").attr("data-suid");
			container = 	$("#overlay-container");
			screen = 		$("#overlay-screen");
			skirt = 		$("#overlay-skirt");
			// initialize
			Browser.initialize();
			Cart.initialize();
			Checkout.initialize();
			Overview.initialize();
			Packages.initialize();
			Package.initialize();
			Sidebar.initialize();
			Clickwrap.initialize();
			ContactForm.initialize();
			// prevent scroll and touch
			screen.bind("touchmove", Func.stop);
			screen.mousewheel(Func.stop);
			// resize it at least once
			StageProxy.addEventListener("onResize", resize);
			Session.addEventListener("onSessionLoaded", start);
			resize();
		}
		
		function dataset () {
			var arr = [];
			if (wallview=="set") {
				arr = images[groups[index]];
			} else if (wallview=="favorites") {
				arr = Session.getFavoritesPaged(index);
				if (!arr) arr = [];
			}
			return arr;
		}
		function imagedata (i) {
			var set = dataset();
			var obj = set[i];
			var obj_hash;
			var obj_puid;
			var obj_cuid;
			var obj_filename;
			var obj_width;
			var obj_height;
			var obj_xoffset = 50;
			var obj_yoffset = 50;
			if (wallview=="set") {
				obj_puid = classid=="ZipFile" ? suid + ".zip" : suid;
				obj_cuid = obj.c;
				obj_hash = md5(obj_puid+obj_cuid);
				obj_filename = obj.f;
				obj_width = parseInt(obj.w, 10);
				obj_height = parseInt(obj.h, 10);
			} else if (wallview=="favorites") {
				obj_hash = obj.hash.substr(0, 32);
				obj_puid = obj.puid;
				obj_cuid = obj.cuid;
				obj_filename = obj.filename;
				obj_width = parseInt(obj.width, 10);
				obj_height = parseInt(obj.height, 10);
			}
			return {
				child: obj_cuid,
				parent: obj_puid,
				hash: obj_hash,
				type: obj_filename.substring(obj_filename.lastIndexOf(".")+1).toUpperCase(),
				src: obj_puid + "/" + obj_cuid,
				width: obj_width,
				height: obj_height,
				alt: obj_filename,
				xoffset: obj_xoffset,
				yoffset: obj_yoffset
			};
		}
		/* public methods
			*/
		this.pageid = function() {
			return suid;
		};
		this.close = function() {
			Controlbar.dispatch("onPageView", [ "browse", "wall", wallview, index, browseindex ]);
		};
		this.addImageSet = function(str, arr) {
			images[str] = arr;
			groups.push(str);
		};
		this.getImageCount = function(str, arr) {
			var tally = 0;
			for (var i=0; i<groups.length; ++i) {
				var group = groups[i];
				var set = images[group];
				tally += set.length;
			}
			return tally;
		};
		this.addAudioTrack = function(obj) {
			tracks.push(obj);
		};
		this.getPlaylist = function() {
			return tracks;
		};
		this.getViewProvider = function() {
			var set = dataset();
			var arr = [];
			var i;
			for (i=0; i<set.length; ++i) {
				arr.push(imagedata(i));
			}
			return arr;
		};
		this.getCurrentImage = function() {
			return this.getImageInfo(browseindex);
		};
		this.getImageInfo = function(i) {
			if (i==-1) {
				return;
			}
			var set = dataset();
			if (!set) return;
			var obj = set[i];
			if (!obj) return;
			if (wallview=="set") {
				return {
					parent: 	classid=="ZipFile"  ? suid + ".zip" : suid,
					child: 		obj.c,
					filename: 	obj.f,
					width: 		parseInt(obj.w, 10),
					height: 	parseInt(obj.h, 10)
				};
			}
			if (wallview=="favorites") {
				return {
					parent: 	obj.puid,
					child: 		obj.cuid,
					filename: 	obj.filename,
					width: 		parseInt(obj.width, 10),
					height: 	parseInt(obj.height, 10)
				};
			}
		};
		this.isOpen = function() {
			return status=="open";
		};
		this.getWallView = function() {
			return wallview;
		};
		this.setWallView = function(str) {
			wallview = str;
		};
		this.getIndex = function() {
			return index;
		};
		this.setIndex = function(num) {
			index = num;
		};
		this.getBrowseIndex = function() {
			return browseindex;
		};
		this.setBrowseIndex = function(num) {
			browseindex = num;
			Browser.refresh();
		};
		this.getBrowseView = function() {
			return browseview;
		};
		this.setBrowseView = function(str) {
			browseview = str;
			if (browseview=="wall") {
				closeOverlay();
			} else {
				openOverlay();
			}
		};
		this.getImageGroupCount = function() {
			if (wallview=="set") {
				return groups.length;
			} else if (wallview=="favorites") {
				var pages = Session.getFavoritesPaged();
				return pages.length;
			}
		};
		this.getMaxImageCount = function() {
			var max = Shell.device().touch ? 150 : 300;
			var prop;
			for (prop in images) {
				if (images.hasOwnProperty(prop)) {
					max = Math.max(max, images[prop].length);
				}
			}
			return max;
		};
		this.prevBrowseIndex = function() {
			var pages, current;
			var pi = index;
			var ii = browseindex-1;
			if (wallview=="set") {
				current = images[groups[pi]];
				if (ii==-1) { // at the end of our current page array
					if (groups.length>1) { // there are more pages
						pi = index-1; // next page index
						if (pi==-1) {
							pi = groups.length-1; // we're at the end of the pages, go back to first page
						}
						current = images[groups[pi]];
					}
					ii = current.length-1; // on any page change, the next browse index will be 0
				}
			} else if (wallview=="favorites") {
				pages = Session.getFavoritesPaged();
				current = pages[pi];
				if (ii==-1) { // at the end of our current page array
					if (pages.length>1) { // there are more pages
						pi = index-1; // next page index
						if (pi==-1) {
							pi = pages.length-1; // we're at the end of the pages, go back to first page
						}
						current = pages[pi];
					}
					ii = current.length-1; // on any page change, the next browse index will be 0
				}
			}
			Controlbar.dispatch("onPageView", [ "browse", "overlay", wallview, pi, ii ]);
		};
		this.nextBrowseIndex = function() {
			var pages, current;
			var pi = index;
			var ii = browseindex+1;
			if (wallview=="set") {
				current = images[groups[index]];
				if (ii>=current.length) { // at the end of our current page array
					if (groups.length>1) { // there are more pages
						pi = index+1; // next page index
						if (pi==groups.length) {
							pi = 0; // we're at the end of the pages, go back to first page
						}
					}
					ii = 0; // on any page change, the next browse index will be 0
				}
			} else if (wallview=="favorites") {
				pages = Session.getFavoritesPaged();
				current = pages[pi];
				if (ii>=current.length) { // at the end of our current page array
					if (pages.length>1) { // there are more pages
						pi = index+1; // next page index
						if (pi==pages.length) {
							pi = 0; // we're at the end of the pages, go back to first page
						}
					}
					ii = 0; // on any page change, the next browse index will be 0
				}
			}
			Controlbar.dispatch("onPageView", [ "browse", "overlay", wallview, pi, ii ]);
		};
		this.initialize = function() {
			Func = classes.helpers.Func;
			StageProxy = classes.StageProxy;
			Shell = classes.Shell;
			Session = classes.Session;
			Browser = classes.overlay.Browser;
			Clickwrap = classes.overlay.Clickwrap;
			Sidebar = classes.overlay.Sidebar;
			Packages = classes.overlay.Packages;
			Overview = classes.overlay.Overview;
			Package = classes.overlay.Package;
			Cart = classes.overlay.Cart;
			Controlbar = classes.elements.Controlbar;
			Checkout = classes.overlay.Checkout;
			ContactForm = classes.elements.ContactForm;
			Display = classes.content.Display;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.Session = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var Checkout; // shortcut
		var Overlay; // shortcut
		var Func; // shortcut
		/* private properites
			*/
		var instance = this;
		var hash = "";
		var request_id = -1;
		var requests = {};
		var type_lookup = {
			cart: [],
			cart_chunked: [],
			download: [],
			download_chunked: [],
			favorites: [],
			favorites_chunked: [],
			package: [],
			parsed: []
		};
		var type_hashtable = {
			cart: {},
			download: {},
			favorites: {},
			package: {},
			parsed: {}
		};
		var type_keys = {
			cart: [
				"hash", "puid", "cuid", // 0 1 2
				"filename", "quantity", "toning", // 3 4 5
				"format_label", "format_aspect", "format_price", "format_shipping", // 6 7 8 9
				"orientation", "orientation_x", "orientation_y", // 10 11 12
				"paper_label", "paper_price", "paper_shipping", // 13 14 15
				"modifier_label", "modifier_price", "modifier_shipping", // 16 17 18
				"subtotal", "shipping", // 19 20
				"comments" // 21
				],
			download: [
				"hash", "puid", "cuid", // 0 1 2
				"filename", "dimensions", "quality", // 3 4 5
				"subtotal", "allprice" // 6 7
				],
			favorites: [
				"hash", "puid", "cuid", // 0 1 2
				"filename", "width", "height" // 3 4 5
				],
			package: [
				"hash", "type", "nickname", "title",// 0 1 2 3
				"quantity", "subtotal", "shipping", // 4 5 6
				"format_titles", // 7
				"format_quantities", // 8
				"format_aspects", // 9
				"format_areas" // 10
				]
		};
		/* private methods
			*/
		function chunk (label) {
			var arr = type_lookup[label];
			var page_breakpoint = Overlay.getMaxImageCount();
			var chunks = [];
			if (arr.length<=page_breakpoint) {
				chunks.push(arr);
			} else {
				chunks = Func.array_chunk(arr, page_breakpoint);
			}
			type_lookup[label+"_chunked"] = chunks;
		}
		function parse (result, ruid) {
			if (result=="0") {
				result = "";
			}
			var request = requests[ruid];
			//trace ("type:" + request.type);
			//trace ("result: " + result);
			var types = [];
				if (request.type=="favorites" || request.type=="*") {
					types.push("favorites");
				}
				if (request.type=="download" || request.type=="alacarte" || request.type=="cart" || request.type=="package" || request.type=="*") {
					types.push("package");
					types.push("cart");
					types.push("download");
				}
			// low-level string parsing
			var lines = result=="" ? [] : result.split("\n");
			var rows = [];
			var i, line, values, suid, type;
			for (i=0; i<lines.length; ++i) {
				line = lines[i];
				values = line.split("\t");
				suid = values[0].split("-");
				type = "cart";
				if (suid[1]=="f") {
					type = "favorites";
				}
				if (suid[1]=="p") {
					type = "package";
				}
				if (suid[1]=="d") {
					type = "download";
				}
				rows.push({
					type: type,
					values: values
				});
			}
			// parse out all the bits and pieces
			var k, j, keys, data, table, row, obj, key, value;
			for (k=0; k<types.length; ++k) {
				type = types[k];
				keys = type_keys[type];
				data = [];
				table = {};
				for (i=0; i<rows.length; ++i) {
					row = rows[i];
					if (row.type!=type) {
						continue;
					}
					values = row.values;
					obj = {};
					for (j=0; j<keys.length; ++j) {
						key = keys[j];
						value = values[j];
						if (value==undefined) {
							value = "";
						}
						obj[key] = value;
					}
					data.push(obj);
					table[obj.hash] = obj;
				}
				type_lookup[type] = data;
				type_hashtable[type] = table;
			}
			// do a custom parse for packages
			if (request.type=="cart" || request.type=="package" || request.type=="*") {
				var package_lookup = [];
				var packages = type_lookup["package"];
				type_lookup.parsed = [];
				var pkg, total, formats, lookup, format_percent_encoded, format_titles, format_quantities, format_aspects, format_areas, format_title, format_hash, format_quantity;
				for (i=0; i<packages.length; ++i) {
					pkg = packages[i];
					total = 0;
					formats = [];
					lookup = {};
					format_percent_encoded = false;
					format_titles = pkg.format_titles;
					if (pkg.format_titles.substr(0, 2)=="%:") {
						format_percent_encoded = true;
						format_titles = pkg.format_titles.substr(2);
					}
					format_titles = format_titles=="" ? [] : format_titles.split(",");
					format_quantities = pkg.format_quantities.split(",");
					format_aspects = pkg.format_aspects.split(",");
					format_areas = pkg.format_areas.split(",");
					for (j=0; j<format_titles.length; ++j) {
						format_title = format_percent_encoded ? unescape(format_titles[j]) : $.base64.decode(format_titles[j]);
						format_hash = md5(format_title);
						format_quantity = parseInt(format_quantities[j], 10);
						total += format_quantity;
						lookup[format_hash] = j;
						formats.push({
							title: format_title,
							price: 0,
							shipping: 0,
							aspect: format_aspects[j],
							area: format_areas[j],
							total: format_quantity,
							count: 0
						});
					}
					package_lookup[pkg.hash] = i;
					type_lookup.parsed.push({
						row: pkg,
						formats: formats,
						lookup: lookup,
						total: total,
						count: 0
					});
				}
				var cart = type_lookup.cart;
				var hashbits, package_hash, format, quantity;
				for (i=0; i<cart.length; ++i) {
					row = cart[i];
					if (row.hash.indexOf(":")!=-1) {
						hashbits = row.hash.split(":");
						package_hash = hashbits[1] + "-p";
						format_hash = md5(row.format_label);
						quantity = parseInt(row.quantity, 10);
						pkg = type_lookup.parsed[package_lookup[package_hash]];
						format = pkg.formats[pkg.lookup[format_hash]];
						pkg.count += quantity;
						format.count += quantity;
					}
				}
			}
			if (request.type=="favorites") {
				chunk("favorites");
				instance.dispatch("onSessionFavorites");
			}
			if (request.type=="download" || request.type=="alacarte" || request.type=="cart" || request.type=="package") {
				chunk("cart");
				chunk("download");
				instance.dispatch("onSessionCart");
			}
			if (request.type=="*") {
				chunk("favorites");
				chunk("download");
				chunk("cart");
				instance.dispatch("onSessionLoaded");
			}
			delete requests[ruid];
		}
		function addSessionObject (type, data) {
			if (data.hash==undefined) {
				return;
			}
			// generate new row
			var keys = type_keys[type];
			var postfix = "";
				if (type=="favorites") {
					postfix = "-f";
				}
				if (type=="download") {
					postfix = "-d";
				}
				if (type=="package") {
					postfix = "-p";
				}
			var row = [];
			var i, key, value;
			for (i=0; i<keys.length; ++i) {
				key = keys[i];
				value = data[key];
				if (value==undefined) {
					value = "";
				}
				row.push(value);
			}
			row[0] = row[0] + postfix;
			// add it to the session table
			++request_id;
			var ruid = "r_"+request_id;
			var request = {
				action: 	"update_session_item",
				type: 		type,
				name: 		hash,
				puid: 		Overlay.pageid(),
				data:		row.join("\t")
			};
			requests[ruid] = request;
			$.post( APP_ROOT + "vend-proofing-gateway.php", request, function (str) {
				parse(str, ruid);
			});
		}
		function removeSessionObject (type, suid) {
			var data;
			var found = false;
			var lookup = type_lookup[type];
			var i;
			for (i=0; i<lookup.length; ++i) {
				data = lookup[i];
				if (data.hash.indexOf(suid)!=-1) {
					found = true;
					break;
				}
			}
			if (found==false) {
				return;
			}
			// add it to the session table
			++request_id;
			var ruid = "r_"+request_id;
			var request = {
				action: 	"delete_session_item",
				type: 	type,
				name: 	hash,
				puid: 	Overlay.pageid(),
				suid:		data.hash
			};
			requests[ruid] = request;
			$.post( APP_ROOT + "vend-proofing-gateway.php", request, function (str) {
				parse(str, ruid);
			});
		}
		function updateSessionObject (type, suid, names, values) {
			// get the lineitem we're working with
			var data;
			var found = false;
			var lookup = type_lookup[type];
			var i;
			for (i=0; i<lookup.length; ++i) {
				data = lookup[i];
				if (data.hash.indexOf(suid)!=-1) {
					found = true;
					break;
				}
			}
			if (found==false) {
				return;
			}
			// if not arrays, let's make them arrays
			if (!(names instanceof Array)) {
				names = [names];
				values = [values];
			}
			// update key values for each item we're updating
			var keys = type_keys[type];
			var row = [];
			var postfix = "";
				if (type=="download") {
					postfix = "-d";
				}
				if (type=="favorites") {
					postfix = "-f";
				}
				if (type=="package") {
					postfix = "-p";
				}
			var j, key, value;
			for (i=0; i<keys.length; ++i) {
				key = keys[i];
				value = data[key];
				for (j=0; j<names.length; ++j) {
					if (key==names[j]) {
						value = values[j];
					}
				}
				if (value==undefined) {
					value = "";
				}
				row.push(value);
			}
			row[0] = row[0] + postfix;
			// add it to the session table
			++request_id;
			var ruid = "r_"+request_id;
			var request = {
				action: 	"update_session_item",
				type: 		type,
				name: 		hash,
				puid: 		Overlay.pageid(),
				data:		row.join("\t")
			};
			requests[ruid] = request;
			$.post( APP_ROOT + "vend-proofing-gateway.php", request, function (str) {
				parse(str, ruid);
			});
		}
		function addAllOfType (group, quality) {
			++request_id;
			var ruid = "r_"+request_id;
			var price = group=="cart" ? Checkout.settings().downloads.all[quality] : Checkout.settings().downloads[quality].price;
			var flat = group=="cart" && Checkout.settings().downloads.all.flat ? "true" : "false";
			var request = {
				action: 	"add_all_of_type",
				name: 		hash,
				type: 		"download",
				group: 		group,
				quality: 	quality,
				price: 		price,
				flat: 		flat,
				puid: 		Overlay.pageid()
			};
			requests[ruid] = request;
			$.post( APP_ROOT + "vend-proofing-gateway.php", request, function (str) {
				parse(str, ruid);
			});
		}
		function clearSessionType (type) {
			instance.dispatch("onLoadSession");
			++request_id;
			var ruid = "r_"+request_id;
			var request = {
				action: 	"delete_session_type",
				type: 		type,
				name: 		hash,
				puid: 		Overlay.pageid()
			};
			requests[ruid] = request;
			$.post( APP_ROOT + "vend-proofing-gateway.php", request, function (str) {
				parse(str, ruid);
			});
		}
		function loadSession () {
			++request_id;
			var ruid = "r_"+request_id;
			var request = {
				action: 	"list_session_table",
				type: 		"*",
				name: 		hash,
				puid: 		Overlay.pageid()
			};
			$.post( APP_ROOT + "vend-proofing-gateway.php", request, function (str) {
				parse(str, ruid);
			});
			requests[ruid] = request;
		}
		/* public methods
			*/
		this.addItem = function(type, data) { // type:String, data:Object
			addSessionObject(type, data);
		};
		this.removeItem = function(type, suid) { // type:String, suid:String
			removeSessionObject(type, suid);
		};
		this.updateItem = function(type, suid, names, values) { // type:String, suid:String, names, values
			updateSessionObject(type, suid, names, values);
		};
		this.purge = function(type) { // type:String
			clearSessionType(type);
		};
		
		this.isFavoritesEmpty = function() { // return:Boolean
			return type_lookup.favorites.length==0;
		};
		this.getFavoritesLength = function() { // return:Array
			return type_lookup.favorites.length;
		};
		this.getFavoritesPaged = function(i) { // return:Array
			return i==undefined || i==-1 ? type_lookup.favorites_chunked : type_lookup.favorites_chunked[i];
		};
		this.getFavorites = function() { // return:Array
			return type_lookup.favorites;
		};
		this.getFavoritesTable = function() { // return:Object
			return type_hashtable.favorites;
		};
		this.getFavoriteObject = function(hash) { // return:Object
			return type_hashtable.favorites[hash];
		};
		
		this.isCartEmpty = function() { // return:Boolean
			return type_lookup.cart.length==0;
		};
		this.getCartLength = function() { // return:Number
			return type_lookup.cart.length;
		};
		this.getCartPaged = function(i) { // return:Array
			return i==undefined || i==-1 ? type_lookup.cart_chunked : type_lookup.cart_chunked[i];
		};
		this.getCart = function() { // return:Array
			return type_lookup.cart;
		};
		this.getCartTable = function() { // return:Object
			return type_hashtable.cart;
		};
		this.getCartObject = function(hash) { // return:Object
			return type_hashtable.cart[hash];
		};
		
		this.downloadAll = function(group, quality) { // group:String, quality:Object
			addAllOfType(group, quality);
		};
		this.isDownloadsEmpty = function() { // return:Boolean
			return type_lookup.download.length==0;
		};
		this.getDownloadsLength = function() { // return:Number
			return type_lookup.download.length;
		};
		this.getDownloadsPaged = function(i) { // return:Array
			return i==undefined || i==-1 ? type_lookup.download_chunked : type_lookup.download_chunked[i];
		};
		this.getDownloads = function() { // return:Array
			return type_lookup.download;
		};
		this.getDownloadsTable = function() { // return:Array
			return type_hashtable.download;
		};
		this.getDownloadObject = function(hash) { // return:Object
			return type_hashtable.download[hash];
		};
		
		this.getPackages = function() { // return:Array
			return type_lookup.package;
		};
		this.getPackagesLength = function() { // return:Number
			return type_lookup.package.length;
		};
		this.getPackagesParsed = function() { // return:Array
			return type_lookup.parsed;
		};
		
		this.getHash = function() { // return:String
			return hash;
		};
		this.setHash = function(str) { // str:String
			hash = str;
			loadSession();
		};
		
		this.initialize = function() {
			Checkout = classes.overlay.Checkout;
			Overlay = classes.Overlay;
			Func = classes.helpers.Func;
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.Shell = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy;
		var Dialog;
		var FormDialog;
		var Overlay;
		var Content;
		var L10N;
		var Func;
		/* private properites
			*/
		var tooltip;
		var tooltip_visible = false;
		var body;
		var error;
		var error_inner;
		var classname = "";
		var setup = {};
		/* private methods
			*/
		function ttposition (event) {
			if (!tooltip_visible) {
				return;
			}
			var mousex = event.pageX + 5;
			var mousey = event.pageY - (tooltip.outerHeight()+5);
			if ( mousex + tooltip.outerWidth() > StageProxy.width()) {
				mousex -= tooltip.outerWidth() + 10;
			}
			tooltip.css({
				top: mousey,
				left: mousex
			});
		}
		function resize_error () {
			var inner = error_inner.outerHeight();
			var outer = StageProxy.height();
			if (inner<outer) {
				error_inner.css("top", Math.round((outer-inner)/2)+"px");
			} else {
				error_inner.css("top", 0);
			}
		}
		function showError (type) {
			body.hide();
			error.show();
			$("#body-fail-icon").removeClass().addClass(type);
			$("#body-fail-title").html(L10N.get("general", "browser_error_" + type + "_title"));
			$("#body-fail-description").html(L10N.get("general", "browser_error_" + type + "_description"));
			resize_error();
		}
		function hideError () {
			body.show();
			error.hide();
		}
		function supported () {
			/* var props = "";
			for (var prop in $.browser) props += prop + ": " + $.browser[prop] + "\n";
			alert(props); //*/
			//return true;
			var success = true;
			// check for mobile webkit chrome/safari/android browsers based on webkit first
			if ( $.browser.mobile ) {
				var version = parseInt($.browser.version, 10);
				if ( $.browser.webkit ) {
					success = version >= 534;
				}
			}
			// mobile/desktop independant
			if ( $.browser.desktop ) {
				if ( $.browser.safari ) {
					success = $.browser.versionNumber >= 5;
				}
			}
			if ( $.browser.chrome ) {
				success = $.browser.versionNumber >= 18;
			}
			if ( $.browser.mozilla ) {
				success = $.browser.versionNumber >= 4;
			}
			if ( $.browser.msie ) {
				success = $.browser.versionNumber >= 10;
			}
			if ( $.browser.opera ) {
				success = $.browser.versionNumber >= 15;
			}
			// let them know
			if (!success) {
				showError("browser");
				return false;
			}
			hideError();
			return true;
		}
		function render () {
			$(document).bind("contextmenu", Func.stop);
			body = $("#body-inner");
			error = $("#body-error");
			error_inner = $("#body-error-inner");
			tooltip = $("#tooltip");
			if ( !supported() ) {
				StageProxy.addEventListener("onResize", resize_error);
			} else {
				FormDialog.initialize();
				Overlay.initialize();
				Content.initialize();
				Dialog.initialize();
				if ( !setup.device.touch ) {
					body.mousemove(ttposition);
				}
			}
		}
		/* public methods
			*/
		this.createToolTip = function (text, isFilename) {
			if (setup.device.touch) {
				return;
			}
			if (isFilename) {
				var bits = text.split(".");
				bits.pop();
				text = bits.join(".");
			}
			if (text=="") {
				this.killToolTip();
				return;
			}
			tooltip.html(text).show();
			tooltip_visible = true;
		};
		this.killToolTip = function () {
			if (setup.device.touch) {
				return;
			}
			tooltip.hide();
			tooltip_visible = false;
		};
		this.device = function () {
			return setup.device;
		};
		this.initialize = function (obj) {
			setup = obj;
			classname = setup.init;
				classname = classname.split(" ");
				classname = classname.pop();
			StageProxy = classes.StageProxy;
			Dialog = classes.Dialog;
			Overlay = classes.Overlay;
			FormDialog = classes.elements.FormDialog;
			L10N = classes.helpers.L10N;
			Content = classes.content[classname];
			Func = classes.helpers.Func;
			render();
		};
	}
	return new Constructor();
}());

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.StageProxy = (function () {
	function Constructor () {
		/* private properties
			*/
		var instance = this;
		var resize_interval_id;
		var resize_interval = 500;
		/* private methods
			*/
		function fire () {
			instance.dispatch("onResize");
		}
		function resize () {
			clearTimeout(resize_interval_id);
			resize_interval_id = setTimeout(fire, resize_interval);
		}
		/* public methods
			*/
		this.width = function() {
			var w = $(window).width();
			return Math.round(w);
		};
		this.height = function() {
			var h = $(window).height();
			return Math.round(h);
		};
		/* constructor
			*/
		$(window).resize(resize);
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.elements.ContactForm = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy;
		var Dialog; // shortcut
		var L10N;
		/* private properites
			*/
		// jquery containers
		var form;
		var inputs;
		/* private methods
			*/
		function fulfilled () {
			var response = true;
			form.find(".Required").each(function () {
				var obj = $(this);
				var input = obj.find("input");
				if (obj.hasClass("Dropdown")) {
					input = obj.find("select");
				} else if (obj.hasClass("Area")) {
					input = obj.find("textarea");
				}
				var val = input.val();
				if (obj.hasClass("Checkbox")) {
					val = obj.find("input:checked").val();
				}
				if (obj.hasClass("Radio")) {
					val = obj.find("input:checked").val();
				}
				obj.removeClass("Focused");
				obj.removeClass("Invalid");
				obj.addClass("Default");
				if ( val=="" || val==undefined ) {
					obj.removeClass("Default");
					obj.addClass("Invalid");
					if (response==true) {
						response = false;
					}
				}
			});
			return response;
		}
		function resize () {
			var sw = StageProxy.width();
			if (sw>600) {
				var sh = StageProxy.height();
				$(".Contact .Column2 .Inner").css("min-height", sh-65);
			} else {
				$(".Contact .Column2 .Inner").css("min-height", "auto");
			}
		}
		function submit_response (data) {
			var success = data=="contact_form_send_success";
			inputs.removeAttr("disabled");
			Dialog.options({
				modal: false,
				title: ( success ? L10N.get("contact", "contact_form_title_success")  : L10N.get("contact", "contact_form_title_fail") ),
				description: L10N.get("contact", data)
			});
			Dialog.draw();
			if (success) {
				form[0].reset();
			}
		}
		function submit (e) {
			e.preventDefault();
			// check the required fields
			if (!fulfilled()) {
				Dialog.options({
					modal: false,
					title: L10N.get("contact", "contact_form_title_fail"),
					description: L10N.get("contact", "highlighted_fields_required")
				});
				Dialog.draw();
				return;
			}
			//loading();
			// ok, everything checks out let's submit
			var postobj = {
				action: "send_email",
				set_url: window.location.href
			};
			form.find(".Input input, .Dropdown select, .Date input, .Area textarea, .Checkbox input:checked, .Radio input:checked").each(function () {
				var input = $(this);
				var name = input.attr("name");
				var val = input.val();
				if ( val!="" ) {
					if (!postobj[name]) {
						postobj[name] = val;
					} else {
						postobj[name] += "\n" + val;
					}
				}
			});
			inputs.attr("disabled", true);
			$.post( APP_ROOT + "vend-proofing-gateway.php", postobj, submit_response );
		}
		function draw () {
			// assign jquery selectors
			form = 			$("#contact-form");
			inputs = 		form.find("input, textarea, select");
			// form
			form
				.submit(submit)
				.find("input, textarea")
					.focus(function () {
						$(this).parent().removeClass("Default");
						$(this).parent().addClass("Focused");
					})
					.blur(function () {
						$(this).parent().removeClass("Focused");
						$(this).parent().addClass("Default");
					})
					.blur();
			if (!Modernizr.inputtypes.date) {
				$('input[type=date]').each(function() {
					var $input = $(this);
					$input.datepicker({
						dateFormat: 'yy-mm-dd'
					});
				});
			}
		}
		function init () {
			draw();
			resize();
		}
		function lateinit () {
			StageProxy.addEventListener("onResize", resize);
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		/* public methods
			*/
		this.initialize = function () {
			StageProxy = classes.StageProxy;
			L10N = classes.helpers.L10N;
			Dialog = classes.Dialog;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, newcap: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.elements.Controlbar = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy; // shortcut
		var Shell; // shortcut
		var Dialog; // shortcut
		var L10N; // shortcut
		var Session; // shortcut
		var Overlay; // shortcut
		var ContactForm; // shortcut
		var Display; // shortcut
		var Func; // shortcut
		var Cart; // shortcut
		var Checkout; // shortcut
		var Package; // shortcut
		/* private properites
			*/
		var instance = this;
		var provider_lookup = {
			set: {
				top: 0,
				bottom: -15,
				label: null,
				view: null,
				container: null,
				current: null,
				options: null,
				index: -1
			},
			favorites: {
				top: 0,
				bottom: -15,
				view: null,
				label: null,
				container: null,
				current: null,
				options: null,
				index: -1
			},
			cart:{
				top: 0,
				bottom: -15,
				view: null,
				label: null,
				container: null,
				current: null,
				options: null,
				index: -1
			}
		};
		var playing = true;
		var state = "";
		var lastview = "wall";
		// jquery holders
		var container = null;
		var icon_mail = null;
		var icon_music = null;
		var jp_player = null;
		/* private methods
			*/
		function count () {
			var cartitems = Session.getCart();
			var tally = 0;
			var i;
			for (i=0; i<cartitems.length; ++i) {
				tally += parseInt(cartitems[i].quantity, 10);
			}
			tally += Session.getDownloadsLength();
			var products_parsed = Session.getPackagesParsed();
			for (i=0; i<products_parsed.length; ++i) {
				if (products_parsed[i].total==0) {
					tally += 1;
				}
			}
			return tally;
		}
		function clear_fav_confirm () {
			instance.dispatch("onPageView", [ "browse", "wall", "set", 0, 0 ]);
			Session.purge("favorites");
		}
		function clear_fav_dialog () {
			Dialog.options({
				unique: 		"controlbarfavoriteclear",
				modal: 			true,
				title: 			L10N.get("ordering", "cart_delete_confirmation_title"),
				description: 	L10N.get("ordering", "cart_delete_confirmation_description"),
				confim: 		clear_fav_confirm
			});
			Dialog.draw();
		}
		function download_all_confirm (group, quality) {
			Session.downloadAll(group, quality);
			instance.dispatch("onPageView", [ "cart" ]);
		}
		function downloadAll (group, quality) {
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var downloads_taxable_bool = Checkout.settings().downloads.tax;
			var count = group=="cart" ? Overlay.getImageCount() : Session.getFavoritesLength();
			var price = group=="cart" ? Checkout.settings().downloads.all[quality] : Checkout.settings().downloads[quality].price;
				price = parseFloat(price);
			if ( Checkout.settings().downloads.all.flat==false || group!="cart" ) {
				price = count*price;
			}
				if ( purchase_price_includes_tax_bool && downloads_taxable_bool ) {
					price = Func.addSalesTax(price);
				}
				price = Func.getFormattedPrice(price);
			var description = L10N.get("ordering", "cart_download_all_confirmation_description");
			var quality_label = L10N.get("ordering", "sidebar_" + quality + "_resolution");
			description = description.split("{QUALITY}").join(quality_label);
			description = description.split("{QUANTITY}").join(count);
			description = description.split("{PRICE}").join(price);
			Dialog.options({
				modal: 			true,
				title: 			L10N.get("ordering", "cart_download_all_confirmation_title"),
				description: 	description,
				args: 			arguments,
				confim: 		download_all_confirm
			});
			Dialog.draw();
		}
		function setActive (obj, type) {
			var popups = ["set", "favorites", "cart"];
			var i, provider;
			for (i=0; i<popups.length; ++i) {
				provider = provider_lookup[popups[i]];
				provider.view.removeClass("Active");
				provider.options.removeClass("Active");
				provider.index = -1;
				provider.current = null;
			}
			provider = provider_lookup[type];
			provider.index = obj.data("index");
			provider.current = provider.options.eq(provider.index);
			provider.current.addClass("Active");
			
		}
		function click (e) {
			var obj = $(this);
			var index = obj.data("index");
			var provider = provider_lookup[obj.data("provider")];
			if (obj.data("key")=="clear-favorites") {
				clear_fav_dialog();
				Func.stop(e);
				return false;
			}
			if (obj.data("key")=="download-all-cart-high") {
				downloadAll("cart", "high");
				Func.stop(e);
				return false;
			}
			if (obj.data("key")=="download-all-cart-low") {
				downloadAll("cart", "low");
				Func.stop(e);
				return false;
			}
			if (obj.data("key")=="download-favorites-cart-high") {
				downloadAll("favorites", "high");
				Func.stop(e);
				return false;
			}
			if (obj.data("key")=="download-favorites-cart-low") {
				downloadAll("favorites", "low");
				Func.stop(e);
				return false;
			}
			if (obj.data("key")=="cart") {
				instance.dispatch("onPageView", [ "cart" ]);
				provider.container.stop().animate({ bottom: provider.bottom });
				Func.stop(e);
				return false;
			}
			if (obj.data("key")=="checkout") {
				Cart.checkout();
				provider.container.stop().animate({ bottom: provider.bottom });
				Func.stop(e);
				return false;
			}
			if (obj.data("key")=="packages") {
				instance.dispatch("onPageView", [ "packages", 0 ]);
				provider.container.stop().animate({ bottom: provider.bottom });
				Func.stop(e);
				return false;
			}
			if (provider.index==index) {
				return false;
			}
			var view = Overlay.getBrowseView();
			if ( lastview!=Overlay.getBrowseView() ) {
				view = "wall";
			}
			instance.dispatch("onPageView", [ "browse", view, obj.data("provider"), index, 0 ]);
			provider.container.stop().animate({ bottom: provider.bottom });
			Func.stop(e);
			return false;
		}
		function open () {
			/*var obj = $(this);
			var val = obj.data("value");
			obj.find("option[data-key]").removeAttr("disabled");
			if (Overlay.getWallView()==obj.data("provider")) {
				obj.val(val);
				obj.find("option:selected").attr("disabled", "disabled");
			}*/
		}
		function change (e) {
			var obj = $(this);
			//get our info since we're gonna wipe it
			var selected = obj.find("option:selected");
			var key = selected.data("key");
			var provider = selected.data("provider");
			var index = selected.data("index");
			var lookup = provider_lookup[provider];
			// ok now wipe it, and select the first one
			var val = selected.val();
			obj.data("value", val);
			var options = obj.find("option");
			options.removeAttr("selected");
			options.eq(0).attr("selected", "selected");
			var key2, provider2;
			for (key2 in provider_lookup) {
				if (provider_lookup.hasOwnProperty(key2)) {
					if (key2==obj.data("provider")) {
						continue;
					}
					provider2 = provider_lookup[key2];
					provider2.view.data("value", "");
				}
			}
			// now do whatever
			if (key=="clear-favorites") {
				clear_fav_dialog();
				Func.stop(e);
				return false;
			}
			if (key=="download-all-cart-high") {
				downloadAll("cart", "high");
				Func.stop(e);
				return false;
			}
			if (key=="download-all-cart-low") {
				downloadAll("cart", "low");
				Func.stop(e);
				return false;
			}
			if (key=="download-favorites-cart-high") {
				downloadAll("favorites", "high");
				Func.stop(e);
				return false;
			}
			if (key=="download-favorites-cart-low") {
				downloadAll("favorites", "low");
				Func.stop(e);
				return false;
			}
			if (key=="cart") {
				instance.dispatch("onPageView", [ "cart" ]);
				Func.stop(e);
				return false;
			}
			if (key=="checkout") {
				Cart.checkout();
				Func.stop(e);
				return false;
			}
			if (key=="packages") {
				instance.dispatch("onPageView", [ "packages", 0 ]);
				Func.stop(e);
				return false;
			}
			if (lookup.index==index) {
				return false;
			}
			var view = Overlay.getBrowseView();
			if ( lastview!=Overlay.getBrowseView() ) {
				view = "wall";
			}
			instance.dispatch("onPageView", [ "browse", view, provider, index, 0 ]);
			Func.stop(e);
			return false;
		}
		function resetIndex (i) {
			$(this).data("index", i);
		}
		function resize () {
			var key, provider, options, label, width;
			if (Shell.device().touch) {
				for (key in provider_lookup) {
					if (provider_lookup.hasOwnProperty(key)) {
						provider = provider_lookup[key];
						provider.options = provider.view.find("option[data-key]");
						provider.options
							.removeAttr("disabled")
							.data("provider", key)
							.each(resetIndex);
						options = provider.view.find("option");
						options.removeAttr("selected");
						options.eq(0).attr("selected", "selected");
					}
				}
			} else {
				for (key in provider_lookup) {
					if (provider_lookup.hasOwnProperty(key)) {
						provider = provider_lookup[key];
						label = provider.label.html();
						provider.view.width("auto");
						provider.view.find("ul").width("auto");
						provider.label.html("0000");
						width = Math.max(provider.view.width(), provider.view.find("ul").width());
						provider.options = provider.view.find("li[data-key]");
						provider.options
							.off()
							.click(click)
							.data("provider", key)
							.each(resetIndex);
						provider.label.html(label);
						provider.view.width(width);
						provider.view.find("ul").width(width-2);
						provider.top = (provider.container.height())*-1;
						provider.bottom = provider.container.css("bottom");
					}
				}
			}
			center();
		}
		function onSessionLoaded () {
			$("#controlbar-inner").show();
			var page_breakpoint = Overlay.getMaxImageCount();
			var favorites = Session.getFavorites();
			var favorite_pages = [];
			var i;
			var partition;
			var provider;
			if (favorites.length<=page_breakpoint) {
				favorite_pages.push( L10N.get("ordering", "navigation_favorites_all") + " (" + favorites.length + ")" );
			} else {
				partition = Func.array_chunk(favorites, page_breakpoint);
				for (i=0; i<partition.length; ++i) {
					favorite_pages.push( L10N.get("ordering", "navigation_favorites_page") + " " + (i+1) + " (" + partition[i].length + ")");
				}
			}
			var cartitems = Session.getCart();
			var cart_length = count();
			if (Shell.device().touch) {
				provider = provider_lookup.favorites;
				if (favorites.length>0) {
					provider.view
						.removeAttr("disabled")
						.html('<option disabled="disabled">' + L10N.get("ordering", "navigation_favorites_title") + " (" + favorites.length + ")" + "</option>");
					for (i=0; i<favorite_pages.length; ++i) {
						provider.view.append('<option data-key="">' + favorite_pages[i] + "</option>");
					}
					provider.view.append('<option disabled="disabled">-----</option>');
					provider.view.append('<option data-key="clear-favorites">' + L10N.get("ordering", "navigation_clear_favorites") + "</option>");
					if (Checkout.settings().downloads.use) {
						provider.view.append('<option disabled="disabled">-----</option>');
						if (Checkout.settings().downloads.high.use) {
							provider.view.append('<option data-key="download-favorites-cart-high">' + L10N.get("ordering", "navigation_download_all_high") + '</option>');
						}
						if (Checkout.settings().downloads.low.use) {
							provider.view.append('<option data-key="download-favorites-cart-low">' + L10N.get("ordering", "navigation_download_all_low") + '</option>');
						}
					}
				} else {
					provider.view
						.attr("disabled", "disabled")
						.html("<option>" + L10N.get("ordering", "navigation_no_favorites") + "</option>");
				}
				provider = provider_lookup.cart;
				if (cart_length>0) {
					provider.view
						.removeAttr("disabled")
						.html('<option disabled="disabled">' + L10N.get("ordering", "navigation_cart_title") + " (" + cart_length + ")" + "</option>");
					provider.view
						.append('<option data-key="cart">' + L10N.get("ordering", "navigation_view_cart") + "</option>")
						.append('<option data-key="checkout">' + L10N.get("ordering", "navigation_checkout") + "</option>");
				} else {
					provider.view
						.attr("disabled", "disabled")
						.html("<option>" + L10N.get("ordering", "navigation_cart_empty") + "</option>");
				}
			} else {
				provider = provider_lookup.favorites;
				if (favorites.length>0) {
					provider.view.removeClass("Disabled");
					provider.title.html( L10N.get("ordering", "navigation_favorites_title") );
					provider.label.html( "(" + favorites.length + ")" );
					provider.container
						.show()
						.empty();
					for (i=0; i<favorite_pages.length; ++i) {
						provider.container.append('<li data-key="' + i + '">' + favorite_pages[i] + "</li>");
					}
					provider.container
						.append('<li class="BreakLine"></li>')
						.append('<li data-key="clear-favorites">' + L10N.get("ordering", "navigation_clear_favorites") + "</li>");
					if (Checkout.settings().downloads.use) {
						provider.container.append('<li class="BreakLine"></li>');
						if (Checkout.settings().downloads.high.use) {
							provider.container.append('<li data-key="download-favorites-cart-high">' + L10N.get("ordering", "navigation_download_all_high") + '</li>');
						}
						if (Checkout.settings().downloads.low.use) {
							provider.container.append('<li data-key="download-favorites-cart-low">' + L10N.get("ordering", "navigation_download_all_low") + '</li>');
						}
					}
				} else {
					provider.view.addClass("Disabled");
					provider.title.html( L10N.get("ordering", "navigation_no_favorites") );
					provider.label.html("(0)");
					provider.container.empty().hide();
				}
				provider = provider_lookup.cart;
				if (cart_length>0) {
					provider.view.removeClass("Disabled");
					provider.title.html( L10N.get("ordering", "navigation_cart_title") );
					provider.label.html( "(" + cart_length + ")" );
					provider.container
						.show()
						.empty();
					provider.container
						.append('<li data-key="cart">' + L10N.get("ordering", "navigation_view_cart") + "</li>")
						.append('<li data-key="checkout">' + L10N.get("ordering", "navigation_checkout") + "</li>");
				} else {
					provider.view.addClass("Disabled");
					provider.title.html( L10N.get("ordering", "navigation_cart_empty") );
					provider.label.html("(0)");
					provider.container.empty().hide();
				}
			}
			resize();
		}
		function toggle_soundtrack () {
			if (playing==true) {
				playing = false;
				icon_music.addClass("Paused");
				jp_player.jPlayer("pause");
			} else {
				playing = true;
				icon_music.removeClass("Paused");
				jp_player.jPlayer("play");
			}
		}
		function release (e) {
			if ($(this).data("state")=="closed") {
				$(this).mouseenter();
			} else {
				$(this).mouseleave();
			}
			Func.stop(e);
			return false;
		}
		function mouseover (e) {
			$(this).data("state", "open");
			var provider = provider_lookup[$(this).data("provider")];
			provider.container.stop().animate({ bottom: provider.top });
			Func.stop(e);
			return false;
		}
		function mouseout (e) {
			$(this).data("state", "closed");
			var provider = provider_lookup[$(this).data("provider")];
			provider.container.stop().animate({ bottom: provider.bottom });
			Func.stop(e);
			return false;
		}
		function draw () {
			// cache our jquery objects
			container = $("#controlbar");
			icon_mail = $("#icon-mail");
			icon_music = $("#icon-music");
			jp_player = $("#jp-player");
			// disable click-throughs
			container.click(function (e) {
				Func.stop(e);
				return false;
			});
			// add clicks to the mail and music icons
			icon_mail.click(function () {
				instance.dispatch("onPageView", [ "contact" ]);
			});
			icon_music.click(function () {
				toggle_soundtrack();
			});
			// enable the supernav functionality
			var popups = ["set", "favorites", "cart"];
			var i, key, view, options, provider;
			if (Shell.device().touch) {
				for (i=0; i<popups.length; ++i) {
					key = popups[i];
					view = $("#controlbar-"+key);
					options = view.find("option[data-key]");
					provider = provider_lookup[popups[i]];
					options
						.data("provider", key)
						.each(resetIndex);
					view
						.data("value", options.eq(0).val())
						.data("provider", key)
						.off()
						.mousedown(open)
						.change(change);
					provider.view = view;
					provider.options = options;
				}
			} else {
				var view_title, view_label, view_container;
				for (i=0; i<popups.length; ++i) {
					key = popups[i];
					view = $("#controlbar-"+key);
					view_title = view.find("span").eq(1);
					view_label = view.find("span").eq(2);
					view_container = view.find("ul");
					options = view.find("li[data-key]");
					provider = provider_lookup[popups[i]];
					options
						.off()
						.click(click)
						.data("provider", key)
						.each(resetIndex);
					view
						.data("state", "closed")
						.data("provider", key)
						.click(release)
						.mouseenter(mouseover)
						.mouseleave(mouseout);
					provider.view = view;
					provider.container = view_container;
					provider.title = view_title;
					provider.label = view_label;
					provider.options = options;
				}
			}
			// start up our wall view
			$(window).hashchange(onHashChange);
			var init = location.hash;
			var UNDEF;
			if ( !init || init=="" || init==null || init==UNDEF ) {
				onPageView([ "browse", "wall", "set", 0, 0 ]);
			} else {
				$(window).hashchange();
			}
			instance.addEventListener("onPageView", onPageView);
		}
		function onHashChange (eo) {
			var hash = location.hash;
			var bits = hash.split("/");
				bits.shift();
				bits.pop();
			updateViews(bits);
		}
		function onPageView (eo) {
			var hash = "#/" + eo.join("/") + "/";
			if (location.hash!=hash) {
				location.hash = "#/" + eo.join("/") + "/";
			}
		}
		function updateViews (eo) {
			state = eo[0];
			$("#overlay-cartview,#image-wall-wrapper,#overlay-container,#overlay-packages,#overlay-checkout,#overlay-clickwrap,#overlay-contact").hide();
			switch (state) {
				case "browse" :
					lastview = eo[2];
					Overlay.setBrowseView(eo[1]);
					Overlay.setWallView(eo[2]);
					Overlay.setIndex(parseInt(eo[3], 10));
					Overlay.setBrowseIndex(parseInt(eo[4], 10));
					Display.update();
					break;
				case "contact" :
					$("#overlay-contact").show();
					break;
				case "cart" :
					$("#overlay-cartview").show();
					break;
				case "tos" :
					$("#overlay-clickwrap").show();
					break;
				case "checkout" :
					$("#overlay-checkout").show();
					Checkout.update();
					break;
				case "packages" :
					Package.setBackStyle(eo[1]);
					$("#overlay-packages").show();
					break;
			}
		}
		function soundtrack () {
			// setup our music
			var playlist = Overlay.getPlaylist();
			if (playlist.length>0) {
				var player = new jPlayerPlaylist({
					jPlayer: "#jp-player",
					cssSelectorAncestor: "#jp-container"
				}, playlist, {
					playlistOptions: {
						autoPlay: true
					},
					wmode: "window",
					swfPath: APP_ROOT + 'vend-proofing-core/swf/Jplayer.swf',
					solution: 'html, flash',
					supplied: 'mp3',
					volume: 50,
					loop: true
				});
				player.option();
			}
		}
		function noscroll () {
			container.bind("touchmove", Func.stop);
			container.mousewheel(Func.stop);
		}
		function rescroll () {
			container.unbind("touchmove", Func.stop);
			container.unmousewheel();
		}
		function center () {
			$("#controlbar").removeClass("Compact");
			var minx = $("#controlbar-left").width();
			var sw = StageProxy.width();
			var cw = $("#controlbar-inner").width();
			var center = (sw-cw)/2;
			var xpos = Math.max(minx, center);
			var remainder = sw - minx - cw - $("#controlbar-right").width();
			if (remainder<0) {
				xpos = center;
				$("#controlbar").addClass("Compact");
			}
			$("#controlbar-inner").css("left", xpos);
		}
		function lateinit () {
			StageProxy.addEventListener("onResize", center);
			Session.addEventListener("onSessionLoaded", onSessionLoaded);
			Session.addEventListener("onSessionCart", onSessionLoaded);
			Session.addEventListener("onSessionFavorites", onSessionLoaded);
			Overlay.addEventListener("onOpen", noscroll);
			Overlay.addEventListener("onClose", rescroll);
			center();
		}
		function init () {
			draw();
			resize();
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		/* public methods
			*/
		this.start = function() {
			soundtrack();
		};
		this.getState = function() {
			return state;
		};
		this.initialize = function() {
			StageProxy = classes.StageProxy;
			L10N = classes.helpers.L10N;
			Shell = classes.Shell;
			Session = classes.Session;
			Overlay = classes.Overlay;
			Dialog = classes.Dialog;
			ContactForm = classes.elements.ContactForm;
			Func = classes.helpers.Func;
			Cart = classes.overlay.Cart;
			Checkout = classes.overlay.Checkout;
			Package = classes.overlay.Package;
			Display = classes.content.Display;
			render();
			resize();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.elements.FormDialog = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy;
		var Cookie;
		var Shell; // shortcut
		var Func;
		/* private properites
			*/
		var defaults = {
			view: 					"init",
			inline: 				false,
			modal: 					false,
			bg_image: 				["", "", ""],
			description: 			"",
			footer: 				"",
			description_markdown: 	false,
			footer_markdown: 		false,
			prefill_variable_name: 	"",
			prefill_variable_value: "",
			field_password: 		false,
			field_label: 			"",
			field_type: 			"text",
			submit_label: 			"",
			error_label: 			"",
			confirm_label: 			"",
			cancel_label: 			"",
			submit:				false,
			cancel:				false,
			confirm:				false
		};
		var opt = {};
		var instance = this;
		var open = false;
		var container;
			var screen;
			var background;
			var dialog;
				var description;
				var form;
				var footer;
					var field;
					var submit_obj;
					var cancel1_obj;
				var response;
					var error;
					var confirm_obj;
					var cancel2_obj;
				var screen2;
		/* private methods
			*/
		function resize () {
			if (!open) {
				container.show();
			}
			var cheight = Math.max(form.height(), response.height());
			$("#form-dialog-content").height(cheight);
			var sw = StageProxy.width();
			var sh = StageProxy.height();
			if (!opt.inline) {
				var dw = dialog.width();
				var dh = dialog.outerHeight();
				dialog.css({
					top: (sh-dh)/2,
					left: (sw-dw)/2
				});
			}
			if (opt.bg_image) {
				if (opt.bg_image[0]!="") {
					var img = background.find("img");
					var iw = img.attr("width");
					var ih = img.attr("height");
					var nw = sw;
					var nh = nw*(ih/iw);
					if (nh<sh) {
						nh = sh;
						nw = nh*(iw/ih);
					}
					img.width(nw).height(nh)
						.offset({
							top: (sh-nh)/2,
							left: (sw-nw)/2
						});
				}
			}
			if (!open) {
				container.hide();
			}
		}
		function loading () {
			screen2.show();
			screen2.css('z-index', 3);
			response.css('opacity', .5);
			form.css('opacity', .5);
			dialog.progress();
		}
		function showForm () {
			opt.view = "form";
			dialog.progress(true);
			response.css('opacity', 1);
			form.css('opacity', 1);
			response.css('z-index', 1).hide();
			form.css('z-index', 2).show();
			screen2.hide();
			resize();
		}
		function showError () {
			opt.view = "error";
			dialog.progress(true);
			response.css('opacity', 1);
			form.css('opacity', 1);
			form.css('z-index', 1).hide();
			response.css('z-index', 2).show();
			screen2.hide();
			resize();
		}
		function change () {
			submit_obj.attr("disabled", "disabled");
			if (field.val()!="") {
				submit_obj.removeAttr("disabled");
			}
			if (opt.prefill_variable_name) {
				Cookie.set(opt.prefill_variable_name, field.val(), 365);
			}
		}
		function destroy () {
			field.blur();
			dialog.progress(true);
			opt = {};
			container.hide();
			open = false;
			instance.dispatch("onClose");
		}
		function confirm () {
			if (opt.confirm) {
				opt.confirm();
			} else {
				showForm();
			}
		}
		function cancel () {
			if (opt.cancel) {
				opt.cancel();
			} else {
				destroy();
			}
		}
		function submit () {
			if (opt.submit) {
				loading();
				opt.submit();
			} else {
				destroy();
			}
		}
		function keyevent (event) {
			if (open) {
				switch (event.which) {
					case 13 : // Key.ENTER :
						if ( opt.view=="form" && submit_obj.attr("disabled")!="disabled" ) {
							submit();
						} else if ( opt.view=="error" ) {
							confirm();
						}
						Func.stop(event);
						return false;
					default :
						if (opt.field_label!="") {
							change();
						}
				}
			}
		}
		function click (event) {
			switch ($(this).attr("id")) {
				case screen.attr("id") :
					if (opt.modal) {
						cancel();
					}
					break;
				case confirm_obj.attr("id") :
					confirm();
					break;
				case cancel1_obj.attr("id") :
				case cancel2_obj.attr("id") :
					cancel();
					break;
				case submit_obj.attr("id") :
					submit();
					break;
			}
			Func.stop(event);
			return false;
		}
		function create () {
			// listen for key events
			// if it's inline, set the class
			if (opt.inline) {
				container.addClass("Inline");
			} else {
				container.removeClass("Inline");
			}
			if (opt.bg_image[0]!="") {
				container.addClass("BgImage");
				background
					.show()
					.find("img")
						.attr("src", opt.bg_image[0])
						.attr("width", opt.bg_image[1])
						.attr("height", opt.bg_image[2]);
			} else {
				container.removeClass("BgImage");
				background
					.hide()
					.find("img")
						.attr("src", "")
						.attr("width", "")
						.attr("height", "");
			}
			background.toggle(opt.bg_image!="");
			// decide if the form is pre-filled
			var prefill_value = "";
			if (opt.prefill_variable_name) {
				prefill_value = Cookie.get(opt.prefill_variable_name);
			}
			// blurb setup
			description.removeClass("Description");
			if (opt.description_markdown) {
				description.addClass("Description");
			}
			description
				.html(opt.description)
				.toggle(opt.description!="");
			// field -- choose if password or not
			field = $("#form-dialog-field");
			field.val(prefill_value)
				.removeAttr("type")
				.prop("type", opt.field_type)
				.attr("placeholder", opt.field_label)
				.toggle(opt.field_label!="");
			// submit button
			submit_obj.html(opt.submit_label).attr("disabled", "disabled");
			if (prefill_value!=""||opt.field_label=="") {
				submit_obj.removeAttr("disabled");
			}
			// cancel button
			cancel1_obj.html(opt.cancel_label).toggle(opt.modal==true);
			// error field
			error.html(opt.error_label).toggle(opt.error_label!="");
			// confirm button
			confirm_obj.html(opt.confirm_label);
			// cancel button
			cancel2_obj.html(opt.cancel_label).toggle(opt.modal==true);
			// blurb setup
			footer.removeClass("Description");
			if (opt.footer_markdown) {
				footer.addClass("Description");
			}
			footer
				.html(opt.footer)
				.toggle(opt.footer!="");
			// screen2
			screen2.hide();
			// display it's initial state
			open = true;
			container.show();
			form.hide();
			response.hide();
			if (opt.view=="init"||opt.view=="form") {
				showForm();
			} else {
				showError();
			}
			// resize
			resize();
			instance.dispatch("onOpen");
		}
		function render () {
			// assign jquery selectors
			container = 	$("#form-dialog-container");
			screen = 		$("#form-dialog-screen");
			background = 	$("#form-dialog-background");
			dialog = 		$("#form-dialog");
			description = 	$("#form-dialog-description");
			footer = 		$("#form-dialog-footer");
			form = 			$("#form-dialog form");
			submit_obj = 	$("#form-dialog-submit");
			cancel1_obj = 	$("#form-dialog-cancel");
			response = 		$("#form-dialog-response");
			error = 		$("#form-dialog-error");
			confirm_obj = 	$("#form-dialog-confirm");
			cancel2_obj = 	$("#form-dialog-cancel2");
			screen2 = 		$("#form-dialog-screen2");
			// submit
			screen.click(click);
			submit_obj.click(click);
			cancel1_obj.click(click);
			confirm_obj.click(click);
			cancel2_obj.click(click);
			// listen to stage
			if (!Shell.device().touch) {
				container.mousewheel(Func.stop);
			} else {
				container.bind("touchmove", Func.stop);
			}
			$("body").keyup(keyevent);
			StageProxy.addEventListener("onResize", resize);
		}
		/* public methods
			*/
		this.kill = function () {
			destroy();
		};
		this.options = function(obj) {
			var prop;
			for (prop in defaults) {
				if (defaults.hasOwnProperty(prop)) {
					opt[prop] = defaults[prop];
				}
			}
			for (prop in obj) {
				if (obj.hasOwnProperty(prop)) {
					opt[prop] = obj[prop];
				}
			}
		};
		this.draw = function() {
			create();
		};
		this.error = function () {
			showError();
		};
		this.inputvalue = function () {
			return $.trim(field.val().split("\t").join("").split("\n").join("").split("\r").join(""));
		};
		this.initialize = function () {
			Func = classes.helpers.Func;
			StageProxy = classes.StageProxy;
			Cookie = classes.helpers.Cookie;
			Shell = classes.Shell;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, bitwise: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.elements.Graphic = function () {
	/* private properites
		*/
	var flag_encode = true;
	var flag_resample = "auto";
	var flag_width = 0;
	var flag_height = 0;
	var flag_fitstyle = "noBorder";
	var flag_watermark = false;
	var flag_source = {};
	/* private methods
		*/
	function isVideo () {
		return (flag_source.type=="FLV"||flag_source.type=="MP4");
	}
	function toHex (num) {
		var result = '';
		var digitArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
		var start = true;
		var i=32, digit;
		while(i>0) {
			i-=4;
			digit = (num>>i) & 0xf;
			if (!start||digit!=0){
				start = false;
				result += digitArray[digit];
			}
		}
		return (result==''?'0':result);
	}
	function pad (str, len, chr) {
		var result = str;
		var i;
		for (i=str.length; i<len; i++){
			result = chr + result;
		}
		return result;
	}
	function encodeHex (str) {
		var result = "";
		var i;
		for (i=0; i<str.length; i++){
			result += pad(toHex(str.charCodeAt(i)&0xff), 2, '0');
		}
		return result;
	}
	/* public methods
		*/
	this.encode = function(bool) {
		flag_encode = bool;
	};
	this.resample = function(type) {
		flag_resample = type;
	};
	this.watermark = function(bool) {
		flag_watermark = bool;
	};
	this.letterbox = function(bool) {
		flag_fitstyle = bool ? "letterBox" : "noBorder";
	};
	this.setSize = function(width, height) {
		if (width) {
			flag_width = width;
		}
		if (height) {
			flag_height = height;
		}
	};
	this.provider = function(obj) {
		var localpath = obj.src;
		if ( !localpath && obj.parent && obj.child) {
			localpath = "vend-proofing-data/storage/" + obj.parent + "/" + obj.child;
		}
		if ( obj.parent.indexOf("zip")!=-1 ) {
			obj.type = "JPG";
		}
		if ( !obj.type || obj.type=="" ) {
			obj.type = localpath.substring(localpath.lastIndexOf(".")+1).toUpperCase();
		}
		flag_source = obj;
	};
	this.source = function() {
		var src_path = APP_ROOT + "vend-proofing-data/storage/" + flag_source.parent + "/" + flag_source.child + (isVideo()?".snapshot.jpg":"");
		var src_type = isVideo() ? "JPG" : flag_source.type;
		/* if the resample mechanism is on, reconstruct the url
			*/
		if (	flag_resample!="none"	&&
			(src_type=="PNG"||src_type=="GIF"||src_type=="JPEG"||src_type=="JPG")
		) {
			/* {PARENT_NAME}:{CHILD_NAME}:{WIDTH}:{HEIGHT}:{EXACT}:{FORMAT}:{QUALITY}:{CACHE}:{WATERMARK}:{WATERMARK_NAME}:{WATERMARK_X%}:{WATERMARK_Y%}:{WATERMARK_ALPHA}:{CROSSHAIRS}:{CROSSHAIRS_COLOR}:{CROSSHAIRS_ALPHA}
				*/
			var path = APP_ROOT + "vend-proofing-resample.php";
			var query = "";
			/* decide on base query
				*/
			query += flag_source.parent + ":" + flag_source.child + (isVideo()?".snapshot.jpg":"");
			if (flag_resample=="postal") {
				/* round to the nearest 50 pixel increment
					*/
				var image_width = (Math.ceil(flag_width/50)*50);
				var image_height = (Math.ceil(flag_height/50)*50);
				switch (flag_fitstyle) {
					case "letterBox" :
						query += ":" + image_width + ":" + image_height + ":0";
						break;
					case "noBorder" :
						if (image_width>image_height) {
							query += ":" + image_width + ":" + ":1";
						} else {
							query += ":" + ":" + image_height + ":1";
						}
						break;
				}
			} else if (flag_resample=="auto") {
				switch (flag_fitstyle) {
					case "letterBox" :
						query += ":" + flag_width + ":" + flag_height + ":0";
						break;
					case "noBorder" :
						query += ":" + flag_width + ":" + flag_height + ":1";
						break;
				}
			}
			/* add the type
				*/
			query += "," + (flag_source.xoffset||50) + "," + (flag_source.yoffset||50);
			/* add the type
				*/
			query += ":" + src_type.toLowerCase();
			/* add the quality
				*/
			query += ":" + VEND_GRAPHIC_QUALITY + "," + (VEND_GRAPHIC_SHARPEN?"1":"0") + "," + (VEND_GRAPHIC_IMAGIC?"1":"0");
			/* add the cache flag
				*/
			query += ":1";
			/* add the watermarking
				*/
			query += ":" + (flag_watermark&&VEND_GRAPHIC_WATERMARK?"1":"0") + ":" + VEND_GRAPHIC_WATERMARK_ASSET + ":" + VEND_GRAPHIC_WATERMARK_X + ":" + VEND_GRAPHIC_WATERMARK_Y + ":" + VEND_GRAPHIC_WATERMARK_ALPHA;
			query += ":" + (flag_watermark&&VEND_GRAPHIC_CROSSHAIRS?"1":"0") + ":" + VEND_GRAPHIC_CROSSHAIRS_COLOR + ":" + VEND_GRAPHIC_CROSSHAIRS_ALPHA;
			/* set our final path
				*/
			if (flag_encode) {
				path += "?hash=" + encodeHex(query);
			} else {
				path += "?q=" + escape(query);
			}
			src_path = path;
		}
		return src_path;
	};
};

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.content.Contact = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var ContactForm;
		/* private properites
			*/
		/* private methods
			*/
		function render() {
			ContactForm.initialize();
		}
		/* public methods
			*/
		this.initialize = function() {
			ContactForm = classes.elements.ContactForm;
			render();
		};
	}
	return new Constructor();
}());

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.content.Expired = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var Func;
		var L10N;
		var FormDialog;
		/* private methods
			*/
		function dialog_confirm () {
			window.location = APP_ROOT;
		}
		function render() {
			Func.setDocumentTitle(L10N.get("general", "set_expired_error"));
			FormDialog.options({
				view: 			"error",
				error_label: 	L10N.get("general", "set_expired_error"),
				confirm_label: 	L10N.get("general", "return_to_gateway"),
				confirm: 		dialog_confirm
			});
			FormDialog.draw();
		}
		/* public methods
			*/
		this.initialize = function() {
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			FormDialog = classes.elements.FormDialog;
			render();
		};
	}
	return new Constructor();
}());

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.content.Login = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var Func;
		var L10N;
		var FormDialog;
		var Overlay;
		/* private properites
			*/
		/* private methods
			*/
		function dialog_response (str) {
			if (str!="d41d8cd98f00b204e9800998ecf8427e") {
				window.location.reload(true);
			} else {
				FormDialog.error();
			}
		}
		function dialog_submit () {
			$.post( APP_ROOT + "vend-proofing-gateway.php", {
				action: 	"validate_login",
				password: 	FormDialog.inputvalue(),
				suid: 		Overlay.pageid()
			}, dialog_response);
		}
		function render() {
			Func.setDocumentTitle(L10N.get("general", "password_required"));
			FormDialog.options({
				field_type: 		"password",
				field_label: 		L10N.get("general", "password_required"),
				submit_label: 		L10N.get("general", "dialog_submit"),
				error_label: 		L10N.get("general", "password_incorrect"),
				confirm_label: 		L10N.get("general", "dialog_confim"),
				submit: 			dialog_submit
			});
			FormDialog.draw();
		}
		/* public methods
			*/
		this.initialize = function() {
			Overlay = classes.Overlay;
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			FormDialog = classes.elements.FormDialog;
			render();
		};
	}
	return new Constructor();
}());

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.content.Splash = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var Func;
		var L10N;
		var FormDialog;
		var Shell;
		var ResampledImageQueue; // shortcut
		/* private properites
			*/
		var thumbnails = 			[];
		var splash_page_view = 		"wall";
		var current_suid = 			"";
		/* private methods
			*/
		function password_response (str) {
			if (str!="d41d8cd98f00b204e9800998ecf8427e") {
				window.location.assign( APP_ROOT + "?/" + URI_PAGE_PREFIX + "/" + current_suid + "/" );
			} else {
				FormDialog.error();
			}
		}
		function password_submit () {
			$.post( APP_ROOT + "vend-proofing-gateway.php", {
				action: 	"validate_login",
				password: 	FormDialog.inputvalue(),
				suid: 		current_suid
			}, password_response);
		}
		function password (suid) {
			current_suid = suid;
			FormDialog.options({
				modal: 				true,
				field_type: 		"password",
				cancel_label: 		L10N.get("general", "dialog_cancel"),
				field_label: 		L10N.get("general", "password_required"),
				submit_label: 		L10N.get("general", "dialog_submit"),
				error_label: 		L10N.get("general", "password_incorrect"),
				confirm_label: 		L10N.get("general", "dialog_confim"),
				submit: 			password_submit
			});
			FormDialog.draw();
		}
		function imageclick () {
			$(this).parent().find(".uiPushButton").trigger("click");
		}
		function click (event) {
			var child = $(this);
			if (child.hasClass("Disabled")) {
				return false;
				Func.stop(event);
			}
			if (child.hasClass("Login")) {
				password(child.attr("data-suid"));
				Func.stop(event);
			}
			var href = child.attr('href');
			window.location.href = href;
		}
		function wall () {
			var wallitems = $(".WallItem");
			wallitems.find(".uiPushButton").click(click);
			wallitems.find(".GraphicWrapper").click(imageclick);
			thumbnails = wallitems.find("img");
			ResampledImageQueue.addObject(thumbnails);
		}
		function dialog_response (str) {
			if (str=="true") {
				window.location.assign( APP_ROOT + "?/" + URI_PAGE_PREFIX + "/" + FormDialog.inputvalue() + "/" );
			} else {
				FormDialog.error();
			}
		}
		function dialog_submit () {
			$.post( APP_ROOT + "vend-proofing-gateway.php", {
				action: 	"validate_suid",
				suid: 		FormDialog.inputvalue()
			}, dialog_response);
		}
		function dialog () {
			var welcome = $(".WelcomeBox");
			FormDialog.options({
				inline: 			welcome.length>0,
				field_label: 		L10N.get("splash", "login_field_prompt"),
				submit_label: 		L10N.get("splash", "login_submit"),
				error_label: 		L10N.get("splash", "login_failure"),
				confirm_label: 		L10N.get("general", "dialog_confim"),
				submit: 			dialog_submit
			});
			FormDialog.draw();
		}
		function render() {
			if (splash_page_view=="wall") {
				wall();
			} else {
				dialog();
			}
		}
		/* public methods
			*/
		this.setPageView = function(str) {
			splash_page_view = str;
		};
		this.initialize = function() {
			Func = classes.helpers.Func;
			Shell = classes.Shell;
			L10N = classes.helpers.L10N;
			FormDialog = classes.elements.FormDialog;
			ResampledImageQueue = classes.helpers.ResampledImageQueue;
			render();
		};
	}
	return new Constructor();
}());

/*jslint browser: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.content.Display = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var L10N; // shortcut
		var Func; // shortcut
		var FormDialog; // shortcut
		var Controlbar; // shortcut
		var Checkout; // shortcut
		var StageProxy; // shortcut
		var Overlay; // shortcut
		var Shell; // shortcut
		var Session; // shortcut
		var Graphic; // shortcut
		/* private properites
			*/
		var lastview = 				0;
		var lastindex = 			0;
		var lastwidth = 			0;
		var inited = 				false;
		var row_height = 			200;
		var welcome_str = 			"";
		var intro_str = 			"";
		var bg_image_arr = 			["", "", ""];
		var children = 				[];
		var lookup = 				{};
		var thumb_loader_index = 	-1;
		var thumbnail_interval_id;
		var stack = 				[];
		var categoryblock;
		var thumbnails;
		var favorites;
		var setup = {
			title: 					"",
			expiry: 				"0",
			gutter: 				1,
			seed_height: 			250,
			expired: 				false,
			tooltips: 				false
		};
		/* private methods
			*/
		function thumbnail_loaded () {
			var child = thumbnails.eq(thumb_loader_index);
			var img = child.find("img");
			child.find(".FavoriteButton").data("loaded", true).show();
			clearInterval(thumbnail_interval_id);
			thumbnail_interval_id = setTimeout(thumbnail_loadnext, 1);
		}
		function thumbnail_loadnext () {
			thumb_loader_index = thumb_loader_index + 1;
			if (thumb_loader_index==children.length) {
				return;
			}
			var img = thumbnails.eq(thumb_loader_index).find("img");
			img
				.attr("src", img.data("source"))
				.one('load', thumbnail_loaded)
				.each(Func.imgonload);
		}
		function drawThumbnails () {
			//kill any previous stuff
			clearTimeout(thumbnail_interval_id);
			thumb_loader_index = -1;
			lookup = {};
			thumbnails.each(function (i) {
				var provider = children[i];
				if (provider) {
					var button_w = 0;
					var graphic = new Graphic();
						graphic.provider(provider);
						graphic.letterbox(false);
					if ( Shell.device().phone ) {
						graphic.watermark(true);
						graphic.setSize(480);
					} else {
						graphic.setSize(button_w*1.5, row_height*1.5);
					}
					$(this)
						.show()
						.css("visibility", "visible")
						.css("opacity", 1)
						.removeClass("Active")
						.data("index", i)
						.data("hash", provider.hash)
						.data("provider", provider)
						.find("img")
							.off()
							.data("original-src", "")
							.attr("src", Func.getEmptyImgSrc())
							.data("source", graphic.source());
					lookup[provider.hash] = $(this);
				} else {
					$(this)
						.hide()
						.data("index", -1)
						.data("hash", "")
						.data("provider", {})
						.find("img")
							.attr("src", Func.getEmptyImgSrc());
				}
			});
			favorites.each(function () {
				$(this)
					.hide()
					.removeClass("Active")
					.data("tiptext", L10N.get("ordering", "favorites_tooltip_add"))
					.data("loaded", false)
					.data("active", false);
			});
			thumbnail_loadnext();
		}
		function drawSetImages () {
			children = Overlay.getViewProvider();
			drawThumbnails();
		}
		function onSessionCart () {
			thumbnails.removeClass("Active");
			var cart = Session.getCart();
			var i, row, cuid, thumbnail;
			for (i=0; i<cart.length; ++i) {
				row = cart[i];
				cuid = md5(row.puid+row.cuid);
				thumbnail = lookup[cuid];
				if (thumbnail) {
					thumbnail.addClass("Active");
				}
			}
			var downloads = Session.getDownloads();
			var i, row, cuid, thumbnail;
			for (i=0; i<downloads.length; ++i) {
				row = downloads[i];
				cuid = md5(row.puid+row.cuid);
				thumbnail = lookup[cuid];
				if (thumbnail) {
					thumbnail.addClass("Active");
				}
			}
		}
		function onSessionFavorites () {
			if ( Overlay.getWallView()=="favorites" && Session.getFavoritesLength()==0 ) {
				Controlbar.dispatch("onPageView", [ "browse", "wall", "set", 0, 0 ]);
				Overlay.close();
				return;
			}
			var favorites_table = Session.getFavoritesTable();
			favorites.each(function () {
				var active = favorites_table[$(this).parent().data("hash")+"-f"];
				if (active) {
					$(this)
						.addClass("Favorited")
						.data("tiptext", L10N.get("ordering", "favorites_tooltip_remove"))
						.data("active", true);
				} else {
					$(this)
						.removeClass("Favorited")
						.data("tiptext", L10N.get("ordering", "favorites_tooltip_add"))
						.data("active", false);
					if ( Overlay.getWallView()=="favorites" ) {
						$(this).parent().css("visibility", "hidden");
					}
				}
				if ($(this).data("loaded")==true) {
					$(this).show();
				}
			});
		}
		function onSessionLoaded () {
			if (Overlay.getWallView()=="favorites") {
				lastview = Overlay.getWallView();
				lastindex = Overlay.getIndex();
				lastwidth = 0;
				drawSetImages();
				resize();
				reposition();
			}
			var length = Overlay.getImageGroupCount();
			if (length==1) {
				$("#image-wall-wrapper .ControlBar").hide();
			} else {
				$("#image-wall-wrapper .ControlBar").show();
			}
			onSessionCart();
			onSessionFavorites();
		}
		function updateBatch (i) {
			var row = stack[i];
			var j, obj, button, sw, sh, nw, nh;
			for (j=0; j<row.length; ++j) {
				obj = row[j];
				button = obj.clip;
				button
					.css({
						width: (obj.w) + "px",
						height: (obj.h) + "px",
						top: obj.y + "px",
						left: obj.x + "px"
					});
				button.find(".Highlight").css({
						width: (obj.w-10) + "px",
						height: (obj.h-10) + "px"
					});
				sw = obj.w;
				sh = obj.h;
				nw = sw;
				nh = nw/obj.r;
				if (nh<sh) {
					nh = sh;
					nw = nh*obj.r;
				}
				button.find("img").css({
						width: nw + "px",
						height: nh + "px",
						top: ((sh-nh)/2) + "px",
						left: ((sw-nw)/2) + "px"
					});
			}
		}
		function resize () {
			if (!thumbnails) {
				return;
			}
			/* redraw thumbnails
				*/
			var sw = StageProxy.width();
			if ( sw==lastwidth ) {
				return;
			}
			var totalwidth = StageProxy.width() - setup.gutter;
			var xpos = 0;
			var ypos = 0;
			var stackindex = 0;
			stack = [[]];
			thumbnails.each(function (i) {
				var button = $(this);
				var provider = children[i];
				var ratio = 1;
				var button_x = 0;
				var button_y = 0;
				var button_h = 0;
				var button_w = 0;
				if (provider) {
					ratio = provider.width/provider.height;
					button_x = xpos;
					button_y = ypos;
					button_h = row_height-setup.gutter;
					button_w = Math.round(button_h*ratio);
					if (button_x+button_w+setup.gutter>totalwidth) {
						stack.push([]);
						stackindex += 1;
						xpos = 0;
						ypos += row_height;
						button_x = xpos;
						button_y = ypos;
					}
					xpos += button_w+setup.gutter;
					stack[stackindex].push({
						clip: button,
						r: ratio,
						x: button_x,
						y: button_y,
						w: button_w,
						h: button_h
					});
				}
			});
			var i, j, rowitems, lastitem, rowwidth, offset, offset_last, rowitem;
			ypos = 0;
			for (i=0; i<stack.length; ++i) {
				xpos = 0;
				rowitems = stack[i];
				lastitem = rowitems[rowitems.length-1];
				if (!lastitem) continue;
				rowwidth = lastitem.x+lastitem.w+setup.gutter;
				offset = (totalwidth/rowwidth);
				if ( offset>2 && totalwidth>=600 ) offset = 1;
				for (j=0; j<rowitems.length; ++j) {
					rowitem = rowitems[j];
					rowitem.x = xpos;
					rowitem.y = ypos;
					rowitem.w *= offset;
					rowitem.w = Math.round(rowitem.w);
					rowitem.h = Math.round(rowitem.w/rowitem.r);
					xpos += rowitem.w+setup.gutter;
				}
				rowwidth = lastitem.x+lastitem.w+setup.gutter;
				offset = totalwidth-rowwidth;
				if ( offset!=0 && i!=stack.length-1 ) {
					rowitem.w += offset;
				}
				ypos += rowitem.h+setup.gutter;
			}
			for (i=0; i<stack.length; ++i) {
				updateBatch(i);
			}
			categoryblock.height( ypos + setup.gutter );
		}
		function reposition () {
			var sw = StageProxy.width();
			var i = Overlay.getBrowseIndex();
			var elm = thumbnails.eq(i);
			var ypos = sw<=800 ? elm.offset().top-(i==0?65:0) : elm.offset().top-65;
			window.scrollTo(0, ypos);
		}
		function refresh () {
			var view = Overlay.getWallView();
			var index = Overlay.getIndex();
			if ( view!=lastview || index !=lastindex ) {
				lastview = view;
				lastindex = index;
				lastwidth = 0;
				drawSetImages();
				onSessionLoaded();
			}
			resize();
			reposition();
		}
		function onClose () {
			if (Overlay.getWallView()=="favorites") {
				if (Session.isFavoritesEmpty()) {
					Controlbar.dispatch("onPageView", [ "browse", "wall", "set", 0, 0 ]);
				} else {
					if (children.length!=Session.getFavoritesLength()) {
						refresh();
					}
				}
			}
		}
		function fixIndexes () {
			var i, j, button;
			j = 0;
			for (i=0; i<children.length; ++i) {
				button = thumbnails.eq(i);
				if (button.data("index")!=-1) {
					button.data("index", j);
					++j;
				}
			}
		}
		function init () {
			categoryblock = $("#image-wall");
			thumbnails = Overlay.getMaxImageCount();
			var i;
			for (i=0; i<thumbnails; ++i) {
				categoryblock.append('<div class="Graphic"><div class="Wrapper"><img src="' + Func.getEmptyImgSrc() + '" width="" height="" alt="" /><div class="Highlight"></div></div><div class="FavoriteButton"></div></div>');
			}
			thumbnails = $("#image-wall .Graphic");
			thumbnails.click(function (e) {
				if ( setup.tooltips && $(this).data("provider").alt!="" ) {
					Shell.killToolTip();
				}
				Controlbar.dispatch("onPageView", [ "browse", "overlay", Overlay.getWallView(), Overlay.getIndex(), $(this).data("index") ]);
				Func.stop(e);
				return false;
			});
			if ( !Shell.device().touch ) {
				thumbnails.mouseenter(function (e) {
					$(this).find(".Wrapper").css("opacity", 0.5);
					if ( setup.tooltips && $(this).data("provider").alt!="" ) {
						Shell.createToolTip($(this).data("provider").alt, true);
					}
					Func.stop(e);
					return false;
				}).mouseleave(function (e) {
					$(this).find(".Wrapper").css("opacity", 1);
					if ( setup.tooltips && $(this).data("provider").alt!="" ) {
						Shell.killToolTip();
					}
					Func.stop(e);
					return false;
				});
			}
			favorites = thumbnails.find(".FavoriteButton");
			favorites.click(function (e) {
				if (setup.tooltips) {
					Shell.killToolTip();
				}
				if (Overlay.getWallView()=="favorites") {
					fixIndexes();
					Session.removeItem("favorites", $(this).parent().data("hash"));
				} else {
					var info = Overlay.getImageInfo($(this).parent().data("index"));
					if ($(this).data("active")) {
						Session.removeItem("favorites", $(this).parent().data("hash"));
					} else {
						var obj = {
							hash: $(this).parent().data("hash"),
							puid: info.parent,
							cuid: info.child,
							filename: info.filename,
							width: info.width,
							height: info.height
						};
						Session.addItem("favorites", obj);
					}
				}
				$(this).hide();
				Func.stop(e);
				return false;
			});
			if ( !Shell.device().touch ) {
				favorites
				.mouseenter(function (e) {
					$(this).parent().mouseleave();
					if (setup.tooltips) {
						Shell.createToolTip($(this).data("tiptext"), false);
					}
					Func.stop(e);
					return false;
				})
				.mouseleave(function (e) {
					$(this).parent().mouseenter();
					if (setup.tooltips) {
						Shell.killToolTip();
					}
					Func.stop(e);
					return false;
				});
			}
			if ( !Shell.device().tablet ) {
				row_height = 175;
			}
			
			$("#imagewall-controlbar-more").click(nextpage);
			$("#imagewall-controlbar-top").click(gototop);
			
			$("#start-screen").show();
			
		}
		function nextpage (eo) {
			var length = Overlay.getImageGroupCount();
			var index = Overlay.getIndex()+1; // next page index
			if (index==length) {
				index = 0; // we're at the end of the pages, go back to first page
			}
			Controlbar.dispatch("onPageView", [ "browse", "wall", Overlay.getWallView(), index, 0 ]);
		}
		function gototop (eo) {
			$('html, body').scrollTop(0);
		}
		function dialog_response (str) {
			if (str=="email_invalid") {
				FormDialog.error();
			} else {
				Checkout.setMail(FormDialog.inputvalue());
				FormDialog.kill();
				Session.setHash(str);
				Controlbar.start();
				inited = true;
				if (Controlbar.getState()=="browse") {
					openWall();
				}
				$("#start-screen").hide();
			}
		}
		function dialog_submit () {
			$.post( APP_ROOT + "vend-proofing-gateway.php", {
				action: 	"open_session",
				email: 		FormDialog.inputvalue().toLowerCase(),
				puid: 		Overlay.pageid()
			}, dialog_response);
		}
		function dialog_open () {
			var expiry = setup.expiry=="0" ? L10N.get("splash", "expiration_never") : setup.expiry;
			var expiry_text = setup.expired ? L10N.get("splash", "set_expired_on") + " " + expiry : L10N.get("splash", "set_expires_on") + " " + expiry;
			var session_desc = '<h2>' + setup.title + '</h2>';
			var session_footer;
				if ( welcome_str!="" ) {
					session_desc += welcome_str;
				}
				if ( intro_str!="" ) {
					session_footer = intro_str;
				}
			FormDialog.options({
				markdown: 		true,
				bg_image: 		bg_image_arr,
				description: 	session_desc,
				footer: 		session_footer,
				prefill_variable_name: "vend_proofing_session_email_" + $("#container").attr("data-suid"),
				field_type: 	"email",
				field_label: 	L10N.get("general", "session_enter_email_address"),
				submit_label: 	L10N.get("general", "session_start_resume"),
				error_label: 	L10N.get("general", "session_invalid_email_address"),
				confirm_label: 	L10N.get("general", "dialog_confim"),
				submit: 		dialog_submit
			});
			FormDialog.draw();
		}
		function render () {
			StageProxy.addEventListener("onResize", resize);
			Overlay.addEventListener("onClose", onClose);
			Session.addEventListener("onSessionLoaded", onSessionLoaded);
			Session.addEventListener("onSessionCart", onSessionCart);
			Session.addEventListener("onSessionFavorites", onSessionFavorites);
			init();
			closeWall();
			dialog_open();
		}
		function appear () {
			Session.initialize();
			Controlbar.initialize();
		}
		function closeWall () {
			$("#image-wall-wrapper").hide();
		}
		function openWall () {
			$("#image-wall-wrapper").show();
			resize();
			reposition();
		}
		/* public methods
			*/
		this.initialize = function() {
			L10N = classes.helpers.L10N;
			Func = classes.helpers.Func;
			FormDialog = classes.elements.FormDialog;
			Graphic = classes.elements.Graphic;
			Checkout = classes.overlay.Checkout;
			Controlbar = classes.elements.Controlbar;
			StageProxy = classes.StageProxy;
			Overlay = classes.Overlay;
			Shell = classes.Shell;
			Session = classes.Session;
			render();
			resize();
			appear();
		};
		this.settings = function(obj) {
			if (obj) {
				setup = obj;
			}
			return setup;
		};
		this.setCoverImage = function(arr) {
			bg_image_arr = arr;
		};
		this.setIntroText = function(str) {
			intro_str = str;
		};
		this.setWelcomeText = function(str) {
			welcome_str = str;
		};
		this.showWall = function() {
			if (inited==false) return;
			openWall();
		};
		this.hideWall = function() {
			closeWall();
		};
		this.update = function() {
			refresh();
		};
	}
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Browser = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy; // shortcut
		var Shell; // shortcut
		var Func; // shortcut
		var L10N; // shortcut
		var Overlay; // shortcut
		var Session; // shortcut
		var Sidebar; // shortcut
		var Controlbar; // shortcut
		var Graphic; // shortcut
		/* private properites
			*/
		var instance = 		this;
		var width = 		0;
		var height = 		0;
		var appx = 			0;
		var appy = 			0;
		var appwidth = 		0;
		var appheight = 	0;
		var maxwidth = 		1000;
		var maxheight = 	1000;
		var index = 		-1;
		var inited = 		false;
		var keylisten = 	true;
		var container;
		var inner;
		var paddles;
		var favorite = {
			ui: 			null,
			active: 		false,
			disabled: 		false,
			next: 			false,
			hash: 			""
		};
		var current = {
			layer: 			null,
			title: 			null,
			info: 			{},
			bounds: 		{}
		};
		var crop = {
			container: 		null,
			o: 				null,
			t: 				null,
			l: 				null,
			b: 				null,
			r: 				null,
			x_offset: 		50,
			y_offset: 		50,
			direction: 		"v",
			limits: 		{},
			width: 			0,
			height: 		0
		};
		var zoom = {
			container: 		null,
			img: 			null,
			ui: 			null,
			open: 			false,
			disabled: 		false,
			active: 		false,
			limits: 		{},
			width: 			0,
			height: 		0
		};
		/* private methods
			*/
		
		/* --- Crop Functions --- */
		function updateCropView () {
			if (!crop.o.position()) {
				return;
			}
			var outline_x = crop.o.position().left;
			var outline_y = crop.o.position().top;
			var outline_w = crop.o.outerWidth();
			var outline_h = crop.o.outerHeight();
			var image_width = appwidth;
			var image_height = appheight;
			var top_w = image_width;
			var top_h = outline_y;
			var left_w = outline_x;
			var left_h = image_height;
			var bottom_y = outline_y+outline_h;
			var bottom_w = image_width;
			var bottom_h = image_height-(outline_y+outline_h);
			var right_x = outline_x+outline_w;
			var right_w = image_width-(outline_x+outline_w);
			var right_h = image_height;
			crop.container.width(appwidth).height(appheight);
			crop.t.width(top_w).height(top_h);
			crop.l.width(left_w).height(left_h);
			crop.b.width(bottom_w).height(bottom_h).css("top", bottom_y);
			crop.r.width(right_w).height(right_h).css("left", right_x);
		}
		function stopCropDrag () {
			var x_offset = crop.direction=="h" ? (crop.o.position().left/crop.limits.right)*100 : 50;
			var y_offset = crop.direction=="v" ? (crop.o.position().top/crop.limits.bottom)*100 : 50;
			crop.x_offset = x_offset;
			crop.y_offset = y_offset;
			instance.dispatch("onCropMove", {x:x_offset, y:y_offset});
		}
		function drawCropView () {
			crop.container.hide();
			crop.o
				.drag(function (ev, dd) {
					$(this).css({
						left: Math.min(crop.limits.right, Math.max(crop.limits.left, dd.offsetX)),
						top: Math.min(crop.limits.bottom, Math.max(crop.limits.top, dd.offsetY))
					});
					updateCropView();
				}, { relative:true })
				.drag("end", stopCropDrag);
		}
		function updateCrop () {
			if (current.layer==null) {
				return;
			}
			var aspect = Sidebar.getFormatAspect();
			if (Sidebar.getOrientation()=="l") {
				aspect = 1/aspect;
			}
			var image_width = Math.round(current.bounds.right-current.bounds.left);
			var image_height = Math.round(current.bounds.bottom-current.bounds.top);
			var outline_x = Math.round(current.bounds.left);
			var outline_y = Math.round(current.bounds.top);
			var outline_h = image_height;
			var outline_w = Math.round(image_height*aspect);
				outline_x += Math.round((image_width-outline_w)*(crop.x_offset/100));
			if (outline_w>image_width) {
				outline_w = image_width;
				outline_h = Math.round(image_width/aspect);
				outline_x = Math.round(current.bounds.left);
				outline_y += Math.round((image_height-outline_h)*(crop.y_offset/100));
			}
			crop.direction = outline_w==image_width ? "v" : "h";
			crop.limits = {
				left: current.bounds.left,
				top: current.bounds.top,
				right: current.bounds.left+(image_width-outline_w),
				bottom: current.bounds.top+(image_height-outline_h)
			};
			crop.o
				.width(outline_w-2).height(outline_h-2)
				.css({
					left: outline_x,
					top: outline_y
				});
			updateCropView();
		}
		function hideCrop () {
			crop.x_offset = 50;
			crop.y_offset = 50;
			crop.container.hide();
			updateCrop();
		}
		function showCrop () {
			crop.container.show();
			updateCrop();
		}
		
		/* --- Zoom Functions --- */
		function drawZoom () {
			zoom.img
				.drag(function (ev, dd) {
					if (zoom.disabled) {
						return;
					}
					$(this).css({
						left: Math.min(zoom.limits.right, Math.max(zoom.limits.left, dd.offsetX)),
						top: Math.min(zoom.limits.bottom, Math.max(zoom.limits.top, dd.offsetY))
					});
				}, { relative:true });
		}
		function updateZoomIcon (forceoff) {
			zoom.ui.addClass("Off");
			zoom.ui.addClass("Disabled");
			zoom.disabled = true;
			if (forceoff==true) {
				return;
			}
			if (zoom.width<maxwidth||zoom.height<maxheight) {
				zoom.ui.removeClass("Off");
				zoom.ui.removeClass("Disabled");
				zoom.disabled = false;
			}
		}
		function closeZoom () {
			if (zoom.open==false) {
				return;
			}
			zoom.open = false;
			// broadcast it
			instance.dispatch("onZoomView", zoom.open);
			// hide it
			zoom.container.hide();
			// update button
			zoom.ui.removeClass("Active");
			// kill image
			zoom.img.attr("src", Func.getEmptyImgSrc());
		}
		function updateZoom () {
			if (zoom.open==false) {
				updateZoomIcon(false);
				return;
			}
			// set sizes
			zoom.container.css({
				width: zoom.width,
				height: zoom.height
			});
			zoom.img.css({
				left: Math.round((zoom.width-zoom.img.width())/2),
				top: Math.round((zoom.height-zoom.img.height())/2)
			});
			// drag points
			var left = zoom.width-zoom.img.width();
			var right = 0;
			if (left>0) {
				left = right = Math.round(left/2);
			}
			var top = zoom.height-zoom.img.height();
			var bottom = 0;
			if (top>0) {
				top = bottom = Math.round(top/2);
			}
			zoom.limits = {
				left: left,
				top: top,
				right: right,
				bottom: bottom
			};
			// force clsoe/disable the zoom
			var force = zoom.width>=zoom.img.width() && zoom.height>=zoom.img.height();
			updateZoomIcon(force);
			if (force) {
				closeZoom();
			}
		}
		function openZoom () {
			if (zoom.open==true) {
				return;
			}
			zoom.open = true;
			zoom.ui.addClass("Disabled");
			zoom.disabled = true;
			// broadcast it
			instance.dispatch("onZoomView", { open:zoom.open });
			// show it
			zoom.container.show();
			// update button
			zoom.ui.addClass("Active");
			// show loader
			zoom.container.progress();
			// load up the new image
			var graphic = new Graphic();
				graphic.provider(current.info);
				graphic.watermark(true);
				graphic.letterbox(true);
				graphic.setSize(maxwidth, maxheight);
			var iw = current.info.width;
			var ih = current.info.height;
			var nw = maxwidth;
			var nh = Math.round(nw*(ih/iw));
			if (nh>maxheight) {
				nh = maxheight;
				nw = Math.round(nh*(iw/ih));
			}
			zoom.img
				.css("opacity", 0)
				.attr("src", graphic.source())
				.width(nw).height(nh)
				.one('load', function () {
					// re-enable
					zoom.ui.removeClass("Disabled");
					zoom.disabled = false;
					// hide loader
					zoom.container.progress(true);
					// make this active, bring it to the front, and fade it up
					zoom.img.css("opacity", 1);
					// call the update first
					updateZoom();
				})
				.each(function(){
					if (this.complete) {
						$(this).load();
					}
				});
			// call the update first
			updateZoom();
		}
		function toggleZoom () {
			if (zoom.disabled) {
				return;
			}
			if (zoom.open==true) {
				closeZoom();
			} else if (zoom.open==false) {
				openZoom();
			}
		}
		
		function resize () {
			var sw = StageProxy.width();
			appx = 			0;
			appwidth = 		width;
			if (appwidth>maxwidth) {
				appwidth = maxwidth;
				appx = (width-appwidth)/2;
			}
			appy = 			44;
			appheight = 	height-44;
			if (appheight>maxheight) {
				appheight = maxheight;
				appy += (height-appheight-appy)/3;
			}
			if (sw<=800) {
				appy = 			0;
				appheight = 	height-50;
				if (appheight>maxheight) {
					appheight = maxheight;
					appy = (height-appheight)/2;
				}
			}
			container.css({
				width: width,
				height: height
			});
			inner.css({
				left: appx,
				top: appy,
				width: appwidth,
				height: appheight
			});
			paddles.css({
				left: appx*-1,
				top: appy*-1,
				width: width,
				height: height
			});
			zoom.width = appwidth;
			zoom.height = appheight;
			crop.width = appwidth;
			crop.height = appheight;
			if (!current.info) return;
			var sw, sh, iw, ih, nw, nh, nx, ny;
			if (current.layer!=null) {
				sw = appwidth;
				sh = appheight;
				iw = current.info.width;
				ih = current.info.height;
				nw = sw;
				nh = Math.round(nw*(ih/iw));
				if (nh>sh) {
					nh = sh;
					nw = Math.round(nh*(iw/ih));
				}
				nx = Math.round((sw-nw)/2);
				ny = Math.round((sh-nh)/2);
				current.layer
					.width(sw).height(sh)
					.find("img")
						.width(nw).height(nh)
						.css({
							left: nx,
							top: ny
						});
				current.bounds = {
					left: nx,
					top: ny,
					right: nx+nw,
					bottom: ny+nh
				};
				updateCrop();
				updateZoom();
			}
		}
		
		/* --- Favorite Functions --- */
		function disableFavorite () {
			favorite.ui.removeClass("Active");
			favorite.active = false;
		}
		function enableFavorite () {
			favorite.ui.addClass("Active");
			favorite.active = true;
		}
		function toggleFavorite () {
			if (favorite.disabled) {
				return;
			}
			if (favorite.active) {
				if (Overlay.getWallView()=="favorites") {
					disableFavorite();
					favorite.next = true;
					// kill zoom
					if (zoom.open==true) {
						zoom.ui.addClass("Disabled");
						zoom.disabled = true;
					}
					// negate any current images
					current.layer.find("img")
						.off()
						.css("opacity", 0)
						.data("original-src", "")
						.attr("src", Func.getEmptyImgSrc());
					current.title.html("---");
					hideCrop();
					resize();
				}
				Session.removeItem("favorites", favorite.hash);
			} else {
				var obj = {
					hash: favorite.hash,
					puid: current.info.parent,
					cuid: current.info.child,
					filename: current.info.filename,
					width: current.info.width,
					height: current.info.height
				};
				Session.addItem("favorites", obj);
			}
			favorite.ui.addClass("Disabled");
			favorite.disabled = true;
		}
		function favorites () {
			disableFavorite();
			if (favorite.next==true) {
				favorite.next = false;
				instance.refresh();
			}
			favorite.ui.removeClass("Disabled");
			favorite.disabled = false;
			var items = Session.getFavorites();
			var i, row, hash;
			for (i=0; i<items.length; ++i) {
				row = items[i];
				hash = md5(row.puid+row.cuid);
				if (hash==favorite.hash) {
					enableFavorite();
					break;
				}
			}
		}
		function openeditor () {
			Sidebar.abscond();
			container.addClass("Editor");
		}
		function closeeditor () {
			Sidebar.reveal();
			container.removeClass("Editor");
		}
		function sidebarevent () {
			Func.filter(current.layer.find("img"), Sidebar.getColorTone());
			if (Sidebar.getShowCrop()==false) {
				hideCrop();
				return;
			}
			showCrop();
		}
		function prev () {
			Overlay.prevBrowseIndex();
		}
		function next () {
			Overlay.nextBrowseIndex();
		}
		function close () {
			Overlay.close();
		}
		function reveal () {
			Sidebar.reveal();
		}
		function abscond () {
			Sidebar.abscond();
		}
		function killProgress () {
			current.layer.progress(true);
		}
		function keyevent (event) {
			if ( Controlbar.getState()!="browse" ) {
				return;
			}
			if ( Overlay.isOpen()==false ) {
				return;
			}
			if ( keylisten==false ) {
				return;
			}
			switch (event.which) {
				case 32 : // Key.SPACE :
				case 39 : // Key.RIGHT :
					$("#browser-hitarea-next, #browse-controlbar-next")
						.data("tooltip", "")
						.unbind("mouseenter")
						.unbind("mouseleave");
					$("#browse-controlbar-next")
						.click();
					break;
				case 37 : // Key.LEFT :
					$("#browser-hitarea-prev, #browse-controlbar-prev")
						.data("tooltip", "")
						.unbind("mouseenter")
						.unbind("mouseleave");
					$("#browse-controlbar-prev")
						.click();
					break;
				case 38 : // Key.UP :
				case 40 : // Key.DOWN :
					$("#browse-controlbar-fav")
						.data("tooltip", "")
						.unbind("mouseenter")
						.unbind("mouseleave")
						.click();
					break;
			}
			Func.stop(event);
			return false;
		}
		function drawControls () {
			$("#browser-hitarea-prev, #browse-controlbar-prev, #browser-hitarea-next, #browse-controlbar-next, #browse-controlbar-fs, #browse-controlbar-fav, #browse-controlbar-close, #browse-controlbar-options, #browse-controlbar-return, #browse-controlbar-return-icon, #browse-controlbar-done")
				.each(function () {
					var self = $(this);
					var tooltip = self.attr("data-tooltip");
					var func = self.attr("id");
						func = func.split("-");
						func = func.pop();
						switch (func) {
							case "prev" :
								func = prev;
								break;
							case "next" :
								func = next;
								break;
							case "fs" :
								func = toggleZoom;
								break;
							case "fav" :
								func = toggleFavorite;
								break;
							case "close" :
								func = close;
								break;
							case "options" :
								func = reveal;
								break;
							case "return" :
							case "icon" :
								func = abscond;
								break;
							case "done" :
								func = closeeditor;
								break;
						}
					if ( tooltip!="" && !Shell.device().touch ) {
						self
							.data("tooltip", tooltip)
							.mouseenter(function () {
								Shell.createToolTip($(this).data("tooltip"));
							})
							.mouseleave(function () {
								Shell.killToolTip();
							})
							.click(function () {
								$(this).unbind("mouseenter").unbind("mouseleave");
								Shell.killToolTip();
								func();
							});
					} else {
						self.click(func);
					}
					self.addClass("Enabled")
				});
				if ( !Shell.device().touch ) {
					$("body").keydown(keyevent);
				} else {
					$("#browser-hitarea-prev, #browser-hitarea-next")
						.touchwipe({
							wipeLeft: next,
							wipeRight: prev
						});
				}
				// prevent scroll and touch
				container.bind("touchmove", Func.stop);
				container.mousewheel(Func.stop);
		}
		function draw () {
			maxwidth = 1000;
			maxheight = 1000;
			var classid = $("#container").attr("class");
			if (classid=="DropboxSet") {
				maxwidth = 1024;
				maxheight = 768;
			}
			//maxwidth = 500;
			//maxheight = 500;
			// cache some jquery lookups
			container = $("#overlay-browser");
			inner = $("#overlay-browser .Inner");
			paddles = $("#browser-paddles");
			input = $("#sidebar-input");
			current.title = $("#browse-controlbar-title");
			current.layer = container.find(".Display");
			crop.container = $("#browser-cropview");
			crop.o = $("#browser-cropview-o");
			crop.t = $("#browser-cropview-t");
			crop.l = $("#browser-cropview-l");
			crop.b = $("#browser-cropview-b");
			crop.r = $("#browser-cropview-r");
			zoom.container = $("#browser-zoom");
			zoom.img = $("#browser-zoom img");
			zoom.ui = $("#browse-controlbar-fs");
			favorite.ui = $("#browse-controlbar-fav");
			// draw up our controls
			drawControls();
			drawCropView();
			drawZoom();
		}
		function lateinit () {
			Session.addEventListener("onSessionFavorites", favorites);
			Sidebar.addEventListener("onChanged", sidebarevent);
			Sidebar.addEventListener("onImageModify", openeditor);
		}
		function init () {
			draw();
			resize();
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		function onLoaded () {
			// hide loader
			if ($.browser.mozilla) {
				setTimeout(killProgress, 100);
			} else {
				killProgress();
			}
			// fade it up
			$(this).css("opacity", 1)
			// reset the zoom and appearance
			if (zoom.open==true) {
				zoom.container.hide();
				closeZoom();
				zoom.ui.removeClass("Disabled");
				zoom.disabled = false;
			}
			updateZoomIcon(false);
		}
		function showChild (i) {
			if ( i==-1 && index==-1 ) {
				return; // if we are already clear, skip it.
			}
			// set index
			index = i;
			// kill zoom
			if (zoom.open==true) {
				zoom.ui.addClass("Disabled");
				zoom.disabled = true;
			}
			// if we're clearing, stop here
			if (index==-1) {
				current.title.html("---");
				hideCrop();
				resize();
				current.info = {};
				favorite.hash = "";
				instance.dispatch("onIndex", index);
				return;
			}
			// get info
			current.info = Overlay.getImageInfo(index);
			if (!current.info) return;
			favorite.hash = md5(current.info.parent+current.info.child);
			instance.dispatch("onIndex", index);
			// load up the new image
			var sw = StageProxy.width();
			var ih = sw<=800 ? height : height-44;
			var multiplier = window.devicePixelRatio ? window.devicePixelRatio : 1;
			var rw = width;
			var rh = ih;
			if ( multiplier>1 ) {
				var rw = width*multiplier;
				if (rw>maxwidth) {
					rw = maxwidth;
				}
				var rh = ih*multiplier;
				if (rh>maxheight) {
					rh = maxheight;
				}
			}
			var graphic = new Graphic();
				graphic.provider(current.info);
				graphic.watermark(true);
				graphic.letterbox(true);
				graphic.setSize(rw, rh);
			current.layer.progress();
			current.layer.find("img")
				.off()
				.data("original-src", "")
				.attr("src", Func.getEmptyImgSrc())
				.attr("src", graphic.source())
				.one('load', onLoaded).each(function() {
					if (this.complete) {
						$(this).load();
					}
				});
			// change the label
			var filelabel = "";
			if (Overlay.getWallView()=="favorites") {
				filelabel += L10N.get("ordering", "favorites_label");
			}
			if (filelabel!="") {
				filelabel += ": ";
			}
			var filename = current.info.filename;
			var bits = filename.split(".");
				bits.pop();
				filename = bits.join(".");
			filelabel += filename;
			current.title.html(filelabel);
			// resize
			resize();
		}
		/* public methods
			*/
		this.freeKeys = function() {
			keylisten = false;
		};
		this.takeKeys = function() {
			keylisten = true;
		};
		this.hideCropView = function() {
			hideCrop();
		};
		this.showCropView = function() {
			showCrop();
		};
		this.refresh = function() {
			showChild(Overlay.getBrowseIndex());
			favorites();
			hideCrop();
		};
		this.clearStage = function() {
			closeZoom();
			showChild(-1);
		};
		this.move = function(x, y) {
			container.css({
				top: y,
				left: x
			});
		};
		this.setSize = function(w, h) {
			width = w;
			height = h;
			resize();
		};
		this.initialize = function() {
			Controlbar = classes.elements.Controlbar;
			StageProxy = classes.StageProxy;
			Graphic = classes.elements.Graphic;
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			Overlay = classes.Overlay;
			Session = classes.Session;
			Shell = classes.Shell;
			Sidebar = classes.overlay.Sidebar;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Cart = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var Func; // shortcut
		var L10N; // shortcut
		var Session; // shortcut
		var Dialog; // shortcut
		var Controlbar; // shortcut
		var Overview; // shortcut
		var Checkout; // shortcut
		/* private properites
			*/
		var cart_index = 		[];
		var cart_tree = 		{};
		var selected_group = 	null;
		var selected_item = 	null;
		var overview_screen = 	null;
		var groups = null;
		/* private methods
			*/
		function disable (eo) {
			overview_screen.toggle(eo.open);
			overview_screen.progress(eo.open==false);
		}
		function select (eo) {
			selected_group = eo.group;
			selected_item = eo.item;
			$(".LineItem").removeClass("Active");
			$("#cart-item-" + selected_item).addClass("Active");
			Overview.show({group:selected_group, item:selected_item});
		}
		function onClearCartConfim () {
			disable({open:true});
			Session.purge("cart");
			Overview.hide();
		}
		function clearCart () {
			Dialog.options({
				unique: "clearcart",
				modal: true,
				title: L10N.get("ordering", "cart_delete_confirmation_title"),
				description: L10N.get("ordering", "cart_delete_confirmation_description"),
				confim: onClearCartConfim
			});
			Dialog.draw();
		}
		function onDeleteConfim (type, hash) {
			disable({open:true});
			if ( !hash || hash=="" || hash==undefined ) {
				Session.purge(type);
			} else {
				Session.removeItem(type, hash);
			}
			//if (hash!=selected_item) {
				selected_item = null;
				selected_group = null;
				Overview.hide();
			//}
		}
		function deleteCartItem () {
			Dialog.options({
				unique: "cartdeleteitem",
				modal: true,
				title: L10N.get("ordering", "cart_delete_confirmation_title"),
				description: L10N.get("ordering", "cart_delete_confirmation_description"),
				args: arguments,
				confim: onDeleteConfim
			});
			Dialog.draw();
		}
		function updatecart () {
			disable({open:false});
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var downloads_taxable_bool = Checkout.settings().downloads.tax;
			var session_cart = Session.getCart();
			var products_parsed = Session.getPackagesParsed();
			var download = Session.getDownloads();
			var i, j, product, hash, completion, row, hashbits;
			var group_data, cart_data, group_price, group_clip, item_hash, item_data, quantity, format_price, paper_price, modifier_price, item_price;
			// the holders of all our important data
			cart_index = [];
			cart_tree = {};
			// loop through the packages to create groups
			for (i=0; i<products_parsed.length; ++i) {
				product = products_parsed[i];
				hash = product.row.hash.substr(0, 32); // clean up our hashes
				completion = ( product.total==0 ? 1 : product.count/product.total ); // if no items, it's complete unto itself
				cart_tree[hash] = {
					index: cart_index.length,
					data: product.row,
					children: [],
					lookup: {},
					indexes: {},
					metrics: {
						total: product.total,
						count: product.count
					}
				};
				cart_index.push({
					completion: completion, // if no items, it's complete unto itself
					hash: hash,
					title: product.row.nickname,
					metadata: product.row.title,
					price: parseFloat(product.row.subtotal)
				});
			}
			// tentatively add allacarte
			cart_tree.alacarte = {
				index: cart_index.length,
				data: {},
				children: [],
				lookup: {},
				indexes: {}
			};
			cart_index.push({
				completion: 1,
				hash: "alacarte",
				title: L10N.get("ordering", "alacarte_label"),
				metadata: "",
				price: 0
			});
			// parse through all the cart items and put them in the right containers
			for (i=0; i<session_cart.length; ++i) {
				row = session_cart[i];
				hashbits = row.hash.split(":");
				if (hashbits.length==1) { // alacarte
					cart_tree.alacarte.indexes[row.hash] = cart_tree.alacarte.children.length;
					cart_tree.alacarte.children.push(row.hash);
					cart_tree.alacarte.lookup[row.hash] = row;
				} else {
					product = hashbits[1];
					cart_tree[product].indexes[hashbits[0]] = cart_tree[product].children.length;
					cart_tree[product].children.push(hashbits[0]);
					cart_tree[product].lookup[hashbits[0]] = row;
				}
			}
			// check if we should ditch alacarte entirely
			if ( cart_tree.alacarte.children.length==0 ) {
				cart_index.pop();
				delete cart_tree.alacarte;
			} else {
				cart_index[cart_tree.alacarte.index].metadata = cart_tree.alacarte.children.length + " " + L10N.get("ordering", "cart_alacarte_items");
			}
			// tentatively add downloads
			cart_tree.download = {
				index: cart_index.length,
				data: {},
				children: [],
				lookup: {},
				indexes: {}
			};
			cart_index.push({
				completion: 1,
				hash: "download",
				title: L10N.get("ordering", "downloads_label"),
				metadata: "",
				price: 0
			});
			// parse through all the cart items and put them in the right containers
			for (i=0; i<download.length; ++i) {
				row = download[i];
				hashbits = row.hash.split(":");
				cart_tree.download.indexes[hashbits[0]] = cart_tree.download.children.length;
				cart_tree.download.children.push(row.hash);
				cart_tree.download.lookup[row.hash] = row;
			}
			// check if we should ditch alacarte entirely
			if ( cart_tree.download.children.length==0 ) {
				cart_index.pop();
				delete cart_tree.download;
			} else {
				cart_index[cart_tree.download.index].metadata = cart_tree.download.children.length + " " + L10N.get("ordering", "cart_alacarte_items");
			}
			// do some garbage removal
			groups.empty();
			// check to see if it's empty
			if (cart_index.length==0) {
				groups.html('<div class="EmptyNotice">' + L10N.get("ordering", "cart_empty") + '</div>');
				$('#overlay-cartview-controlbar').hide();
				return;
			}
			// ok, now that we have any crap out of the way, lets
			// start building in earnest
			// obviously skipping over things already rendered
			var table = '';
			for (i=0; i<cart_index.length; ++i) {
				// create cart groups
				group_data = cart_index[i];
				cart_data = cart_tree[group_data.hash];
				group_price = group_data.price;
				if (purchase_price_includes_tax_bool) {
					group_price = Func.addSalesTax(group_price);
				}
				table += '<table id="cart-group-' + group_data.hash + '">';
				table += 	'<tr class="GroupHeading">';
				if (group_data.hash=="alacarte") {
					table += 	'<td class="col1">' + group_data.title + '</td>';
					table += 	'<td class="col2" colspan="2">' + group_data.metadata + '</td>';
				} else if (group_data.hash=="download") {
					table += 	'<td class="col1">' + group_data.title + '</td>';
					table += 	'<td class="col2" colspan="2">' + group_data.metadata + '</td>';
				} else {
					table += 	'<td class="col1">' + group_data.title + " (" + group_data.metadata + ") " + '</td>';
					table += 	'<td class="col2" colspan="2">' + Math.round(group_data.completion*100) + "% " + L10N.get("ordering", "cart_package_completion") + '</td>';
				}
				table += 		'<td class="col4">GROUP_PRICE_FORMATTED_TEMP</td>';
				if (group_data.hash=="alacarte") {
					table += 	'<td class="col5"><button data-type="alacarte" data-hash="">' + L10N.get("ordering", "cart_alacarte_delete")  + '</button></td>';
				} else if (group_data.hash=="download") {
					table += 	'<td class="col5"><button data-type="download" data-hash="">' + L10N.get("ordering", "cart_alacarte_delete")  + '</button></td>';
				} else {
					table += 	'<td class="col5"><button data-type="package" data-hash="' + group_data.hash + "-p" + '">' + L10N.get("ordering", "cart_package_delete")  + '</button></td>';
				}
				table += 	'</tr>';
				// loop through all the children and draw anything missing
				var j, delete_type, item_data, item, filename, bits, quantity, format_label, format_price, paper_price, modifier_price, item_price, item_title;
				for (j=0; j<cart_data.children.length; ++j) {
					item_hash = cart_data.children[j];
					item_data = cart_data.lookup[item_hash];
					delete_type = "cart";
					var active = selected_item==item_hash && selected_group==group_data.hash;
					filename = item_data.filename;
						bits = filename.split(".");
							bits.pop();
						filename = bits.join(".");
					if (group_data.hash=="download") {
						delete_type = "download";
						format_label = item_data.quality;
						quantity = 1;
						item_price = parseFloat(item_data.subtotal, 10);
					} else {
						format_label = item_data.format_label;
						quantity = parseFloat(item_data.quantity, 10);
						format_price = parseFloat(item_data.format_price, 10);
						paper_price = parseFloat(item_data.paper_price, 10);
						modifier_price = parseFloat(item_data.modifier_price, 10);
						item_price = 0;
						if (!isNaN(format_price)) {
							item_price += format_price;
						}
						if (!isNaN(paper_price)) {
							item_price += paper_price;
						}
						if (!isNaN(modifier_price)) {
							item_price += modifier_price;
						}
					}
						if (item_price>0) {
							if ( purchase_price_includes_tax_bool) {
								if ( group_data.hash!="download" || (group_data.hash=="download" && downloads_taxable_bool) ) {
									item_price = Func.addSalesTax(item_price);
								}
							}
							group_price += item_price*quantity;
						}
					table += 	'<tr class="LineItem' + (active?" Active":"") + '" id="cart-item-' + item_hash + '" data-group-hash="' + group_data.hash + '" data-item-hash="' + item_hash + '">';
					table += 		'<td class="col1">' + filename + '</td>';
					table += 		'<td class="col2">' + format_label + '</td>';
					table += 		'<td class="col3">' + quantity + '</td>';
					if (group_data.hash=="download") {
						if (item_data.allprice=="0") {
							table += 		'<td class="col4">' + Func.getFormattedPrice(item_price*quantity) + '</td>';
						} else {
							table += 		'<td class="col4">---</td>';
						}
					} else {
						table += 		'<td class="col4">' + Func.getFormattedPrice(item_price*quantity) + '</td>';
					}
					//table += 		'<td class="col4">' + Func.getFormattedPrice(item_price*quantity) + '</td>';
					if (group_data.hash=="download") {
						if (item_data.allprice=="0") {
							table += 	'<td class="col5"><button data-type="' + delete_type + '" data-hash="' + item_hash + '">' + L10N.get("ordering", "cart_item_delete")  + '</button></td>';
						}
					} else {
						table += 	'<td class="col5"><button data-type="' + delete_type + '" data-hash="' + item_hash + '">' + L10N.get("ordering", "cart_item_delete")  + '</button></td>';
					}
					table += 	'</tr>';
				}
				table = table.split("GROUP_PRICE_FORMATTED_TEMP").join(Func.getFormattedPrice(group_price));
				table += '</table>';
			}
			
			groups.html(table);
			groups.find(".GroupHeading button").click(function () {
				deleteCartItem($(this).data("type"), $(this).data("hash"));
			});
			groups.find(".LineItem").click(function () {
				select({group:$(this).data("group-hash"), item:$(this).data("item-hash")});
			});
			groups.find(".LineItem button").click(function (e) {
				deleteCartItem($(this).data("type"), $(this).data("hash"));
				e.stopPropagation()
			});
			
			$('#overlay-cartview-controlbar').show();

			if ( selected_group!=null && selected_item!=null ) {
				select({group:selected_group, item:selected_item});
			}
			
		}
		function doCheckout (returnonly) {
			if (cart_index.length==0) {
				if (returnonly==false) {
					Dialog.options({
						unique: "cartincomplete",
						modal: false,
						title: L10N.get("checkout", "checkout_package_incomplete_title"),
						description: L10N.get("checkout", "checkout_package_incomplete_description")
					});
					Dialog.draw();
				}
				return false;
			}
			// check to see if all the cart items are fulfilled
			var completion = 0;
			var i;
			for (i=0; i<cart_index.length; ++i) {
				completion += cart_index[i].completion;
			}
			if (completion<cart_index.length) {
				if (returnonly==false) {
					Dialog.options({
						unique: "cartincomplete",
						modal: false,
						title: L10N.get("checkout", "checkout_package_incomplete_title"),
						description: L10N.get("checkout", "checkout_package_incomplete_description")
					});
					Dialog.draw();
				}
				return false;
			}
			// check to see if the cart minimums are reached
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var cart_minimum_value_num = Checkout.settings().minimum.value;
			var cart_minimum_count_num = Checkout.settings().minimum.count;
			var tally = 0;
			var subtotal = 0;
			var rows = Session.getCart();
			var price, quantity;
			for (i=0; i<rows.length; ++i) {
				price = parseFloat(rows[i].subtotal);
				quantity = parseInt(rows[i].quantity, 10);
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
				subtotal += price*quantity;
				tally += quantity;
			}
			rows = Session.getDownloads();
			var price, quantity;
			for (i=0; i<rows.length; ++i) {
				price = parseFloat(rows[i].subtotal);
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
				subtotal += price;
				tally += 1;
			}
			rows = Session.getPackagesParsed();
			for (i=0; i<rows.length; ++i) {
				if (rows[i].total==0) {
					tally += 1;
				}
			}
			rows = Session.getPackages();
			for (i=0; i<rows.length; ++i) {
				price = parseFloat(rows[i].subtotal);
				quantity = 1;
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
				subtotal += price*quantity;
			}
			if (tally<cart_minimum_count_num||subtotal<cart_minimum_value_num) {
				var description = tally<cart_minimum_count_num ? L10N.get("checkout", "checkout_minimum_count_description") : L10N.get("checkout", "checkout_minimum_subtotal_description");
				description = description.split("{COUNT_MINIMUM}").join(cart_minimum_count_num).split("{SUBTOTAL_MINIMUM}").join(Func.getFormattedPrice(cart_minimum_value_num));
				if (returnonly==false) {
					Dialog.options({
						unique: "cartminimum"+(tally<cart_minimum_count_num?"count":"subtotal"),
						modal: false,
						title: L10N.get("checkout", "checkout_minimum_title"),
						description: description
					});
					Dialog.draw();
				}
				return false;
			}
			// we made it!
			if (returnonly==false) {
				Controlbar.dispatch("onPageView", [ "checkout" ]);
			}
			return true;
		}
		function draw () {
			groups = $("#cart-groups");
			overview_screen = $("#overview-screen");
		}
		function init () {
			draw();
		}
		function lateinit () {
			Session.addEventListener("onSessionLoaded", updatecart);
			Session.addEventListener("onSessionCart", updatecart);
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		/* public methods
			*/
		this.checkout = function(returnonly) {
			var UNDEF;
			if (returnonly==UNDEF) {
				returnonly = false;
			}
			return doCheckout(returnonly);
		};
		this.clear = function() {
			clearCart();
		};
		this.initialize = function() {
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			Session = classes.Session;
			Controlbar = classes.elements.Controlbar;
			Overview = classes.overlay.Overview;
			Checkout = classes.overlay.Checkout;
			Dialog = classes.Dialog;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Checkout = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy; // shortcut
		var Func; // shortcut
		var L10N; // shortcut
		var Overlay; // shortcut
		var Session; // shortcut
		var Dialog; // shortcut
		var Cart; // shortcut
		var Controlbar; // shortcut
		/* private properites
			*/
		var taxrules = 		[];
		var discount = 		[];
		var options = {
			country: 			"",
			state: 			"",
			province: 			"",
			currency: 			"",
			intl: 			false,
			pickup: 			false,
			offline: 			false,
			paypal: 			false,
			merchant: 			false,
			downloads: { 
				use: false, 
				tax: false, 
				high: {
					use: false, 
					price: "0" 
				},
				low: {
					use: false, 
					price: "0" 
				},
				all: {
					use: false, 
					high: "0",
					low: "0" 
				}
			},
			shipping: {
				use: 			true,
				tax: 			false,
				flat: 		0,
				rate: 		0
			},
			handling: {
				use: 			false,
				tax: 			false,
				flat: 		0,
				intl: 		0
			},
			tax: {
				use: 			true,
				included: 		false
			},
			discount: 			false,
			minimum: {
				value: 			0,
				count: 			0
			}
		};
		var order = {
			id: 				"",
			payment_method: 		"offline",
			shipping_method: 		"ship",
			country_code: 		"",
			postal_code: 		"",
			state_code: 		"",
			final_value: 		0,
			discount_value: 		0,
			final_shipping: 		0,
			final_handling: 		0,
			final_tax: 			0
		};
		var defaultemail = 			"";
		var inited = 			false;
		var cart_no_payment = 	false;
		var ignore_ssl_warning = false;
		var recheck = 			false;
		var container = null;
			var screen = null;
			var blocks = null;
			var summary = null;
			var back_obj = null;
			var process_obj = null;
			var accept_obj = null;
			var clickwrap_obj = null;
		var sidebar_input = null;
			var sidebar_input_content = null;
		/* private methods
			*/
		function getTaxRate () {
			var i, taxrule;
			if (order.country_code=="") {
				return [0, 0, 0, false];
			}
			if (options.country=="US") {
				if (options.country!=order.country_code) {
					return [0];
				}
				if (order.state_code=="") {
					return [0];
				}
				for (i=0; i<taxrules.length; ++i) {
					taxrule = taxrules[i];
					if (order.state_code==taxrule[0]) {
						return [taxrule[1]];
					}
				}
			} else if (options.country=="CA") {
				if (options.country!=order.country_code) {
					return [0, 0, 0, false];
				}
				if (order.state_code=="") {
					return [0, 0, 0, false];
				}
				for (i=0; i<taxrules.length; ++i) {
					taxrule = taxrules[i];
					if (order.state_code==taxrule[0]) {
						return [taxrule[1], taxrule[2], taxrule[3], (taxrule[0]=="QC")];
					}
				}
			} else {
				for (i=0; i<taxrules.length; ++i) {
					taxrule = taxrules[i];
					if (order.country_code==taxrule[0]) {
						return [taxrule[1]];
					}
				}
			}
			return [0, 0, 0, false];
		}
		function updateTotals () {
			var cart_subtotal = 0;
			var download_subtotal = 0;
			var shipping_subtotal = options.shipping.flat;
			var products = Session.getPackages();
			var cart_items = Session.getCart();
			var downloads = Session.getDownloads();
			var i, item, subtotal, shipping, display_value, handling;
			for (i=0; i<products.length; ++i) {
				item = products[i];
				subtotal = parseFloat(item.subtotal);
				shipping = parseFloat(item.shipping);
				cart_subtotal += isNaN(subtotal) ? 0 : subtotal;
				shipping_subtotal += isNaN(shipping) ? 0 : shipping;
			}
			for (i=0; i<cart_items.length; ++i) {
				item = cart_items[i];
				subtotal = parseFloat(item.subtotal) * parseFloat(item.quantity);
				shipping = parseFloat(item.shipping) * parseFloat(item.quantity);
				cart_subtotal += isNaN(subtotal) ? 0 : subtotal;
				shipping_subtotal += isNaN(shipping) ? 0 : shipping;
			}
			for (i=0; i<downloads.length; ++i) {
				item = downloads[i];
				subtotal = parseFloat(item.subtotal);
				download_subtotal += isNaN(subtotal) ? 0 : subtotal;
			}
			order.final_value = cart_subtotal + download_subtotal;
			order.discount_value = 0;
			order.final_shipping = 0;
			order.final_handling = 0;
			order.final_tax = 0;
			if (options.tax.included) {
				cart_subtotal = Func.addSalesTax(cart_subtotal);
				cart_subtotal += options.downloads.tax ? Func.addSalesTax(download_subtotal) : download_subtotal;
			} else {
				cart_subtotal += download_subtotal;
			}
			$("#cart-total").find(".Value").html(Func.getFormattedPrice(cart_subtotal));
			if (options.discount) {
				if (discount[0]=="true") {
					// true, 216d8, 9501, 50off, fdsafdas, 50, percentage, 4, 5, 0, 1
					var discount_type = discount[5];
					var discount_value = parseFloat(discount[4]);
					order.discount_value = discount_type=="percentage" ? order.final_value*(discount_value/100) : discount_value;
					if (order.discount_value>order.final_value) {
						order.discount_value = order.final_value;
					}
					display_value = order.discount_value;
					if (options.tax.included) {
						display_value = Func.addSalesTax(display_value);
					}
					$("#cart-discount").find(".Value").html(Func.getFormattedPrice(display_value*-1));
				} else if (discount[0]=="false") {
					order.discount_value = 0;
					$("#cart-discount").find(".Value").html(L10N.get("checkout", "checkout_"+discount[1]));
				} else {
					order.discount_value = 0;
					$("#cart-discount").find(".Value").html(Func.getFormattedPrice(0));
				}
				display_value = order.final_value - order.discount_value - download_subtotal;
				if (display_value<0) {
					display_value = 0;
				}
				if (options.tax.included) {
					display_value = Func.addSalesTax(display_value);
					display_value += options.downloads.tax ? Func.addSalesTax(download_subtotal) : download_subtotal;
				} else {
					display_value += download_subtotal;
				}
				$("#cart-subtotal").find(".Value").html(Func.getFormattedPrice(display_value));
			}
			shipping_subtotal += (order.final_value-order.discount_value)*(options.shipping.rate/100);
			if (options.shipping.use) {
				if (order.shipping_method=="local") {
					shipping_subtotal = 0;
				}
				if ( products.length==0 && cart_items.length==0 && downloads.length>0 ) {
					shipping_subtotal = 0;
				}
				if (options.discount) {
					if (discount[0]=="true"&&discount[10]=="1") {
						shipping_subtotal = 0;
					}
				}
				order.final_shipping = shipping_subtotal;
				display_value = shipping_subtotal;
				if (options.tax.included&&options.shipping.tax) {
					display_value = Func.addSalesTax(display_value);
				}
				$("#cart-shipping").find(".Value").html(Func.getFormattedPrice(display_value));
				if (options.intl&&options.handling.intl>0) {
					handling = options.country!=order.country_code ? options.handling.intl : 0;
					if (order.shipping_method=="local") {
						handling = 0;
					}
					if ( products.length==0 && cart_items.length==0 && downloads.length>0 ) {
						handling = 0;
					}
					if (options.discount) {
						if (discount[0]=="true"&&discount[10]=="1") {
							handling = 0;
						}
					}
					order.final_handling += handling;
					display_value = handling;
					if (options.tax.included&&options.handling.tax) {
						display_value = Func.addSalesTax(display_value);
					}
					$("#cart-handling-intl").find(".Value").html(Func.getFormattedPrice(display_value));
				}
				if (options.handling.flat>0) {
					handling = options.handling.flat;
					if (order.shipping_method=="local") {
						handling = 0;
					}
					if ( products.length==0 && cart_items.length==0 && downloads.length>0 ) {
						handling = 0;
					}
					if (options.discount) {
						if (discount[0]=="true"&&discount[10]=="1") {
							handling = 0;
						}
					}
					order.final_handling += handling;
					display_value = handling;
					if (options.tax.included&&options.handling.tax) {
						display_value = Func.addSalesTax(display_value);
					}
					$("#cart-handling").find(".Value").html(Func.getFormattedPrice(display_value));
				}
			}
			if (options.tax.use) {
				var taxes = getTaxRate();
				var taxable_amount = order.final_value - order.discount_value;
				if (options.downloads.tax==false) {
					taxable_amount -= download_subtotal;
				}
				if (taxable_amount<0) {
					taxable_amount = 0;
				}
				if (options.shipping.tax) {
					taxable_amount += order.final_shipping;
				}
				if (options.handling.tax) {
					taxable_amount += order.final_handling;
				}
				if (options.country=="CA") {
					var hst_value = taxable_amount*(taxes[0]/100);
					var gst_value = taxable_amount*(taxes[1]/100);
						if (taxes[3]==true) {
							taxable_amount += gst_value;
						}
					var pst_value = taxable_amount*(taxes[2]/100);
					order.final_tax += hst_value;
					order.final_tax += gst_value;
					order.final_tax += pst_value;
					$("#cart-tax-hst").toggle(taxes[0]!=0);
					$("#cart-tax-gst").toggle(taxes[1]!=0);
					$("#cart-tax-pst").toggle(taxes[2]!=0);
					$("#cart-tax-hst").find(".Label").html("HST" + " - " + taxes[0] + "%");
					$("#cart-tax-gst").find(".Label").html("GST" + " - " + taxes[1] + "%");
					$("#cart-tax-pst").find(".Label").html("PST" + " - " + taxes[2] + "%");
					$("#cart-tax-hst").find(".Value").html(Func.getFormattedPrice(hst_value));
					$("#cart-tax-gst").find(".Value").html(Func.getFormattedPrice(gst_value));
					$("#cart-tax-pst").find(".Value").html(Func.getFormattedPrice(pst_value));
				} else {
					var tax_label = options.country=="US" ? "Sales Tax" : L10N.get("checkout", "checkout_cart_tax");
					var tax_value = taxable_amount*(taxes[0]/100);
					order.final_tax += tax_value;
					$("#cart-tax").find(".Label").html(tax_label + " - " + taxes[0] + "%");
					$("#cart-tax").find(".Value").html(Func.getFormattedPrice(order.final_tax));
				}
			}
			$("#cart-final-total").find(".Value").html(Func.getFormattedPrice(order.final_value-order.discount_value+order.final_shipping+order.final_handling+order.final_tax));
		}
		function updatePaymentMethod () {
			var products = Session.getPackagesLength();
			var cart_items = Session.getCartLength();
			var downloads = Session.getDownloadsLength();
			var subtotal = ( order.final_value - order.discount_value ) + order.final_shipping + order.final_handling + order.final_tax;
			$("#checkout-shipping").show();
			$("#checkout-shipping h2").show();
			$("#checkout-shipping .Wrapper").show();
			$("#cart-shipping, #cart-handling-intl, #cart-handling").show();
			$("#cart-tax").show();
			if (options.tax.use) {
				var taxes = getTaxRate();
				$("#cart-tax-hst").toggle(taxes[0]!=0);
				$("#cart-tax-gst").toggle(taxes[1]!=0);
				$("#cart-tax-pst").toggle(taxes[2]!=0);
			}
			if (options.offline) {
				$("#checkout-method-offline").removeAttr("disabled", "disabled")
					.next()
					.removeClass("Disabled");
			}
			if ( downloads>0 && cart_items==0 && products==0 ) {
				order.shipping_method = "local";
				$("#checkout-shipping input[name=shipping-method][value=" + order.shipping_method + "]").prop('checked', 'checked');
				$("#checkout-shipping h2").hide();
				$("#checkout-shipping .Wrapper").hide();
				$("#cart-shipping, #cart-handling-intl, #cart-handling").hide();
				if ( options.offline && subtotal>0 ) {
					$("#checkout-method-offline").attr("disabled", "disabled")
						.next()
						.addClass("Disabled");
					if (order.payment_method=="offline") {
						if (options.paypal) {
							order.payment_method = "paypal";
						}
						if (options.merchant) {
							order.payment_method = "merchant";
						}
						$("#checkout-payment input[name=checkout-method][value=" + order.payment_method + "]").prop('checked', 'checked');
					}
				}
				if (!options.downloads.tax) {
					$("#checkout-shipping").hide();
					$("#cart-tax-hst, #cart-tax-gst, #cart-tax-pst, #cart-tax").hide();
				}
			}
			$("#checkout-country option").eq(0).html( order.shipping_method=="local" ? L10N.get("checkout", "checkout_billing_country") : L10N.get("checkout", "checkout_shipping_country") );
			$("#checkout-shipping-postal-code").attr( "placeholder", order.shipping_method=="local" ? L10N.get("checkout", "checkout_billing_postal_code") : L10N.get("checkout", "checkout_shipping_postal_code") );
			if (order.payment_method=="paypal") {
				$("#shipping-method-ship").next().html(L10N.get("checkout", "checkout_shipping_method_ship_paypal"));
				$("#checkout-cc").hide();
				$("#checkout-info").hide();
				$("#checkout-shipping_address").hide();
			} else if (order.payment_method=="offline") {
				$("#shipping-method-ship").next().html(L10N.get("checkout", "checkout_shipping_method_ship"));
				$("#checkout-cc").hide();
				$("#checkout-info").show();
				$("#checkout-shipping_address").toggle( order.shipping_method!="local" );
			} else if ( order.payment_method=="merchant") {
				$("#shipping-method-ship").next().html(L10N.get("checkout", "checkout_shipping_method_ship"));
				$("#checkout-cc").toggle(subtotal>0);
				$("#checkout-info").show();
				$("#checkout-shipping_address").toggle( order.shipping_method!="local" );
			}
			if ( options.offline && (options.merchant||options.paypal) ) {
				$("#checkout-method-merchant, #checkout-method-paypal").removeAttr("disabled", "disabled")
					.next()
					.removeClass("Disabled");
				if (subtotal==0) {
					$("#checkout-method-merchant, #checkout-method-paypal").attr("disabled", "disabled")
						.next()
						.addClass("Disabled");
					if (order.payment_method!="offline") {
						order.payment_method = "offline";
						$("#checkout-payment input[name=checkout-method][value=" + order.payment_method + "]").prop('checked', 'checked');
					}
				}
			}
			if ( !options.offline && order.payment_method=="paypal" && subtotal==0 ) {
				$("#checkout-info").show();
				$("#shipping-method-ship").next().html(L10N.get("checkout", "checkout_shipping_method_ship"));
				$("#checkout-shipping_address").toggle( order.shipping_method!="local" );
			}
			$("#checkout-country").toggle( options.tax.use || ( options.shipping.use && options.handling.intl>0 && order.shipping_method!="local" ));
			if ( options.country=="US" || options.country=="CA" ) {
				$("#checkout-state").toggle( options.country==order.country_code );
				$("#checkout-shipping-postal-code").toggle( $("#checkout-shipping_address").is(":visible") );
			} else {
				$("#checkout-shipping-postal-code").toggle( order.shipping_method!="local" );
				$("#cart-tax").toggle( options.tax.included==false );
			}
			//$("#checkout-discount").toggle(subtotal>0);
		}
		function prevent (event) {
			event.stopPropagation();
			event.preventDefault();
		}
		function applyDiscountCode (str) {
			// skip empty codes
			var input = $("#checkout-discount input");
			var button = $("#checkout-discount button");
			// enable button + field
			input.removeAttr("disabled");
			button.click(click).removeClass(".Disabled");
			if (str==""||!str) {
				discount = [];
			} else {
				discount = str.split("\t");
			}
			updateTotals();
			updatePaymentMethod();
		}
		function checkDiscountCode () {
			// skip empty codes
			var input = $("#checkout-discount input");
			var button = $("#checkout-discount button");
			var codeval = input.val();
			if (codeval=="") {
				return;
			}
			// disable button + field
			input.attr("disabled", "disabled");
			button.off().addClass(".Disabled");
			// ccall it
			$.post( APP_ROOT + "vend-proofing-gateway.php", {
				action: 	"verify_discount_code",
				puid: 	Overlay.pageid(),
				code: 	codeval,
				subtotal: 	order.final_value
			}, function(data) {
				applyDiscountCode(data);
			});
		}
		function click (event) {
			if ( $(this).attr("id") == "checkout-clickwrap" ) {
				Controlbar.dispatch("onPageView", [ "tos" ]);
			}
			if ( $(this).attr("id") == "checkout-controlbar-process" ) {
				initPayment();
			}
			if ( $(this).parent().parent().attr("id") == "checkout-discount" ) {
				checkDiscountCode();
				updateTotals();
			}
			prevent(event);
			return false;
		}
		function change (event) {
			if ( $(this).attr("id") == "checkout-accept" ) {
				if (accept_obj.is(':checked')) {
					process_obj.removeClass("Disabled").addClass("Enabled").click(click);
				} else {
					process_obj.removeClass("Enabled").addClass("Disabled").off();
				}
			}
			if ( $(this).attr("id")=="shipping-method-local" || $(this).attr("id")=="shipping-method-ship" ) {
				order.shipping_method = $(this).val();
				updatePaymentMethod();
				updateTotals();
			}
			if ( $(this).parent().parent().parent().attr("id") == "checkout-payment" ) {
				order.payment_method = $(this).val();
				updatePaymentMethod();
				updateTotals();
			}
			if ( $(this).attr("id") == "checkout-state" ) {
				order.state_code = $(this).val();
				updateTotals();
			}
			if ( $(this).attr("id") == "checkout-country" ) {
				order.country_code = $(this).val();
				updateTotals();
			}
			if ( $(this).attr("id") == "checkout-shipping-postal-code" ) {
				order.postal_code = $(this).val();
				updateTotals();
			}
			prevent(event);
			return false;
		}
		function disable (eo) {
			screen.toggle(eo.open);
			screen.progress(eo.open==false);
		}
		function checkForEmptyCart () {
			if ( location.hash=="#/checkout/" && Cart.checkout(true)==false ) {
				Controlbar.dispatch("onPageView", [ "cart" ]);
				return;
			}
		}
		function session () {
			if ( inited==false) {
				inited = true;
				setTimeout(checkForEmptyCart, 33);
			}
			updateTotals();
			updatePaymentMethod();
		}
		function draw () {
			// cache some jquery objects
			container = $("#overlay-checkout");
			screen = $("#checkout-screen");
			blocks = $("#checkout-blocks");
			summary = $("#checkout-summary");
			back_obj = $("#checkout-controlbar-back");
			process_obj = $("#checkout-controlbar-process");
			accept_obj = $("#checkout-accept");
			clickwrap_obj = $("#checkout-clickwrap");
			sidebar_input = $("#sidebar-input");
			sidebar_input_content = $("#sidebar-input-content");
			back_obj.click(click);
			if (accept_obj.length>0) {
				accept_obj.change(change);
				clickwrap_obj.click(click);
				process_obj.removeClass("Enabled").addClass("Disabled").off();
			} else {
				process_obj.click(click);
			}
			// add listener to shipping selector
			if (options.country=="US") {
				order.state_code = options.state;
			}
			if (options.country=="CA") {
				order.state_code = options.province;
			}
			order.country_code = options.country;
			if ($("#checkout-shipping .Block").children().length==0) {
				$("#checkout-shipping").hide();
			} else {
				$("#checkout-shipping input, #checkout-shipping select").change(change);
			}
			// decide on the payment view
			var count = 0;
			if (options.offline) {
				count += 1;
			}
			if (options.paypal) {
				count += 1;
			}
			if (options.merchant) {
				count += 1;
			}
			if (count<=1) {
				$("#checkout-payment").hide();
			}
			if (count==0) {
				cart_no_payment = true;
			}
			if (options.offline) {
				order.payment_method = "offline";
			}
			if (options.paypal) {
				order.payment_method = "paypal";
			}
			if (options.merchant) {
				order.payment_method = "merchant";
			}
			$("#checkout-payment input").change(change);
			$("#checkout-payment input[name=checkout-method][value=" + order.payment_method + "]").prop('checked', 'checked');
			// add listener to credit card stuff selector
			$("#checkout-cc select").change(change);
			// discount code
			$("#checkout-discount button").click(click);
			// update tally board
			var zero = Func.getFormattedPrice(0);
			var pass = L10N.get("checkout", "checkout_cart_no_calculate");
			$("#summary-table").find(".Value").html(zero);
			if (!options.shipping.use) {
				$("#cart-shipping").find(".Value").html(pass);
			}
			if (!options.tax.use) {
				$("#cart-tax, #cart-tax-hst, #cart-tax-gst, #cart-tax-pst").find(".Value").html(pass);
			}
			// update
			updateTotals();
		}
		function resize () {
			var sw = StageProxy.width();
			if (sw>600) {
				var sh = StageProxy.height();
				$("#checkout-blocks").css("min-height", sh-65-40);
			} else {
				$("#checkout-blocks").css("min-height", "auto");
			}
		}
		function onFinalizeOrder (success, data) {
			if (success==false) {
				disable({open:false});
				Dialog.options({
					modal: false,
					title: L10N.get("checkout", "checkout_credit_card_error"),
					description: L10N.get("checkout", "checkout_credit_card_"+data)
				});
				Dialog.draw();
				recheck = true;
				process_obj.click(click);
			} else {
				var form = '<form action="' + APP_ROOT + "?/order/" + order.id + "/invoice/" + '" method="post">';
				form += '<input type="text" name="email_address" value="' + $("#checkout-email-address").val() + '" />';
				form += '</form>';
				form = $(form);
				$('body').append(form);
				$(form).submit();
			}
		}
		function finalizeOrder (iscc) {
			var subtotal = ( order.final_value - order.discount_value ) + order.final_shipping + order.final_handling + order.final_tax;
				if (subtotal==0) {
					iscc = false;
				}
				subtotal = subtotal.toFixed(2);
			var shipping_address;
			if ($("#checkout-shipping_address").hasClass("INTL")) {
				shipping_address = $("#checkout-shipping_address").val();
				shipping_address = shipping_address.split("\t").join("     ").split("\r").join("<[[BR]]>").split("\n").join("<[[BR]]>");
			} else {
				shipping_address = $("#checkout-shipping_address-line1").val();
				shipping_address += "<[[BR]]>";
				shipping_address += $("#checkout-shipping_address-line2").val();
				shipping_address += "<[[BR]]>";
				shipping_address += $("#checkout-shipping_address-city").val();
			}
			var comments = $("#checkout-comments textarea").val();
				comments = comments.split("\t").join("     ").split("\r").join("<[[BR]]>").split("\n").join("<[[BR]]>");
			var dataarr = [];
				dataarr.push(order.id);						// order id
				dataarr.push(Overlay.pageid());						// original set id
				dataarr.push(0);								// order timestamp
				dataarr.push(order.payment_method);					// payment type
				dataarr.push("");								// paypal id
				dataarr.push(order.shipping_method);					// shipping type
				dataarr.push($("#checkout-discount_code").val());		// discount applied
				dataarr.push($("#checkout-fullname").val());			// full name
				dataarr.push($("#checkout-email-address").val());			// email address
				dataarr.push($("#checkout-phone-number").val());			// phone number
				dataarr.push(shipping_address);					// normalized shipping address
				dataarr.push(order.country_code);					// country
				dataarr.push(order.postal_code);					// postal code
				dataarr.push(order.state_code);					// state
				dataarr.push(subtotal);							// subtotal
				dataarr.push( ( order.final_value ).toFixed(2) );					// total cart price
				dataarr.push( ( order.discount_value ).toFixed(2) );					// discount value
				dataarr.push( ( order.final_shipping ).toFixed(2) );					// shipping
				dataarr.push( ( order.final_handling ).toFixed(2) );					// handling
				dataarr.push( ( order.final_tax ).toFixed(2) );						// tax
				dataarr.push(getTaxRate().join(","));					// taxrate info
				dataarr.push(options.tax.included);			// taxrate info
				dataarr.push(options.shipping.tax);				// taxrate info
				dataarr.push(options.handling.tax);				// taxrate info
				dataarr.push(comments);								// comments
			var post = {};
			if (iscc) {
				post.cc_num = $("#checkout-cc-number").val();
				post.cc_expiry = $("#checkout-cc-expiry-month").val() + $("#checkout-cc-expiry-year").val();
				post.cc_cvv = $("#checkout-cvv-number").val();
				post.cc_zip = $("#checkout-cc-billing-postal-code").val();
			}
			post.puid = Overlay.pageid();
			post.name = Session.getHash();
			post.data = dataarr.join("\t");
			post.action = iscc ? "process_credit_card" : "finalize_order";
			$.post( APP_ROOT + "vend-proofing-gateway.php", post, function(str) {
				var bits = str.split("\t");
				var success = bits.shift();
					success = success=="true";
				onFinalizeOrder(success, bits.join("\t"));
			});
		}
		function processPayment () {
			if (order.payment_method=="paypal") {
				if ( (order.final_value>order.discount_value) || order.final_shipping>0 || order.final_handling>0 || order.final_tax>0 ) {
					var input = $("#checkout-discount input");
					var codeval = input.val();
					var comments = $("#checkout-comments textarea").val();
						comments = comments.split("\t").join("     ").split("\r").join("<[[BR]]>").split("\n").join("<[[BR]]>");
					var post = {};
					post.on0 = L10N.get("ordering", "sidebar_comments");
					post.os0 = comments;
					post.cmd = "_xclick";
					post.notify_url = APP_ROOT_ABSOLUTE + "/vend-proofing-gateway.php?action=validate_paypal_ipn";
					post["return"] = APP_ROOT_ABSOLUTE + "/?/order/" + order.id + "/invoice/";
					post.cancel_return = window.location;
					post.rm = "2";
					post.invoice = order.id;
					post.custom = Overlay.pageid() +
								"-" + Session.getHash() +
								"-" + order.final_value +
								"-" + order.discount_value +
								"-" + codeval +
								"-" + getTaxRate().join(",") +
								"-" + (options.tax.included?"1":"0") +
								"-" + (options.shipping.tax?"1":"0") +
								"-" + (options.handling.tax?"1":"0");
					post.item_name = classes.content.Display.settings().title + " - " + L10N.get("checkout", "checkout_paypal_order");
					post.item_number = Overlay.pageid();
					if ( order.final_value==order.discount_value ) {
						post.amount = ( order.final_shipping + order.final_handling + order.final_tax ).toFixed(2);
						post.shipping = 0;
						post.handling = 0;
						post.tax = 0;
					} else {
						post.amount = ( order.final_value ).toFixed(2);
						post.discount_amount = ( order.discount_value ).toFixed(2);
						if ( options.shipping.use ) {
							post.shipping = ( order.final_shipping ).toFixed(2);
							post.handling = ( order.final_handling ).toFixed(2);
						}
						if ( options.tax.use ) {
							post.tax = ( order.final_tax ).toFixed(2);
						}
					}
					post.no_shipping = order.shipping_method=="local" ? "1" : "2";
					post.currency_code = options.currency;
					post.business = $.base64.decode(options.business);
					post.lc = order.country_code;
					post.no_note = "1";
					var form = '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">';
					var prop;
					for ( prop in post ) {
						if (post.hasOwnProperty(prop)) {
							form += "\n\t" + '<input type="text" name="' + prop + '" value="' + post[prop] + '" />';
						}
					}
					form += "\n" + '</form>';
					form = $(form);
					$('body').append(form);
					$(form).submit();
				} else {
					finalizeOrder(false);
				}
			} else if ( order.payment_method=="offline" ) {
				finalizeOrder(false);
			} else if ( order.payment_method=="merchant" ) {
				finalizeOrder(true);
			} else {
				finalizeOrder(false);
			}
		}
		function onPrequalifyResponse (success, data) {
			if (success==false) {
				disable({open:false});
				if (data=="invalid_email_address") {
					$("#checkout-email-address").addClass("Highlight");
					Dialog.options({
						modal: false,
						title: L10N.get("checkout", "checkout_invalid_email_address_title"),
						description: L10N.get("checkout", "checkout_invalid_email_address_description")
					});
					Dialog.draw();
					process_obj.click(click);
				} else { // it's a discount code error
					var input = $("#checkout-discount input");
					var button = $("#checkout-discount button");
					input.removeAttr("disabled");
					button.click(click).removeClass(".Disabled");
					Dialog.options({
						modal: false,
						title: L10N.get("checkout", "checkout_discount_code_error_title"),
						description: L10N.get("checkout", "checkout_discount_code_error_description")
					});
					Dialog.draw();
					process_obj.click(click);
				}
			} else {
				order.id = data;
				processPayment();
			}
		}
		function sslCheckConfirm () {
			ignore_ssl_warning = true;
			initPayment();
		}
		function initPayment () {
			if (cart_no_payment) {
				Dialog.options({
					modal: false,
					title: "No Payment Options Available",
					description: "This cart does not have any available payment methods for ordering.  Please contact the photographer directly for help processing this order."
				});
				Dialog.draw();
				return false;
			}
			process_obj.off();
			// assume the best
			var error_code = "";
			$("#checkout-blocks input, #checkout-blocks textarea, #checkout-blocks select").removeClass("Highlight");
			if ( $("#checkout-info").is(":visible") ) {
				if ( $("#checkout-email-address").val()=="" ) {
					$("#checkout-email-address").addClass("Highlight");
					error_code = "highlighted_fields_required";
				}
				if (error_code=="") {
					if ($("#checkout-email-address").val()!=$("#checkout-email-address-check").val()) {
						$("#checkout-email-address").addClass("Highlight");
						$("#checkout-email-address-check").addClass("Highlight");
						error_code = "email_addresses_do_not_match";
					}
				}
			}
			// ok, check everything else now
			if (error_code=="") {
				var items = "#checkout-fullname, #checkout-phone-number, #checkout-shipping-postal-code, #checkout-state, #checkout-country, #checkout-cc-number, #checkout-cvv-number, #checkout-cc-expiry-month, #checkout-cc-expiry-year, #checkout-cc-billing-postal-code";
				if ($("#checkout-shipping_address").hasClass("INTL")) {
					items += ", #checkout-shipping_address";
				} else {
					items += ", #checkout-shipping_address-line1, #checkout-shipping_address-city";
				}
				$(items)
					.removeClass("Highlight")
					.each(function () {
						if ( $(this).is(":visible") && $(this).val()=="" ) {
							$(this).addClass("Highlight");
							error_code = "highlighted_fields_required";
						}
					});
			}
			if (error_code!="") {
				Dialog.options({
					modal: false,
					title: L10N.get("checkout", "checkout_" + error_code + "_title"),
					description: L10N.get("checkout", "checkout_" + error_code + "_description")
				});
				Dialog.draw();
				process_obj.click(click);
				return false;
			}
			var subtotal = ( order.final_value - order.discount_value ) + order.final_shipping + order.final_handling + order.final_tax;
			/*if ( order.payment_method=="paypal"&&subtotal==0 ) {
				Dialog.options({
					modal: false,
					title: L10N.get("checkout", "checkout_paypal_price_zero_title"),
					description: L10N.get("checkout", "checkout_paypal_price_zero_description")
				});
				Dialog.draw();
				process_obj.click(click);
				return;
			}*/
			var downloads = Session.getDownloadsLength();
			if ( subtotal>0 && order.payment_method=="offline" && downloads>0 ) {
				Dialog.options({
					modal: false,
					title: L10N.get("checkout", "checkout_offline_unavailable_with_downloads_title"),
					description: L10N.get("checkout", "checkout_offline_unavailable_with_downloads_description")
				});
				Dialog.draw();
				process_obj.click(click);
				return;
			}
			if ( order.payment_method=="merchant" && "https:"!=document.location.protocol && ignore_ssl_warning==false ) {
				Dialog.options({
					title: L10N.get("checkout", "checkout_cart_insecure_title"),
					description: L10N.get("checkout", "checkout_cart_insecure_description"),
					confim: sslCheckConfirm
				});
				Dialog.draw();
				process_obj.click(click);
				return;
			} 
			// ok, lets's do it
			disable({open:true});
			var input = $("#checkout-discount input");
			var button = $("#checkout-discount button");
			var codeval = input.val();
			input.attr("disabled", "disabled");
			button.off().addClass(".Disabled");
			$.post( APP_ROOT + "vend-proofing-gateway.php", {
				action: 	"prequalify_order",
				puid: 	Overlay.pageid(),
				orderid: 	order.id,
				subtotal: 	order.final_value,
				code: 	( recheck ? codeval : "" ),
				email: 	order.payment_method=="paypal" ? "" : $("#checkout-email-address").val()
			}, function(str) {
				var bits = str.split("\t");
				var success = bits.shift();
					success = success=="true";
				onPrequalifyResponse(success, bits.join("\t"));
			});
		}
		function init () {
			draw();
			resize();
		}
		function lateinit () {
			StageProxy.addEventListener("onResize", resize);
			Session.addEventListener("onSessionLoaded", session);
			Session.addEventListener("onSessionCart", session);
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		/* public methods
			*/
		this.setMail = function(str) {
			$("#checkout-email-address").val(str);
		}
		this.update = function() {
			if ( inited==true ) {
				checkForEmptyCart();
			}
			updateTotals();
			updatePaymentMethod();
		};
		this.settings = function(obj) {
			if (obj) {
				options = obj;
			}
			return options;
		};
		this.addTaxRule = function(arr) {
			taxrules.push(arr);
		};
		this.getTaxRate = function() {
			return getTaxRate();
		};
		this.initialize = function() {
			StageProxy = classes.StageProxy;
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			Overlay = classes.Overlay;
			Session = classes.Session;
			Dialog = classes.Dialog;
			Cart = classes.overlay.Cart;
			Controlbar = classes.elements.Controlbar;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Clickwrap = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var Controlbar; // shortcut
		/* private properites
			*/
		/* private methods
			*/
		function back () {
			Controlbar.dispatch("onPageView", [ "checkout" ]);
		}
		function draw () {
			$("#clickwrap-controlbar-back").click(back);
		}
		function render () {
			draw();
		}
		/* public methods
			*/
		this.initialize = function() {
			Controlbar = classes.elements.Controlbar;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Overview = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy; // shortcut
		var Shell; // shortcut
		var Func; // shortcut
		var L10N; // shortcut
		var Session; // shortcut
		var Cart; // shortcut
		var Graphic; // shortcut
		var Checkout; // shortcut
		/* private properites
			*/
		var download = 			false;
		var remainder = 		-1;
		var maximum = 			null;
		var data = 				{};
		var datahash = 			"";
		var overlay_overview = 	null;
		var overview_screen = 	null;
		var overview_options = 	null;
		var overview_quantity = null;
		var update_obj = 		null;
		/* private methods
			*/
		function disable (eo) {
			overview_screen.toggle(eo.open);
			overview_screen.progress(eo.open==false);
		}
		function getQuantityVal () {
			return parseInt($("#overview-quantity").find("span").html(), 10);
		}
		function update () {
			disable({open:true});
			Session.updateItem("cart", data.hash, "quantity", getQuantityVal());
		}
		function clearcart () {
			Cart.clear();
		}
		function checkout () {
			Cart.checkout();
		}
		function check () {
			// disable the add button for now
			update_obj.removeClass("Enabled").addClass("Disabled").off();
			var quantity = parseInt(data.quantity, 10);
			if (getQuantityVal()==quantity) {
				return;
			}
			// enable the control
			update_obj.removeClass("Disabled").addClass("Enabled").click(update);
		}
		function numberevent (event) {
			var self = $(this);
			var parent = self.parent();
			var current = parseInt(parent.find("span").html(), 10);
			var delta = parseInt(self.val(), 10);
			var value = current + delta;
				if (value<=0) {
					value = 1;
				}
				if (maximum!=null) {
					if (value>maximum) {
						value = maximum;
					}
				}
			$("#overview-quantity").find("span").html(value);
			check();
			return false;
		}
		function close () {
			$("#overlay-cartview .Wide").removeClass("Column1");
			$("#overlay-cartview .Column2").hide();
			$(".LineItem").removeClass("Active");
			return false;
		}
		function resize () {
			var sw = StageProxy.width();
			var sh = StageProxy.height();
			$("#overlay-overview").off();
			if (sw>600) {
				var left = $("#overlay-cartview .Column1").height()+65;
				var sh = Math.max(left, StageProxy.height());
				$("#overlay-overview").css("min-height", sh-65);
				$("#overlay-overview").css("height", "auto");
			} else {
				$("#overlay-overview").css("min-height", "none");
				$("#overlay-overview").css("height", sh);
				if (Shell.device().touch) {
					$("#overlay-overview").bind('touchstart', Func.touchboundsstart);
					$("#overlay-overview").bind('touchmove', Func.touchboundsmove);
				} else {
					$("#overlay-overview").mousewheelStopPropagation();
				}
			}
		}
		function drawControls () {
			$("#overview-controlbar-clearcart, #overview-controlbar-checkout, #overview-controlbar-update, #overview-controlbar-cancel")
				.each(function () {
					var self = $(this);
					var tooltip = self.attr("data-tooltip");
					var func = self.attr("id");
						func = func.split("-");
						func = func.pop();
						switch (func) {
							case "cancel" :
								func = close;
								break;
							case "clearcart" :
								func = clearcart;
								break;
							case "checkout" :
								func = checkout;
								break;
							case "next" :
								func = next;
								break;
							case "update" :
								func = update;
								break;
							case "prev" :
								func = prev;
								break;
						}
					if ( tooltip!="" && !Shell.device().touch ) {
						self
							.data("tooltip", tooltip)
							.mouseenter(function () {
								Shell.createToolTip($(this).data("tooltip"));
							})
							.mouseleave(function () {
								Shell.killToolTip();
							})
							.click(function (event) {
								$(this).unbind("mouseenter").unbind("mouseleave");
								Shell.killToolTip();
								func(event);
							});
					} else {
						self.click(func);
					}
				});
			overview_quantity.find("button").click(numberevent);
		}
		function draw () {
			overlay_overview = $("#overlay-overview");
			overview_screen = $("#overview-screen");
			overview_options = $("#overview-options");
			overview_quantity = $("#overview-quantity");
			update_obj = $("#overview-controlbar-update");
			update_obj.removeClass("Enabled").addClass("Disabled").off();
			overview_options.hide();
			drawControls();
		}
		function init () {
			draw();
			resize();
		}
		function onLoaded () {
			overview_options.find(".Display").progress(true);
			if (!download) {
				Func.filter($(this), data.toning);
			}
		}
		function redraw () {
			disable({open:false});
			// make sure there is a valid data object
			if (!data) {
				overview_options.hide();
				// disable the add button for now
				update_obj.removeClass("Enabled").addClass("Disabled").off();
				overview_options.hide();
				return;
			}
			// turn on tings
			overview_options.show();
			// disable the add button for now
			update_obj.removeClass("Enabled").addClass("Disabled").off();
			// these will affect the pricing labels
			var calculate_and_display_shipping_bool = Checkout.settings().shipping.use;
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var shipping_taxable_bool = Checkout.settings().shipping.tax;
			var downloads_taxable_bool = Checkout.settings().downloads.tax;
			var letterbox = true;
			var width = $("#overlay-overview").width();
			var image_width = width-24;
			var image_height = 200;
			var aspect = parseFloat(data.format_aspect);
			if (!isNaN(aspect)) {
				if (data.orientation=="l") {
					aspect = 1/aspect;
				}
				letterbox = false;
				image_width = Math.round(image_height*aspect);
			}
			var multiplier = window.devicePixelRatio ? window.devicePixelRatio : 1;
			var rw = image_width;
			var rh = image_height;
			if ( multiplier>1 ) {
				var rw = image_width*multiplier;
				if (rw>1000) {
					rw = 1000;
				}
				var rh = image_height*multiplier;
				if (rh>1000) {
					rh = 1000;
				}
			}
			var graphic = new Graphic();
				graphic.provider({
					child: data.cuid,
					parent: data.puid,
					hash: data.hash,
					src: data.puid + "/" + data.cuid,
					alt: data.filename,
					xoffset: data.orientation_x,
					yoffset: data.orientation_y
				});
				graphic.letterbox(letterbox);
				graphic.setSize(rw, rh);
			overview_options.find(".Display").progress();
			overview_options.find("img")
				.off()
				.data("original-src", "")
				.attr("src", Func.getEmptyImgSrc())
				.attr("src", graphic.source())
				.one('load', onLoaded)
				.each(function() {
					if(this.complete) {
						$(this).load();
					}
				});
			var title, price, shipping;
			var filename = data.filename;
			var bits = filename.split(".");
			bits.pop();
			filename = bits.join(".");
			$("#overview-options")
				.find("h2")
				.html(filename);
			if ( data.quality!="" && data.quality!=undefined ) {
				$("#overview-quality")
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_image_quality") );
				title = data.quality;
				price = parseFloat(data.subtotal);
					if (isNaN(price)) {
						price = 0;
					}
				if (price>0) {
					if ( purchase_price_includes_tax_bool && downloads_taxable_bool ) {
						price = Func.addSalesTax(price);
					}
					title += " (" + Func.getFormattedPrice(price) + ")";
				}
				$("#overview-quality")
					.find("span")
					.html( title );
			} else {
				$("#overview-quality").hide();
			}
			if ( data.format_label!="" && data.format_label!=undefined ) {
				$("#overview-format")
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_image_format") );
				title = data.format_label;
				price = parseFloat(data.format_price);
					if (isNaN(price)) {
						price = 0;
					}
				shipping = parseFloat(data.format_shipping);
					if (isNaN(shipping)) {
						shipping = 0;
					}
				if (price>0) {
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
					title += " (" + Func.getFormattedPrice(price) + ")";
				}
				if (calculate_and_display_shipping_bool&&shipping>0) {
					if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
						shipping = Func.addSalesTax(shipping);
					}
					title += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
				}
				$("#overview-format")
					.find("span")
					.html( title );
			} else {
				$("#overview-format").hide();
			}
			var quantity = parseInt(data.quantity, 10);
			if (!isNaN(quantity)) {
				$("#overview-controlbar-update").show();
				overview_quantity
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_change_quantity") + (remainder==-1?"":" ("+(quantity+remainder)+") "+L10N.get("ordering", "overview_package_maximum")) );
				maximum = remainder==-1 ? null : quantity+remainder;
				overview_quantity
					.find("span")
						.empty()
						.html(quantity);
			} else {
				$("#overview-controlbar-update").hide();
				overview_quantity.hide();
			}
			if ( data.toning!="" && data.toning!=undefined ) {
				$("#overview-tone")
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_toning") );
				title = data.toning=="sepia" ? L10N.get("ordering", "sidebar_tone_sepia") : L10N.get("ordering", "sidebar_tone_black_and_white");
				$("#overview-tone")
					.find("span")
					.html( title );
			} else {
				$("#overview-tone").hide();
			}
			if ( data.paper_label!="" && data.paper_label!=undefined ) {
				$("#overview-paper")
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_paper_format") );
				title = data.paper_label;
				price = parseFloat(data.paper_price);
					if (isNaN(price)) {
						price = 0;
					}
				shipping = parseFloat(data.paper_shipping);
					if (isNaN(shipping)) {
						shipping = 0;
					}
				if (price>0) {
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
					title += " (" + Func.getFormattedPrice(price) + ")";
				}
				if (calculate_and_display_shipping_bool&&shipping>0) {
					if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
						shipping = Func.addSalesTax(shipping);
					}
					title += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
				}
				$("#overview-paper")
					.find("span")
					.html( title );
			} else {
				$("#overview-paper").hide();
			}
			if ( data.modifier_label!="" && data.modifier_label!=undefined ) {
				$("#overview-modifier")
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_modifier") );
				title = data.modifier_label;
				price = parseFloat(data.modifier_price);
					if (isNaN(price)) {
						price = 0;
					}
				shipping = parseFloat(data.modifier_shipping);
					if (isNaN(shipping)) {
						shipping = 0;
					}
				if (price>0) {
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
					title += " (" + Func.getFormattedPrice(price) + ")";
				}
				if (calculate_and_display_shipping_bool&&shipping>0) {
					if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
						shipping = Func.addSalesTax(shipping);
					}
					title += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
				}
				$("#overview-modifier")
					.find("span")
					.html( title );
			} else {
				$("#overview-modifier").hide();
			}
			if ( data.orientation!="" && data.orientation!=undefined ) {
				$("#overview-orientation")
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_orientation") );
				title = data.orientation=="p" ? L10N.get("ordering", "sidebar_crop_portrait") : L10N.get("ordering", "sidebar_crop_landscape");
				$("#overview-orientation")
					.find("span")
					.html( title );
			} else {
				$("#overview-orientation").hide();
			}
			if ( data.comments!="" && data.comments!=undefined ) {
				$("#overview-comments")
					.show()
					.find("h3")
					.html( L10N.get("ordering", "overview_comments") );
				$("#overview-comments")
					.find("span")
					.html( data.comments );
			} else {
				$("#overview-comments").hide();
			}
		}
		function selected (eo) {
			$("#overlay-cartview .Wide").addClass("Column1");
			$("#overlay-cartview .Column2").show();
			datahash = eo.item + ":" + eo.group;
			if (eo.group=="alacarte") {
				datahash = eo.item;
			}
			if (eo.group=="download") {
				download = true;
				datahash = eo.item;
				data = Session.getDownloadObject(datahash);
			} else {
				download = false;
				data = Session.getCartObject(datahash);
			}
			if (!data) {
				redraw();
				return;
			}
			remainder = -1;
			if ( eo.group!="alacarte" && eo.group!="download" ) {
				var products_parsed = Session.getPackagesParsed();
				var i, product, format_hash, format_index, format;
				for (i=0; i<products_parsed.length; ++i) {
					product = products_parsed[i];
					if (product.row.hash==eo.group+"-p") {
						format_hash = md5(data.format_label);
						format_index = product.lookup[format_hash];
						format = product.formats[format_index];
						remainder = format.total - format.count;
						break;
					}
				}
			}
			redraw();
			resize();
		}
		function lateinit () {
			Cart.addEventListener("onCartItem", selected);
			StageProxy.addEventListener("onResize", resize);
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		/* public methods
			*/
		this.show = function(eo) {
			selected(eo);
		};
		this.hide = function() {
			close();
		};
		this.initialize = function() {
			StageProxy = classes.StageProxy;
			Graphic = classes.elements.Graphic;
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			Session = classes.Session;
			Shell = classes.Shell;
			Cart = classes.overlay.Cart;
			Checkout = classes.overlay.Checkout;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Package = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var StageProxy; // shortcut
		var Shell; // shortcut
		var Func; // shortcut
		var L10N; // shortcut
		var Overlay; // shortcut
		var Session; // shortcut
		var Packages; // shortcut
		var Graphic; // shortcut
		var Sidebar; // shortcut
		var FormDialog; // shortcut
		var Checkout; // shortcut
		var Controlbar; // shortcut
		/* private properites
			*/
		var type = 			"";
		var key = 			"";
		var backtobrowse = 	false;
		var data = 			null;
		var provider = 		{};
		var overlay_package = null;
		var package_display = null;
		var package_context = null;
		/* private methods
			*/
		function addPackage (nickname) {
			var uuid = new Date().getTime();
			var format_titles = [];
			var format_quantities = [];
			var format_aspects = [];
			var format_areas = [];
			var i, format;
			for (i=0; i<provider.formats.length; ++i) {
				format = provider.formats[i];
				format_titles.push(escape(format.title));
				format_quantities.push(format.quantity);
				format_aspects.push(format.aspect);
				format_areas.push(format.area);
			}
			var hash = md5(uuid+nickname+key);
			Session.addItem("package", {
				hash: 				hash,
				type: 				type,
				nickname: 			nickname,
				title: 				provider.title,
				quantity: 			1,
				subtotal: 			provider.price,
				shipping: 			provider.shipping,
				format_titles: 		"%:" + format_titles.join(","),
				format_quantities: 	format_quantities.join(","),
				format_aspects: 	format_aspects.join(","),
				format_areas: 		format_areas.join(",")
			});
			Sidebar.setActiveSelctionHash(hash.substr(0, 32));
			back();
			if (backtobrowse) {
				cancel();
			}
		}
		function cancel () {
			Controlbar.dispatch("onPageView", [ "browse", Overlay.getBrowseView(), Overlay.getWallView(), Overlay.getIndex(), Overlay.getBrowseIndex() ]);
		}
		function back () {
			$("#overlay-packages .Wide").removeClass("Column2");
			$("#overlay-packages .Column1").hide();
			$("#overlay-packages .LineItem").removeClass("Active");
		}
		function cart () {
			FormDialog.options({
				modal: 			true,
				field_label: 	L10N.get("ordering", "package_add_dialog_enter_nickname"),
				submit_label: 	L10N.get("ordering", "package_add_dialog_submit"),
				cancel_label: 	L10N.get("general", "dialog_cancel"),
				submit: 		function () {
					addPackage(FormDialog.inputvalue());
					FormDialog.kill();
				}
			});
			FormDialog.draw();
		}
		function processData (obj) {
			var calculate_and_display_shipping_bool = Checkout.settings().shipping.use;
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var shipping_taxable_bool = Checkout.settings().shipping.tax;
			var price_label = "";
			var price = parseFloat(obj.price);
			if (isNaN(price)) {
				price = 0;
			}
			var shipping = parseFloat(obj.shipping);
			if (isNaN(shipping)) {
				shipping = 0;
			}
			if (price>0) {
				if (purchase_price_includes_tax_bool) {
					price = Func.addSalesTax(price);
				}
				price_label += Func.getFormattedPrice(price);
			}
			if (calculate_and_display_shipping_bool&&shipping>0) {
				if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
					shipping = Func.addSalesTax(shipping);
				}
				if (price_label!="") {
					price_label += " + ";
				}
				price_label += Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
			}
			var desc = obj.description;
			if (desc=="") {
				desc = "<p>" + L10N.get("ordering", "package_no_description_heading") + "</p>";
				desc += "<ul>";
				var i, format;
				for (i=0; i<obj.formats.length; ++i) {
					format = obj.formats[i];
					desc += "<li>(" + format.quantity + ") " + format.title + "</li>";
				}
				desc += "</ul>";
			}
			var items = 0;
			for (var i=0; i<obj.formats.length; ++i) {
				var format = obj.formats[i];
				items += parseFloat(format.quantity);
			}
			if (items==0) items = "---";
			if (price_label=="") price_label = "---";
			return {
				price_label: price_label,
				items: items,
				desc: desc
			};
		}
		function onLoaded () {
		}
		function redraw () {
			$("#overlay-packages .Wide").addClass("Column2");
			$("#overlay-packages .Column1").show();
			$("#overlay-packages  .Column1 .Inner").scrollTop(0);
			var calculate_and_display_shipping_bool = Checkout.settings().shipping.use;
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var shipping_taxable_bool = Checkout.settings().shipping.tax;
			var price_label = "";
			var price = parseFloat(provider.price);
			if (isNaN(price)) {
				price = 0;
			}
			var shipping = parseFloat(provider.shipping);
			if (isNaN(shipping)) {
				shipping = 0;
			}
			if (price>0) {
				if (purchase_price_includes_tax_bool) {
					price = Func.addSalesTax(price);
				}
				price_label += Func.getFormattedPrice(price);
			}
			if (calculate_and_display_shipping_bool&&shipping>0) {
				if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
					shipping = Func.addSalesTax(shipping);
				}
				if (price_label!="") {
					price_label += " + ";
				}
				price_label += Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
			}
			var desc = provider.description;
			if (desc=="") {
				desc = "<p>" + L10N.get("ordering", "package_no_description_heading") + "</p>";
				desc += "<ul>";
				var i, format;
				for (i=0; i<provider.formats.length; ++i) {
					format = provider.formats[i];
					desc += "<li>(" + format.quantity + ") " + format.title + "</li>";
				}
				desc += "</ul>";
			}
			overlay_package.show();
			$("#overlay-packages-controlbar").show();
			overlay_package.find("h2").empty().html(provider.title);
			overlay_package.find("h3").empty().html(price_label);
			overlay_package.find(".Description").empty().html(desc);
			package_display.find("img").off().attr("src", Func.getEmptyImgSrc());
			if (provider.filename) {
				var width = $("#overlay-packages  .Column1 .Inner").width();
				var image_width = width-24;
				var image_height = 200;
				var graphic = new Graphic();
					graphic.provider({
						child: provider.filename,
						parent: type
					});
					graphic.letterbox(true);
					graphic.setSize(image_width, image_height);
				package_display
					.show()
					.find("img")
						.attr("src", graphic.source())
						.one('load', onLoaded)
						.each(function() {
							if(this.complete) {
								$(this).load();
							}
						});
			} else {
				package_display.hide();
			}
			resize();
		}
		function draw () {
			overlay_package = $("#overlay-package");
			package_display = overlay_package.find(".Display");
			package_context = $("#package-context");
			overlay_package.hide();
			$("#overlay-packages-controlbar").hide();
			$("#packages-controlbar-add, #packages-controlbar-back, #overlay-package-cancel")
				.each(function () {
					var self = $(this);
					var tooltip = self.attr("data-tooltip");
					var func = self.attr("id");
						func = func.split("-");
						func = func.pop();
						switch (func) {
							case "cancel" :
								func = cancel;
								break;
							case "add" :
								func = cart;
								break;
							case "back" :
								func = back;
								break;
						}
					if ( tooltip!="" && !Shell.device().touch ) {
						self
							.data("tooltip", tooltip)
							.data("func", func)
							.mouseenter(function () {
								Shell.createToolTip($(this).data("tooltip"));
							})
							.mouseleave(function () {
								Shell.killToolTip();
							})
							.click(function () {
								$(this).unbind("mouseenter").unbind("mouseleave");
								Shell.killToolTip();
								$(this).data("func")();
							});
					} else {
						self.click(func);
					}
				});
			for (var prop in data) {
				var obj = data[prop];
				var meta = processData(obj);
				$("#cart-item-"+obj.hash+" .col2").html(meta.items);
				$("#cart-item-"+obj.hash+" .col3").html(meta.price_label);
			}
		}
		function resize () {
			var sw = StageProxy.width();
			var sh = StageProxy.height();
			$("#overlay-packages  .Column1 .Inner").off();
			if (sw>600) {
				var left = $("#overlay-packages  .Column2").height()+65;
				var sh = Math.max(left, StageProxy.height());
				$("#overlay-packages  .Column1 .Inner").css("min-height", sh-65);
				$("#overlay-packages  .Column1 .Inner").css("height", "auto");
			} else {
				$("#overlay-packages  .Column1 .Inner").css("min-height", "none");
				$("#overlay-packages  .Column1 .Inner").css("height", sh);
				if (Shell.device().touch) {
					$("#overlay-packages  .Column1 .Inner").bind('touchstart', Func.touchboundsstart);
					$("#overlay-packages  .Column1 .Inner").bind('touchmove', Func.touchboundsmove);
				} else {
					$("#overlay-packages  .Column1 .Inner").mousewheelStopPropagation();
				}
			}
		}
		function select (eo) {
			type = eo.type;
			key = eo.key;
			provider = data[key];
			redraw();
			resize();
		}
		function lateinit () {
			Packages.addEventListener("onPackageSelected", select);
			StageProxy.addEventListener("onResize", resize);
		}
		function init () {
			draw();
			resize();
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		/* public methods
			*/
		this.setBackStyle = function(str) {
			backtobrowse = str=="1";
			$("#overlay-package-controlbar").toggle(backtobrowse);
			back();
		}
		this.add = function(key, obj) {
			if (data==null) {
				data = {};
			}
			data[key] = obj;
		};
		this.available = function() {
			return data!=null;
		};
		this.initialize = function() {
			StageProxy = classes.StageProxy;
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			Overlay = classes.Overlay;
			Session = classes.Session;
			Shell = classes.Shell;
			Packages = classes.overlay.Packages;
			Graphic = classes.elements.Graphic;
			FormDialog = classes.elements.FormDialog;
			Sidebar = classes.overlay.Sidebar;
			Checkout = classes.overlay.Checkout;
			Controlbar = classes.elements.Controlbar;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Packages = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		/* private properites
			*/
		var instance = 			this;
		var packages_packages = null;
		var packages_products = null;
		/* private methods
			*/
		function select (t, i, id) {
			var ui = t=="package" ? packages_packages : packages_products;
			$(".LineItem").removeClass("Active");
			$("#"+id).addClass("Active");
			instance.dispatch("onPackageSelected", { type:t, index:i, key:$("#"+id).data("value") });
		}
		function draw () {
			packages_packages = $("#packages-packages");
			packages_products = $("#packages-products");
			packages_packages.find(".LineItem").click(function () {
				select("package", $(this).index(), $(this).attr('id'));
			});
			packages_products.find(".LineItem").click(function () {
				select("product", $(this).index(), $(this).attr('id'));
			});
		}
		function render () {
			draw();
		}
		/* public methods
			*/
		this.initialize = function() {
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

/*jslint browser: true, continue: true, eqeq: true, plusplus: true, sloppy: true, vars: true, white: true */

classes.overlay.Sidebar = (function () {
	function Constructor () {
		/* "imported" classes
			*/
		var Shell; // shortcut
		var Func; // shortcut
		var L10N; // shortcut
		var Overlay; // shortcut
		var Session; // shortcut
		var Browser; // shortcut
		var Package; // shortcut
		var Checkout; // shortcut
		var Display; // shortcut
		var Controlbar; // shortcut
		/* private properites
			*/
		var instance = 			this;
		var original_x = 		0;
		var original_y = 		0;
		var hidden = 			true;
		var width = 			0;
		var height = 			0;
		var alacarte = 			[];
		var alacarte_lookup = 	{};
		var papers = 			[];
		var papers_lookup = 	{};
		var modifiers = 		[];
		var modifiers_lookup = 	{};
		var selection = {
			type:				"",
			quality:			"",
			browse_provider: 	[],
			browse: 			{ label:"", type: "none", hash: "none" },
			format_provider: 	[],
			format: 			{ price:"0", area:0, aspect:NaN, shipping:"0", maximum:-1 },
			paper_provider: 	[],
			paper: 				{ title:"", price:"0", shipping:"0" },
			modifier_provider:	[],
			modifier: 			{ title:"", price:"0", shipping:"0" },
			quantity: 			1,
			orientation:		"",
			toning:				"",
			x_offset: 			50,
			y_offset: 			50,
			comment: 			""
		};
		var cart_object = 	{};
		var last_selected_hash = 	"";

		var downloads_available = 	false;
		var packages_available = 	false;
		var alacarte_available = 	false;
		var packages_in_cart = 		false;
		var formats_available = 	false;
		var quantity_available = 	false;
		var toning_available = 		false;
		var papers_available = 		false;
		var modifiers_available = 	false;
		var cropping_available = 	false;
		var comments_available = 	false;
		var formats_visible = 		false;

		var overlay_sidebar= null;
			var sidebar_input = null;
			var sidebar_screen = null;
			var sidebar_input_screen = null;
			var sidebar_input_content = null;
				var sidebar_download = null;
				var sidebar_browse = null;
				var sidebar_selection = null;
				var sidebar_formats = null;
				var sidebar_quantity = null;
				var sidebar_toning = null;
				var sidebar_papers = null;
				var sidebar_modifiers = null;
				var sidebar_crop = null;
				var sidebar_comments = null;
			var sidebar_control = null;
			var checkout_obj = null;
		/* private methods
			*/
		function prevent (event) {
			event.stopPropagation();
			event.preventDefault();
		}
		function convertToJsEval (str) {
			if (str.indexOf("function")!=-1) {
				return str;
			}
			if (str.indexOf("Math")!=-1) {
				return str;
			}
			var math_props = ["E", "LN2", "LN10", "LOG2E", "LOG10E", "PI", "SQRT1_2", "SQRT2", "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "exp", "floor", "log", "max", "min", "pow", "random", "round", "sin", "sqrt", "tan"];
			var i, prop;
			for (i=0; i<math_props.length; ++i) {
				prop = math_props[i];
				str = str.split(prop).join("Math."+prop);
			}
			return str;
		}
		function evaluate (expr, format_area, quantity, format_price) {
			if (!expr) {
				expr = "0";
			}
			if (!format_area) {
				format_area = "0";
			}
			if (!quantity) {
				quantity = "0";
			}
			if (!format_price) {
				format_price = "0";
			}
			expr = expr.split("A").join(format_area);
			expr = expr.split("Q").join(quantity);
			expr = expr.split("P").join(format_price);
			expr = convertToJsEval(expr);
			try {
				return eval(expr);
			} catch(err) {
				return parseFloat(expr);
			}
		}
		function click (event) {
			if ( $(this).parent().attr("id") == "sidebar-browse" ) {
				Controlbar.dispatch("onPageView", [ "packages", "1" ]);
			}
			if ( $(this).attr("id") == "browse-controlbar-cart" ) {
				Controlbar.dispatch("onPageView", [ "cart" ]);
			}
			if ( $(this).attr("id") == "browse-controlbar-add" ) {
				disable({open:true});
				Session.addItem(selection.type, cart_object);
			}
			prevent(event);
			return false;
		}
		function radioevent (event) {
			var self = $(this);
			var form = self.parent();
			var parent = form.parent();
			if (parent.data("enabled")==false) return;
			var checked = form.find(':checked');
			parent.find("select")
				.val(checked.val())
				.trigger("change");
		}
		function numberevent (event) {
			var self = $(this);
			var parent = self.parent();
			if (parent.data("enabled")==false) return;
			var current = parseInt(parent.find("span").html(), 10);
			var delta = parseInt(self.val(), 10);
			var value = current + delta;
				if (value<=0) {
					value = 1;
				}
				if (value>selection.format.maximum) {
					value = selection.format.maximum;
				}
			parent.data("value", value);
			parent.find("span").html(value);
			check();
		}
		function textevent (event) {
			var self = $(this);
			var form = self.parent();
			var parent = form.parent();
			if (parent.data("enabled")==false) return;
			var input = form.find("textarea");
			var value = input.val();
			parent.data("value", value);
			check();
		}
		function downloadchange (event) {
			var self = $(this);
			var form = self.parent();
			var parent = form.parent();
			var checked = form.find(':checked');
			var value = checked.val();
			if ( value=="" || value==undefined || !value  ) {
				selection.type = "cart";
				selection.quality = "";
				enableinputs();
			} else if (value=="high" || value=="low") {
				selection.type = "download";
				selection.quality = value;
				disableinputs();
			}
			check();
		}
		function change (event) {
			var self = $(this);
			var parent = self.parent().attr("id") == "sidebar-input-content" ? sidebar_input_content.data("parent") : self.parent();
			var selected = self.find(':selected');
			var value = self.val();
			if (parent.data("enabled")==false) return;
			parent
				.data("index", selected.index())
				.data("value", value)
				.find("span").html(selected.html());
			if ( parent.attr("id") == "sidebar-selection" ) {
				group(value);
			} else {
				if ( parent.attr("id") == "sidebar-formats" ) {
					fixOrientation();
				}
				check();
				instance.dispatch("onChanged");
			}
			if ( parent.attr("id") == "sidebar-crop" || parent.attr("id") == "sidebar-toning" ) {
				instance.dispatch("onImageModify");
			}
			sidebar_input.hide();
			prevent(event);
			return false;
		}
		function showInputUI (event) {
			var self = $(this);
			var value = self.data("value");
			sidebar_input.show();
			sidebar_input_content
				.empty()
				.append('<div class="UIText"><div class="Wrapper"><textarea>' + value + '</textarea><button>' + L10N.get("ordering", "sidebar_comments_done") + '</button></div></div>')
				.data("parent", self)
				.find("button").click(hideInputUI);
			Browser.freeKeys();
			prevent(event);
			return false;
		}
		function hideInputUI () {
			var self = $(this);
			var parent = sidebar_input_content.data("parent");
			var input= self.parent().find("textarea");
			var value = input.val();
			var label = value.length>32 ? value.substr(0, 32) + " ..." : value;
			if (value=="") {
				label = L10N.get("ordering", "sidebar_none_selected");
			}
			parent.data("value", value);
			parent.find("span").html(label);
			Browser.takeKeys();
			sidebar_input.hide();
			check();
		}
		function group () {
			selection.browse = selection.browse_provider[sidebar_selection.data("index")];
			last_selected_hash = selection.browse.hash;
			redraw();
			reset(false);
			check();
		}
		function offsets (eo) {
			selection.x_offset = Math.round(eo.x);
			selection.y_offset = Math.round(eo.y);
			check();
		}
		function disable (eo) {
			sidebar_screen.toggle(eo.open);
		}
		function disableinputs () {
			$("#overlay-sidebar .Inner div > div").show();
			if (!isNaN(selection.format.aspect)) {
				Browser.hideCropView();
			}
		}
		function enableinputs () {
			$("#overlay-sidebar .Inner div > div").hide();
			if (!isNaN(selection.format.aspect)) {
				Browser.showCropView();
			}
		}
		function updateDownloadOptions () {
			var info = Overlay.getCurrentImage();
			var hash = md5( Overlay.pageid() + info.filename + "high" );
			var obj = Session.getDownloadObject(hash+"-d");
			if (obj==undefined) {
				$("#sidebar-download-high")
					.removeAttr("disabled")
					.next()
						.removeClass("Disabled");
			} else {
				$("#sidebar-download-high")
					.attr("disabled", "disabled")
					.next()
						.addClass("Disabled");
			}
			var hash = md5( Overlay.pageid() + info.filename + "low" );
			var obj = Session.getDownloadObject(hash+"-d");
			if (obj==undefined) {
				$("#sidebar-download-low")
					.removeAttr("disabled")
					.next()
						.removeClass("Disabled");
			} else {
				$("#sidebar-download-low")
					.attr("disabled", "disabled")
					.next()
						.addClass("Disabled");
			}
		}
		function image () {
			reset();
			check();
			updateDownloadOptions();
		}
		function start () {
			disable({open:false});
			redraw();
			reset();
			check();
			updateDownloadOptions();
			instance.dispatch("onChanged");
		}
		function resize () {
			var ih = height-50;
			overlay_sidebar.css({
				left: (hidden?original_x:0),
				width: width,
				height: height
			});
			overlay_sidebar.find(".Inner").css({
				width: width,
				height: ih
			});
		}
		function draw () {
			overlay_sidebar = $("#overlay-sidebar");
			sidebar_input = $("#sidebar-input");
			sidebar_screen = $("#sidebar-screen");
			sidebar_input_screen = $("#sidebar-input-screen");
			sidebar_input_content = $("#sidebar-input-content");
			sidebar_selection = $("#sidebar-selection");
			sidebar_browse = $("#sidebar-browse");
			sidebar_control = $("#browse-controlbar-add");
			checkout_obj = $("#browse-controlbar-cart");
			sidebar_formats = $("#sidebar-formats");
			sidebar_quantity = $("#sidebar-quantity");
			sidebar_toning = $("#sidebar-toning");
			sidebar_papers = $("#sidebar-papers");
			sidebar_modifiers = $("#sidebar-modifiers");
			sidebar_crop = $("#sidebar-crop");
			sidebar_comments = $("#sidebar-comments");
			sidebar_download = $("#sidebar-download");
			
			// prevent scroll and touch
			if (Shell.device().touch) {
				overlay_sidebar.find(".ControlBar").bind("touchmove", Func.stop);
				overlay_sidebar.find(".Inner").bind('touchstart', Func.touchboundsstart);
				overlay_sidebar.find(".Inner").bind('touchmove', Func.touchboundsmove);
			} else {
				overlay_sidebar.find(".ControlBar").mousewheel(Func.stop);
				overlay_sidebar.find(".Inner").mousewheelStopPropagation();
			}
			sidebar_input.mousewheel(Func.stop);
			sidebar_input.mousewheelStopPropagation();
			
			// package/product button
			checkout_obj.addClass("Enabled").click(click);
			sidebar_browse.find("button").click(click);
			sidebar_input_screen.click(hideInputUI);
			if (Shell.device().touch) {
				overlay_sidebar.find(".Selection").each(function () {
					$(this).find("span").css("visibility", "hidden");
					$(this)
						.data("enabled", true)
						.data("index", 0)
						.data("value", null)
						.find("select")
							.change(change);
				});
				overlay_sidebar.find(".Text").each(function () {
					$(this).click(showInputUI);
				});
				overlay_sidebar.find("form").hide();
				$("#sidebar-download").find("form").show();
			} else {
				overlay_sidebar.find(".Selection").each(function () {
					$(this).find("span").hide();
					$(this).find("select").change(change).hide();
					$(this)
						.data("enabled", true)
						.data("index", 0)
						.data("value", null);
				});
				overlay_sidebar.find(".Text").each(function () {
					$(this).find("span").hide();
				});
			}
			overlay_sidebar.find(".Numeric button").click(numberevent);
			
			downloads_available = Checkout.settings().downloads.use;
			if (downloads_available) {
				sidebar_download.find("input").click(downloadchange);
			}
			
		}
		function lateinit () {
			Browser.addEventListener("onCropMove", offsets);
			Browser.addEventListener("onZoomView", disable);
			Browser.addEventListener("onIndex", image);
			Session.addEventListener("onSessionLoaded", start);
			Session.addEventListener("onSessionCart", start);
		}
		function init () {
			draw();
			resize();
		}
		function render () {
			init();
			setTimeout(lateinit, 33);
		}
		function fixOrientation () {
			var current = Overlay.getCurrentImage();
			var aspect = current.width/current.height;
			var parent = sidebar_crop;
			var provider = selection.orientation_provider;
			var input = parent.find("select");
			var label = parent.find("span");
			var index = aspect<1 ? 1 : 2;
			var value = provider[index].value;
			var form = parent.find("form input[value=" + value + "]");
			var text = provider[index].label;
			parent
				.data("index", index)
				.data("value", value);
			input.val(value);
			form.prop('checked', true);
			label.html(text);
			selection.orientation = provider[index];
		}
		function check () {
			// these will affect the pricing labels
			var calculate_and_display_shipping_bool = Checkout.settings().shipping.use;
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var shipping_taxable_bool = Checkout.settings().shipping.tax;
			var downloads_taxable_bool = Checkout.settings().downloads.tax;
			// create a new cart object
			cart_object = {};
			// disable the add button for now
			sidebar_control.removeClass("Enabled").addClass("Disabled").off();
			if (selection.type=="cart") {
				// set the selected format
				if (formats_available) {
					selection.format = selection.format_provider[sidebar_formats.data("index")];
				}
				// set some defaults
				if (toning_available) {
					selection.toning = sidebar_toning.data("value");
				}
				// update quantity selection
				if (quantity_available) {
					selection.quantity = sidebar_quantity.data("value");
					if ( selection.quantity==0 || isNaN(selection.quantity) ) {
						selection.quantity = 1;
					}
					if ( selection.quantity > selection.format.maximum ) {
						selection.quantity = selection.format.maximum;
					}
				}
				if (selection.format.maximum==-1) {
					selection.quantity = 1;
					sidebar_quantity.hide();
				} else {
					sidebar_quantity.show();
				}
				// update crop option
				if (cropping_available) {
					selection.orientation = sidebar_crop.data("value");
				}
				if (isNaN(selection.format.aspect)) {
					selection.orientation = "";
					sidebar_crop.hide();
				} else {
					sidebar_crop.show();
				}
				// kill this if formats are available, but none are selected
				if ( formats_available && ( selection.format.label==L10N.get("ordering", "sidebar_none_selected") || !selection.format ) ) {
					return;
				}
				// get the format basics
				var format_area = isNaN(selection.format.area) ? 0 : selection.format.area;
				var format_price = selection.format.price;
					format_price = evaluate(format_price, format_area, selection.quantity, null);
				// modify the paper labels
				if (papers_available) {
					selection.paper = selection.paper_provider[sidebar_papers.data("index")];
					sidebar_papers.find("option").each(function (i) {
						if (i==0) {
							return;
						}
						var input = sidebar_papers.find("label").eq(i);
						var paper = selection.paper_provider[i];
						var label = paper.title;
						var price = paper.price;
							if (price==""||!price) {
								price = "0";
							}
							price = evaluate(price, format_area, selection.quantity, format_price);
						var shipping = paper.shipping;
							if (shipping==""||!shipping) {
								shipping = "0";
							}
							shipping = evaluate(shipping, format_area, selection.quantity, format_price);
							if (calculate_and_display_shipping_bool==false) {
								shipping = 0;
							}
						if (price>0) {
							if (purchase_price_includes_tax_bool) {
								price = Func.addSalesTax(price);
							}
							label += " (" + Func.getFormattedPrice(price) + ")";
							
						}
						if (calculate_and_display_shipping_bool&&shipping>0) {
							if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
								shipping = Func.addSalesTax(shipping);
							}
							label += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
						}
						$(this).html(label);
						input.html(label);
					});
				}
				// modify the paper labels
				if (modifiers_available) {
					selection.modifier = selection.modifier_provider[sidebar_modifiers.data("index")];
					sidebar_modifiers.find("option").each(function (i) {
						if (i==0) {
							return;
						}
						var input = sidebar_modifiers.find("label").eq(i);
						var modifier = selection.modifier_provider[i];
						var label = modifier.title;
						var price = modifier.price;
							if (price==""||!price) {
								price = "0";
							}
							price = evaluate(price, format_area, selection.quantity, format_price);
						var shipping = modifier.shipping;
							if (shipping==""||!shipping) {
								shipping = "0";
							}
							shipping = evaluate(shipping, format_area, selection.quantity, format_price);
							if (calculate_and_display_shipping_bool==false) {
								shipping = 0;
							}
						if (price>0) {
							if (purchase_price_includes_tax_bool) {
								price = Func.addSalesTax(price);
							}
							label += " (" + Func.getFormattedPrice(price) + ")";
						}
						if (calculate_and_display_shipping_bool&&shipping>0) {
							if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
								shipping = Func.addSalesTax(shipping);
							}
							label += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
						}
						$(this).html(label);
						input.html(label);
					});
				}
				// get final values for cart object
				var comment_text = comments_available ? sidebar_comments.data("value") : "";
					comment_text = comment_text.split("\t").join("").split("\r").join(" ").split("\n").join(" ");
				var format_shipping = selection.format.shipping;
					format_shipping = evaluate(format_shipping, format_area, selection.quantity, format_price);
					if (calculate_and_display_shipping_bool==false) {
						format_shipping = 0;
					}
				var paper_price = papers_available ? selection.paper.price : "0";
					paper_price = evaluate(paper_price, format_area, selection.quantity, format_price);
				var paper_shipping = papers_available ? selection.paper.shipping : "0";
					paper_shipping = evaluate(paper_shipping, format_area, selection.quantity, format_price);
					if (calculate_and_display_shipping_bool==false) {
						paper_shipping = 0;
					}
				var modifier_price = modifiers_available ? selection.modifier.price : "0";
					modifier_price = evaluate(modifier_price, format_area, selection.quantity, format_price);
				var modifier_shipping = modifiers_available ? selection.modifier.shipping : "0";
					modifier_shipping = evaluate(modifier_shipping, format_area, selection.quantity, format_price);
					if (calculate_and_display_shipping_bool==false) {
						modifier_shipping = 0;
					}
				// create a unique hash for the cart object
				var info = Overlay.getCurrentImage();
				var hash_obj = {
					pageid: Overlay.pageid(),
					filename: info.filename,
					tone: ( toning_available ? instance.getColorTone() : "" ),
					format: ( formats_available ? selection.format.title : "" ),
					orientation: ( instance.getShowCrop() ? instance.getOrientation() : "" ),
					x_offset: ( instance.getShowCrop() ? selection.x_offset : "" ),
					y_offset: ( instance.getShowCrop() ? selection.y_offset : "" ),
					paper: ( papers_available ? selection.paper.title : "" ),
					modifier: ( modifiers_available ? selection.modifier.title : "" ),
					comment: comment_text
				};
				/*var hash_prop_str = "";
				for (var prop in hash_obj) {
					if (hash_obj.hasOwnProperty(prop)) {
						hash_prop_str += prop + ": " + hash_obj[prop] + "\n";
					}
					alert(hash_prop_str);
				}*/
				var hash = md5( hash_obj.pageid +
						hash_obj.filename +
						hash_obj.tone +
						hash_obj.format +
						hash_obj.orientation +
						hash_obj.x_offset +
						hash_obj.y_offset +
						hash_obj.paper +
						hash_obj.modifier +
						hash_obj.comment );
				if ( selection.browse.type=="product" || selection.browse.type=="package" ) {
					hash += ":" + selection.browse.hash;
				}
				/* add any and all pertinent info to the cart object
					*/
				cart_object.hash = hash;
				cart_object.puid = info.parent;
				cart_object.cuid = info.child;
				cart_object.filename = info.filename;
				cart_object.quantity = selection.quantity;
				cart_object.toning = selection.toning;
				if (formats_available) {
					cart_object.format_label = selection.format.title;
					if (isNaN(instance.getFormatAspect())==false) {
						cart_object.format_aspect = instance.getFormatAspect();
					}
					cart_object.format_price = format_price;
					cart_object.format_shipping = format_shipping;
				}
				if (instance.getShowCrop()) {
					cart_object.orientation = instance.getOrientation();
					cart_object.orientation_x = selection.x_offset;
					cart_object.orientation_y = selection.y_offset;
				}
				if (papers_available) {
					cart_object.paper_label = selection.paper.title;
					cart_object.paper_price = paper_price;
					cart_object.paper_shipping = paper_shipping;
				}
				if (modifiers_available) {
					cart_object.modifier_label = selection.modifier.title;
					cart_object.modifier_price = modifier_price;
					cart_object.modifier_shipping = modifier_shipping;
				}
				cart_object.comments = comment_text;
				cart_object.subtotal = format_price + paper_price + modifier_price;
				cart_object.shipping = format_shipping + paper_shipping + modifier_shipping;
			} else if (selection.type=="download") {
				// create a unique hash for the cart object
				var info = Overlay.getCurrentImage();
				var hash = md5( Overlay.pageid() + info.filename + selection.quality );
				var price = Checkout.settings().downloads[selection.quality].price;
					price = evaluate(price, null, null, null);
				/* add any and all pertinent info to the cart object
					*/
				cart_object.hash = hash;
				cart_object.puid = info.parent;
				cart_object.cuid = info.child;
				cart_object.filename = info.filename;
				cart_object.dimensions = info.width + "x" + info.height;
				cart_object.quality = selection.quality;
				cart_object.subtotal = price;
				cart_object.allprice = 0;
			}
			// enable the control
			sidebar_control.removeClass("Disabled").addClass("Enabled").click(click);
		}
		
		/*
			this function updates the views, but keeps the selections the same.  
			updates labels
			adds newly added packages (and auto-selects them)
			turns on/off functionality (like quantities)
			basically gets called when things get clicked that changes what is visible and available in the sidebar view
			*/
		function redraw () {
			// these will affect the pricing labels
			var calculate_and_display_shipping_bool = Checkout.settings().shipping.use;
			var purchase_price_includes_tax_bool = Checkout.settings().tax.included;
			var shipping_taxable_bool = Checkout.settings().shipping.tax;
			var downloads_taxable_bool = Checkout.settings().downloads.tax;
			// get a list of packages in the cart
			var packages = [];
			var packages_parsed = Session.getPackagesParsed();
			var i, provider, pkg, package_hash, parent, form, input, label, index, value, text, dataset, format, area, price, shipping, remaining, paper, modifier;
			for (i=0; i<packages_parsed.length; ++i) {
				pkg = packages_parsed[i];
				if ( pkg.total==0 || pkg.total==pkg.count ) {
					continue;
				}
				packages.push(pkg.row);
			}
			// decide on display flags
			packages_available = Package.available();
			alacarte_available = alacarte.length > 0;
			packages_in_cart = packages.length > 0;
			formats_available = alacarte_available || packages_in_cart;
			formats_visible = formats_available;
			quantity_available = sidebar_quantity.length > 0;
			toning_available = sidebar_toning.length > 0;
			papers_available = papers.length > 0;
			modifiers_available = modifiers.length > 0;
			cropping_available = formats_available && sidebar_crop.length > 0;
			comments_available = sidebar_comments.length > 0;
			
			sidebar_browse.toggle(packages_available);
			
			// create a cart provider array and decide on what we should be seeing
			provider = [];
			index = 0;
			provider.push({
				label: L10N.get("ordering", "sidebar_none_selected"),
				type: "none",
				hash: "none"
			});
			for (i=0; i<packages.length; ++i) {
				pkg = packages[i];
				package_hash = pkg.hash.substr(0, 32);
				if (
					( last_selected_hash == package_hash ) || // known last hash
					( selection.browse.hash == package_hash) || // the selection object has been selected manually
					( alacarte_available==false && packages.length==1 ) // only packages are available, and there is only one in the cart
				) {
					index = provider.length;
				}
				provider.push({
					label: pkg.nickname + " (" + pkg.title + ")",
					type: pkg.type,
					hash: package_hash
				});
			}
			if (alacarte_available) {
				if ( index==0) {
					if (
						( selection.browse.type=="alacarte" ) || // manual selection of alacarte
						( packages_available==true && packages_in_cart==false ) || // packages are available for choosing, but none have been added to cart
						( packages_available==false ) // packages are not available, but alacarte formats are
					) {
						index = provider.length;
					}
				}
				provider.push({
					label: L10N.get("ordering", "alacarte_label"),
					type: "alacarte",
					hash: "alacarte"
				});
			}
			
			parent = sidebar_download;
			parent.find("#sidebar-download-none").next().html(L10N.get("ordering", "sidebar_none_selected"));
				label = L10N.get("ordering", "sidebar_high_resolution");
				price = Checkout.settings().downloads.high.price;
					if (price==""||!price) {
						price = "0";
					}
					price = evaluate(price, null, null, null);
					if (price>0) {
						if ( purchase_price_includes_tax_bool && downloads_taxable_bool ) {
							price = Func.addSalesTax(price);
						}
						label += " (" + Func.getFormattedPrice(price) + ")";
					}
			parent.find("#sidebar-download-high").next().html(label);
				label = L10N.get("ordering", "sidebar_low_resolution");
				price = Checkout.settings().downloads.low.price;
					if (price==""||!price) {
						price = "0";
					}
					price = evaluate(price, null, null, null);
					if (price>0) {
						if ( purchase_price_includes_tax_bool && downloads_taxable_bool ) {
							price = Func.addSalesTax(price);
						}
						label += " (" + Func.getFormattedPrice(price) + ")";
					}
			parent.find("#sidebar-download-low").next().html(label);
				
			// update the text labels of the downloads
			// enable/disable quantity
			parent = sidebar_quantity;
			parent.toggle(quantity_available); // && !formats_visible );
				
			// now that we have an array of views, setup the select
			parent = sidebar_selection;
			input = parent.find("select");
			label = parent.find("span");
			form = parent.find("form");
			form.off().empty();
			input.empty();
			value = provider[index].hash;
			text = provider[index].label;
			for (i=0; i<provider.length; ++i) {
				input.append('<option value="' + provider[i].hash  + '">' + provider[i].label  + '</option>');
				form.append('<input id="selection-radio-' + i  + '" name="selection" ' + (provider[i].hash==value?' checked ':'') + 'type="radio" value="' + provider[i].hash  + '" /><label for="selection-radio-' + i  + '">' + provider[i].label  + '</label><br />');
			}
			parent
				.data("index", index)
				.data("value", value);
			input.val(value);
			form.find("input").change(radioevent);
			label.html(text);
			selection.browse_provider = provider;
			selection.browse = provider[index];
			parent.toggle(provider.length>=3);

			// turn off everything if there is none selected
			if (selection.browse.type=="none") {
				formats_visible = false;
				quantity_available = false;
				toning_available = false;
				papers_available = false;
				modifiers_available = false;
				cropping_available = false;
				comments_available = false;
			}

			// decide on the format dataset
			// assume alacarte by default
			dataset = alacarte;
			if ( selection.browse.type=="package" || selection.browse.type=="product" ) {
				for (i=0; i<packages_parsed.length; ++i) {
					pkg = packages_parsed[i];
					if ( pkg.row.hash.substr(0, 32) == selection.browse.hash ) {
						dataset = pkg.formats;
						break;
					}
				}
				formats_visible = dataset.length>0;
			}
			provider = [];
				provider.push({
					label: L10N.get("ordering", "sidebar_none_selected"),
					price: "",
					area: NaN,
					aspect: NaN,
					shipping: "",
					maximum: -1
				});
			for (i=0; i<dataset.length; ++i) {
				format = dataset[i];
				area = parseFloat(format.area);
				price = format.price;
				if ( price=="" || !price ) {
					price = "0";
				}
					price = evaluate(price, area, null, null);
				shipping = format.shipping;
				if ( shipping=="" || !shipping ) {
					shipping = "0";
				}
					shipping = evaluate(shipping, area, null, null);
				if ( calculate_and_display_shipping_bool==false ) {
					shipping = 0;
				}
				label = format.title;
				if (format.total) {
					remaining = format.total - format.count;
					if (remaining==0) {
						continue;
					}
					label += " (" + remaining + ") " + L10N.get("ordering", "sidebar_package_remaining");
				}
				if (price>0) {
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
					label += " (" + Func.getFormattedPrice(price) + ")";
				}
				if (calculate_and_display_shipping_bool&&shipping>0) {
					if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
						shipping = Func.addSalesTax(shipping);
					}
					label += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
				}
				provider.push({
					label: label,
					area: area,
					maximum: (remaining||9999),
					title: format.title,
					price: format.price,
					aspect: parseFloat(format.aspect),
					shipping: format.shipping
				});
			}
			parent = sidebar_formats;
			input = parent.find("select");
			form = parent.find("form");
			form.off().empty();
			input.empty();
			for (i=0; i<provider.length; ++i) {
				input.append('<option value="' + i  + '">' + provider[i].label  + '</option>');
				form.append('<input id="formats-radio-' + i  + '" name="formats" ' + (i==0?' checked ':'') + 'type="radio" value="' + i  + '" /><label for="formats-radio-' + i  + '">' + provider[i].label  + '</label><br />');
			}
			form.find("input").change(radioevent);
			selection.format_provider = provider;
			parent.toggle(formats_visible);

			// enable/disable quantity
			parent = sidebar_quantity;
			parent.toggle(quantity_available); // && !formats_visible );

			// enable/disable toning
			provider = [{
				label: L10N.get("ordering", "sidebar_none_selected"),
				value: ""
			}];
			if (Display.settings().mono) {
				provider.push({
					label: L10N.get("ordering", "sidebar_tone_black_and_white"),
					value: "mono"
				});
			}
			if (Display.settings().sepia) {
				provider.push({
					label: L10N.get("ordering", "sidebar_tone_sepia"),
					value: "sepia"
				});
			}
			parent = sidebar_toning;
			input = parent.find("select");
			form = parent.find("form");
			form.off().empty();
			input.empty();
			for (i=0; i<provider.length; ++i) {
				input.append('<option value="' + provider[i].value  + '">' + provider[i].label  + '</option>');
				form.append('<input id="toning-radio-' + i  + '" name="toning" ' + (i==0?' checked ':'') + 'type="radio" value="' + provider[i].value  + '" /><label for="toning-radio-' + i  + '">' + provider[i].label  + '</label><br />');
			}
			form.find("input").change(radioevent);
			selection.toning_provider = provider;
			parent.toggle(toning_available);

			// papers
			dataset = papers;
			provider = [];
			provider.push({
				label: L10N.get("ordering", "sidebar_none_selected"),
				title: "",
				price: "",
				shipping: ""
			});
			for (i=0; i<dataset.length; ++i) {
				paper = dataset[i];
				label = paper.title;
				price = paper.price;
					if (price==""||!price) {
						price = "0";
					}
					price = evaluate(price, null, null, null);
				shipping = paper.shipping;
					if (shipping==""||!shipping) {
						shipping = "0";
					}
					shipping = evaluate(shipping, null, null, null);
					if (calculate_and_display_shipping_bool==false) {
						shipping = 0;
					}
				if (price>0) {
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
					label += " (" + Func.getFormattedPrice(price) + ")";
				}
				if (calculate_and_display_shipping_bool&&shipping>0) {
					if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
						shipping = Func.addSalesTax(shipping);
					}
					label += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
				}
				provider.push({
					label: label,
					title: paper.title,
					price: paper.price,
					shipping: paper.shipping
				});
			}
			parent = sidebar_papers;
			input = parent.find("select");
			form = parent.find("form");
			form.off().empty();
			input.empty();
			for (i=0; i<provider.length; ++i) {
				input.append('<option value="' + i  + '">' + provider[i].label  + '</option>');
				form.append('<input id="papers-radio-' + i  + '" name="papers" ' + (i==0?' checked ':'') + 'type="radio" value="' + i  + '" /><label for="papers-radio-' + i  + '">' + provider[i].label  + '</label><br />');
			}
			form.find("input").change(radioevent);
			selection.paper_provider = provider;
			parent.toggle(papers_available);

			// modifiers
			dataset = modifiers;
			provider = [];
			provider.push({
				label: L10N.get("ordering", "sidebar_none_selected"),
				title: "",
				price: "",
				shipping: ""
			});
			for (i=0; i<dataset.length; ++i) {
				modifier = dataset[i];
				label = modifier.title;
				price = modifier.price;
					if (price==""||!price) {
						price = "0";
					}
					price = evaluate(price, null, null, null);
				shipping = modifier.shipping;
					if (shipping==""||!shipping) {
						shipping = "0";
					}
					shipping = evaluate(shipping, null, null, null);
					if (calculate_and_display_shipping_bool==false) {
						shipping = 0;
					}
				if (price>0) {
					if (purchase_price_includes_tax_bool) {
						price = Func.addSalesTax(price);
					}
					label += " (" + Func.getFormattedPrice(price) + ")";
				}
				if (calculate_and_display_shipping_bool&&shipping>0) {
					if (purchase_price_includes_tax_bool&&shipping_taxable_bool) {
						shipping = Func.addSalesTax(shipping);
					}
					label += " + " + Func.getFormattedPrice(shipping) + " " + L10N.get("localization", "currency_shipping_and_handling_abbreviation");
				}
				provider.push({
					label: label,
					title: modifier.title,
					price: modifier.price,
					shipping: modifier.shipping
				});
			}
			parent = sidebar_modifiers;
			input = parent.find("select");
			form = parent.find("form");
			form.off().empty();
			input.empty();
			for (i=0; i<provider.length; ++i) {
				input.append('<option value="' + i  + '">' + provider[i].label  + '</option>');
				form.append('<input id="modifiers-radio-' + i  + '" name="modifiers" ' + (i==0?' checked ':'') + 'type="radio" value="' + i  + '" /><label for="modifiers-radio-' + i  + '">' + provider[i].label  + '</label><br />');
			}
			form.find("input").change(radioevent);
			selection.modifier_provider = provider;
			parent.toggle(modifiers_available);

			// enable/disable crop
			provider = [{
				label: L10N.get("ordering", "sidebar_none_selected"),
				value: ""
			},{
				label: L10N.get("ordering", "sidebar_crop_portrait"),
				value: "p"
			},{
				label: L10N.get("ordering", "sidebar_crop_landscape"),
				value: "l"
			}];
			parent = sidebar_crop;
			input = parent.find("select");
			form = parent.find("form");
			form.off().empty();
			input.empty();
			for (i=0; i<provider.length; ++i) {
				input.append('<option value="' + provider[i].value  + '">' + provider[i].label  + '</option>');
				form.append('<input id="crop-radio-' + i  + '" name="crop" ' + (i==0?' checked ':'') + 'type="radio" value="' + provider[i].value  + '" /><label for="crop-radio-' + i  + '">' + provider[i].label  + '</label><br />');
			}
			form.find("input").change(radioevent);
			selection.orientation_provider = provider;
			parent.toggle(cropping_available);

			// enable/disable quantity
			parent = sidebar_comments;
			form = parent.find("form");
			form.off().empty();
			form.append('<textarea></textarea>');
			form.find("textarea").change(textevent).focus(function () { Browser.freeKeys(); }).blur(function () { Browser.takeKeys(); });
			parent.toggle(comments_available);
			
			if (!isavailable()) {
				$("#overlay-container").addClass("NoSidebar");
			}

		}
		
		/*
			this function resets everything to default state
			the hide vairbale re-hides the sidebar if it's in a hidden mobile view
			*/
		function reset (hide) {
			var undef;
			if (hide==undef) hide = true;
			// take it to the top
			overlay_sidebar.find(".Inner").scrollTop(0);
			// create a new cart object
			cart_object = {};
			// disable the add button for now
			sidebar_control.removeClass("Enabled").addClass("Disabled").off();
			// reset the format
			var provider, parent, input, form, label, index, value, text;
			var input = sidebar_download.find("input");
			if (downloads_available) {
				if (input.length>1) {
					sidebar_download.find("input").eq(0).click();
				} else {
					sidebar_download.find("input").attr('checked', false);
				}
				enableinputs();
				selection.quality = "";
			}
			selection.type = "cart";
			if (formats_visible) {
				provider = selection.format_provider;
				parent = sidebar_formats;
				input = parent.find("select");
				label = parent.find("span");
				index = 0;
				value = index;
				text = provider[index].label;
				parent
					.data("index", index)
					.data("value", value);
				form = parent.find("form input[value=" + value + "]");
				form.prop('checked', true);
				input.val(value);
				label.html(text);
				selection.format = provider[index];
			}
			// reset the quantity
			if (quantity_available) {
				parent = sidebar_quantity;
				label = parent.find("span");
				value = 1;
				text = "1";
				parent
					.data("value", value);
				label.html(text);
				selection.quantity = value;
			}
			// reset the papers
			if (papers_available) {
				provider = selection.paper_provider;
				parent = sidebar_papers;
				input = parent.find("select");
				label = parent.find("span");
				index = 0;
				value = index;
				text = provider[index].label;
				parent
					.data("index", index)
					.data("value", value);
				form = parent.find("form input[value=" + value + "]");
				form.prop('checked', true);
				input.val(value);
				label.html(text);
				selection.paper = provider[index];
			}
			// reset the modifiers
			if (modifiers_available) {
				provider = selection.modifier_provider;
				parent = sidebar_modifiers;
				input = parent.find("select");
				label = parent.find("span");
				index = 0;
				value = index;
				text = provider[index].label;
				parent
					.data("index", index)
					.data("value", value);
				form = parent.find("form input[value=" + value + "]");
				form.prop('checked', true);
				input.val(value);
				label.html(text);
				selection.modifier = provider[index];
			}
			// reset the toning
			if (toning_available) {
				provider = selection.toning_provider;
				parent = sidebar_toning;
				input = parent.find("select");
				label = parent.find("span");
				index = 0;
				value = provider[index].value;
				text = provider[index].label;
				parent
					.data("index", index)
					.data("value", value);
				form = parent.find("form input[value=" + value + "]");
				form.prop('checked', true);
				input.val(value);
				label.html(text);
				selection.toning = provider[index];
			}
			// reset the crop
			if (cropping_available) {
				provider = selection.orientation_provider;
				parent = sidebar_crop;
				input = parent.find("select");
				label = parent.find("span");
				index = 0;
				value = provider[index].value;
				text = provider[index].label;
				parent
					.data("index", index)
					.data("value", value);
				form = parent.find("form input[value=" + value + "]");
				form.prop('checked', true);
				input.val(value);
				label.html(text);
				selection.orientation = provider[index];
			}
			// reset the comments
			if (comments_available) {
				parent = sidebar_comments;
				label = parent.find("span");
				value = "";
				text = L10N.get("ordering", "sidebar_none_selected");
				parent
					.data("value", value);
				form = parent.find("textarea");
				form.val(value);
				label.html(text);
				selection.comment = value;
			}
			// reset the offsets
			selection.x_offset = 50;
			selection.y_offset = 50;
			// re-hide
			if (hide) {
				hidden = true;
				overlay_sidebar.css({
					left: original_x,
					top: 0
				});
			}
		}
		function isavailable () {
			return ( downloads_available || packages_available || formats_available || quantity_available || toning_available || papers_available || modifiers_available || cropping_available || comments_available );
		}
		/* public methods
			*/
		this.available = function() {
			return isavailable();
		};
		this.addFormat = function(key, obj) {
			alacarte_lookup[key] = alacarte.length;
			alacarte.push(obj);
		};
		this.hasFormats = function() {
			return alacarte.length > 0;
		};
		this.addPaper = function(key, obj) {
			papers_lookup[key] = papers.length;
			papers.push(obj);
		};
		this.addModifier = function(key, obj) {
			modifiers_lookup[key] = modifiers.length;
			modifiers.push(obj);
		};
		this.getOrientation = function() {
			return selection.orientation || "";
		};
		this.getFormatAspect = function() {
			return selection.format.aspect || NaN;
		};
		this.getShowCrop = function() {
			return !isNaN(this.getFormatAspect()) && cropping_available && this.getOrientation()!="";
		};
		this.getColorTone = function() {
			return selection.toning || "";
		};
		this.move = function(x, y) {
			original_x = x;
			original_y = y;
			overlay_sidebar.css({
				top: y,
				left: x
			});
		};
		this.setSize = function(w, h) {
			width = w;
			height = h;
			resize();
		};
		this.reveal = function() {
			hidden = false;
			overlay_sidebar.css({
				top: 0,
				left: 0
			});
		};
		this.abscond = function() {
			hidden = true;
			overlay_sidebar.css({
				top: 0,
				left: original_x
			});
		};
		this.setActiveSelctionHash = function(hash) {
			last_selected_hash = hash;
		};
		this.initialize = function() {
			Func = classes.helpers.Func;
			L10N = classes.helpers.L10N;
			Overlay = classes.Overlay;
			Session = classes.Session;
			Shell = classes.Shell;
			Browser = classes.overlay.Browser;
			Package = classes.overlay.Package;
			Checkout = classes.overlay.Checkout;
			Display = classes.content.Display;
			Controlbar = classes.elements.Controlbar;
			render();
		};
	}
	Constructor.prototype = new EventDispatcher();
	return new Constructor();
}());

classes.helpers.L10N = (function () {
	function Constructor () {
		/* private methods
			*/
		var l10n = {
			general: {
				password_required: 'Mot de passe requis',
				password_incorrect: 'Mot de passe incorrect !',
				set_expired_error: 'La galerie de sÃ©lection demandÃ©e a expirÃ©!  Contactez-nous au 05 56 81 23 99',
				session_dialog_directions: '<p>Veuillez renseigner votre adresse email pour dÃ©buter votre commande. Vos sÃ©lections seront enregistrÃ©es sur notre serveur, et seront accessibles depuis n\'importe quel ordinateur, en vous identifiant avec la mÃªme adresse email, pour vous connecter.</p>',
				session_enter_email_address: 'Veuillez saisir votre adresse E-mail',
				session_start_resume: 'DÃ©marrer/Reprendre une session',
				session_invalid_email_address: 'Adresse E-mail invalide',
				return_to_gateway: 'Revenir Ã  la page de connexion',
				dialog_submit: 'Envoyer !',
				dialog_confim: 'O.K.',
				dialog_approve: 'Continuer',
				dialog_cancel: 'Annuler',
				dialog_no_remind: 'Ne pas me le rappeler',
				dialog_close_window: 'FERMER LA FENÃŠTRE',
				contact_us: 'Nous contacter au 05 56 81 23 99',
				browser_error_resolution_title: 'Nous avons besoin de plus d&#039;espace !',
				browser_error_resolution_description: '<p>Cette application requiert les version les plus rÃ©centes des navigateurs internet qui sont pleinement compatibles avec la norme HTML5.  Ce qui inclut Firefox (version 4 ou supÃ©rieur), Chrome (version 18 ou supÃ©rieur), Safari/Webkit (version 534 ou supÃ©rieur) et Internet Explorer 10 pour toutes plateformes qui ont une rÃ©solution Ã©cran minimum de 1024x768 pixels.  Les tÃ©lÃ©phones mobiles ne sont pas supportÃ©s Ã  cause de limitations et dâ€™ergonomie.</p>',
				browser_error_orientation_title: 'Veuillez s&#039;il vous plait passer en mode horizontal.',
				browser_error_orientation_description: '<p>Cette application a Ã©tÃ© conÃ§ue pour le mode horizontal.  Veuillez s\'il vous plaÃ®t basculer votre terminal.  Tout est sauvegardÃ©, vous n\'avez qu\'Ã  basculer en horizontal.</p>',
				browser_error_browser_title: 'Zut ! Votre terminal internet ou votre navigateur n&#039;est pas compatible !',
				browser_error_browser_description: '<p>Cette application requiert les versions les plus rÃ©centes des navigateurs internet qui sont pleinement compatible avec la norme HTML5.  Ce qui inclut Firefox (version 4 ou supÃ©rieur), Chrome (version 18 ou supÃ©rieur), Safari/Webkit (version 534 ou supÃ©rieur) et Internet Explorer 10 pour toutes plateformes qui ont une rÃ©solution Ã©cran minimum de 1024x768 pixels.  Les tÃ©lÃ©phones mobiles ne sont pas supportÃ©s Ã  cause de limitations et dâ€™ergonomie.</p>',
				page_not_found_title: '404 Non TrouvÃ©',
				page_not_found_description: '<h2>Non trouvÃ©</h2><p>L\'URL demandÃ©e n\'a pu Ãªtre trouvÃ©e sur ce serveur.</p><p>Par ailleurs, une erreur 404 Non TrouvÃ© a Ã©tÃ© rencontrÃ©e en essayant d\'utiliser un ErrorDocument pour traiter la requÃªte.</p>',
				_: '',
			},
			splash: {
				login_field_prompt: 'Saisissez l&#039;IDentifiant d&#039;une galerie',
				login_failure: 'La galerie demandÃ©e n&#039;est pas valide, ou n&#039;est plus disponible',
				login_submit: 'DÃ©marrer la sÃ©lection !',
				expiration_never: 'Jamais',
				set_images: 'Images :',
				set_expired_on: 'ExpirÃ© depuis le :',
				set_expires_on: 'Expire le :',
				view_gallery: 'Voir la Galerie',
				view_gallery_login: 'AccÃ©der Ã  la Galerie',
				_: '',
			},
			contact: {
				contact_form_submit: 'Envoyer',
				contact_form_send_success: 'Message envoyÃ© !',
				contact_form_send_failure: 'Erreur lors de l&#039;envoi du message !',
				contact_form_ml_optin: 'Mailing List Opt-in',
				contact_form_ml_checkbox: 'Ajoutez-moi Ã  votre mailing-list',
				email_address_invalid: 'Adresse email invalide !',
				highlighted_fields_required: 'Les champs mis en surbrillance sont requis !',
				form_idle_message: 'en attente d&#039;activitÃ©...',
				sending_data_to_server: 'envoi des donnÃ©es au serveur...',
				form_email_subject: '[{SITE_URL}] - Un nouveau message de ({SENDER_NAME})',
				form_email_message_body: '<p>{FORMATTED<em>FORM</em>BLOCK}</p>',
				order_client_reciept_subject: 'ReÃ§u pour votre commande',
				order_client_reciept_message_body: '<p>La commande {ORDER_ID} a Ã©tÃ© crÃ©Ã©e, et elle est maintenant disponible pour consultation.  Si vous avez utilisÃ© Paypal pour payer votre commande, vous allez recevoir prochainement une confirmation de paiement.  Si vous avez l\'intention de payer par un mode de paiement autre qu\'en ligne, vous devrez contacter le studio pour organiser le paiement.</p><ul><li><strong>URL du bon de commande</strong> - &lt;{INVOICE_URL}></li><li><strong>Nom du Photographe</strong> - {OWNER_NAME}</li><li><strong>Emai du Photographe</strong> - {OWNER_EMAIL}</li></ul>',
				order_merchant_reciept_subject: '[{ORDER_ID}] - Une nouvelle commande a Ã©tÃ© crÃ©Ã©e',
				order_merchant_reciept_message_body: '<p>La commande {ORDER_ID} a Ã©tÃ© crÃ©Ã©e et est maintenant disponible Ã  la consultation.  Si le client a utilisÃ© Paypal, vous allez recevoir prochainement une confirmation de paiement.  Si le client a l\'intention de payer en dehors d\'Internet, vous devrez alors le contacter pour organiser le paiement.</p><ul><li><strong>URL du bon de commande</strong> - &lt;{INVOICE_URL}></li><li><strong>URL du bon de production</strong> - &lt;{OUTPUT_URL}></li><li><strong>Nom du client</strong> - {PURCHASER_NAME}</li><li><strong>Email du client</strong> - {PURCHASER_EMAIL}</li><li><strong>TÃ©lÃ©phone du client</strong> - {PURCHASER_PHONE}</li></ul>',
				output_notify_subject: 'Vos photos sont prÃªtes pour Ãªtre visualisÃ©es et commandÃ©es !',
				output_notify_message_body: '<p>Une nouvelle sÃ©rie de photos est disponible pour la sÃ©lection et l\'achat de produits !</p><ul><li><strong>URL de la galerie</strong> - &lt;{SET_URL}></li><li><strong>Date d\'expiration</strong> - {EXPIRATION}</li><li><strong>Mot de passe (si requis)</strong> - {PASSWORD}</li><li><strong>Nom du Photographe</strong> - {OWNER_NAME}</li><li><strong>Email du Photographe</strong> - {OWNER_EMAIL}</li></ul><p>Le message personnel qui vous est destinÃ© :</p><p>{MESSAGE}</p>',
				output_reminder_subject: 'Votre galerie de photos va bientÃ´t expirer !',
				output_reminder_message_body: '<p>Nous souhaitions simplement vous rappeler que votre galerie de photos va bientÃ´t arriver Ã  expiration.</p><ul><li><strong>URL de la galerie</strong> - &lt;{SET_URL}></li><li><strong>Date d\'expiration</strong> - {EXPIRATION}</li><li><strong>Mot de passe (si requis)</strong> - {PASSWORD}</li><li><strong>Nom du Photographe</strong> - {OWNER_NAME}</li><li><strong>Email du Photographe</strong> - {OWNER_EMAIL}</li></ul><p>Le message personnel qui vous est destinÃ© :</p><p>{MESSAGE}</p>',
				output_general_subject: 'Un message concernant votre galerie de photos',
				output_general_message_body: '<p>{MESSAGE}</p><ul><li><strong>URL de la galerie</strong> - &lt;{SET_URL}></li><li><strong>Date d\'expiration</strong> - {EXPIRATION}</li><li><strong>Mot de passe (si requis)</strong> - {PASSWORD}</li><li><strong>Nom du Photographe</strong> - {OWNER_NAME}</li><li><strong>Email du Photographe</strong> - {OWNER_EMAIL}</li></ul>',
				contact_form_title_success: 'Success!',
				contact_form_title_fail: 'Whoops!',
				dropbox_reset_approved_subject: 'Download Limit Reset Request Approved',
				dropbox_reset_approved_body: '<h2>Download Limit Reset Request Approved</h2><p>Your request for your download limit to be reset for order {ORDER_ID} has been approved.</p><p><a href="{INVOICE_URL}">View Invoice</a></p><p><strong>Contact Name</strong> - {OWNER_NAME}</p><p><strong>Contact Email</strong> - {OWNER_EMAIL}</p>',
				dropbox_reset_request_subject: 'Download Limit Reset Request',
				dropbox_reset_request_body: '<h2>Download Limit Reset Request</h2><p>A client has requested that their download limit for order {ORDER_ID} be reset.</p><p><a href="{RESET_URL}">Click to Approve</a></p><p><a href="{INVOICE_URL}">View Invoice</a></p><p><strong>Contact Name</strong> - {PURCHASER_NAME}</p><p><strong>Contact Email</strong> - {PURCHASER_EMAIL}</p><p><strong>Contact Phone</strong> - {PURCHASER_PHONE}</p>',
				dropbox_reset_notify_subject: 'Dropbox API Issues',
				dropbox_reset_notify_body: '<h2>Dropbox API Issues</h2><p>A client is trying to download files for order {ORDER_ID} but there seems to be an issue.  You may need to re-authorize your Dropbox app, or you might have been rate-limited.</p><p><a href="{INVOICE_URL}">Invoice URL</a></p><ul><li><p><strong>Contact Name</strong> - {PURCHASER_NAME}</p></li><li><p><strong>Contact Email</strong> - {PURCHASER_EMAIL}</p></li><li><p><strong>Contact Phone</strong> - {PURCHASER_PHONE}</p></li></ul>',
				contact_form_autoresponder_subject: 'Thank You For Contacting Us!',
				contact_form_autoresponder_message_body: '<h2>Hello There!</h2><p>Hello {SENDER_NAME},</p><p>Thank you for contacting us.  We\'ll respond to your message promptly.</p>',
				_: '',
			},
			ordering: {
				alacarte_label: 'Tirages seuls',
				favorites_label: 'SÃ©lection',
				favorites_tooltip_add: 'Ajouter Ã  la sÃ©lection',
				favorites_tooltip_remove: 'Retirer de la sÃ©lection',
				sidebar_add_to_cart: 'AJOUTER AU PANIER',
				sidebar_none_selected: 'Rien de sÃ©lectionnÃ©',
				sidebar_choose_a_size: 'Choisir le format ou le produit pour cette image',
				sidebar_choose_quantity: 'Choisir une quantitÃ©',
				sidebar_choose_tone: 'Choisir une couleur/tonalitÃ©',
				sidebar_tone_black_and_white: 'Noir &amp; blanc',
				sidebar_tone_sepia: 'SÃ©pia',
				sidebar_choose_paper: 'Choisir un papier',
				sidebar_choose_modifier: 'Plus d&#039;options',
				sidebar_enable_crop: 'Autoriser la prÃ©visualisation de recadrage',
				sidebar_crop_portrait: 'Portrait',
				sidebar_crop_landscape: 'Paysage',
				sidebar_comments: 'Commentaires',
				sidebar_package_remaining: 'restant',
				sidebar_browse_packages: 'Cliquez ici et dÃ©couvrez nos diffÃ©rents packs',
				sidebar_currently_adding_to: 'Choisissez vers quel produit vous destinez cette image',
				image_preview_return: 'RETOURNER A LA SELECTION',
				image_preview_return_to_wall: 'FERMER ET RETOURNER AU MUR',
				image_preview_tooltip_previous: 'Voir l&#039;article prÃ©cÃ©dent du panier',
				image_preview_tooltip_next: 'Voir l&#039;article suivant du panier',
				image_browser_tooltip_left: 'Image prÃ©cÃ©dente (touche flÃ¨che gauche)',
				image_browser_tooltip_right: 'Image suivante (barre espace ou touche flÃ¨che droite)',
				image_browser_tooltip_fullscreen: 'Zoomer &amp; Panoramique',
				image_browser_tooltip_favorite: 'Basculer cette image dans la sÃ©lection (touches flÃ¨ches haut ou bas)',
				overview_change_quantity: 'Modifier la quantitÃ©',
				overview_package_maximum: 'maximum',
				overview_toning: 'Couleur/TonalitÃ© sÃ©lectionnÃ©e',
				overview_image_format: 'Format d&#039;image',
				overview_orientation: 'Orientation',
				overview_paper_format: 'Format de papier',
				overview_modifier: 'Option de format',
				overview_comments: 'Vos commentaires',
				overview_save_changes: 'ENREGISTRER',
				overview_empty: 'PANIER VIDE',
				overview_view_cart: 'CONTENU DU PANIER',
				cart_checkout: 'COMMANDER',
				cart_clear_cart: 'VIDER LE PANIER',
				cart_delete_confirmation_title: 'ÃŠtes-vous certain ?',
				cart_delete_confirmation_description: 'La suppression des articles de votre panier ne peut-Ãªtre annulÃ©e.  ÃŠtes-vous certain de vouloir supprimer ?',
				cart_alacarte_items: 'articles',
				cart_package_delete: 'SUPPRIMER',
				cart_item_delete: 'SUPPRIMER',
				cart_alacarte_delete: 'EFFACER LES ARTICLES',
				cart_package_completion: 'TerminÃ©',
				package_add_dialog_enter_nickname: 'Donnez un nom Ã  ce produit',
				package_add_dialog_submit: 'Ajouter au panier',
				package_tooltip_previous: 'Voir l&#039;article prÃ©cÃ©dent',
				package_tooltip_next: 'Voir l&#039;article suivant',
				package_add_to_cart: 'AJOUTER AU PANIER',
				package_no_description_heading: 'Contient les Ã©lÃ©ments suivants :',
				packages_available_packages: 'Packages disponibles',
				packages_available_products: 'Produits disponibles',
				packages_return_to_browsing: 'RETOURNER A LA SELECTION',
				navigation_images_title: 'Images',
				navigation_images_all: 'Toutes les Images',
				navigation_images_page: 'Page',
				navigation_favorites_title: 'SÃ©lections',
				navigation_favorites_all: 'Toutes les sÃ©lections',
				navigation_favorites_page: 'Page sÃ©lections',
				navigation_cart_title: 'Elements du panier',
				navigation_cart_all: 'Tous les Ã©lÃ©ments du panier',
				navigation_cart_page: 'Page Ã©lements du panier',
				navigation_clear_favorites: 'Effacer les sÃ©lections',
				navigation_cart_empty: 'Panier vide',
				navigation_no_favorites: 'Aucune sÃ©lection',
				navigation_view_cart: 'Contenu du panier',
				navigation_clear_cart: 'Vider le panier',
				navigation_checkout: 'COMMANDER',
				navigation_download_all_high: 'Download All High Resolution',
				navigation_download_all_low: 'Download All Low Resolution',
				imagewall_next: 'Next Page',
				imagewall_back_to_top: 'Back To Top',
				image_browser_options: 'CART OPTIONS',
				image_browser_options_done: 'DONE',
				sidebar_download: 'Download',
				sidebar_return: 'RETURN',
				packages_none_available: 'There Are No Packages Available',
				packages_items_label: 'Items',
				packages_price_label: 'Price',
				packages_cancel: 'Cancel',
				packages_close: 'Close',
				overview_close: 'Close',
				cart_download_all_confirmation_title: 'Are you Sure?',
				cart_download_all_confirmation_description: 'You are about to download {QUANTITY} {QUALITY} images to your cart for {PRICE}.  Are you sure you want to continue?',
				downloads_label: 'Digital Downloads',
				cart_empty: 'There Are No Items In Your Cart',
				overview_image_quality: 'Image Quality',
				sidebar_comments_done: 'Done',
				sidebar_high_resolution: 'High Resolution',
				sidebar_low_resolution: 'Web Resolution',
				_: '',
			},
			checkout: {
				checkout_return_to_checkout: 'RETOUR AU PAIEMENT',
				checkout_return_to_cart: 'RETOUR AU PANIER',
				checkout_terms_accept: 'J&#039;accepte les',
				checkout_terms_label: 'Termes et Conditions',
				checkout_package_incomplete_title: 'Quelque chose ne semble pas finalisÃ© !',
				checkout_package_incomplete_description: 'Vous avez un package ou bien un produit dans votre panier, qui ne contient pas le nombre d&#039;images requis.  Veuillez s&#039;il vous plait revoir vos sÃ©lections, et vÃ©rifier que chaque produit ou package est correctement complÃ©tÃ©.  Merci !',
				checkout_minimum_title: 'Votre panier n&#039;atteint pas le minimum de commande requis',
				checkout_minimum_count_description: 'Avant de pouvoir valider votre commande, vous devrez atteindre le minimum de commande requis.  Le nombre minimum d&#039;articles dans votre panier doit Ãªtre de {COUNT_MINIMUM}.  Veuillez s&#039;il vous plait retourner Ã  la sÃ©lection afin d&#039;ajouter d&#039;autres articles dans votre panier pour pouvoir poursuivre.',
				checkout_minimum_subtotal_description: 'Avant de pouvoir valider votre commande, vous devrez atteindre le minimum de commande requis.  Le montant minimum de commande doit-Ãªtre de {SUBTOTAL_MINIMUM}.  Veuillez s&#039;il vous plait retourner Ã  la sÃ©lection afin d&#039;ajouter d&#039;autres articles dans votre panier pour pouvoir poursuivre.',
				checkout_highlighted_fields_required_title: 'Les champs mis en Ã©vidence sont requis !',
				checkout_highlighted_fields_required_description: 'Veuillez vÃ©rifier d&#039;avoir complÃ¨tement renseignÃ©s tous les champs disponibles et mis en Ã©vidence avec des informations valides.  Merci !',
				checkout_email_addresses_do_not_match_title: 'Oups !',
				checkout_email_addresses_do_not_match_description: 'Les adresses email fournies ne sont pas identiques.  C&#039;est extrÃªmement important que nous ayons une adresse valide, car ce sera une premiÃ¨re forme de confirmation.',
				checkout_invalid_email_address_title: 'Oups !',
				checkout_invalid_email_address_description: 'Les adresses email fournies ne sont pas valides.  C&#039;est extrÃªmement important que nous ayons une adresse valide, car ce sera une premiÃ¨re forme de confirmation.',
				checkout_discount_code_error_title: 'Erreur de code de rÃ©duction !',
				checkout_discount_code_error_description: 'Le code de rÃ©duction que vous avez fourni lorsque vous avez dÃ©butÃ© votre commande a expirÃ©.  Veuillez nous contacter dÃ¨s que possible pour vÃ©rifier cette erreur.',
				checkout_paypal_order: 'Commande',
				checkout_return_to_browsing: 'RETOURNER A LA SELECTION',
				checkout_purchase_now: 'ACHETER MAINTENANT',
				checkout_choose_payment_method: 'SÃ©lectionnez un moyen de paiement',
				checkout_payment_method_offline: 'Choisir un mode de paiement autre qu&#039;en ligne',
				checkout_payment_method_paypal: 'Payer maintenant avec Paypal',
				checkout_payment_method_merchant: 'Payer maintenant avec une carte bancaire',
				checkout_choose_shipping_method: 'SÃ©lectionner un mode de livraison',
				checkout_shipping_method_local: 'Passez rÃ©cupÃ©rer la commande au studio',
				checkout_shipping_method_ship: 'DÃ©finir une adresse de livraison',
				checkout_shipping_method_ship_paypal: 'Adresse de livraison de votre compte Paypal',
				checkout_cc_number: 'Votre numÃ©ro de carte de crÃ©dit',
				checkout_cc_cvv_number: 'Code de sÃ©curitÃ©',
				checkout_cc_expiry_month: 'Mois d&#039;expiration',
				checkout_cc_expiry_year: 'AnnÃ©e d&#039;expiration',
				checkout_cc_billing_postal_code: 'Code postal de l&#039;adresse de facturation',
				checkout_info_name: 'Votre nom et prÃ©nom',
				checkout_info_email_address: 'Votre adresse email',
				checkout_info_email_check: 'Confirmez votre adresse email',
				checkout_info_phone: 'Votre numÃ©ro de tÃ©lÃ©phone',
				checkout_shipping_address: 'Adresse de livraison complÃ¨te',
				checkout_shipping_country: 'Pays de livraison',
				checkout_shipping_postal_code: 'Code postal de livraison',
				checkout_billing_country: 'Pays de facturation',
				checkout_billing_postal_code: 'Code postal de facturation',
				checkout_discount_code: 'Code de rÃ©duction',
				checkout_discount_code_apply: 'Appliquer',
				checkout_cart_total: 'Sous-total du panier',
				checkout_cart_discount: 'Montant de rÃ©duction',
				checkout_cart_subtotal: 'Sous-total',
				checkout_cart_tax: 'Taxes',
				checkout_cart_shipping: 'Livraison',
				checkout_cart_handling_i18l: 'Frais de prÃ©paration pour l&#039;international',
				checkout_cart_handling: 'Frais de prÃ©paration',
				checkout_cart_final_total: 'Prix d&#039;achat',
				checkout_cart_no_calculate: '(calculÃ© lors de l&#039;achat)',
				checkout_discount_does_not_exist: 'Le code de rÃ©duction n&#039;existe pas !',
				checkout_discount_expired: 'Le code de rÃ©duction a expirÃ© !',
				checkout_discount_maximum_uses_filled: 'Le nombre d&#039;utilisiation du code de rÃ©duction a dÃ©jÃ  Ã©tÃ© utilisÃ© Ã  son maximum !',
				checkout_discount_cart_minimum_not_fulfilled: 'Le panier n&#039;atteint pas le seuil minimum d&#039;achat !',
				checkout_paypal_price_zero_title: 'Oups !',
				checkout_paypal_price_zero_description: 'Les achats via Paypal doivent Ãªtre supÃ©rieurs Ã  zÃ©ro.  Veuillez choisir un autre mode de paiement, ou contactez directement le studio pour poursuivre le traitement de cette commande.',
				checkout_credit_card_error: 'Oups !',
				checkout_credit_card_card_expired: 'Apparemment, la carte de crÃ©dit que vous souhaitez utiliser est expirÃ©e.  Veuillez utiliser une autre carte de crÃ©dit.',
				checkout_credit_card_cvv_invalid: 'Le code de sÃ©curitÃ© de votre carte de crÃ©dit, apparaissant sur le dos de celle-ci, n&#039;est pas valide ou incorrect.',
				checkout_credit_card_processor_declined: 'Votre banque Ã©mettrice a refusÃ© cette transaction.  Veuillez contacter votre banque ou sociÃ©tÃ© de crÃ©dit, ou essayez une autre carte de crÃ©dit.',
				checkout_credit_card_invalid_expiration: 'La date d&#039;expiration que vous avez renseignÃ©e est incorrecte.  Elle doit Ãªtre composÃ©e d&#039;un mois Ã  2 chiffres (MM) et d&#039;une annÃ©e Ã  4 chiffres (AAAA).  Veuillez vÃ©rifier les valeurs saisies et essayez Ã  nouveau.',
				checkout_credit_card_invalid_card_type: 'Nous ne pouvons pas vÃ©rifier les informations de carte de crÃ©dit que vous avez renseignÃ©.  Elles apparaissent comme non valides.  Veuillez vÃ©rifier les informations que vous avez saisies et essayez Ã  nouveau.',
				checkout_credit_card_zip_code_no_match: 'Le code postal fourni ne correspond pas Ã  celui que votre banque renseigne.  Veuillez vÃ©rifier les informations, et essayez Ã  nouveau.',
				checkout_credit_card_gateway_decline: 'Notre systÃ¨me de paiement ne peut pas accepter ce paiement.  Veuillez essayer une autre carte, ou vÃ©rifier les informations que vous avez saisies, et essayez Ã  nouveau.',
				checkout_credit_card_filter_declined: 'Notre systÃ¨me de paiement ne peut pas accepter ce paiement.  Votre mode de paiement n&#039;est pas conforme Ã  nos normes de sÃ©curitÃ©.  Veuillez essayer une autre carte, ou vÃ©rifiez les informations que vous avez saisies, et essayez Ã  nouveau.',
				checkout_credit_card_temporarily_unavailable: 'Notre systÃ¨me de paiement est actuellement indisponible.  Veuillez rÃ©essayer plus tard.',
				checkout_credit_card_general_error: 'Notre systÃ¨me de paiement ne peut pas accepter ce paiement.  Veuillez essayer une autre carte, ou vÃ©rifier les informations que vous avez saisies, et essayez Ã  nouveau.',
				checkout_shipping_address_line1: 'Address Line 1',
				checkout_shipping_address_line2: 'Address Line 2',
				checkout_shipping_address_city: 'City',
				checkout_offline_unavailable_with_downloads_title: 'Whoops!',
				checkout_offline_unavailable_with_downloads_description: 'When purchasing digital downloads, you must choose an real-time payment option due to it&#039;s live delivery.',
				checkout_cart_insecure_title: 'Security Warning',
				checkout_cart_insecure_description: 'You are about to send your sensitive credit card information over an insecure connection that any hacker with a sniffer can listen in on.  Doing so is a security risk that exposes you to security vulnerabilities.  It&#039;s really not recommended ... you&#039;ve been warned!',
				_: '',
			},
			invoice: {
				invoice_please_login: 'Visualiser le bon de commande',
				invoice_dialog_orderid: 'NumÃ©ro de commande',
				invoice_dialog_email_address: 'Email du client',
				invoice_dialog_submit: 'Envoyer',
				invoice_email_not_matching: 'L&#039;adresse email fournie ne correspond pas Ã  celle que nous avons enregistrÃ©e pour ce bon de commande.  Veuillez vÃ©rifier et soumettre Ã  nouveau.',
				invoice_order_inexistent: 'Nous n&#039;avons aucune trace de cette commande en base de donnÃ©es.  Veuillez vÃ©rifier le numÃ©ro de commande et soumettre Ã  nouveau.',
				invoice_title: 'BON DE COMMANDE',
				invoice_order_date_label: 'Date de commande :',
				invoice_orderid: 'NumÃ©ro de commande :',
				invoice_setid: 'ID de la galerie :',
				invoice_payment_method: 'MÃ©thode de paiement :',
				invoice_payment_offline: 'En dehors d&#039;Internet',
				invoice_payment_paypal: 'Paypal',
				invoice_payment_merchant: 'Carte bancaire',
				invoice_phone_prefix: 'TÃ©lÃ©phone :',
				invoice_email_prefix: 'Email :',
				invoice_web_prefix: 'Internet :',
				invoice_item_label: 'Article',
				invoice_quantity_label: 'QuantitÃ©',
				invoice_unit_price_label: 'Prix unitaire',
				invoice_unit_total_label: 'Total',
				invoice_purchaser_notes: 'Notes d&#039;achat',
				invoice_download_label: 'Downloads',
				invoice_quality_label: 'Quality',
				download_start: 'Start Processing Download',
				download_start_label: 'This may take some time, depending on how many images and thier sizes.',
				download_show: 'Show Downloads',
				download_show_label: 'Downloads may be split into multiple downloads.',
				download_continue_processing: 'Continue Processing Package',
				download_continue_processing_label: 'This may take some time, depending on how many images and thier sizes.',
				download_processing: 'Processing Package',
				download_processing_label: '{PERCENT}% Complete',
				download_reset: 'Request Reset',
				download_reset_label: 'You have reached your download limit.  Please request a download limit reset.',
				download_reset_reply: 'Your request has been sent -- we&#039;ll notify you by email once the limit has been reset.',
				download_notify: 'Something Is Wrong',
				download_notify_label: 'Something is not setup correctly on our end.  Please let us know so we can fix it!',
				download_notify_reply: 'Thanks for the heads up!  We&#039;ll get back to you ASAP.',
				download_reply_sent: 'Sent!',
				download_link_format: 'File Group {COUNT} of {TOTAL}',
				invoice_high_resolution: 'High',
				invoice_low_resolution: 'Low',
				_: '',
			},
			localization: {
				currency_shipping_and_handling_abbreviation: 'S&amp;H',
				currency_decimal_symbol: ',',
				currency_digits_after_decimal_num: '2',
				currency_grouping_symbol: '.',
				currency_digits_per_group_num: '3',
				currency_negative_pattern: '-#',
				currency_display_leading_zeros_bool: 'false',
				currency_leading_zero_digits_num: '0',
				currency_currency_pattern: '# â‚¬',
				date_pattern: 'd/m/Y',
				_: '',
			},
			_: {}
		};
		/* public methods
			*/
		this.get = function(group, node) {
			return l10n[group][node];
		};
	}
	return new Constructor();
})();


$(document).ready(function() {
	
	if (typeof fbq == 'function') { 
		fbq('track', 'PageView');
	}
	if (typeof ga == 'function') { 
		ga('set', 'page', document.location);
		ga('send', 'pageview');
	}
	
});