/* Minification failed. Returning unminified contents.
(9799,25-26): run-time warning JS1004: Expected ';': c
 */
(function (n, t) { typeof module == "object" && typeof module.exports == "object" ? module.exports = n.document ? t(n, !0) : function (n) { if (!n.document) throw new Error("jQuery requires a window with a document"); return t(n) } : t(n) })(typeof window != "undefined" ? window : this, function (n, t) { function ui(n) { var t = n.length, r = i.type(n); return r === "function" || i.isWindow(n) ? !1 : n.nodeType === 1 && t ? !0 : r === "array" || t === 0 || typeof t == "number" && t > 0 && t - 1 in n } function fi(n, t, r) { if (i.isFunction(t)) return i.grep(n, function (n, i) { return !!t.call(n, i, n) !== r }); if (t.nodeType) return i.grep(n, function (n) { return n === t !== r }); if (typeof t == "string") { if (ef.test(t)) return i.filter(t, n, r); t = i.filter(t, n) } return i.grep(n, function (n) { return et.call(t, n) >= 0 !== r }) } function ur(n, t) { while ((n = n[t]) && n.nodeType !== 1); return n } function of(n) { var t = ei[n] = {}; return i.each(n.match(c) || [], function (n, i) { t[i] = !0 }), t } function ct() { u.removeEventListener("DOMContentLoaded", ct, !1); n.removeEventListener("load", ct, !1); i.ready() } function p() { Object.defineProperty(this.cache = {}, 0, { get: function () { return {} } }); this.expando = i.expando + Math.random() } function fr(n, t, r) { var u; if (r === undefined && n.nodeType === 1) if (u = "data-" + t.replace(hf, "-$1").toLowerCase(), r = n.getAttribute(u), typeof r == "string") { try { r = r === "true" ? !0 : r === "false" ? !1 : r === "null" ? null : +r + "" === r ? +r : sf.test(r) ? i.parseJSON(r) : r } catch (f) { } e.set(n, t, r) } else r = undefined; return r } function at() { return !0 } function g() { return !1 } function hr() { try { return u.activeElement } catch (n) { } } function vr(n, t) { return i.nodeName(n, "table") && i.nodeName(t.nodeType !== 11 ? t : t.firstChild, "tr") ? n.getElementsByTagName("tbody")[0] || n.appendChild(n.ownerDocument.createElement("tbody")) : n } function bf(n) { return n.type = (n.getAttribute("type") !== null) + "/" + n.type, n } function kf(n) { var t = pf.exec(n.type); return t ? n.type = t[1] : n.removeAttribute("type"), n } function oi(n, t) { for (var i = 0, u = n.length; i < u; i++) r.set(n[i], "globalEval", !t || r.get(t[i], "globalEval")) } function yr(n, t) { var f, c, o, s, h, l, a, u; if (t.nodeType === 1) { if (r.hasData(n) && (s = r.access(n), h = r.set(t, s), u = s.events, u)) { delete h.handle; h.events = {}; for (o in u) for (f = 0, c = u[o].length; f < c; f++) i.event.add(t, o, u[o][f]) } e.hasData(n) && (l = e.access(n), a = i.extend({}, l), e.set(t, a)) } } function o(n, t) { var r = n.getElementsByTagName ? n.getElementsByTagName(t || "*") : n.querySelectorAll ? n.querySelectorAll(t || "*") : []; return t === undefined || t && i.nodeName(n, t) ? i.merge([n], r) : r } function df(n, t) { var i = t.nodeName.toLowerCase(); i === "input" && er.test(n.type) ? t.checked = n.checked : (i === "input" || i === "textarea") && (t.defaultValue = n.defaultValue) } function pr(t, r) { var f, u = i(r.createElement(t)).appendTo(r.body), e = n.getDefaultComputedStyle && (f = n.getDefaultComputedStyle(u[0])) ? f.display : i.css(u[0], "display"); return u.detach(), e } function hi(n) { var r = u, t = si[n]; return t || (t = pr(n, r), t !== "none" && t || (vt = (vt || i("<iframe frameborder='0' width='0' height='0'/>")).appendTo(r.documentElement), r = vt[0].contentDocument, r.write(), r.close(), t = pr(n, r), vt.detach()), si[n] = t), t } function rt(n, t, r) { var e, o, s, u, f = n.style; return r = r || yt(n), r && (u = r.getPropertyValue(t) || r[t]), r && (u !== "" || i.contains(n.ownerDocument, n) || (u = i.style(n, t)), ci.test(u) && wr.test(t) && (e = f.width, o = f.minWidth, s = f.maxWidth, f.minWidth = f.maxWidth = f.width = u, u = r.width, f.width = e, f.minWidth = o, f.maxWidth = s)), u !== undefined ? u + "" : u } function br(n, t) { return { get: function () { if (n()) { delete this.get; return } return (this.get = t).apply(this, arguments) } } } function gr(n, t) { if (t in n) return t; for (var r = t[0].toUpperCase() + t.slice(1), u = t, i = dr.length; i--;) if (t = dr[i] + r, t in n) return t; return u } function nu(n, t, i) { var r = ne.exec(t); return r ? Math.max(0, r[1] - (i || 0)) + (r[2] || "px") : t } function tu(n, t, r, u, f) { for (var e = r === (u ? "border" : "content") ? 4 : t === "width" ? 1 : 0, o = 0; e < 4; e += 2) r === "margin" && (o += i.css(n, r + w[e], !0, f)), u ? (r === "content" && (o -= i.css(n, "padding" + w[e], !0, f)), r !== "margin" && (o -= i.css(n, "border" + w[e] + "Width", !0, f))) : (o += i.css(n, "padding" + w[e], !0, f), r !== "padding" && (o += i.css(n, "border" + w[e] + "Width", !0, f))); return o } function iu(n, t, r) { var o = !0, u = t === "width" ? n.offsetWidth : n.offsetHeight, e = yt(n), s = i.css(n, "boxSizing", !1, e) === "border-box"; if (u <= 0 || u == null) { if (u = rt(n, t, e), (u < 0 || u == null) && (u = n.style[t]), ci.test(u)) return u; o = s && (f.boxSizingReliable() || u === n.style[t]); u = parseFloat(u) || 0 } return u + tu(n, t, r || (s ? "border" : "content"), o, e) + "px" } function ru(n, t) { for (var e, u, s, o = [], f = 0, h = n.length; f < h; f++) (u = n[f], u.style) && (o[f] = r.get(u, "olddisplay"), e = u.style.display, t ? (o[f] || e !== "none" || (u.style.display = ""), u.style.display === "" && it(u) && (o[f] = r.access(u, "olddisplay", hi(u.nodeName)))) : (s = it(u), e === "none" && s || r.set(u, "olddisplay", s ? e : i.css(u, "display")))); for (f = 0; f < h; f++) (u = n[f], u.style) && (t && u.style.display !== "none" && u.style.display !== "" || (u.style.display = t ? o[f] || "" : "none")); return n } function s(n, t, i, r, u) { return new s.prototype.init(n, t, i, r, u) } function fu() { return setTimeout(function () { nt = undefined }), nt = i.now() } function bt(n, t) { var r, u = 0, i = { height: n }; for (t = t ? 1 : 0; u < 4; u += 2 - t) r = w[u], i["margin" + r] = i["padding" + r] = n; return t && (i.opacity = i.width = n), i } function eu(n, t, i) { for (var u, f = (ut[t] || []).concat(ut["*"]), r = 0, e = f.length; r < e; r++) if (u = f[r].call(i, t, n)) return u } function fe(n, t, u) { var f, a, p, v, o, w, h, b, l = this, y = {}, s = n.style, c = n.nodeType && it(n), e = r.get(n, "fxshow"); u.queue || (o = i._queueHooks(n, "fx"), o.unqueued == null && (o.unqueued = 0, w = o.empty.fire, o.empty.fire = function () { o.unqueued || w() }), o.unqueued++, l.always(function () { l.always(function () { o.unqueued--; i.queue(n, "fx").length || o.empty.fire() }) })); n.nodeType === 1 && ("height" in t || "width" in t) && (u.overflow = [s.overflow, s.overflowX, s.overflowY], h = i.css(n, "display"), b = h === "none" ? r.get(n, "olddisplay") || hi(n.nodeName) : h, b === "inline" && i.css(n, "float") === "none" && (s.display = "inline-block")); u.overflow && (s.overflow = "hidden", l.always(function () { s.overflow = u.overflow[0]; s.overflowX = u.overflow[1]; s.overflowY = u.overflow[2] })); for (f in t) if (a = t[f], re.exec(a)) { if (delete t[f], p = p || a === "toggle", a === (c ? "hide" : "show")) if (a === "show" && e && e[f] !== undefined) c = !0; else continue; y[f] = e && e[f] || i.style(n, f) } else h = undefined; if (i.isEmptyObject(y)) (h === "none" ? hi(n.nodeName) : h) === "inline" && (s.display = h); else { e ? "hidden" in e && (c = e.hidden) : e = r.access(n, "fxshow", {}); p && (e.hidden = !c); c ? i(n).show() : l.done(function () { i(n).hide() }); l.done(function () { var t; r.remove(n, "fxshow"); for (t in y) i.style(n, t, y[t]) }); for (f in y) v = eu(c ? e[f] : 0, f, l), f in e || (e[f] = v.start, c && (v.end = v.start, v.start = f === "width" || f === "height" ? 1 : 0)) } } function ee(n, t) { var r, f, e, u, o; for (r in n) if (f = i.camelCase(r), e = t[f], u = n[r], i.isArray(u) && (e = u[1], u = n[r] = u[0]), r !== f && (n[f] = u, delete n[r]), o = i.cssHooks[f], o && "expand" in o) { u = o.expand(u); delete n[f]; for (r in u) r in n || (n[r] = u[r], t[r] = e) } else t[f] = e } function ou(n, t, r) { var e, o, s = 0, l = wt.length, f = i.Deferred().always(function () { delete c.elem }), c = function () { if (o) return !1; for (var s = nt || fu(), t = Math.max(0, u.startTime + u.duration - s), h = t / u.duration || 0, i = 1 - h, r = 0, e = u.tweens.length; r < e; r++) u.tweens[r].run(i); return f.notifyWith(n, [u, i, t]), i < 1 && e ? t : (f.resolveWith(n, [u]), !1) }, u = f.promise({ elem: n, props: i.extend({}, t), opts: i.extend(!0, { specialEasing: {} }, r), originalProperties: t, originalOptions: r, startTime: nt || fu(), duration: r.duration, tweens: [], createTween: function (t, r) { var f = i.Tween(n, u.opts, t, r, u.opts.specialEasing[t] || u.opts.easing); return u.tweens.push(f), f }, stop: function (t) { var i = 0, r = t ? u.tweens.length : 0; if (o) return this; for (o = !0; i < r; i++) u.tweens[i].run(1); return t ? f.resolveWith(n, [u, t]) : f.rejectWith(n, [u, t]), this } }), h = u.props; for (ee(h, u.opts.specialEasing) ; s < l; s++) if (e = wt[s].call(u, n, h, u.opts), e) return e; return i.map(h, eu, u), i.isFunction(u.opts.start) && u.opts.start.call(n, u), i.fx.timer(i.extend(c, { elem: n, anim: u, queue: u.opts.queue })), u.progress(u.opts.progress).done(u.opts.done, u.opts.complete).fail(u.opts.fail).always(u.opts.always) } function pu(n) { return function (t, r) { typeof t != "string" && (r = t, t = "*"); var u, f = 0, e = t.toLowerCase().match(c) || []; if (i.isFunction(r)) while (u = e[f++]) u[0] === "+" ? (u = u.slice(1) || "*", (n[u] = n[u] || []).unshift(r)) : (n[u] = n[u] || []).push(r) } } function wu(n, t, r, u) { function e(s) { var h; return f[s] = !0, i.each(n[s] || [], function (n, i) { var s = i(t, r, u); if (typeof s != "string" || o || f[s]) { if (o) return !(h = s) } else return t.dataTypes.unshift(s), e(s), !1 }), h } var f = {}, o = n === li; return e(t.dataTypes[0]) || !f["*"] && e("*") } function ai(n, t) { var r, u, f = i.ajaxSettings.flatOptions || {}; for (r in t) t[r] !== undefined && ((f[r] ? n : u || (u = {}))[r] = t[r]); return u && i.extend(!0, n, u), n } function ae(n, t, i) { for (var e, u, f, o, s = n.contents, r = n.dataTypes; r[0] === "*";) r.shift(), e === undefined && (e = n.mimeType || t.getResponseHeader("Content-Type")); if (e) for (u in s) if (s[u] && s[u].test(e)) { r.unshift(u); break } if (r[0] in i) f = r[0]; else { for (u in i) { if (!r[0] || n.converters[u + " " + r[0]]) { f = u; break } o || (o = u) } f = f || o } if (f) return f !== r[0] && r.unshift(f), i[f] } function ve(n, t, i, r) { var h, u, f, s, e, o = {}, c = n.dataTypes.slice(); if (c[1]) for (f in n.converters) o[f.toLowerCase()] = n.converters[f]; for (u = c.shift() ; u;) if (n.responseFields[u] && (i[n.responseFields[u]] = t), !e && r && n.dataFilter && (t = n.dataFilter(t, n.dataType)), e = u, u = c.shift(), u) if (u === "*") u = e; else if (e !== "*" && e !== u) { if (f = o[e + " " + u] || o["* " + u], !f) for (h in o) if (s = h.split(" "), s[1] === u && (f = o[e + " " + s[0]] || o["* " + s[0]], f)) { f === !0 ? f = o[h] : o[h] !== !0 && (u = s[0], c.unshift(s[1])); break } if (f !== !0) if (f && n.throws) t = f(t); else try { t = f(t) } catch (l) { return { state: "parsererror", error: f ? l : "No conversion from " + e + " to " + u } } } return { state: "success", data: t } } function vi(n, t, r, u) { var f; if (i.isArray(t)) i.each(t, function (t, i) { r || pe.test(n) ? u(n, i) : vi(n + "[" + (typeof i == "object" ? t : "") + "]", i, r, u) }); else if (r || i.type(t) !== "object") u(n, t); else for (f in t) vi(n + "[" + f + "]", t[f], r, u) } function ku(n) { return i.isWindow(n) ? n : n.nodeType === 9 && n.defaultView } var k = [], a = k.slice, bi = k.concat, ii = k.push, et = k.indexOf, ot = {}, nf = ot.toString, ri = ot.hasOwnProperty, f = {}, u = n.document, ki = "2.1.1", i = function (n, t) { return new i.fn.init(n, t) }, tf = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, rf = /^-ms-/, uf = /-([\da-z])/gi, ff = function (n, t) { return t.toUpperCase() }, y, st, nr, tr, ir, rr, c, ei, ht, l, d, vt, si, oe, su, tt, hu, kt, cu, dt, gt, yi, ti, pi, wi, du, gu; i.fn = i.prototype = { jquery: ki, constructor: i, selector: "", length: 0, toArray: function () { return a.call(this) }, get: function (n) { return n != null ? n < 0 ? this[n + this.length] : this[n] : a.call(this) }, pushStack: function (n) { var t = i.merge(this.constructor(), n); return t.prevObject = this, t.context = this.context, t }, each: function (n, t) { return i.each(this, n, t) }, map: function (n) { return this.pushStack(i.map(this, function (t, i) { return n.call(t, i, t) })) }, slice: function () { return this.pushStack(a.apply(this, arguments)) }, first: function () { return this.eq(0) }, last: function () { return this.eq(-1) }, eq: function (n) { var i = this.length, t = +n + (n < 0 ? i : 0); return this.pushStack(t >= 0 && t < i ? [this[t]] : []) }, end: function () { return this.prevObject || this.constructor(null) }, push: ii, sort: k.sort, splice: k.splice }; i.extend = i.fn.extend = function () { var e, f, r, t, o, s, n = arguments[0] || {}, u = 1, c = arguments.length, h = !1; for (typeof n == "boolean" && (h = n, n = arguments[u] || {}, u++), typeof n == "object" || i.isFunction(n) || (n = {}), u === c && (n = this, u--) ; u < c; u++) if ((e = arguments[u]) != null) for (f in e) (r = n[f], t = e[f], n !== t) && (h && t && (i.isPlainObject(t) || (o = i.isArray(t))) ? (o ? (o = !1, s = r && i.isArray(r) ? r : []) : s = r && i.isPlainObject(r) ? r : {}, n[f] = i.extend(h, s, t)) : t !== undefined && (n[f] = t)); return n }; i.extend({ expando: "jQuery" + (ki + Math.random()).replace(/\D/g, ""), isReady: !0, error: function (n) { throw new Error(n); }, noop: function () { }, isFunction: function (n) { return i.type(n) === "function" }, isArray: Array.isArray, isWindow: function (n) { return n != null && n === n.window }, isNumeric: function (n) { return !i.isArray(n) && n - parseFloat(n) >= 0 }, isPlainObject: function (n) { return i.type(n) !== "object" || n.nodeType || i.isWindow(n) ? !1 : n.constructor && !ri.call(n.constructor.prototype, "isPrototypeOf") ? !1 : !0 }, isEmptyObject: function (n) { for (var t in n) return !1; return !0 }, type: function (n) { return n == null ? n + "" : typeof n == "object" || typeof n == "function" ? ot[nf.call(n)] || "object" : typeof n }, globalEval: function (n) { var t, r = eval; n = i.trim(n); n && (n.indexOf("use strict") === 1 ? (t = u.createElement("script"), t.text = n, u.head.appendChild(t).parentNode.removeChild(t)) : r(n)) }, camelCase: function (n) { return n.replace(rf, "ms-").replace(uf, ff) }, nodeName: function (n, t) { return n.nodeName && n.nodeName.toLowerCase() === t.toLowerCase() }, each: function (n, t, i) { var u, r = 0, f = n.length, e = ui(n); if (i) { if (e) { for (; r < f; r++) if (u = t.apply(n[r], i), u === !1) break } else for (r in n) if (u = t.apply(n[r], i), u === !1) break } else if (e) { for (; r < f; r++) if (u = t.call(n[r], r, n[r]), u === !1) break } else for (r in n) if (u = t.call(n[r], r, n[r]), u === !1) break; return n }, trim: function (n) { return n == null ? "" : (n + "").replace(tf, "") }, makeArray: function (n, t) { var r = t || []; return n != null && (ui(Object(n)) ? i.merge(r, typeof n == "string" ? [n] : n) : ii.call(r, n)), r }, inArray: function (n, t, i) { return t == null ? -1 : et.call(t, n, i) }, merge: function (n, t) { for (var u = +t.length, i = 0, r = n.length; i < u; i++) n[r++] = t[i]; return n.length = r, n }, grep: function (n, t, i) { for (var u, f = [], r = 0, e = n.length, o = !i; r < e; r++) u = !t(n[r], r), u !== o && f.push(n[r]); return f }, map: function (n, t, i) { var u, r = 0, e = n.length, o = ui(n), f = []; if (o) for (; r < e; r++) u = t(n[r], r, i), u != null && f.push(u); else for (r in n) u = t(n[r], r, i), u != null && f.push(u); return bi.apply([], f) }, guid: 1, proxy: function (n, t) { var u, f, r; return (typeof t == "string" && (u = n[t], t = n, n = u), !i.isFunction(n)) ? undefined : (f = a.call(arguments, 2), r = function () { return n.apply(t || this, f.concat(a.call(arguments))) }, r.guid = n.guid = n.guid || i.guid++, r) }, now: Date.now, support: f }); i.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (n, t) { ot["[object " + t + "]"] = t.toLowerCase() }); y = function (n) { function r(n, t, i, r) { var w, h, c, v, k, y, d, l, nt, g; if ((t ? t.ownerDocument || t : s) !== e && p(t), t = t || e, i = i || [], !n || typeof n != "string") return i; if ((v = t.nodeType) !== 1 && v !== 9) return []; if (a && !r) { if (w = sr.exec(n)) if (c = w[1]) { if (v === 9) if (h = t.getElementById(c), h && h.parentNode) { if (h.id === c) return i.push(h), i } else return i; else if (t.ownerDocument && (h = t.ownerDocument.getElementById(c)) && ot(t, h) && h.id === c) return i.push(h), i } else { if (w[2]) return b.apply(i, t.getElementsByTagName(n)), i; if ((c = w[3]) && u.getElementsByClassName && t.getElementsByClassName) return b.apply(i, t.getElementsByClassName(c)), i } if (u.qsa && (!o || !o.test(n))) { if (l = d = f, nt = t, g = v === 9 && n, v === 1 && t.nodeName.toLowerCase() !== "object") { for (y = et(n), (d = t.getAttribute("id")) ? l = d.replace(hr, "\\$&") : t.setAttribute("id", l), l = "[id='" + l + "'] ", k = y.length; k--;) y[k] = l + yt(y[k]); nt = gt.test(n) && ii(t.parentNode) || t; g = y.join(",") } if (g) try { return b.apply(i, nt.querySelectorAll(g)), i } catch (tt) { } finally { d || t.removeAttribute("id") } } } return si(n.replace(at, "$1"), t, i, r) } function ni() { function n(r, u) { return i.push(r + " ") > t.cacheLength && delete n[i.shift()], n[r + " "] = u } var i = []; return n } function h(n) { return n[f] = !0, n } function c(n) { var t = e.createElement("div"); try { return !!n(t) } catch (i) { return !1 } finally { t.parentNode && t.parentNode.removeChild(t); t = null } } function ti(n, i) { for (var u = n.split("|"), r = n.length; r--;) t.attrHandle[u[r]] = i } function wi(n, t) { var i = t && n, r = i && n.nodeType === 1 && t.nodeType === 1 && (~t.sourceIndex || ai) - (~n.sourceIndex || ai); if (r) return r; if (i) while (i = i.nextSibling) if (i === t) return -1; return n ? 1 : -1 } function cr(n) { return function (t) { var i = t.nodeName.toLowerCase(); return i === "input" && t.type === n } } function lr(n) { return function (t) { var i = t.nodeName.toLowerCase(); return (i === "input" || i === "button") && t.type === n } } function tt(n) { return h(function (t) { return t = +t, h(function (i, r) { for (var u, f = n([], i.length, t), e = f.length; e--;) i[u = f[e]] && (i[u] = !(r[u] = i[u])) }) }) } function ii(n) { return n && typeof n.getElementsByTagName !== ut && n } function bi() { } function yt(n) { for (var t = 0, r = n.length, i = ""; t < r; t++) i += n[t].value; return i } function ri(n, t, i) { var r = t.dir, u = i && r === "parentNode", e = ki++; return t.first ? function (t, i, f) { while (t = t[r]) if (t.nodeType === 1 || u) return n(t, i, f) } : function (t, i, o) { var s, h, c = [v, e]; if (o) { while (t = t[r]) if ((t.nodeType === 1 || u) && n(t, i, o)) return !0 } else while (t = t[r]) if (t.nodeType === 1 || u) { if (h = t[f] || (t[f] = {}), (s = h[r]) && s[0] === v && s[1] === e) return c[2] = s[2]; if (h[r] = c, c[2] = n(t, i, o)) return !0 } } } function ui(n) { return n.length > 1 ? function (t, i, r) { for (var u = n.length; u--;) if (!n[u](t, i, r)) return !1; return !0 } : n[0] } function ar(n, t, i) { for (var u = 0, f = t.length; u < f; u++) r(n, t[u], i); return i } function pt(n, t, i, r, u) { for (var e, o = [], f = 0, s = n.length, h = t != null; f < s; f++) (e = n[f]) && (!i || i(e, r, u)) && (o.push(e), h && t.push(f)); return o } function fi(n, t, i, r, u, e) { return r && !r[f] && (r = fi(r)), u && !u[f] && (u = fi(u, e)), h(function (f, e, o, s) { var l, c, a, p = [], y = [], w = e.length, k = f || ar(t || "*", o.nodeType ? [o] : o, []), v = n && (f || !t) ? pt(k, p, n, o, s) : k, h = i ? u || (f ? n : w || r) ? [] : e : v; if (i && i(v, h, o, s), r) for (l = pt(h, y), r(l, [], o, s), c = l.length; c--;) (a = l[c]) && (h[y[c]] = !(v[y[c]] = a)); if (f) { if (u || n) { if (u) { for (l = [], c = h.length; c--;) (a = h[c]) && l.push(v[c] = a); u(null, h = [], l, s) } for (c = h.length; c--;) (a = h[c]) && (l = u ? nt.call(f, a) : p[c]) > -1 && (f[l] = !(e[l] = a)) } } else h = pt(h === e ? h.splice(w, h.length) : h), u ? u(null, e, h, s) : b.apply(e, h) }) } function ei(n) { for (var s, u, r, o = n.length, h = t.relative[n[0].type], c = h || t.relative[" "], i = h ? 1 : 0, l = ri(function (n) { return n === s }, c, !0), a = ri(function (n) { return nt.call(s, n) > -1 }, c, !0), e = [function (n, t, i) { return !h && (i || t !== ct) || ((s = t).nodeType ? l(n, t, i) : a(n, t, i)) }]; i < o; i++) if (u = t.relative[n[i].type]) e = [ri(ui(e), u)]; else { if (u = t.filter[n[i].type].apply(null, n[i].matches), u[f]) { for (r = ++i; r < o; r++) if (t.relative[n[r].type]) break; return fi(i > 1 && ui(e), i > 1 && yt(n.slice(0, i - 1).concat({ value: n[i - 2].type === " " ? "*" : "" })).replace(at, "$1"), u, i < r && ei(n.slice(i, r)), r < o && ei(n = n.slice(r)), r < o && yt(n)) } e.push(u) } return ui(e) } function vr(n, i) { var u = i.length > 0, f = n.length > 0, o = function (o, s, h, c, l) { var y, d, w, k = 0, a = "0", g = o && [], p = [], nt = ct, tt = o || f && t.find.TAG("*", l), it = v += nt == null ? 1 : Math.random() || .1, rt = tt.length; for (l && (ct = s !== e && s) ; a !== rt && (y = tt[a]) != null; a++) { if (f && y) { for (d = 0; w = n[d++];) if (w(y, s, h)) { c.push(y); break } l && (v = it) } u && ((y = !w && y) && k--, o && g.push(y)) } if (k += a, u && a !== k) { for (d = 0; w = i[d++];) w(g, p, s, h); if (o) { if (k > 0) while (a--) g[a] || p[a] || (p[a] = gi.call(c)); p = pt(p) } b.apply(c, p); l && !o && p.length > 0 && k + i.length > 1 && r.uniqueSort(c) } return l && (v = it, ct = nt), g }; return u ? h(o) : o } var it, u, t, ht, oi, et, wt, si, ct, y, rt, p, e, l, a, o, g, lt, ot, f = "sizzle" + -new Date, s = n.document, v = 0, ki = 0, hi = ni(), ci = ni(), li = ni(), bt = function (n, t) { return n === t && (rt = !0), 0 }, ut = typeof undefined, ai = -2147483648, di = {}.hasOwnProperty, w = [], gi = w.pop, nr = w.push, b = w.push, vi = w.slice, nt = w.indexOf || function (n) { for (var t = 0, i = this.length; t < i; t++) if (this[t] === n) return t; return -1 }, kt = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", i = "[\\x20\\t\\r\\n\\f]", ft = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", yi = ft.replace("w", "w#"), pi = "\\[" + i + "*(" + ft + ")(?:" + i + "*([*^$|!~]?=)" + i + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + yi + "))|)" + i + "*\\]", dt = ":(" + ft + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + pi + ")*)|.*)\\)|)", at = new RegExp("^" + i + "+|((?:^|[^\\\\])(?:\\\\.)*)" + i + "+$", "g"), tr = new RegExp("^" + i + "*," + i + "*"), ir = new RegExp("^" + i + "*([>+~]|" + i + ")" + i + "*"), rr = new RegExp("=" + i + "*([^\\]'\"]*?)" + i + "*\\]", "g"), ur = new RegExp(dt), fr = new RegExp("^" + yi + "$"), vt = { ID: new RegExp("^#(" + ft + ")"), CLASS: new RegExp("^\\.(" + ft + ")"), TAG: new RegExp("^(" + ft.replace("w", "w*") + ")"), ATTR: new RegExp("^" + pi), PSEUDO: new RegExp("^" + dt), CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + i + "*(even|odd|(([+-]|)(\\d*)n|)" + i + "*(?:([+-]|)" + i + "*(\\d+)|))" + i + "*\\)|)", "i"), bool: new RegExp("^(?:" + kt + ")$", "i"), needsContext: new RegExp("^" + i + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + i + "*((?:-\\d)?\\d*)" + i + "*\\)|)(?=[^-]|$)", "i") }, er = /^(?:input|select|textarea|button)$/i, or = /^h\d$/i, st = /^[^{]+\{\s*\[native \w/, sr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, gt = /[+~]/, hr = /'|\\/g, k = new RegExp("\\\\([\\da-f]{1,6}" + i + "?|(" + i + ")|.)", "ig"), d = function (n, t, i) { var r = "0x" + t - 65536; return r !== r || i ? t : r < 0 ? String.fromCharCode(r + 65536) : String.fromCharCode(r >> 10 | 55296, r & 1023 | 56320) }; try { b.apply(w = vi.call(s.childNodes), s.childNodes); w[s.childNodes.length].nodeType } catch (yr) { b = { apply: w.length ? function (n, t) { nr.apply(n, vi.call(t)) } : function (n, t) { for (var i = n.length, r = 0; n[i++] = t[r++];); n.length = i - 1 } } } u = r.support = {}; oi = r.isXML = function (n) { var t = n && (n.ownerDocument || n).documentElement; return t ? t.nodeName !== "HTML" : !1 }; p = r.setDocument = function (n) { var v, r = n ? n.ownerDocument || n : s, h = r.defaultView; return r === e || r.nodeType !== 9 || !r.documentElement ? e : (e = r, l = r.documentElement, a = !oi(r), h && h !== h.top && (h.addEventListener ? h.addEventListener("unload", function () { p() }, !1) : h.attachEvent && h.attachEvent("onunload", function () { p() })), u.attributes = c(function (n) { return n.className = "i", !n.getAttribute("className") }), u.getElementsByTagName = c(function (n) { return n.appendChild(r.createComment("")), !n.getElementsByTagName("*").length }), u.getElementsByClassName = st.test(r.getElementsByClassName) && c(function (n) { return n.innerHTML = "<div class='a'><\/div><div class='a i'><\/div>", n.firstChild.className = "i", n.getElementsByClassName("i").length === 2 }), u.getById = c(function (n) { return l.appendChild(n).id = f, !r.getElementsByName || !r.getElementsByName(f).length }), u.getById ? (t.find.ID = function (n, t) { if (typeof t.getElementById !== ut && a) { var i = t.getElementById(n); return i && i.parentNode ? [i] : [] } }, t.filter.ID = function (n) { var t = n.replace(k, d); return function (n) { return n.getAttribute("id") === t } }) : (delete t.find.ID, t.filter.ID = function (n) { var t = n.replace(k, d); return function (n) { var i = typeof n.getAttributeNode !== ut && n.getAttributeNode("id"); return i && i.value === t } }), t.find.TAG = u.getElementsByTagName ? function (n, t) { if (typeof t.getElementsByTagName !== ut) return t.getElementsByTagName(n) } : function (n, t) { var i, r = [], f = 0, u = t.getElementsByTagName(n); if (n === "*") { while (i = u[f++]) i.nodeType === 1 && r.push(i); return r } return u }, t.find.CLASS = u.getElementsByClassName && function (n, t) { if (typeof t.getElementsByClassName !== ut && a) return t.getElementsByClassName(n) }, g = [], o = [], (u.qsa = st.test(r.querySelectorAll)) && (c(function (n) { n.innerHTML = "<select msallowclip=''><option selected=''><\/option><\/select>"; n.querySelectorAll("[msallowclip^='']").length && o.push("[*^$]=" + i + "*(?:''|\"\")"); n.querySelectorAll("[selected]").length || o.push("\\[" + i + "*(?:value|" + kt + ")"); n.querySelectorAll(":checked").length || o.push(":checked") }), c(function (n) { var t = r.createElement("input"); t.setAttribute("type", "hidden"); n.appendChild(t).setAttribute("name", "D"); n.querySelectorAll("[name=d]").length && o.push("name" + i + "*[*^$|!~]?="); n.querySelectorAll(":enabled").length || o.push(":enabled", ":disabled"); n.querySelectorAll("*,:x"); o.push(",.*:") })), (u.matchesSelector = st.test(lt = l.matches || l.webkitMatchesSelector || l.mozMatchesSelector || l.oMatchesSelector || l.msMatchesSelector)) && c(function (n) { u.disconnectedMatch = lt.call(n, "div"); lt.call(n, "[s!='']:x"); g.push("!=", dt) }), o = o.length && new RegExp(o.join("|")), g = g.length && new RegExp(g.join("|")), v = st.test(l.compareDocumentPosition), ot = v || st.test(l.contains) ? function (n, t) { var r = n.nodeType === 9 ? n.documentElement : n, i = t && t.parentNode; return n === i || !!(i && i.nodeType === 1 && (r.contains ? r.contains(i) : n.compareDocumentPosition && n.compareDocumentPosition(i) & 16)) } : function (n, t) { if (t) while (t = t.parentNode) if (t === n) return !0; return !1 }, bt = v ? function (n, t) { if (n === t) return rt = !0, 0; var i = !n.compareDocumentPosition - !t.compareDocumentPosition; return i ? i : (i = (n.ownerDocument || n) === (t.ownerDocument || t) ? n.compareDocumentPosition(t) : 1, i & 1 || !u.sortDetached && t.compareDocumentPosition(n) === i) ? n === r || n.ownerDocument === s && ot(s, n) ? -1 : t === r || t.ownerDocument === s && ot(s, t) ? 1 : y ? nt.call(y, n) - nt.call(y, t) : 0 : i & 4 ? -1 : 1 } : function (n, t) { if (n === t) return rt = !0, 0; var i, u = 0, o = n.parentNode, h = t.parentNode, f = [n], e = [t]; if (o && h) { if (o === h) return wi(n, t) } else return n === r ? -1 : t === r ? 1 : o ? -1 : h ? 1 : y ? nt.call(y, n) - nt.call(y, t) : 0; for (i = n; i = i.parentNode;) f.unshift(i); for (i = t; i = i.parentNode;) e.unshift(i); while (f[u] === e[u]) u++; return u ? wi(f[u], e[u]) : f[u] === s ? -1 : e[u] === s ? 1 : 0 }, r) }; r.matches = function (n, t) { return r(n, null, null, t) }; r.matchesSelector = function (n, t) { if ((n.ownerDocument || n) !== e && p(n), t = t.replace(rr, "='$1']"), u.matchesSelector && a && (!g || !g.test(t)) && (!o || !o.test(t))) try { var i = lt.call(n, t); if (i || u.disconnectedMatch || n.document && n.document.nodeType !== 11) return i } catch (f) { } return r(t, e, null, [n]).length > 0 }; r.contains = function (n, t) { return (n.ownerDocument || n) !== e && p(n), ot(n, t) }; r.attr = function (n, i) { (n.ownerDocument || n) !== e && p(n); var f = t.attrHandle[i.toLowerCase()], r = f && di.call(t.attrHandle, i.toLowerCase()) ? f(n, i, !a) : undefined; return r !== undefined ? r : u.attributes || !a ? n.getAttribute(i) : (r = n.getAttributeNode(i)) && r.specified ? r.value : null }; r.error = function (n) { throw new Error("Syntax error, unrecognized expression: " + n); }; r.uniqueSort = function (n) { var r, f = [], t = 0, i = 0; if (rt = !u.detectDuplicates, y = !u.sortStable && n.slice(0), n.sort(bt), rt) { while (r = n[i++]) r === n[i] && (t = f.push(i)); while (t--) n.splice(f[t], 1) } return y = null, n }; ht = r.getText = function (n) { var r, i = "", u = 0, t = n.nodeType; if (t) { if (t === 1 || t === 9 || t === 11) { if (typeof n.textContent == "string") return n.textContent; for (n = n.firstChild; n; n = n.nextSibling) i += ht(n) } else if (t === 3 || t === 4) return n.nodeValue } else while (r = n[u++]) i += ht(r); return i }; t = r.selectors = { cacheLength: 50, createPseudo: h, match: vt, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: !0 }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: !0 }, "~": { dir: "previousSibling" } }, preFilter: { ATTR: function (n) { return n[1] = n[1].replace(k, d), n[3] = (n[3] || n[4] || n[5] || "").replace(k, d), n[2] === "~=" && (n[3] = " " + n[3] + " "), n.slice(0, 4) }, CHILD: function (n) { return n[1] = n[1].toLowerCase(), n[1].slice(0, 3) === "nth" ? (n[3] || r.error(n[0]), n[4] = +(n[4] ? n[5] + (n[6] || 1) : 2 * (n[3] === "even" || n[3] === "odd")), n[5] = +(n[7] + n[8] || n[3] === "odd")) : n[3] && r.error(n[0]), n }, PSEUDO: function (n) { var i, t = !n[6] && n[2]; return vt.CHILD.test(n[0]) ? null : (n[3] ? n[2] = n[4] || n[5] || "" : t && ur.test(t) && (i = et(t, !0)) && (i = t.indexOf(")", t.length - i) - t.length) && (n[0] = n[0].slice(0, i), n[2] = t.slice(0, i)), n.slice(0, 3)) } }, filter: { TAG: function (n) { var t = n.replace(k, d).toLowerCase(); return n === "*" ? function () { return !0 } : function (n) { return n.nodeName && n.nodeName.toLowerCase() === t } }, CLASS: function (n) { var t = hi[n + " "]; return t || (t = new RegExp("(^|" + i + ")" + n + "(" + i + "|$)")) && hi(n, function (n) { return t.test(typeof n.className == "string" && n.className || typeof n.getAttribute !== ut && n.getAttribute("class") || "") }) }, ATTR: function (n, t, i) { return function (u) { var f = r.attr(u, n); return f == null ? t === "!=" : t ? (f += "", t === "=" ? f === i : t === "!=" ? f !== i : t === "^=" ? i && f.indexOf(i) === 0 : t === "*=" ? i && f.indexOf(i) > -1 : t === "$=" ? i && f.slice(-i.length) === i : t === "~=" ? (" " + f + " ").indexOf(i) > -1 : t === "|=" ? f === i || f.slice(0, i.length + 1) === i + "-" : !1) : !0 } }, CHILD: function (n, t, i, r, u) { var s = n.slice(0, 3) !== "nth", o = n.slice(-4) !== "last", e = t === "of-type"; return r === 1 && u === 0 ? function (n) { return !!n.parentNode } : function (t, i, h) { var a, k, c, l, y, w, b = s !== o ? "nextSibling" : "previousSibling", p = t.parentNode, g = e && t.nodeName.toLowerCase(), d = !h && !e; if (p) { if (s) { while (b) { for (c = t; c = c[b];) if (e ? c.nodeName.toLowerCase() === g : c.nodeType === 1) return !1; w = b = n === "only" && !w && "nextSibling" } return !0 } if (w = [o ? p.firstChild : p.lastChild], o && d) { for (k = p[f] || (p[f] = {}), a = k[n] || [], y = a[0] === v && a[1], l = a[0] === v && a[2], c = y && p.childNodes[y]; c = ++y && c && c[b] || (l = y = 0) || w.pop() ;) if (c.nodeType === 1 && ++l && c === t) { k[n] = [v, y, l]; break } } else if (d && (a = (t[f] || (t[f] = {}))[n]) && a[0] === v) l = a[1]; else while (c = ++y && c && c[b] || (l = y = 0) || w.pop()) if ((e ? c.nodeName.toLowerCase() === g : c.nodeType === 1) && ++l && (d && ((c[f] || (c[f] = {}))[n] = [v, l]), c === t)) break; return l -= u, l === r || l % r == 0 && l / r >= 0 } } }, PSEUDO: function (n, i) { var e, u = t.pseudos[n] || t.setFilters[n.toLowerCase()] || r.error("unsupported pseudo: " + n); return u[f] ? u(i) : u.length > 1 ? (e = [n, n, "", i], t.setFilters.hasOwnProperty(n.toLowerCase()) ? h(function (n, t) { for (var r, f = u(n, i), e = f.length; e--;) r = nt.call(n, f[e]), n[r] = !(t[r] = f[e]) }) : function (n) { return u(n, 0, e) }) : u } }, pseudos: { not: h(function (n) { var i = [], r = [], t = wt(n.replace(at, "$1")); return t[f] ? h(function (n, i, r, u) { for (var e, o = t(n, null, u, []), f = n.length; f--;) (e = o[f]) && (n[f] = !(i[f] = e)) }) : function (n, u, f) { return i[0] = n, t(i, null, f, r), !r.pop() } }), has: h(function (n) { return function (t) { return r(n, t).length > 0 } }), contains: h(function (n) { return function (t) { return (t.textContent || t.innerText || ht(t)).indexOf(n) > -1 } }), lang: h(function (n) { return fr.test(n || "") || r.error("unsupported lang: " + n), n = n.replace(k, d).toLowerCase(), function (t) { var i; do if (i = a ? t.lang : t.getAttribute("xml:lang") || t.getAttribute("lang")) return i = i.toLowerCase(), i === n || i.indexOf(n + "-") === 0; while ((t = t.parentNode) && t.nodeType === 1); return !1 } }), target: function (t) { var i = n.location && n.location.hash; return i && i.slice(1) === t.id }, root: function (n) { return n === l }, focus: function (n) { return n === e.activeElement && (!e.hasFocus || e.hasFocus()) && !!(n.type || n.href || ~n.tabIndex) }, enabled: function (n) { return n.disabled === !1 }, disabled: function (n) { return n.disabled === !0 }, checked: function (n) { var t = n.nodeName.toLowerCase(); return t === "input" && !!n.checked || t === "option" && !!n.selected }, selected: function (n) { return n.parentNode && n.parentNode.selectedIndex, n.selected === !0 }, empty: function (n) { for (n = n.firstChild; n; n = n.nextSibling) if (n.nodeType < 6) return !1; return !0 }, parent: function (n) { return !t.pseudos.empty(n) }, header: function (n) { return or.test(n.nodeName) }, input: function (n) { return er.test(n.nodeName) }, button: function (n) { var t = n.nodeName.toLowerCase(); return t === "input" && n.type === "button" || t === "button" }, text: function (n) { var t; return n.nodeName.toLowerCase() === "input" && n.type === "text" && ((t = n.getAttribute("type")) == null || t.toLowerCase() === "text") }, first: tt(function () { return [0] }), last: tt(function (n, t) { return [t - 1] }), eq: tt(function (n, t, i) { return [i < 0 ? i + t : i] }), even: tt(function (n, t) { for (var i = 0; i < t; i += 2) n.push(i); return n }), odd: tt(function (n, t) { for (var i = 1; i < t; i += 2) n.push(i); return n }), lt: tt(function (n, t, i) { for (var r = i < 0 ? i + t : i; --r >= 0;) n.push(r); return n }), gt: tt(function (n, t, i) { for (var r = i < 0 ? i + t : i; ++r < t;) n.push(r); return n }) } }; t.pseudos.nth = t.pseudos.eq; for (it in { radio: !0, checkbox: !0, file: !0, password: !0, image: !0 }) t.pseudos[it] = cr(it); for (it in { submit: !0, reset: !0 }) t.pseudos[it] = lr(it); return bi.prototype = t.filters = t.pseudos, t.setFilters = new bi, et = r.tokenize = function (n, i) { var e, f, s, o, u, h, c, l = ci[n + " "]; if (l) return i ? 0 : l.slice(0); for (u = n, h = [], c = t.preFilter; u;) { (!e || (f = tr.exec(u))) && (f && (u = u.slice(f[0].length) || u), h.push(s = [])); e = !1; (f = ir.exec(u)) && (e = f.shift(), s.push({ value: e, type: f[0].replace(at, " ") }), u = u.slice(e.length)); for (o in t.filter) (f = vt[o].exec(u)) && (!c[o] || (f = c[o](f))) && (e = f.shift(), s.push({ value: e, type: o, matches: f }), u = u.slice(e.length)); if (!e) break } return i ? u.length : u ? r.error(n) : ci(n, h).slice(0) }, wt = r.compile = function (n, t) { var r, u = [], e = [], i = li[n + " "]; if (!i) { for (t || (t = et(n)), r = t.length; r--;) i = ei(t[r]), i[f] ? u.push(i) : e.push(i); i = li(n, vr(e, u)); i.selector = n } return i }, si = r.select = function (n, i, r, f) { var s, e, o, l, v, c = typeof n == "function" && n, h = !f && et(n = c.selector || n); if (r = r || [], h.length === 1) { if (e = h[0] = h[0].slice(0), e.length > 2 && (o = e[0]).type === "ID" && u.getById && i.nodeType === 9 && a && t.relative[e[1].type]) { if (i = (t.find.ID(o.matches[0].replace(k, d), i) || [])[0], i) c && (i = i.parentNode); else return r; n = n.slice(e.shift().value.length) } for (s = vt.needsContext.test(n) ? 0 : e.length; s--;) { if (o = e[s], t.relative[l = o.type]) break; if ((v = t.find[l]) && (f = v(o.matches[0].replace(k, d), gt.test(e[0].type) && ii(i.parentNode) || i))) { if (e.splice(s, 1), n = f.length && yt(e), !n) return b.apply(r, f), r; break } } } return (c || wt(n, h))(f, i, !a, r, gt.test(n) && ii(i.parentNode) || i), r }, u.sortStable = f.split("").sort(bt).join("") === f, u.detectDuplicates = !!rt, p(), u.sortDetached = c(function (n) { return n.compareDocumentPosition(e.createElement("div")) & 1 }), c(function (n) { return n.innerHTML = "<a href='#'><\/a>", n.firstChild.getAttribute("href") === "#" }) || ti("type|href|height|width", function (n, t, i) { if (!i) return n.getAttribute(t, t.toLowerCase() === "type" ? 1 : 2) }), u.attributes && c(function (n) { return n.innerHTML = "<input/>", n.firstChild.setAttribute("value", ""), n.firstChild.getAttribute("value") === "" }) || ti("value", function (n, t, i) { if (!i && n.nodeName.toLowerCase() === "input") return n.defaultValue }), c(function (n) { return n.getAttribute("disabled") == null }) || ti(kt, function (n, t, i) { var r; if (!i) return n[t] === !0 ? t.toLowerCase() : (r = n.getAttributeNode(t)) && r.specified ? r.value : null }), r }(n); i.find = y; i.expr = y.selectors; i.expr[":"] = i.expr.pseudos; i.unique = y.uniqueSort; i.text = y.getText; i.isXMLDoc = y.isXML; i.contains = y.contains; var di = i.expr.match.needsContext, gi = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, ef = /^.[^:#\[\.,]*$/; i.filter = function (n, t, r) { var u = t[0]; return r && (n = ":not(" + n + ")"), t.length === 1 && u.nodeType === 1 ? i.find.matchesSelector(u, n) ? [u] : [] : i.find.matches(n, i.grep(t, function (n) { return n.nodeType === 1 })) }; i.fn.extend({ find: function (n) { var t, u = this.length, r = [], f = this; if (typeof n != "string") return this.pushStack(i(n).filter(function () { for (t = 0; t < u; t++) if (i.contains(f[t], this)) return !0 })); for (t = 0; t < u; t++) i.find(n, f[t], r); return r = this.pushStack(u > 1 ? i.unique(r) : r), r.selector = this.selector ? this.selector + " " + n : n, r }, filter: function (n) { return this.pushStack(fi(this, n || [], !1)) }, not: function (n) { return this.pushStack(fi(this, n || [], !0)) }, is: function (n) { return !!fi(this, typeof n == "string" && di.test(n) ? i(n) : n || [], !1).length } }); nr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/; tr = i.fn.init = function (n, t) { var r, f; if (!n) return this; if (typeof n == "string") { if (r = n[0] === "<" && n[n.length - 1] === ">" && n.length >= 3 ? [null, n, null] : nr.exec(n), r && (r[1] || !t)) { if (r[1]) { if (t = t instanceof i ? t[0] : t, i.merge(this, i.parseHTML(r[1], t && t.nodeType ? t.ownerDocument || t : u, !0)), gi.test(r[1]) && i.isPlainObject(t)) for (r in t) i.isFunction(this[r]) ? this[r](t[r]) : this.attr(r, t[r]); return this } return f = u.getElementById(r[2]), f && f.parentNode && (this.length = 1, this[0] = f), this.context = u, this.selector = n, this } return !t || t.jquery ? (t || st).find(n) : this.constructor(t).find(n) } return n.nodeType ? (this.context = this[0] = n, this.length = 1, this) : i.isFunction(n) ? typeof st.ready != "undefined" ? st.ready(n) : n(i) : (n.selector !== undefined && (this.selector = n.selector, this.context = n.context), i.makeArray(n, this)) }; tr.prototype = i.fn; st = i(u); ir = /^(?:parents|prev(?:Until|All))/; rr = { children: !0, contents: !0, next: !0, prev: !0 }; i.extend({ dir: function (n, t, r) { for (var u = [], f = r !== undefined; (n = n[t]) && n.nodeType !== 9;) if (n.nodeType === 1) { if (f && i(n).is(r)) break; u.push(n) } return u }, sibling: function (n, t) { for (var i = []; n; n = n.nextSibling) n.nodeType === 1 && n !== t && i.push(n); return i } }); i.fn.extend({ has: function (n) { var t = i(n, this), r = t.length; return this.filter(function () { for (var n = 0; n < r; n++) if (i.contains(this, t[n])) return !0 }) }, closest: function (n, t) { for (var r, f = 0, o = this.length, u = [], e = di.test(n) || typeof n != "string" ? i(n, t || this.context) : 0; f < o; f++) for (r = this[f]; r && r !== t; r = r.parentNode) if (r.nodeType < 11 && (e ? e.index(r) > -1 : r.nodeType === 1 && i.find.matchesSelector(r, n))) { u.push(r); break } return this.pushStack(u.length > 1 ? i.unique(u) : u) }, index: function (n) { return n ? typeof n == "string" ? et.call(i(n), this[0]) : et.call(this, n.jquery ? n[0] : n) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1 }, add: function (n, t) { return this.pushStack(i.unique(i.merge(this.get(), i(n, t)))) }, addBack: function (n) { return this.add(n == null ? this.prevObject : this.prevObject.filter(n)) } }); i.each({ parent: function (n) { var t = n.parentNode; return t && t.nodeType !== 11 ? t : null }, parents: function (n) { return i.dir(n, "parentNode") }, parentsUntil: function (n, t, r) { return i.dir(n, "parentNode", r) }, next: function (n) { return ur(n, "nextSibling") }, prev: function (n) { return ur(n, "previousSibling") }, nextAll: function (n) { return i.dir(n, "nextSibling") }, prevAll: function (n) { return i.dir(n, "previousSibling") }, nextUntil: function (n, t, r) { return i.dir(n, "nextSibling", r) }, prevUntil: function (n, t, r) { return i.dir(n, "previousSibling", r) }, siblings: function (n) { return i.sibling((n.parentNode || {}).firstChild, n) }, children: function (n) { return i.sibling(n.firstChild) }, contents: function (n) { return n.contentDocument || i.merge([], n.childNodes) } }, function (n, t) { i.fn[n] = function (r, u) { var f = i.map(this, t, r); return n.slice(-5) !== "Until" && (u = r), u && typeof u == "string" && (f = i.filter(u, f)), this.length > 1 && (rr[n] || i.unique(f), ir.test(n) && f.reverse()), this.pushStack(f) } }); c = /\S+/g; ei = {}; i.Callbacks = function (n) { n = typeof n == "string" ? ei[n] || of(n) : i.extend({}, n); var u, h, o, c, f, e, t = [], r = !n.once && [], l = function (i) { for (u = n.memory && i, h = !0, e = c || 0, c = 0, f = t.length, o = !0; t && e < f; e++) if (t[e].apply(i[0], i[1]) === !1 && n.stopOnFalse) { u = !1; break } o = !1; t && (r ? r.length && l(r.shift()) : u ? t = [] : s.disable()) }, s = { add: function () { if (t) { var r = t.length; (function e(r) { i.each(r, function (r, u) { var f = i.type(u); f === "function" ? n.unique && s.has(u) || t.push(u) : u && u.length && f !== "string" && e(u) }) })(arguments); o ? f = t.length : u && (c = r, l(u)) } return this }, remove: function () { return t && i.each(arguments, function (n, r) { for (var u; (u = i.inArray(r, t, u)) > -1;) t.splice(u, 1), o && (u <= f && f--, u <= e && e--) }), this }, has: function (n) { return n ? i.inArray(n, t) > -1 : !!(t && t.length) }, empty: function () { return t = [], f = 0, this }, disable: function () { return t = r = u = undefined, this }, disabled: function () { return !t }, lock: function () { return r = undefined, u || s.disable(), this }, locked: function () { return !r }, fireWith: function (n, i) { return t && (!h || r) && (i = i || [], i = [n, i.slice ? i.slice() : i], o ? r.push(i) : l(i)), this }, fire: function () { return s.fireWith(this, arguments), this }, fired: function () { return !!h } }; return s }; i.extend({ Deferred: function (n) { var u = [["resolve", "done", i.Callbacks("once memory"), "resolved"], ["reject", "fail", i.Callbacks("once memory"), "rejected"], ["notify", "progress", i.Callbacks("memory")]], f = "pending", r = { state: function () { return f }, always: function () { return t.done(arguments).fail(arguments), this }, then: function () { var n = arguments; return i.Deferred(function (f) { i.each(u, function (u, e) { var o = i.isFunction(n[u]) && n[u]; t[e[1]](function () { var n = o && o.apply(this, arguments); n && i.isFunction(n.promise) ? n.promise().done(f.resolve).fail(f.reject).progress(f.notify) : f[e[0] + "With"](this === r ? f.promise() : this, o ? [n] : arguments) }) }); n = null }).promise() }, promise: function (n) { return n != null ? i.extend(n, r) : r } }, t = {}; return r.pipe = r.then, i.each(u, function (n, i) { var e = i[2], o = i[3]; r[i[1]] = e.add; o && e.add(function () { f = o }, u[n ^ 1][2].disable, u[2][2].lock); t[i[0]] = function () { return t[i[0] + "With"](this === t ? r : this, arguments), this }; t[i[0] + "With"] = e.fireWith }), r.promise(t), n && n.call(t, t), t }, when: function (n) { var t = 0, u = a.call(arguments), r = u.length, e = r !== 1 || n && i.isFunction(n.promise) ? r : 0, f = e === 1 ? n : i.Deferred(), h = function (n, t, i) { return function (r) { t[n] = this; i[n] = arguments.length > 1 ? a.call(arguments) : r; i === o ? f.notifyWith(t, i) : --e || f.resolveWith(t, i) } }, o, c, s; if (r > 1) for (o = new Array(r), c = new Array(r), s = new Array(r) ; t < r; t++) u[t] && i.isFunction(u[t].promise) ? u[t].promise().done(h(t, s, u)).fail(f.reject).progress(h(t, c, o)) : --e; return e || f.resolveWith(s, u), f.promise() } }); i.fn.ready = function (n) { return i.ready.promise().done(n), this }; i.extend({ isReady: !1, readyWait: 1, holdReady: function (n) { n ? i.readyWait++ : i.ready(!0) }, ready: function (n) { (n === !0 ? --i.readyWait : i.isReady) || (i.isReady = !0, n !== !0 && --i.readyWait > 0) || (ht.resolveWith(u, [i]), i.fn.triggerHandler && (i(u).triggerHandler("ready"), i(u).off("ready"))) } }); i.ready.promise = function (t) { return ht || (ht = i.Deferred(), u.readyState === "complete" ? setTimeout(i.ready) : (u.addEventListener("DOMContentLoaded", ct, !1), n.addEventListener("load", ct, !1))), ht.promise(t) }; i.ready.promise(); l = i.access = function (n, t, r, u, f, e, o) { var s = 0, c = n.length, h = r == null; if (i.type(r) === "object") { f = !0; for (s in r) i.access(n, t, s, r[s], !0, e, o) } else if (u !== undefined && (f = !0, i.isFunction(u) || (o = !0), h && (o ? (t.call(n, u), t = null) : (h = t, t = function (n, t, r) { return h.call(i(n), r) })), t)) for (; s < c; s++) t(n[s], r, o ? u : u.call(n[s], s, t(n[s], r))); return f ? n : h ? t.call(n) : c ? t(n[0], r) : e }; i.acceptData = function (n) { return n.nodeType === 1 || n.nodeType === 9 || !+n.nodeType }; p.uid = 1; p.accepts = i.acceptData; p.prototype = { key: function (n) { if (!p.accepts(n)) return 0; var r = {}, t = n[this.expando]; if (!t) { t = p.uid++; try { r[this.expando] = { value: t }; Object.defineProperties(n, r) } catch (u) { r[this.expando] = t; i.extend(n, r) } } return this.cache[t] || (this.cache[t] = {}), t }, set: function (n, t, r) { var f, e = this.key(n), u = this.cache[e]; if (typeof t == "string") u[t] = r; else if (i.isEmptyObject(u)) i.extend(this.cache[e], t); else for (f in t) u[f] = t[f]; return u }, get: function (n, t) { var i = this.cache[this.key(n)]; return t === undefined ? i : i[t] }, access: function (n, t, r) { var u; return t === undefined || t && typeof t == "string" && r === undefined ? (u = this.get(n, t), u !== undefined ? u : this.get(n, i.camelCase(t))) : (this.set(n, t, r), r !== undefined ? r : t) }, remove: function (n, t) { var u, r, f, o = this.key(n), e = this.cache[o]; if (t === undefined) this.cache[o] = {}; else for (i.isArray(t) ? r = t.concat(t.map(i.camelCase)) : (f = i.camelCase(t), t in e ? r = [t, f] : (r = f, r = r in e ? [r] : r.match(c) || [])), u = r.length; u--;) delete e[r[u]] }, hasData: function (n) { return !i.isEmptyObject(this.cache[n[this.expando]] || {}) }, discard: function (n) { n[this.expando] && delete this.cache[n[this.expando]] } }; var r = new p, e = new p, sf = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, hf = /([A-Z])/g; i.extend({ hasData: function (n) { return e.hasData(n) || r.hasData(n) }, data: function (n, t, i) { return e.access(n, t, i) }, removeData: function (n, t) { e.remove(n, t) }, _data: function (n, t, i) { return r.access(n, t, i) }, _removeData: function (n, t) { r.remove(n, t) } }); i.fn.extend({ data: function (n, t) { var o, f, s, u = this[0], h = u && u.attributes; if (n === undefined) { if (this.length && (s = e.get(u), u.nodeType === 1 && !r.get(u, "hasDataAttrs"))) { for (o = h.length; o--;) h[o] && (f = h[o].name, f.indexOf("data-") === 0 && (f = i.camelCase(f.slice(5)), fr(u, f, s[f]))); r.set(u, "hasDataAttrs", !0) } return s } return typeof n == "object" ? this.each(function () { e.set(this, n) }) : l(this, function (t) { var r, f = i.camelCase(n); if (u && t === undefined) return (r = e.get(u, n), r !== undefined) ? r : (r = e.get(u, f), r !== undefined) ? r : (r = fr(u, f, undefined), r !== undefined) ? r : void 0; this.each(function () { var i = e.get(this, f); e.set(this, f, t); n.indexOf("-") !== -1 && i !== undefined && e.set(this, n, t) }) }, null, t, arguments.length > 1, null, !0) }, removeData: function (n) { return this.each(function () { e.remove(this, n) }) } }); i.extend({ queue: function (n, t, u) { var f; if (n) return t = (t || "fx") + "queue", f = r.get(n, t), u && (!f || i.isArray(u) ? f = r.access(n, t, i.makeArray(u)) : f.push(u)), f || [] }, dequeue: function (n, t) { t = t || "fx"; var r = i.queue(n, t), e = r.length, u = r.shift(), f = i._queueHooks(n, t), o = function () { i.dequeue(n, t) }; u === "inprogress" && (u = r.shift(), e--); u && (t === "fx" && r.unshift("inprogress"), delete f.stop, u.call(n, o, f)); !e && f && f.empty.fire() }, _queueHooks: function (n, t) { var u = t + "queueHooks"; return r.get(n, u) || r.access(n, u, { empty: i.Callbacks("once memory").add(function () { r.remove(n, [t + "queue", u]) }) }) } }); i.fn.extend({ queue: function (n, t) { var r = 2; return (typeof n != "string" && (t = n, n = "fx", r--), arguments.length < r) ? i.queue(this[0], n) : t === undefined ? this : this.each(function () { var r = i.queue(this, n, t); i._queueHooks(this, n); n === "fx" && r[0] !== "inprogress" && i.dequeue(this, n) }) }, dequeue: function (n) { return this.each(function () { i.dequeue(this, n) }) }, clearQueue: function (n) { return this.queue(n || "fx", []) }, promise: function (n, t) { var u, e = 1, o = i.Deferred(), f = this, s = this.length, h = function () { --e || o.resolveWith(f, [f]) }; for (typeof n != "string" && (t = n, n = undefined), n = n || "fx"; s--;) u = r.get(f[s], n + "queueHooks"), u && u.empty && (e++, u.empty.add(h)); return h(), o.promise(t) } }); var lt = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, w = ["Top", "Right", "Bottom", "Left"], it = function (n, t) { return n = t || n, i.css(n, "display") === "none" || !i.contains(n.ownerDocument, n) }, er = /^(?:checkbox|radio)$/i; (function () { var i = u.createDocumentFragment(), n = i.appendChild(u.createElement("div")), t = u.createElement("input"); t.setAttribute("type", "radio"); t.setAttribute("checked", "checked"); t.setAttribute("name", "t"); n.appendChild(t); f.checkClone = n.cloneNode(!0).cloneNode(!0).lastChild.checked; n.innerHTML = "<textarea>x<\/textarea>"; f.noCloneChecked = !!n.cloneNode(!0).lastChild.defaultValue })(); d = typeof undefined; f.focusinBubbles = "onfocusin" in n; var cf = /^key/, lf = /^(?:mouse|pointer|contextmenu)|click/, or = /^(?:focusinfocus|focusoutblur)$/, sr = /^([^.]*)(?:\.(.+)|)$/; i.event = { global: {}, add: function (n, t, u, f, e) { var v, y, w, p, b, h, s, l, o, k, g, a = r.get(n); if (a) for (u.handler && (v = u, u = v.handler, e = v.selector), u.guid || (u.guid = i.guid++), (p = a.events) || (p = a.events = {}), (y = a.handle) || (y = a.handle = function (t) { return typeof i !== d && i.event.triggered !== t.type ? i.event.dispatch.apply(n, arguments) : undefined }), t = (t || "").match(c) || [""], b = t.length; b--;) (w = sr.exec(t[b]) || [], o = g = w[1], k = (w[2] || "").split(".").sort(), o) && (s = i.event.special[o] || {}, o = (e ? s.delegateType : s.bindType) || o, s = i.event.special[o] || {}, h = i.extend({ type: o, origType: g, data: f, handler: u, guid: u.guid, selector: e, needsContext: e && i.expr.match.needsContext.test(e), namespace: k.join(".") }, v), (l = p[o]) || (l = p[o] = [], l.delegateCount = 0, s.setup && s.setup.call(n, f, k, y) !== !1 || n.addEventListener && n.addEventListener(o, y, !1)), s.add && (s.add.call(n, h), h.handler.guid || (h.handler.guid = u.guid)), e ? l.splice(l.delegateCount++, 0, h) : l.push(h), i.event.global[o] = !0) }, remove: function (n, t, u, f, e) { var p, k, h, v, w, s, l, a, o, b, d, y = r.hasData(n) && r.get(n); if (y && (v = y.events)) { for (t = (t || "").match(c) || [""], w = t.length; w--;) { if (h = sr.exec(t[w]) || [], o = d = h[1], b = (h[2] || "").split(".").sort(), !o) { for (o in v) i.event.remove(n, o + t[w], u, f, !0); continue } for (l = i.event.special[o] || {}, o = (f ? l.delegateType : l.bindType) || o, a = v[o] || [], h = h[2] && new RegExp("(^|\\.)" + b.join("\\.(?:.*\\.|)") + "(\\.|$)"), k = p = a.length; p--;) s = a[p], (e || d === s.origType) && (!u || u.guid === s.guid) && (!h || h.test(s.namespace)) && (!f || f === s.selector || f === "**" && s.selector) && (a.splice(p, 1), s.selector && a.delegateCount--, l.remove && l.remove.call(n, s)); k && !a.length && (l.teardown && l.teardown.call(n, b, y.handle) !== !1 || i.removeEvent(n, o, y.handle), delete v[o]) } i.isEmptyObject(v) && (delete y.handle, r.remove(n, "events")) } }, trigger: function (t, f, e, o) { var w, s, c, b, a, v, l, p = [e || u], h = ri.call(t, "type") ? t.type : t, y = ri.call(t, "namespace") ? t.namespace.split(".") : []; if ((s = c = e = e || u, e.nodeType !== 3 && e.nodeType !== 8) && !or.test(h + i.event.triggered) && (h.indexOf(".") >= 0 && (y = h.split("."), h = y.shift(), y.sort()), a = h.indexOf(":") < 0 && "on" + h, t = t[i.expando] ? t : new i.Event(h, typeof t == "object" && t), t.isTrigger = o ? 2 : 3, t.namespace = y.join("."), t.namespace_re = t.namespace ? new RegExp("(^|\\.)" + y.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, t.result = undefined, t.target || (t.target = e), f = f == null ? [t] : i.makeArray(f, [t]), l = i.event.special[h] || {}, o || !l.trigger || l.trigger.apply(e, f) !== !1)) { if (!o && !l.noBubble && !i.isWindow(e)) { for (b = l.delegateType || h, or.test(b + h) || (s = s.parentNode) ; s; s = s.parentNode) p.push(s), c = s; c === (e.ownerDocument || u) && p.push(c.defaultView || c.parentWindow || n) } for (w = 0; (s = p[w++]) && !t.isPropagationStopped() ;) t.type = w > 1 ? b : l.bindType || h, v = (r.get(s, "events") || {})[t.type] && r.get(s, "handle"), v && v.apply(s, f), v = a && s[a], v && v.apply && i.acceptData(s) && (t.result = v.apply(s, f), t.result === !1 && t.preventDefault()); return t.type = h, o || t.isDefaultPrevented() || (!l._default || l._default.apply(p.pop(), f) === !1) && i.acceptData(e) && a && i.isFunction(e[h]) && !i.isWindow(e) && (c = e[a], c && (e[a] = null), i.event.triggered = h, e[h](), i.event.triggered = undefined, c && (e[a] = c)), t.result } }, dispatch: function (n) { n = i.event.fix(n); var o, s, e, u, t, h = [], c = a.call(arguments), l = (r.get(this, "events") || {})[n.type] || [], f = i.event.special[n.type] || {}; if (c[0] = n, n.delegateTarget = this, !f.preDispatch || f.preDispatch.call(this, n) !== !1) { for (h = i.event.handlers.call(this, n, l), o = 0; (u = h[o++]) && !n.isPropagationStopped() ;) for (n.currentTarget = u.elem, s = 0; (t = u.handlers[s++]) && !n.isImmediatePropagationStopped() ;) (!n.namespace_re || n.namespace_re.test(t.namespace)) && (n.handleObj = t, n.data = t.data, e = ((i.event.special[t.origType] || {}).handle || t.handler).apply(u.elem, c), e !== undefined && (n.result = e) === !1 && (n.preventDefault(), n.stopPropagation())); return f.postDispatch && f.postDispatch.call(this, n), n.result } }, handlers: function (n, t) { var e, u, f, o, h = [], s = t.delegateCount, r = n.target; if (s && r.nodeType && (!n.button || n.type !== "click")) for (; r !== this; r = r.parentNode || this) if (r.disabled !== !0 || n.type !== "click") { for (u = [], e = 0; e < s; e++) o = t[e], f = o.selector + " ", u[f] === undefined && (u[f] = o.needsContext ? i(f, this).index(r) >= 0 : i.find(f, this, null, [r]).length), u[f] && u.push(o); u.length && h.push({ elem: r, handlers: u }) } return s < t.length && h.push({ elem: this, handlers: t.slice(s) }), h }, 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 (n, t) { return n.which == null && (n.which = t.charCode != null ? t.charCode : t.keyCode), n } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function (n, t) { var e, i, r, f = t.button; return n.pageX == null && t.clientX != null && (e = n.target.ownerDocument || u, i = e.documentElement, r = e.body, n.pageX = t.clientX + (i && i.scrollLeft || r && r.scrollLeft || 0) - (i && i.clientLeft || r && r.clientLeft || 0), n.pageY = t.clientY + (i && i.scrollTop || r && r.scrollTop || 0) - (i && i.clientTop || r && r.clientTop || 0)), n.which || f === undefined || (n.which = f & 1 ? 1 : f & 2 ? 3 : f & 4 ? 2 : 0), n } }, fix: function (n) { if (n[i.expando]) return n; var f, e, o, r = n.type, s = n, t = this.fixHooks[r]; for (t || (this.fixHooks[r] = t = lf.test(r) ? this.mouseHooks : cf.test(r) ? this.keyHooks : {}), o = t.props ? this.props.concat(t.props) : this.props, n = new i.Event(s), f = o.length; f--;) e = o[f], n[e] = s[e]; return n.target || (n.target = u), n.target.nodeType === 3 && (n.target = n.target.parentNode), t.filter ? t.filter(n, s) : n }, special: { load: { noBubble: !0 }, focus: { trigger: function () { if (this !== hr() && this.focus) return this.focus(), !1 }, delegateType: "focusin" }, blur: { trigger: function () { if (this === hr() && this.blur) return this.blur(), !1 }, delegateType: "focusout" }, click: { trigger: function () { if (this.type === "checkbox" && this.click && i.nodeName(this, "input")) return this.click(), !1 }, _default: function (n) { return i.nodeName(n.target, "a") } }, beforeunload: { postDispatch: function (n) { n.result !== undefined && n.originalEvent && (n.originalEvent.returnValue = n.result) } } }, simulate: function (n, t, r, u) { var f = i.extend(new i.Event, r, { type: n, isSimulated: !0, originalEvent: {} }); u ? i.event.trigger(f, null, t) : i.event.dispatch.call(t, f); f.isDefaultPrevented() && r.preventDefault() } }; i.removeEvent = function (n, t, i) { n.removeEventListener && n.removeEventListener(t, i, !1) }; i.Event = function (n, t) { if (!(this instanceof i.Event)) return new i.Event(n, t); n && n.type ? (this.originalEvent = n, this.type = n.type, this.isDefaultPrevented = n.defaultPrevented || n.defaultPrevented === undefined && n.returnValue === !1 ? at : g) : this.type = n; t && i.extend(this, t); this.timeStamp = n && n.timeStamp || i.now(); this[i.expando] = !0 }; i.Event.prototype = { isDefaultPrevented: g, isPropagationStopped: g, isImmediatePropagationStopped: g, preventDefault: function () { var n = this.originalEvent; this.isDefaultPrevented = at; n && n.preventDefault && n.preventDefault() }, stopPropagation: function () { var n = this.originalEvent; this.isPropagationStopped = at; n && n.stopPropagation && n.stopPropagation() }, stopImmediatePropagation: function () { var n = this.originalEvent; this.isImmediatePropagationStopped = at; n && n.stopImmediatePropagation && n.stopImmediatePropagation(); this.stopPropagation() } }; i.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function (n, t) { i.event.special[n] = { delegateType: t, bindType: t, handle: function (n) { var u, f = this, r = n.relatedTarget, e = n.handleObj; return r && (r === f || i.contains(f, r)) || (n.type = e.origType, u = e.handler.apply(this, arguments), n.type = t), u } } }); f.focusinBubbles || i.each({ focus: "focusin", blur: "focusout" }, function (n, t) { var u = function (n) { i.event.simulate(t, n.target, i.event.fix(n), !0) }; i.event.special[t] = { setup: function () { var i = this.ownerDocument || this, f = r.access(i, t); f || i.addEventListener(n, u, !0); r.access(i, t, (f || 0) + 1) }, teardown: function () { var i = this.ownerDocument || this, f = r.access(i, t) - 1; f ? r.access(i, t, f) : (i.removeEventListener(n, u, !0), r.remove(i, t)) } } }); i.fn.extend({ on: function (n, t, r, u, f) { var e, o; if (typeof n == "object") { typeof t != "string" && (r = r || t, t = undefined); for (o in n) this.on(o, t, r, n[o], f); return this } if (r == null && u == null ? (u = t, r = t = undefined) : u == null && (typeof t == "string" ? (u = r, r = undefined) : (u = r, r = t, t = undefined)), u === !1) u = g; else if (!u) return this; return f === 1 && (e = u, u = function (n) { return i().off(n), e.apply(this, arguments) }, u.guid = e.guid || (e.guid = i.guid++)), this.each(function () { i.event.add(this, n, u, r, t) }) }, one: function (n, t, i, r) { return this.on(n, t, i, r, 1) }, off: function (n, t, r) { var u, f; if (n && n.preventDefault && n.handleObj) return u = n.handleObj, i(n.delegateTarget).off(u.namespace ? u.origType + "." + u.namespace : u.origType, u.selector, u.handler), this; if (typeof n == "object") { for (f in n) this.off(f, t, n[f]); return this } return (t === !1 || typeof t == "function") && (r = t, t = undefined), r === !1 && (r = g), this.each(function () { i.event.remove(this, n, r, t) }) }, trigger: function (n, t) { return this.each(function () { i.event.trigger(n, t, this) }) }, triggerHandler: function (n, t) { var r = this[0]; if (r) return i.event.trigger(n, t, r, !0) } }); var cr = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, lr = /<([\w:]+)/, af = /<|&#?\w+;/, vf = /<(?:script|style|link)/i, yf = /checked\s*(?:[^=]|=\s*.checked.)/i, ar = /^$|\/(?:java|ecma)script/i, pf = /^true\/(.*)/, wf = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, h = { 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, "", ""] }; h.optgroup = h.option; h.tbody = h.tfoot = h.colgroup = h.caption = h.thead; h.th = h.td; i.extend({ clone: function (n, t, r) { var u, c, s, e, h = n.cloneNode(!0), l = i.contains(n.ownerDocument, n); if (!f.noCloneChecked && (n.nodeType === 1 || n.nodeType === 11) && !i.isXMLDoc(n)) for (e = o(h), s = o(n), u = 0, c = s.length; u < c; u++) df(s[u], e[u]); if (t) if (r) for (s = s || o(n), e = e || o(h), u = 0, c = s.length; u < c; u++) yr(s[u], e[u]); else yr(n, h); return e = o(h, "script"), e.length > 0 && oi(e, !l && o(n, "script")), h }, buildFragment: function (n, t, r, u) { for (var f, e, y, l, p, a, s = t.createDocumentFragment(), v = [], c = 0, w = n.length; c < w; c++) if (f = n[c], f || f === 0) if (i.type(f) === "object") i.merge(v, f.nodeType ? [f] : f); else if (af.test(f)) { for (e = e || s.appendChild(t.createElement("div")), y = (lr.exec(f) || ["", ""])[1].toLowerCase(), l = h[y] || h._default, e.innerHTML = l[1] + f.replace(cr, "<$1><\/$2>") + l[2], a = l[0]; a--;) e = e.lastChild; i.merge(v, e.childNodes); e = s.firstChild; e.textContent = "" } else v.push(t.createTextNode(f)); for (s.textContent = "", c = 0; f = v[c++];) if ((!u || i.inArray(f, u) === -1) && (p = i.contains(f.ownerDocument, f), e = o(s.appendChild(f), "script"), p && oi(e), r)) for (a = 0; f = e[a++];) ar.test(f.type || "") && r.push(f); return s }, cleanData: function (n) { for (var f, t, o, u, h = i.event.special, s = 0; (t = n[s]) !== undefined; s++) { if (i.acceptData(t) && (u = t[r.expando], u && (f = r.cache[u]))) { if (f.events) for (o in f.events) h[o] ? i.event.remove(t, o) : i.removeEvent(t, o, f.handle); r.cache[u] && delete r.cache[u] } delete e.cache[t[e.expando]] } } }); i.fn.extend({ text: function (n) { return l(this, function (n) { return n === undefined ? i.text(this) : this.empty().each(function () { (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) && (this.textContent = n) }) }, null, n, arguments.length) }, append: function () { return this.domManip(arguments, function (n) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { var t = vr(this, n); t.appendChild(n) } }) }, prepend: function () { return this.domManip(arguments, function (n) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { var t = vr(this, n); t.insertBefore(n, t.firstChild) } }) }, before: function () { return this.domManip(arguments, function (n) { this.parentNode && this.parentNode.insertBefore(n, this) }) }, after: function () { return this.domManip(arguments, function (n) { this.parentNode && this.parentNode.insertBefore(n, this.nextSibling) }) }, remove: function (n, t) { for (var r, f = n ? i.filter(n, this) : this, u = 0; (r = f[u]) != null; u++) t || r.nodeType !== 1 || i.cleanData(o(r)), r.parentNode && (t && i.contains(r.ownerDocument, r) && oi(o(r, "script")), r.parentNode.removeChild(r)); return this }, empty: function () { for (var n, t = 0; (n = this[t]) != null; t++) n.nodeType === 1 && (i.cleanData(o(n, !1)), n.textContent = ""); return this }, clone: function (n, t) { return n = n == null ? !1 : n, t = t == null ? n : t, this.map(function () { return i.clone(this, n, t) }) }, html: function (n) { return l(this, function (n) { var t = this[0] || {}, r = 0, u = this.length; if (n === undefined && t.nodeType === 1) return t.innerHTML; if (typeof n == "string" && !vf.test(n) && !h[(lr.exec(n) || ["", ""])[1].toLowerCase()]) { n = n.replace(cr, "<$1><\/$2>"); try { for (; r < u; r++) t = this[r] || {}, t.nodeType === 1 && (i.cleanData(o(t, !1)), t.innerHTML = n); t = 0 } catch (f) { } } t && this.empty().append(n) }, null, n, arguments.length) }, replaceWith: function () { var n = arguments[0]; return this.domManip(arguments, function (t) { n = this.parentNode; i.cleanData(o(this)); n && n.replaceChild(t, this) }), n && (n.length || n.nodeType) ? this : this.remove() }, detach: function (n) { return this.remove(n, !0) }, domManip: function (n, t) { n = bi.apply([], n); var h, v, s, c, u, y, e = 0, l = this.length, w = this, b = l - 1, a = n[0], p = i.isFunction(a); if (p || l > 1 && typeof a == "string" && !f.checkClone && yf.test(a)) return this.each(function (i) { var r = w.eq(i); p && (n[0] = a.call(this, i, r.html())); r.domManip(n, t) }); if (l && (h = i.buildFragment(n, this[0].ownerDocument, !1, this), v = h.firstChild, h.childNodes.length === 1 && (h = v), v)) { for (s = i.map(o(h, "script"), bf), c = s.length; e < l; e++) u = h, e !== b && (u = i.clone(u, !0, !0), c && i.merge(s, o(u, "script"))), t.call(this[e], u, e); if (c) for (y = s[s.length - 1].ownerDocument, i.map(s, kf), e = 0; e < c; e++) u = s[e], ar.test(u.type || "") && !r.access(u, "globalEval") && i.contains(y, u) && (u.src ? i._evalUrl && i._evalUrl(u.src) : i.globalEval(u.textContent.replace(wf, ""))) } return this } }); i.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function (n, t) { i.fn[n] = function (n) { for (var u, f = [], e = i(n), o = e.length - 1, r = 0; r <= o; r++) u = r === o ? this : this.clone(!0), i(e[r])[t](u), ii.apply(f, u.get()); return this.pushStack(f) } }); si = {}; var wr = /^margin/, ci = new RegExp("^(" + lt + ")(?!px)[a-z%]+$", "i"), yt = function (n) { return n.ownerDocument.defaultView.getComputedStyle(n, null) }; (function () { function h() { t.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute"; t.innerHTML = ""; e.appendChild(r); var i = n.getComputedStyle(t, null); s = i.top !== "1%"; o = i.width === "4px"; e.removeChild(r) } var s, o, e = u.documentElement, r = u.createElement("div"), t = u.createElement("div"); t.style && (t.style.backgroundClip = "content-box", t.cloneNode(!0).style.backgroundClip = "", f.clearCloneStyle = t.style.backgroundClip === "content-box", r.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute", r.appendChild(t), n.getComputedStyle && i.extend(f, { pixelPosition: function () { return h(), s }, boxSizingReliable: function () { return o == null && h(), o }, reliableMarginRight: function () { var f, i = t.appendChild(u.createElement("div")); return i.style.cssText = t.style.cssText = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0", i.style.marginRight = i.style.width = "0", t.style.width = "1px", e.appendChild(r), f = !parseFloat(n.getComputedStyle(i, null).marginRight), e.removeChild(r), f } })) })(); i.swap = function (n, t, i, r) { var f, u, e = {}; for (u in t) e[u] = n.style[u], n.style[u] = t[u]; f = i.apply(n, r || []); for (u in t) n.style[u] = e[u]; return f }; var gf = /^(none|table(?!-c[ea]).+)/, ne = new RegExp("^(" + lt + ")(.*)$", "i"), te = new RegExp("^([+-])=(" + lt + ")", "i"), ie = { position: "absolute", visibility: "hidden", display: "block" }, kr = { letterSpacing: "0", fontWeight: "400" }, dr = ["Webkit", "O", "Moz", "ms"]; i.extend({ cssHooks: { opacity: { get: function (n, t) { if (t) { var i = rt(n, "opacity"); return i === "" ? "1" : i } } } }, cssNumber: { columnCount: !0, fillOpacity: !0, flexGrow: !0, flexShrink: !0, fontWeight: !0, lineHeight: !0, opacity: !0, order: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0 }, cssProps: { float: "cssFloat" }, style: function (n, t, r, u) { if (n && n.nodeType !== 3 && n.nodeType !== 8 && n.style) { var o, h, e, s = i.camelCase(t), c = n.style; if (t = i.cssProps[s] || (i.cssProps[s] = gr(c, s)), e = i.cssHooks[t] || i.cssHooks[s], r !== undefined) { if (h = typeof r, h === "string" && (o = te.exec(r)) && (r = (o[1] + 1) * o[2] + parseFloat(i.css(n, t)), h = "number"), r == null || r !== r) return; h !== "number" || i.cssNumber[s] || (r += "px"); f.clearCloneStyle || r !== "" || t.indexOf("background") !== 0 || (c[t] = "inherit"); e && "set" in e && (r = e.set(n, r, u)) === undefined || (c[t] = r) } else return e && "get" in e && (o = e.get(n, !1, u)) !== undefined ? o : c[t] } }, css: function (n, t, r, u) { var f, s, e, o = i.camelCase(t); return (t = i.cssProps[o] || (i.cssProps[o] = gr(n.style, o)), e = i.cssHooks[t] || i.cssHooks[o], e && "get" in e && (f = e.get(n, !0, r)), f === undefined && (f = rt(n, t, u)), f === "normal" && t in kr && (f = kr[t]), r === "" || r) ? (s = parseFloat(f), r === !0 || i.isNumeric(s) ? s || 0 : f) : f } }); i.each(["height", "width"], function (n, t) { i.cssHooks[t] = { get: function (n, r, u) { if (r) return gf.test(i.css(n, "display")) && n.offsetWidth === 0 ? i.swap(n, ie, function () { return iu(n, t, u) }) : iu(n, t, u) }, set: function (n, r, u) { var f = u && yt(n); return nu(n, r, u ? tu(n, t, u, i.css(n, "boxSizing", !1, f) === "border-box", f) : 0) } } }); i.cssHooks.marginRight = br(f.reliableMarginRight, function (n, t) { if (t) return i.swap(n, { display: "inline-block" }, rt, [n, "marginRight"]) }); i.each({ margin: "", padding: "", border: "Width" }, function (n, t) { i.cssHooks[n + t] = { expand: function (i) { for (var r = 0, f = {}, u = typeof i == "string" ? i.split(" ") : [i]; r < 4; r++) f[n + w[r] + t] = u[r] || u[r - 2] || u[0]; return f } }; wr.test(n) || (i.cssHooks[n + t].set = nu) }); i.fn.extend({ css: function (n, t) { return l(this, function (n, t, r) { var f, e, o = {}, u = 0; if (i.isArray(t)) { for (f = yt(n), e = t.length; u < e; u++) o[t[u]] = i.css(n, t[u], !1, f); return o } return r !== undefined ? i.style(n, t, r) : i.css(n, t) }, n, t, arguments.length > 1) }, show: function () { return ru(this, !0) }, hide: function () { return ru(this) }, toggle: function (n) { return typeof n == "boolean" ? n ? this.show() : this.hide() : this.each(function () { it(this) ? i(this).show() : i(this).hide() }) } }); i.Tween = s; s.prototype = { constructor: s, init: function (n, t, r, u, f, e) { this.elem = n; this.prop = r; this.easing = f || "swing"; this.options = t; this.start = this.now = this.cur(); this.end = u; this.unit = e || (i.cssNumber[r] ? "" : "px") }, cur: function () { var n = s.propHooks[this.prop]; return n && n.get ? n.get(this) : s.propHooks._default.get(this) }, run: function (n) { var t, r = s.propHooks[this.prop]; return this.pos = this.options.duration ? t = i.easing[this.easing](n, this.options.duration * n, 0, 1, this.options.duration) : t = n, this.now = (this.end - this.start) * t + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), r && r.set ? r.set(this) : s.propHooks._default.set(this), this } }; s.prototype.init.prototype = s.prototype; s.propHooks = { _default: { get: function (n) { var t; return n.elem[n.prop] != null && (!n.elem.style || n.elem.style[n.prop] == null) ? n.elem[n.prop] : (t = i.css(n.elem, n.prop, ""), !t || t === "auto" ? 0 : t) }, set: function (n) { i.fx.step[n.prop] ? i.fx.step[n.prop](n) : n.elem.style && (n.elem.style[i.cssProps[n.prop]] != null || i.cssHooks[n.prop]) ? i.style(n.elem, n.prop, n.now + n.unit) : n.elem[n.prop] = n.now } } }; s.propHooks.scrollTop = s.propHooks.scrollLeft = { set: function (n) { n.elem.nodeType && n.elem.parentNode && (n.elem[n.prop] = n.now) } }; i.easing = { linear: function (n) { return n }, swing: function (n) { return .5 - Math.cos(n * Math.PI) / 2 } }; i.fx = s.prototype.init; i.fx.step = {}; var nt, pt, re = /^(?:toggle|show|hide)$/, uu = new RegExp("^(?:([+-])=|)(" + lt + ")([a-z%]*)$", "i"), ue = /queueHooks$/, wt = [fe], ut = { "*": [function (n, t) { var f = this.createTween(n, t), s = f.cur(), u = uu.exec(t), e = u && u[3] || (i.cssNumber[n] ? "" : "px"), r = (i.cssNumber[n] || e !== "px" && +s) && uu.exec(i.css(f.elem, n)), o = 1, h = 20; if (r && r[3] !== e) { e = e || r[3]; u = u || []; r = +s || 1; do o = o || ".5", r = r / o, i.style(f.elem, n, r + e); while (o !== (o = f.cur() / s) && o !== 1 && --h) } return u && (r = f.start = +r || +s || 0, f.unit = e, f.end = u[1] ? r + (u[1] + 1) * u[2] : +u[2]), f }] }; i.Animation = i.extend(ou, { tweener: function (n, t) { i.isFunction(n) ? (t = n, n = ["*"]) : n = n.split(" "); for (var r, u = 0, f = n.length; u < f; u++) r = n[u], ut[r] = ut[r] || [], ut[r].unshift(t) }, prefilter: function (n, t) { t ? wt.unshift(n) : wt.push(n) } }); i.speed = function (n, t, r) { var u = n && typeof n == "object" ? i.extend({}, n) : { complete: r || !r && t || i.isFunction(n) && n, duration: n, easing: r && t || t && !i.isFunction(t) && t }; return u.duration = i.fx.off ? 0 : typeof u.duration == "number" ? u.duration : u.duration in i.fx.speeds ? i.fx.speeds[u.duration] : i.fx.speeds._default, (u.queue == null || u.queue === !0) && (u.queue = "fx"), u.old = u.complete, u.complete = function () { i.isFunction(u.old) && u.old.call(this); u.queue && i.dequeue(this, u.queue) }, u }; i.fn.extend({ fadeTo: function (n, t, i, r) { return this.filter(it).css("opacity", 0).show().end().animate({ opacity: t }, n, i, r) }, animate: function (n, t, u, f) { var s = i.isEmptyObject(n), o = i.speed(t, u, f), e = function () { var t = ou(this, i.extend({}, n), o); (s || r.get(this, "finish")) && t.stop(!0) }; return e.finish = e, s || o.queue === !1 ? this.each(e) : this.queue(o.queue, e) }, stop: function (n, t, u) { var f = function (n) { var t = n.stop; delete n.stop; t(u) }; return typeof n != "string" && (u = t, t = n, n = undefined), t && n !== !1 && this.queue(n || "fx", []), this.each(function () { var s = !0, t = n != null && n + "queueHooks", o = i.timers, e = r.get(this); if (t) e[t] && e[t].stop && f(e[t]); else for (t in e) e[t] && e[t].stop && ue.test(t) && f(e[t]); for (t = o.length; t--;) o[t].elem === this && (n == null || o[t].queue === n) && (o[t].anim.stop(u), s = !1, o.splice(t, 1)); (s || !u) && i.dequeue(this, n) }) }, finish: function (n) { return n !== !1 && (n = n || "fx"), this.each(function () { var t, e = r.get(this), u = e[n + "queue"], o = e[n + "queueHooks"], f = i.timers, s = u ? u.length : 0; for (e.finish = !0, i.queue(this, n, []), o && o.stop && o.stop.call(this, !0), t = f.length; t--;) f[t].elem === this && f[t].queue === n && (f[t].anim.stop(!0), f.splice(t, 1)); for (t = 0; t < s; t++) u[t] && u[t].finish && u[t].finish.call(this); delete e.finish }) } }); i.each(["toggle", "show", "hide"], function (n, t) { var r = i.fn[t]; i.fn[t] = function (n, i, u) { return n == null || typeof n == "boolean" ? r.apply(this, arguments) : this.animate(bt(t, !0), n, i, u) } }); i.each({ slideDown: bt("show"), slideUp: bt("hide"), slideToggle: bt("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function (n, t) { i.fn[n] = function (n, i, r) { return this.animate(t, n, i, r) } }); i.timers = []; i.fx.tick = function () { var r, n = 0, t = i.timers; for (nt = i.now() ; n < t.length; n++) r = t[n], r() || t[n] !== r || t.splice(n--, 1); t.length || i.fx.stop(); nt = undefined }; i.fx.timer = function (n) { i.timers.push(n); n() ? i.fx.start() : i.timers.pop() }; i.fx.interval = 13; i.fx.start = function () { pt || (pt = setInterval(i.fx.tick, i.fx.interval)) }; i.fx.stop = function () { clearInterval(pt); pt = null }; i.fx.speeds = { slow: 600, fast: 200, _default: 400 }; i.fn.delay = function (n, t) { return n = i.fx ? i.fx.speeds[n] || n : n, t = t || "fx", this.queue(t, function (t, i) { var r = setTimeout(t, n); i.stop = function () { clearTimeout(r) } }) }, function () { var n = u.createElement("input"), t = u.createElement("select"), i = t.appendChild(u.createElement("option")); n.type = "checkbox"; f.checkOn = n.value !== ""; f.optSelected = i.selected; t.disabled = !0; f.optDisabled = !i.disabled; n = u.createElement("input"); n.value = "t"; n.type = "radio"; f.radioValue = n.value === "t" }(); tt = i.expr.attrHandle; i.fn.extend({ attr: function (n, t) { return l(this, i.attr, n, t, arguments.length > 1) }, removeAttr: function (n) { return this.each(function () { i.removeAttr(this, n) }) } }); i.extend({ attr: function (n, t, r) { var u, f, e = n.nodeType; if (n && e !== 3 && e !== 8 && e !== 2) { if (typeof n.getAttribute === d) return i.prop(n, t, r); if (e === 1 && i.isXMLDoc(n) || (t = t.toLowerCase(), u = i.attrHooks[t] || (i.expr.match.bool.test(t) ? su : oe)), r !== undefined) if (r === null) i.removeAttr(n, t); else return u && "set" in u && (f = u.set(n, r, t)) !== undefined ? f : (n.setAttribute(t, r + ""), r); else return u && "get" in u && (f = u.get(n, t)) !== null ? f : (f = i.find.attr(n, t), f == null ? undefined : f) } }, removeAttr: function (n, t) { var r, u, e = 0, f = t && t.match(c); if (f && n.nodeType === 1) while (r = f[e++]) u = i.propFix[r] || r, i.expr.match.bool.test(r) && (n[u] = !1), n.removeAttribute(r) }, attrHooks: { type: { set: function (n, t) { if (!f.radioValue && t === "radio" && i.nodeName(n, "input")) { var r = n.value; return n.setAttribute("type", t), r && (n.value = r), t } } } } }); su = { set: function (n, t, r) { return t === !1 ? i.removeAttr(n, r) : n.setAttribute(r, r), r } }; i.each(i.expr.match.bool.source.match(/\w+/g), function (n, t) { var r = tt[t] || i.find.attr; tt[t] = function (n, t, i) { var u, f; return i || (f = tt[t], tt[t] = u, u = r(n, t, i) != null ? t.toLowerCase() : null, tt[t] = f), u } }); hu = /^(?:input|select|textarea|button)$/i; i.fn.extend({ prop: function (n, t) { return l(this, i.prop, n, t, arguments.length > 1) }, removeProp: function (n) { return this.each(function () { delete this[i.propFix[n] || n] }) } }); i.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function (n, t, r) { var f, u, o, e = n.nodeType; if (n && e !== 3 && e !== 8 && e !== 2) return o = e !== 1 || !i.isXMLDoc(n), o && (t = i.propFix[t] || t, u = i.propHooks[t]), r !== undefined ? u && "set" in u && (f = u.set(n, r, t)) !== undefined ? f : n[t] = r : u && "get" in u && (f = u.get(n, t)) !== null ? f : n[t] }, propHooks: { tabIndex: { get: function (n) { return n.hasAttribute("tabindex") || hu.test(n.nodeName) || n.href ? n.tabIndex : -1 } } } }); f.optSelected || (i.propHooks.selected = { get: function (n) { var t = n.parentNode; return t && t.parentNode && t.parentNode.selectedIndex, null } }); i.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () { i.propFix[this.toLowerCase()] = this }); kt = /[\t\r\n\f]/g; i.fn.extend({ addClass: function (n) { var o, t, r, u, s, f, h = typeof n == "string" && n, e = 0, l = this.length; if (i.isFunction(n)) return this.each(function (t) { i(this).addClass(n.call(this, t, this.className)) }); if (h) for (o = (n || "").match(c) || []; e < l; e++) if (t = this[e], r = t.nodeType === 1 && (t.className ? (" " + t.className + " ").replace(kt, " ") : " "), r) { for (s = 0; u = o[s++];) r.indexOf(" " + u + " ") < 0 && (r += u + " "); f = i.trim(r); t.className !== f && (t.className = f) } return this }, removeClass: function (n) { var o, t, r, u, s, f, h = arguments.length === 0 || typeof n == "string" && n, e = 0, l = this.length; if (i.isFunction(n)) return this.each(function (t) { i(this).removeClass(n.call(this, t, this.className)) }); if (h) for (o = (n || "").match(c) || []; e < l; e++) if (t = this[e], r = t.nodeType === 1 && (t.className ? (" " + t.className + " ").replace(kt, " ") : ""), r) { for (s = 0; u = o[s++];) while (r.indexOf(" " + u + " ") >= 0) r = r.replace(" " + u + " ", " "); f = n ? i.trim(r) : ""; t.className !== f && (t.className = f) } return this }, toggleClass: function (n, t) { var u = typeof n; return typeof t == "boolean" && u === "string" ? t ? this.addClass(n) : this.removeClass(n) : i.isFunction(n) ? this.each(function (r) { i(this).toggleClass(n.call(this, r, this.className, t), t) }) : this.each(function () { if (u === "string") for (var t, e = 0, f = i(this), o = n.match(c) || []; t = o[e++];) f.hasClass(t) ? f.removeClass(t) : f.addClass(t); else (u === d || u === "boolean") && (this.className && r.set(this, "__className__", this.className), this.className = this.className || n === !1 ? "" : r.get(this, "__className__") || "") }) }, hasClass: function (n) { for (var i = " " + n + " ", t = 0, r = this.length; t < r; t++) if (this[t].nodeType === 1 && (" " + this[t].className + " ").replace(kt, " ").indexOf(i) >= 0) return !0; return !1 } }); cu = /\r/g; i.fn.extend({ val: function (n) { var t, r, f, u = this[0]; return arguments.length ? (f = i.isFunction(n), this.each(function (r) { var u; this.nodeType === 1 && (u = f ? n.call(this, r, i(this).val()) : n, u == null ? u = "" : typeof u == "number" ? u += "" : i.isArray(u) && (u = i.map(u, function (n) { return n == null ? "" : n + "" })), t = i.valHooks[this.type] || i.valHooks[this.nodeName.toLowerCase()], t && "set" in t && t.set(this, u, "value") !== undefined || (this.value = u)) })) : u ? (t = i.valHooks[u.type] || i.valHooks[u.nodeName.toLowerCase()], t && "get" in t && (r = t.get(u, "value")) !== undefined) ? r : (r = u.value, typeof r == "string" ? r.replace(cu, "") : r == null ? "" : r) : void 0 } }); i.extend({ valHooks: { option: { get: function (n) { var t = i.find.attr(n, "value"); return t != null ? t : i.trim(i.text(n)) } }, select: { get: function (n) { for (var o, t, s = n.options, r = n.selectedIndex, u = n.type === "select-one" || r < 0, h = u ? null : [], c = u ? r + 1 : s.length, e = r < 0 ? c : u ? r : 0; e < c; e++) if (t = s[e], (t.selected || e === r) && (f.optDisabled ? !t.disabled : t.getAttribute("disabled") === null) && (!t.parentNode.disabled || !i.nodeName(t.parentNode, "optgroup"))) { if (o = i(t).val(), u) return o; h.push(o) } return h }, set: function (n, t) { for (var u, r, f = n.options, e = i.makeArray(t), o = f.length; o--;) r = f[o], (r.selected = i.inArray(r.value, e) >= 0) && (u = !0); return u || (n.selectedIndex = -1), e } } } }); i.each(["radio", "checkbox"], function () { i.valHooks[this] = { set: function (n, t) { if (i.isArray(t)) return n.checked = i.inArray(i(n).val(), t) >= 0 } }; f.checkOn || (i.valHooks[this].get = function (n) { return n.getAttribute("value") === null ? "on" : n.value }) }); i.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 (n, t) { i.fn[t] = function (n, i) { return arguments.length > 0 ? this.on(t, null, n, i) : this.trigger(t) } }); i.fn.extend({ hover: function (n, t) { return this.mouseenter(n).mouseleave(t || n) }, bind: function (n, t, i) { return this.on(n, null, t, i) }, unbind: function (n, t) { return this.off(n, null, t) }, delegate: function (n, t, i, r) { return this.on(t, n, i, r) }, undelegate: function (n, t, i) { return arguments.length === 1 ? this.off(n, "**") : this.off(t, n || "**", i) } }); dt = i.now(); gt = /\?/; i.parseJSON = function (n) { return JSON.parse(n + "") }; i.parseXML = function (n) { var t, r; if (!n || typeof n != "string") return null; try { r = new DOMParser; t = r.parseFromString(n, "text/xml") } catch (u) { t = undefined } return (!t || t.getElementsByTagName("parsererror").length) && i.error("Invalid XML: " + n), t }; var b, v, se = /#.*$/, lu = /([?&])_=[^&]*/, he = /^(.*?):[ \t]*([^\r\n]*)$/mg, ce = /^(?:GET|HEAD)$/, le = /^\/\//, au = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, vu = {}, li = {}, yu = "*/".concat("*"); try { v = location.href } catch (ge) { v = u.createElement("a"); v.href = ""; v = v.href } b = au.exec(v.toLowerCase()) || []; i.extend({ active: 0, lastModified: {}, etag: {}, ajaxSettings: { url: v, type: "GET", isLocal: /^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(b[1]), global: !0, processData: !0, async: !0, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: { "*": yu, 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": i.parseJSON, "text xml": i.parseXML }, flatOptions: { url: !0, context: !0 } }, ajaxSetup: function (n, t) { return t ? ai(ai(n, i.ajaxSettings), t) : ai(i.ajaxSettings, n) }, ajaxPrefilter: pu(vu), ajaxTransport: pu(li), ajax: function (n, t) { function w(n, t, h, c) { var v, it, b, y, w, l = t; e !== 2 && (e = 2, d && clearTimeout(d), s = undefined, k = c || "", u.readyState = n > 0 ? 4 : 0, v = n >= 200 && n < 300 || n === 304, h && (y = ae(r, u, h)), y = ve(r, y, u, v), v ? (r.ifModified && (w = u.getResponseHeader("Last-Modified"), w && (i.lastModified[f] = w), w = u.getResponseHeader("etag"), w && (i.etag[f] = w)), n === 204 || r.type === "HEAD" ? l = "nocontent" : n === 304 ? l = "notmodified" : (l = y.state, it = y.data, b = y.error, v = !b)) : (b = l, (n || !l) && (l = "error", n < 0 && (n = 0))), u.status = n, u.statusText = (t || l) + "", v ? nt.resolveWith(o, [it, l, u]) : nt.rejectWith(o, [u, l, b]), u.statusCode(p), p = undefined, a && g.trigger(v ? "ajaxSuccess" : "ajaxError", [u, r, v ? it : b]), tt.fireWith(o, [u, l]), a && (g.trigger("ajaxComplete", [u, r]), --i.active || i.event.trigger("ajaxStop"))) } typeof n == "object" && (t = n, n = undefined); t = t || {}; var s, f, k, y, d, h, a, l, r = i.ajaxSetup({}, t), o = r.context || r, g = r.context && (o.nodeType || o.jquery) ? i(o) : i.event, nt = i.Deferred(), tt = i.Callbacks("once memory"), p = r.statusCode || {}, it = {}, rt = {}, e = 0, ut = "canceled", u = { readyState: 0, getResponseHeader: function (n) { var t; if (e === 2) { if (!y) for (y = {}; t = he.exec(k) ;) y[t[1].toLowerCase()] = t[2]; t = y[n.toLowerCase()] } return t == null ? null : t }, getAllResponseHeaders: function () { return e === 2 ? k : null }, setRequestHeader: function (n, t) { var i = n.toLowerCase(); return e || (n = rt[i] = rt[i] || n, it[n] = t), this }, overrideMimeType: function (n) { return e || (r.mimeType = n), this }, statusCode: function (n) { var t; if (n) if (e < 2) for (t in n) p[t] = [p[t], n[t]]; else u.always(n[u.status]); return this }, abort: function (n) { var t = n || ut; return s && s.abort(t), w(0, t), this } }; if (nt.promise(u).complete = tt.add, u.success = u.done, u.error = u.fail, r.url = ((n || r.url || v) + "").replace(se, "").replace(le, b[1] + "//"), r.type = t.method || t.type || r.method || r.type, r.dataTypes = i.trim(r.dataType || "*").toLowerCase().match(c) || [""], r.crossDomain == null && (h = au.exec(r.url.toLowerCase()), r.crossDomain = !!(h && (h[1] !== b[1] || h[2] !== b[2] || (h[3] || (h[1] === "http:" ? "80" : "443")) !== (b[3] || (b[1] === "http:" ? "80" : "443"))))), r.data && r.processData && typeof r.data != "string" && (r.data = i.param(r.data, r.traditional)), wu(vu, r, t, u), e === 2) return u; a = r.global; a && i.active++ == 0 && i.event.trigger("ajaxStart"); r.type = r.type.toUpperCase(); r.hasContent = !ce.test(r.type); f = r.url; r.hasContent || (r.data && (f = r.url += (gt.test(f) ? "&" : "?") + r.data, delete r.data), r.cache === !1 && (r.url = lu.test(f) ? f.replace(lu, "$1_=" + dt++) : f + (gt.test(f) ? "&" : "?") + "_=" + dt++)); r.ifModified && (i.lastModified[f] && u.setRequestHeader("If-Modified-Since", i.lastModified[f]), i.etag[f] && u.setRequestHeader("If-None-Match", i.etag[f])); (r.data && r.hasContent && r.contentType !== !1 || t.contentType) && u.setRequestHeader("Content-Type", r.contentType); u.setRequestHeader("Accept", r.dataTypes[0] && r.accepts[r.dataTypes[0]] ? r.accepts[r.dataTypes[0]] + (r.dataTypes[0] !== "*" ? ", " + yu + "; q=0.01" : "") : r.accepts["*"]); for (l in r.headers) u.setRequestHeader(l, r.headers[l]); if (r.beforeSend && (r.beforeSend.call(o, u, r) === !1 || e === 2)) return u.abort(); ut = "abort"; for (l in { success: 1, error: 1, complete: 1 }) u[l](r[l]); if (s = wu(li, r, t, u), s) { u.readyState = 1; a && g.trigger("ajaxSend", [u, r]); r.async && r.timeout > 0 && (d = setTimeout(function () { u.abort("timeout") }, r.timeout)); try { e = 1; s.send(it, w) } catch (ft) { if (e < 2) w(-1, ft); else throw ft; } } else w(-1, "No Transport"); return u }, getJSON: function (n, t, r) { return i.get(n, t, r, "json") }, getScript: function (n, t) { return i.get(n, undefined, t, "script") } }); i.each(["get", "post"], function (n, t) { i[t] = function (n, r, u, f) { return i.isFunction(r) && (f = f || u, u = r, r = undefined), i.ajax({ url: n, type: t, dataType: f, data: r, success: u }) } }); i.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (n, t) { i.fn[t] = function (n) { return this.on(t, n) } }); i._evalUrl = function (n) { return i.ajax({ url: n, type: "GET", dataType: "script", async: !1, global: !1, throws: !0 }) }; i.fn.extend({ wrapAll: function (n) { var t; return i.isFunction(n) ? this.each(function (t) { i(this).wrapAll(n.call(this, t)) }) : (this[0] && (t = i(n, this[0].ownerDocument).eq(0).clone(!0), this[0].parentNode && t.insertBefore(this[0]), t.map(function () { for (var n = this; n.firstElementChild;) n = n.firstElementChild; return n }).append(this)), this) }, wrapInner: function (n) { return i.isFunction(n) ? this.each(function (t) { i(this).wrapInner(n.call(this, t)) }) : this.each(function () { var t = i(this), r = t.contents(); r.length ? r.wrapAll(n) : t.append(n) }) }, wrap: function (n) { var t = i.isFunction(n); return this.each(function (r) { i(this).wrapAll(t ? n.call(this, r) : n) }) }, unwrap: function () { return this.parent().each(function () { i.nodeName(this, "body") || i(this).replaceWith(this.childNodes) }).end() } }); i.expr.filters.hidden = function (n) { return n.offsetWidth <= 0 && n.offsetHeight <= 0 }; i.expr.filters.visible = function (n) { return !i.expr.filters.hidden(n) }; var ye = /%20/g, pe = /\[\]$/, bu = /\r?\n/g, we = /^(?:submit|button|image|reset|file)$/i, be = /^(?:input|select|textarea|keygen)/i; i.param = function (n, t) { var r, u = [], f = function (n, t) { t = i.isFunction(t) ? t() : t == null ? "" : t; u[u.length] = encodeURIComponent(n) + "=" + encodeURIComponent(t) }; if (t === undefined && (t = i.ajaxSettings && i.ajaxSettings.traditional), i.isArray(n) || n.jquery && !i.isPlainObject(n)) i.each(n, function () { f(this.name, this.value) }); else for (r in n) vi(r, n[r], t, f); return u.join("&").replace(ye, "+") }; i.fn.extend({ serialize: function () { return i.param(this.serializeArray()) }, serializeArray: function () { return this.map(function () { var n = i.prop(this, "elements"); return n ? i.makeArray(n) : this }).filter(function () { var n = this.type; return this.name && !i(this).is(":disabled") && be.test(this.nodeName) && !we.test(n) && (this.checked || !er.test(n)) }).map(function (n, t) { var r = i(this).val(); return r == null ? null : i.isArray(r) ? i.map(r, function (n) { return { name: t.name, value: n.replace(bu, "\r\n") } }) : { name: t.name, value: r.replace(bu, "\r\n") } }).get() } }); i.ajaxSettings.xhr = function () { try { return new XMLHttpRequest } catch (n) { } }; var ke = 0, ni = {}, de = { 0: 200, 1223: 204 }, ft = i.ajaxSettings.xhr(); if (n.ActiveXObject) i(n).on("unload", function () { for (var n in ni) ni[n]() }); return f.cors = !!ft && "withCredentials" in ft, f.ajax = ft = !!ft, i.ajaxTransport(function (n) { var t; if (f.cors || ft && !n.crossDomain) return { send: function (i, r) { var f, u = n.xhr(), e = ++ke; if (u.open(n.type, n.url, n.async, n.username, n.password), n.xhrFields) for (f in n.xhrFields) u[f] = n.xhrFields[f]; n.mimeType && u.overrideMimeType && u.overrideMimeType(n.mimeType); n.crossDomain || i["X-Requested-With"] || (i["X-Requested-With"] = "XMLHttpRequest"); for (f in i) u.setRequestHeader(f, i[f]); t = function (n) { return function () { t && (delete ni[e], t = u.onload = u.onerror = null, n === "abort" ? u.abort() : n === "error" ? r(u.status, u.statusText) : r(de[u.status] || u.status, u.statusText, typeof u.responseText == "string" ? { text: u.responseText } : undefined, u.getAllResponseHeaders())) } }; u.onload = t(); u.onerror = t("error"); t = ni[e] = t("abort"); try { u.send(n.hasContent && n.data || null) } catch (o) { if (t) throw o; } }, abort: function () { t && t() } } }), i.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function (n) { return i.globalEval(n), n } } }), i.ajaxPrefilter("script", function (n) { n.cache === undefined && (n.cache = !1); n.crossDomain && (n.type = "GET") }), i.ajaxTransport("script", function (n) { if (n.crossDomain) { var r, t; return { send: function (f, e) { r = i("<script>").prop({ async: !0, charset: n.scriptCharset, src: n.url }).on("load error", t = function (n) { r.remove(); t = null; n && e(n.type === "error" ? 404 : 200, n.type) }); u.head.appendChild(r[0]) }, abort: function () { t && t() } } } }), yi = [], ti = /(=)\?(?=&|$)|\?\?/, i.ajaxSetup({ jsonp: "callback", jsonpCallback: function () { var n = yi.pop() || i.expando + "_" + dt++; return this[n] = !0, n } }), i.ajaxPrefilter("json jsonp", function (t, r, u) { var f, o, e, s = t.jsonp !== !1 && (ti.test(t.url) ? "url" : typeof t.data == "string" && !(t.contentType || "").indexOf("application/x-www-form-urlencoded") && ti.test(t.data) && "data"); if (s || t.dataTypes[0] === "jsonp") return f = t.jsonpCallback = i.isFunction(t.jsonpCallback) ? t.jsonpCallback() : t.jsonpCallback, s ? t[s] = t[s].replace(ti, "$1" + f) : t.jsonp !== !1 && (t.url += (gt.test(t.url) ? "&" : "?") + t.jsonp + "=" + f), t.converters["script json"] = function () { return e || i.error(f + " was not called"), e[0] }, t.dataTypes[0] = "json", o = n[f], n[f] = function () { e = arguments }, u.always(function () { n[f] = o; t[f] && (t.jsonpCallback = r.jsonpCallback, yi.push(f)); e && i.isFunction(o) && o(e[0]); e = o = undefined }), "script" }), i.parseHTML = function (n, t, r) { if (!n || typeof n != "string") return null; typeof t == "boolean" && (r = t, t = !1); t = t || u; var f = gi.exec(n), e = !r && []; return f ? [t.createElement(f[1])] : (f = i.buildFragment([n], t, e), e && e.length && i(e).remove(), i.merge([], f.childNodes)) }, pi = i.fn.load, i.fn.load = function (n, t, r) { if (typeof n != "string" && pi) return pi.apply(this, arguments); var u, o, s, f = this, e = n.indexOf(" "); return e >= 0 && (u = i.trim(n.slice(e)), n = n.slice(0, e)), i.isFunction(t) ? (r = t, t = undefined) : t && typeof t == "object" && (o = "POST"), f.length > 0 && i.ajax({ url: n, type: o, dataType: "html", data: t }).done(function (n) { s = arguments; f.html(u ? i("<div>").append(i.parseHTML(n)).find(u) : n) }).complete(r && function (n, t) { f.each(r, s || [n.responseText, t, n]) }), this }, i.expr.filters.animated = function (n) { return i.grep(i.timers, function (t) { return n === t.elem }).length }, wi = n.document.documentElement, i.offset = { setOffset: function (n, t, r) { var e, o, s, h, u, c, v, l = i.css(n, "position"), a = i(n), f = {}; l === "static" && (n.style.position = "relative"); u = a.offset(); s = i.css(n, "top"); c = i.css(n, "left"); v = (l === "absolute" || l === "fixed") && (s + c).indexOf("auto") > -1; v ? (e = a.position(), h = e.top, o = e.left) : (h = parseFloat(s) || 0, o = parseFloat(c) || 0); i.isFunction(t) && (t = t.call(n, r, u)); t.top != null && (f.top = t.top - u.top + h); t.left != null && (f.left = t.left - u.left + o); "using" in t ? t.using.call(n, f) : a.css(f) } }, i.fn.extend({ offset: function (n) { if (arguments.length) return n === undefined ? this : this.each(function (t) { i.offset.setOffset(this, n, t) }); var r, f, t = this[0], u = { top: 0, left: 0 }, e = t && t.ownerDocument; if (e) return (r = e.documentElement, !i.contains(r, t)) ? u : (typeof t.getBoundingClientRect !== d && (u = t.getBoundingClientRect()), f = ku(e), { top: u.top + f.pageYOffset - r.clientTop, left: u.left + f.pageXOffset - r.clientLeft }) }, position: function () { if (this[0]) { var n, r, u = this[0], t = { top: 0, left: 0 }; return i.css(u, "position") === "fixed" ? r = u.getBoundingClientRect() : (n = this.offsetParent(), r = this.offset(), i.nodeName(n[0], "html") || (t = n.offset()), t.top += i.css(n[0], "borderTopWidth", !0), t.left += i.css(n[0], "borderLeftWidth", !0)), { top: r.top - t.top - i.css(u, "marginTop", !0), left: r.left - t.left - i.css(u, "marginLeft", !0) } } }, offsetParent: function () { return this.map(function () { for (var n = this.offsetParent || wi; n && !i.nodeName(n, "html") && i.css(n, "position") === "static";) n = n.offsetParent; return n || wi }) } }), i.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function (t, r) { var u = "pageYOffset" === r; i.fn[t] = function (i) { return l(this, function (t, i, f) { var e = ku(t); if (f === undefined) return e ? e[r] : t[i]; e ? e.scrollTo(u ? n.pageXOffset : f, u ? f : n.pageYOffset) : t[i] = f }, t, i, arguments.length, null) } }), i.each(["top", "left"], function (n, t) { i.cssHooks[t] = br(f.pixelPosition, function (n, r) { if (r) return r = rt(n, t), ci.test(r) ? i(n).position()[t] + "px" : r }) }), i.each({ Height: "height", Width: "width" }, function (n, t) { i.each({ padding: "inner" + n, content: t, "": "outer" + n }, function (r, u) { i.fn[u] = function (u, f) { var e = arguments.length && (r || typeof u != "boolean"), o = r || (u === !0 || f === !0 ? "margin" : "border"); return l(this, function (t, r, u) { var f; return i.isWindow(t) ? t.document.documentElement["client" + n] : t.nodeType === 9 ? (f = t.documentElement, Math.max(t.body["scroll" + n], f["scroll" + n], t.body["offset" + n], f["offset" + n], f["client" + n])) : u === undefined ? i.css(t, r, o) : i.style(t, r, u, o) }, t, e ? u : undefined, e, null) } }) }), i.fn.size = function () { return this.length }, i.fn.andSelf = i.fn.addBack, typeof define == "function" && define.amd && define("jquery", [], function () { return i }), du = n.jQuery, gu = n.$, i.noConflict = function (t) { return n.$ === i && (n.$ = gu), t && n.jQuery === i && (n.jQuery = du), i }, typeof t === d && (n.jQuery = n.$ = i), i });
/*
//# sourceMappingURL=jquery.min.js.map
*/;!function(t){"use strict";function n(t){if(void 0===Function.prototype.name){var n=/function\s([^(]{1,})\(/,i=n.exec(t.toString());return i&&i.length>1?i[1].trim():""}return void 0===t.prototype?t.constructor.name:t.prototype.constructor.name}function i(t){return"true"===t||"false"!==t&&(isNaN(1*t)?t:parseFloat(t))}function e(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}var o="6.3.1",r={version:o,_plugins:{},_uuids:[],rtl:function(){return"rtl"===t("html").attr("dir")},plugin:function(t,i){var o=i||n(t),r=e(o);this._plugins[r]=this[o]=t},registerPlugin:function(t,i){var o=i?e(i):n(t.constructor).toLowerCase();t.uuid=this.GetYoDigits(6,o),t.$element.attr("data-"+o)||t.$element.attr("data-"+o,t.uuid),t.$element.data("zfPlugin")||t.$element.data("zfPlugin",t),t.$element.trigger("init.zf."+o),this._uuids.push(t.uuid)},unregisterPlugin:function(t){var i=e(n(t.$element.data("zfPlugin").constructor));this._uuids.splice(this._uuids.indexOf(t.uuid),1),t.$element.removeAttr("data-"+i).removeData("zfPlugin").trigger("destroyed.zf."+i);for(var o in t)t[o]=null},reInit:function(n){var i=n instanceof t;try{if(i)n.each(function(){t(this).data("zfPlugin")._init()});else{var o=typeof n,r=this,a={object:function(n){n.forEach(function(n){n=e(n),t("[data-"+n+"]").foundation("_init")})},string:function(){n=e(n),t("[data-"+n+"]").foundation("_init")},undefined:function(){this.object(Object.keys(r._plugins))}};a[o](n)}}catch(t){console.error(t)}finally{return n}},GetYoDigits:function(t,n){return t=t||6,Math.round(Math.pow(36,t+1)-Math.random()*Math.pow(36,t)).toString(36).slice(1)+(n?"-"+n:"")},reflow:function(n,e){"undefined"==typeof e?e=Object.keys(this._plugins):"string"==typeof e&&(e=[e]);var o=this;t.each(e,function(e,r){var a=o._plugins[r],u=t(n).find("[data-"+r+"]").addBack("[data-"+r+"]");u.each(function(){var n=t(this),e={};if(n.data("zfPlugin"))return void console.warn("Tried to initialize "+r+" on an element that already has a Foundation plugin.");if(n.attr("data-options")){n.attr("data-options").split(";").forEach(function(t,n){var o=t.split(":").map(function(t){return t.trim()});o[0]&&(e[o[0]]=i(o[1]))})}try{n.data("zfPlugin",new a(t(this),e))}catch(t){console.error(t)}finally{return}})})},getFnName:n,transitionend:function(t){var n,i={transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend"},e=document.createElement("div");for(var o in i)"undefined"!=typeof e.style[o]&&(n=i[o]);return n?n:(n=setTimeout(function(){t.triggerHandler("transitionend",[t])},1),"transitionend")}};r.util={throttle:function(t,n){var i=null;return function(){var e=this,o=arguments;null===i&&(i=setTimeout(function(){t.apply(e,o),i=null},n))}}};var a=function(i){var e=typeof i,o=t("meta.foundation-mq"),a=t(".no-js");if(o.length||t('<meta class="foundation-mq">').appendTo(document.head),a.length&&a.removeClass("no-js"),"undefined"===e)r.MediaQuery._init(),r.reflow(this);else{if("string"!==e)throw new TypeError("We're sorry, "+e+" is not a valid parameter. You must use a string representing the method you wish to invoke.");var u=Array.prototype.slice.call(arguments,1),s=this.data("zfPlugin");if(void 0===s||void 0===s[i])throw new ReferenceError("We're sorry, '"+i+"' is not an available method for "+(s?n(s):"this element")+".");1===this.length?s[i].apply(s,u):this.each(function(n,e){s[i].apply(t(e).data("zfPlugin"),u)})}return this};window.Foundation=r,t.fn.foundation=a,function(){Date.now&&window.Date.now||(window.Date.now=Date.now=function(){return(new Date).getTime()});for(var t=["webkit","moz"],n=0;n<t.length&&!window.requestAnimationFrame;++n){var i=t[n];window.requestAnimationFrame=window[i+"RequestAnimationFrame"],window.cancelAnimationFrame=window[i+"CancelAnimationFrame"]||window[i+"CancelRequestAnimationFrame"]}if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){var e=0;window.requestAnimationFrame=function(t){var n=Date.now(),i=Math.max(e+16,n);return setTimeout(function(){t(e=i)},i-n)},window.cancelAnimationFrame=clearTimeout}window.performance&&window.performance.now||(window.performance={start:Date.now(),now:function(){return Date.now()-this.start}})}(),Function.prototype.bind||(Function.prototype.bind=function(t){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var n=Array.prototype.slice.call(arguments,1),i=this,e=function(){},o=function(){return i.apply(this instanceof e?this:t,n.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(e.prototype=this.prototype),o.prototype=new e,o})}(jQuery);;"use strict";function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function t(t,e){for(var n=0;n<e.length;n++){var a=e[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(t,a.key,a)}}return function(e,n,a){return n&&t(e.prototype,n),a&&t(e,a),e}}();!function(t){var e=function(){function e(n,a){_classCallCheck(this,e),this.$element=n,this.options=t.extend({},e.defaults,this.$element.data(),a),this._init(),Foundation.registerPlugin(this,"Accordion"),Foundation.Keyboard.register("Accordion",{ENTER:"toggle",SPACE:"toggle",ARROW_DOWN:"next",ARROW_UP:"previous"})}return _createClass(e,[{key:"_init",value:function(){this.$element.attr("role","tablist"),this.$tabs=this.$element.children("[data-accordion-item]"),this.$tabs.each(function(e,n){var a=t(n),i=a.children("[data-tab-content]"),o=i[0].id||Foundation.GetYoDigits(6,"accordion"),r=n.id||o+"-label";a.find("a:first").attr({"aria-controls":o,role:"tab",id:r,"aria-expanded":!1,"aria-selected":!1}),i.attr({role:"tabpanel","aria-labelledby":r,"aria-hidden":!0,id:o})});var e=this.$element.find(".is-active").children("[data-tab-content]");e.length&&this.down(e,!0),this._events()}},{key:"_events",value:function(){var e=this;this.$tabs.each(function(){var n=t(this),a=n.children("[data-tab-content]");a.length&&n.children("a").off("click.zf.accordion keydown.zf.accordion").on("click.zf.accordion",function(t){t.preventDefault(),e.toggle(a)}).on("keydown.zf.accordion",function(t){Foundation.Keyboard.handleKey(t,"Accordion",{toggle:function(){e.toggle(a)},next:function(){var t=n.next().find("a").focus();e.options.multiExpand||t.trigger("click.zf.accordion")},previous:function(){var t=n.prev().find("a").focus();e.options.multiExpand||t.trigger("click.zf.accordion")},handled:function(){t.preventDefault(),t.stopPropagation()}})})})}},{key:"toggle",value:function(t){t.parent().hasClass("is-active")?this.up(t):this.down(t)}},{key:"down",value:function(e,n){var a=this;if(e.attr("aria-hidden",!1).parent("[data-tab-content]").addBack().parent().addClass("is-active"),!this.options.multiExpand&&!n){var i=this.$element.children(".is-active").children("[data-tab-content]");i.length&&this.up(i.not(e))}e.slideDown(this.options.slideSpeed,function(){a.$element.trigger("down.zf.accordion",[e])}),t("#"+e.attr("aria-labelledby")).attr({"aria-expanded":!0,"aria-selected":!0})}},{key:"up",value:function(e){var n=e.parent().siblings(),a=this;(this.options.allowAllClosed||n.hasClass("is-active"))&&e.parent().hasClass("is-active")&&(e.slideUp(a.options.slideSpeed,function(){a.$element.trigger("up.zf.accordion",[e])}),e.attr("aria-hidden",!0).parent().removeClass("is-active"),t("#"+e.attr("aria-labelledby")).attr({"aria-expanded":!1,"aria-selected":!1}))}},{key:"destroy",value:function(){this.$element.find("[data-tab-content]").stop(!0).slideUp(0).css("display",""),this.$element.find("a").off(".zf.accordion"),Foundation.unregisterPlugin(this)}}]),e}();e.defaults={slideSpeed:250,multiExpand:!1,allowAllClosed:!1},Foundation.plugin(e,"Accordion")}(jQuery);;"use strict";!function(e){function t(e){var t={};return"string"!=typeof e?t:(e=e.trim().slice(1,-1))?t=e.split("&").reduce(function(e,t){var n=t.replace(/\+/g," ").split("="),r=n[0],i=n[1];return r=decodeURIComponent(r),i=void 0===i?null:decodeURIComponent(i),e.hasOwnProperty(r)?Array.isArray(e[r])?e[r].push(i):e[r]=[e[r],i]:e[r]=i,e},{}):t}var n={queries:[],current:"",_init:function(){var n,r=this,i=e(".foundation-mq").css("font-family");n=t(i);for(var a in n)n.hasOwnProperty(a)&&r.queries.push({name:a,value:"only screen and (min-width: "+n[a]+")"});this.current=this._getCurrentSize(),this._watcher()},atLeast:function(e){var t=this.get(e);return!!t&&window.matchMedia(t).matches},is:function(e){return e=e.trim().split(" "),e.length>1&&"only"===e[1]?e[0]===this._getCurrentSize():this.atLeast(e[0])},get:function(e){for(var t in this.queries)if(this.queries.hasOwnProperty(t)){var n=this.queries[t];if(e===n.name)return n.value}return null},_getCurrentSize:function(){for(var e,t=0;t<this.queries.length;t++){var n=this.queries[t];window.matchMedia(n.value).matches&&(e=n)}return"object"==typeof e?e.name:e},_watcher:function(){var t=this;e(window).on("resize.zf.mediaquery",function(){var n=t._getCurrentSize(),r=t.current;n!==r&&(t.current=n,e(window).trigger("changed.zf.mediaquery",[n,r]))})}};Foundation.MediaQuery=n,window.matchMedia||(window.matchMedia=function(){var e=window.styleMedia||window.media;if(!e){var t=document.createElement("style"),n=document.getElementsByTagName("script")[0],r=null;t.type="text/css",t.id="matchmediajs-test",n&&n.parentNode&&n.parentNode.insertBefore(t,n),r="getComputedStyle"in window&&window.getComputedStyle(t,null)||t.currentStyle,e={matchMedium:function(e){var n="@media "+e+"{ #matchmediajs-test { width: 1px; } }";return t.styleSheet?t.styleSheet.cssText=n:t.textContent=n,"1px"===r.width}}}return function(t){return{matches:e.matchMedium(t||"all"),media:t||"all"}}}()),Foundation.MediaQuery=n}(jQuery);;"use strict";!function(e){function n(e){var n={};for(var t in e)n[e[t]]=e[t];return n}var t={9:"TAB",13:"ENTER",27:"ESCAPE",32:"SPACE",37:"ARROW_LEFT",38:"ARROW_UP",39:"ARROW_RIGHT",40:"ARROW_DOWN"},o={},r={keys:n(t),parseKey:function(e){var n=t[e.which||e.keyCode]||String.fromCharCode(e.which).toUpperCase();return n=n.replace(/\W+/,""),e.shiftKey&&(n="SHIFT_"+n),e.ctrlKey&&(n="CTRL_"+n),e.altKey&&(n="ALT_"+n),n=n.replace(/_$/,"")},handleKey:function(n,t,r){var a,i,d,f=o[t],u=this.parseKey(n);if(!f)return console.warn("Component not defined!");if(a="undefined"==typeof f.ltr?f:Foundation.rtl()?e.extend({},f.ltr,f.rtl):e.extend({},f.rtl,f.ltr),i=a[u],d=r[i],d&&"function"==typeof d){var l=d.apply();(r.handled||"function"==typeof r.handled)&&r.handled(l)}else(r.unhandled||"function"==typeof r.unhandled)&&r.unhandled()},findFocusable:function(n){return!!n&&n.find("a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]").filter(function(){return!(!e(this).is(":visible")||e(this).attr("tabindex")<0)})},register:function(e,n){o[e]=n},trapFocus:function(e){var n=Foundation.Keyboard.findFocusable(e),t=n.eq(0),o=n.eq(-1);e.on("keydown.zf.trapfocus",function(e){e.target===o[0]&&"TAB"===Foundation.Keyboard.parseKey(e)?(e.preventDefault(),t.focus()):e.target===t[0]&&"SHIFT_TAB"===Foundation.Keyboard.parseKey(e)&&(e.preventDefault(),o.focus())})},releaseFocus:function(e){e.off("keydown.zf.trapfocus")}};Foundation.Keyboard=r}(jQuery);;"use strict";!function(n){function i(n,i,e){function t(s){r||(r=s),o=s-r,e.apply(i),o<n?a=window.requestAnimationFrame(t,i):(window.cancelAnimationFrame(a),i.trigger("finished.zf.animate",[i]).triggerHandler("finished.zf.animate",[i]))}var a,o,r=null;return 0===n?(e.apply(i),void i.trigger("finished.zf.animate",[i]).triggerHandler("finished.zf.animate",[i])):void(a=window.requestAnimationFrame(t))}function e(i,e,o,r){function s(){i||e.hide(),u(),r&&r.apply(e)}function u(){e[0].style.transitionDuration=0,e.removeClass(d+" "+f+" "+o)}if(e=n(e).eq(0),e.length){var d=i?t[0]:t[1],f=i?a[0]:a[1];u(),e.addClass(o).css("transition","none"),requestAnimationFrame(function(){e.addClass(d),i&&e.show()}),requestAnimationFrame(function(){e[0].offsetWidth,e.css("transition","").addClass(f)}),e.one(Foundation.transitionend(e),s)}}var t=["mui-enter","mui-leave"],a=["mui-enter-active","mui-leave-active"],o={animateIn:function(n,i,t){e(!0,n,i,t)},animateOut:function(n,i,t){e(!1,n,i,t)}};Foundation.Move=i,Foundation.Motion=o}(jQuery);;/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
	getItem: function (sKey) {
		if (!sKey) { return null; }
		return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
	},
	setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
		if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
		var sExpires = "";
		if (vEnd) {
			switch (vEnd.constructor) {
				case Number:
					sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
					break;
				case String:
					sExpires = "; expires=" + vEnd;
					break;
				case Date:
					sExpires = "; expires=" + vEnd.toUTCString();
					break;
			}
		}
		bSecure = true;
		document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "") + "; SameSite=Lax";
		return true;
	},
	removeItem: function (sKey, sPath, sDomain) {
		if (!this.hasItem(sKey)) { return false; }
		document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + "; secure; SameSite=Lax";
		return true;
	},
	hasItem: function (sKey) {
		if (!sKey) { return false; }
		return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
	},
	keys: function () {
		var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
		for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
		return aKeys;
	}
};;!function(e,t){"object"==typeof exports&&exports?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.Mustache={})}(this,function(e){function t(e){return"function"==typeof e}function n(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function r(e,t){return g.call(e,t)}function i(e){return!r(w,e)}function s(e){return String(e).replace(/[&<>"'\/]/g,function(e){return d[e]})}function o(t,r){function s(){if(U&&!m)for(;d.length;)delete w[d.pop()];else d=[];U=!1,m=!1}function o(e){if("string"==typeof e&&(e=e.split(k,2)),!f(e)||2!==e.length)throw new Error("Invalid tags: "+e);h=new RegExp(n(e[0])+"\\s*"),l=new RegExp("\\s*"+n(e[1])),p=new RegExp("\\s*"+n("}"+e[1]))}if(!t)return[];var h,l,p,g=[],w=[],d=[],U=!1,m=!1;o(r||e.tags);for(var E,T,j,C,A,R,S=new u(t);!S.eos();){if(E=S.pos,j=S.scanUntil(h))for(var O=0,$=j.length;$>O;++O)C=j.charAt(O),i(C)?d.push(w.length):m=!0,w.push(["text",C,E,E+1]),E+=1,"\n"===C&&s();if(!S.scan(h))break;if(U=!0,T=S.scan(x)||"name",S.scan(v),"="===T?(j=S.scanUntil(y),S.scan(y),S.scanUntil(l)):"{"===T?(j=S.scanUntil(p),S.scan(b),S.scanUntil(l),T="&"):j=S.scanUntil(l),!S.scan(l))throw new Error("Unclosed tag at "+S.pos);if(A=[T,j,E,S.pos],w.push(A),"#"===T||"^"===T)g.push(A);else if("/"===T){if(R=g.pop(),!R)throw new Error('Unopened section "'+j+'" at '+E);if(R[1]!==j)throw new Error('Unclosed section "'+R[1]+'" at '+E)}else"name"===T||"{"===T||"&"===T?m=!0:"="===T&&o(j)}if(R=g.pop())throw new Error('Unclosed section "'+R[1]+'" at '+S.pos);return c(a(w))}function a(e){for(var t,n,r=[],i=0,s=e.length;s>i;++i)t=e[i],t&&("text"===t[0]&&n&&"text"===n[0]?(n[1]+=t[1],n[3]=t[3]):(r.push(t),n=t));return r}function c(e){for(var t,n,r=[],i=r,s=[],o=0,a=e.length;a>o;++o)switch(t=e[o],t[0]){case"#":case"^":i.push(t),s.push(t),i=t[4]=[];break;case"/":n=s.pop(),n[5]=t[2],i=s.length>0?s[s.length-1][4]:r;break;default:i.push(t)}return r}function u(e){this.string=e,this.tail=e,this.pos=0}function h(e,t){this.view=null==e?{}:e,this.cache={".":this.view},this.parent=t}function l(){this.cache={}}var p=Object.prototype.toString,f=Array.isArray||function(e){return"[object Array]"===p.call(e)},g=RegExp.prototype.test,w=/\S/,d={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},v=/\s*/,k=/\s+/,y=/\s*=/,b=/\s*\}/,x=/#|\^|\/|>|\{|&|=|!/;u.prototype.eos=function(){return""===this.tail},u.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n},u.prototype.scanUntil=function(e){var t,n=this.tail.search(e);switch(n){case-1:t=this.tail,this.tail="";break;case 0:t="";break;default:t=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=t.length,t},h.prototype.push=function(e){return new h(e,this)},h.prototype.lookup=function(e){var n,r=this.cache;if(e in r)n=r[e];else{for(var i,s,o=this;o;){if(e.indexOf(".")>0)for(n=o.view,i=e.split("."),s=0;null!=n&&s<i.length;)n=n[i[s++]];else n=o.view[e];if(null!=n)break;o=o.parent}r[e]=n}return t(n)&&(n=n.call(this.view)),n},l.prototype.clearCache=function(){this.cache={}},l.prototype.parse=function(e,t){var n=this.cache,r=n[e];return null==r&&(r=n[e]=o(e,t)),r},l.prototype.render=function(e,t,n){var r=this.parse(e),i=t instanceof h?t:new h(t);return this.renderTokens(r,i,n,e)},l.prototype.renderTokens=function(n,r,i,s){function o(e){return h.render(e,r,i)}for(var a,c,u="",h=this,l=0,p=n.length;p>l;++l)switch(a=n[l],a[0]){case"#":if(c=r.lookup(a[1]),!c)continue;if(f(c))for(var g=0,w=c.length;w>g;++g)u+=this.renderTokens(a[4],r.push(c[g]),i,s);else if("object"==typeof c||"string"==typeof c)u+=this.renderTokens(a[4],r.push(c),i,s);else if(t(c)){if("string"!=typeof s)throw new Error("Cannot use higher-order sections without the original template");c=c.call(r.view,s.slice(a[3],a[5]),o),null!=c&&(u+=c)}else u+=this.renderTokens(a[4],r,i,s);break;case"^":c=r.lookup(a[1]),(!c||f(c)&&0===c.length)&&(u+=this.renderTokens(a[4],r,i,s));break;case">":if(!i)continue;c=t(i)?i(a[1]):i[a[1]],null!=c&&(u+=this.renderTokens(this.parse(c),r,i,c));break;case"&":c=r.lookup(a[1]),null!=c&&(u+=c);break;case"name":c=r.lookup(a[1]),null!=c&&(u+=e.escape(c));break;case"text":u+=a[1]}return u},e.name="mustache.js",e.version="0.8.1",e.tags=["{{","}}"];var U=new l;e.clearCache=function(){return U.clearCache()},e.parse=function(e,t){return U.parse(e,t)},e.render=function(e,t,n){return U.render(e,t,n)},e.to_html=function(n,r,i,s){var o=e.render(n,r,i);return t(s)?(s(o),void 0):o},e.escape=s,e.Scanner=u,e.Context=h,e.Writer=l});;/*
 * jQuery RefineSlide plugin v0.4.1
 * http://github.com/alexdunphy/refineslide
 * Requires: jQuery v1.8+
 * MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

 ;(function ($, window, document) {
    'use strict';

	// Baked-in settings for extension
	var defaults = {
        maxWidth              : 800,      // Max slider width - should be set to image width
        transition            : 'fade',  // String (default 'cubeV'): Transition type ('custom', random', 'cubeH', 'cubeV', 'fade', 'sliceH', 'sliceV', 'slideH', 'slideV', 'scale', 'blockScale', 'kaleidoscope', 'fan', 'blindH', 'blindV')
        customTransitions     : [],
        fallback3d            : 'fade', // String (default 'sliceV'): Fallback for browsers that support transitions, but not 3d transforms (only used if primary transition makes use of 3d-transforms)
        perspective           : 1000,     // Perspective (used for 3d transforms)
        useThumbs             : false,     // Bool (default true): Navigation type thumbnails
        useArrows             : true,    // Bool (default false): Navigation type previous and next arrows
        thumbMargin           : 3,        // Int (default 3): Percentage width of thumb margin
        autoPlay              : false,    // Int (default false): Auto-cycle slider
        delay                 : 4000,     // Int (default 5000) Time between slides in ms
        transitionDuration    : 400,      // Int (default 800): Transition length in ms
        startSlide            : 0,        // Int (default 0): First slide
        keyNav                : true,     // Bool (default true): Use left/right arrow keys to switch slide
        captionWidth          : 50,       // Int (default 50): Percentage of slide taken by caption
        arrowTemplate         : '<div class="rs-arrows"><a href="#" class="rs-prev"></a><a href="#" class="rs-next"></a></div>', // String: The markup used for arrow controls (if arrows are used). Must use classes '.rs-next' & '.rs-prev'
        onInit                : function () {}, // Func: User-defined, fires with slider initialisation
        onChange              : function () {}, // Func: User-defined, fires with transition start
        afterChange           : function () {}  // Func: User-defined, fires after transition end
	};

	// RS (RefineSlide) object constructor
	function RS(elem, settings) {
		this.$slider            = $(elem).addClass('rs-slider');      // Elem: Slider element
		this.settings           = $.extend({}, defaults, settings);    // Obj: Merged user settings/defaults
		this.$slides            = this.$slider.find('> li');           // Elem Arr: Slide elements
		this.totalSlides        = this.$slides.length;                 // Int: Number of slides
		this.cssTransitions     = testBrowser.cssTransitions();        // Bool: Test for CSS transition support
		this.cssTransforms3d    = testBrowser.cssTransforms3d();       // Bool: Test for 3D transform support
		this.currentPlace       = this.settings.startSlide;         // Int: Index of current slide (starts at 0)
		this.$currentSlide      = this.$slides.eq(this.currentPlace);  // Elem: Starting slide
		this.inProgress         = false;                               // Bool: Prevents overlapping transitions
		this.$sliderWrap        = this.$slider.wrap('<div class="rs-wrap" />').parent();      // Elem: Slider wrapper div
		this.$sliderBG          = this.$slider.wrap('<div class="rs-slide-bg" />').parent();  // Elem: Slider background (useful for styling & essential for cube transitions)
		this.settings.slider = this;  // Make slider object accessible to client call code with 'this.slider' (there's probably a better way to do this)

		this.init();
	}

	RS.prototype = {
        cycling: null,
        $slideImages: null,

        init: function () {
            // User-defined function to fire on slider initialisation
            this.settings.onInit();

            // Setup captions
            this.captions();

            if(this.settings.transition === 'custom') {
                this.nextAnimIndex = -1; // Set animation index for custom animation
            }

            if (this.settings.useArrows) {
                this.setArrows(); // Setup arrow navigation
            }

            if (this.settings.keyNav) {
                this.setKeys(); // Setup keyboard navigation
            }

            for (var i = 0; i < this.totalSlides; i++) { // Add slide identifying classes
                this.$slides.eq(i).addClass('rs-slide-' + i);
            }

            if (this.settings.autoPlay) {
                this.setAutoPlay();

                // Listen for slider mouseover
                this.$slider.on({
                    mouseenter: $.proxy(function () {
                        if (this.cycling !== null) {
                            clearTimeout(this.cycling);
                        }
                    }, this),
                    mouseleave: $.proxy(this.setAutoPlay, this) // Resume slideshow
                });
            }

            // Get the first image in each slide <li>
            this.$slideImages = this.$slides.find('img:eq(0)').addClass('rs-slide-image');

            this.setup();
        }

        ,setup: function () {
            this.$sliderWrap.css('width', this.settings.maxWidth);

            if (this.settings.useThumbs) {
                this.setThumbs();
            }

            // Display first slide
            this.$currentSlide.css({'opacity' : 1, 'z-index' : 2});
        }

        ,setArrows:function () {
            var that = this;

            // Append user-defined arrow template (elems) to '.rs-wrap' elem
            this.$sliderWrap.append(this.settings.arrowTemplate);

            // Fire next() method when clicked
            $('.rs-next', this.$sliderWrap).on('click', function (e) {
                e.preventDefault();
                that.next();
            });

            // Fire prev() method when clicked
            $('.rs-prev', this.$sliderWrap).on('click', function (e) {
                e.preventDefault();
                that.prev();
            });
        }

        ,next: function () {
            if (this.settings.transition === 'custom') {
                this.nextAnimIndex++;
            }

            // If on final slide, loop back to first slide
            if (this.currentPlace === this.totalSlides - 1) {
                this.transition(0, true); // Call transition
            } else {
                this.transition(this.currentPlace + 1, true); // Call transition
            }
        }

        ,prev: function () {
            if (this.settings.transition === 'custom') {
                this.nextAnimIndex--;
            }

            // If on first slide, loop round to final slide
            if (this.currentPlace == 0) {
                this.transition(this.totalSlides - 1, false); // Call transition
            } else {
                this.transition(this.currentPlace - 1, false); // Call transition
            }
        }

        ,setKeys: function () {
            var that = this;

            // Bind keyboard left/right arrows to next/prev methods
            $(document).on('keydown', function (e) {
                if (e.keyCode === 39) { // Right arrow key
                    that.next();
                } else if (e.keyCode === 37) { // Left arrow key
                    that.prev();
                }
            });
        }

        ,setAutoPlay: function () {
            var that = this;

            // Set timeout to object property so it can be accessed/cleared externally
            this.cycling = setTimeout(function () {
                that.next();
            }, this.settings.delay);
        }

        ,setThumbs: function () {
            var that = this,
                // Set percentage width (minus user-defined margin) to span width of slider
                width = (100 - ((this.totalSlides - 1) * this.settings.thumbMargin)) / this.totalSlides + '%';

            //<Wrapper to contain thumbnails
            this.$thumbWrap = $('<div class="rs-thumb-wrap" />').appendTo(this.$sliderWrap);

            // Loop to apply thumbnail widths/margins to <a> wraps, appending an image clone to each
            for (var i = 0; i < this.totalSlides; i++) {
                var $thumb = $('<a />')
                    .css({
                        width : width,
                        marginLeft : this.settings.thumbMargin + '%'
                    })
                    .attr('href', '#')
                    .data('rs-num', i);

                this.$slideImages.eq(i).clone()
                    .removeAttr('style')
                    .appendTo(this.$thumbWrap)
                    .wrap($thumb);
            }

            this.$thumbWrapLinks = this.$thumbWrap.find('a');

            // Safety margin to stop IE7 wrapping the thumbnails (no visual effect in other browsers)
            this.$thumbWrap.children().last().css('margin-right', -10);

            // Add active class to starting slide's respective thumb
            this.$thumbWrapLinks.eq(this.settings.startSlide).addClass('active');

            // Listen for click events on thumnails
            this.$thumbWrap.on('click', 'a', function (e) {
                e.preventDefault();

                that.transition(parseInt($(this).data('rs-num'))); // Call transition using identifier from thumb class
            });
        }

        ,captions: function() {
            var that = this,
                $captions = this.$slides.find('.rs-caption');

            // User-defined caption width
            $captions.css({
                width: that.settings.captionWidth + '%',
                opacity: 0
            });

            // Display starting slide's caption
            this.$currentSlide.find('.rs-caption').css('opacity', 1);

            $captions.each(function() {
                $(this).css({
                    transition: 'opacity ' + that.settings.transitionDuration + 'ms linear',
                    backfaceVisibility: 'hidden'
                });
            });
        }

        ,transition: function (slideNum, forward) {
            // If inProgress flag is not set (i.e. if not mid-transition)
            if (!this.inProgress) {
                // If not already on requested slide
                if (slideNum !== this.currentPlace) {
                    // Check whether the requested slide index is ahead or behind in the array (if not passed in as param)
                    if (typeof forward === 'undefined') {
                    	forward = slideNum > this.currentPlace ? true : false;
                    }

                    // If thumbnails exist, revise active class states
                    if (this.settings.useThumbs) {
                        this.$thumbWrapLinks.eq(this.currentPlace).removeClass('active');
                        this.$thumbWrapLinks.eq(slideNum).addClass('active');
                    }

                    // Assign next slide prop (elem)
                    this.$nextSlide = this.$slides.eq(slideNum);

                    // Assign next slide index prop (int)
                    this.currentPlace = slideNum;

                    // User-defined function, fires with transition
                    this.settings.onChange();

                    // Instantiate new Transition object, passing in self (RS obj), transition type (string), direction (bool)
                    new Transition(this, this.settings.transition, forward);
                }
            }
        }
    };

	// Transition object constructor
	function Transition(RS, transition, forward) {
		this.RS = RS; // RS (RefineSlide) object
		this.RS.inProgress = true; // Set RS inProgress flag to prevent additional Transition objects being instantiated until transition end
		this.forward = forward; // Bool: true for forward, false for backward
		this.transition = transition; // String: name of transition requested

        if (this.transition === 'custom') {
            this.customAnims = this.RS.settings.customTransitions;
            this.isCustomTransition = true;
        }

        // Remove incorrect specified elements from customAnims array.
        if (this.transition === 'custom') {
            var that = this;
            $.each(this.customAnims, function (i, obj) {
                if ($.inArray(obj, that.anims) === -1) {
                    that.customAnims.splice(i, 1);
                }
            });
        }

        this.fallback3d = this.RS.settings.fallback3d; // String: fallback to use when 3D transforms aren't supported

		this.init(); // Call Transition initialisation method
	}

	// Transition object Prototype
	Transition.prototype = {
        // Fallback to use if CSS transitions are unsupported
        fallback: 'fade'

        // Array of possible animations
        ,anims: ['cubeH', 'cubeV', 'fade', 'sliceH', 'sliceV', 'slideH', 'slideV', 'scale', 'blockScale', 'kaleidoscope', 'fan', 'blindH', 'blindV']

        ,customAnims: []

        ,init: function () {
            // Call requested transition method
            this[this.transition]();
        }

        ,before: function (callback) {
            var that = this;

            // Prepare slide opacity & z-index
            this.RS.$currentSlide.css('z-index', 2);
            this.RS.$nextSlide.css({'opacity' : 1, 'z-index' : 1});

            // Fade out/in captions with CSS/JS depending on browser capability
            if (this.RS.cssTransitions) {
                this.RS.$currentSlide.find('.rs-caption').css('opacity', 0);
                this.RS.$nextSlide.find('.rs-caption').css('opacity', 1);
            } else {
                this.RS.$currentSlide.find('.rs-caption').animate({'opacity' : 0}, that.RS.settings.transitionDuration);
                this.RS.$nextSlide.find('.rs-caption').animate({'opacity' : 1}, that.RS.settings.transitionDuration);
            }

            // Check if transition describes a setup method
            if (typeof this.setup === 'function') {
                // Setup required by transition
                var transition = this.setup();

                setTimeout(function () {
                    callback(transition);
                }, 20);
            } else {
                // Transition execution
                this.execute();
            }

            // Listen for CSS transition end on elem (set by transition)
            if (this.RS.cssTransitions) {
                $(this.listenTo).one('webkitTransitionEnd transitionend otransitionend oTransitionEnd mstransitionend', $.proxy(this.after, this));
            }
        }

        ,after: function () {
            // Reset transition CSS
            this.RS.$sliderBG.removeAttr('style');
            this.RS.$slider.removeAttr('style');
            this.RS.$currentSlide.removeAttr('style');
            this.RS.$nextSlide.removeAttr('style');
            this.RS.$currentSlide.css({
                zIndex: 1,
                opacity: 0
            });
            this.RS.$nextSlide.css({
                zIndex: 2,
                opacity : 1
            });

            // Additional reset steps required by transition (if any exist)
            if (typeof this.reset === 'function') {
                this.reset();
            }

            // If slideshow is active, reset the timeout
            if (this.RS.settings.autoPlay) {
                clearTimeout(this.RS.cycling);
                this.RS.setAutoPlay();
            }

            // Assign new slide position
            this.RS.$currentSlide = this.RS.$nextSlide;

            // Remove RS obj inProgress flag (i.e. allow new Transition to be instantiated)
            this.RS.inProgress = false;

            // User-defined function, fires after transition has ended
            this.RS.settings.afterChange();
        }

        ,fade: function () {
            var that = this;

            // If CSS transitions are supported by browser
            if (this.RS.cssTransitions) {
                // Setup steps
                this.setup = function () {
                    // Set event listener to next slide elem
                    that.listenTo = that.RS.$currentSlide;

                    that.RS.$currentSlide.css('transition', 'opacity ' + that.RS.settings.transitionDuration + 'ms linear');
                };

                // Execution steps
                this.execute = function () {
                    // Display next slide over current slide
                    that.RS.$currentSlide.css('opacity', 0);
                }
            } else { // JS animation fallback
                this.execute = function () {
                    that.RS.$currentSlide.animate({'opacity' : 0}, that.RS.settings.transitionDuration, function () {
                        // Reset steps
                        that.after();
                    });
                }
            }

            this.before($.proxy(this.execute, this));
        }

        // cube() method is used by cubeH() & cubeV() - not for calling directly
        ,cube: function (tz, ntx, nty, nrx, nry, wrx, wry) { // Args: translateZ, (next slide) translateX, (next slide) translateY, (next slide) rotateX, (next slide) rotateY, (wrap) rotateX, (wrap) rotateY
            // Fallback if browser does not support 3d transforms/CSS transitions
            if (!this.RS.cssTransitions || !this.RS.cssTransforms3d) {
                return this[this['fallback3d']](); // User-defined transition
            }

            var that = this;

            // Setup steps
            this.setup = function () {
                // Set event listener to '.rs-slider' <ul>
                that.listenTo = that.RS.$slider;

                this.RS.$sliderBG.css('perspective', 1000);

                // props for slide <li>s
                that.RS.$currentSlide.css({
                    transform : 'translateZ(' + tz + 'px)',
                    backfaceVisibility : 'hidden'
                });

                // props for next slide <li>
                that.RS.$nextSlide.css({
                    opacity : 1,
                    backfaceVisibility : 'hidden',
                    transform : 'translateY(' + nty + 'px) translateX(' + ntx + 'px) rotateY('+ nry +'deg) rotateX('+ nrx +'deg)'
                });

                // props for slider <ul>
                that.RS.$slider.css({
                    transform: 'translateZ(-' + tz + 'px)',
                    transformStyle: 'preserve-3d'
                });
            };

            // Execution steps
            this.execute = function () {
                that.RS.$slider.css({
                    transition: 'all ' + that.RS.settings.transitionDuration + 'ms ease-in-out',
                    transform: 'translateZ(-' + tz + 'px) rotateX('+ wrx +'deg) rotateY('+ wry +'deg)'
                });
            };

            this.before($.proxy(this.execute, this));
        }

        ,cubeH: function () {
            // Set to half of slide width
            var dimension = $(this.RS.$slides).width() / 2;

            // If next slide is ahead in array
            if (this.forward) {
                this.cube(dimension, dimension, 0, 0, 90, 0, -90);
            } else {
                this.cube(dimension, -dimension, 0, 0, -90, 0, 90);
            }
        }

        ,cubeV: function () {
            // Set to half of slide height
            var dimension = $(this.RS.$slides).height() / 2;

            // If next slide is ahead in array
            if (this.forward) {
                this.cube(dimension, 0, -dimension, 90, 0, -90, 0);
            } else {
                this.cube(dimension, 0, dimension, -90, 0, 90, 0);
            }
        }

        // grid() method is used by many transitions - not for calling directly
        // Grid calculations are based on those in the awesome flux slider (joelambert.co.uk/flux)
        ,grid: function (cols, rows, ro, tx, ty, sc, op) { // Args: columns, rows, rotate, translateX, translateY, scale, opacity
            // Fallback if browser does not support CSS transitions
            if (!this.RS.cssTransitions) {
                return this[this['fallback']]();
            }

            var that = this;

            // Setup steps
            this.setup = function () {
                // The time (in ms) added to/subtracted from the delay total for each new gridlet
                var count = (that.RS.settings.transitionDuration) / (cols + rows);

                // Gridlet creator (divisions of the image grid, positioned with background-images to replicate the look of an entire slide image when assembled)
                function gridlet(width, height, top, left, src, imgWidth, imgHeight, c, r) {
                    var delay = (c + r) * count;

                    // Return a gridlet elem with styles for specific transition
                    return $('<div class="rs-gridlet" />').css({
                        width : width,
                        height : height,
                        top : top,
                        left : left,
                        backgroundImage : 'url(' + src + ')',
                        backgroundPosition : '-' + left + 'px -' + top + 'px',
                        backgroundSize : imgWidth + 'px ' + imgHeight + 'px',
                        transition : 'all ' + that.RS.settings.transitionDuration + 'ms ease-in-out ' + delay + 'ms',
                        transform : 'none'
                    });
                }

                // Get the next slide's image
                that.$img = that.RS.$currentSlide.find('img.rs-slide-image');

                // Create a grid to hold the gridlets
                that.$grid = $('<div />').addClass('rs-grid');

                // Prepend the grid to the next slide (i.e. so it's above the slide image)
                that.RS.$currentSlide.prepend(that.$grid);

                // vars to calculate positioning/size of gridlets
                var imgWidth = that.$img.width(),
                    imgHeight = that.$img.height(),
                    imgSrc = that.$img.attr('src'),
                    colWidth = Math.floor(imgWidth / cols),
                    rowHeight = Math.floor(imgHeight / rows),
                    colRemainder = imgWidth - (cols * colWidth),
                    colAdd = Math.ceil(colRemainder / cols),
                    rowRemainder = imgHeight - (rows * rowHeight),
                    rowAdd = Math.ceil(rowRemainder / rows),
                    leftDist = 0;

                // tx/ty args can be passed as 'auto'/'min-auto' (meaning use slide width/height or negative slide width/height)
                tx = tx === 'auto' ? imgWidth : tx;
                tx = tx === 'min-auto' ? - imgWidth : tx;
                ty = ty === 'auto' ? imgHeight : ty;
                ty = ty === 'min-auto' ? - imgHeight : ty;

                // Loop through cols
                for (var i = 0; i < cols; i++) {
                    var topDist = 0,
                        newColWidth = colWidth;

                    // If imgWidth (px) does not divide cleanly into the specified number of cols, adjust individual col widths to create correct total
                    if (colRemainder > 0) {
                        var add = colRemainder >= colAdd ? colAdd : colRemainder;
                        newColWidth += add;
                        colRemainder -= add;
                    }

                    // Nested loop to create row gridlets for each col
                    for (var j = 0; j < rows; j++)  {
                        var newRowHeight = rowHeight,
                            newRowRemainder = rowRemainder;

                        // If imgHeight (px) does not divide cleanly into the specified number of rows, adjust individual row heights to create correct total
                        if (newRowRemainder > 0) {
                            add = newRowRemainder >= rowAdd ? rowAdd : rowRemainder;
                            newRowHeight += add;
                            newRowRemainder -= add;
                        }

                        // Create & append gridlet to grid
                        that.$grid.append(gridlet(newColWidth, newRowHeight, topDist, leftDist, imgSrc, imgWidth, imgHeight, i, j));

                        topDist += newRowHeight;
                    }

                    leftDist += newColWidth;
                }

                // Set event listener on last gridlet to finish transitioning
                that.listenTo = that.$grid.children().last();

                // Show grid & hide the image it replaces
                that.$grid.show();
                that.$img.css('opacity', 0);

                // Add identifying classes to corner gridlets (useful if applying border radius)
                that.$grid.children().first().addClass('rs-top-left');
                that.$grid.children().last().addClass('rs-bottom-right');
                that.$grid.children().eq(rows - 1).addClass('rs-bottom-left');
                that.$grid.children().eq(- rows).addClass('rs-top-right');
            };

            // Execution steps
            this.execute = function () {
                that.$grid.children().css({
                    opacity: op,
                    transform: 'rotate('+ ro +'deg) translateX('+ tx +'px) translateY('+ ty +'px) scale('+ sc +')'
                });
            };

            this.before($.proxy(this.execute, this));

            // Reset steps
            this.reset = function () {
                that.$img.css('opacity', 1);
                that.$grid.remove();
            }
        }

        ,sliceH: function () {
            this.grid(1, 8, 0, 'min-auto', 0, 1, 0);
        }

        ,sliceV: function () {
            this.grid(10, 1, 0, 0, 'auto', 1, 0);
        }

        ,slideV: function () {
            var dir = this.forward ?
                'min-auto' :
                'auto';

            this.grid(1, 1, 0, 0, dir, 1, 1);
        }

        ,slideH: function () {
            var dir = this.forward ?
                'min-auto' :
                'auto';

            this.grid(1, 1, 0, dir, 0, 1, 1);
        }

        ,scale: function () {
            this.grid(1, 1, 0, 0, 0, 1.5, 0);
        }

        ,blockScale: function () {
            this.grid(8, 6, 0, 0, 0, .6, 0);
        }

        ,kaleidoscope: function () {
            this.grid(10, 8, 0, 0, 0, 1, 0);
        }

        ,fan: function () {
            this.grid(1, 10, 45, 100, 0, 1, 0);
        }

        ,blindV: function () {
            this.grid(1, 8, 0, 0, 0, .7, 0);
        }

        ,blindH: function () {
            this.grid(10, 1, 0, 0, 0, .7, 0);
        }

        ,random: function () {
            // Pick a random transition from the anims array (obj prop)
            this[this.anims[Math.floor(Math.random() * this.anims.length)]]();
        }

        ,custom: function() {
            if (this.RS.nextAnimIndex < 0) {
                this.RS.nextAnimIndex = this.customAnims.length - 1;
            }
            if (this.RS.nextAnimIndex === this.customAnims.length) {
                this.RS.nextAnimIndex = 0;
            }

            // Pick the next item in the list of transitions provided by user.
            this[this.customAnims[this.RS.nextAnimIndex]]();
        }
    };

	// Obj to check browser capabilities
	var testBrowser = {
        // Browser vendor CSS prefixes
        browserVendors: ['', '-webkit-', '-moz-', '-ms-', '-o-', '-khtml-']

        // Browser vendor DOM prefixes
        ,domPrefixes: ['', 'Webkit', 'Moz', 'ms', 'O', 'Khtml']

        // Method to iterate over a property (using all DOM prefixes)
        // Returns true if prop is recognised by browser (else returns false)
        ,testDom: function (prop) {
            var i = this.domPrefixes.length;

            while (i--) {
                if (typeof document.body.style[this.domPrefixes[i] + prop] !== 'undefined') {
                    return true;
                }
            }

            return false;
        }

        ,cssTransitions: function () {
            // Use Modernizr if available & implements csstransitions test
            if (typeof window.Modernizr !== 'undefined' && Modernizr.csstransitions !== 'undefined') {
                return Modernizr.csstransitions;
            }

            // Use testDom method to check prop (returns bool)
            return this.testDom('Transition');
        }

        ,cssTransforms3d: function () {
            // Use Modernizr if available & implements csstransforms3d test
            if (typeof window.Modernizr !== 'undefined' && Modernizr.csstransforms3d !== 'undefined') {
                return Modernizr.csstransforms3d;
            }

            // Check for vendor-less prop
            if (typeof document.body.style['perspectiveProperty'] !== 'undefined') {
                return true;
            }

            // Use testDom method to check prop (returns bool)
            return this.testDom('Perspective');
        }
    };

	// jQuery plugin wrapper
	$.fn['refineSlide'] = function (settings) {
		return this.each(function () {
            // Check if already instantiated on this elem
			if (!$.data(this, 'refineSlide')) {
                // Instantiate & store elem + string
				$.data(this, 'refineSlide', new RS(this, settings));
			}
		});
	}
})(window.jQuery, window, window.document);
;/* =========================================================
 * bootstrap-datepicker.js 
 * http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Copyright 2012 Stefan Petre
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */
 
(function( $ ) {
	
	// Picker object
	
	var Datepicker = function(element, options){
		this.element = $(element);
		this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy');
		this.picker = $(DPGlobal.template)
			.appendTo('body')
			.on({
				click: $.proxy(this.click, this)//,
				//mousedown: $.proxy(this.mousedown, this)
			});
		this.isInput = this.element.is('input');
		this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
		
		if (this.isInput) {
			this.element.on({
				focus: $.proxy(this.show, this),
				//blur: $.proxy(this.hide, this),
				keyup: $.proxy(this.update, this)
			});
		} else {
			if (this.component){
				this.component.on('click', $.proxy(this.show, this));
			} else {
				this.element.on('click', $.proxy(this.show, this));
			}
		}
	
		this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
		if (typeof this.minViewMode === 'string') {
			switch (this.minViewMode) {
				case 'months':
					this.minViewMode = 1;
					break;
				case 'years':
					this.minViewMode = 2;
					break;
				default:
					this.minViewMode = 0;
					break;
			}
		}
		this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
		if (typeof this.viewMode === 'string') {
			switch (this.viewMode) {
				case 'months':
					this.viewMode = 1;
					break;
				case 'years':
					this.viewMode = 2;
					break;
				default:
					this.viewMode = 0;
					break;
			}
		}
		this.startViewMode = this.viewMode;
		this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
		this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
		this.onRender = options.onRender;
		this.fillDow();
		this.fillMonths();
		this.update();
		this.showMode();
	};
	
	Datepicker.prototype = {
		constructor: Datepicker,
		
		show: function(e) {
			this.picker.show();
			this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
			this.place();
			$(window).on('resize', $.proxy(this.place, this));
			if (e ) {
				e.stopPropagation();
				e.preventDefault();
			}
			if (!this.isInput) {
			}
			var that = this;
			$(document).on('mousedown', function(ev){
				if ($(ev.target).closest('.datepicker').length == 0) {
					that.hide();
				}
			});
			this.element.trigger({
				type: 'show',
				date: this.date
			});
		},
		
		hide: function(){
			this.picker.hide();
			$(window).off('resize', this.place);
			this.viewMode = this.startViewMode;
			this.showMode();
			if (!this.isInput) {
				$(document).off('mousedown', this.hide);
			}
			//this.set();
			this.element.trigger({
				type: 'hide',
				date: this.date
			});
		},
		
		set: function() {
			var formated = DPGlobal.formatDate(this.date, this.format);
			if (!this.isInput) {
				if (this.component){
					this.element.find('input').prop('value', formated);
				}
				this.element.data('date', formated);
			} else {
				this.element.prop('value', formated);
			}
		},
		
		setValue: function(newDate) {
			if (typeof newDate === 'string') {
				this.date = DPGlobal.parseDate(newDate, this.format);
			} else {
				this.date = new Date(newDate);
			}
			this.set();
			this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
			this.fill();
		},
		
		place: function(){
			var offset = this.component ? this.component.offset() : this.element.offset();
			this.picker.css({
				top: offset.top + this.height,
				left: offset.left
			});
		},
		
		update: function(newDate){
			this.date = DPGlobal.parseDate(
				typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
				this.format
			);
			this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
			this.fill();
		},
		
		fillDow: function(){
			var dowCnt = this.weekStart;
			var html = '<tr>';
			while (dowCnt < this.weekStart + 7) {
				html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
			}
			html += '</tr>';
			this.picker.find('.datepicker-days thead').append(html);
		},
		
		fillMonths: function(){
			var html = '';
			var i = 0
			while (i < 12) {
				html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
			}
			this.picker.find('.datepicker-months td').append(html);
		},
		
		fill: function() {
			var d = new Date(this.viewDate),
				year = d.getFullYear(),
				month = d.getMonth(),
				currentDate = this.date.valueOf();
			this.picker.find('.datepicker-days th:eq(1)')
						.text(DPGlobal.dates.months[month]+' '+year);
			var prevMonth = new Date(year, month-1, 28,0,0,0,0),
				day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
			prevMonth.setDate(day);
			prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
			var nextMonth = new Date(prevMonth);
			nextMonth.setDate(nextMonth.getDate() + 42);
			nextMonth = nextMonth.valueOf();
			var html = [];
			var clsName,
				prevY,
				prevM;
			while(prevMonth.valueOf() < nextMonth) {
				if (prevMonth.getDay() === this.weekStart) {
					html.push('<tr>');
				}
				clsName = this.onRender(prevMonth);
				prevY = prevMonth.getFullYear();
				prevM = prevMonth.getMonth();
				if ((prevM < month &&  prevY === year) ||  prevY < year) {
					clsName += ' old';
				} else if ((prevM > month && prevY === year) || prevY > year) {
					clsName += ' new';
				}
				if (prevMonth.valueOf() === currentDate) {
					clsName += ' active';
				}
				html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
				if (prevMonth.getDay() === this.weekEnd) {
					html.push('</tr>');
				}
				prevMonth.setDate(prevMonth.getDate()+1);
			}
			this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
			var currentYear = this.date.getFullYear();
			
			var months = this.picker.find('.datepicker-months')
						.find('th:eq(1)')
							.text(year)
							.end()
						.find('span').removeClass('active');
			if (currentYear === year) {
				months.eq(this.date.getMonth()).addClass('active');
			}
			
			html = '';
			year = parseInt(year/10, 10) * 10;
			var yearCont = this.picker.find('.datepicker-years')
								.find('th:eq(1)')
									.text(year + '-' + (year + 9))
									.end()
								.find('td');
			year -= 1;
			for (var i = -1; i < 11; i++) {
				html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
				year += 1;
			}
			yearCont.html(html);
		},
		
		click: function(e) {
			e.stopPropagation();
			e.preventDefault();
			var target = $(e.target).closest('span, td, th');
			if (target.length === 1) {
				switch(target[0].nodeName.toLowerCase()) {
					case 'th':
						switch(target[0].className) {
							case 'switch':
								this.showMode(1);
								break;
							case 'prev':
							case 'next':
								this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
									this.viewDate,
									this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + 
									DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
								);
								this.fill();
								this.set();
								break;
						}
						break;
					case 'span':
						if (target.is('.month')) {
							var month = target.parent().find('span').index(target);
							this.viewDate.setMonth(month);
						} else {
							var year = parseInt(target.text(), 10)||0;
							this.viewDate.setFullYear(year);
						}
						if (this.viewMode !== 0) {
							this.date = new Date(this.viewDate);
							this.element.trigger({
								type: 'changeDate',
								date: this.date,
								viewMode: DPGlobal.modes[this.viewMode].clsName
							});
						}
						this.showMode(-1);
						this.fill();
						this.set();
						break;
					case 'td':
						if (target.is('.day') && !target.is('.disabled')){
							var day = parseInt(target.text(), 10)||1;
							var month = this.viewDate.getMonth();
							if (target.is('.old')) {
								month -= 1;
							} else if (target.is('.new')) {
								month += 1;
							}
							var year = this.viewDate.getFullYear();
							this.date = new Date(year, month, day,0,0,0,0);
							this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
							this.fill();
							this.set();
							this.element.trigger({
								type: 'changeDate',
								date: this.date,
								viewMode: DPGlobal.modes[this.viewMode].clsName
							});
						}
						break;
				}
			}
		},
		
		mousedown: function(e){
			e.stopPropagation();
			e.preventDefault();
		},
		
		showMode: function(dir) {
			if (dir) {
				this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
			}
			this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
		}
	};
	
	$.fn.datepicker = function ( option, val ) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('datepicker'),
				options = typeof option === 'object' && option;
			if (!data) {
				$this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
			}
			if (typeof option === 'string') data[option](val);
		});
	};

	$.fn.datepicker.defaults = {
		onRender: function(date) {
			return '';
		}
	};
	$.fn.datepicker.Constructor = Datepicker;
	
	var DPGlobal = {
		modes: [
			{
				clsName: 'days',
				navFnc: 'Month',
				navStep: 1
			},
			{
				clsName: 'months',
				navFnc: 'FullYear',
				navStep: 1
			},
			{
				clsName: 'years',
				navFnc: 'FullYear',
				navStep: 10
		}],
		dates:{
			days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
			daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
			daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
			months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
			monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
		},
		isLeapYear: function (year) {
			return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
		},
		getDaysInMonth: function (year, month) {
			return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
		},
		parseFormat: function(format){
			var separator = format.match(/[.\/\-\s].*?/),
				parts = format.split(/\W+/);
			if (!separator || !parts || parts.length === 0){
				throw new Error("Invalid date format.");
			}
			return {separator: separator, parts: parts};
		},
		parseDate: function(date, format) {
			var parts = date.split(format.separator),
				date = new Date(),
				val;
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
			if (parts.length === format.parts.length) {
				var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
				for (var i=0, cnt = format.parts.length; i < cnt; i++) {
					val = parseInt(parts[i], 10)||1;
					switch(format.parts[i]) {
						case 'dd':
						case 'd':
							day = val;
							date.setDate(val);
							break;
						case 'mm':
						case 'm':
							month = val - 1;
							date.setMonth(val - 1);
							break;
						case 'yy':
							year = 2000 + val;
							date.setFullYear(2000 + val);
							break;
						case 'yyyy':
							year = val;
							date.setFullYear(val);
							break;
					}
				}
				date = new Date(year, month, day, 0 ,0 ,0);
			}
			return date;
		},
		formatDate: function(date, format){
			var val = {
				d: date.getDate(),
				m: date.getMonth() + 1,
				yy: date.getFullYear().toString().substring(2),
				yyyy: date.getFullYear()
			};
			val.dd = (val.d < 10 ? '0' : '') + val.d;
			val.mm = (val.m < 10 ? '0' : '') + val.m;
			var date = [];
			for (var i=0, cnt = format.parts.length; i < cnt; i++) {
				date.push(val[format.parts[i]]);
			}
			return date.join(format.separator);
		},
		headTemplate: '<thead>'+
							'<tr>'+
								'<th class="prev">&lsaquo;</th>'+
								'<th colspan="5" class="switch"></th>'+
								'<th class="next">&rsaquo;</th>'+
							'</tr>'+
						'</thead>',
		contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
	};
	DPGlobal.template = '<div class="datepicker dropdown-menu">'+
							'<div class="datepicker-days">'+
								'<table class=" table-condensed">'+
									DPGlobal.headTemplate+
									'<tbody></tbody>'+
								'</table>'+
							'</div>'+
							'<div class="datepicker-months">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
								'</table>'+
							'</div>'+
							'<div class="datepicker-years">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
								'</table>'+
							'</div>'+
						'</div>';

})( window.jQuery );;/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:  
 * `<img src="blank.gif" data-lazyload="my_image.png" width="600" height="400" class="lazy">`
 */

var pc = pc || {};

(function ($, window)
{
    var $q = function(q, res) {
        if(document.querySelectorAll) {
            res = document.querySelectorAll(q);
        }
        else {
            var d = document,
                a = d.styleSheets[0] || d.createStyleSheet();

            a.addRule(q, 'f:b');
            for(var l = d.all, b = 0, c = [], f = l.length; b < f; b++)
                l[b].currentStyle.f && c.push(l[b]);

            a.removeRule(0);
            res = c;
        }
        return res;
    };

    var addEventListener = function(evt, fn)
    {
        window.addEventListener
            ? this.addEventListener(evt, fn, false)
            : (window.attachEvent)
              ? this.attachEvent('on' + evt, fn)
              : this['on' + evt] = fn;
    };

    var has = function (obj, key) {
	  	return Object.prototype.hasOwnProperty.call(obj, key);
	};

	function loadImage(el, fn) {
		var img = new Image(),
			src = el.getAttribute('data-lazyload');

		img.onload = function () {
			// handle images that are not found.
			if ('naturalHeight' in this) {
				if (this.naturalHeight + this.naturalWidth === 0) {
					this.onerror();
					return;
				}
			} else if (this.width + this.height === 0) {
				this.onerror();
				return;
			}

			if (!!el.parent) {
				el.parent.replaceChild(img, el);
			}
			else {
				el.src = src;
			}

			el.removeAttribute('data-lazyload');
			fn ? fn() : null;
		};

		img.onerror = function () {
			// remove the lazyload on images that return an error.
			el.removeAttribute('data-lazyload');
			fn ? fn() : null;
		};

		if (src != null) {
			img.src = src;
		}
	};

	function elementInViewport(el) {
	    var rect = el.getBoundingClientRect();

	    return (
	        rect.top >= 0
	            && rect.left >= 0
	            && rect.top <= (window.innerHeight || document.documentElement.clientHeight)
	            && $(el).is(':visible')
	    );
	};

	var images = new Array();

	function processScroll() {
		for (var i = 0, imagesLen = images.length; i < imagesLen; i += 1) {
			if (elementInViewport(images[i])) {
				loadImage(images[i], function () {
					images.splice(i, 1);
				});
			}
		};
	};

	function setup() {
		var query = $q('[data-lazyload]');

		if (query.length > 0) {
			images.length = 0;

			for (var i = 0; i < query.length; i++) {
				images.push(query[i]);
			};

			if (typeof window.isloaded === 'undefined') {
				$(window).load(processScroll);
			}
			else {
				processScroll();
			}

			addEventListener('scroll', processScroll);
		}
	};

	setup();

	pc.lazyloadsetup = function () {
		setup();
	};

	pc.lazyload = function () {
		processScroll();
	};

	$(window).load(function () {
		window.isloaded = true;
	});

})(jQuery, this);;// Generated by CoffeeScript 1.10.0
(function () {
    var $, Range, Trie,
        indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

    Trie = (function () {
        function Trie() {
            this.trie = {};
        }

        Trie.prototype.push = function (value) {
            var char, i, j, len, obj, ref, results;
            value = value.toString();
            obj = this.trie;
            ref = value.split('');
            results = [];
            for (i = j = 0, len = ref.length; j < len; i = ++j) {
                char = ref[i];
                if (obj[char] == null) {
                    if (i === (value.length - 1)) {
                        obj[char] = null;
                    } else {
                        obj[char] = {};
                    }
                }
                results.push(obj = obj[char]);
            }
            return results;
        };

        Trie.prototype.find = function (value) {
            var char, i, j, len, obj, ref;
            value = value.toString();
            obj = this.trie;
            ref = value.split('');
            for (i = j = 0, len = ref.length; j < len; i = ++j) {
                char = ref[i];
                if (obj.hasOwnProperty(char)) {
                    if (obj[char] === null) {
                        return true;
                    }
                } else {
                    return false;
                }
                obj = obj[char];
            }
        };

        return Trie;

    })();

    Range = (function () {
        function Range(trie1) {
            this.trie = trie1;
            if (this.trie.constructor !== Trie) {
                throw Error('Range constructor requires a Trie parameter');
            }
        }

        Range.rangeWithString = function (ranges) {
            var j, k, len, n, r, range, ref, ref1, trie;
            if (typeof ranges !== 'string') {
                throw Error('rangeWithString requires a string parameter');
            }
            ranges = ranges.replace(/ /g, '');
            ranges = ranges.split(',');
            trie = new Trie;
            for (j = 0, len = ranges.length; j < len; j++) {
                range = ranges[j];
                if (r = range.match(/^(\d+)-(\d+)$/)) {
                    for (n = k = ref = r[1], ref1 = r[2]; ref <= ref1 ? k <= ref1 : k >= ref1; n = ref <= ref1 ? ++k : --k) {
                        trie.push(n);
                    }
                } else if (range.match(/^\d+$/)) {
                    trie.push(range);
                } else {
                    throw Error("Invalid range '" + r + "'");
                }
            }
            return new Range(trie);
        };

        Range.prototype.match = function (number) {
            return this.trie.find(number);
        };

        return Range;

    })();


    /*
    jQuery Credit Card Validator 1.1
    
    Copyright 2012-2015 Pawel Decowski
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software
    is furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    IN THE SOFTWARE.
     */

    $ = jQuery;

    $.fn.validateCreditCard = function (callback, options) {
        var bind, card, card_type, card_types, get_card_type, is_valid_length, is_valid_luhn, j, len, normalize, ref, validate, validate_number;
        card_types = [
            {
                name: 'amex',
                range: '34,37',
                valid_length: [15]
            }, {
                name: 'diners_club_carte_blanche',
                range: '300-305, 3095, 36, 38-39',
                valid_length: [14]
            }, {
                name: 'jcb',
                range: '3528-3589',
                valid_length: [16]
            }, {
                name: 'laser',
                range: '6304, 6706, 6709, 6771',
                valid_length: [16, 17, 18, 19]
            }, {
                name: 'visa_electron',
                range: '4026, 417500, 4508, 4844, 4913, 4917',
                valid_length: [16]
            }, {
                name: 'visa',
                range: '4',
                valid_length: [13, 14, 15, 16, 17, 18, 19]
            }, {
                name: 'mastercard',
                range: '51-55,2221-2720',
                valid_length: [16]
            }, {
                name: 'discover',
                range: '6011, 622126-622925, 644-649, 65',
                valid_length: [16]
            }, {
                name: 'dankort',
                range: '5019',
                valid_length: [16]
            }, {
                name: 'maestro',
                range: '50, 56-69',
                valid_length: [12, 13, 14, 15, 16, 17, 18, 19]
            }, {
                name: 'uatp',
                range: '1',
                valid_length: [15]
            }, {
                name: 'enroute',
                range: '2014, 2149',
                valid_length: [15]
            }
        ];
        bind = false;
        if (callback) {
            if (typeof callback === 'object') {
                options = callback;
                bind = false;
                callback = null;
            } else if (typeof callback === 'function') {
                bind = true;
            }
        }
        if (options == null) {
            options = {};
        }
        if (options.accept == null) {
            options.accept = (function () {
                var j, len, results;
                results = [];
                for (j = 0, len = card_types.length; j < len; j++) {
                    card = card_types[j];
                    results.push(card.name);
                }
                return results;
            })();
        }
        ref = options.accept;
        for (j = 0, len = ref.length; j < len; j++) {
            card_type = ref[j];
            if (indexOf.call((function () {
                var k, len1, results;
                results = [];
                for (k = 0, len1 = card_types.length; k < len1; k++) {
                    card = card_types[k];
                    results.push(card.name);
                }
                return results;
            })(), card_type) < 0) {
                throw Error("Credit card type '" + card_type + "' is not supported");
            }
        }
        get_card_type = function (number) {
            var k, len1, r, ref1;
            ref1 = (function () {
                var l, len1, ref1, results;
                results = [];
                for (l = 0, len1 = card_types.length; l < len1; l++) {
                    card = card_types[l];
                    if (ref1 = card.name, indexOf.call(options.accept, ref1) >= 0) {
                        results.push(card);
                    }
                }
                return results;
            })();
            for (k = 0, len1 = ref1.length; k < len1; k++) {
                card_type = ref1[k];
                r = Range.rangeWithString(card_type.range);
                if (r.match(number)) {
                    return card_type;
                }
            }
            return null;
        };
        is_valid_luhn = function (number) {
            var digit, k, len1, n, ref1, sum;
            sum = 0;
            ref1 = number.split('').reverse();
            for (n = k = 0, len1 = ref1.length; k < len1; n = ++k) {
                digit = ref1[n];
                digit = +digit;
                if (n % 2) {
                    digit *= 2;
                    if (digit < 10) {
                        sum += digit;
                    } else {
                        sum += digit - 9;
                    }
                } else {
                    sum += digit;
                }
            }
            return sum % 10 === 0;
        };
        is_valid_length = function (number, card_type) {
            var ref1;
            return ref1 = number.length, indexOf.call(card_type.valid_length, ref1) >= 0;
        };
        validate_number = function (number) {
            var length_valid, luhn_valid;
            card_type = get_card_type(number);
            luhn_valid = false;
            length_valid = false;
            if (card_type != null) {
                luhn_valid = is_valid_luhn(number);
                length_valid = is_valid_length(number, card_type);
            }
            return {
                card_type: card_type,
                valid: luhn_valid && length_valid,
                luhn_valid: luhn_valid,
                length_valid: length_valid
            };
        };
        validate = (function (_this) {
            return function () {
                var number;
                number = normalize($(_this).val());
                return validate_number(number);
            };
        })(this);
        normalize = function (number) {
            return number.replace(/[ -]/g, '');
        };
        if (!bind) {
            return validate();
        }
        this.on('input.jccv', (function (_this) {
            return function () {
                $(_this).off('keyup.jccv');
                return callback.call(_this, validate());
            };
        })(this));
        this.on('keyup.jccv', (function (_this) {
            return function () {
                return callback.call(_this, validate());
            };
        })(this));
        callback.call(this, validate());
        return this;
    };

}).call(this);
;// default footer
// js loaded in the footer

if (!window.console) {
	console = {
		log: function () { }
	};
}

var pc = pc || {};

// addthis
pc.addthis = pc.addthis || '';

(function ($) {	
	if (pc.addthis !== '') {
		$.getScript('//s7.addthis.com/js/300/addthis_widget.js#pubid=' + pc.addthis);
	}
})(jQuery);

;(function ($) {

	function setup() {
		// trailer functionality
		
		createOverlay();

		$(document).on('click', '[data-trailer-btn], [href*="youtube.com"], [href*="youtu.be"]', function (e) {
			if (this.target.toLowerCase() === '_blank') {
				return;
			}

			e.preventDefault();
			var $this = $(this),
				thisHref = $this.attr('href'),
				$trailer = $('[data-trailer]'),
				$video = $trailer.find('video'),
				$iframe = $trailer.find('iframe'),
				trailerID,
				trailerHref,
				videoItems = [],
				videoSrc = [];

				
			if (thisHref.indexOf('mymovies') > -1 && thisHref.indexOf('|') > -1 && typeof $this.attr('mm_options') === 'undefined') {
				// html video
				// mymovies
				videoItems = thisHref.split('|');

				if (videoItems.length > 5 && typeof _V_ !== 'undefined') {

					window.mid = videoItems[1];
					window.mti = videoItems[2];
					window.fid = videoItems[3];
					window.fti = videoItems[5];
					window.mtid = 'trl';
					window.pid = '';

					$.each(videoItems[0].split(','), function (index, value) {
						var videoType = value.split('.').pop();

						if (videoType.toLowerCase() === 'ogv') {
							videoType = 'ogg';
						}

						videoSrc.push({
							type: 'video/' + videoType,
							src: value
						});
					});

					if ($video.length === 0) {
						$trailer.find('.overlayTrailerFrame').append('<video id="trailerVideo" class="video-js vjs-default-skin" controls data-trailer-video></video>');
						$video = $trailer.find('video');
					}
						
					_V_('trailerVideo').ready(function () {
						var myPlayer = this;
						myPlayer.src(videoSrc);
						myPlayer.addEvent("play", triggerSDC);
						myPlayer.addEvent("ended", triggerEnd);
					});

					$video.attr({
						'poster': videoItems[4]
					});

					$('#trailerVideo').addClass('active');
				}

			}
			else {
				// iframe
				if (thisHref.indexOf('youtu') > -1) {
					// youtube
					trailerID = thisHref.replace(/.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/g, '$1'),
					trailerHref = '//www.youtube.com/embed/' + trailerID + '?rel=0&autoplay=1';
				}
				else {
					// other
					trailerHref = thisHref;
				}

				$iframe.attr('src', trailerHref).css('display', 'block');
			}
			
			$trailer.addClass('active');
		});
	}

	function createOverlay() {
		var $trailer = $('[data-trailer]'),
			$trailerContent,
			$trailerClose;		

		if ($trailer.length === 0) {
			$.get('/template?name=OverlayTrailer&extensionToFind=mustache&extensionToReturn=txt', function (data) {
				$('body').append(data);

				$trailer = $('[data-trailer]');

				$trailer.find('iframe').attr('src', '');

				$trailerClose = $trailer.find('[data-trailer-close]');

				$trailer.on('click', function (e) {
					if (e.target === this) {
						closeOverlay($trailer);
					}
				});

				$trailerClose.on('click', function (e) {
					e.preventDefault();
					closeOverlay($trailer);
				});
			});
		}
	}

	function closeOverlay($trailer) {
		if (typeof _V_ !== 'undefined' && $trailer.find('#trailerVideo').length > 0) {
			_V_('trailerVideo').destroy();
			$trailer.find('#trailerVideo').remove();

			if (typeof triggerEnd !== 'undefined') {
			  triggerEnd();
			}
		}

		if ($trailer.find('iframe').length > 0) {
			$trailer.find('iframe').attr('src', '').hide();
		}

		$trailer.removeClass('active');
	}

	function init() {
		$(function () {
			setup();
		});
	}

	init();
})(jQuery);;// tooltip functionality

(function ($) {
	if ($('[data-tooltip]').length > 0) {
		$(document).on('mouseenter', '[data-tooltip]', function () {
			var target = $(this),
					tip = target.attr('title'),
					tooltip = $('<div id="tooltip"></div>');

			if (!tip || tip == '') {
				return false;
			}

			target.removeAttr('title');
			tooltip.css('opacity', 0)
					.html(tip)
					.appendTo('body');

			var init_tooltip = function () {
				if ($(window).width() < tooltip.outerWidth() * 1.5)
					tooltip.css('max-width', $(window).width() / 2);
				else
					tooltip.css('max-width', 340);

				var pos_left = target.offset().left + (target.outerWidth() / 2) - (tooltip.outerWidth() / 2),
				pos_top = target.offset().top - tooltip.outerHeight() - 25;

				if (pos_left < 0) {
					pos_left = target.offset().left + target.outerWidth() / 2 - 25;
					tooltip.addClass('left');
				}
				else
					tooltip.removeClass('left');

				if (pos_left + tooltip.outerWidth() > $(window).width()) {
					pos_left = target.offset().left - tooltip.outerWidth() + target.outerWidth() / 2 + 25;
					tooltip.addClass('right');
				}
				else
					tooltip.removeClass('right');

				if (pos_top < 0) {
					var pos_top = target.offset().top + target.outerHeight();
					tooltip.addClass('top');
				}
				else
					tooltip.removeClass('top');

				tooltip.css({ left: pos_left, top: pos_top })
				.animate({ top: '+=10', opacity: 1 }, 50);
			};

			init_tooltip();
			$(window).resize(init_tooltip);

			var remove_tooltip = function () {
				tooltip.animate({ top: '-=10', opacity: 0 }, 50, function () {
					$(this).remove();
				});

				target.attr('title', tip);
			};

			target.bind('mouseleave', remove_tooltip);
			tooltip.bind('click', remove_tooltip);
		});
	}
})(jQuery);;var pc = pc || {};
var peach = peach || {};
/*
module to control maps functionality
providers supported:
- google v3 api

@return {object} This object exposes the public properties and methods of this object
*/

pc.map = pc.map || {
	//"key": "AIzaSyAqLR-bwHXQpmABWxiWsL_qIdX7Nnb36ZU"
};

peach.maps = (function ($) {
	// Set to strict
    "use strict";

    var useIframe = true;

	// declare main variables, settings and functions
	var publicObj = {},
		defaultSettings = {
			"mapCanvas": "[data-map]",
			"mapProvider": "google",
			"zoom": "13",
			"lat": "-34.397",
			"lng": "150.644"
		},
		googleSettings = {
			"url": "https://maps.googleapis.com/maps/api/js",
			"mapType": "ROADMAP", // ROADMAP | SATELLITE  | HYBRID | TERRAIN
			"mapTypeControl": true, // true | false
			"mapTypeControlStyle": "", // HORIZONTAL_BAR | DROPDOWN_MENU | ""
			"mapTypeControlPosition": "TOP_RIGHT", // TOP_CENTER | TOP_LEFT | TOP_RIGHT | LEFT_TOP | RIGHT_TOP | LEFT_CENTER | RIGHT_CENTER | LEFT_BOTTOM | RIGHT_BOTTOM | BOTTOM_CENTER | BOTTOM_LEFT | BOTTOM_RIGHT
			"zoomControl": true, // true | false
			"zoomControlStyle": "SMALL", // SMALL | LARGE | ""
			"zoomControlPosition": "LEFT_TOP", // TOP_CENTER | TOP_LEFT | TOP_RIGHT | LEFT_TOP | RIGHT_TOP | LEFT_CENTER | RIGHT_CENTER | LEFT_BOTTOM | RIGHT_BOTTOM | BOTTOM_CENTER | BOTTOM_LEFT | BOTTOM_RIGHT
			"panControl": false, // true | false
			"panControlPosition": "", // TOP_CENTER | TOP_LEFT | TOP_RIGHT | LEFT_TOP | RIGHT_TOP | LEFT_CENTER | RIGHT_CENTER | LEFT_BOTTOM | RIGHT_BOTTOM | BOTTOM_CENTER | BOTTOM_LEFT | BOTTOM_RIGHT
			"scaleControl": false, // true | false
			"scaleControlPosition": "RIGHT_BOTTOM", // TOP_CENTER | TOP_LEFT | TOP_RIGHT | LEFT_TOP | RIGHT_TOP | LEFT_CENTER | RIGHT_CENTER | LEFT_BOTTOM | RIGHT_BOTTOM | BOTTOM_CENTER | BOTTOM_LEFT | BOTTOM_RIGHT
			"streetViewControl": true, // true | false
			"streetViewControlPosition": "LEFT_CENTER" // TOP_CENTER | TOP_LEFT | TOP_RIGHT | LEFT_TOP | RIGHT_TOP | LEFT_CENTER | RIGHT_CENTER | LEFT_BOTTOM | RIGHT_BOTTOM | BOTTOM_CENTER | BOTTOM_LEFT | BOTTOM_RIGHT
		},
		googleMapCanvas = [],
		setupMaps = function () { throw new Error("setupMaps is undefined."); },
		loadGoogleScript = function () { throw new Error("loadGoogleScript is undefined."); },
		loadGoogleMap = function () { throw new Error("loadGoogleMap is undefined."); },
        loadGoogleMarkers = function () { throw new Error("loadGoogleMarkers is undefined."); },
        loadGoogleIframe = function () { throw new Error("loadGoogleIframe is undefined."); };

	/*
function to setup maps
*/
	setupMaps = function () {
		var $mapCanvas = $(defaultSettings.mapCanvas);

		$mapCanvas.each(function () {
			var $this = $(this),
				thisOptions = $this.data("options") || {},
				mapProvider = thisOptions.mapProvider || defaultSettings.mapProvider;

			switch (mapProvider) {
				case "google":
					googleMapCanvas.push($this);
					break;
			}
		});

        if (googleMapCanvas.length > 0) {
            if (useIframe) {
                loadGoogleIframe();
            }
            else {
                loadGoogleScript();
            }
        }
    };

    loadGoogleIframe = function () {
        $.each(googleMapCanvas, function () {
            var $this = $(this);
            var thisOptions = $this.data('map') || {};
            var thisLat = parseFloat(thisOptions.lat || defaultSettings.lat);
            var thisLng = parseFloat(thisOptions.lng || defaultSettings.lng);
            var location = thisOptions.location || (thisLat + ',' + thisLng);

            $this.html('<iframe frameborder="0" style="border:0; width: 100%; height: 100%;" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyASDuUF_QXBl6eGaoWELLtqoVAdrWl4PaI&q=' + encodeURIComponent(location) + '" allowfullscreen title="location map"></iframe>');
        });
    };

	/*
function to load in google script
	*/
	loadGoogleScript = function () {
		var script = document.createElement("script"),
			scriptUrl = googleSettings.url,
			scriptKey = pc.map.key || '',
			scriptSensor = false;

		// check if geolocation supported
		if (navigator.geolocation) {
			scriptSensor = true;
		}

		if (scriptKey !== '') {
			scriptKey = '&key=' + scriptKey;
		}

		script.type = "text/javascript";
		script.src = scriptUrl + "?" + scriptKey + "&sensor=" + scriptSensor + "&callback=peach.maps.googleCallback";
		document.body.appendChild(script);
	};

	/*
	function to create google maps
	*/
	loadGoogleMap = function () {
		$.each(googleMapCanvas, function () {
			var $this = $(this),
				thisOptions = $this.data("map") || {},
				thisZoom = parseInt(thisOptions.zoom || defaultSettings.zoom),
				thisLat = parseFloat(thisOptions.lat || defaultSettings.lat),
				thisLng = parseFloat(thisOptions.lng || defaultSettings.lng),
				mapType = thisOptions.mapType || googleSettings.mapType,
				mapTypeControl = thisOptions.mapTypeControl || googleSettings.mapTypeControl,
				mapTypeControlStyle = thisOptions.mapTypeControlStyle || googleSettings.mapTypeControlStyle,
				mapTypeControlPosition = thisOptions.mapTypeControlPosition || googleSettings.mapTypeControlPosition,
				zoomControl = thisOptions.zoomControl || googleSettings.zoomControl,
				zoomControlStyle = thisOptions.zoomControlStyle || googleSettings.zoomControlStyle,
				zoomControlPosition = thisOptions.zoomControlPosition || googleSettings.zoomControlPosition,
				panControl = thisOptions.panControl || googleSettings.panControl,
				panControlPosition = thisOptions.panControlPosition || googleSettings.panControlPosition,
				scaleControl = thisOptions.scaleControl || googleSettings.scaleControl,
				scaleControlPosition = thisOptions.scaleControlPosition || googleSettings.scaleControlPosition,
				streetViewControl = thisOptions.streetViewControl || googleSettings.streetViewControl,
				streetViewControlPosition = thisOptions.streetViewControlPosition || googleSettings.streetViewControlPosition,
				markers = thisOptions.markers || [],
				mapOptions = {},
				map;

			// set map options
			mapOptions = {
				zoom: thisZoom,
				center: new google.maps.LatLng(thisLat, thisLng),
				mapTypeId: google.maps.MapTypeId[mapType],
				mapTypeControl: mapTypeControl,
				mapTypeControlOptions: {
					style: google.maps.MapTypeControlStyle[mapTypeControlStyle],
					position: google.maps.ControlPosition[mapTypeControlPosition]
				},
				zoomControl: zoomControl,
				zoomControlOptions: {
					style: google.maps.ZoomControlStyle[zoomControlStyle],
					position: google.maps.ControlPosition[zoomControlPosition]
				},
				panControl: panControl,
				panControlOptions: {
					position: google.maps.ControlPosition[panControlPosition]
				},
				scaleControl: scaleControl,
				scaleControlOptions: {
					position: google.maps.ControlPosition[scaleControlPosition]
				},
				streetViewControl: streetViewControl,
				streetViewControlOptions: {
					position: google.maps.ControlPosition[streetViewControlPosition]
				}
			};

			// create map
			map = new google.maps.Map($this[0], mapOptions);

			// load markers
			if (markers.length > 0) {
				loadGoogleMarkers(map, markers);
			}

			publicObj.recenter = function () {
				google.maps.event.trigger(map, 'resize');
				map.setCenter(new google.maps.LatLng(thisLat, thisLng));
			};

		});
	};

	/*
	function to load google markers
	*/
	loadGoogleMarkers = function (map, markers) {
		$.each(markers, function () {
			var thisLat = parseFloat(this.lat || 0),
					thisLng = parseFloat(this.lng || 0),
					thisLatLng = new google.maps.LatLng(thisLat, thisLng),
					thisTitle = this.title || "",
					thisIcon = this.icon || "",
					marker,
					infoWindow,
					infoWindowContentString = this.infoWindowContent || "",
					infoWindowMaxWidth = parseInt(this.infoWindowMaxWidth || 0);

			// create marker
			marker = new google.maps.Marker({
				position: thisLatLng,
				map: map,
				title: thisTitle,
				icon: thisIcon
			});

			// create marker info window
			if (infoWindowContentString !== "") {
				infoWindow = new google.maps.InfoWindow({
					content: infoWindowContentString,
					maxWidth: infoWindowMaxWidth
				});

				google.maps.event.addListener(marker, "click", function () {
					infoWindow.open(map, marker);
				});
			}
		});
	};

	/*
	function called once google scripts loaded
	*/
	publicObj.googleCallback = function () {
		loadGoogleMap();
	};

	// call setup maps
	setupMaps();

	// Expose the public object
	return publicObj;

}(jQuery || {}));;var pc = pc || {};

// date
pc.date = pc.date || {
	'reminder': '1' // hours
};

(function ($) {

	function setup() {
		var $btn = $(this),
			url = '/api/calendar/saveoccasion/{{event}}?reminderInHours={{reminder}}';

		$btn.on('click', function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $this = $(this),
				thisEvent = $this.attr('data-date-btn'),
				thisUrl = url;

			thisUrl = thisUrl
				.replace(/{{event}}/g, thisEvent)
				.replace(/{{reminder}}/g, pc.date.reminder);

			// open up url to get iCalendar file
		    //window.location = thisUrl;
			
			window.open(thisUrl);
		});		
	}

	function init() {
		var $btn = $('[data-date-btn]');

		if ($btn.length > 0) {
			$btn.each(setup);
		} 
	}

	init();
})(jQuery);;var pc = pc || {};

// toggle functionality

(function ($) {

	function setup() {
		$(document).on('click', '[data-toggle-btn]:visible', function (e) {
			e.preventDefault();

			var $btn = $(this),
				el = $btn.attr('data-toggle-btn') || '',
				$el,
				copyOrig = $btn.data('copyorig') || $btn.text(),
				copyNew = $btn.attr('data-toggle-copy') || '';

			// check el data exists
			if (el !== '') {
				$el = $('[data-toggle="' + el + '"]');
				// check element exists
				if ($el.length > 0) {
					// check if element is active
					if ($el.hasClass('active')) {
						// make element inactive
						$el.removeClass('active');
						$btn.removeClass('active');
						if (copyNew !== '') {
							$btn.text(copyOrig);
						}
					}
					else {
						// make element active
						$el.addClass('active');
						$btn.addClass('active');
						if (copyNew !== '') {
							$btn.text(copyNew);
						}
						$btn.data('copyorig', copyOrig);
					}
				}
			}
		});						
	}

	function init() {
		$(function () {
			setup();
		});
	}

	init();

})(jQuery);;var pc = pc || {};

// forms

pc.form = {
    'temp': {
        'region': '',
        'cinema': ''
    }
};

(function ($) {

    var $years = $('[data-form-populate-year]'),
        $months = $('[data-form-populate-month]'),
        $days = $('[data-form-populate-day]');

    if ($years.length > 0) {
        $years.each(function () {
            var $year = $(this),
                numToAdd = $year.data('form-populate-year') || 10,
                template = '<option value="{{year}}">{{year}}</option>',
                today = new Date(),
                thisYear = today.getFullYear();

            for (var i = thisYear, len = thisYear + numToAdd; i < len; i++) {
                $year.append(template.replace(/{{year}}/g, i));
            }
        });
    }

    if ($months.length > 0) {
        $months.each(function () {
            var $month = $(this),
                template = '<option value="{{month}}">{{month}}</option>',
                type = $month.attr('data-form-populate-month') || '',
                data = [];

            if (type === 'full') {
                data = [
                    'January',
                    'February',
                    'March',
                    'April',
                    'May',
                    'June',
                    'July',
                    'August',
                    'September',
                    'October',
                    'November',
                    'December'
                ];
            }
            else {
                for (var a = 0; a < 12; a++) {
                    data.push(('0' + a).slice(-2));
                }
            }

            for (var i = 0; i < 12; i++) {
                $month.append(template.replace(/{{month}}/g, data[i]));
            }
        });
    }

    if ($days.length > 0) {
        $days.each(function () {
            var $day = $(this),
                template = '<option value="{{day}}">{{day}}</option>';

            for (var i = 1; i <= 31; i++) {
                $day.append(template.replace(/{{day}}/g, ('0' + i).slice(-2)));
            }
        });
    }

    var $parent = $('[data-theatre-rental]');

    if ($parent.length > 0) {

        var $btn = $parent.find('[data-privatehire-selects-show]'),
            $radio = $('[name="catering"]'),
            $btn1 = $('[data-button-one]'),
            $btn2 = $('[data-button-two]'),
            $btn3 = $('[data-button-three]'),
            $btn4 = $('[data-button-four]'),
            $selects = $parent.find('[data-privatehire-selects-item].dn'),
            $selects2 = $parent.find('[data-privatehire-selects-item].show'),
            $removeBtn = $('[data-removeBtn]');

        if ($btn.length > 0 && $selects.length > 0) {

            $radio.on('click', function () {
                $radio.removeClass('invalid');
            });

            $btn1.on('click', function () {
                $('[data-date-one]').addClass('dn');
                $('[data-date-one] select').val('').trigger('change');
                $('[data-date-one] select').removeClass('invalid');
            });

            $btn2.on('click', function () {
                $('[data-date-two]').addClass('dn');
                $('[data-date-two] select').val('').trigger('change');
                $('[data-date-two] select').removeClass('invalid');
            });

            $btn3.on('click', function () {
                $('[data-date-three]').addClass('dn');
                $('[data-date-three] select').val('').trigger('change');
                $('[data-date-three] select').removeClass('invalid');
            });

            $btn4.on('click', function () {
                $('[data-date-four]').addClass('dn');
                $('[data-date-four] select').val('').trigger('change');
                $('[data-date-four] select').removeClass('invalid');
            });

            $removeBtn.on('click', function (e) {
                e.preventDefault();
                $btn.show();
                $selects = $parent.find('[data-privatehire-selects-item].dn');

                if ($selects.length === 3) {
                    $removeBtn.hide();
                } else {
                    $removeBtn.show();
                }
            });

            $btn.on('click', function (e) {
                e.preventDefault();

                $btn1.removeClass('dn');

                $selects.first().slideDown(150, function () {
                    $(this).removeClass('dn').css('display', '');
                    $('[data-removeBtn]').show();

                    $selects = $parent.find('[data-privatehire-selects-item].dn');
                    if ($selects.length === 0) {
                        $btn.hide();
                    } else {
                        $btn.show();
                    }

                });
            });
        }
    }

    function setup() {
        var $form = $('[data-form]'),
            $curRegion = $('[data-id-region]'),
            $curCinema = $('[data-id-cinema]');

        if ($form.length > 0) {

            if ($curRegion.length > 0) {
                pc.form.temp.region = $curRegion.attr('data-id-region');
            }

            if ($curCinema.length > 0) {
                pc.form.temp.cinema = $curCinema.attr('data-id-cinema');
            }

            $form.each(setupForm);
        }
    }

    function setupForm() {
        var $form = $(this),
            $fields = $form.find('[data-form-field]'),
            $submit = $form.find('[data-form-submit]');

        $form.attr('novalidate', true).on('submit', function (e) {
            e.preventDefault();
            if (validate($form)) {
                $submit.fadeOut();
                submitForm($form);
            }
        });

        $fields.filter('[required]').on('click keyup', function () {
            $(this).removeClass('invalid');
        });

        $submit.removeClass('disabled').prop('disabled', false);

        // numbers only in cardnumber field
        $fields.filter('[name="cardnumber"]').on('keypress', function (e) {
            if ((e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) || this.value.length > 18) {
                return false;
            }
        });

        // numbers only in zipcode field
        $fields.filter('[name="zipcode"]').on('keypress', function (e) {
            if ((e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) || this.value.length > 18) {
                return false;
            }
        });

        setupExpYear();
    }

    function setupExpYear() {
        // add years to expiration select
        var today = new Date(),
            thisYear = today.getFullYear(),
            options = [],
            totalYears = 10,
            i = 0;

        for (i = 0; i < totalYears; i += 1) {
            options.push(
                '<option value="' + thisYear + '">' + thisYear + '</option>'
            );
            thisYear += 1;
        }
        $('[data-form-field="expiryyear"]').html(options.join(''));
    }

    function validate($form) {
        var $fields = $form.find('[data-form-field][required]:visible'),
            isValid = true;

        $fields.each(function () {
            var $field = $(this);

            if (validateField($field) === false) {
                isValid = false;
            }
        });

        return isValid;
    }

    function validateField($field) {
        var isValid = true,
            fieldType = $field.attr('type') || '',
            fieldVal = $field.val() || '',
            regEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            $fieldParent = $field.parent(),
            validateType = $field.attr('data-form-field') || '',
            validateConfirm = $field.attr('data-form-confirm') || '',
            zipRe = /^\d{5}([\-]\d{4})?$/,
            cnRe = /^\d+$/;

        var cardResult;

        fieldType = fieldType.toLowerCase();
        validateType = validateType.toLowerCase();

        if (fieldVal.length === 0) {
            isValid = false;
        }
        else if (fieldType === 'email' && regEx.test(fieldVal) === false) {
            isValid = false;
        }
        else if (validateConfirm !== '' && fieldVal !== $('[name="' + validateConfirm + '"]').val()) {
            isValid = false;
        }
        else if (fieldType === 'checkbox' && $field[0].checked === false) {
            isValid = false;
        } else if (fieldType === 'radio' && $('[name="' + $field.attr('name') + '"]:checked').length === 0) {
            isValid = false;
        }
        else if (validateType === 'zipcode' && zipRe.test(fieldVal) === false) {
            isValid = false;
        }
        else if (validateType === 'cardnumber') {
            if (cnRe.test(fieldVal) === false) {
                isValid = false;
            }
            else {
                cardResult = $field.validateCreditCard();
                if (cardResult.valid !== true) {
                    isValid = false;
                }
            }

        }
        else if (validateType === 'expirymonth') {
            (function () {
                var today = new Date(),
                    expDate = new Date(),
                    $expYear = $('[data-form-field="expiryyear"]'),
                    expYear;

                if ($expYear.length > 0) {
                    expYear = $expYear.val();

                    expDate.setFullYear(expYear, fieldVal);

                    if (today.getTime() > expDate.getTime()) {
                        isValid = false;
                    }
                }
                else {
                    isValid = false;
                }
            })();
        }
        else if (validateType === 'dateyear') {
            (function () {
                // check valid date after today
                var today = new Date(),
                    thisDate = new Date(),
                    $selectGroup = $field.closest('[data-select-group]'),
                    $dateDay = $selectGroup.find('[data-form-field="dateday"]'),
                    $dateMonth = $selectGroup.find('[data-form-field="datemonth"]'),
                    monthArray = {
                        'January': 0,
                        'February': 1,
                        'March': 2,
                        'April': 3,
                        'May': 4,
                        'June': 5,
                        'July': 6,
                        'August': 7,
                        'September': 8,
                        'October': 9,
                        'November': 10,
                        'December': 11
                    },
                    month = typeof monthArray[$dateMonth.val()] !== 'undefined' ? monthArray[$dateMonth.val()] : (parseInt($dateMonth.val()) - 1);

                thisDate.setFullYear(fieldVal, month, $dateDay.val());
                thisDate.setHours(0, 0, 0, 0);
                today.setHours(0, 0, 0, 0);

                if (thisDate.getMonth() !== month || today.getTime() >= thisDate.getTime()) {
                    isValid = false;

                    $dateDay.addClass('invalid');
                    $dateMonth.addClass('invalid');
                }
            })();
        }
        else if (validateType === 'dobyear') {
            (function () {
                // check valid date
                var today = new Date(),
                    thisDate = new Date(),
                    $selectGroup = $field.closest('[data-select-group]'),
                    $dateDay = $selectGroup.find('[data-form-field="dobday"]'),
                    $dateMonth = $selectGroup.find('[data-form-field="dobmonth"]'),
                    monthArray = {
                        'January': 0,
                        'February': 1,
                        'March': 2,
                        'April': 3,
                        'May': 4,
                        'June': 5,
                        'July': 6,
                        'August': 7,
                        'September': 8,
                        'October': 9,
                        'November': 10,
                        'December': 11
                    },
                    month = monthArray[$dateMonth.val()] || (parseInt($dateMonth.val()) - 1);

                thisDate.setFullYear(fieldVal, month, $dateDay.val());
                thisDate.setHours(0, 0, 0, 0);
                today.setFullYear(today.getFullYear() - 18);
                today.setHours(0, 0, 0, 0);

                if (thisDate.getMonth() !== month || thisDate.getTime() > today.getTime()) {
                    isValid = false;

                    $dateDay.addClass('invalid');
                    $dateMonth.addClass('invalid');
                }
            })();
        }
        else if (validateType === 'endtime') {
            // check valid start and end time
            var startIndex = $('[data-form-field="starttime"]')[0].selectedIndex,
                endIndex = $field[0].selectedIndex;

            if (startIndex >= endIndex) {
                isValid = false;
            }
        }

        if (isValid === false) {
            if ($fieldParent.hasClass('select-custom') || fieldType === 'checkbox') {
                // custom select
                $fieldParent.addClass('invalid');
            }
            else {
                $field.addClass('invalid');
            }
        }
        else {
            if ($fieldParent.hasClass('select-custom') || fieldType === 'checkbox') {
                // custom select
                $fieldParent.removeClass('invalid');
            }
            else {
                $field.removeClass('invalid');
            }
        }

        return isValid;
    }

    function submitForm($form) {
        // submit form
        var url = $form.attr('action'),
            formType = $form.attr('data-form'),
            params = $form.serialize(),
            canSend = false;

        if (params === '') {
            $form.find('[name]').each(function (i) {
                var field = $(this),
                    param = field.attr('name') + '=' + field.val();
                if (i > 0) {
                    param = '&' + param;
                }
                params += param;
            });
        }

        switch (formType) {
            case 'contactus':
				/*if (pc.form.temp.cinema !== '' && pc.form.temp.cinema !== '0') {
					// {cinemaId}
					url = url + pc.form.temp.cinema;
					canSend = true;
				}*/

                if (pc.form.temp.cinema === '') {
                    pc.form.temp.cinema = '0';
                }

                url = url + pc.form.temp.cinema;
                canSend = true;
                break;
            case 'theatrerentals':
                if (pc.form.temp.cinema === '') {
                    pc.form.temp.cinema = '0';
                }

                url = url + pc.form.temp.cinema;
                newsletterCanSend = true;
                break;
            case 'subscription':
                if (pc.form.temp.cinema !== '' && pc.form.temp.cinema !== '0') {
                    // cinema/{cinemaId}
                    url = url + 'cinema/' + pc.form.temp.cinema;
                    canSend = true;
                }
                else if (pc.form.temp.region !== '' && pc.form.temp.region !== '0') {
                    // region/{regionId}
                    url = url + 'region/' + pc.form.temp.region;
                    canSend = true;
                }
                else {
                    // circuit
                    canSend = true;
                }
                break;
            case 'booking':
                if (typeof pc.book.submit !== 'undefined') {
                    pc.book.submit();
                }
                break;
            case 'giftcard':
                if (typeof pc.gc.step !== 'undefined') {
                    pc.gc.step();
                }
                break;
            case 'giftcard-check-cards':
                var $detailsForm = $('[data-form="giftcard-check-details"]');
                if (validate($detailsForm)) {
                    if (typeof pc.gc.addCards !== 'undefined') {
                        pc.gc.addCards();
                    }
                }
                else {
                    $('html,body').animate({
                        scrollTop: $('input.invalid').offset().top - 50
                    }, 500);
                }
                break;
            case 'giftcard-check-details':
                if (typeof pc.gc.selectGC !== 'undefined') {
                    pc.gc.selectGC();
                }
                break;
        }

        if (canSend) {
            $.ajax({
                url: url,
                type: 'POST',
                data: params,
                success: function (data) {
                    //console.log(data);
                    $form.hide();
                    $form.siblings('[data-form-success]').show();
                },
                error: function () {
                    $form.hide();
                    $form.siblings('[data-form-error]').show();
                    throw new Error("There has been an issue with the AJAX call");
                }
            });
        }

        if (typeof newsletterCanSend !== 'undefined' && newsletterCanSend === true) {

            var myFormTheatreRelease = document.getElementById('theatreRentalsForm');
            var formDataTheatreRelease = new FormData(myFormTheatreRelease);

            $.ajax({
                url: url,
                type: 'POST',
                data: formDataTheatreRelease,
                async: false,
                cache: false,
                contentType: false,
                processData: false
            })
                .done(function (data) {
                    $form.hide();

                    if (typeof data !== 'undefined' && data === true) {
                        var $confirmationHide = $('[data-confirmation-hide]');

                        if ($confirmationHide.length > 0) {
                            $confirmationHide.addClass('dn');
                            $("body").scrollTop(0);
                        }
                        $('[data-form-success]').removeClass('dn');
                    }
                    else {
                        $('[data-form-error]').removeClass('dn');
                    }
                })
                .fail(function () {
                    $form.hide();
                    $('[data-form-error]').removeClass('dn');

                    throw new Error("There has been an issue with the AJAX call");
                });
        }

    }

    function setupCustomSelect() {
        var timer = 0;

        $(document).on('focus', '[class*="select-"] select', function (e) {
            timer = 1;
            setTimeout(function () {
                timer = 0;
            }, 150);
        });

        $(document).on('click', '[class*="select-"] select', function (e) {
            if (timer === 0 && $(this).parent().hasClass('focus')) {
                $(this).trigger('blur');
            }
        });

        $(document).on('mousedown', '[class*="select-"] select', function (e) {
            $(this).parent().addClass('focus');
        });

        $(document).on('change', '[class*="select-"] select', function () {
            $(this).trigger('blur');
        });

        $(document).on('blur', '[class*="select-"] select', function () {
            $(this).parent().removeClass('focus');
        });
    }

    function setupCardNumbers() {
        var $cardnumber = $('[data-form-field="cardnumber"]');
        var $cardtype = $('[data-form-field="cardtype"]');

        if (typeof $().validateCreditCard === 'undefined' || $cardnumber.length === 0 || $cardtype.length === 0) {
            return;
        }

        $cardnumber.validateCreditCard(function (result) {
            if (typeof result !== 'undefined' && result !== null && typeof result.card_type !== 'undefined' && result.card_type !== null && $cardtype.find('[value="' + result.card_type.name + '"]').length === 1) {
                $cardtype.val(result.card_type.name);
            }
            else {
                $cardtype.val('');
            }
        });
    }

    function init() {
        $(function () {
            setup();
            setupCustomSelect();
            setupCardNumbers();
        });
    }

    init();


})(jQuery);

(function ($) {
    var $message = $('[data-contactus-message]');

    if ($message.length === 0) {
        return;
    }

    $message.each(function (index) {
        var $textarea = $(this),
            maxLength = parseInt($textarea.attr('maxlength') || 0);

        if (maxLength === 0) {
            return;
        }

        function updateCount() {
            $('[data-contactus-message-maxlength="' + index + '"]').html((maxLength - $textarea.val().length) + ' Characters Remaining');
        }

        $textarea.on('keyup', updateCount);

        $textarea.on('paste', null, function () {
            setTimeout(function () {
                updateCount();
            }, 20);
        });

        $textarea.before('<span class="formMessageCounter" data-contactus-message-maxlength="' + index + '"></span>').trigger('keyup');
    });

})(jQuery);;var pc = pc || {};

// geolocation
(function ($) {

	function getPos() {
		if ('geolocation' in navigator) {
			navigator.geolocation.getCurrentPosition(function (position) {
				$.get('/geolocation?latitude=' + position.coords.latitude + '&longitude=' + position.coords.longitude, function (link) {
					//console.log(link);

					if (link !== '' && link !== location.pathname) {
						// redirect user if there is a link and it does not match current page
						location = link;
					}

				});
			});
		}
	}

	function init() {
		if ($('[data-geo]').length > 0) {
			getPos();
		}
	}

	init();

})(jQuery);

// finder
// /LocationFindResults?cityStateOrZipCode=&region=&latitude=&longitude=
(function ($) {

    var searchUrl = '/';

	function setup() {
		var $region = $('[data-finder-region]'),
			$geo = $('[data-finder-geo]'),
			$searchInput = $('[data-finder-search-input]'),
			$searchBtn = $('[data-finder-search-btn]');

		if ($region.length > 0) {
			$region.on('change', function () {
				var thisVal = $(this).val() || '';

				if (thisVal !== '') {
					if (thisVal.indexOf('/') === 0) {
						window.location = thisVal;
					}
					else {
						window.location = searchUrl + thisVal;
					}
				}
			});
		}

		if ($geo.length > 0) {
			$geo.on('click', function (e) {
				e.preventDefault();

				if ('geolocation' in navigator) {
					navigator.geolocation.getCurrentPosition(function (position) {
						window.location = searchUrl + '?latitude=' + position.coords.latitude + '&longitude=' + position.coords.longitude;
					}, function (error) {
						var errorMsg = '';

						switch (error.code) {
							case error.PERMISSION_DENIED:
								errorMsg = 'Please allow permission to use location.';
								break;
							default:
								errorMsg = 'Sorry, we could not get your location at this time.';
								break;
						}

						alert(errorMsg);
					});
				}
				else {
					alert('If supported on your device please ensure geolocation is switched on.');
				}
			});
		}

		if ($searchInput.length > 0 && $searchBtn.length > 0) {
			$searchInput.on('keypress', function (e) {
				var searchVal = $(this).val() || '';
				if (e.which === 13 && searchVal !== '') {
					submitSearch(searchVal);
				}
			});

			$searchInput.on('focus', function (e) {
				var $this = $(this),
					thisPH = $this.attr('placeholder');

				if (typeof $this.data('ph') === 'undefined') {
					$this.data('ph', thisPH);
				}

				$this.attr('placeholder', '');
			});

			$searchInput.on('blur', function (e) {
				var $this = $(this);

				if ($this.val() === '') {
					$this.attr('placeholder', $this.data('ph'));
				}
			});

			$searchBtn.on('click', function (e) {
				e.preventDefault();
				var searchVal = $searchInput.val() || '';
				if (searchVal !== '') {
					submitSearch(searchVal);
				}
			});
		}
	}

	function submitSearch(searchVal) {
		var isValid = true,
			numRe = /^(\d+-?)+\d+$/,
			zipRe = /^\d{5}([\-]\d{4})?$/;
		
		if (searchVal && searchVal !== '') {
			if (numRe.test(searchVal)) {
				// zipcode
				//console.log('zip');
				isValid = zipRe.test(searchVal);
			}
			else if (searchVal.indexOf(',') > -1) {
				// city, state
				//console.log('city');
				isValid = true;
			}
			else {

				isValid = false;
			}
		}
		else {
			isValid = false;
		}

		if (isValid) {
			window.location = searchUrl + '?cityStateOrZipCode=' + searchVal;
		}
		else {
			alert('Please enter "City, State" or Zip');
		}
	}

	function init() {
		setup();
	}

	init();

})(jQuery);;
var pc = pc || {};

pc.book = {};

// booking functionality
(function ($) {

    var book = {};

    pc.book.submit = function () {
        submitBooking();
    };

    // setup objects
    book.page = {};
    book.currentpage = '';
    book.order = {};

    book.user = {};
    book.user.UserSessionId = null;

    book.cinemaid = '';
    book.sessionid = '';
    book.orderid = '';

    book.api = {};
    book.api.tickets = {};
    book.api.seats = {};

    book.tickets = {};

    book.seats = {};

    // templates
    book.temp = {};
    book.temp.tickets = '';
    book.temp.seats = '';
    book.temp.labels = '';
    book.temp.promo = '';
    book.temp.order = '';
    book.temp.film = '';
    book.temp.cinema = '';

    // data
    book.data = {};
    book.data.order = {};
    book.data.tickets = {};
    book.data.seats = {};
    book.data.cinema = {};

    book.basket = {};
    book.basket.tickets = [];

    function setup() {
        var urlPath = window.location.pathname,
            urlPathSplit = [];

        // /booking/cinema/{sessionid}
        // /booking/regent/641515 

        // get details
        if (urlPath.indexOf('/') > -1) {
            urlPathSplit = urlPath.split('/');

            if (urlPathSplit.length > 3) {
                book.sessionid = urlPathSplit[3];

                showLoad();

                // we need requirejs for booking api scripts
                $.when(
                    $.getScript(pc.api.booking + 'ClientScripts/require.js')
                ).done(function () {
                    // get booking api scripts
                    require.config({
                        paths: {
                            httprequest: pc.api.booking + 'ClientScripts/HTTPRequest',
                            peachlogger: pc.api.booking + 'ClientScripts/PeachLogger',
                            ticketbookingclient: pc.api.booking + 'ClientScripts/TicketBookingClient',
                            seatbooking: pc.api.booking + 'ClientScripts/SeatBooking',
                            sessionmanager: pc.api.booking + 'ClientScripts/SessionManager',
                            cors: '/themes/default/content/js/_cors'
                        }
                    });

                    define('jquery', [], function () {
                        return jQuery;
                    });

                    require([
                        'ticketbookingclient',
                        'seatbooking',
                        'cors'
                    ], function (ticketBookingClient, SeatBooking, cors) {

                        var $tabLinks = $('[data-tab-link]');

                        // update tab links click event to add disabled class to previous links
                        $tabLinks.on('click', function () {

                            $tabLinks.removeClass('back backNext');
                            $tabLinks.filter(':gt(' + $tabLinks.index($(this)) + ')').addClass('disabled');

                            switch (this.hash) {
                                case '#tickets':
                                    hideOrderExtras();
                                    break;
                                case '#seats':
                                case '#payment':
                                    $(this).addClass('backNext');
                                    $(this).prevAll('[data-tab-link]:not(".disabled")').first().addClass('back');
                                    break;
                            }
                        });

                        // we have booking api scripts, we can now proceed
                        book.api.tickets = ticketBookingClient;
                        book.api.seats = SeatBooking;

                        // setup order
                        setupOrder(true);

                    });
                }).fail(getError);
            }
        }
    }

    function changePage(page) {
        var $pages = $('[data-book-page]'),
            $curPage,
            $newPage,
            $tabLinks = $('[data-tab-link]'),
            newTab,
            $newTab,
            pageTitle = '';

        // check step exists then carry out function
        if (typeof book.page[page] !== 'undefined' && $pages.length > 0) {
            // call page function
            book.page[page]();
            // save current page
            book.currentpage = page;

            $curPage = $pages.filter('.active');
            $newPage = $pages.filter('[data-book-page="' + page + '"]');

            if ($newPage.hasClass('active') === false) {
                // make page active
                $curPage.removeClass('active');
                $newPage.addClass('active');

                // scroll to top of page
                window.scrollTo(0, 0);

                newTab = $newPage.attr('data-tab-item');
                $tabLinks.removeClass('active back backNext');
                $newTab = $tabLinks.filter('[href="' + newTab + '"]');
                $newTab.removeClass('disabled').addClass('active');

                switch (newTab) {
                    case '#seats':
                    case '#payment':
                        $newTab.addClass('backNext');
                        $newTab.prevAll('[data-tab-link]:not(".disabled")').first().addClass('back');
                        break;
                    case '#confirmation':
                        if (typeof peach.maps !== 'undefined' && typeof peach.maps.recenter !== 'undefined' && $('[data-map]').length > 0) {
                            peach.maps.recenter();
                        }
                        break;
                }
            }

            // tracking			
            switch (page) {
                case 'tickets':
                    pageTitle = 'Select Tickets';
                    break;
                case 'seats':
                    pageTitle = 'Choose Seats';
                    break;
                case 'payment':
                    pageTitle = 'Payment';
                    break;
                case 'confirmation':
                    // done in confirmationSuccess()
                    break;
                case 'error':
                    pageTitle = 'Error';
                    break;
                case 'timeout':
                    pageTitle = 'Timeout';
                    break;
            }

            if (pageTitle !== '' && typeof dataLayer !== 'undefined') {
                dataLayer.push({
                    'event': 'VirtualPageview',
                    'virtualPageURL': '/booking/' + page,
                    'virtualPageTitle': pageTitle
                });
            }
        }
    }

    function disableTabs(except) {
        var $tabLinks = $('[data-tab-link]');

        if (except) {
            $tabLinks = $tabLinks.not('[href="' + except + '"]');
        }

        $tabLinks.removeClass('active back backNext').addClass('disabled');
    }

    book.page.login = function () {
        disableTabs();

        hideLoad();
    };

    book.page.tickets = function () {
        var $ticketSubmit = $('[data-book-tickets-submit]');

        // ticket submit click event
        $ticketSubmit.off('click').on('click', function (e) {
            e.preventDefault();

            showLoad();

            // reset ticket basket
            book.basket.tickets.length = 0;

            // check if we have tickets selected
            var $quantity = $('[data-book-ticket-price]').filter(function () {
                var $this = $(this),
                    thisVal = $this.val() || 0,
                    thisType = $this.attr('data-book-ticket-type') || '',
                    thisPrice = $this.attr('data-book-ticket-price') || '',
                    thisRecognitionId = $this.attr('data-book-ticket-recognitionid') || '',
                    thisVoucherCode = $this.attr('data-book-ticket-vouchercode') || '',
                    ticket = [];

                if (thisVal > 0) {
                    ticket = new book.tickets.CreateTicketSelection(thisType, thisVal, thisPrice);
                    ticket.RecognitionId = thisRecognitionId;
                    ticket.VoucherCode = thisVoucherCode;
                    book.basket.tickets.push(ticket);
                    return true;
                }
                else {
                    return false;
                }
            });

            if ($quantity.length > 0) {
                // we have tickets
                saveTickets();
            }
            else {
                // no tickets selected
                hideLoad();
                alert('Please select a ticket');
            }
        });

        // get tickets
        book.tickets.GetTicketTypes(updateTickets, getError);

    };

    book.page.seats = function () {
        setupSeats();
        toggleInfo();
    };

    book.page.payment = function () {
        setupGiftCard();

        hideLoad();
        toggleInfo();
    };

    book.page.confirmation = function () {
        setupConfirmation();
        disableTabs('#confirmation');
        hideLoad();
    };

    book.page.timeout = function () {
        disableTabs();
        hideLoad();
    };

    book.page.error = function () {
        disableTabs();
        hideLoad();
    };

    book.page.ticketerror = function () {
        disableTabs();
        hideLoad();
    };

    function setupOrder(firstTime) {
        // get film data
        //$.getJSON(pc.api.movie + 'sessions/' + book.sessionid).done(function (data) {

        book.data.order = filmData;

        //console.log(book.data.order);

        // check we have template
        if (book.temp.order === '') {
            // get template
            $.get('/template?name=BookingOrder&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                // save template
                book.temp.order = template;
                addOrder();
            });
        }
        else {
            addOrder();
        }

        // check we have template
        if (book.temp.film === '') {
            // get template
            $.get('/template?name=BookingFilm&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                // save template
                book.temp.film = template;
                addFilm();
            });
        }
        else {
            addFilm();
        }

        if (firstTime) {
            //console.log(filmData.Sessions[0].Times[0].Screen);

            book.cinemaid = book.data.order.Sessions[0].Times[0].CinemaId;

            // create new booking api object
            book.tickets = new book.api.tickets(pc.api.booking + 'api/', book.cinemaid, book.sessionid, '', timeCountdown, timeOut);

            if (window.location.hash.indexOf('order=') > -1) {
                book.orderid = window.location.hash.substring(window.location.hash.indexOf('order=') + 6);
                // go to confirmation page
                changePage('confirmation');
            }
            else {
                // go to first page
                //changePage('login');
                changePage('tickets');
            }
        }

        //});
    }

    function addFilm() {
        var $film = $('[data-book-film]'),
            runtime,
            hour,
            min,
            release,
            expArray = [];

        if ($film.length > 0) {
            //console.log(book.data.order);

			/*if (book.data.order.RunTime) {
				// pRuntime
				// 2 hrs. 43 mins.
				runtime = parseFloat(book.data.order.RunTime);
				hour = Math.floor(runtime / 60);
				min = (runtime - (hour * 60));
				book.data.order.pRunTime = hour + ' hrs. ' + min + ' mins.';
				//book.data.order.pRunTime = runtime + ' mins';
			}*/

            if (book.data.order.ReleaseDate) {
                // pReleaseDate
                // mm/dd/yyyy
                release = new Date(book.data.order.ReleaseDate);
                book.data.order.pReleaseDate = (release.getMonth() + 1) + '/' + release.getDate() + '/' + release.getFullYear();
            }

            if (book.data.order.Sessions[0].Times[0].Experience) {
                for (var i = 0, exp = book.data.order.Sessions[0].Times[0].Experience, len = exp.length; i < len; i += 1) {
                    expArray.push(exp[i].Name);
                }

                book.data.order.pExperiences = expArray.join(', ');
            }

            // add film
            $film.html(Mustache.to_html(book.temp.film, book.data.order));
        }
    }

    function addOrder() {
        var $order = $('[data-book-order]');

        if ($order.length > 0) {

            if (book.data.order.Sessions[0].NewDate) {
                var tempDate = book.data.order.Sessions[0].NewDate.split('-');
                book.data.order.Sessions[0].pDate = tempDate[1] + '/' + tempDate[2] + '/' + tempDate[0];
            }

            // Add order.
            $order.html(Mustache.to_html(book.temp.order, book.data.order));

            toggleInfo();
        }
    }

    function updateOrder() {
        var $order = $('[data-book-order]');

        if ($order.length > 0) {
            // update order
            book.tickets.Initialise(null, function (data) {
                //console.log(data);

                updateTicketOrder(data);

                if (typeof data.AllocatedSeats !== 'undefined' && data.AllocatedSeats !== '') {
                    updateSeatsOrder(data.AllocatedSeats);
                }
            });
        }
    }

    function updateSeatsOrder(seats) {
        var allocatedSeats = '';
        if (seats) {
            allocatedSeats = seats;
        }

        $('[data-book-movie-seats-info]').html(allocatedSeats);
        $('[data-book-movie-seats]').show();
    }

    function updateTicketOrder(data) {
        var tickets = [],
            orderSubTotal = 0,
            orderTotal = 0,
            pTickets = [];

        if (typeof data.Tickets !== 'undefined') {
            pTickets = data.Tickets;
        }
        else if (typeof data.TicketsRequired !== 'undefined') {
            pTickets = data.TicketsRequired;
        }

        if (pTickets.length > 0) {
            // loop tickets
            $.each(pTickets, function (ticketIndex, ticketValue) {

                if (ticketValue.Quantity > 0) {
                    orderSubTotal += ticketValue.Quantity * ticketValue.Price;

                    tickets.push(
                        ticketValue.Quantity + ' x ' + ticketValue.DisplayName
                    );
                }
            });

            orderTotal = parseFloat(orderSubTotal + data.BookingFee);

            // add tickets to order
            if (tickets.length > 0) {
                $('[data-book-movie-tickets-info]').html(tickets.join('<br>'));
                $('[data-book-movie-tickets]').show();
            }

            // update order costs
            $('[data-book-movie-cost-subtotal]').html((parseFloat(orderSubTotal) / 100).toFixed(2));
            $('[data-book-movie-cost-charge]').html((parseFloat(data.BookingFee) / 100).toFixed(2));
            $('[data-book-movie-cost-total]').data('book-movie-cost-total', orderTotal).html((orderTotal / 100).toFixed(2));
            $('[data-book-movie-cost]').show();
            $('[data-gc-balance]').hide();
        }
    }

    function hideOrderExtras() {
        $('[data-book-movie-tickets]').hide();
        $('[data-book-movie-cost]').hide();
        $('[data-book-movie-seats]').hide();
    }

    function updateTickets(data) {

        if (data.TicketTypes.length > 0) {
            // we have tickets
            // create formatted price property
            $.each(data.TicketTypes, function (index, value) {
                data.TicketTypes[index].PriceFormatted = parseFloat(value.Price / 100).toFixed(2);
            });

            // save ticket data for later
            book.data.tickets = data;

            // check we have template
            if (book.temp.tickets === '') {
                // get template
                $.get('/template?name=BookingTickets&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                    // save template
                    book.temp.tickets = template;
                    addTickets();
                });
            }
            else {
                addTickets();
            }
        }
        else {
            // no tickets
            //console.log('no tickets');
            getError();
        }
    }

    function addTickets(data) {
        var $tickets = $('[data-book-tickets]'),
            $subtotal = $('[data-book-tickets-subtotal]'),
            $quantity;

        if ($tickets.length > 0) {
            // add tickets
            if (data) {
                $tickets.prepend(Mustache.to_html(book.temp.tickets, data));
            }
            else {
                $tickets.html(Mustache.to_html(book.temp.tickets, book.data.tickets));
            }

            $quantity = $('[data-book-ticket-price]');

            // quantity change event
            $quantity.off('change.quantity').on('change.quantity', function () {
                var total = 0;

                // add up quantities
                $quantity.each(function () {
                    var $this = $(this),
                        thisVal = $this.val(),
                        thisPrice = $this.attr('data-book-ticket-price');

                    if (thisVal > 0) {
                        total += (parseInt(thisPrice) * thisVal);
                    }
                });

                // update subtotal
                $subtotal.data('book-tickets-subtotal', total).html(parseFloat(total / 100).toFixed(2));
            });

            hideLoad();
        }
    }

    function saveTickets() {
        //console.log(book.basket.tickets);

        // save tickets
        book.tickets.AddTickets(book.basket.tickets, function () {

            book.seats = new book.api.seats(pc.api.booking + 'api/', book.tickets.orderState.CinemaId, book.tickets.orderState.SessionId, book.tickets.orderState.UserSessionId, book.tickets.orderState.OrderId);

            //check if need seatpicker
            book.seats.GetSeatData(function (data) {
                var showSeats = false,
                    cat = data.AreaCategories;

                //console.log(data);

                // check to see if we have seats to allocate
                if (typeof cat !== 'undefined' && cat.length > 0) {
                    for (var i = 0, len = cat.length; i < len; i += 1) {
                        if (typeof cat[i].SeatsToAllocate !== 'undefined' && cat[i].SeatsToAllocate > 0) {
                            showSeats = true;
                            break;
                        }
                    }
                }

                if (showSeats === true) {
                    // we have seating
                    // save for later
                    book.data.seats = data;
                    //console.log(data);
                    changePage('seats');
                }
                else {
                    // no seats					
                    changePage('payment');
                }

                updateOrder();

            }, getError);

        }, getError);
    }

    function setupSeats() {
        var $seatpicker = $('[data-book-seats]'),
            $seatContainer = $('[data-book-seats-container]'),
            $screen = $('[data-book-seats-screen]'),
            $theatre = $('[data-book-seats-theatre]'),
            $labels = $('[data-book-seats-labels]'),
            $seatNum = $('[data-book-seats-num]'),
            seatsToAllocate = [],
            seatWidth = 27,
            seatHeight = 27,
            theatreWidth = 0,
            theatreHeight = 0,
            allocatedSeats = [],
            theatreFactor = 0;

        // setup area object
        book.data.seats.pAreas = {};

        // setup allocated object
        book.data.seats.pAllocated = {};

        // setup all seats object
        book.data.seats.pAllSeats = {};

        if (typeof book.tickets.orderState.AllocatedSeats !== 'undefined') {
            allocatedSeats = book.tickets.orderState.AllocatedSeats.replace(/\s/g, '').split(',');
        }

        // loop to get factor to work out correct heights
        for (var areaIndex = 0, areaLen = book.data.seats.Area.length; areaIndex < areaLen; areaIndex += 1) {
            var area = book.data.seats.Area[areaIndex],
                tempFactor = (Math.round(area.SeatingContainerRows * seatHeight) / area.Height);

            if (tempFactor > theatreFactor) {
                theatreFactor = tempFactor;
            }
        }

        // loop areas
        $.each(book.data.seats.Area, function (areaIndex, areaValue) {
            var areaCols = areaValue.SeatingContainerColumns,
                areaRows = areaValue.SeatingContainerRows,
                curRow = 0,
                curCol = 0,
                areaWidth = Math.round(areaCols * seatWidth),
                areaHeight = Math.round(areaRows * seatHeight),
                hasSeats = false,
                tempRow = [],
                areaBottom = Math.round((theatreFactor * 100) * ((100 - areaValue.Height - areaValue.Top) / 100)),
                tempHeight = Math.round((theatreFactor * 100) * (areaValue.Height / 100)) + areaBottom,
                tempWidth = ((areaWidth / areaValue.Width) * 100);

            // check there are seats to allocate in area
            $.each(book.data.seats.AreaCategories, function (catIndex, catValue) {
                if (catValue.AreaCategoryCode === areaValue.AreaId) {
                    if (catValue.SeatsToAllocate > 0) {
                        hasSeats = true;
                    }
                    else {
                        areaValue.pHasNoSeats = true;
                    }
                    return false;
                }
            });

            // if no seats skip area
            if (hasSeats === false) {
                //return true;
            }

            // add description to area object
            book.data.seats.pAreas[areaValue.AreaId] = {
                "AreaDescription": areaValue.AreaDescription
            };

            //// update theatre width
            //if (areaWidth > theatreWidth) {
            //	theatreWidth = areaWidth;
            //}

            //// update theatre height
            //if (areaValue.Height === 100 && areaHeight > theatreHeight) {
            //	// area set to 100%
            //	theatreHeight = areaHeight;
            //}
            //else if (areaValue.Height !== 100) {
            //	// area not 100% so add to theatre height
            //	theatreHeight += areaHeight + seatHeight;
            //}

            // update theatre width and height
            if (book.data.seats.Area.length > 1) {
                // multiple area
                if (tempHeight > theatreHeight) {
                    theatreHeight = tempHeight;
                }

                if (tempWidth > theatreWidth) {
                    theatreWidth = tempWidth;
                }
            }
            else {
                // single area
                theatreHeight = areaHeight + areaBottom;

                theatreWidth = tempWidth;
            }

            // work out pHeight
            areaValue.pHeight = Math.round((theatreFactor * 100) * (areaValue.Height / 100)) + 'px';

            // work out pBottom	
            areaValue.pBottom = areaBottom + 'px';

            // work out pRight
            areaValue.pRight = Math.round(100 - areaValue.Width - areaValue.Left) + '%';

            // loop rows/columns converting objects to arrays
            // create label array
            areaValue.pLabelArray = [];
            for (curRow = 0; curRow < areaRows; curRow += 1) {
                tempRow[curRow] = {};
                tempRow[curRow].Seats = [];
                if (typeof areaValue.Rows['' + curRow] === 'undefined') {
                    for (curCol = 0; curCol < areaCols; curCol += 1) {
                        tempRow[curRow].Seats[curCol] = {};
                    }
                    areaValue.pLabelArray.push('');
                }
                else {
                    tempRow[curRow]['PhysicalName'] = areaValue.Rows['' + curRow]['PhysicalName'];

                    for (curCol = 0; curCol < areaCols; curCol += 1) {
                        if (typeof areaValue.Rows['' + curRow]['Seats']['' + curCol] === 'undefined') {
                            tempRow[curRow]['Seats'][curCol] = {};
                        }
                        else {
                            tempRow[curRow]['Seats'][curCol] = areaValue.Rows['' + curRow]['Seats']['' + curCol];
                        }
                    }
                    areaValue.pLabelArray.push(areaValue.Rows[curRow].PhysicalName);
                }
            }

            areaValue.Rows = tempRow;

            // loop rows
            $.each(areaValue.Rows, function (rowIndex, rowValue) {
                var curCol = 0;

                // loop through seats
                for (curCol = 0; curCol < areaCols; curCol += 1) {
                    // check if seats exist
                    if (typeof rowValue.Seats[curCol] === 'undefined') {
                        // add seat spacer
                        rowValue.Seats[curCol] = {};
                    }
                    else {
                        // check status
                        if (typeof rowValue.Seats[curCol].Status === 'undefined') {
                            // available
                            rowValue.Seats[curCol].Status = 0;
                        }

                        // check type
                        // unavailable and selected styled based on status so don't need specific pType
                        if (rowValue.Seats[curCol].Status === 6) {
                            // broken seat indicating exit
                            rowValue.Seats[curCol].pType = 'exit';
                            rowValue.Seats[curCol].Status = 1;
                        }
                        else if (rowValue.Seats[curCol].Type === 2) {
                            // standard area
                            // special/disabled seat
                            rowValue.Seats[curCol].pType = '4';
                        }
                        else if (rowValue.Seats[curCol].Priority === 3) {
                            rowValue.Seats[curCol].pType = '3';
                        }
                        else if (typeof rowValue.Seats[curCol].Style !== 'undefined') {
                            // sofa seats
                            switch (rowValue.Seats[curCol].Style) {
                                case 1:
                                    // sofa left
                                    rowValue.Seats[curCol].pType = '0_sofa_left';
                                    break;
                                case 2:
                                    // sofa mid
                                    rowValue.Seats[curCol].pType = '0_sofa_mid';
                                    break;
                                case 3:
                                    // sofa right
                                    rowValue.Seats[curCol].pType = '0_sofa_right';
                                    break;
                                default:
                                    // standard seats
                                    rowValue.Seats[curCol].pType = '0';
                                    break;
                            }
                        }
                        else {
                            // standard seats
                            rowValue.Seats[curCol].pType = '0';
                        }

                        // check if allocated
                        if (typeof rowValue.Seats[curCol].SeatName !== 'undefined' && allocatedSeats.length > 0 && allocatedSeats.indexOf(rowValue.Seats[curCol].SeatName) > -1) {
                            book.data.seats.pAllocated[rowValue.Seats[curCol].SeatName] = {
                                "SeatName": rowValue.Seats[curCol].SeatName,
                                "AreaCategoryCode": rowValue.Seats[curCol].AreaCategoryCode,
                                "AreaId": rowValue.Seats[curCol].AreaId,
                                "Column": rowValue.Seats[curCol].Column,
                                "Row": rowValue.Seats[curCol].Row,
                                "SeatId": rowValue.Seats[curCol].SeatId,
                                "Type": rowValue.Seats[curCol].Type
                            };
                        }

                        // add to all seats object
                        book.data.seats.pAllSeats[rowValue.Seats[curCol].SeatName] = {
                            "SeatName": rowValue.Seats[curCol].SeatName,
                            "AreaCategoryCode": rowValue.Seats[curCol].AreaCategoryCode,
                            "AreaId": rowValue.Seats[curCol].AreaId,
                            "Column": rowValue.Seats[curCol].Column,
                            "Row": rowValue.Seats[curCol].Row,
                            "SeatId": rowValue.Seats[curCol].SeatId,
                            "Type": rowValue.Seats[curCol].Type
                        };
                    }
                }

                // create seats array
                rowValue.pSeatsArray = rowValue.Seats;
            });

            // create row array
            areaValue.pRowsArray = areaValue.Rows;
        });

        // update screen width
        $screen.width(theatreWidth + seatWidth);
        // update seat container width
        $seatContainer.width(theatreWidth + seatWidth);
        // update theatre width
        $theatre.width(theatreWidth);
        // update label width
        $labels.width(seatWidth);

        // update seat container height
        $seatContainer.height(theatreHeight);

        // update seat num
        $.each(book.data.seats.AreaCategories, function (catIndex, catValue) {
            if (catValue.SeatsToAllocate > 0) {
                // add seat allocation to area object
                for (var catValueItem in catValue) {
                    book.data.seats.pAreas[catValue.AreaCategoryCode][catValueItem] = catValue[catValueItem];
                }

                seatsToAllocate.push(
                    '<span data-book-seats-num-area="' + catValue.AreaCategoryCode + '">' + catValue.SeatsAllocatedCount + '</span>/' + catValue.SeatsToAllocate + ' ' + book.data.seats.pAreas[catValue.AreaCategoryCode].AreaDescription
                );
            }
        });
        $seatNum.html(seatsToAllocate.join('<br>'));

        // check we have template
        if (book.temp.seats === '') {
            // get template
            $.get('/template?name=BookingSeats&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                // save template
                book.temp.seats = template;
                addSeats();
            });
        }
        else {
            addSeats();
        }

        // check we have template
        if (book.temp.labels === '') {
            // get template
            $.get('/template?name=BookingSeatsLabels&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                // save template
                book.temp.labels = template;
                addLabels();
            });
        }
        else {
            addLabels();
        }
    }

    function addSeats() {
        var $theatre = $('[data-book-seats-theatre]'),
            allocatedSeats = [],
            $seats,
            $submit = $('[data-book-seats-submit]');

        $('[data-recliner]').hide();


        if ($theatre.length > 0) {
            $theatre.html(Mustache.to_html(book.temp.seats, book.data.seats));

            // update status of allocated seats
            $.each(book.data.seats.pAllocated, function (selIndex, selValue) {
                $('[data-book-seats-seatname="' + selIndex + '"]').attr('data-book-seats-status', 5);
                allocatedSeats.push(selIndex);

            });

            // update seat order
            allocatedSeats.sort(sortAlphaNum);
            updateSeatsOrder(allocatedSeats.join(', '));

            // redefine seats jquery object
            $seats = $('[data-book-seats-seatname]').not('[data-book-seats-status="1"]').not('[data-book-seats-status="7"]');

            $seats.each(function () {
                var seatPriority = $(this).attr('data-book-seats-priority');

                if (seatPriority === '3') {
                    $('[data-recliner]').show();
                    return false;
                }

            });

            // add companion seats
            // loop disabled seats and look for seats next to
			/*$seats.filter('.book-seats-seat-4').each(function () {

				var $seat = $(this),
					seatid = $seat.attr('data-book-seats-seatid'),
					seatidA,
					$prev,
					$next;
				
				if (typeof seatid !== 'undefined') {
					seatidA = seatid.split('|');
					if (seatidA.length > 3) {
						$prev = $('[data-book-seats-seatid="' + seatidA[0] + '|' + seatidA[1] + '|' + seatidA[2] + '|' + (parseInt(seatidA[3]) + 1) + '"].book-seats-seat-0');
						$next = $('[data-book-seats-seatid="' + seatidA[0] + '|' + seatidA[1] + '|' + seatidA[2] + '|' + (parseInt(seatidA[3]) - 1) + '"].book-seats-seat-0');

						if ($prev.length > 0) {
							$prev.removeClass('book-seats-seat-0').addClass('book-seats-seat-c-4');
						}
						else if ($next.length > 0) {
							$next.removeClass('book-seats-seat-0').addClass('book-seats-seat-c-4');
						}
					}
				}
			});*/

            // seat click event
            $seats.off('click').on('click', function (e) {
                var $this = $(this),
                    seatName = $this.attr('data-book-seats-seatname'),
                    seatStatus = $this.attr('data-book-seats-status'),
                    seatPriority = $this.attr('data-book-seats-priority'),
                    proceed = true;

                if (seatStatus !== '5') {
                    // disabled seat message
                    if ($this.hasClass('book-seats-seat-4')) {
                        proceed = confirm('You have selected an access space designated for disabled individuals. THIS IS NOT A SEAT. Ok to select, CANCEL to make a different selection.');
                    }

                    // companion seat message
                    if (seatPriority === '4' || seatPriority === '2') {
                        proceed = confirm('You have selected a seat designated for companions of disabled individuals, who require accessible seating because of a mobility disability. OK to select, CANCEL to choose another seat.');
                    }

                    // reclining seat message
                    //if (seatPriority === '3') {
                    //    proceed = confirm('You have selected a reclining seat. OK to select, CANCEL to choose another seat.');
                    //}
                }

                if (proceed) {
                    changeSeat(seatName);
                }
            });

            // submit click event
            $submit.off('click').on('click', function (e) {
                e.preventDefault();

                var seatSelection = [];

                showLoad();

                if (validateSeats()) {
                    $.each(book.data.seats.pAllocated, function (selIndex, selValue) {
                        seatSelection.push(selValue);
                    });

                    book.seats.ConfirmSeats(seatSelection, function () {
                        changePage('payment');
                    },
                        getError);
                }
            });

            hideLoad();
        }
    }

    function addLabels() {
        var $labels = $('[data-book-seats-labels]');

        if ($labels.length > 0) {
            $labels.html(Mustache.to_html(book.temp.labels, book.data.seats));
        }
    }

    function changeSeat(seatName) {
        var $seat = $('[data-book-seats-seatname="' + seatName + '"]'),
            seatObj = book.data.seats.pAllSeats[seatName],
            seatArea = seatObj.AreaCategoryCode,
            allocatedSeats = [];

        // check seat exits and area has seats to allocate
        if ($seat.length > 0 && book.data.seats.pAreas[seatArea].SeatsToAllocate > 0) {

            if (typeof book.data.seats.pAllocated[seatName] !== 'undefined') {
                // seat already allocated

                // change status
                $seat.attr('data-book-seats-status', '0');

                // update area allocated count
                book.data.seats.pAreas[seatArea].SeatsAllocatedCount -= 1;
                book.data.seats.pAreas[seatArea].SeatsNotAllocatedCount += 1;

                // remove from allocated object
                delete book.data.seats.pAllocated[seatName];
            }
            else {
                // seat not allocated

                // check if we have reached allocated limit and deselect other seats in area
                if (book.data.seats.pAreas[seatArea].SeatsNotAllocatedCount === 0) {

                    $('[data-book-seats-status="5"]').each(function () {
                        var $selSeat = $(this),
                            selSeatName = $selSeat.attr('data-book-seats-seatname'),
                            selSeatObj = book.data.seats.pAllSeats[selSeatName];

                        // double check seat is allocated and is in correct area
                        if (book.data.seats.pAllocated[selSeatName] !== 'undefined' && selSeatObj.AreaCategoryCode === book.data.seats.pAreas[seatArea].AreaCategoryCode) {
                            // update status
                            $selSeat.attr('data-book-seats-status', '0');
                            // remove from allocated object
                            delete book.data.seats.pAllocated[selSeatName];
                        }
                    });

                    // update area allocated count
                    book.data.seats.pAreas[seatArea].SeatsAllocatedCount = 0;
                    book.data.seats.pAreas[seatArea].SeatsNotAllocatedCount = book.data.seats.pAreas[seatArea].SeatsToAllocate;
                }

                // change status
                $seat.attr('data-book-seats-status', '5');

                // update area allocated count
                book.data.seats.pAreas[seatArea].SeatsAllocatedCount += 1;
                book.data.seats.pAreas[seatArea].SeatsNotAllocatedCount -= 1;

                // add to allocated object
                book.data.seats.pAllocated[seatName] = seatObj;
            }

            // update area allocated count
            $('[data-book-seats-num-area="' + seatObj.AreaCategoryCode + '"]').html(book.data.seats.pAreas[seatArea].SeatsAllocatedCount);

            // update seat order
            for (var seat in book.data.seats.pAllocated) {
                allocatedSeats.push(seat);
            }
            allocatedSeats.sort(sortAlphaNum);
            //console.log(allocatedSeats);
            updateSeatsOrder(allocatedSeats.join(', '));
        }
    }

    function validateSeats() {
        var isValid = true,
            error = '',
            messages = {};

        messages = {
            'missing': 'Please select another {{number}} seat(s).',
            'gap': 'Please ensure that you do not leave a single gap between seats.',
            'default': 'Please check your seat selection.'
        };

        if (isValid) {
            // loop areas
            $.each(book.data.seats.pAreas, function (areaIndex, areaValue) {
                // check area is bookable
                if (areaValue.SeatsToAllocate > 0) {
                    // check all seats are allocated
                    if (areaValue.SeatsNotAllocatedCount !== 0) {
                        // is valid false
                        isValid = false;
                        // update error message
                        error = messages['missing'].toString().replace('{{number}}', areaValue.SeatsNotAllocatedCount);
                        // exit each
                        return false;
                    }
                }
            });
        }

        if (isValid) {
            // loop allocated seats
            $.each(book.data.seats.pAllocated, function (seatIndex, seatValue) {
                var $seat = $('[data-book-seats-seatname="' + seatValue.SeatName + '"]'),
                    $prev1 = $('[data-book-seats-seatid="' + seatValue.AreaCategoryCode + '|' + seatValue.AreaId + '|' + seatValue.Row + '|' + (seatValue.Column + 1) + '"]').not('[data-book-seats-status="1"]').not('[data-book-seats-status="5"]'),
                    $prev2 = $('[data-book-seats-seatid="' + seatValue.AreaCategoryCode + '|' + seatValue.AreaId + '|' + seatValue.Row + '|' + (seatValue.Column + 2) + '"][data-book-seats-status="5"]'),
                    $next1 = $('[data-book-seats-seatid="' + seatValue.AreaCategoryCode + '|' + seatValue.AreaId + '|' + seatValue.Row + '|' + (seatValue.Column - 1) + '"]').not('[data-book-seats-status="1"]').not('[data-book-seats-status="5"]'),
                    $next2 = $('[data-book-seats-seatid="' + seatValue.AreaCategoryCode + '|' + seatValue.AreaId + '|' + seatValue.Row + '|' + (seatValue.Column - 2) + '"][data-book-seats-status="5"]');

                // check if there is a gap
                if (($prev1.length === 1 && $prev2.length === 1) || ($next1.length === 1 && $next2.length === 1)) {
                    // is valid false
                    isValid = false;
                    // update error message
                    error = messages['gap'];
                    // exit each
                    return false;
                }
            });
        }

        // there was an error
        if (isValid === false) {
            // check for error message
            if (error !== '') {
                // display error message
                alert(error);
            }
            else {
                // display default error message
                alert(messages['default']);
            }
            hideLoad();
        }

        return isValid;
    }

    function submitBooking() {
        var paymentDetails = {},
            $fields = $('[data-form-field]'),
            isValid = true;

        showLoad();

        paymentDetails['CustomerDetails'] = {};
        paymentDetails['Payment'] = {};

        // get form fields and populate payment details
        $fields.each(function () {
            var $field = $(this),
                fieldType = $field.attr('name'),
                fieldVal = $field.val(),
                url = [];

            if (fieldVal !== '') {
                switch (fieldType) {
                    case 'newslettersignup':
                        // newsletter signup
                        if ($field.is(':checked')) {
                            url.length = 0;
                            url.push(
                                '/api/subscription/cinema/',
                                book.cinemaid,
                                '?name=',
                                $fields.filter('[name="name"]').val(),
                                '&email=',
                                $fields.filter('[name="email"]').val()
                            );

                            $.ajax({
                                url: url.join(''),
                                type: 'POST'
                            });
                        }
                        break;
                    case 'email':
                        paymentDetails['CustomerDetails']['Email'] = fieldVal;
                        break;
                    case 'zipcode':
                        paymentDetails['CustomerDetails']['ZipCode'] = fieldVal;
                        break;
                    case 'gc':
                        // only add gift card value if it has been validated
                        if ($field.closest('[data-gc-row]').hasClass('valid')) {
                            paymentDetails['GiftCard'] = {};
                            paymentDetails['GiftCard']['Number'] = fieldVal;
                        }
                        else if ($field.closest('[data-gc-row]').hasClass('checked') === false) {
                            getError({ 'responseText': '{"PeachErrorCode":"999"}' });
                            isValid = false;
                            return false;
                        }
                        break;
                    case 'name':
                        paymentDetails['Payment']['CardName'] = fieldVal;
                        break;
                    case 'cardtype':
                        paymentDetails['Payment']['CardType'] = fieldVal;
                        break;
                    case 'cardnumber':
                        paymentDetails['Payment']['Number'] = fieldVal;
                        break;
                    case 'expirymonth':
                        paymentDetails['Payment']['ExpiryMonth'] = fieldVal;
                        break;
                    case 'expiryyear':
                        paymentDetails['Payment']['ExpiryYear'] = fieldVal;
                        break;
                    case 'cvc':
                        paymentDetails['Payment']['CVC'] = fieldVal;
                        break;
                }
            }
        });

        if (isValid) {
            // submit booking
            book.tickets.CompletePayment(
                paymentDetails,
                paymentSuccess,
                getError
            );
        }
    }

    function paymentSuccess(data) {
        book.orderid = data.ExternalOrderId;
        //console.log(book.orderid);
        window.location.hash = "order=" + book.orderid;
        // redirect to confirmation page
        changePage('confirmation');
    }

    function setupConfirmation() {
        // setup confirmation page
        // check we have the cinema and order ids
        if (book.cinemaid !== '' && book.orderid !== '') {
            // get order details
            book.tickets.GetCompleteOrder(book.cinemaid, book.orderid, confirmationSuccess, getError);
        }
        else {
            getError();
        }
    }

    function confirmationSuccess(data) {
        var seats = [],
            selSeats,
            selSeatsLen,
            i = 0;

        book.data.order = $.extend({}, book.data.order, data);

        //console.log(data);

        // update ticket order
        updateTicketOrder(data);

        // update seat order
        if (typeof data.SelectedSeats !== 'undefined') {
            selSeats = data.SelectedSeats;
            selSeatsLen = selSeats.length;

            if (selSeatsLen > 0) {
                for (i = 0; i < selSeatsLen; i += 1) {
                    seats.push(selSeats[i].SeatName);
                }

                updateSeatsOrder(seats.join(' '));
            }
        }

        // update booking ref
        if (typeof data.BookingReference !== 'undefined') {
            $('[data-book-movie-bookingnumber-info]').html(data.BookingReference);
            $('[data-book-movie-bookingnumber]').show();
            $('[data-book-qr]').attr('src', '/barcode?scale=3&data=' + data.BookingReference).removeClass('dn');
        }

        if (typeof data.BookingConfirmationId !== 'undefined') {
            $('[data-book-movie-bookingid-info]').html(data.BookingConfirmationId);
            $('[data-book-movie-bookingid]').show();
        }

        // Build the print email url.
        $('[data-book-print]').attr('href', (pc.rooturl + "Booking/ConfirmationEmailPage/" + book.cinemaid + "/" + book.orderid));
        $('[data-book-print]').removeClass('dn');
        //GA tracking using doccookies

        var cookieSet = false;

        if (typeof data !== 'undefined') {
            // check if we have cookie as only want to do this part once
            if (typeof docCookies !== 'undefined' && docCookies.getItem('gaOrderId' + data.BookingReference) !== null) {
                cookieSet = true;
            }

            if (cookieSet === false) {
                if (typeof docCookies !== 'undefined') {
                    docCookies.setItem('gaOrderId' + data.BookingReference, data.BookingReference, Infinity);
                }

                var products = [];

                for (var i2 = 0; i2 < data.Tickets.length; i2++) {
                    products.push({
                        'id': filmData.FilmId,
                        'name': filmData.Title,
                        'category': 'films',
                        'price': parseFloat(data.Tickets[i2].Price / 100).toFixed(2),
                        'quantity': data.Tickets[i2].Quantity,
                        'variant': data.Tickets[i2].DisplayName
                    });
                }

                if (typeof data.BookingFee !== 'undefined' && data.BookingFee > 0) {
                    products.push({
                        'id': '0',
                        'name': 'Booking Fee',
                        'category': 'films',
                        'price': parseFloat(data.BookingFee / 100).toFixed(2),
                        'quantity': '1',
                        'variant': 'Booking Fee'
                    });
                }

                if (typeof dataLayer !== 'undefined') {
                    dataLayer.push({
                        'event': 'VirtualPageview',
                        'virtualPageURL': '/booking/confirmation',
                        'virtualPageTitle': 'Confirmation',
                        'stepName': 'confirmation',
                        'ecommerce': {
                            'purchase': {
                                'actionField': {
                                    'id': data.BookingConfirmationId,
                                    'revenue': (parseFloat(data.GrandTotal) / 100).toFixed(2)
                                },
                                'products': products
                            }
                        }
                    });
                }

                if (typeof fbq !== 'undefined') {
                    fbq('track', 'Purchase', {
                        value: (parseFloat(data.GrandTotal) / 100).toFixed(2),
                        currency: 'USD'
                    });
                }

                (function () {
                    window.ScarabQueue = window.ScarabQueue || [];

                    (function (id) {
                        if (document.getElementById(id)) return;
                        var js = document.createElement('script'); js.id = id;
                        js.src = '//cdn.scarabresearch.com/js/1A2FE2AD76C11C89/scarab-v2.js';
                        var fs = document.getElementsByTagName('script')[0];
                        fs.parentNode.insertBefore(js, fs);
                    })('scarab-js-api');

                    if (typeof data.EmailAddress !== 'undefined' && data.EmailAddress !== null) {
                        ScarabQueue.push([
                            'setEmail',
                            data.EmailAddress
                        ]);
                    }

                    ScarabQueue.push(['cart', []]);

                    ScarabQueue.push(['purchase', {
                        orderId: data.BookingConfirmationId,
                        items: [{
                            'item': [
                                $('[data-id-region]').attr('data-id-region'),
                                data.ExternalCinemaId,
                                filmData.FilmId
                            ].join('_'),
                            'quantity': data.Tickets.reduce(function (a, c) {
                                return a + c.Quantity;
                            }, 0),
                            'price': parseFloat((data.GrandTotal / 100).toFixed(2))
                        }]
                    }]);

                    ScarabQueue.push(['go']);
                })();
            }
            else {
                if (typeof dataLayer !== 'undefined') {
                    dataLayer.push({
                        'event': 'VirtualPageview',
                        'virtualPageURL': '/booking/confirmation-repeat',
                        'virtualPageTitle': 'Confirmation Repeat'
                    });
                }
            }
        }
    }

    function setupGiftCard() {
        // gift card redemption

        var $row = $('[data-gc-row]').not('[data-gc-row="setup"]');
        var $rowSetup = $('[data-gc-row="setup"]');

        if ($row.length > 0) {
            $row.each(setupGiftCardRow);
        }

        if ($rowSetup.length > 0) {
            $rowSetup.each(function () {
                var $thisRow = $(this);
                var $input = $thisRow.find('[data-gc-input]');
                var $btn = $thisRow.find('[data-gc-check]');

                // validate gift card field if there is a value when payment page loads
                if ($input.val() !== '') {
                    $btn.trigger('click.gc');
                }
            });
        }
    }

    function setupGiftCardRow() {
        var $row = $(this),
            $input = $row.find('[data-gc-input]'),
            $btn = $row.find('[data-gc-check]'),
            $msg = $row.find('[data-gc-message]'),
            $pay = $('[data-gc-pay]'),
            $valid = $row.find('[data-gc-valid]'),
            paymentFields = null;

        // 76*** regular card 14 characters
        var gcRegular = ['75', '76', '77'];
        // 70*** egift cards with 18 characters
        var gcEGift = ['70'];

        function removeGCMessage() {
            // clear messages
            $row.removeClass('valid invalid checked');
            $input.removeClass('invalid');
            $msg.html('');
        }

        function showCC() {
            // show cc
            if (paymentFields) {
                $pay.html(paymentFields);
                paymentFields = null;
            }
        }

        function showGCError() {
            var msg = 'Sorry, this card number isn\'t valid or there is no available balance.';

            $row.addClass('invalid');
            $input.addClass('invalid');
            $msg.html(msg);
            showGCBalance(0);
            showCC();
            hideLoad();
        }

        function showGCSuccess(balance) {
            var msg = 'Please pay the remaining ${{balance}}.';

            if (typeof balance !== 'undefined') {
                msg = msg.replace('{{balance}}', (parseFloat(balance) / 100).toFixed(2));
                $msg.html(msg);
            }
            else {
                $msg.html('');
            }

            $row.addClass('valid');
            hideLoad();
        }

        function showGCBalance(balance) {
            if (typeof balance !== 'undefined') {
                var cardValue = parseFloat(balance),
                    total = parseFloat($('[data-book-movie-cost-total]').data('book-movie-cost-total') || 0),
                    newTotal = 0;

                if (total !== 0) {
                    newTotal = total - cardValue;

                    $('[data-gc-balance-cost]').html((cardValue / 100).toFixed(2));

                    $('[data-book-movie-cost-total]').html((newTotal / 100).toFixed(2));

                    if (cardValue !== 0) {
                        $('[data-gc-balance]').show();
                    }
                    else {
                        $('[data-gc-balance]').hide();
                    }
                }
            }
        }

        function checkGC() {
            var inputVal = $input.val() || '';

            inputVal = inputVal.replace(/\s+/g, '');

            if (inputVal !== '') {
                showLoad();

                // check if value is numeric
                if ($.isNumeric(inputVal) === false) {
                    showGCError();
                    return false;
                }

                // check character length
                var inputValFirstTwo = inputVal.slice(0, 2);



                if (gcRegular.indexOf(inputValFirstTwo) > -1 && inputVal.length !== 14) {
                    showGCError();
                    return false;
                }

                if (gcEGift.indexOf(inputValFirstTwo) > -1 && inputVal.length !== 18) {
                    showGCError();
                    return false;
                }

                book.tickets.GetGiftCardDetails(inputVal, function (data) {
                    /*{"Id":"12312312312","BalanceRemaining":"500"}*/

                    var cardValue = 0,
                        total = 0,
                        dif = 0,
                        used = 0;

                    // check we have balance
                    if (data && typeof data['BalanceRemaining'] !== 'undefined') {

                        cardValue = parseFloat(data['BalanceRemaining']);
                        total = parseFloat($('[data-book-movie-cost-total]').data('book-movie-cost-total') || 0);

                        if (cardValue !== 0 && total !== 0) {
                            dif = cardValue - total;

                            if (dif >= 0) {
                                // hide cc
                                paymentFields = $pay.children().detach();
                                showGCSuccess();
                                used = cardValue - dif;
                            }
                            else {
                                showCC();
                                dif = (dif * -1);
                                showGCSuccess(dif);
                                used = cardValue;
                            }

                            showGCBalance(used);

                            // make gc required field
                            //$input.attr('required', '');
                        }
                        else {
                            showGCError();
                        }
                    }
                    else {
                        showGCError();
                    }
                }, showGCError);
            }
            else {
                showGCError();
            }
        }

        $input.on('keyup paste', function (e) {
            removeGCMessage();

            if (e.type === 'paste') {
                var newValue = e.originalEvent.clipboardData.getData('text').trim();

                $input.attr('maxlength', gcRegular.indexOf(newValue.slice(0, 2)) > -1 ? 14 : 18);

                this.value = newValue;
            }
            else {
                $input.attr('maxlength', gcRegular.indexOf(this.value.slice(0, 2)) > -1 ? 14 : 18);
            }

            if (this.value !== '' && $.isNumeric(this.value) === false) {
                $row.addClass('invalid');
                $input.addClass('invalid');
            }

            showCC();

            showGCBalance(0);
        });

        $valid.on('click.gc', function (e) {
            e.preventDefault();
            if ($row.hasClass('invalid')) {
                $input.val('');
                removeGCMessage();
            }
        });

        $btn.on('click.gc', function (e) {
            e.preventDefault();
            $row.addClass('checked');
            checkGC();
        });

        $row.attr('data-gc-row', 'setup');
    }

    function timeCountdown(time) {
        // timer
		/*var $timer = $('[data-book-timer]'),
				min = Math.floor(time/60),
				sec = (time - min * 60);

		sec = sec < 10 ? '0' + sec : sec;

		$timer.html(min + ':' + sec);*/
    }

    function timeOut() {
        // time has ellapsed
        // hide timer
        //$('[data-book-timer]').hide();

        // show timeout page
        changePage('timeout');
    }

    function showLoad() {
        $('[data-book-load]').show();
    }

    function hideLoad() {
        $('[data-book-load]').hide();
    }

    function toggleInfo() {
		/*var $btn = $('[data-book-order] [data-toggle-btn]:visible');

		if ($btn.length > 0) {
			// check which booking page we are on
			switch (book.currentpage) {
				case 'tickets':
				case 'confirmation':
					// show order			
					$('[data-toggle-btn]').trigger('click');
					break;
				default:
					// hide order
					if ($btn.hasClass('active')) {
						$btn.trigger('click');
					}
					break;
			}
		}*/
    }

    function getError(a, b, c) {
        var $error = $('[data-error]');
        var $formError = $('[data-form-error]');
        var errorData = {};
        var error = '';
        var showContactUs = false;
        var showErrorPage = true;
        var defaultMessage = pc.errorCode.defaultMessage;

        if (typeof pc.errorCode !== 'undefined') {
            if (typeof a !== 'undefined' && typeof a.responseText !== 'undefined') {
                errorData = JSON.parse(a.responseText);
            }

            switch (book.currentpage) {
                case 'tickets':
                    defaultMessage = pc.errorCode.defaultMessageTickets;


                    break;
                case 'seats':
                    defaultMessage = pc.errorCode.defaultMessageSeats;
                    break;
                case 'payment':
                    defaultMessage = pc.errorCode.defaultMessagePayment;
                    showErrorPage = false;

                    // reset form payment details
                    $('[data-form-field][name="cardnumber"]').val('');
                    $('[data-form-field][name="expirymonth"]').val('');
                    $('[data-form-field][name="expiryyear"]').val('');
                    $('[data-form-field][name="cardtype"]').val('');
                    $('[data-form-field][name="cvc"]').val('');

                    // reshow submit button
                    $('[data-form-submit]').stop().show();

                    break;
            }

            if (typeof errorData.ProviderErrorCode !== 'undefined' && errorData.ProviderErrorCode !== null && typeof pc.errorCode.vista !== 'undefined' && typeof pc.errorCode.vista[errorData.ProviderErrorCode] !== 'undefined') {
                error = pc.errorCode.vista[errorData.ProviderErrorCode].message;
                showContactUs = pc.errorCode.vista[errorData.ProviderErrorCode].showContactUs;
            }
            else if (typeof errorData.PeachCode !== 'undefined' && errorData.PeachCode !== null && typeof pc.errorCode.peach !== 'undefined' && typeof pc.errorCode.peach[errorData.PeachCode] !== 'undefined') {
                error = pc.errorCode.peach[errorData.PeachCode].message;
                showContactUs = pc.errorCode.peach[errorData.PeachCode].showContactUs;
            }
            
            if (error === '' && typeof defaultMessage !== 'undefined') {
                error = defaultMessage.message;
                showContactUs = defaultMessage.showContactUs;
            }

            if (showErrorPage) {
                $('[data-error-contact]').toggleClass('dn', showContactUs === false);
                $error.html(error);
                changePage('error');
            }
            else {                
                // update form error message
                $formError.html('<p>' + error + '</p>').show();
                hideLoad();
            }
        }
    }

    // function to sort alphanumerically
    function sortAlphaNum(a, b) {
        var aA = a.replace(/[^a-zA-Z]/g, "");
        var bA = b.replace(/[^a-zA-Z]/g, "");
        if (aA === bA) {
            var aN = parseInt(a.replace(/[^0-9]/g, ""), 10);
            var bN = parseInt(b.replace(/[^0-9]/g, ""), 10);
            return aN === bN ? 0 : aN > bN ? 1 : -1;
        } else {
            return aA > bA ? 1 : -1;
        }
    }

    function init() {
        var $book = $('[data-book]');

        // check we are on booking page
        if ($book.length > 0) {
            setup();
        }
    }

    init();

})(jQuery);;// refund ticket functionality
(function ($) {
    var $refundAmount = $('[data-refund-amount]');
    var refAmtCents;
    var refAmtDollars;

    if ($refundAmount.length === 0) {
        return;
    }

    refAmtCents = $refundAmount.data('refundAmount');
    refAmtDollars = parseFloat(refAmtCents / 100).toFixed(2);

    $refundAmount.text(refAmtDollars);  
})(jQuery);

(function () {
    var refund_form = document.getElementById('refund_form');
    var refund_form_submit = document.getElementById('refund_form_submit');

    if (refund_form === null || refund_form_submit === null) {
        return;
    }

    refund_form.addEventListener('submit', function (e) {
        refund_form_submit.disabled = true;
    });
})();;(function ($) {
    function truncate(string, newLength) {
        if (string.length > newLength)
            return string.substring(0, newLength);
        else
            return string;
    };

    $(".dates .month").each(function (index) {

        var monthCopy = $(this).text();

        $(this).text(truncate(monthCopy, 3));

    });

})(jQuery);;
// Theme_LandmarkTheaters/_nav.js

(function ($) {

	// navmain functionality

	function setup()
    {
		var $navMain = $('[data-navmain]'),
			navMainTop = 0,
			navMainHeight = 0,
			$navMainLinks = $('[data-navmain-links]'),
			$navMainBtn = $('[data-navmain-btn]');

		if ($navMain.length > 0 
            && $navMainLinks.length > 0 
            && $navMainBtn.length > 0)
        {
			// show/hide mobile menu
			$navMainBtn.on('click', function (e)
            {
				e.preventDefault();

				var $btn = $(this);
				if ($btn.hasClass('active'))
                {
					$btn.removeClass('active');
					$navMainLinks.removeClass('active');
				}
				else
                {
					$btn.addClass('active');
					$navMainLinks.addClass('active');
				}
			});

			navMainTop = $navMain[0].offsetTop;
			navMainHeight = $navMain.outerHeight();
			
			// sticky menu
			$(document).on('ready scroll', function ()
            {
				var docScroll = $(document).scrollTop();

				if (docScroll >= navMainTop)
                {
					if ($navMain.hasClass('fixed') === false)
                    {
						$navMain.addClass('fixed');
						$('<div data-navmain-place/>').css({
							height: navMainHeight
						}).insertBefore($navMain);
					}
				}
				else
                {
					if ($navMain.hasClass('fixed') === true)
                    {
						$navMain.removeClass('fixed');
						$('[data-navmain-place]').remove();
					}
				}
			});
		}
	};

	function init()
    {
		$(function () 
        {
			setup();
		});
	};

	init();

})(jQuery);

(function ($) {

	// tab functionality

	function setup()
    {
		var $tabs = $('[data-tab-item]'),
			$tabLinks = $('[data-tab-link]'),
			$curTab = $(),
			curHash = '';

		if ($tabs.length > 0 && $tabLinks.length > 0)
        {

		    $tabLinks.on('click.tabclick', function (e)
            {
				var $link = $(this),
					linkHash = this.hash || '';

			    // TODO: for gift cards - remove if breaks booking
				var $linkStep = $link.data('gc-step-link');
				if ($linkStep)
                {
				    pc.gc.curstep = $linkStep;
				}

				e.preventDefault();

				if ($link.hasClass('disabled') === false 
                    && $link.hasClass('active') === false 
                    && linkHash !== '')
                {
				    //console.log(linkHash);
				    //console.log($tabs);

					$tabLinks.filter('.active').removeClass('active');
					$link.addClass('active');

					$tabs.filter('.active').removeClass('active');
					$tabs.filter('[data-tab-item="' + linkHash + '"]').addClass('active');

					curHash = linkHash;

					if ($link.closest('.topTab_book').length === 0)
                    {
						window.location.hash = linkHash;
					}
				}
			});

			if (window.location.hash !== '')
            {
				$curTab = $tabLinks.filter('[href="' + window.location.hash + '"]');
				curHash = window.location.hash;
			}

			if ($curTab.length === 0)
            {
				// show first tab
				$curTab = $tabLinks.first();
			}

			$curTab.trigger('click.tabclick');

			$(window).on('hashchange', function ()
            {
				if (window.location.hash !== curHash)
                {
					var $newTab = $tabLinks.filter('[href="' + window.location.hash + '"]');

					if ($newTab.length > 0)
                    {
						$newTab.trigger('click');
					}
				}
			});
		}
	};

	function init()
    {
		$(function ()
        {
			setup();
		});
	};

	init();

})(jQuery);;
// Theme_LandmarkTheaters/_film.js

var pc = pc || {};

pc.film = {
    'filter': {
        'nowshowing': {
            'name': 'nowshowing',
            'method': 'movies/GetFilmsByCinema/{{circuit}}/{{cinema}}',
            'methodregion': 'movies/GetByRegion/{{circuit}}/{{region}}/{{cinema}}'
        },
        'comingsoon': {
            'name': 'comingsoon',
            'method': 'upcomingbycinema/{{circuit}}/{{cinema}}',
            'methodregion': 'upcomingbyregion/{{circuit}}/{{region}}'
        },
        'cinema': {
            'name': 'cinema',
            'populate': 'cinemas/{{circuit}}',
            'template': '{{#.}}<option value="{{CinemaId}}">{{CinemaName}}</option>{{/.}}'
        },
        'date': {
            'name': 'date',
            'populate': 'movies/GetFilmsByCinema/{{circuit}}/{{cinema}}',
            'template': '{{#.}}{{#Result}}<option value="{{NewDate}}">{{DisplayDate}}</option>{{/Result}}{{/.}}'
        },
        'datelist': {
            'name': 'datelist',
            'populate': 'movies/{{circuit}}/{{cinema}}/{{filmid}}',
            'template': '{{#.}}<label class="dateListItem {{#IsDisabled}}disabled{{/IsDisabled}}" data-dp-listitem title="{{DisplayDate}}" tabindex="0">{{DisplayDateDay}}<span>{{DisplayDateDate}}</span><input type="radio" {{#IsDisabled}}disabled{{/IsDisabled}} value="{{NewDate}}" name="date" /></label>{{/.}}'
        },
        'exp': {
            'name': 'exp'
        },
        'expcs': {
            'name': 'expcs'
        }
    },
    'template': '',
    'temp': {
        'method': '',
        'methodregion': '',
        'cinema': '',
        'region': '',
        'datelist': [],
        'date': '',
        'filmid': '',
        'exp': '',
        'minheight': ''
    }
};

(function ($) {
    var isLoad = false,
        notAds = '[data-film="landingpage"]',
        notAux = '[data-film="landingpage"]',
        bodyCinemaId = $('[data-id-cinema]').attr('data-id-cinema'),
        bodyRegionId = $('[data-id-region]').attr('data-id-region');

    function setup() {
        // console.log('_film.js setup');

        $(window).off('resize').on('resize', debouncer(function (e) {
            var winWidth = Math.max($(window).width(), window.innerWidth);
            if (winWidth > 767) {
                setHeight();
            }
        }));

        var $filters = $('[data-film-filter]'),
            $filmList = $('[data-film]'),
            activeFilter = $filters.filter('.active').attr('data-film-filter'),
            $curRegion = $('[data-id-region]'),
            $curCinema = $('[data-id-cinema]'),
            $curFilter;

        if ($filters.length > 0) {
            showLoad();

            // filter tab event
            $filters.not('select, input')
                .on('click.filterclick', function (e) {
                    e.preventDefault();
                    change(this);
                });

            // filter select event
            $filters.filter('select, input')
                .on('change.filterchange', function (e) {
                    e.preventDefault();
                    change(this);
                });

            if ($('[data-filmid]').length > 0) {
                pc.film.temp.filmid = $('[data-filmid]').attr('data-filmid');
            }

            if ($curRegion.length > 0
                && $curRegion.attr('data-id-region') !== '0') {
                pc.film.temp.region = $curRegion.attr('data-id-region');
            }

            if ($curCinema.length > 0
                && $curCinema.attr('data-id-cinema') !== '0') {
                pc.film.temp.cinema = $curCinema.attr('data-id-cinema');
            }
            else {
                hideLoad();

                if (typeof pc.ellipsis !== 'undefined') {
                    pc.ellipsis($('[data-ellipsiscontain]'));
                }
            }

            // populate date list
            populate(pc.film.filter.datelist);

            // populate cinema select
            populate(pc.film.filter.cinema);

            // populate experiences
            populate(pc.film.filter.exp);

            setupAuxPanels();

            setHeight();

            if (window.location.hash !== '') {
                $curFilter = $filters.filter('[href="' + window.location.hash + '"]');
                if ($curFilter.length > 0) {
                    $curFilter.trigger('click.filterclick');
                }
            }
        }
    }

    function change(filter) {
        // console.log('_film.js change');
        //console.log(sessionStorage.sessionDate);

        // filter changed
        var $filter = $(filter),
            thisType = $filter.attr('data-film-filter'),
            thisHead = $filter.text() || '',
            thisVal = $filter.val() || '',
            isTab = false;

        if (thisVal === '-1') {
            thisVal = '';
        }

        showLoad();

        // console.log('_film.js change: thisType=' + thisType);

        switch (thisType) {
            case pc.film.filter.nowshowing.name:

                //#region Nowshowing Tab

                if (typeof pc.film.filter.nowshowing.setup === 'undefined') {
                    var $inp = $('[data-dp-list] [data-dp-listitem]');
                    isLoad = true;

                    if ($inp.length > 0) {
                        // console.log(hasSession);

                        // DPUPDATE
                        // update following if statement to check for querystring date and session storage date
                        if (sessionStorage.sessionDate
                            && $('[data-dp-list] [name="date"][value="' + sessionStorage.sessionDate + '"]').length > 0) {
                            $('[data-dp-list] [name="date"][value="' + sessionStorage.sessionDate + '"]').closest('label').removeClass('active');
                            $('[data-dp-list] [name="date"][value="' + sessionStorage.sessionDate + '"]').trigger('click.dateclick');
                        }
                        else if
                            ($inp.filter('.active').length > 0) {
                            // change between tabs
                            // remove active date and reapply to reload films
                            $inp.filter('.active').removeClass('active').find('[name="date"]').trigger('click.dateclick');
                        }
                        else {
                            // trigger first date
                            $inp.first().find('[name="date"]').trigger('click.dateclick');
                        }
                    }
                    else {
                        hideLoad();
                    }

                    pc.film.filter.nowshowing.setup = true;
                }
                else {
                    hideLoad();
                }

                showFilter(pc.film.filter.cinema);
                showFilter(pc.film.filter.date);
                isTab = true;
                break;

            //#endregion Nowshowing Tab

            case pc.film.filter.comingsoon.name:

                //#region ComingSoon Tab

                hideLoad();
                hideFilter(pc.film.filter.cinema);
                hideFilter(pc.film.filter.date);
                isTab = true;
                break;

            //#endregion ComingSoon Tab

            case pc.film.filter.cinema.name:

                //#region Cinema Filter

                isLoad = true;
                pc.film.temp.cinema = thisVal;
                update(pc.film.filter.cinema);
                break;

            //#endregion Cinema Filter

            case pc.film.filter.date.name:
            case pc.film.filter.datelist.name:

                //#region Date Filter

                isLoad = true;
                updateListFilter();
                break;

            //#endregion Date Filter

            case pc.film.filter.exp.name:
            case pc.film.filter.expcs.name:

                //#region Experiences Filter

                if (isLoad) {
                    setTimeout(function () {
                        change(filter);
                    }, 200);
                    break;
                }

                updateListFilter();
                break;

            //#endregion Experiences Filter
        }

        if (isTab === true) {
            // extra stuff for tabs
            $('[data-film-filter]').filter('.active').removeClass('active');
            $filter.addClass('active');

            setupAuxPanels();

            if (typeof pc.lazyload !== 'undefined') {
                pc.lazyload();
            }

            if (typeof pc.ellipsis !== 'undefined') {
                pc.ellipsis($('[data-ellipsiscontain]'));
            }

            setHeight();
        }
    }

    function showFilter(filter) {
        //console.log('_film.j showFilter');
        $('[data-film-filter="' + filter.name + '"]').show();
    }

    function hideFilter(filter) {
        //console.log('_film.j hideFilter');
        $('[data-film-filter="' + filter.name + '"]').hide();
    }

    /*
	function changeHead(newText)
	{
	    console.log('_film.j changeHead');

		// change heading
		var $filmHead = $('[data-film-head]');

		if ($filmHead.length > 0 && newText !== '')
        {
			$filmHead.text(newText);
		}
	}
    */

    function update(filter) {
        // console.log('_film.js update');

        // update filter
        var template = pc.film.template || '';

        if (template === '') {
            $.get('/template?name=MovieListingsTheater&extensionToFind=mustache&extensionToReturn=txt', function (data) {
                //console.log(data);
                pc.film.template = data;
                updateList(filter);
            });
        }
        else {
            updateList(filter);
        }
    }

    function updateList(filter) {
        // console.log('_film.js updateList');

        // update list
        var url;

        if (typeof filter.isset === 'undefined') {
            if (pc.film.temp.region !== ''
                && pc.film.temp.region !== '0'
                && pc.film.temp.cinema === ''
                && typeof filter.methodregion !== 'undefined') {
                url = filter.methodregion;
            }
            else {
                url = filter.method;
            }

            if (filter.name === pc.film.filter.comingsoon.name
                && typeof pc.film.temp.csdata !== 'undefined') {
                filterUpdate(pc.film.temp.csdata);
            }
            else if (filter.name === pc.film.filter.nowshowing.name
                && typeof pc.film.temp.nsdata !== 'undefined') {
                filterUpdate(pc.film.temp.nsdata);
            }
            else {
                getData(filter.name, url, filterUpdate);
            }
        }

        function filterUpdate(data) {
            // console.log('_film.js updateList.filterUpdate');

            var template = pc.film.template,
                html = '',
                filmLink = '',
                $filmList;

            if (pc.film.temp.region !== ''
                && pc.film.temp.region !== '0') {
                filmLink += '/region/' + pc.film.temp.region;
            }

            if (pc.film.temp.cinema !== ''
                && pc.film.temp.cinema !== '0') {
                filmLink += '/cinema/' + pc.film.temp.cinema;
            }

            // update film link
            $.each(data, function (filmIndex, filmValue) {
                // /region/{{regionid}}/cinema/{{cinemaid}}/film-info/{{friendlyname}}
                var tempFilmLink = filmLink + '/film-info/' + filmValue.FriendlyName;

                data[filmIndex].FriendlyName = tempFilmLink;

                if (filter.name === pc.film.filter.comingsoon.name
                    && typeof filmValue.Sessions !== 'undefined') {
                    data[filmIndex].IsAdvancedSale = true;
                }
            });

            //console.log(data);

            html = Mustache.to_html(template, data);

            $filmList = $('[data-film="' + filter.name + '"]');

            if ($filmList.length === 0) {
                $filmList = $('[data-film]');
            }

            $filmList.html(html);

            switch (filter.name) {
                case pc.film.filter.comingsoon.name:

                    hideLoad();
                    break;

                case pc.film.filter.nowshowing.name:

                    getDates(data);
                    break;
            }

            setupAuxPanels();

            if (typeof pc.ellipsis !== 'undefined') {
                pc.ellipsis($('[data-ellipsiscontain]'));
            }

            filter.isset = true;
        }
    }

    function updateListFilter() {
        // console.log('_film.j updateListFilter');

        // Update list based on filters
        var $sessions = $('[data-tab-item]:visible [data-film] [data-film-session][data-film-exp], [data-filminfo]:visible [data-film-session]'),
            $sessionsDate = $sessions.find('[data-film-session]'),
            $sessionsExp = $sessions.find('[data-film-exp]');

        // Reset temp date
        pc.film.temp.date = resetTempDate();

        // Reset temp exp
        pc.film.temp.exp = resetTempExperience();

        // Hide listings
        $sessions.hide();
        $sessionsDate.hide();
        $sessionsExp.hide();

        if (pc.film.temp.date !== '') {
            // filter sessions by date
            $sessions = $sessions.filter('[data-film-session*="' + pc.film.temp.date + '"]');
            $sessionsDate = $sessions.find('[data-film-session]');
            $sessionsDate = $sessionsDate.filter('[data-film-session*="' + pc.film.temp.date + '"]');

            // Remove the Theatre Title if 

            if (pc.film.temp.exp !== ''
                && pc.film.temp.exp !== '-1') {
                // filter sessions by exp
                $sessions = $sessions.filter('[data-film-exp*="' + pc.film.temp.exp + '"]');
                $sessionsExp = $();

                // look for exp times
                if (pc.film.temp.cinema !== '') {
                    $sessions.each(function () {
                        var $this = $(this),
                            $exp = $this.find('[data-film-session*="' + pc.film.temp.date + '"] [data-film-exp*="' + pc.film.temp.exp + '"]');

                        if ($exp.length === 0) {
                            $sessions = $sessions.not($this);
                        }
                        else {
                            $sessionsExp = $sessionsExp.add($exp);
                        }
                    });
                }
            }

            // show filtered listings date and exp.
            $sessionsDate.show();
            $sessionsExp.show();
        }
        else if (pc.film.temp.exp !== '') {
            // filter sessions by exp
            $sessions = $sessions.filter('[data-film-exp*="' + pc.film.temp.exp + '"]');
        }

        // show filtered listings
        $sessions.each(function () {
            //
            // Set the accordian open/close state depending on date visibility
            // and on the number of cinemas displayable with sessions.
            //

            var $thisAccordian = $(this).find('.accordion'),
                $allAccordItems,
                $allOpenItems;

            if (typeof $thisAccordian !== 'undefined'
                && $thisAccordian !== null
                && $thisAccordian.length > 0) {
                if (bodyCinemaId !== null
                    && bodyCinemaId > 0) {
                    //
                    // User is on a cinemas page so only open the single cinema sessions list.
                    //
                    $allAccordItems = $thisAccordian.find('[data-accordion-item]:visible');
                    if (typeof $allAccordItems !== 'undefined'
                        && $allAccordItems !== null
                        && $allAccordItems.length > 0) {
                        $allAccordItems.addClass("is-active");
                        $allOpenItems = $allAccordItems.find("[data-tab-content]");
                        $allOpenItems.each(function (i, section) {
                            $thisAccordian.foundation('down', $(section), true);
                        });
                    }
                }
                else {
                    //
                    // User is on a region page so only open the first cinema sessions list and close the others.
                    //
                    $allAccordItems = $thisAccordian.find('[data-accordion-item]:visible');
                    if (typeof $allAccordItems !== 'undefined'
                        && $allAccordItems !== null
                        && $allAccordItems.length > 0) {
                        if ($allAccordItems.length > 1) {
                            $thisAccordian.removeClass("is-single-cinema");
                        }

                        $allAccordItems.addClass("is-active");
                        $allOpenItems = $allAccordItems.find("[data-tab-content]");
                        $allOpenItems.each(function (i, section) {
                            if (i === 0) {
                                $thisAccordian.foundation('down', $(section), true);
                            }
                            else {
                                $thisAccordian.foundation('up', $(section));
                            }
                        });
                    }
                }
            }
        }).show();

        hideLoad();

        if (typeof pc.lazyload !== 'undefined') {
            pc.lazyload();
        }

        if (typeof pc.ellipsis !== 'undefined') {
            pc.ellipsis($('[data-ellipsiscontain]'));
        }

        moveAuxPanels();

        setHeight();
    }

    function showAuxPanels() {
        // console.log('_film.j showAuxPanels');

        // show aux panel to fill gap
		/*
        $('[data-film]:visible').not(notAux).each(function () {
			var $list = $(this),
				$items = $list.find('li[data-film-session]:visible'),
				itemsLen = $items.length || 0,
				$aux = $list.find('li[data-auxpanel]'),
				rowItems = 3,
				rows = Math.ceil(itemsLen / rowItems),
				auxShow = ((rows * rowItems) % itemsLen) || 0;

			$aux.hide();

			// we want to show min 2 rows
			if (itemsLen <= rowItems) {
				auxShow += rowItems;
			}
			
			if (auxShow > 0) {
				$aux.filter(':lt(' + auxShow + ')').show();

				if (typeof pc.ellipsis !== 'undefined') {
					pc.ellipsis($('.auxPanelText'));
				}
			}
		});
        */

        // show all aux panels
        $('[data-film]:visible').not(notAux).each(function () {
            var $list = $(this),
                $aux = $list.find('li[data-auxpanel]').not(':visible');

            if ($aux.length > 0) {
                $aux.show();

                if (typeof pc.ellipsis !== 'undefined') {
                    pc.ellipsis($('.auxPanelText'));
                }
            }
        });
    }

    function resetTempDate() {
        var $curDate = $('[data-film-filtergroup]:visible [data-film-filter="' + pc.film.filter.date.name + '"]'),
            $curDateList = $('[data-film-filtergroup]:visible [data-film-filter="' + pc.film.filter.datelist.name + '"]');

        // reset date
        pc.film.temp.date = '';

        // set date from current date.
        if ($curDate.length > 0) {
            pc.film.temp.date = $curDate.val();
        }
        else if ($curDateList.length > 0) {
            pc.film.temp.date = $curDateList.val();
        }

        return pc.film.temp.date;
    }

    function resetTempExperience() {
        var $curExp = $('[data-film-filtergroup]:visible [data-film-filter="' + pc.film.filter.exp.name + '"]'),
            $curExpCs = $('[data-film-filtergroup]:visible [data-film-filter="' + pc.film.filter.expcs.name + '"]');

        // reset exp
        pc.film.temp.exp = '';

        // set exp from current experience.
        if ($curExp.length > 0) {
            pc.film.temp.exp = $curExp.val();
        }
        else if ($curExpCs.length > 0) {
            pc.film.temp.exp = $curExpCs.val();
        }

        return pc.film.temp.exp;
    }

    function getDates(data) {
        // console.log('_film.j getDates');

        var temp = {};

        // get new dates based on cinema
        if (Object.prototype.toString.call(data) === '[object Array]') {
            $.each(data, function (index, value) {
                if (typeof value.Sessions !== 'undefined') {
                    $.each(value.Sessions, function (index2, value2) {
                        var dObj = {
                            'NewDate': value2.NewDate,
                            'DisplayDate': value2.DisplayDate
                        };

                        if (typeof temp[value2.NewDate] === 'undefined') {
                            temp[value2.NewDate] = dObj;
                        }
                    });
                }
            });
        }
        else if (typeof data.Sessions !== 'undefined') {
            $.each(data.Sessions, function (index2, value2) {
                var dObj = {
                    'NewDate': value2.NewDate,
                    'DisplayDate': value2.DisplayDate
                };

                if (typeof temp[value2.NewDate] === 'undefined') {
                    temp[value2.NewDate] = dObj;
                }
            });
        }

        // reset date list
        pc.film.temp.datelist.length = 0;

        for (var tempKey in temp) {
            pc.film.temp.datelist.push(temp[tempKey]);
        }

        if (pc.film.temp.datelist.length > 0) {
            pc.film.temp.datelist.sort(function (a, b) {
                if (a.NewDate < b.NewDate) {
                    return -1;
                }

                if (a.NewDate > b.NewDate) {
                    return 1;
                }

                return 0;
            });

            //populate(pc.film.filter.date);
            populate(pc.film.filter.datelist);
        }
        else {
            //populate(pc.film.filter.date, true);
            populate(pc.film.filter.datelist, true);
        }
    }

    function populate(filter, isEmpty) {
        // console.log('_film.j populate');

        // populate filter
        isEmpty = isEmpty || false;

        var $filter = $('[data-film-filter="' + filter.name + '"]'),
            $firstChild,
            firstChildVal = '',
            firstOption = '',
            url,
            html;

        if ($filter.length > 0) {
            if ($filter.children().length > 0) {
                $firstChild = $filter.children('option:first-child');
                firstChildVal = $firstChild.val();

                if (firstChildVal === '-1' || firstChildVal === '') {
                    firstOption = $firstChild[0].outerHTML;
                }
            }

            if (isEmpty) {
                // empty
                $filter.html(firstOption).prop('disabled', true).addClass('disabled');
            }
            else {
                switch (filter.name) {
                    case pc.film.filter.date.name:
                    case pc.film.filter.datelist.name:

                        //#region Date Filter

                        if (pc.film.temp.datelist.length > 0) {
                            // datelist filter
                            popFilterData(pc.film.temp.datelist);
                        }
                        else if (typeof filmData !== 'undefined') {
                            if (filmData.length === 0) {
                                hideLoad();
                            }
                            else {
                                saveData(filter.name, filmData);
                                getDates(filmData);
                            }
                        }
                        else if (typeof filter.populate !== 'undefined') {
                            url = filter.populate;
                            getData(filter.name, url, getDates);
                        }
                        break;

                    //#endregion Date Filter

                    case pc.film.filter.exp.name:
                        if (
                            typeof filmData !== 'undefined' &&
                            filmData !== null &&
                            filmData.length > 0 &&
                            $filter.find('.dn').length > 0
                        ) {                            
                            for (var filmIndex = 0; filmIndex < filmData.length; filmIndex++) {        
                                if (
                                    typeof filmData[filmIndex].Experiences !== 'undefined' &&
                                    filmData[filmIndex].Experiences !== null &&
                                    filmData[filmIndex].Experiences.length > 0
                                ) {
                                    filmData[filmIndex].Experiences.forEach(function (exp) {
                                        if ($filter.find('.dn[value="exp-' + exp.ExternalId + '"]').length === 1) {
                                            $filter.find('.dn[value="exp-' + exp.ExternalId + '"]').removeClass('dn');
                                        }
                                    });
                                }

                                if ($filter.find('.dn').length === 0) {
                                    break;
                                }
                            }
                        }
                        break;

                    case pc.film.filter.expcs.name:
                        if (
                            typeof csFilmData !== 'undefined' &&
                            csFilmData !== null &&
                            csFilmData.length > 0 &&
                            csFilmData.find('.dn').length > 0
                        ) {                            
                            for (var csFilmIndex = 0; csFilmIndex < csFilmData.length; csFilmIndex++) {        
                                if (
                                    typeof csFilmData[csFilmIndex].Experiences !== 'undefined' &&
                                    csFilmData[csFilmIndex].Experiences !== null &&
                                    csFilmData[csFilmIndex].Experiences.length > 0
                                ) {
                                    csFilmData[csFilmIndex].Experiences.forEach(function (exp) {
                                        if ($filter.find('.dn[value="exp-' + exp.ExternalId + '"]').length === 1) {
                                            $filter.find('.dn[value="exp-' + exp.ExternalId + '"]').removeClass('dn');
                                        }
                                    });
                                }

                                if ($filter.find('.dn').length === 0) {
                                    break;
                                }
                            }
                        }
                        break;

                    default:

                        if (typeof filter.populate !== 'undefined') {
                            // other filters
                            url = filter.populate;
                            getData(filter.name, url, popFilter);
                        }
                        break;
                }
            }
        }

        function popFilterData(data) {
            // console.log('_film.j populate.popFilterData');

            switch (filter.name) {
                case pc.film.filter.datelist.name:

                    //#region Date Filter

                    var $dp = $('[data-dp-list]'),
                        dpWidth = $dp.width(),
                        $dpInputs,
                        $dpLabels,
                        $labelFirst,
                        labelWidth,
                        labelLeftMax,
                        labelLeftMin,
                        today = new Date(),
                        curUTCDate = new Date(),
                        todayValueOf,
                        curUTCValueOf,
                        tempArray = [],
                        dayArray = [
                            'Sun',
                            'Mon',
                            'Tue',
                            'Wed',
                            'Thu',
                            'Fri',
                            'Sat'
                        ];

                    today.setHours(0, 0, 0, 0);
                    todayValueOf = today.valueOf();

                    curUTCDate.setHours(0, 0, 0, 0);
                    curUTCValueOf = curUTCDate.valueOf();

                    $.each(pc.film.temp.datelist, function (dateIndex, dateValue) {
                        var temp = dateValue.NewDate.split('-'),
                            tempDate = new Date(temp[0], parseInt(temp[1], 10) - 1, temp[2], 0, 0, 0, 0),
                            tempUTCDate = new Date(temp[0], parseInt(temp[1], 10) - 1, temp[2], 0, 0, 0, 0),
                            tempDay = '',
                            thisValueOf = tempDate.valueOf(),
                            thisUTCValueOf = tempUTCDate.valueOf();

                        if (dateIndex === 0) {
                            curUTCValueOf = thisUTCValueOf;
                        }

                        while (curUTCValueOf < thisUTCValueOf) {
                            var curDate = new Date(curUTCValueOf),
                                curValueOf,
                                curDay;

                            //console.log(thisValueOf - curValueOf);

                            if (curUTCValueOf === todayValueOf) {
                                curDay = 'Today';
                            }
                            else {
                                curDay = dayArray[curDate.getDay()];
                            }

                            tempArray.push({
                                'IsDisabled': true,
                                'DisplayDateDate': (curDate.getMonth() + 1) + '/' + curDate.getDate(),
                                'DisplayDateDay': curDay,
                                'NewDate': curDate.getFullYear() + '-' + (curDate.getMonth() + 1) + '-' + curDate.getDate(),
                                'UTCValueOf': curUTCValueOf,
                                'ValueOf': curUTCValueOf
                            });

                            // add day
                            curDate.setDate(curDate.getDate() + 1);
                            curUTCValueOf = curDate.valueOf();
                        }

                        if (thisValueOf === todayValueOf) {
                            tempDay = 'Today';
                        }
                        else {
                            tempDay = dayArray[tempDate.getDay()];
                        }

                        dateValue.DisplayDateDay = tempDay;
                        dateValue.DisplayDateDate = (tempDate.getMonth() + 1) + '/' + tempDate.getDate();
                        dateValue.UTCValueOf = thisUTCValueOf;
                        dateValue.ValueOf = thisValueOf;

                        tempArray.push(dateValue);

                        // add day
                        tempDate.setDate(tempDate.getDate() + 1);
                        curUTCValueOf = tempDate.valueOf();
                    });

                    pc.film.temp.datelist = tempArray;

                    // create mustache template
                    html = Mustache.to_html(filter.template, pc.film.temp.datelist);

                    // update html
                    $dp.html(html);

                    // setup date picker
                    setupDatePicker();

                    // define inputs
                    $dpLabels = $dp.find('[data-dp-listitem]');
                    $dpInputs = $dp.find('[name="date"]');
                    $labelFirst = $dpInputs.first().parent('label');

                    labelWidth = $labelFirst[0].getBoundingClientRect().width;
                    labelLeftMin = Math.floor(dpWidth / labelWidth) * labelWidth;
                    labelLeftMax = (labelWidth * $dpInputs.length) - dpWidth + ($dpInputs.length / 2);

                    $dpLabels.on('keyup', function (e) {
                        if (e.which === 13) {
                            e.preventDefault();
                            $(this).find('[name="date"]').trigger('click.dateclick');
                        }
                    });

                    // input click event
                    $dpInputs.on('click.dateclick', function (e, isCalClick) {
                        var $radio = $(this),
                            radioVal = $radio.val(),
                            radioDate = new Date(Date.parse(radioVal)),
                            $label = $radio.parent('label'),
                            newLeft = 0;

                        // check we aren't already active
                        if ($label.hasClass('active') === false) {
                            // change value on filter and trigger change event
                            $filter.val(radioVal).trigger('change.filterchange');

                            // remove active class from previous
                            $dp.find('.active').removeClass('active');

                            // add active class to parent label
                            $label.addClass('active');

                            if (typeof isCalClick === 'undefined') {
                                // save for date picker
                                radioDate.setHours(0, 0, 0, 0);
                                $('[data-dp-cal]').datepicker('setValue', radioDate);
                            }
                            // update position of date list
                            newLeft = ($dpInputs.index($radio) * labelWidth);
                            if (newLeft < labelLeftMin) {
                                newLeft = 0;
                            }
                            else if (newLeft > labelLeftMax) {
                                newLeft = labelLeftMax;
                            }
                            $labelFirst.css('margin-left', -newLeft);

                            // DPUPDATE
                            // save thisDate to session storage
                            sessionStorage.sessionDate = radioVal;
                        }
                    });

                    // DPUPDATE
                    var savedDate = getQueryVariable('date') || sessionStorage.sessionDate || '';
                    if (savedDate !== '' && $('[data-dp-list] [name="date"][value="' + savedDate + '"]').length > 0) {
                        // trigger saved date
                        $('[data-dp-list] [name="date"][value="' + savedDate + '"]').trigger('click.dateclick');
                    }
                    else {
                        // trigger first item
                        $('[data-dp-list]:visible [data-dp-listitem]:first').find('[name=date]').trigger('click.dateclick');
                    }
                    break;

                //#endregion Date Filter

                default:

                    // other date filters
                    // create mustache template
                    html = Mustache.to_html(filter.template, pc.film.temp.datelist);

                    // update filter html
                    $filter.html(firstOption + html).prop('disabled', false).removeClass('disabled');

                    // if no first option trigger change to make sure we are just showing the first option date
                    if (firstOption === '') {
                        $filter.trigger('change.filterchange');
                    }
                    break;
            }
        }

        function popFilter(data) {
            // console.log('_film.j populate.popFilter');

            switch (filter.name) {
                case pc.film.filter.exp.name:
                case pc.film.filter.expcs.name:

                    //#region Experience Filter

                    var temp = {};

                    $.each(data, function (expIndex, expValue) {
                        var exp = expValue.Experiences,
                            expLen = 0,
                            i = 0;

                        if (typeof exp !== 'undefined'
                            && exp !== null) {
                            expLen = exp.length;
                            if (expLen > 0) {
                                for (i = 0; i < expLen; i += 1) {
                                    if (typeof temp[exp[i].Id] === 'undefined') {
                                        temp[exp[i].Id] = exp[i].Name;
                                    }
                                }
                            }
                        }
                    });

                    filter.data = [];

                    for (var key in temp) {
                        if (temp.hasOwnProperty(key)) {
                            filter.data.push({
                                'Id': key,
                                'Name': temp[key]
                            });
                        }
                    }

                    filter.data.sort(function (a, b) {
                        if (a.Name > b.Name) {
                            return 1;
                        }

                        if (a.Name < b.Name) {
                            return -1;
                        }

                        // a must be equal to b
                        return 0;
                    });

                    html = Mustache.to_html(filter.template, filter.data);

                    break;

                //#endregion Experience Filter

                default:

                    html = Mustache.to_html(filter.template, data);
                    break;
            }

            if (html !== '') {
                $filter.html(firstOption + html)
                    .prop('disabled', false)
                    .removeClass('disabled');

                // set current cinema
                if (filter.name === pc.film.filter.cinema.name
                    && pc.film.temp.cinema !== '') {
                    $filter.val(pc.film.temp.cinema);
                }
            }
        }
    }

    function getData(filterName, url, callback) {
        // console.log('_film.j getData');

        url = pc.api.movie + url;

        url = url
            .replace(/{{circuit}}/g, pc.api.circuit)
            .replace(/{{region}}/g, pc.film.temp.region)
            .replace(/{{cinema}}/g, pc.film.temp.cinema)
            .replace(/{{date}}/g, pc.film.temp.date)
            .replace(/{{filmid}}/g, pc.film.temp.filmid);

        $.getJSON(url)
            .done(function (data) {
                saveData(filterName, data);
                if (typeof callback !== 'undefined') {
                    callback(data);
                }
            })
            .fail(function (jqxhr, textStatus, error) {
                //console.log('Request Failed: ' + textStatus + ', ' + error);
            });
    }

    function saveData(filterName, data) {
        // console.log('_film.j saveData');

        switch (filterName) {
            case pc.film.filter.comingsoon.name:

                pc.film.temp.csdata = data;
                break;

            case pc.film.filter.nowshowing.name:

                pc.film.temp.nsdata = data;
                break;

            case pc.film.filter.date.name:
            case pc.film.filter.datelist.name:

                pc.film.temp.datedata = data;
                break;
        }
    }

    function setupDatePicker() {
        // console.log('_film.j setupDatePicker');

        // date picker 
        // requires bootstrap-datepicker plugin

        var $dpList = $('[data-dp-list]'),
            $dpSelect = $dpList.find('[data-film-filter]'),
            dpSelectDates = [],
            $dpBtn = $('[data-dp-cal]');

        // set datepicker to first date
        $dpBtn.data('date', pc.film.temp.datelist[0].NewDate);

        $dpBtn.datepicker({
            onRender: function (date) {
                var thisClass = '',
                    i = 0,
                    isValid = false,
                    dlLen = pc.film.temp.datelist.length;

                date.setHours(0, 0, 0, 0);

                // make sure date is after today
                if (date.valueOf() < pc.film.temp.datelist[0].ValueOf) {
                    thisClass = 'disabled';
                }
                // make sure date is not after last datelist
                else if (date.valueOf() > pc.film.temp.datelist[dlLen - 1].ValueOf) {
                    thisClass = 'disabled';
                }
                // make sure date exists in datelist
                else {
                    for (i = 0; i < dlLen; i += 1) {
                        if (typeof pc.film.temp.datelist[i].IsDisabled === 'undefined'
                            && date.valueOf() === pc.film.temp.datelist[i].ValueOf) {
                            isValid = true;
                            break;
                        }
                    }

                    // does not exist
                    if (isValid === false) {
                        thisClass = 'disabled';
                    }
                }

                return thisClass;
            }
        })
            .on('show', function (e) {
                var $dp = $('.datepicker');

                // add close button
                $('<button class="datepicker-close">X</button>')
                    .appendTo('.datepicker')
                    .on('click', function (e) {
                        e.preventDefault();
                        $dpBtn.datepicker('hide');
                    });

                // add overlay
                $('<div class="datepicker-overlay"/>').insertAfter('.datepicker');

                // add active class
                $dpBtn.addClass('active');
            })
            .on('hide', function (e) {
                // remove close btn and overlay
                $('.datepicker-close, .datepicker-overlay').remove();

                // remove active class
                $dpBtn.removeClass('active');
            })
            .on('changeDate', function (e) {
                var thisDate = new Date(e.date),
                    thisMonth = (thisDate.getMonth() + 1),
                    thisMonthFormat = thisMonth < 10 ? ('0' + thisMonth) : thisMonth,
                    thisDay = thisDate.getDate(),
                    thisDayFormat = thisDay < 10 ? ('0' + thisDay) : thisDay,
                    thisDateFormat = thisDate.getFullYear() + '-' + thisMonthFormat + '-' + thisDayFormat,
                    $input = $('[data-dp-list] [name="date"][value="' + thisDateFormat + '"]');

                if ($input.length > 0) {
                    // trigger input click event
                    $input.trigger('click.dateclick', true);
                    // hide datepicker
                    $dpBtn.datepicker('hide');
                }
            });
    }

    function setupAuxPanels() {
        // console.log('_film.j setupAuxPanels');

        // check we have aux panels
        if (typeof pc.aux !== 'undefined'
            && pc.aux.length > 0) {
            var $parent = $('[data-film]:visible').not(notAux).not('[data-auxpanelsetup="true"]'),
                $temp2 = $();

            if ($parent.length > 0) {
                // set attribute so only do this once per list
                $parent.attr('data-auxpanelsetup', 'true');
                // get template
                $.get('/template?name=AuxiliaryPanels&extensionToFind=mustache&extensionToReturn=txt', function (data) {
                    // loop items
                    $.each(pc.aux, function (auxIndex, auxValue) {
                        // set min height
                        auxValue.minheight = pc.film.temp.minheight;

                        // get html
                        var html = Mustache.to_html(data, auxValue);

                        if (typeof auxValue.DisplayIndex !== 'undefined' && auxValue.DisplayIndex !== 0) {
                            $temp2 = $temp2.add(html);
                        }
                        else {
                            // add to end of list
                            $parent.append(html);
                        }
                    });

                    if ($temp2.length > 0) {
                        // sort left over aux items that have displayindex then add to end of film list
                        $temp2.sort(function (aux1, aux2) {
                            var aux1Index = $(aux1).data('auxpanel'),
                                aux2Index = $(aux2).data('auxpanel');

                            if (aux1Index > aux2Index) {
                                return 1;
                            }
                            else if (aux1Index < aux2Index) {
                                return -1;
                            }
                            else {
                                return 0;
                            }
                        });

                        if ($parent.find('[data-film-nosession]').length > 0) {
                            $parent.find('[data-film-nosession]').after($temp2);
                        }
                        else {
                            $.each($temp2, function (auxIndex, auxValue) {
                                var $aux = $(auxValue),
                                    $children = $parent.find('>li:visible'),
                                    $child = $children.filter(':eq(' + ($aux.data('auxpanel') - 1) + ')');

                                if ($child.length > 0) {
                                    $child.before(auxValue);
                                }
                                else {
                                    $parent.find('>li[data-film-session]:last').after(auxValue);
                                }
                            });
                        }
                    }

                    if (typeof pc.ellipsis !== 'undefined') {
                        pc.ellipsis($('.auxPanelText'));
                    }

                    setHeight();

                    setupAd();
                });
            }
        }
        else {
            setupAd();
        }
    }

    function moveAuxPanels() {
        // console.log('_film.j moveAuxPanels');

        var $parent = $('[data-auxpanelsetup="true"]:visible'),
            $auxPanels,
            $temp,
            $temp2 = $();

        if ($parent.length > 0) {
            $auxPanels = $parent.find('[data-auxpanel]').not('[data-auxpanel="0"]');

            if ($auxPanels.length > 0) {
                $temp = $auxPanels.detach();
                removeAd();

                // loop through detached and reattach
                $temp.each(function () {
                    var $panel = $(this),
                        thisDisplayIndex = $panel.data('auxpanel'),
                        $child = $parent.find('>li:visible:eq(' + (thisDisplayIndex - 1) + ')');

                    if ($child.length > 0) {
                        $child.before($panel);
                    }
                    else {
                        $temp2 = $temp2.add($panel);
                    }
                });

                if ($temp2.length > 0) {
                    // sort left over aux items that have displayindex then add to end of film list
                    $temp2.sort(function (aux1, aux2) {
                        if (typeof aux1 !== 'undefined' && typeof aux2 !== 'undefined') {
                            var aux1Index = $(aux1).data('auxpanel'),
                                aux2Index = $(aux2).data('auxpanel');

                            if (aux1Index > aux2Index) {
                                return 1;
                            }
                            else if (aux1Index < aux2Index) {
                                return -1;
                            }
                            else {
                                return 0;
                            }
                        }
                        else {
                            return 0;
                        }
                    });

                    $parent.find('>li[data-film-session]:last').after($temp2);
                }

                setupAd();
            }
            else {
                moveAd();
            }
        }
        else {
            moveAd();
        }
    }

    function setupAd() {
        // console.log('_film.j setupAd');

        var $parent = $('[data-film]:visible').not(notAds).not('[data-adsetup="true"]');
        if (typeof pc.ads !== 'undefined'
            && $parent.length > 0) {
            $parent.attr('data-adsetup', 'true');
            if (Object.prototype.toString.call(pc.ads) === '[object Array]') {
                // mutiple ads
                $.each(pc.ads, function (adIndex, adValue) {
                    showAd(adValue);
                });
            }
            else if (Object.prototype.toString.call(pc.ads) !== '[object Null]') {
                // single ad
                showAd(pc.ads);
            }
        }
    }

    function showAd(ad) {
        // console.log('_film.j showAd');

        var template = {},
            placeAfter = 3,
            temp = '',
            $parent = $('[data-film]:visible').not(notAds),
            $child;

        template.leaderboard = '<li class="gridCol-s-12 gridCol-m-12 gridCol-l-12 listAd" data-listad="{{Index}}"><a href="{{ExternalUrl}}" target="_blank"><img src="{{Image}}" alt="{{Name}}"/></a></li>';

        if (typeof template[ad.Placement] !== 'undefined') {
            temp = Mustache.to_html(template[ad.Placement], ad);

            if (ad.Placement === 'leaderboard') {
                if (typeof ad.Index !== 'undefined') {
                    placeAfter = ((placeAfter * (ad.Index + 1)) + ad.Index);
                }

                $child = $parent.find('>li:visible').not('[data-film-nosession]').filter(':eq(' + (placeAfter - 1) + ')');

                if ($child.length > 0) {
                    $child.after(temp);
                }
                else {
                    $parent.append(temp);
                }
            }
        }
    }

    function moveAd() {
        // console.log('_film.j moveAd');

        var $parent = $('[data-film]:visible').not(notAds),
            $ads,
            $temp;

        if ($parent.length > 0) {
            $ads = $parent.find('[data-listad]');
            if ($ads.length > 0) {
                $temp = $ads.detach();
                $temp.each(function () {
                    var $ad = $(this),
                        thisIndex = $ad.data('listad'),
                        placeAfter = 3;

                    if (typeof thisIndex !== 'undefined') {
                        placeAfter = ((placeAfter * (thisIndex + 1)) + thisIndex);
                    }

                    var $child = $parent.find('>li:visible:eq(' + (placeAfter - 1) + ')');

                    if ($child.length > 0) {
                        $child.after($ad);
                    }
                    else {
                        $parent.append($ad);
                    }
                });
            }
        }
    }

    function removeAd() {
        // console.log('_film.j removeAd');

        $('[data-film][data-adsetup="true"]:visible').not(notAds)
            .removeAttr('data-adsetup')
            .find('[data-listad]')
            .remove();
    }

    function showLoad() {
        // console.log('_film.j showLoad');

        $('[data-tab-item]:visible [data-film]').hide();
        $('[data-tab-item]:visible [data-film-load]').show();
    }

    function hideLoad() {
        // console.log('_film.j hideLoad');

        $('[data-film-load]').hide();
        $('[data-tab-item]:visible [data-film]').show();
        isLoad = false;
    }

    // Sets the height of each rows columns including any aux panels.
    function setHeight() {
        //console.log('_film.j setHeight');

        var winWidth = Math.max($(window).width(), window.innerWidth);

        if (winWidth > 767) {
            var $items = $("[data-film] > li:visible").not('[data-listad]');

            if ($items.length > 0) {
                var newHeight = 0,
                    rowColumns = 3;

                for (var i = 0, len = $items.length; i < len; i += rowColumns) {
                    var $itemRow = $items.slice(i, i + rowColumns);

                    $itemRow.each(function () {
                        var thisHeight = parseInt($(this).find("div").first().outerHeight());
                        if (thisHeight > newHeight) {
                            newHeight = thisHeight;
                        }
                    }).each(function () {
                        var item = $(this).find("div").first();
                        item.css('min-height', newHeight + 1);
                    });

                    newHeight = 0;
                }
            }
        }
        else {
            $("[data-film] > li:visible > div").css('min-height', '');
        }
    }

    function debouncer(func) {
        var timeoutId,
            timeout = 200;

        return function () {
            var scope = this, args = arguments;
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function () {
                func.apply(scope, Array.prototype.slice.call(args));
            }, timeout);
        };
    }

    function init() {
        $(function () {
            setup();
        });
    }

    init();

    pc.film.setup = setup;

})(jQuery);

function getQueryVariable(variable) {
    // console.log('_film.j getQueryVariable');

    var query = window.location.search.substring(1);
    var vars = query.split("&");

    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === variable) {
            return pair[1];
        }
    }

    return (false);
}

;
(function ($) {

	var $btn = $('[data-offcanvas-btn]'),
		$menu = $('[data-offcanvas-menu]'),
		$canvas = $('.canvas'),
		$body = $('body'),
		activeClass = 'navOffCanvasActive';
	
	if ($btn.length > 0)
	{
	    $btn.on('click', function (e)
	    {
			e.preventDefault();

			var vpWidth = document.documentElement.clientWidth,
				newLeft = 0;

			if ($body.hasClass(activeClass))
			{
				$body.removeClass(activeClass);
				$menu.css('left', '');
				$canvas.css('left', '');
			}
			else
			{
			    $body.addClass(activeClass);
			    if (vpWidth >= 1280 && vpWidth < 1520)
			    {
					newLeft = 240 - ((vpWidth - 1040) / 2);

					if (newLeft < 0)
					{
						newLeft = 0;
					}
					else if (newLeft > 240)
					{
						newLeft = 240;
					}
					$canvas.css('left', newLeft);
				}
			    else if (vpWidth >= 1520)
			    {
					newLeft = ((vpWidth - 1040) / 2) - 240;
					if (newLeft < 0)
					{
						newLeft = 0;
					}
					$menu.css('left', newLeft);
				}
			    else
			    {
					$menu.css('left', '');
				}
			}
		});

	    $(document).on('click.offcanvas', function (e)
	    {
			// hide off canvas menu if clicking elsewhere on page
	        if ($body.hasClass(activeClass) === true
                && $menu.is(e.target) === false
                && $menu.has(e.target).length === 0
                && $btn.is(e.target) === false
                && $btn.has(e.target).length === 0)
	        {
				$btn.trigger('click');
			}
		});
	}
})(jQuery);;var pc = pc || {};

// gift card
pc.gc = pc.gc || {};

pc.gc.eCommerceTracking = {};
pc.gc.eCommerceTracking.ecommerce = {};
pc.gc.eCommerceTracking.ecommerce.purchase = {};
pc.gc.eCommerceTracking.ecommerce.purchase.actionField = {};
pc.gc.eCommerceTracking.ecommerce.purchase.products = [];

(function ($) {

    $(document).on("input", "#giftCardNumber", function () {
        this.value = this.value.replace(/[^0-9]/g, '');
    });

    $(document).on("input", "#ZipCode", function () {
        this.value = this.value.replace(/[^0-9]/g, '');
    });

    $("#giftCardNumber").attr('maxlength', '19');
    
    var gc = {},
        errorMessages = {
            'default': '<p>Sorry there has been an error. Please try again later.</p>',
            'noConcessions': '<p>Sorry there are no concessions available.</p>',
            'addToBasket': '<p>Sorry there was an issue adding item to basket.</p>',
            'noBasket': '<p>Sorry there are no items in your basket.</p>',
            'checkPayment': '<p>Your credit card could not be processed. Please try again or use another card.</p>',
            'sendOrder': '<p>Sorry there was an issue sending your order.</p>',
            'noOrder': '<p>There was an issue retrieving your order.</p>',
            'orderLimit': '<p>You have exceeded the allowed purchase amount. If you would like to purchase e-Gift cards greater than $250 please contact our customer service department at (888-724-6362)</p>'
        };

    pc.gc.curstep = 0;

    stepGC();

    pc.gc.step = function () {
        stepGC();
    };

    pc.gc.addCards = function () {
        saveBasket();
    };

    $('.topTabLink.back').on('click', function (e) {
        if (pc.gc.curstep > 1) {
            e.preventDefault();
            //console.log(pc.gc.curstep);
            stepGC(pc.gc.curstep - 1);
        }
    });

    //here we go, breaking default browser functionality... sighhhhh....
    $(document).ready(function () {
        $('input[type=email][name=CustomerDetails--Confirmemail]').bind('paste', function (e) {
            e.preventDefault();
        });
    });

    pc.gc.selectGC = function () {
        //alert('selecting');

        $firstName = $('input[name="CustomerDetails--FirstName"]').val();
        $lastName = $('input[name="CustomerDetails--LastName"]').val();
        $email = $('input[name="CustomerDetails--Email"]').val();
        $confEmail = $('input[name="CustomerDetails--Confirmemail"]').val();

        var n = $email.localeCompare($confEmail);

        if (n === 0) {
            if ($('[name="gcstf"]:checked').val() === '1') {
                pc.gc.sendTo = $('[name="Concessions--FriendName"]').val();
            }
            else {
                pc.gc.sendTo = $firstName + ' ' + $lastName;
            }
            addGC();
            $('.my-gc').show();
            if (typeof dataLayer !== 'undefined') {
                dataLayer.push({
                    'event': 'VirtualPageview',
                    'virtualPageURL': '/giftcards/confirm',
                    'virtualPageTitle': 'Confirm Gift Cards'
                });
            }
        } else {
            $('input[name="CustomerDetails--Confirmemail"]').addClass('invalid');
        }

    };

    function setupNavURL() {

        // Sets the navigation link for gift cards.
        var $giftCardLink = $('[data-gift-card-link]'),
            urlPathSplit = null;



        if ($giftCardLink.attr('href') !== undefined) {
            urlPathSplit = $giftCardLink.attr('href').split('/');
        } else {
            urlPathSplit = window.location.pathname.split('/');

        }

        if (urlPathSplit.length > 2) {

            // Append region and cinema name to giftcard link url.
            var url = '/{{Region}}/{{Cinema}}/giftcard',
                region = urlPathSplit[1],
                cinema = urlPathSplit[2];

            url = url.replace(/{{Region}}/g, region).replace(/{{Cinema}}/g, cinema);
            $giftCardLink.attr('href', url);
        }

        // Test for Gift Card page and activate menu.
        urlPathSplit = window.location.pathname.split('/');
        if (urlPathSplit.length > 3) {
            if (urlPathSplit[3] === 'giftcard') {
                // Remove any active nav items and make gift cards active.
                $(".navMainLink").filter('.active').removeClass('active');
                $giftCardLink.addClass('active');
            }
        }
    }

    function setup() {

        var $gcPlace = $('[data-gc]');

        if ($gcPlace.length > 0) {
            $gcPay = $('[gc-payment]');
            // setup objects
            gc.temp = {};
            gc.basket = {};
            gc.basket.PlaceholderSrc = "/Themes/Theme_LandmarkTheaters/Content/images/gc-image.jpg";
            gc.basket.Concessions = [];
            gc.order = {
                'CustomerDetails': {
                    'FirstName': '',
                    'LastName': '',
                    'Email': '',
                    'PhoneNumber': ''
                },
                'Payment': {
                    'Number': '',
                    'ExpiryMonth': '',
                    'ExpiryYear': '',
                    'CardType': '',
                    'NameOnCard': '',
                    'PrimaryBillingCard': true
                }
            };

            // get concessions
            if (typeof pc.api.booking !== 'undefined' && typeof pc.api.giftStoreId !== 'undefined') {

                var showConcessionsSuccess = function (response) {
                    if (
                        typeof response === 'undefined' ||
                        response === null ||
                        typeof response.ListConcessionGrouping === 'undefined' ||
                        response.ListConcessionGrouping === null ||
                        response.ListConcessionGrouping.length === 0 ||
                        typeof response.ListConcessionGrouping[0].Items === 'undefined' ||
                        response.ListConcessionGrouping[0].Items === null ||
                        response.ListConcessionGrouping[0].Items.length === 0
                    ) {
                        showErrorPage(errorMessages['noConcessions']);
                        return;
                    }

                    var data = response.ListConcessionGrouping[0].Items;

                    for (var i = 0; i < data.length; i += 1) {

                        data[i]['pCost'] = (parseFloat(data[i]['Cost']) / 100);

                        data[i]['Quantity'] = 1;

                        data[i]['OrderDelivery'] = {

                            'IsGift': '',
                            'IsGiftWrapped': 'false',
                            'GiftMessage': '',
                            'BillingAddress': {
                                'Name': '',
                                'Email': ''
                            },
                            'DeliveryAddress': {
                                'Name': '',
                                'Email': ''
                            }
                        };
                    }

                    gc.data = data;

                    $(document).on('click', '[data-gc-add]', function (e) {
                        e.preventDefault();
                        addGC();
                    });

                };

                var showConcessionsFail = function () {
                    showErrorPage(errorMessages['noConcessions']);
                };

                $.ajax({
                    url: pc.api.booking + 'api/GiftCard/GetGiftCards/' + pc.api.giftStoreId,
                    type: 'GET'
                })
                    .done(showConcessionsSuccess)
                    .fail(showConcessionsFail);
            }

            $('[data-gc-error-back]').on('click', function (e) {
                e.preventDefault();
                stepGC(1);
            });
        }
    }



    function stepGC(navStep) {
        var $steps = $('[data-gc-step]'),
            $stepLinks = $('[data-gc-step-link]'),
            $curStep,
            $curStepLink,
            curStep = pc.gc.curstep,
            $newStep,
            $newStepLink,
            newStep = curStep + 1,
            maxStep = $steps.length,
            page = '',
            pageTitle = '';

        // console.log(curStep);

        if (newStep > maxStep) {
            newStep = maxStep;
        }

        if (typeof navStep !== 'undefined') {
            newStep = navStep;
        }

        if (curStep !== newStep) {

            showLoad();

            // clear old errors
            $('[data-gc-error]').html('');

            // console.log(curStep);
            //console.log(newStep);

            $curStep = $steps.filter('[data-gc-step="' + curStep + '"]');
            $curStepLink = $stepLinks.filter('[data-gc-step-link="' + curStep + '"]');
            $newStep = $steps.filter('[data-gc-step="' + newStep + '"]');
            $newStepLink = $stepLinks.filter('[data-gc-step-link="' + newStep + '"]');

            //console.log($curStepLink);
            //console.log($newStepLink);

            if ($curStep.length > 0) {
                //alert();
                $curStep.removeClass('active');
                //$tabLinks.filter('.active').removeClass('active');
                $curStepLink.removeClass('active');
            }

            $newStep.addClass('active');
            $newStepLink.addClass('active').removeClass('disabled');

            window.scrollTo(0, 0);

            switch (newStep) {
                case 0:
                    // error
                    page = 'error';
                    pageTitle = 'Error';
                    break;
                case 1:
                    //console.log('Step 1');
                    // select gift cards.
                    page = 'select';
                    pageTitle = 'Select Gift Cards';
                    break;
                case 2:
                    //console.log('Step 2');
                    // payment step                    
                    page = 'payment';
                    pageTitle = 'Payment';
                    break;
                case 3:
                    //console.log('Step 3');
                    // send payment info.
                    savePayment();
                    break;
                case 4:
                    //console.log('Step 4');
                    // confirmation
                    // done in sendOrderSuccess()
                    break;
            }

            // tracking
            if (page !== '') {
                if (typeof dataLayer !== 'undefined') {
                    dataLayer.push({
                        'event': 'VirtualPageview',
                        'virtualPageURL': '/giftcards/' + page,
                        'virtualPageTitle': pageTitle
                    });
                }
            }

            pc.gc.curstep = newStep;

            if (pc.gc.curstep !== 3 && pc.gc.curstep !== 4) {
                hideLoad();
            }
        }
    }

    $('[data-gc-step-link]').on('click', function () {
        if (!$(this).hasClass('disabled')) {
            var navStep = $(this).data('gc-step-link');
            removePayment();
            stepGC(navStep);
        }
    });

    function addConfirm() {
        // add gc
        //alert("called");
        if (typeof gc.temp.confirm === 'undefined') {
            $.get('/template?name=GiftCardConfirm&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                gc.temp.confirm = template;
                populateConfirm();
            });
        } else {
            populateConfirm();
        }
    }

    function populateConfirm() {

        // add gc
        var $gcPlace = $('[data-gc-confirm]');
        $gcPlace.empty();
        $gcPlace.append(Mustache.to_html(gc.temp.confirm, gc));

    }

    function addConfirmPurchase() {

        // add gc
        if (typeof gc.temp.confirmPurchase === 'undefined') {
            $.get('/template?name=GiftCardConfirmPurchase&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                gc.temp.confirmPurchase = template;
                populateConfirmPurchase();
            });
        } else {
            populateConfirmPurchase();
        }
    }

    function populateConfirmPurchase() {

        // add gc
        var $gcPlace = $('[data-gc-confirm-purchase]');
        $gcPlace.empty();
        $gcPlace.append(Mustache.to_html(gc.temp.confirmPurchase, gc));
    }

    function addBasket() {
        // add gc
        if (typeof gc.temp.basket === 'undefined') {
            $.get('/template?name=GiftCardOrder&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                gc.temp.basket = template;
                populateBasketImage();
                populateBasket();
            });
        } else {
            populateBasket();
        }
    }

    function populateBasketImage() {
        var gcBasketImage = $('[data-gc-basket-imgsrc]').attr('data-gc-basket-imgsrc');
        if (gcBasketImage !== "") {
            gc.basket.PlaceholderSrc = gcBasketImage;
        }
    }

    function populateBasket() {
        // add gc
        var $gcPlace = $('[data-gc-basket]');
        $gcPlace.empty();
        $gcPlace.append(Mustache.to_html(gc.temp.basket, gc));
    }

    function addGC() {
        // add gc
        if (typeof gc.temp.item === 'undefined') {
            $.get('/template?name=GiftCardItem&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                gc.temp.item = template;
                populateGC();
            });
        } else {
            populateGC();
        }
    }

    function populateGC() {
        // add gc
        var $gcPlace = $('[data-gc]'),
            id = gc.basket.Concessions.length,
            num = id + 1;

        $gcPlace.append(Mustache.to_html(gc.temp.item, {
            'id': id,
            'num': num
        }));

        $('input[type=email][name="Concessions--Email--Confirm"]').bind('paste', function (e) {
            e.preventDefault();
        });

        // add gc list
        if (typeof gc.temp.list === 'undefined') {
            $.get('/template?name=GiftCardList&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                gc.temp.list = template;
                populateGCList(id);
            });
        } else {
            populateGCList(id);
        }

        // show/hide message form
        $('[data-gc-msg-form]').toggleClass('dn', $('[data-gc-con-show]:checked').length !== 1);
    }

    function populateGCList(id) {
        // add gc items to list
        //console.log('pop ' + id);
        var $gcItem = $('[data-gc-item="' + id + '"]'),
            $gcList = $gcItem.find('[data-gc-list]'),
            $gcLess = $gcItem.find('[data-gc-list-less]'),
            $gcMore = $gcItem.find('[data-gc-list-more]'),
            $gcRemove = $gcItem.find('[data-gc-remove]'),
            $gcShow = $gcItem.find('[data-gc-con-show]'),
            $gcHide = $gcItem.find('[data-gc-con-hide]'),
            $gcHidden = $gcItem.find('[data-gc-con-hidden]'),
            $gcTextArea = $gcItem.find('textarea[maxlength]'),
            $gcAdd = $gcItem.find('[data-gc-add]');

        function moveItems(d) {
            // carousel functionality

            var dataLen = gc.data.length,
                curItem = parseInt($gcList.attr('data-gc-list')),
                maxItem = dataLen - 1;
            //summTotal = gc.data[curItem].pCost,
            curItem = curItem + d;

            if (curItem <= 0) {
                curItem = 0;
                $gcLess.addClass('inactive');
                $gcMore.removeClass('inactive');
            } else if (curItem >= maxItem) {
                curItem = maxItem;
                $gcMore.addClass('inactive');
                $gcLess.removeClass('inactive');
            } else {
                $gcLess.removeClass('inactive');
                $gcMore.removeClass('inactive');
            }

            $gcList.attr('data-gc-list', curItem);

            gc.basket.Concessions[id] = (JSON.parse(JSON.stringify(gc.data[curItem])));

            updateTotals(id, gc.data[curItem].pCost);
            // console.log(gc.data[curItem].pCost);

            $gcList.css('top', (curItem * 100 * -1) + '%');
        }

        function hiddenShow() {
            if ($gcHide.is(':checked')) {
                $gcHide.prop('checked', false);
                $gcHidden.slideDown(500);
            }
        }

        function hiddenHide(id) {
            if ($gcShow.is(':checked')) {
                $gcShow.prop('checked', false);
                $gcHidden.slideUp(500, function () {
                    $gcHidden.find('[name]').val('');
                    $gcHidden.find('.invalid').removeClass('invalid');
                    $gcHidden.find('[maxlength]').trigger('keyup');
                });

                var $firstName = $('input[name="CustomerDetails--FirstName"]').val();
                var $lastName = $('input[name="CustomerDetails--LastName"]').val();
                $('[data-gc-sendto="' + id + '"]').text($firstName + " " + $lastName);
                $('[data-gc-item-summary="' + id + '"] .gc-msg').hide();
            }
        }

        $gcList.html(Mustache.to_html(gc.temp.list, gc.data));

        // set gc item to first gc
        gc.basket.Concessions[id] = {};

        if (
            typeof gc.data !== 'undefined' && 
            gc.data !== null && 
            typeof gc.data[0] !== 'undefined' && 
            gc.data[0] !== null
        ) {
            gc.basket.Concessions[id] = (JSON.parse(JSON.stringify(gc.data[0])));
        }
        $gcList.attr('data-gc-list', 0);

        addGCSummary();

        updateTotals(id);

        // activate carousel
        if (gc.data.length > 1) {
            $gcLess.click(function (e) {
                e.preventDefault();
                if ($(this).hasClass('inactive') === false) {
                    moveItems(-1);
                }
            });

            $gcMore.click(function (e) {
                e.preventDefault();
                if ($(this).hasClass('inactive') === false) {
                    moveItems(1);
                }
            });

            $gcMore.removeClass('inactive');
        }

        $gcRemove.click(function (e) {
            e.preventDefault();
            removeGC($(this).closest('[data-gc-item]').attr('data-gc-item'));
        });

        $gcShow.click(function (e) {
            hiddenShow();
        });

        $gcHide.click(function (e) {
            hiddenHide($(this).closest('[data-gc-item]').attr('data-gc-item'));
        });

        $gcTextArea.each(function (index) {
            var $textarea = $(this),
                maxLength = $textarea.attr('maxlength');

            function updateCount() {
                $('[data-gc-con-maxlength="' + index + '"]').html((maxLength - $textarea.val().length) + ' characters');
            }

            $textarea.on('keyup', updateCount);

            $textarea.on('paste', null, function () {
                setTimeout(function () {
                    updateCount();
                }, 20);
            });

            $textarea.before('<span data-gc-con-maxlength="' + index + '"></span>').trigger('keyup');
        });
    }


    function addGCSummary() {
        // add gc
        if (typeof gc.temp.summ === 'undefined') {
            $.get('/template?name=GiftCardItemSummary&extensionToFind=mustache&extensionToReturn=txt', function (template) {
                gc.temp.summ = template;
                populateGCSummary();
            });
        } else {
            populateGCSummary();
        }
    }

    function populateGCSummary() {
        // add gc to summary

        var temp = [],
            conLen = gc.basket.Concessions.length;

        conLen = conLen <= 0 ? 0 : conLen - 1;

        $('[data-gc-summary]').append(Mustache.to_html(gc.temp.summ, {
            'id': conLen,
            'num': conLen + 1,
            'value': gc.data[0].pCost,
            'sendTo': pc.gc.sendTo
        }));
    }

    $(document).on('click', '[data-gc-remove-sum]', function (e) {
        e.preventDefault();
        sumId = $(this).attr('data-gc-remove-sum');
        removeGC(sumId);
        //console.log('doc ' + sumId);
    });

    $(document).on('focus', '[name="Concessions--Email--Confirm"]', function (e) {
        $(this).removeClass('invalid');
    });

    $(document).on('blur', '[name="Concessions--Email--Confirm"]', function (e) {
        var thisItemId = $(this).parents('[data-gc-item]').data('gc-item');
        $friendEmail = $('input[name="Concessions--Email"]').val();
        $confFriendEmail = $('input[name="Concessions--Email--Confirm"]').val();
        var n = $friendEmail.localeCompare($confFriendEmail);
        if (n !== 0) {
            $('input[name="Concessions--Email--Confirm"]').val('').addClass('invalid');
        }
    });


    function updateTotals(id, summVal) {
        //console.log(gc.basket);
        // update totals
        //console.log(summVal, id);

        var $subTotal = $('[data-gc-subtotal]'),
            $total = $('[data-gc-total]'),
            $summaryToUpdate = $('[data-gc-sum-total="' + id + '"]'),
            subTotal = 0,
            i = 0,

            itemsLen = gc.basket.Concessions.length;

        //console.log("con-len " + itemsLen);

        for (i = 0; i < itemsLen; i += 1) {
            subTotal += parseFloat(gc.basket.Concessions[i]['pCost']);
        }
        //console.log($summaryToUpdate);
        $summaryToUpdate.html(summVal);
        $subTotal.html(subTotal);
        $total.html(subTotal);
        gc.basket.subTotal = subTotal;
        gc.basket.Total = subTotal;
    }

    function removeGC(id) {

        var $gcItem = $('[data-gc-item="' + id + '"]'),
            $gcItemSummary = $('[data-gc-item-summary="' + id + '"]');

        // remove gc
        $gcItem.remove();
        $gcItemSummary.remove();
        gc.basket.Concessions.splice(id, 1);

        //console.log("consrem " + gc.basket.Concessions);
        //console.log("splice id " + id);


        // update other gc
        $('[data-gc-item]').each(function (i) {
            var $item = $(this);
            $(this).attr('data-gc-item', i);
            $item.find('[data-gc-num]').html(i + 1);

        });

        $('[data-gc-item-summary]').each(function (i) {
            var $item = $(this);
            $(this).attr('data-gc-item-summary', i);
            $item.find('[data-gc-num]').html(i + 1);
            $(this).find('[data-gc-remove-sum]').attr('data-gc-remove-sum', i);

        });

        // add gc if array empty
        if (gc.basket.Concessions.length === 0) {

            addGC();
        }

        updateTotals(id);
    }

    $(document).on('blur', 'input[name="Concessions--FriendName"]', function () {
        var id = $(this).attr('data-gc-sendto-field'),
            sendTo = $(this).val();
        updateSendTo(id, sendTo);
    });

    function updateSendTo(id, sendTo) {
        $('[data-gc-sendTo]').text(sendTo);
        pc.gc.sendTo = sendTo;
    }

    $(document).on('blur', 'textarea[name="Concessions--GiftMessage"]', function () {
        var id = $(this).attr('data-gc-msg-field'),
            msg = $(this).val();
        updateGcMsg(id, msg);
    });

    function updateGcMsg(id, msg) {
        $msgToUpdate = $('[data-gc-msg="' + id + '"]');
        $msgToUpdate.text(msg);
        $('[data-gc-item-summary="' + id + '"] .gc-msg').show();
    }

    function saveBasket() {

        //console.log('Gift Card : saveBasket()');

        var $items = $('[data-gc-item]'),
            itemsLen = $items.length,
            subTotal = 0;

        // save details
        gc.order.CustomerDetails.FirstName = $('[name="CustomerDetails--FirstName"]').val();
        gc.order.CustomerDetails.LastName = $('[name="CustomerDetails--LastName"]').val();
        gc.order.CustomerDetails.FullName = gc.order.CustomerDetails.FirstName + " " + gc.order.CustomerDetails.LastName;
        gc.order.CustomerDetails.Email = $('[name="CustomerDetails--Email"]').val();

        //console.log(gc.basket.Concessions);

        // loop [data-gc-item]
        $items.each(function (i) {
            var $item = $(this);

            //console.log(i);

            // Add the billing address to all concessions.
            gc.basket.Concessions[i].OrderDelivery.BillingAddress.Name = gc.order.CustomerDetails.FullName;
            gc.basket.Concessions[i].OrderDelivery.BillingAddress.Email = gc.order.CustomerDetails.Email;

            /*if ($item.find('[name="Concessions--Email"]').val() === '') {
      
              //console.log('me');
      
              gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Name = gc.order.CustomerDetails.FullName;
              gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Email = gc.order.CustomerDetails.Email;
              gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.SendTo = gc.order.CustomerDetails.FullName;
              gc.basket.Concessions[i].OrderDelivery.IsGift = 'false';
            } else {
      
              //console.log('friend');
      
              gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Name = $item.find('[name="Concessions--FriendName"]').val();
              gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Email = $item.find('[name="Concessions--Email"]').val();
              gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.SendTo = $item.find('[name="Concessions--FriendName"]').val();
              gc.basket.Concessions[i].OrderDelivery.IsGift = 'true';
            }*/

            if ($('[name="gcstf"]:checked').val() === '1') {
                // friend
                gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Name = $('[name="Concessions--FriendName"]').val();
                gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Email = $('[name="Concessions--Email"]').val();
                gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.SendTo = $('[name="Concessions--FriendName"]').val();
                gc.basket.Concessions[i].OrderDelivery.IsGift = 'true';
                gc.basket.Concessions[i].OrderDelivery.GiftMessage = $item.find('[name="Concessions--GiftMessage"]').val();
            }
            else {
                // purchaser
                gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Name = gc.order.CustomerDetails.FullName;
                gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.Email = gc.order.CustomerDetails.Email;
                gc.basket.Concessions[i].OrderDelivery.DeliveryAddress.SendTo = gc.order.CustomerDetails.FullName;
                gc.basket.Concessions[i].OrderDelivery.IsGift = 'false';
            }
        });

        // console.log(gc.basket.Concessions);
        // console.log(gc.order.CustomerDetails);

        addBasket();        
        testCaptcha();
    }

    function hideNumber(number) {
        var blockedOut = "XXXX-XXXX-XXXX-";
        var slicedNumber = number.slice(-4);
        var hiddenNumber = blockedOut + slicedNumber;
        return hiddenNumber;
    }

    function savePayment() {

        // console.log('Gift Card : savePayment()');

        gc.order.Payment.NameOnCard = $('[name="Payment--NameOnCard"]').val();
        gc.order.Payment.Number = $('[name="Payment--Number"]').val();
        gc.order.Payment.HiddenNumber = hideNumber(gc.order.Payment.Number);
        gc.order.Payment.ExpiryMonth = $('[name="Payment--ExpiryMonth"]').val();
        gc.order.Payment.ExpiryYear = $('[name="Payment--ExpiryYear"]').val();
        gc.order.Payment.CardType = $('[name="Payment--CardType"]').val();

        gc.order.Payment.CVC = $('[name="Payment--CVC"]').val();
        gc.order.CustomerDetails.ZipCode = $('[name="CustomerDetails--ZipCode"]').val();

        sendOrder();
    }

    function removePayment() {

        gc.order.Payment.NameOnCard = "";
        gc.order.Payment.Number = "";
        gc.order.Payment.ExpiryMonth = "";
        gc.order.Payment.ExpiryYear = "";
        gc.order.Payment.CardType = "";

        // Adding CVC causes the payment to fail on Vista call.
        // gc.order.Payment.CVC = "";

        // Adding ZipCode causes the payment to fail on Vista call.
        // gc.order.CustomerDetails.ZipCode = "";

        $('[name="Payment--NameOnCard"]').val("");
        $('[name="Payment--Number"]').val("");
        $('[name="Payment--ExpiryMonth"]').val("");
        $('[name="Payment--ExpiryYear"]').val("");
        $('[name="Payment--CardType"]').val("");
        $('[name="Payment--CVC"]').val("");
        $('[name="CustomerDetails--ZipCode"]').val("");
        // show these in case hidden by error in step 3
        $('[data-gc-continue="ConfirmPurchase"]').show();
        $('[data-gc-step="3"] h2').show();
    }

    function testCaptcha() {

        pc.captcha.response = $('#g-recaptcha-response').val() || '';
        var captchaJsonData = {};
        captchaJsonData['captchaResponse'] = pc.captcha.response;


        if (pc.captcha.response.length == 0) {
            $('[data-form-validate-captcha-message]').removeClass('dn');
            return false;
        }

        $.ajax({
                beforeSend: function (xhrObj) {
                    xhrObj.setRequestHeader("Content-Type", "application/json");
                    xhrObj.setRequestHeader("Accept", "application/json");
                },
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: 'api/Captcha/ValidateCaptcha',
                data: JSON.stringify(captchaJsonData)
            })
            .done(function (response) {

                if (response === "OK") {
                    $('[data-form-validate-captcha-message]').addClass('dn');
                    sendBasketConcessions();
                } else {
                    $('[data-form-validate-captcha-message]').removeClass('dn');
                    return false;
                }
            });
    }

    function sendBasketConcessions() {

        // function to send basket concessions

        $('[data-gc-card-error]').html('');

        // Build the AddConcession json data.
        var conJsonData = {};
        conJsonData["CinemaId"] = pc.api.giftStoreId;
        conJsonData["Concessions"] = [];
        conJsonData['SessionId'] = "0";
        conJsonData['IsGiftStoreOrder'] = "true";
        conJsonData['CaptchaResponse'] = pc.captcha.response;

        for (var i = 0, len = gc.basket.Concessions.length; i < len; i += 1) {
            conJsonData["Concessions"].push(gc.basket.Concessions[i]);
            //gc.basket
        }

        //console.log("conJsonData = " + conJsonData);

        showLoad();

        $.ajax({
            beforeSend: function (xhrObj) {
                xhrObj.setRequestHeader("Content-Type", "application/json");
                xhrObj.setRequestHeader("Accept", "application/json");
            },
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            url:  'api/GiftCardApi/AddGiftCards/?cinemaId=' + pc.api.giftStoreId,
            data: JSON.stringify(conJsonData)
        })
            .always(function (response) {
                var data;
                var message;

                if (
                    typeof response !== 'undefined' &&
                    response !== null
                ) {
                    if (
                        typeof response.responseJSON !== 'undefined' &&
                        response.responseJSON !== null
                    ) {
                        data = response.responseJSON;
                    }
                    else {
                        data = response;
                    }

                    if (
                        data.StatusCode === 200 &&
                        typeof data.UserSessionId !== 'undefined' &&
                        data.UserSessionId !== null && 
                        typeof data.OrderId !== 'undefined' && 
                        data.OrderId !== null
                    ) {
                        gc['UserSessionId'] = data.UserSessionId;
                        gc['OrderId'] = data.OrderId;
                        stepGC(2);
                        return;
                    }
                    else if (
                        typeof data.PeachCode !== 'undefined' &&
                        data.PeachCode !== null &&
                        data.PeachCode === 83
                    ) {
                        message = errorMessages['orderLimit'];
                    }
                }
                showErrorPage(message);
            });
    }

    function sendOrder() {
        // function to send order.

        showLoad();

        var callData = {}; 
        callData['CinemaId'] = pc.api.giftStoreId;
        callData['OrderId'] = gc.OrderId;
        callData["UserSessionId"] = gc.UserSessionId;
        callData['CustomerDetails'] = gc.order.CustomerDetails;
        callData['CustomerDetails']["FullName"] = undefined; // Delete
        callData['PaymentList'] = [gc.order.Payment];

        function sendOrderSuccess(data) {
            addConfirm();
            hideLoad();
            $('[data-gc-confirm-copy').show();

            // success function for sending order

            var cookieSet = false;

            if (typeof data !== 'undefined') {
                // check if we have cookie as only want to do this part once

                if (typeof docCookies !== 'undefined' && docCookies.getItem('gaOrderId' + data.BookingReference) !== null) {
                    cookieSet = true;
                }

                if (cookieSet === false) {

                    var products = [];

                    for (var i = 0; i < gc.basket.Concessions.length; i++) {
                        products.push({
                            'id': gc.basket.Concessions[i].Id,
                            'name': gc.basket.Concessions[i].Description,
                            'category': 'Gift Card',
                            'price': parseFloat(gc.basket.Concessions[i].Cost / 100).toFixed(2),
                            'quantity': gc.basket.Concessions[i].Quantity
                        });
                    }

                    if (typeof data.BookingFee !== 'undefined' && data.BookingFee > 0) {
                        products.push({
                            'id': '0',
                            'name': 'Booking Fee',
                            'category': 'Gift Card',
                            'price': parseFloat(data.BookingFee / 100).toFixed(2),
                            'quantity': '1',
                            'variant': 'Booking Fee'
                        });
                    }

                    if (typeof dataLayer !== 'undefined') {
                        dataLayer.push({
                            'event': 'VirtualPageview',
                            'virtualPageURL': '/giftcards/confirmation',
                            'virtualPageTitle': 'Confirmation',
                            'stepName': 'confirmation',
                            'ecommerce': {
                                'purchase': {
                                    'actionField': {
                                        'id': data.BookingConfirmationId,
                                        'revenue': (parseFloat(data.GrandTotal) / 100).toFixed(2)
                                    },
                                    'products': products
                                }
                            }
                        });
                    }

                    if (typeof docCookies !== 'undefined') {
                        docCookies.setItem('gaOrderId' + data.BookingReference, data.BookingReference, Infinity);
                    }
                }
                else {
                    if (typeof dataLayer !== 'undefined') {
                        dataLayer.push({
                            'event': 'VirtualPageview',
                            'virtualPageURL': '/giftcards/confirmation-repeat',
                            'virtualPageTitle': 'Confirmation Repeat'
                        });
                    }
                }
            }
        }

        // console.log(callData);

        // make call to send order
        $.ajax({
            beforeSend: function (xhrObj) {
                xhrObj.setRequestHeader("Content-Type", "application/json");
                xhrObj.setRequestHeader("Accept", "application/json");
            },
            url: pc.api.booking + 'api/GiftCard/CompleteOrder?cinemaId=' + pc.api.giftStoreId,
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(callData)
        })
            .done(function (data) {
                gc['BookingConfirmationId'] = data.BookingConfirmationId;
                sendOrderSuccess(data);
            })
            .fail(function (a, b, c) {
                // todo - check data and check if card detail issue

                // card detail issue
                if (typeof a !== 'undefined' && typeof a.responseText !== 'undefined') {
                    var errorData = JSON.parse(a.responseText);

                    if (typeof errorData.PeachErrorCode !== 'undefined' && errorData.PeachErrorCode !== null && errorData.PeachErrorCode.toString() === '2') {
                        // go to payment page
                        stepGC(2);
                        // show payment error
                        showError(errorMessages['checkPayment']);
                        // exit
                        return;
                    }
                }

                // go to error page
                showErrorPage(errorMessages['sendOrder']);
            });
    }

    function showErrorPage(message) {
        // update error on error page
        if (typeof message !== 'undefined') {
            $('[data-gc-errorpage]').html(message);
        }
        else {
            $('[data-gc-errorpage]').html(errorMessages['default']);
        }
        // disable tabs
        $('[data-tab-link]').addClass('disabled');
        // show error page
        stepGC(0);
    }

    function showError(message) {
        // show error on page
        if (typeof message !== 'undefined') {
            $('[data-gc-error]').html(message);
        }
        else {
            $('[data-gc-error]').html(errorMessages['default']);
        }
    }

    function showLoad() {
        $('[data-book-load]').show();

    }

    function hideLoad() {
        $('[data-book-load]').hide();
    }

    function lsSupport() {
        // function to test for localstorage
        var a = 'test';
        try {
            localStorage.setItem(a, a);
            localStorage.removeItem(a);
            return true;
        } catch (e) {
            return false;
        }
    }

    function init() {
        $(function () {
            setupNavURL();
            setup();
        });
    }


    init();

})(jQuery);

(function ($) {

    var $showhide = $('[data-gc-con]');

    if ($showhide.length > 0) {
        $showhide.find('[data-gc-con-show]').on('change', function (e) {
            //e.preventDefault();
            if (this.checked) {
                $showhide.find('[data-gc-con-hidden]').removeClass('dn');
                pc.gc.sendTo = $('[name="Concessions--FriendName"]').val();
                $('[data-gc-sendTo]').text(pc.gc.sendTo);
                $('[data-gc-msg-form]').removeClass('dn');
            }
            else {
                $showhide.find('[data-gc-con-hidden]').addClass('dn');
                pc.gc.sendTo = $('input[name="CustomerDetails--FirstName"]').val() + ' ' + $('input[name="CustomerDetails--LastName"]').val();
                $('[data-gc-sendTo]').text(pc.gc.sendTo);
                $('[data-gc-msg-form]').addClass('dn');
            }
        });
    }

})(jQuery);;var pc = pc || {};

(function ($) {

    if ($('[data-check-gc]').length === 0) {
        return;
    }

    // 76*** regular card 14 characters
    var gcRegular = ['75', '76', '77'];

    // 70*** egift cards with 18 characters
    var gcEGift = ['70'];

    var gcObj;

    function showGCCheckSuccess(data) {
        /*{"Id":"12312312312","BalanceRemaining":"500"}*/
        var msg = '';
        if (typeof data.BalanceRemaining !== 'undefined') {
            if (data.BalanceRemaining === 0) {
                msg = 'The Balance on this Gift Card is $0';
            }
            else {
                msg = 'Your balance is $' + (parseFloat(data.BalanceRemaining) / 100).toFixed(2);
            }
            $('[data-check-gc-msg]').html(msg).show();
            hideLoad();
        }
        else {
            showGCCheckError();
        }
    }

    function showGCCheckError() {
        $('[data-check-gc-msg]').html('This Gift Card is invalid.').show();
        hideLoad();
    }

    function checkGC() {
        var $gcInput = $('[data-check-gc-input]');
        var inputVal = $gcInput.val() || '';
        var showError = false;

        showLoad();
        $('[data-check-gc-msg]').hide().html('');

        if (inputVal === '') {
            showGCCheckError();
            return false;
        }

        // check if value is numeric
        if ($.isNumeric(inputVal) === false) {
            showGCCheckError();
            return false;
        }

        // check character length
        var inputValFirstTwo = inputVal.slice(0, 2);

        if (gcRegular.indexOf(inputValFirstTwo) > -1 && inputVal.length !== 14) {
            showGCCheckError();
            return false;
        }

        if (gcEGift.indexOf(inputValFirstTwo) > -1 && inputVal.length !== 18) {
            showGCCheckError();
            return false;
        }

        gcObj.GetGiftCardDetails(inputVal, showGCCheckSuccess, showGCCheckError);
    }

    function showLoad() {
        $('[data-check-gc-load]').show();
    }

    function hideLoad() {
        $('[data-check-gc-load]').hide();
    }

    $('[data-check-gc-input]').on('keyup paste', function (e) {
        if (e.type === 'paste') {
            var newValue = e.originalEvent.clipboardData.getData('text').trim();

            $(this).attr('maxlength', gcRegular.indexOf(newValue.slice(0, 2)) > -1 ? 14 : 18);

            this.value = newValue;
        }
        else {
            $(this).attr('maxlength', gcRegular.indexOf(this.value.slice(0, 2)) > -1 ? 14 : 18);
        }

        $('[data-check-gc-msg]').hide().html('');
    });

    $.when(
        $.getScript(pc.api.booking + 'ClientScripts/require.js')
    ).done(function () {
        // get booking api scripts
        require.config({
            paths: {
                httprequest: pc.api.booking + 'ClientScripts/HTTPRequest',
                peachlogger: pc.api.booking + 'ClientScripts/PeachLogger',
                ticketbookingclient: pc.api.booking + 'ClientScripts/TicketBookingClient',
                sessionmanager: pc.api.booking + 'ClientScripts/SessionManager',
                cors: '/themes/default/content/js/_cors'
            }
        });

        define('jquery', [], function () {
            return jQuery;
        });

        require([
            'ticketbookingclient',
            'cors'
        ], function (ticketBookingClient, cors) {
            // we have booking api scripts, we can now proceed
            var tickets = ticketBookingClient;

            if (typeof pc.api !== 'undefined' && typeof pc.api.booking !== 'undefined') {
                gcObj = new tickets(pc.api.booking + 'api/', '154', 0, '', function () { }, function () { });

                $('[data-check-gc-btn]').on('click', function (e) {
                    e.preventDefault();
                    checkGC();
                });
            }
        });
    });
})(jQuery);;var pc = pc || {};

// objects to store error messages
pc.errorCode = {};

// default errors
pc.errorCode.defaultMessage = {
    message: 'There has been an error with your order, please contact us to resolve the issue.',
    showContactUs: false
};

pc.errorCode.defaultMessageTickets = {
    message: 'There has been an error with your order. This screening may now be sold out.  Please try a different selection or show time.',
    showContactUs: false
};

pc.errorCode.defaultMessageSeats = {
    message: 'Seats for the selection you are trying to purchase for are no longer available. Please try a different selection or show time.',
    showContactUs: false
};

pc.errorCode.defaultMessagePayment = {
    message: 'There was an error processing your payment. Please check your payment details and try again.',
    showContactUs: false
};

// vista error codes
pc.errorCode.vista = {
    '2':  {
        message: 'Theatre ticketing is currently unavalable, please try back later. Your credit card was not charged.',
        showContactUs: false
    },
    '4': {
        message: 'Your information was not properly entered. Please try again.',
        showContactUs: false
    },
    '5': {
        message: 'Theatre ticketing is currently unavalable, please try back later. Your credit card was not charged.',
        showContactUs: false
    },
    '8': {
        message: 'This Showtime is either soldout, or seats requested exceeds remaining availablity. Please try a different selection or show time.',
        showContactUs: false
    },
    '9': {
        message: 'There was an error with your booking.  Your credit card was not charged, Please try again.',
        showContactUs: false
    },
    '10': {
        message: 'There was an error with your booking.  Your credit card was not charged, Please try again.',
        showContactUs: false
    },
    '11': {
        message: 'There was an error with your booking.  Your credit card was not charged, Please try again.',
        showContactUs: false
    },
    '12': {
        message: 'Your credit card could not be processed possibly due to incorrect information provided. Your card has not been charged and any "pending status" will resolve within 48 hours. Please try again or use another card.',
        showContactUs: false
    },
    '13': {
        message: 'There was an error processing your payment. Please check your booking email confirmation or contact the theatre to verify if payment was received and the booking is confirmed.',
        showContactUs: false
    },
    '14': {
        message: 'Payment processed, but ticket order not finalized. Please check your booking email confirmation or contact the theatre to verify if payment was received and the booking is confirmed.',
        showContactUs: true
    },
    '24': {
        message: 'There was an error processing your payment. Please check your booking email confirmation or contact the theatre to verify if payment was received and the booking is confirmed.',
        showContactUs: true
    },
    '25': {
        message: 'Your credit card could not be processed. Please try again or use another card.',
        showContactUs: false
    },
    '26': {
        message: 'Your credit card could not be processed possibly due to incorrect information provided. Your card has not been charged and any "pending status" will resolve within 48 hours. Please try again or use another card.',
        showContactUs: false
    },
    '27': {
        message: 'Card entered did not have enough funds to cover order amount. Transaction voided, please try again.',
        showContactUs: false
    },
    '28': {
        message: 'Card entered did not have enough funds to cover order amount. Transaction voided, please try again.',
        showContactUs: false
    }
};

// peach error codes
pc.errorCode.peach = {
    '1': {
        message: 'Your credit card could not be processed possibly due to incorrect information provided. Your card has not been charged and any "pending status" will resolve within 48 hours. Please try again or use another card.',
        showContactUs: false
    },
    '2': {
        message: 'Your credit card could not be processed possibly due to incorrect information provided. Your card has not been charged and any "pending status" will resolve within 48 hours. Please try again or use another card.',
        showContactUs: false
    },
    '3': {
        message: 'There was an error processing your payment. Please check your booking email confirmation or contact the theatre to verify if payment was received and the booking is confirmed.',
        showContactUs: false
    },
    '4': {
        message: 'Your order has already been submitted for processing. Please check your email for confirmation.',
        showContactUs: true
    },
    '55': {
        message: 'Your order has timed out, please start a new order.',
        showContactUs: false
    },
    '999': {
        message: 'If you would like to use your gift card, please select Use Gift Card for Payment to proceed with payment.',
        showContactUs: false
    }
};
;
var pc = pc || {};

// accordion finder functionality

(function ($) {
    var $accordionFinderCta = $('#accordion-finder-cta'),
        $accordionFinderOverlay = $('#accordion-finder-overlay'),
        $accordionFinderOverlayClose = $('#accordion-finder-overlay-close');

    function setup() {

        var accordion =
        {
            "ActiveRegionId": 0,
            "Location":
            {
                "Region": "",
                "Theatre": "",
                "IsSet": false
            }
        };

        var $accordionFinder = $(this);
        
        var $locationFinderBtn = $accordionFinder.find('#location-finder-btn');
        
        function setData() {
            $accordionFinder.data('accordion', accordion);
        }

        setData();

        function openPromise() {
            return $.Deferred(function (def) {
                $accordionFinder.find('[data-accordion]').one('down.zf.accordion', function () {
                    def.resolve();
                });
            });
        }

        function closePromise() {
            return $.Deferred(function (def) {
                $accordionFinder.find('[data-accordion]').one('up.zf.accordion', function () {
                    def.resolve();
                });
            });
        }

        function switchActivePanel(selectedRegionId) {
            var $closeTheatre = $accordionFinder.find("[data-accordion-theatre-item='" + accordion.ActiveRegionId + "']");
            if ($closeTheatre.length > 0
                && $closeTheatre.hasClass('is-active')) {
                var closeObserver = closePromise();
                closeObserver.done(function () {
                    $closeTheatre.addClass('dn');
                    openSelectedPanel(selectedRegionId);
                });

                var $objToClose = $closeTheatre.find('[data-tab-content]');
                $accordionFinder.find('[data-accordion]').foundation('up', $objToClose);
            }
            else if ($closeTheatre.length > 0) {
                $closeTheatre.addClass('dn');
                openSelectedPanel(selectedRegionId);
            }
        }

        function openSelectedPanel(selectedRegionId) {
            var $openTheatre = $accordionFinder.find("[data-accordion-theatre-item='" + selectedRegionId + "']");
            if ($openTheatre.length > 0) {
                $openTheatre.removeClass('dn');

                var openObserver = openPromise();
                openObserver.done(function () {
                    accordion.ActiveRegionId = selectedRegionId;
                    setData();

                    if ($accordionFinder.find('[data-accordion-theatre-item="' + selectedRegionId + '"] [data-accordion-theatre-id]').length === 1) {
                        $accordionFinder.find('[data-accordion-theatre-item="' + selectedRegionId + '"] [data-accordion-theatre-id]').trigger('click');
                    }
                });

                var $objToOpen = $openTheatre.find('[data-tab-content]');
                $accordionFinder.find('[data-accordion]').foundation('down', $objToOpen, true);
            }
        }

        function closeSelectedPanel(selectedRegionId) {
            var $closeTheatre = $accordionFinder.find("[data-accordion-theatre-item='" + selectedRegionId + "']");
            if ($closeTheatre.length > 0) {
                $closeTheatre.removeClass('dn');

                var closeObserver = closePromise();
                closeObserver.done(function () {
                    accordion.ActiveRegionId = selectedRegionId;
                    setData();
                });

                var $objToClose = $closeTheatre.find('[data-tab-content]');
                $accordionFinder.find('[data-accordion]').foundation('up', $objToClose);
            }
        }

        function getLocationCookie() {
            if (location.search.indexOf('?portal') === 0) {
                document.cookie = 'PCC.Location' + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT; secure; SameSite=Lax';
            }

            if (typeof docCookies !== 'undefined'
                && docCookies.getItem('PCC.Location') !== null) {
                var locationCookie = docCookies.getItem('PCC.Location');
                if (locationCookie.toLowerCase().indexOf("region:") !== -1) {
                    accordion.Location.Region = locationCookie.toLowerCase().replace("region:", "");
                    setData();
                }

                if (locationCookie.toLowerCase().indexOf("cinema:") !== -1) {
                    locationCookie = locationCookie.toLowerCase().replace("cinema:", "").split("/");

                    accordion.Location.Region = locationCookie[0];
                    accordion.Location.Theatre = locationCookie[1];
                    setData();
                }
            }
        }

        // Disabled the location finder button.
        $locationFinderBtn.on('click', function (evt) {
            evt.preventDefault();
            return false;
        });

        // Add events for the region panel links to open assotiated theatre panels.
        var $regionLnk = $accordionFinder.find('[data-accordion-region-id]');
        $regionLnk.each(function () {
            $(this).on('click', function (e) {
                e.preventDefault();

                if ($accordionFinder.find('[data-filminfo-sessions]').length === 1) {
                    $accordionFinder.find('[data-filminfo-sessions]').html('');
                }

                var $title = $accordionFinder.find('[data-accordion-region-title]');

                if ($title.length > 0 && $title.parent('[data-accordion-item].is-active').length > 0) {
                    $title.trigger('click');
                }

                // Ensure the initial blank theatre panel is hidden.
                if (accordion.ActiveRegionId === 0) {
                    $accordionFinder.find('[data-accordion-empty-theatre]').addClass('dn');
                }

                // Set the location finder button href for a selected region.
                var regionName = $(this).attr('data-accordion-region-name').toUpperCase();
                var regionUrl = $(this).attr('data-accordion-region-link');

                var linkUrl = '/' + regionUrl;
                
                // Update the location finder button.
                $locationFinderBtn.html('SEE SHOWTIMES for ' + regionName)
                    .unbind('click')
                    .attr('href', linkUrl)
                    .removeClass('disabled')
                    .prop('disabled', false);

                //
                // Open and/or close panels.
                //

                var selectedRegionId = $(this).attr('data-accordion-region-id');
                if (selectedRegionId !== accordion.ActiveRegionId) {
                    if (accordion.ActiveRegionId === 0) {
                        openSelectedPanel(selectedRegionId);
                    }
                    else {
                        switchActivePanel(selectedRegionId);
                    }
                }

                if (selectedRegionId === accordion.ActiveRegionId) {
                    var $currentTheatre = $accordionFinder.find("[data-accordion-theatre-item='" + accordion.ActiveRegionId + "']");
                    if ($currentTheatre.hasClass('is-active')) {
                        closeSelectedPanel(selectedRegionId);
                    }
                    else {
                        openSelectedPanel(selectedRegionId);
                    }
                }

                if (typeof docCookies !== 'undefined' && docCookies !== null) {
                    var expDate = new Date();
                    expDate.setMonth(expDate.getMonth() + 1);
                    docCookies.setItem('PCC.Region', regionUrl, expDate, '/');
                }

                return false;
            });
        });

        if ($accordionFinder.find('[data-accordion-region]').length > 0) {
            $accordionFinder.find('[data-accordion-region-link]').on('click', function (e) {
                $accordionFinder.find("[data-accordion-region-link]").each(function () {
                    $(this).removeClass('active');
                });

                $(this).addClass('active');
            });

            $accordionFinder.find('.accordion-theatre-link').on('click', function (e) {
                $accordionFinder.find(".accordion-theatre-link").each(function () {
                    $(this).removeClass('active');
                });

                $(this).addClass('active');
            });

        }

        // Add events for all the theatre panels links.
        var $theatreLnk = $accordionFinder.find('[data-accordion-theatre-id]');
        $theatreLnk.each(function () {
            $(this).on('click', function (e) {
                e.preventDefault();
                
                // check if we are on circuit level film info and show showtimes instead
                if ($accordionFinder.find('[data-filminfo-sessions]').length === 1) {
                    getFilmSessions(this.dataset.accordionTheatreId);
                    return false;
                }

                // Set the location finder button href for a selected theatre.
                var $region = $accordionFinder.find("[data-accordion-region-id='" + accordion.ActiveRegionId + "']");
                var regionName = $region.attr('data-accordion-region-name').toUpperCase();
                var regionUrl = $region.attr('data-accordion-region-link');

                var theatreName = $(this).attr('data-accordion-theatre-name').toUpperCase();
                var theatreUrl = $(this).attr('data-accordion-theatre-link');

                var linkUrl = '/' + regionUrl + '/' + theatreUrl;
                
                // Update the location finder button.
                $locationFinderBtn.html('SEE SHOWTIMES for ' + regionName + ', ' + theatreName)
                    .unbind('click')
                    .attr('href', linkUrl)
                    .removeClass('disabled')
                    .prop('disabled', false);                               

                return false;
            });
        });

        getLocationCookie();

        if (accordion.Location.Region === "") {
            $accordionFinder.find('[data-accordion-region-title]').parent('[data-accordion-item]').not('.is-active').addClass('is-active');
        }
    }

    function getFilmSessions(theatreId) {
        var $sessionContainer = $('[data-filminfo-sessions]');
        var template = $('[data-filminfo-template-sessions]').html() || '';
        var filmId = $('[data-filminfo-filmid]').attr('data-filminfo-filmid');

        if (
            $sessionContainer.length === 0 ||
            typeof theatreId === 'undefined' ||
            theatreId === null ||
            typeof filmId === 'undefined' ||
            filmId === null ||
            typeof pc === 'undefined' || 
            pc === null || 
            typeof pc.film === 'undefined' ||
            pc.film === null || 
            typeof pc.film.setup === 'undefined' ||
            pc.film.setup === null
        ) {
            return;
        }
        
        $.ajax({
            url: pc.api.movie + 'movies/' + pc.api.circuit + '/' + theatreId + '/' + filmId + '?splitByAttributes=true'
        }).always(function (response) {
            var data;

            if (
                typeof response !== 'undefined' &&
                response !== null &&
                typeof response.Result !== 'undefined' &&
                response.Result !== null
            ) {
                data = response.Result;
            }
            else if (
                typeof response !== 'undefined' &&
                response !== null &&
                typeof response.Result === 'undefined'
            ) {
                data = response;
            }
            
            if (typeof data === 'undefined' || data === null) {
                return;
            }

            window.filmData = data;

            if ($('.datepicker').length > 0) {
                $('.datepicker').remove();
            }

            $sessionContainer.html(Mustache.render(template, data));

            if (
                typeof pc !== 'undefined' &&
                pc !== null &&
                typeof pc.film !== 'undefined' &&
                pc.film !== null
            ) {
                if (
                    typeof pc.film.temp !== 'undefined' &&
                    pc.film.temp !== null &&
                    typeof pc.film.temp.datelist !== 'undefined' &&
                    pc.film.temp.datelist !== null &&
                    pc.film.temp.datelist.length > 0
                ) {
                    // clear datepicker dates
                    pc.film.temp.datelist.length = 0;
                }
                pc.film.setup();
            }
        });

    }

    function setupModelOverlay() {
                
        $accordionFinderOverlayClose.removeClass('dn');

        $accordionFinderCta.on('click', function (evt) {
            evt.preventDefault();

            var accordion = $accordionFinderOverlay.find('[data-accordion-finder]').data('accordion');

            $accordionFinderOverlay.addClass('active');

            if ($(window).width() > 760) {

                $('body').css('overflow', 'hidden');
                $('body').css('position', 'fixed');
                $('body').css('left', '0');
                $('body').css('right', '0');

            }

            // Open the region and cinema in the accordion if cookie set.
            if ($accordionFinderOverlay.length > 0
                && accordion.Location.Region !== ""
                && accordion.Location.IsSet === false) {
                var $locRegionLnk = $accordionFinderOverlay.find("[data-accordion-region-link='" + accordion.Location.Region + "']");
                if ($locRegionLnk.length > 0 && $locRegionLnk.hasClass('active') === false) {
                    $locRegionLnk.trigger('click');
                    $accordionFinderOverlay.find('[data-accordion-empty-theatre]').addClass('dn');
                }
            }
            else {
                $accordionFinderOverlay.find('[data-accordion-region-title]').parent('[data-accordion-item]').not('.is-active').trigger('click');
            }

            $accordionFinderOverlay.find('[data-accordion-region-title]:first').focus();

            return false;
        });

        $accordionFinderOverlayClose.on('click', function (evt) {
            evt.preventDefault();
            $accordionFinderOverlay.removeClass('active');
            $('body').css('overflow', 'auto');
            $('body').css('position', 'relative');
        });

        $accordionFinderOverlay.on('click', function (evt) {
            if (evt.target === this) {
                $accordionFinderOverlay.removeClass('active');
                $('body').css('overflow', 'auto');
                $('body').css('position', 'relative');
            }
        });
    }

    function init() {
        var $accordionFinder = $('[data-accordion-finder]');
        if ($accordionFinder.length > 0) {
            $accordionFinder.each(setup);
        }

        if ($accordionFinderCta.length > 0
            && $accordionFinderOverlay.length > 0) {
            setupModelOverlay();
        }

        $(document).on('click', '[data-accordion-empty-theatre] a', function (e) {
            e.preventDefault();
        });
    }

    init();

    pc.accordion = {
        setup: setup
    };

})(jQuery);
;var pc = pc || {};

// quick buy
pc.qb = pc.qb || {};

pc.qb.field = pc.qb.field || {
    'region': {
        'name': 'region',
        'method': '',
        'template': '',
        'spanText': 'PLEASE SELECT',
        'spanNoData': 'NONE AVAILABLE'
    },
    'cinema': {
        'name': 'cinema',
        'method': 'CinemasByRegion/{{circuit}}/{{region}}',
        'template': '{{#.}}<a href="#" class="quickBuyOptionBtn" data-nr-qb-theatreName	data-quickbuy-option-cinema="{{Id}}"><span class="quickbuyCinemaName">{{Name}}{{#Address}}</span><span class="quickBuyCinemaAddress">{{Address}}</span>{{/Address}}{{#Phone}}<span class="quickBuyCinemaPhone">{{Phone}}</span>{{/Phone}}{{/.}}</a>',
        'spanText': 'PLEASE SELECT',
        'spanNoData': 'NONE AVAILABLE'
    },
    'film': {
        'name': 'film',
        'method': 'movies/GetFilmsByCinema/{{circuit}}/{{cinema}}',
        'template': '{{#.}}<a href="#" class="quickBuyOptionBtn" data-nr-qb-filmName data-quickbuy-option-film="{{FilmId}}">{{Title}}</a>{{/.}}',
        'spanText': 'PLEASE SELECT MOVIE / EVENT',
        'spanNoData': 'NONE AVAILABLE'
    },
    'date': {
        'name': 'date',
        'method': 'movies/{{circuit}}/{{cinema}}/{{film}}',
        'template': '{{#.}}{{#Sessions}}<a href="#" class="quickBuyOptionBtn" data-nr-qb-date data-quickbuy-option-date="{{Date}}">{{DisplayDate}}</a>{{/Sessions}}{{/.}}',
        'spanText': 'PLEASE SELECT',
        'spanNoData': 'NONE AVAILABLE'
    },
    'time': {
        'name': 'time',
        'method': 'movies/{{circuit}}/{{cinema}}/{{film}}/{{date}}',
        'template': '{{#.}}{{#Sessions}}{{#Times}}{{^SoldOut}}<a href="#" class="quickBuyOptionBtn" data-nr-qb-time	data-quickbuy-option-time="{{Scheduleid}}" title="{{StartTime}}, {{DisplayDate}} - {{Title}}">{{StartTime}}</a>{{/SoldOut}}{{/Times}}{{/Sessions}}{{/.}}',
        'spanText': 'PLEASE SELECT',
        'spanNoData': 'NONE AVAILABLE'
    }
};

(function ($) {
    var $quickBuy = $('[data-quickbuy]'),
        $quickBuyBtn = $('[data-quickbuy-btn]'),
        $quickBuyOverlay = $('#quick-buy-overlay'),
        $curRegion = $('[data-id-region]'),
        $curCinema = $('[data-id-cinema]');

    function setup() {
        if ($quickBuy.length > 0
            && $quickBuyBtn.length > 0) {
            // quick buy show/hide
            $quickBuyBtn.on('click', function (evt) {
                evt.preventDefault();
                evt.stopPropagation();

                var $btn = $(this),
                    btnHeight = $btn.outerHeight();

                if ($btn.hasClass('active') === true) {
                    // overlay show
                    $quickBuyOverlay.removeClass('active');

                    $btn.removeClass('active');
                    $quickBuy.removeClass('active');
                }
                else {
                    $btn.addClass('active');
                    $quickBuy.css('top', btnHeight).addClass('active');

                    // overlay hide
                    $quickBuyOverlay.addClass('active');
                }
            });

            $('.quick-buy-load').each(function () {
                var $this = $(this);
                $this.on('click',
                    function (evt) {
                        evt.preventDefault();
                        evt.stopPropagation();
                    });
            });

            setupModelOverlay();
            setupUserLocation();
            getLocationCookie();
        }
    }

    //
    // Sets the quickBuy data attribute for the region and cinema
    // using the page body data attributes.
    //
    function setupUserLocation() {
        if ($curRegion.length > 0) {
            $quickBuy.data('region', $curRegion.attr('data-id-region'));
        }

        if ($curCinema.length > 0) {
            $quickBuy.data('cinema', $curCinema.attr('data-id-cinema'));
        }
    }

    function setupSelects() {
        var $selects = $quickBuy.find('[data-quickbuy-select]'),
            $submit = $quickBuy.find('[data-quickbuy-submit]');

        $selects.on('click', function (evt) {
            evt.preventDefault();
            var $thisSelect = $(this),
                thisType = $thisSelect.attr('data-quickbuy-select'),
                isDisabled = $thisSelect.hasClass('disabled');

            if (isDisabled === false) {
                
                switch (thisType) {
                    case pc.qb.field.region.name:

                        var $thisRegionOptions = $("[data-quickbuy-options='region']"),
                            $thisRegionSelectSpan = $thisSelect.find('span'),
                            isRegionActive = $thisRegionOptions.hasClass('active');

                        if (isRegionActive) {
                            $thisRegionOptions.removeClass('active');
                        }
                        else {
                            $thisRegionOptions.addClass('active')
                                .find('.quickBuyOptionBtn')
                                .each(function () {
                                    var $thisOptionBtn = $(this);

                                    $thisOptionBtn.off('click').on('click', function (evt) {
                                        evt.preventDefault();

                                        // Set the select buttons span with the selected option data
                                        var regionName = $thisOptionBtn.html();
                                        $thisRegionSelectSpan.html(regionName);
                                        var regionId = $thisOptionBtn.attr('data-quickbuy-option-region');
                                        $quickBuy.data('region', regionId);
                                        $thisRegionOptions.removeClass('active');

                                        // Reset
                                        resetSelect(pc.qb.field.film);
                                        resetSelect(pc.qb.field.date);
                                        resetSelect(pc.qb.field.time);
                                        resetSelect($submit);

                                        // Update
                                        updateSelectOptions(pc.qb.field.cinema);

                                        return false;
                                    });
                                });
                        }

                        break;
                    case pc.qb.field.cinema.name:

                        var $thisCinemaOptions = $("[data-quickbuy-options='cinema']"),
                            $thisCinemaSelectSpan = $thisSelect.find('span'),
                            isCinemaActive = $thisCinemaOptions.hasClass('active');

                        if (isCinemaActive) {
                            $thisCinemaOptions.removeClass('active');
                        }
                        else {
                            $thisCinemaOptions.addClass('active')
                                .find('.quickBuyOptionBtn')
                                .each(function () {
                                    var $thisOptionBtn = $(this);

                                    $thisOptionBtn.off('click').on('click', function (evt) {
                                        evt.preventDefault();

                                        // Set the select buttons span with the selected option data
                                        var cinemaName = $thisOptionBtn.html();
                                        $thisCinemaSelectSpan.html(cinemaName);
                                        var cinemaId = $thisOptionBtn.attr('data-quickbuy-option-cinema');
                                        $quickBuy.data('cinema', cinemaId);
                                        $thisCinemaOptions.removeClass('active');

                                        // Reset
                                        resetSelect(pc.qb.field.date);
                                        resetSelect(pc.qb.field.time);
                                        resetSelect($submit);

                                        // Update
                                        updateSelectOptions(pc.qb.field.film);

                                        return false;
                                    });
                                });
                        }

                        break;
                    case pc.qb.field.film.name:

                        var $thisFilmOptions = $("[data-quickbuy-options='film']"),
                            $thisFilmSelectSpan = $thisSelect.find('span'),
                            isFilmActive = $thisFilmOptions.hasClass('active');

                        if (isFilmActive) {
                            $thisFilmOptions.removeClass('active');
                        }
                        else {
                            $thisFilmOptions.addClass('active')
                                .find('.quickBuyOptionBtn')
                                .each(function () {
                                    var $thisOptionBtn = $(this);

                                    $thisOptionBtn.off('click').on('click', function (evt) {
                                        evt.preventDefault();

                                        // Set the select buttons span with the selected option data
                                        var filmName = $thisOptionBtn.html();
                                        $thisFilmSelectSpan.html(filmName);
                                        var filmId = $thisOptionBtn.attr('data-quickbuy-option-film');
                                        $quickBuy.data('film', filmId);
                                        $thisFilmOptions.removeClass('active');

                                        // Reset
                                        resetSelect(pc.qb.field.time);
                                        resetSelect($submit);

                                        // Update
                                        updateSelectOptions(pc.qb.field.date);

                                        return false;
                                    });
                                });
                        }

                        break;
                    case pc.qb.field.date.name:

                        var $thisDateOptions = $("[data-quickbuy-options='date']"),
                            $thisDateSelectSpan = $thisSelect.find('span'),
                            isDateActive = $thisDateOptions.hasClass('active');

                        if (isDateActive) {
                            $thisDateOptions.removeClass('active');
                        }
                        else {
                            $thisDateOptions.addClass('active')
                                .find('.quickBuyOptionBtn')
                                .each(function () {
                                    var $thisOptionBtn = $(this);

                                    $thisOptionBtn.off('click').on('click', function (evt) {
                                        evt.preventDefault();

                                        // Set the select buttons span with the selected option data
                                        var dateName = $thisOptionBtn.html();
                                        $thisDateSelectSpan.html(dateName);
                                        var dateValue = $thisOptionBtn.attr('data-quickbuy-option-date').split("T")[0];
                                        $quickBuy.data('date', dateValue);
                                        $thisDateOptions.removeClass('active');

                                        // Reset
                                        resetSelect($submit);

                                        // Update
                                        updateSelectOptions(pc.qb.field.time);

                                        return false;
                                    });
                                });
                        }

                        break;
                    case pc.qb.field.time.name:

                        var $thisTimeOptions = $("[data-quickbuy-options='time']"),
                            $thisTimeSelectSpan = $thisSelect.find('span'),
                            isTimeActive = $thisTimeOptions.hasClass('active');

                        if (isTimeActive) {
                            $thisTimeOptions.removeClass('active');
                        }
                        else {
                            $thisTimeOptions.addClass('active')
                                .find('.quickBuyOptionBtn')
                                .each(function () {
                                    var $thisOptionBtn = $(this);

                                    $thisOptionBtn.off('click').on('click', function (evt) {
                                        evt.preventDefault();

                                        var timeName = $thisOptionBtn.html();
                                        $thisTimeSelectSpan.html(timeName);

                                        var timeValue = $thisOptionBtn.attr('data-quickbuy-option-time');
                                        $quickBuy.data('time', timeValue);

                                        $thisTimeOptions.removeClass('active');

                                        updateSubmit();

                                        return false;
                                    });
                                });
                        }

                        break;
                }
            }
        });

        $submit.on('click', function (e) {
            var $this = $(this);
            if ($this.attr('href') === '#' && $this.hasClass('disabled') === true) {
                e.preventDefault();
                return false;
            }
        });

        function updateSelectOptions(field) {
            if (field.name === 'region') {
                return;
            }

            var $selectBtn = $quickBuy.find('[data-quickbuy-select="' + field.name + '"]'),
                $selectOptions = $quickBuy.find('[data-quickbuy-options="' + field.name + '"]'),
                $selectBtnSpan = $selectBtn.find('span'),
                $selectBtnLoader = $selectBtn.find('.quick-buy-load'),
                method,
                url;

            if ($selectBtn.length > 0 && $selectOptions.length > 0) {
                $selectBtn.removeClass('disabled');
                $selectBtnLoader.show();
                $selects.prop('disabled', true);

                method = field.method
                    .replace(/{{circuit}}/g, pc.api.circuit)
                    .replace(/{{region}}/g, $quickBuy.data('region'))
                    .replace(/{{cinema}}/g, $quickBuy.data('cinema'))
                    .replace(/{{film}}/g, $quickBuy.data('film'))
                    .replace(/{{date}}/g, $quickBuy.data('date'));

                url = pc.api.movie + method;

                if (field.name === 'cinema') {
                    url = pc.api.clientApi + 'api/CinemasByRegion/' + $quickBuy.data('region');
                }

                $.getJSON(url)
                    .done(function (response) {
                        $selectBtnLoader.hide();

                        var data;

                        if (
                            typeof response !== 'undefined' &&
                            response !== null &&
                            typeof response.Result !== 'undefined' &&
                            response.Result !== null &&
                            response.Result.length !== 0
                        ) {
                            data = response.Result;
                        }
                        else if (
                            typeof response !== 'undefined' &&
                            response !== null &&
                            response.length !== 0 &&
                            typeof response.Result === 'undefined'
                        ) {
                            data = response;
                        }

                        if (Array.isArray(data) === false) {
                            data = [data];
                        }

                        if (
                            typeof pc.api !== 'undefined' &&
                            pc.api !== null &&
                            typeof pc.api.customAttributes !== 'undefined' &&
                            pc.api.customAttributes !== null &&
                            pc.api.customAttributes.length > 0 &&
                            typeof data !== 'undefined' &&
                            data !== null &&
                            data.length > 0 &&
                            (
                                field.name === 'film' ||
                                field.name === 'date' ||
                                field.name === 'time'
                            )
                        ) {
                            for (var f = data.length - 1; f >= 0; f--) {
                                if (
                                    typeof data[f].Sessions !== 'undefined' &&
                                    data[f].Sessions !== null &&
                                    data[f].Sessions.length > 0
                                ) {
                                    for (var s = data[f].Sessions.length - 1; s >= 0; s--) {
                                        if (
                                            typeof data[f].Sessions[s].Times !== 'undefined' &&
                                            data[f].Sessions[s].Times !== null &&
                                            data[f].Sessions[s].Times.length > 0
                                        ) {
                                            for (var t = data[f].Sessions[s].Times.length - 1; t >= 0; t--) {
                                                if (
                                                    data[f].Sessions[s].Times[t].SoldOut === true || 
                                                    data[f].Sessions[s].Times[t].NotBookable === true ||
                                                    data[f].Sessions[s].Times[t].SessionExpired === true
                                                ) {
                                                    data[f].Sessions[s].Times.splice(t, 1);
                                                    continue;
                                                }

                                                if (
                                                    typeof data[f].Sessions[s].Times[t].Experience !== 'undefined' &&
                                                    data[f].Sessions[s].Times[t].Experience !== null &&
                                                    data[f].Sessions[s].Times[t].Experience.length > 0
                                                ) {
                                                    for (var e = data[f].Sessions[s].Times[t].Experience.length - 1; e >= 0; e--) {
                                                        if (pc.api.customAttributes.indexOf(parseInt(data[f].Sessions[s].Times[t].Experience[e].Id)) > -1) {
                                                            data[f].Sessions[s].Times.splice(t, 1);
                                                            break;
                                                        }
                                                    }
                                                }
                                            }

                                            if (data[f].Sessions[s].Times.length === 0) {
                                                data[f].Sessions.splice(s, 1);
                                            }
                                        }
                                    }

                                    if (data[f].Sessions.length === 0) {
                                        data.splice(f, 1);
                                    }
                                }
                                else {
                                    data.splice(f, 1);
                                }
                            }
                        }

                        if (typeof data !== 'undefined' && data !== null && data.length !== 0) {
                            if ((field.name === 'date' || field.name === 'time') && (typeof data[0].Sessions === 'undefined' || data[0].Sessions === null || data[0].Sessions.length === 0)) {
                                $selectBtn.addClass('disabled');
                                $selectBtnSpan.html(field.spanNoData);
                                $selectOptions.html("");
                            }
                            else {
                                $selectBtnSpan.html(field.spanText);
                                var html = Mustache.to_html(field.template, data);
                                $selectOptions.html(html);
                            }
                        }
                        else {
                            $selectBtn.addClass('disabled');
                            $selectBtnSpan.html(field.spanNoData);
                            $selectOptions.html("");
                        }
                    })
                    .fail(function (jqxhr, textStatus, error) {
                        //console.log('Request Failed: ' + textStatus + ', ' + error);

                        $selectBtnLoader.hide();
                        $selectBtn.addClass('disabled');
                        $selectBtnSpan.html(field.spanNoData);
                        $selectOptions.html("");
                    })
                    .always(function () {
                        $selects.not('.disabled').prop('disabled', false);
                    });
            }
        }

        function updateSubmit() {
            var url = pc.url.booking || '';

            if ($submit.length > 0
                && url !== ''
                && typeof $quickBuy.data('time') !== 'undefined'
                && $quickBuy.data('time') !== '') {
                url = url
                    .replace(/{{Scheduleid}}/g, $quickBuy.data('time'))
                    .replace(/{{CinemaId}}/g, $quickBuy.data('cinema'))
                    .replace(/{{FilmId}}/g, $quickBuy.data('film'));

                $submit.attr('href', url).removeClass('disabled');
            }
            else {
                resetSelect($submit);
            }
        }

        function resetSelect(field) {
            var $resetSelectBtn,
                $resetSelectSpan,
                $resetSelectOptions;

            if (typeof field.name === 'string') {
                // Select and options
                $resetSelectBtn = $('[data-quickbuy-select="' + field.name + '"]');
                $resetSelectSpan = $resetSelectBtn.find('span');
                $resetSelectOptions = $('[data-quickbuy-options="' + field.name + '"]');

                $quickBuy.data(field.name, "");

                $resetSelectOptions.removeClass('active').html("");
                $resetSelectSpan.html(field.spanText);
                $resetSelectBtn.addClass('disabled');
            }
            else {
                // Submit button.
                $submit.attr('href', '#').addClass('disabled');
            }
        }

        if ($selects.length === 5) {
            // Enable the regions
            var $regionSelect = $("[data-quickbuy-select='region']"),
                regionId = $quickBuy.data('region') || 0,
                cinemaId = $quickBuy.data('cinema') || 0;

            $regionSelect.removeClass('disabled');
            
            if (regionId > 0) {
                var $regionOptionBtn = $("[data-quickbuy-option-region='" + regionId + "']");
                if ($regionOptionBtn.length > 0) {
                    // Set the select buttons span with the selected option data
                    var regionName = $regionOptionBtn.html();
                    var $regionSelectSpan = $regionSelect.find('span');
                    $regionSelectSpan.html(regionName);

                    // Reset
                    resetSelect(pc.qb.field.film);
                    resetSelect(pc.qb.field.date);
                    resetSelect(pc.qb.field.time);
                    resetSelect($submit);
                }

                $.getJSON(pc.api.clientApi + 'api/CinemasByRegion/' + regionId)
                    .done(function (data) {
                        if (
                            typeof data !== 'undefined' &&
                            data !== null &&
                            data.length > 0
                        ) {
                            var html = Mustache.to_html(pc.qb.field.cinema.template, data);
                            var $cinemaSelectOptions = $quickBuy.find('[data-quickbuy-options="cinema"]');
                            $cinemaSelectOptions.html(html);

                            var $cinemaSelect = $("[data-quickbuy-select='cinema']");
                            $cinemaSelect.removeClass('disabled').prop('disabled', false);

                            var $cinemaOptionBtn = $("[data-quickbuy-option-cinema='" + cinemaId + "']");
                            if ($cinemaOptionBtn.length > 0) {
                                // Set the select buttons span with the selected option data                                
                                var cinemaName = $cinemaOptionBtn.html();
                                var $cinemaSelectSpan = $cinemaSelect.find('span');
                                $cinemaSelectSpan.html(cinemaName);
                            }

                            // Reset
                            resetSelect(pc.qb.field.film);
                            resetSelect(pc.qb.field.date);
                            resetSelect(pc.qb.field.time);
                            resetSelect($submit);
                        }

                        if (cinemaId > 0) {
                            updateSelectOptions(pc.qb.field.film);
                            $('#filmCheck').removeClass('disabled');
                        }
                    });
            }
        }
    }

    function setupModelOverlay() {
        $quickBuyOverlay.on('click', function (evt) {
            if (evt.target === this) {
                $quickBuyBtn.removeClass('active');
                $quickBuy.removeClass('active');

                // overlay hide
                $quickBuyOverlay.removeClass('active');
            }
        });
    }

    //
    // Sets the quickBuy data attribute for the region and cinema
    // using the users location cookie.
    //
    function getLocationCookie() {
        var regionName,
            cinemaName;

        if (typeof docCookies !== 'undefined'
            && docCookies.getItem('PCC.Location') !== null) {
            var locationCookie = docCookies.getItem('PCC.Location');

            if (locationCookie.toLowerCase().indexOf("region:") !== -1) {
                regionName = locationCookie.toLowerCase().replace("region:", "");
                var regionObserver = regionCookiePromise(regionName);
                regionObserver.done(function () {
                    setupSelects();
                });
            }

            if (locationCookie.toLowerCase().indexOf("cinema:") !== -1) {
                var cookieSplit = locationCookie.toLowerCase().replace("cinema:", "").split("/");
                regionName = cookieSplit[0];
                cinemaName = cookieSplit[1];
                var cinemaObserver = cinemaCookiePromise(regionName, cinemaName);
                cinemaObserver.done(function () {
                    setupSelects();
                });
            }
        }
        else {
            setupSelects();
        }
    }

    function regionCookiePromise(regionName) {
        return $.Deferred(function (def) {
            var url = pc.api.clientApi + 'api/RegionByName/' + regionName;
            $.getJSON(url)
                .done(function (data) {
                    if (typeof data !== 'undefined'
                        && data !== null) {
                        $quickBuy.data('region', data.Id);
                        def.resolve();
                    }
                    else {
                        def.reject();
                    }
                })
                .fail(function () {
                    def.reject();
                });
        });
    }

    function cinemaCookiePromise(regionName, cinemaName) {
        return $.Deferred(function (def) {
            var url = pc.api.clientApi + 'api/RegionByName/' + regionName;
            $.getJSON(url)
                .done(function (data) {
                    if (typeof data !== 'undefined'
                        && data !== null) {
                        $quickBuy.data('region', data.Id);

                        url = pc.api.clientApi + 'api/CinemaByName/' + cinemaName;
                        $.getJSON(url)
                            .done(function (data) {
                                if (typeof data !== 'undefined'
                                    && data !== null) {
                                    $quickBuy.data('cinema', data.Id);
                                    def.resolve();
                                }
                                else {
                                    def.reject();
                                }
                            })
                            .fail(function () {
                                def.reject();
                            });
                    }
                })
                .fail(function () {
                    def.reject();
                });
        });
    }

    function init() {
        $(function () {
            setup();
        });
    }

    init();
})(jQuery);;
var pc = pc || {};

(function ($) {

    //CVV2 tooltip toggle for booking and gift cards

    $('[data-cvv-icon]').on('click', function () {
        $('[data-cvv-info]').toggle();
    });

    // film times toggle
    var $filmList = $('[data-film]');

    if ($filmList.find('.filmItemTimes').length > 0)
    {
        $filmList.not('[data-film="landingpage"]').find('.filmItemTimes').each(function ()
        {
            var $session = $(this),
                $times = $session.find('.filmTimes-1'),
                $toggleBtn = $session.find('[data-toggle-btn]'),
                $links = $times.find('.filmTimeItem'),
                linksLen = $links.length;

            if (linksLen > 6) {
                $toggleBtn.addClass('show-m');
            }

            if (linksLen > 9) {
                $toggleBtn.addClass('show-l show-s');
            }
        });

        $filmList.filter('[data-film="landingpage"]').find('.filmItemTimes').each(function ()
        {
            var $session = $(this),
                $times = $session.find('.filmTimes-1'),
                $toggleBtn = $session.find('[data-toggle-btn]'),
                $links = $times.find('.filmTimeItem'),
                linksLen = $links.length;

            if (linksLen > 2) {
                $toggleBtn.addClass('show-m');
            }

            if (linksLen > 3) {
                $toggleBtn.addClass('show-l show-s');
            }
        });
    }

    // stop bfcache so js will run if back button used
    window.onunload = function () { };

    // sticky footer 
    $(window).on('load resize', function ()
    {
        var $body = $('body'),
            $content = $('.content'),
            mh = 0,
            ch = 0,
            vh = document.documentElement.clientHeight,
            $child = $body.find('> .gridRow, > .canvas');

        if ($child.length > 0
            && $content.length > 0)
        {
            $child.each(function ()
            {
                mh += $(this).outerHeight(true);
            });
		
            ch = $content.outerHeight(true);

            if (mh < vh)
            {
                mh = vh - mh + ch;
                $content.css('min-height', mh);
            }
        }
    });

    // ellipsis
    pc.ellipsis = function ($el) {
    function setup($items) {
      var itemsLen,
				count = 0;

      $items = $items.filter(':visible');

      itemsLen = $items.length;

      for (count=0; count<itemsLen; count+=1) {
        var $this = $items.eq(count);

        if ($this.length > 0 && $this.find('[data-ellipsis]').length > 0) {

          var thisHeight = $this.height(),
						$child = $this.find('> *').not('[data-ellipsis]'),
						childHeight = 0,
						newHeight,
						$ellipsis = $this.find('[data-ellipsis]'),
						$origText = $this.find('[data-origtext]'),
						thisText = $ellipsis[0].innerHTML,
						newText = thisText.split(' ');

          if ($child.length > 0) {
            for (var i=0,len=$child.length; i<len; i+=1) {
              childHeight += $child.eq(i).outerHeight(true);
            }
          }

          newHeight = Math.floor(thisHeight - childHeight);
          if (newHeight && newHeight > 0) {
            while ($ellipsis.outerHeight() >= newHeight) {
              if (newText.length < 5) {
                break;
              }
              newText = newText.slice(0, newText.length - 5);

              $ellipsis[0].innerHTML = newText.join(' ') + '...';
            }
          }
          $ellipsis.removeAttr('data-ellipsis');
        }
      }
    }

    if ($el.length > 0) {
      if (typeof window.isloaded === 'undefined') {
        $(window).load(function () {
          window.isloaded = true;
          setup($el);
        });
      }
      else {
        setup($el);
      }
    }
  };

    $(window).load(function () {
		window.isloaded = true;
	});
})(jQuery);

(function () {
    var backlinks = document.querySelectorAll('[data-backlink]');

    if (backlinks === null || backlinks.length === 0) {
        return;
    }

    var isNewTab = false;
    
    if (
        (
            window.history.length === 1 &&
            document.referrer.indexOf(window.location.origin) === 0
        )
        ||
        (
            typeof window.opener !== 'undefined' &&
            window.opener !== null &&
            window.location.href.indexOf(window.opener.origin) === 0
        )
    ) {
        isNewTab = true;
    }
        
    for (var i = 0; i < backlinks.length; i++) {
        if (isNewTab) {
            backlinks[i].textContent = 'Close this page';
            backlinks[i].addEventListener('click', function (e) {
                e.preventDefault();
                window.close();
            }, false);
        }
        else {
            backlinks[i].addEventListener('click', function (e) {
                e.preventDefault();

                var linkHref = this.href;

                var locationTimeout = setTimeout(function () {
                    // window.history.back might fail so fallback to href
                    window.location = linkHref;
                }, 10);

                window.addEventListener('beforeunload', function () {
                    // brower is going somewhere so clear timeout
                    clearTimeout(locationTimeout);
                });

                if (
                    typeof this.dataset.backlink !== 'undefined' &&
                    this.dataset.backlink !== null &&
                    this.dataset.backlink !== ''
                ) {
                    if (this.dataset.backlink.toLowerCase() === linkHref.toLowerCase()) {
                        // href and data match so use browser back functionality so we pick up hash
                        window.history.back();
                    }
                }
                else if (window.history.length > 1 && document.referrer.indexOf(document.domain) > -1) {
                    window.history.back();
                }
            }, false);
        }
    }
})();;(function ($) {
    var $page = $('[data-allmovies]');

    if ($page.length === 0) {
        return;
    }

    Date.prototype.getWeek = function () {
        var onejan = new Date(this.getFullYear(), 0, 1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
    };

    var $filters = $page.find('[data-allmovies-filters]');
    var $search = $page.find('[data-allmovies-search]');
    var $filter = $page.find('[data-allmovies-filter]');
    var $sort = $page.find('[data-allmovies-sort]');
    var $count = $page.find('[data-allmovies-count]');
    var $list = $page.find('[data-allmovies-list]');
    var $messageNone = $page.find('[data-allmovies-message-none]');
    var itemTemplate = $('[data-allmovies-template-item]').html() || '';

    var dataAll;

    // now playing - fri to thu based on current date.
    var day = new Date();
    var weekdays = [5, 6, 0, 1, 2, 3, 4];
    var dayIndex = weekdays.indexOf(day.getDay());
    var week = [];

    for (var d = dayIndex; d < weekdays.length; d++) {        
        var dayFormatted = day.getFullYear() + '-' + ('0' + (day.getMonth() + 1)).slice(-2) + '-' + ('0' + day.getDate()).slice(-2);
        week.push(dayFormatted);
        day.setDate(day.getDate() + 1);
    }

    function filterSortFilms(e) {
        var startTime = typeof performance !== 'undefined' ? performance.now() : 0;
        var delay = 500;

        if (typeof e !== 'undefined' && e !== null && typeof e.target !== 'undefined' && e.target !== null && e.target.id === 'all_movies_search') {
            delay = 200;
        }

        var searchValue = $search.val();
        var filterValue = $filter.val();
        var sortValue = $sort.val();
        var filteredData;

        $list.addClass('loading');

        searchValue = searchValue.trim();
        searchValue = searchValue.toLowerCase();

        filteredData = dataAll.filter(function (film) {
            if (searchValue === '') {
                return true;
            }

            var lowerTitle = film.Title.toLowerCase();

            return lowerTitle.indexOf(searchValue) > -1;
        });

        filteredData = filteredData.filter(function (film) {
            switch (filterValue) {
                case 'nowPlaying':
                    return film.IsNowPlaying === true;

                case 'comingSoon':
                    return film.IsComingSoon === true;

                case 'all':
                    return true;
            }
        });

        filteredData.sort(function (filmA, filmB) {
            switch (sortValue) {
                case 'nameAZ':
                    if (filmA.Title > filmB.Title) {
                        return 1;
                    }
                    if (filmA.Title < filmB.Title) {
                        return -1;
                    }
                    return 0;

                case 'releaseDate':
                    // now playing
                    if (filterValue === 'nowPlaying') {
                        // 1. release date descending
                        if (filmA.ReleaseDate.getTime() < filmB.ReleaseDate.getTime()) {
                            return 1;
                        }
                        if (filmA.ReleaseDate.getTime() > filmB.ReleaseDate.getTime()) {
                            return -1;
                        }

                        // 2. cms priority ascending
                        if (filmA.Order > filmB.Order) {
                            return 1;
                        }
                        if (filmA.Order < filmB.Order) {
                            return -1;
                        }

                        // 3. alphabetical
                        if (filmA.Title > filmB.Title) {
                            return 1;
                        }
                        if (filmA.Title < filmB.Title) {
                            return -1;
                        }

                        return 0;
                    }

                    // coming soon
                    if (filterValue === 'comingSoon') {
                        // coming soon sessions
                        if (filmA.Week !== null && filmB.Week !== null) {
                            // 1. date playing ascending week
                            if (filmA.Week > filmB.Week) {
                                return 1;
                            }
                            if (filmA.Week < filmB.Week) {
                                return -1;
                            }

                            // 2. cms priority ascending
                            if (filmA.Order > filmB.Order) {
                                return 1;
                            }
                            if (filmA.Order < filmB.Order) {
                                return -1;
                            }

                            // 3. release date descending
                            if (filmA.ReleaseDate.getTime() < filmB.ReleaseDate.getTime()) {
                                return 1;
                            }
                            if (filmA.ReleaseDate.getTime() > filmB.ReleaseDate.getTime()) {
                                return -1;
                            }

                            // 4. alphabetical
                            if (filmA.Title > filmB.Title) {
                                return 1;
                            }
                            if (filmA.Title < filmB.Title) {
                                return -1;
                            }

                            return 0;
                        }
                        else {
                            // coming soon no sessions
                            // 1. release date descending
                            if (filmA.ReleaseDate.getTime() < filmB.ReleaseDate.getTime()) {
                                return 1;
                            }
                            if (filmA.ReleaseDate.getTime() > filmB.ReleaseDate.getTime()) {
                                return -1;
                            }

                            // 2. cms priority ascending
                            if (filmA.Order > filmB.Order) {
                                return 1;
                            }
                            if (filmA.Order < filmB.Order) {
                                return -1;
                            }

                            // 3. alphabetical
                            if (filmA.Title > filmB.Title) {
                                return 1;
                            }
                            if (filmA.Title < filmB.Title) {
                                return -1;
                            }

                            return 0;
                        }
                    }

                    // all
                    if (filterValue === 'all') {
                        // 1. release date descending
                        if (filmA.ReleaseDate.getTime() < filmB.ReleaseDate.getTime()) {
                            return 1;
                        }
                        if (filmA.ReleaseDate.getTime() > filmB.ReleaseDate.getTime()) {
                            return -1;
                        }

                        // 2. alphabetical
                        if (filmA.Title > filmB.Title) {
                            return 1;
                        }
                        if (filmA.Title < filmB.Title) {
                            return -1;
                        }

                        return 0;
                    }
            }
        });

        //console.log(filteredData);

        if (startTime !== 0) {
            delay = delay - (performance.now() - startTime);

            if (delay < 0) {
                delay = 0;
            }
        }

        setTimeout(function () {
            $list.html(Mustache.render(itemTemplate, filteredData)).removeClass('loading');
            $count.html(filteredData.length);
        }, delay);
    }

    $search.on('keyup', filterSortFilms);
    $filter.on('change', filterSortFilms);
    $sort.on('change', filterSortFilms);

    function displayFilms(response) {
        if (typeof response === 'undefined' || response === null || response.length === 0) {
            $messageNone.removeClass('dn');
            $list.addClass('dn');
            return;
        }

        var filmCounter = 0;

        dataAll = response.filter(function (film) {
            if (typeof film.Experiences !== 'undefined' && film.Experiences !== null && film.Experiences.length > 0) {
                for (var i = 0; i < film.Experiences.length; i++) {
                    if (typeof film.Experiences[i].ExternalId !== 'undefined' && film.Experiences[i].ExternalId !== null && film.Experiences[i].ExternalId === 'SpcScrng') {
                        return false;
                    }
                }
            }

            return true;
        }).map(function (film) {
            var filmData = {
                FilmId: film.FilmId,
                Title: film.Title,
                FriendlyName: film.FriendlyName,
                Trailer: film.Trailer || film.MediaItems.YouTubeTrailer || film.MediaItems.Trailer,
                Image: null,
                ReleaseDate: null,
                IsNowPlaying: false,
                IsComingSoon: false,
                Order: film.Order,
                Week: null,
                OrigOrder: filmCounter
            };

            var releaseDateSplit;
            var weekSplit;
            var weekDate;

            if (
                typeof film.MediaItems !== 'undefined' &&
                film.MediaItems !== null &&
                typeof film.MediaItems.OneSheet !== 'undefined' &&
                film.MediaItems.OneSheet !== null
            ) {
                filmData.Image = film.MediaItems.OneSheet;
            }

            if (
                typeof film.ReleaseDate !== 'undefined' &&
                film.ReleaseDate !== null
            ) {
                releaseDateSplit = film.ReleaseDate.split('-');
                filmData.ReleaseDate = new Date(parseInt(releaseDateSplit[0]), parseInt(releaseDateSplit[1]) - 1, parseInt(releaseDateSplit[2].slice(0, 2)), 0, 0, 0);
            }

            if (
                typeof film.Sessions !== 'undefined' &&
                film.Sessions !== null &&
                film.Sessions.length > 0
            ) {
                for (var s = 0; s < film.Sessions.length; s++) {
                    if (week.indexOf(film.Sessions[s].NewDate) > -1) {
                        filmData.IsNowPlaying = true;
                    }
                    else {
                        filmData.IsComingSoon = true;
                    }
                }
            }

            if (
                filmData.IsComingSoon === true &&
                typeof film.FirstSessionTime !== 'undefined' &&
                film.FirstSessionTime !== null
            ) {
                weekSplit = film.FirstSessionTime.split('-');
                weekDate = new Date(parseInt(weekSplit[0]), parseInt(weekSplit[1]) - 1, parseInt(weekSplit[2].slice(0, 2)), 0, 0, 0);
                filmData.Week = parseFloat(weekDate.getFullYear() + '.' + weekDate.getWeek());
            }

            filmCounter++;

            return filmData;
        });

        $filters.slideDown(400);

        filterSortFilms();
    }

    
    $.ajax({
        url: pc.api.movie + 'PaginatedMovies/' + pc.api.circuit + '?days=0&expandAttributes=true&number=99999'
    }).always(function (nsResponse) {
        $.ajax({
            url: pc.api.movie + 'PaginatedComingSoon/' + pc.api.circuit + '?expandAttributes=true&number=99999'
        }).always(function (csResponse) {
            var response = [];

            if (
                typeof nsResponse !== 'undefined' &&
                nsResponse !== null &&
                nsResponse.length > 0
            ) {
                response = $.merge(response, nsResponse);
            }

            if (
                typeof csResponse !== 'undefined' &&
                csResponse !== null &&
                typeof csResponse.Result !== 'undefined' &&
                csResponse.Result !== null && 
                csResponse.Result.length > 0
            ) {
                response = $.merge(response, csResponse.Result);

                // test
                //var temp = csResponse.Result.slice(0);

                //for (var i = temp.length - 1; i >= 0; i--) {
                //    for (var ns = 0; ns < nsResponse.length; ns++) {
                //        if (temp[i].FilmId === nsResponse[ns].FilmId) {
                //            temp.splice(i, 1);
                //            break;
                //        }
                //    }
                //}

                //console.log(temp);
                // end test
            }

            if(
                typeof pc.api !== 'undefined' &&
                pc.api !== null &&
                typeof pc.api.customAttributes !== 'undefined' &&
                pc.api.customAttributes !== null &&
                pc.api.customAttributes.length > 0
            ) {
                var len = response.length,
                    exclude = [];

                for(var i = 0; i < len; i++) {
                    let count = 0;
                    if(
                        typeof response[i].Experiences !== 'undefined' &&
                        response[i].Experiences !== null &&
                        response[i].Experiences.length > 0
                    ) {
                        response[i].Experiences.forEach(function (experience) {
                        
                            if(pc.api.customAttributes.indexOf(parseInt(experience.Id)) !== -1) {
                                count = count + 1;
                            }
    
                        });
                    }
                    
                    if(count > 0) {
                        exclude.push(i);
                    }
                }

                response = response.filter(function(r, i) { 
                    return exclude.indexOf(i) === -1 
                });
            }

            if (response.length > 0) {
                var filmIds = {};
                response = response.filter(function (film) {
                    if (typeof filmIds[film.FilmId] !== 'undefined') {
                        return false;
                    }
                    filmIds[film.FilmId] = true;
                    return true;
                });
            }

            if (response.length > 0) {
                var filmIds = {};
                response = response.filter(function (film) {
                    if (typeof filmIds[film.FilmId] !== 'undefined') {
                        return false;
                    }
                    filmIds[film.FilmId] = true;
                    return true;
                });
            }

            displayFilms(response);
        });
    });

    $('[data-header-theatre-group]').prepend('<span class="header-theatre-group-top"><span class="header-theatre-intro">ALL MOVIES AT:</span>&nbsp;&nbsp;<span class="header-theatre-location">ALL LANDMARK THEATRES</span></span><br>');

})(jQuery);;(function () {
    var synopsis = document.querySelector('[data-filminfo-synopsis]');

    if (synopsis === null) {
        return;
    }

    if (synopsis.scrollHeight === synopsis.clientHeight) {
        synopsis.className += ' show';
    }
    else {
        synopsis.className += ' hide';

        synopsis.addEventListener('click', function (e) {
            synopsis.className = synopsis.className.replace('hide', 'show');
        }, false);
    }
})();

(function ($) {
    var $picker = $('[data-filminfo-cinemapicker]');

    if (
        typeof pc.accordion === 'undefined' ||
        $picker.length === 0 ||
        typeof lmtRegions === 'undefined' ||
        lmtRegions === null ||
        typeof lmtRegions.Regions === 'undefined' || 
        lmtRegions.Regions === null || 
        lmtRegions.Regions.length === 0 ||
        typeof filmData === 'undefined' || 
        filmData === null || 
        typeof filmData.Cinemas === 'undefined' || 
        filmData.Cinemas === null
    ) {
        return;
    }

    var template = $('[data-filminfo-template-picker]').html() || '';

    var filmCinemas = [];

    if (
        typeof filmData.Cinemas.NowShowing !== 'undefined' &&
        filmData.Cinemas.NowShowing !== null &&
        filmData.Cinemas.NowShowing.length > 0
    ) {
        filmCinemas = $.extend(filmCinemas, filmData.Cinemas.NowShowing);
    }

    if (
        typeof filmData.Cinemas.ComingSoon !== 'undefined' &&
        filmData.Cinemas.ComingSoon !== null &&
        filmData.Cinemas.ComingSoon.length > 0
    ) {
        filmCinemas = $.extend(filmCinemas, filmData.Cinemas.ComingSoon);
    }

    if (filmCinemas.length === 0) {
        return;
    }

    for (var r = lmtRegions.Regions.length - 1; r >= 0; r--) {
        if (
            typeof lmtRegions.Regions[r].Cinemas !== 'undefined' &&
            lmtRegions.Regions[r].Cinemas !== null &&
            lmtRegions.Regions[r].Cinemas.length > 0
        ) {
            regionCinemas: for (var c = lmtRegions.Regions[r].Cinemas.length - 1; c >= 0; c--) {
                for (var i = 0; i < filmCinemas.length; i++) {
                    if (filmCinemas[i].CinemaId === lmtRegions.Regions[r].Cinemas[c].CinemaId) {
                        continue regionCinemas;
                    }
                }

                lmtRegions.Regions[r].Cinemas.splice(c, 1);
            }
        }

        if (
            typeof lmtRegions.Regions[r].Cinemas === 'undefined' || 
            lmtRegions.Regions[r].Cinemas === null || 
            lmtRegions.Regions[r].Cinemas.length === 0
        ) {
            lmtRegions.Regions.splice(r, 1);
        }
    }


    if (lmtRegions.Regions.length === 0) {
        return;
    }

    lmtRegions.FilmFriendlyName = filmData.FriendlyName;

    $picker.html(Mustache.render(template, lmtRegions));

    $picker.find('[data-accordion]').foundation();

    pc.accordion.setup.call($picker[0]);

    function checkForSingleTheatre() {
        $picker.find('[data-accordion]').one('down.zf.accordion', function () {
            var regionId = $picker.find('[data-accordion-region-id]').attr('data-accordion-region-id');
            var counter = 0;
            var accordionInterval;

            // check for single theatre
            if ($picker.find('[data-accordion-theatre-id]').length === 1) {

                accordionInterval = setInterval(function () {
                    counter++;

                    var data = $picker.data('accordion') || {};

                    if (typeof data.ActiveRegionId.toString() !== 'undefined' && data.ActiveRegionId === regionId) {
                        $picker.find('[data-accordion-theatre-id]').trigger('click');
                        clearInterval(accordionInterval);
                    }

                    if (counter > 10) {
                        clearInterval(accordionInterval);
                    }
                }, 50);
            }
        });
    }

    var regionCookie = typeof docCookies !== 'undefined' && docCookies !== null ? docCookies.getItem('PCC.Region') : null;

    if ($picker.find('[data-accordion-region-id]').length === 1) {
        // we have a single region
        checkForSingleTheatre();

        $picker.find('[data-accordion-region-id]').trigger('click');
    }
    else if (
        regionCookie !== null &&
        $picker.find('[data-accordion-region-link="' + regionCookie + '"]').length === 1
    ) {
        // we have a cookied region
        checkForSingleTheatre();

        $picker.find('[data-accordion-region-link="' + regionCookie + '"]').trigger('click');
    }
    else {
        $picker.find('.is-active').removeClass('is-active');
        $picker.find('[data-accordion-region]').trigger('click');
    }

    $('[data-header-theatre-group]').prepend('<span class="header-theatre-group-top"><span class="header-theatre-intro">SHOWTIMES FOR:</span>&nbsp;&nbsp;<span class="header-theatre-location">ALL LANDMARK THEATRES</span></span><br>');
})(jQuery);;var pc = pc || {};

if (pc.captcha && pc.captcha.enabled) {
    window.onloadCaptchaCallback = function () {
        var $gReCaptha = $("#g-recaptcha"),
            captchaSiteKey = $gReCaptha.attr("data-sitekey"),
            captchaType = $gReCaptha.attr("data-type"),
            captchaTheme = $gReCaptha.attr("data-theme");

        grecaptcha.render("g-recaptcha", {
            "sitekey": captchaSiteKey,
            "theme": captchaTheme,
            "type": captchaType,
            "expired-callback": pc.captcha.onExpired
        });
    };

    pc.captcha.onExpired = function () {
        grecaptcha.reset();
    };

    pc.captcha.hasCaptchaResponse = function () {
        pc.captcha.response = $('#g-recaptcha-response').val() || '';
        var captchaJsonData = {};
        captchaJsonData['captchaResponse'] = pc.captcha.response;


        if (pc.captcha.response.length == 0) {
            $('[data-form-validate-captcha-message]').removeClass('dn');
            return false;
        } else {
            $('[data-form-validate-captcha-message]').addClass('dn');

            return true;
        }

        
        
    }
}
;