/* Minification failed. Returning unminified contents.
(5140,56-57): run-time error JS1195: Expected expression: >
(5140,93-94): run-time error JS1004: Expected ';': )
(5141,17-21): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(5148,36-37): run-time error JS1004: Expected ';': {
(5222,76-77): run-time error JS1195: Expected expression: >
(5222,90-91): run-time error JS1004: Expected ';': )
(5232,36-37): run-time error JS1010: Expected identifier: [
(5232,49-51): run-time error JS1004: Expected ';': of
(5232,52-58): run-time error JS1006: Expected ')': Object
(5232,86-87): run-time error JS1004: Expected ';': )
(5240,13-14): run-time error JS1002: Syntax error: }
(5244,13-14): run-time error JS1002: Syntax error: }
(5247,70-71): run-time error JS1004: Expected ';': {
(5316,60-61): run-time error JS1195: Expected expression: >
(5316,91-92): run-time error JS1004: Expected ';': )
(5347,55-56): run-time error JS1195: Expected expression: >
(5347,58-59): run-time error JS1197: Too many errors. The file might not be a JavaScript file: .
(5346,31-53): run-time error JS1301: End of file encountered before function is properly closed: function (trackerName)
(5347,59-63): run-time error JS1004: Expected ';': name
(5347,78-79): run-time error JS1004: Expected ';': )
(5347,79-80): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
(5149,13-96): run-time error JS1018: 'return' statement outside of function: return gJobs && gJobs.areaInfoService ? gJobs.areaInfoService.getCurrentArea() : ''
 */
/* Minification failed. Returning unminified contents.
(5116,56-57): run-time error JS1195: Expected expression: >
(5116,93-94): run-time error JS1004: Expected ';': )
(5117,17-21): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(5124,36-37): run-time error JS1004: Expected ';': {
(5198,76-77): run-time error JS1195: Expected expression: >
(5198,90-91): run-time error JS1004: Expected ';': )
(5208,36-37): run-time error JS1010: Expected identifier: [
(5208,49-51): run-time error JS1004: Expected ';': of
(5208,52-58): run-time error JS1006: Expected ')': Object
(5208,86-87): run-time error JS1004: Expected ';': )
(5216,13-14): run-time error JS1002: Syntax error: }
(5220,13-14): run-time error JS1002: Syntax error: }
(5223,70-71): run-time error JS1004: Expected ';': {
(5292,60-61): run-time error JS1195: Expected expression: >
(5292,91-92): run-time error JS1004: Expected ';': )
(5323,55-56): run-time error JS1195: Expected expression: >
(5323,58-59): run-time error JS1197: Too many errors. The file might not be a JavaScript file: .
(5322,31-53): run-time error JS1301: End of file encountered before function is properly closed: function (trackerName)
(5323,59-63): run-time error JS1004: Expected ';': name
(5323,78-79): run-time error JS1004: Expected ';': )
(5323,79-80): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
(5125,13-96): run-time error JS1018: 'return' statement outside of function: return gJobs && gJobs.areaInfoService ? gJobs.areaInfoService.getCurrentArea() : ''
 */
typeof JSON != "object" && (JSON = {}), function () { "use strict"; function f(e) { return e < 10 ? "0" + e : e } function quote(e) { return escapable.lastIndex = 0, escapable.test(e) ? '"' + e.replace(escapable, function (e) { var t = meta[e]; return typeof t == "string" ? t : "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4) }) + '"' : '"' + e + '"' } function str(e, t) { var n, r, i, s, o = gap, u, a = t[e]; a && typeof a == "object" && typeof a.toJSON == "function" && (a = a.toJSON(e)), typeof rep == "function" && (a = rep.call(t, e, a)); switch (typeof a) { case "string": return quote(a); case "number": return isFinite(a) ? String(a) : "null"; case "boolean": case "null": return String(a); case "object": if (!a) return "null"; gap += indent, u = []; if (Object.prototype.toString.apply(a) === "[object Array]") { s = a.length; for (n = 0; n < s; n += 1) u[n] = str(n, a) || "null"; return i = u.length === 0 ? "[]" : gap ? "[\n" + gap + u.join(",\n" + gap) + "\n" + o + "]" : "[" + u.join(",") + "]", gap = o, i } if (rep && typeof rep == "object") { s = rep.length; for (n = 0; n < s; n += 1) typeof rep[n] == "string" && (r = rep[n], i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i)) } else for (r in a) Object.prototype.hasOwnProperty.call(a, r) && (i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i)); return i = u.length === 0 ? "{}" : gap ? "{\n" + gap + u.join(",\n" + gap) + "\n" + o + "}" : "{" + u.join(",") + "}", gap = o, i } } typeof Date.prototype.toJSON != "function" && (Date.prototype.toJSON = function (e) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null }, String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (e) { return this.valueOf() }); var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { "\b": "\\b", "	": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\" }, rep; typeof JSON.stringify != "function" && (JSON.stringify = function (e, t, n) { var r; gap = "", indent = ""; if (typeof n == "number") for (r = 0; r < n; r += 1) indent += " "; else typeof n == "string" && (indent = n); rep = t; if (!t || typeof t == "function" || typeof t == "object" && typeof t.length == "number") return str("", { "": e }); throw new Error("JSON.stringify") }), typeof JSON.parse != "function" && (JSON.parse = function (text, reviver) { function walk(e, t) { var n, r, i = e[t]; if (i && typeof i == "object") for (n in i) Object.prototype.hasOwnProperty.call(i, n) && (r = walk(i, n), r !== undefined ? i[n] = r : delete i[n]); return reviver.call(e, t, i) } var j; text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function (e) { return "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4) })); if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) return j = eval("(" + text + ")"), typeof reviver == "function" ? walk({ "": j }, "") : j; throw new SyntaxError("JSON.parse") }) }(), function (e, t) { "use strict"; var n = e.History = e.History || {}, r = e.jQuery; if (typeof n.Adapter != "undefined") throw new Error("History.js Adapter has already been loaded..."); n.Adapter = { bind: function (e, t, n) { r(e).bind(t, n) }, trigger: function (e, t, n) { r(e).trigger(t, n) }, extractEventData: function (e, n, r) { var i = n && n.originalEvent && n.originalEvent[e] || r && r[e] || t; return i }, onDomLoad: function (e) { r(e) } }, typeof n.init != "undefined" && n.init() }(window), function (e, t) { "use strict"; var n = e.document, r = e.setTimeout || r, i = e.clearTimeout || i, s = e.setInterval || s, o = e.History = e.History || {}; if (typeof o.initHtml4 != "undefined") throw new Error("History.js HTML4 Support has already been loaded..."); o.initHtml4 = function () { if (typeof o.initHtml4.initialized != "undefined") return !1; o.initHtml4.initialized = !0, o.enabled = !0, o.savedHashes = [], o.isLastHash = function (e) { var t = o.getHashByIndex(), n; return n = e === t, n }, o.isHashEqual = function (e, t) { return e = encodeURIComponent(e).replace(/%25/g, "%"), t = encodeURIComponent(t).replace(/%25/g, "%"), e === t }, o.saveHash = function (e) { return o.isLastHash(e) ? !1 : (o.savedHashes.push(e), !0) }, o.getHashByIndex = function (e) { var t = null; return typeof e == "undefined" ? t = o.savedHashes[o.savedHashes.length - 1] : e < 0 ? t = o.savedHashes[o.savedHashes.length + e] : t = o.savedHashes[e], t }, o.discardedHashes = {}, o.discardedStates = {}, o.discardState = function (e, t, n) { var r = o.getHashByState(e), i; return i = { discardedState: e, backState: n, forwardState: t }, o.discardedStates[r] = i, !0 }, o.discardHash = function (e, t, n) { var r = { discardedHash: e, backState: n, forwardState: t }; return o.discardedHashes[e] = r, !0 }, o.discardedState = function (e) { var t = o.getHashByState(e), n; return n = o.discardedStates[t] || !1, n }, o.discardedHash = function (e) { var t = o.discardedHashes[e] || !1; return t }, o.recycleState = function (e) { var t = o.getHashByState(e); return o.discardedState(e) && delete o.discardedStates[t], !0 }, o.emulated.hashChange && (o.hashChangeInit = function () { o.checkerFunction = null; var t = "", r, i, u, a, f = Boolean(o.getHash()); return o.isInternetExplorer() ? (r = "historyjs-iframe", i = n.createElement("iframe"), i.setAttribute("id", r), i.setAttribute("title", "t"), i.setAttribute("src", "#"), i.style.display = "none", n.body.appendChild(i), i.contentWindow.document.open(), i.contentWindow.document.close(), u = "", a = !1, o.checkerFunction = function () { if (a) return !1; a = !0; var n = o.getHash(), r = o.getHash(i.contentWindow.document); return n !== t ? (t = n, r !== n && (u = r = n, i.contentWindow.document.open(), i.contentWindow.document.close(), i.contentWindow.document.location.hash = o.escapeHash(n)), o.Adapter.trigger(e, "hashchange")) : r !== u && (u = r, f && r === "" ? o.back() : o.setHash(r, !1)), a = !1, !0 }) : o.checkerFunction = function () { var n = o.getHash() || ""; return n !== t && (t = n, o.Adapter.trigger(e, "hashchange")), !0 }, o.intervalList.push(s(o.checkerFunction, o.options.hashChangeInterval)), !0 }, o.Adapter.onDomLoad(o.hashChangeInit)), o.emulated.pushState && (o.onHashChange = function (t) { var n = t && t.newURL || o.getLocationHref(), r = o.getHashByUrl(n), i = null, s = null, u = null, a; return o.isLastHash(r) ? (o.busy(!1), !1) : (o.doubleCheckComplete(), o.saveHash(r), r && o.isTraditionalAnchor(r) ? (o.Adapter.trigger(e, "anchorchange"), o.busy(!1), !1) : (i = o.extractState(o.getFullUrl(r || o.getLocationHref()), !0), o.isLastSavedState(i) ? (o.busy(!1), !1) : (s = o.getHashByState(i), a = o.discardedState(i), a ? (o.getHashByIndex(-2) === o.getHashByState(a.forwardState) ? o.back(!1) : o.forward(!1), !1) : (o.pushState(i.data, i.title, encodeURI(i.url), !1), !0)))) }, o.Adapter.bind(e, "hashchange", o.onHashChange), o.pushState = function (t, n, r, i) { r = encodeURI(r).replace(/%25/g, "%"); if (o.getHashByUrl(r)) throw new Error("History.js does not support states with fragment-identifiers (hashes/anchors)."); if (i !== !1 && o.busy()) return o.pushQueue({ scope: o, callback: o.pushState, args: arguments, queue: i }), !1; o.busy(!0); var s = o.createStateObject(t, n, r), u = o.getHashByState(s), a = o.getState(!1), f = o.getHashByState(a), l = o.getHash(), c = o.expectedStateId == s.id; return o.storeState(s), o.expectedStateId = s.id, o.recycleState(s), o.setTitle(s), u === f ? (o.busy(!1), !1) : (o.saveState(s), c || o.Adapter.trigger(e, "statechange"), !o.isHashEqual(u, l) && !o.isHashEqual(u, o.getShortUrl(o.getLocationHref())) && o.setHash(u, !1), o.busy(!1), !0) }, o.replaceState = function (t, n, r, i) { r = encodeURI(r).replace(/%25/g, "%"); if (o.getHashByUrl(r)) throw new Error("History.js does not support states with fragment-identifiers (hashes/anchors)."); if (i !== !1 && o.busy()) return o.pushQueue({ scope: o, callback: o.replaceState, args: arguments, queue: i }), !1; o.busy(!0); var s = o.createStateObject(t, n, r), u = o.getHashByState(s), a = o.getState(!1), f = o.getHashByState(a), l = o.getStateByIndex(-2); return o.discardState(a, s, l), u === f ? (o.storeState(s), o.expectedStateId = s.id, o.recycleState(s), o.setTitle(s), o.saveState(s), o.Adapter.trigger(e, "statechange"), o.busy(!1)) : o.pushState(s.data, s.title, s.url, !1), !0 }), o.emulated.pushState && o.getHash() && !o.emulated.hashChange && o.Adapter.onDomLoad(function () { o.Adapter.trigger(e, "hashchange") }) }, typeof o.init != "undefined" && o.init() }(window), function (e, t) { "use strict"; var n = e.console || t, r = e.document, i = e.navigator, s = !1, o = e.setTimeout, u = e.clearTimeout, a = e.setInterval, f = e.clearInterval, l = e.JSON, c = e.alert, h = e.History = e.History || {}, p = e.history; try { s = e.sessionStorage, s.setItem("TEST", "1"), s.removeItem("TEST") } catch (d) { s = !1 } l.stringify = l.stringify || l.encode, l.parse = l.parse || l.decode; if (typeof h.init != "undefined") throw new Error("History.js Core has already been loaded..."); h.init = function (e) { return typeof h.Adapter == "undefined" ? !1 : (typeof h.initCore != "undefined" && h.initCore(), typeof h.initHtml4 != "undefined" && h.initHtml4(), !0) }, h.initCore = function (d) { if (typeof h.initCore.initialized != "undefined") return !1; h.initCore.initialized = !0, h.options = h.options || {}, h.options.hashChangeInterval = h.options.hashChangeInterval || 100, h.options.safariPollInterval = h.options.safariPollInterval || 500, h.options.doubleCheckInterval = h.options.doubleCheckInterval || 500, h.options.disableSuid = h.options.disableSuid || !1, h.options.storeInterval = h.options.storeInterval || 1e3, h.options.busyDelay = h.options.busyDelay || 250, h.options.debug = h.options.debug || !1, h.options.initialTitle = h.options.initialTitle || r.title, h.options.html4Mode = h.options.html4Mode || !1, h.options.delayInit = h.options.delayInit || !1, h.intervalList = [], h.clearAllIntervals = function () { var e, t = h.intervalList; if (typeof t != "undefined" && t !== null) { for (e = 0; e < t.length; e++) f(t[e]); h.intervalList = null } }, h.debug = function () { (h.options.debug || !1) && h.log.apply(h, arguments) }, h.log = function () { var e = typeof n != "undefined" && typeof n.log != "undefined" && typeof n.log.apply != "undefined", t = r.getElementById("log"), i, s, o, u, a; e ? (u = Array.prototype.slice.call(arguments), i = u.shift(), typeof n.debug != "undefined" ? n.debug.apply(n, [i, u]) : n.log.apply(n, [i, u])) : i = "\n" + arguments[0] + "\n"; for (s = 1, o = arguments.length; s < o; ++s) { a = arguments[s]; if (typeof a == "object" && typeof l != "undefined") try { a = l.stringify(a) } catch (f) { } i += "\n" + a + "\n" } return t ? (t.value += i + "\n-----\n", t.scrollTop = t.scrollHeight - t.clientHeight) : e || c(i), !0 }, h.getInternetExplorerMajorVersion = function () { var e = h.getInternetExplorerMajorVersion.cached = typeof h.getInternetExplorerMajorVersion.cached != "undefined" ? h.getInternetExplorerMajorVersion.cached : function () { var e = 3, t = r.createElement("div"), n = t.getElementsByTagName("i"); while ((t.innerHTML = "<!--[if gt IE " + ++e + "]><i></i><![endif]-->") && n[0]); return e > 4 ? e : !1 }(); return e }, h.isInternetExplorer = function () { var e = h.isInternetExplorer.cached = typeof h.isInternetExplorer.cached != "undefined" ? h.isInternetExplorer.cached : Boolean(h.getInternetExplorerMajorVersion()); return e }, h.options.html4Mode ? h.emulated = { pushState: !0, hashChange: !0 } : h.emulated = { pushState: !Boolean(e.history && e.history.pushState && e.history.replaceState && !/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent) && !/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)), hashChange: Boolean(!("onhashchange" in e || "onhashchange" in r) || h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 8) }, h.enabled = !h.emulated.pushState, h.bugs = { setHash: Boolean(!h.emulated.pushState && i.vendor === "Apple Computer, Inc." && /AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)), safariPoll: Boolean(!h.emulated.pushState && i.vendor === "Apple Computer, Inc." && /AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)), ieDoubleCheck: Boolean(h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 8), hashEscape: Boolean(h.isInternetExplorer() && h.getInternetExplorerMajorVersion() < 7) }, h.isEmptyObject = function (e) { for (var t in e) if (e.hasOwnProperty(t)) return !1; return !0 }, h.cloneObject = function (e) { var t, n; return e ? (t = l.stringify(e), n = l.parse(t)) : n = {}, n }, h.getRootUrl = function () { var e = r.location.protocol + "//" + (r.location.hostname || r.location.host); if (r.location.port || !1) e += ":" + r.location.port; return e += "/", e }, h.getBaseHref = function () { var e = r.getElementsByTagName("base"), t = null, n = ""; return e.length === 1 && (t = e[0], n = t.href.replace(/[^\/]+$/, "")), n = n.replace(/\/+$/, ""), n && (n += "/"), n }, h.getBaseUrl = function () { var e = h.getBaseHref() || h.getBasePageUrl() || h.getRootUrl(); return e }, h.getPageUrl = function () { var e = h.getState(!1, !1), t = (e || {}).url || h.getLocationHref(), n; return n = t.replace(/\/+$/, "").replace(/[^\/]+$/, function (e, t, n) { return /\./.test(e) ? e : e + "/" }), n }, h.getBasePageUrl = function () { var e = h.getLocationHref().replace(/[#\?].*/, "").replace(/[^\/]+$/, function (e, t, n) { return /[^\/]$/.test(e) ? "" : e }).replace(/\/+$/, "") + "/"; return e }, h.getFullUrl = function (e, t) { var n = e, r = e.substring(0, 1); return t = typeof t == "undefined" ? !0 : t, /[a-z]+\:\/\//.test(e) || (r === "/" ? n = h.getRootUrl() + e.replace(/^\/+/, "") : r === "#" ? n = h.getPageUrl().replace(/#.*/, "") + e : r === "?" ? n = h.getPageUrl().replace(/[\?#].*/, "") + e : t ? n = h.getBaseUrl() + e.replace(/^(\.\/)+/, "") : n = h.getBasePageUrl() + e.replace(/^(\.\/)+/, "")), n.replace(/\#$/, "") }, h.getShortUrl = function (e) { var t = e, n = h.getBaseUrl(), r = h.getRootUrl(); return h.emulated.pushState && (t = t.replace(n, "")), t = t.replace(r, "/"), h.isTraditionalAnchor(t) && (t = "./" + t), t = t.replace(/^(\.\/)+/g, "./").replace(/\#$/, ""), t }, h.getLocationHref = function (e) { return e = e || r, e.URL === e.location.href ? e.location.href : e.location.href === decodeURIComponent(e.URL) ? e.URL : e.location.hash && decodeURIComponent(e.location.href.replace(/^[^#]+/, "")) === e.location.hash ? e.location.href : e.URL.indexOf("#") == -1 && e.location.href.indexOf("#") != -1 ? e.location.href : e.URL || e.location.href }, h.store = {}, h.idToState = h.idToState || {}, h.stateToId = h.stateToId || {}, h.urlToId = h.urlToId || {}, h.storedStates = h.storedStates || [], h.savedStates = h.savedStates || [], h.normalizeStore = function () { h.store.idToState = h.store.idToState || {}, h.store.urlToId = h.store.urlToId || {}, h.store.stateToId = h.store.stateToId || {} }, h.getState = function (e, t) { typeof e == "undefined" && (e = !0), typeof t == "undefined" && (t = !0); var n = h.getLastSavedState(); return !n && t && (n = h.createStateObject()), e && (n = h.cloneObject(n), n.url = n.cleanUrl || n.url), n }, h.getIdByState = function (e) { var t = h.extractId(e.url), n; if (!t) { n = h.getStateString(e); if (typeof h.stateToId[n] != "undefined") t = h.stateToId[n]; else if (typeof h.store.stateToId[n] != "undefined") t = h.store.stateToId[n]; else { for (; ;) { t = (new Date).getTime() + String(Math.random()).replace(/\D/g, ""); if (typeof h.idToState[t] == "undefined" && typeof h.store.idToState[t] == "undefined") break } h.stateToId[n] = t, h.idToState[t] = e } } return t }, h.normalizeState = function (e) { var t, n; if (!e || typeof e != "object") e = {}; if (typeof e.normalized != "undefined") return e; if (!e.data || typeof e.data != "object") e.data = {}; return t = {}, t.normalized = !0, t.title = e.title || "", t.url = h.getFullUrl(e.url ? e.url : h.getLocationHref()), t.hash = h.getShortUrl(t.url), t.data = h.cloneObject(e.data), t.id = h.getIdByState(t), t.cleanUrl = t.url.replace(/\??\&_suid.*/, ""), t.url = t.cleanUrl, n = !h.isEmptyObject(t.data), (t.title || n) && h.options.disableSuid !== !0 && (t.hash = h.getShortUrl(t.url).replace(/\??\&_suid.*/, ""), /\?/.test(t.hash) || (t.hash += "?"), t.hash += "&_suid=" + t.id), t.hashedUrl = h.getFullUrl(t.hash), (h.emulated.pushState || h.bugs.safariPoll) && h.hasUrlDuplicate(t) && (t.url = t.hashedUrl), t }, h.createStateObject = function (e, t, n) { var r = { data: e, title: t, url: n }; return r = h.normalizeState(r), r }, h.getStateById = function (e) { e = String(e); var n = h.idToState[e] || h.store.idToState[e] || t; return n }, h.getStateString = function (e) { var t, n, r; return t = h.normalizeState(e), n = { data: t.data, title: e.title, url: e.url }, r = l.stringify(n), r }, h.getStateId = function (e) { var t, n; return t = h.normalizeState(e), n = t.id, n }, h.getHashByState = function (e) { var t, n; return t = h.normalizeState(e), n = t.hash, n }, h.extractId = function (e) { var t, n, r, i; return e.indexOf("#") != -1 ? i = e.split("#")[0] : i = e, n = /(.*)\&_suid=([0-9]+)$/.exec(i), r = n ? n[1] || e : e, t = n ? String(n[2] || "") : "", t || !1 }, h.isTraditionalAnchor = function (e) { var t = !/[\/\?\.]/.test(e); return t }, h.extractState = function (e, t) { var n = null, r, i; return t = t || !1, r = h.extractId(e), r && (n = h.getStateById(r)), n || (i = h.getFullUrl(e), r = h.getIdByUrl(i) || !1, r && (n = h.getStateById(r)), !n && t && !h.isTraditionalAnchor(e) && (n = h.createStateObject(null, null, i))), n }, h.getIdByUrl = function (e) { var n = h.urlToId[e] || h.store.urlToId[e] || t; return n }, h.getLastSavedState = function () { return h.savedStates[h.savedStates.length - 1] || t }, h.getLastStoredState = function () { return h.storedStates[h.storedStates.length - 1] || t }, h.hasUrlDuplicate = function (e) { var t = !1, n; return n = h.extractState(e.url), t = n && n.id !== e.id, t }, h.storeState = function (e) { return h.urlToId[e.url] = e.id, h.storedStates.push(h.cloneObject(e)), e }, h.isLastSavedState = function (e) { var t = !1, n, r, i; return h.savedStates.length && (n = e.id, r = h.getLastSavedState(), i = r.id, t = n === i), t }, h.saveState = function (e) { return h.isLastSavedState(e) ? !1 : (h.savedStates.push(h.cloneObject(e)), !0) }, h.getStateByIndex = function (e) { var t = null; return typeof e == "undefined" ? t = h.savedStates[h.savedStates.length - 1] : e < 0 ? t = h.savedStates[h.savedStates.length + e] : t = h.savedStates[e], t }, h.getCurrentIndex = function () { var e = null; return h.savedStates.length < 1 ? e = 0 : e = h.savedStates.length - 1, e }, h.getHash = function (e) { var t = h.getLocationHref(e), n; return n = h.getHashByUrl(t), n }, h.unescapeHash = function (e) { var t = h.normalizeHash(e); return t = decodeURIComponent(t), t }, h.normalizeHash = function (e) { var t = e.replace(/[^#]*#/, "").replace(/#.*/, ""); return t }, h.setHash = function (e, t) { var n, i; return t !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.setHash, args: arguments, queue: t }), !1) : (h.busy(!0), n = h.extractState(e, !0), n && !h.emulated.pushState ? h.pushState(n.data, n.title, n.url, !1) : h.getHash() !== e && (h.bugs.setHash ? (i = h.getPageUrl(), h.pushState(null, null, i + "#" + e, !1)) : r.location.hash = e), h) }, h.escapeHash = function (t) { var n = h.normalizeHash(t); return n = e.encodeURIComponent(n), h.bugs.hashEscape || (n = n.replace(/\%21/g, "!").replace(/\%26/g, "&").replace(/\%3D/g, "=").replace(/\%3F/g, "?")), n }, h.getHashByUrl = function (e) { var t = String(e).replace(/([^#]*)#?([^#]*)#?(.*)/, "$2"); return t = h.unescapeHash(t), t }, h.setTitle = function (e) { var t = e.title, n; t || (n = h.getStateByIndex(0), n && n.url === e.url && (t = n.title || h.options.initialTitle)); try { r.getElementsByTagName("title")[0].innerHTML = t.replace("<", "&lt;").replace(">", "&gt;").replace(" & ", " &amp; ") } catch (i) { } return r.title = t, h }, h.queues = [], h.busy = function (e) { typeof e != "undefined" ? h.busy.flag = e : typeof h.busy.flag == "undefined" && (h.busy.flag = !1); if (!h.busy.flag) { u(h.busy.timeout); var t = function () { var e, n, r; if (h.busy.flag) return; for (e = h.queues.length - 1; e >= 0; --e) { n = h.queues[e]; if (n.length === 0) continue; r = n.shift(), h.fireQueueItem(r), h.busy.timeout = o(t, h.options.busyDelay) } }; h.busy.timeout = o(t, h.options.busyDelay) } return h.busy.flag }, h.busy.flag = !1, h.fireQueueItem = function (e) { return e.callback.apply(e.scope || h, e.args || []) }, h.pushQueue = function (e) { return h.queues[e.queue || 0] = h.queues[e.queue || 0] || [], h.queues[e.queue || 0].push(e), h }, h.queue = function (e, t) { return typeof e == "function" && (e = { callback: e }), typeof t != "undefined" && (e.queue = t), h.busy() ? h.pushQueue(e) : h.fireQueueItem(e), h }, h.clearQueue = function () { return h.busy.flag = !1, h.queues = [], h }, h.stateChanged = !1, h.doubleChecker = !1, h.doubleCheckComplete = function () { return h.stateChanged = !0, h.doubleCheckClear(), h }, h.doubleCheckClear = function () { return h.doubleChecker && (u(h.doubleChecker), h.doubleChecker = !1), h }, h.doubleCheck = function (e) { return h.stateChanged = !1, h.doubleCheckClear(), h.bugs.ieDoubleCheck && (h.doubleChecker = o(function () { return h.doubleCheckClear(), h.stateChanged || e(), !0 }, h.options.doubleCheckInterval)), h }, h.safariStatePoll = function () { var t = h.extractState(h.getLocationHref()), n; if (!h.isLastSavedState(t)) return n = t, n || (n = h.createStateObject()), h.Adapter.trigger(e, "popstate"), h; return }, h.back = function (e) { return e !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.back, args: arguments, queue: e }), !1) : (h.busy(!0), h.doubleCheck(function () { h.back(!1) }), p.go(-1), !0) }, h.forward = function (e) { return e !== !1 && h.busy() ? (h.pushQueue({ scope: h, callback: h.forward, args: arguments, queue: e }), !1) : (h.busy(!0), h.doubleCheck(function () { h.forward(!1) }), p.go(1), !0) }, h.go = function (e, t) { var n; if (e > 0) for (n = 1; n <= e; ++n) h.forward(t); else { if (!(e < 0)) throw new Error("History.go: History.go requires a positive or negative integer passed."); for (n = -1; n >= e; --n) h.back(t) } return h }; if (h.emulated.pushState) { var v = function () { }; h.pushState = h.pushState || v, h.replaceState = h.replaceState || v } else h.onPopState = function (t, n) { var r = !1, i = !1, s, o; return h.doubleCheckComplete(), s = h.getHash(), s ? (o = h.extractState(s || h.getLocationHref(), !0), o ? h.replaceState(o.data, o.title, o.url, !1) : (h.Adapter.trigger(e, "anchorchange"), h.busy(!1)), h.expectedStateId = !1, !1) : (r = h.Adapter.extractEventData("state", t, n) || !1, r ? i = h.getStateById(r) : h.expectedStateId ? i = h.getStateById(h.expectedStateId) : i = h.extractState(h.getLocationHref()), i || (i = h.createStateObject(null, null, h.getLocationHref())), h.expectedStateId = !1, h.isLastSavedState(i) ? (h.busy(!1), !1) : (h.storeState(i), h.saveState(i), h.setTitle(i), h.Adapter.trigger(e, "statechange"), h.busy(!1), !0)) }, h.Adapter.bind(e, "popstate", h.onPopState), h.pushState = function (t, n, r, i) { if (h.getHashByUrl(r) && h.emulated.pushState) throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors)."); if (i !== !1 && h.busy()) return h.pushQueue({ scope: h, callback: h.pushState, args: arguments, queue: i }), !1; h.busy(!0); var s = h.createStateObject(t, n, r); return h.isLastSavedState(s) ? h.busy(!1) : (h.storeState(s), h.expectedStateId = s.id, p.pushState(s.id, s.title, s.url), h.Adapter.trigger(e, "popstate")), !0 }, h.replaceState = function (t, n, r, i) { if (h.getHashByUrl(r) && h.emulated.pushState) throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors)."); if (i !== !1 && h.busy()) return h.pushQueue({ scope: h, callback: h.replaceState, args: arguments, queue: i }), !1; h.busy(!0); var s = h.createStateObject(t, n, r); return h.isLastSavedState(s) ? h.busy(!1) : (h.storeState(s), h.expectedStateId = s.id, p.replaceState(s.id, s.title, s.url), h.Adapter.trigger(e, "popstate")), !0 }; if (s) { try { h.store = l.parse(s.getItem("History.store")) || {} } catch (m) { h.store = {} } h.normalizeStore() } else h.store = {}, h.normalizeStore(); h.Adapter.bind(e, "unload", h.clearAllIntervals), h.saveState(h.storeState(h.extractState(h.getLocationHref(), !0))), s && (h.onUnload = function () { var e, t, n; try { e = l.parse(s.getItem("History.store")) || {} } catch (r) { e = {} } e.idToState = e.idToState || {}, e.urlToId = e.urlToId || {}, e.stateToId = e.stateToId || {}; for (t in h.idToState) { if (!h.idToState.hasOwnProperty(t)) continue; e.idToState[t] = h.idToState[t] } for (t in h.urlToId) { if (!h.urlToId.hasOwnProperty(t)) continue; e.urlToId[t] = h.urlToId[t] } for (t in h.stateToId) { if (!h.stateToId.hasOwnProperty(t)) continue; e.stateToId[t] = h.stateToId[t] } h.store = e, h.normalizeStore(), n = l.stringify(e); try { s.setItem("History.store", n) } catch (i) { if (i.code !== DOMException.QUOTA_EXCEEDED_ERR) throw i; s.length && (s.removeItem("History.store"), s.setItem("History.store", n)) } }, h.intervalList.push(a(h.onUnload, h.options.storeInterval)), h.Adapter.bind(e, "beforeunload", h.onUnload), h.Adapter.bind(e, "unload", h.onUnload)); if (!h.emulated.pushState) { h.bugs.safariPoll && h.intervalList.push(a(h.safariStatePoll, h.options.safariPollInterval)); if (i.vendor === "Apple Computer, Inc." || (i.appCodeName || "") === "Mozilla") h.Adapter.bind(e, "hashchange", function () { h.Adapter.trigger(e, "popstate") }), h.getHash() && h.Adapter.onDomLoad(function () { h.Adapter.trigger(e, "hashchange") }) } }, (!h.options || !h.options.delayInit) && h.init() }(window);
(function($) {
    "use strict";

    $.fn.htmlClean = function() {
        this.contents().filter(function() {
            if (this.nodeType != 3) {
                $(this).htmlClean();
                return false;
            } else {
                //var $that = $(this);
                //var textContent = $that.text();
                //textContent = $.trim(textContent);
                //$that.text(textContent);

                return !/\S/.test(this.nodeValue);
            }
        }).remove();
        return this;
    };

})(jQuery);;
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as anonymous module.
		define(['jquery'], factory);
	} else {
		// Browser globals.
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\+/g;

	function decode(s) {
		if (config.raw) {
			return s;
		}
		return decodeURIComponent(s.replace(pluses, ' '));
	}

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

		s = decode(s);

		try {
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

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

		// Write
		if (value !== undefined) {
			options = $.extend({}, config.defaults, options);

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = config.json ? JSON.stringify(value) : String(value);

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

		// Read
		var cookies = document.cookie.split('; ');
		var result = key ? undefined : {};
		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decode(parts.shift());
			var cookie = parts.join('=');

			if (key && key === name) {
				result = decodeAndParse(cookie);
				break;
			}

			if (!key) {
				result[name] = decodeAndParse(cookie);
			}
		}

		return result;
	};

	config.defaults = {};

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

}));
;
/*
    jQuery Switch Plugin
*/

(function($) {
    'use strict';

    var config = $.fn.switchButton = function(options) {
        var opts = {};

        function createMarkup($container) {
            var label = $('<span>')
                .addClass('switch-label')
                .addClass(opts.labelStyle)
                .text(opts.label);
            var button = $('<div>')
                .addClass('switch-button')
                .addClass(opts.buttonStyle);
            var frame = $('<div>')
                .addClass('switch-frame')
                .addClass(opts.frameStyle)
                .append(button)
                .hide();

            $container
                .append(label)
                .append(frame);
        }

        function subscribeToEvents($frame, $button) {
            $frame
                .on('click', function() {
                    $button.click();
                });

            $button.toggle(function() {
                $(this).addClass('off').html(opts.offLabel);

                if (typeof(opts.offCallback) === 'function') {
                    opts.offCallback();
                }
            }, function() {
                $(this).removeClass('off').html(opts.onLabel);

                if (typeof(opts.onCallback) === 'function') {
                    opts.onCallback();
                }
            });
        }

        function setInitialState($button) {
            if (opts.initialState === 'off') {
                $button.click();
                $button.html(opts.offLabel);
            } else {
                $button.html(opts.onLabel);
            }
        }

        function updateSettings($container) {
            opts = $.extend({}, $.fn.switchButton.defaults, options);

            opts.label = $container.data('label') || opts.label;

            opts.onLabel = $container.data('on-label') || 'ON';
            opts.offLabel = $container.data('off-label') || 'OFF';

            opts.labelStyle = $container.data('label-style') || opts.labelStyle;
            opts.frameStyle = $container.data('frame-style') || opts.frameStyle;
            opts.buttonStyle = $container.data('button-style') || opts.buttonStyle;
        }

        return this.each(function() {
            var $container = $(this);

            // create initial settings
            updateSettings($container);

            // init markup
            createMarkup($container);

            var $frame = $container.find('.switch-frame');
            var $button = $frame.find('.switch-button');

            // add event subscription
            subscribeToEvents($frame, $button);

            // set initial state
            setInitialState($button);

            // fix flickering
            $frame.show();

            // prevent reinitialization of switch
            $container.removeClass('make-switch');
        });
    };

    config.defaults = {
        initialState: 'on',
    };
})(jQuery);;
(function ($) {
    'use strict';

    $.fn.visibleOnFocus = function() {

        if (!this) {
            return;
        }

        var self = this;

        var visibleCss = {
            'z-index': self.css('zIndex'),
            'opacity': self.css('opacity')
        };

        var hiddenCss = {
            'z-index': '-1',
            'opacity': '0'
        };
        
        function hideElement() {
            self.css(hiddenCss);
        }

        function showElement() {
            self.css(visibleCss);
            self.one('click', hideElement);
        }

        self
            .css(hiddenCss)
            .on('focus', showElement)
            .on('blur', hideElement);
    }
})(jQuery);;
(function ($) {
    'use strict';

    //Sets attributes passed as key-value pairs on an element.
    $.fn.setAttributes = function (attributes) {

        if (!this) {
            return;
        }

        var self = this;

        $.each(attributes, function (index, value) {
            self.attr(value[0], value[1]);
        });
    };
})(jQuery);;

/*
Copyright (C) <2012> <haithem bel haj>
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.
*/

(function() {
    'use strict';

  window.Router = (function() {

    Router.namedParam = /:\w+/g;

    Router.splatParam = /\*\w+/g;

    Router.prototype.trigger = true;

    function Router(routes) {
      var _this = this;
      this.routes = routes != null ? routes : {};
      History.Adapter.bind(window, 'statechange', function() {
        return _this.checkRoutes(History.getState());
      });
    }

    Router.prototype.route = function(route, callback, name) {
        route = route.replace(Router.namedParam, '([^\/^\?]+)').replace(Router.splatParam, '(.*?)');
        name = name || null;

        return this.routes["^" + route + "$"] = { callback: callback, name: name };
    };

    Router.prototype.checkRoutes = function(state) {
        var callback, regex, regexText, url, _ref;

        if (this.trigger) {
            _ref = this.routes;

            // There is need to add backslash in case of state.data object is null and url goes from state.hash when hashes fallback is used
            url = state.data.url || (window.history && window.history.pushState ? state.hash : '/' + state.hash);

            // sometimes state.data.url comes as a full url "http://gjobs.dev.neogov.net/jobs/258114/accounting-clerk"
            // for routing to work we only need a pathname part "/jobs/258114/accounting-clerk"
            // IE 8- uses hash-based urls - leave them as is
            // todo: investigate IE8 behaviour
            //if (!History.emulated.pushState) {
            // Chrome, FF
            var a = document.createElement('a');
            a.href = url;
            url = a.pathname + a.search + a.hash;

            // ensure that url starts with a slash
            url = url.indexOf('/') === 0 ? url : '/' + url;
            //} else {
            // IE 8 and below (hash based)
            // use original url
            //}

            var urlParts = url.split('?');
            urlParts[0] = urlParts[0];
            url = urlParts.join('?');

            for (regexText in _ref) {
                callback = _ref[regexText].callback;
                regex = new RegExp(regexText);

                if (regex.test(url)) {
                    callback.apply(window, regex.exec(url).slice(1));
                    // When there is a match break the cycle not to fire other matching routes
                    break;
                }
            }
        }

        return this.trigger = true;
    };

    Router.prototype.isCurrentUrlMatchedToRoute = function (routeName) {
        var _ref = this.routes;
        var url = window.location.pathname.toLowerCase() + window.location.search;

        for (var regexText in _ref) {
            var regex = new RegExp(regexText);
            var name = _ref[regexText].name;

            if (name === routeName && regex.test(url)) {
                return true;
            }
        }

        return false;
    };

    Router.prototype.cutQueryString = function (url) {
        return url.replace(/\?.+/, '');
    }

    Router.prototype.removePageTypeFromQuery = function (url) {
        var index = url.indexOf('pagetype=');
        var regexp = /pagetype=.*/;
        if (url.charAt(index - 1) === '&') {
            regexp = /&pagetype=.*/;
        }
        return url.replace(regexp, '');
    }

    Router.prototype.addQueryString = function (url) {
        return url + window.location.search;
    }

    Router.prototype.navigate = function (url, trigger, replace, name, innerData, saveQueryString) {
        if (trigger == null) trigger = true;
        if (replace == null) replace = false;
        if (name == null) name = null;
        if (saveQueryString) url = Router.prototype.addQueryString(url);
        this.trigger = trigger;
        if (replace) {
            return History.replaceState({
                'url': url,
                innerData: innerData
            }, document.title, url);
        } else {
            return History.pushState({
                'url': url,
                innerData: innerData
            }, document.title, url);
        }
    };

    Router.prototype.go = function(num) {
      return History.go(num);
    };

    Router.prototype.back = function() {
      return History.back();
    };

    return Router;

  })();

}).call(this);
;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').router = (function () {

        var router = new Router(),
            isFilterChanged,
            getUrlParams;

        isFilterChanged = function () {
            var savedStates = History.savedStates,
                currentState = History.getState(),
                previousState = savedStates[savedStates.length - 2],
                paramsToExclude = ['page', '_suid'],
                currentFilterParams,
                previousFilterParams,
                param,
                i;

            //Exclude params that aren't part of filter criteria
            currentFilterParams = getUrlParams(currentState.hash, paramsToExclude);
            previousFilterParams = getUrlParams(previousState.hash, paramsToExclude);

            if (currentFilterParams.length == previousFilterParams.length) {
                for (i = 0; i < currentFilterParams.length; i++) {
                    param = currentFilterParams[i];
                    if (currentFilterParams[param] != previousFilterParams[param]) {
                        return true;
                    }
                }

                return false;
            }

            return true;
        };

        getUrlParams = function (url, paramsToExclude) {
            var params = [],
                hashes = url.slice(url.indexOf('?') + 1).split('&'),
                hash,
                i;

            for (i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');

                if ((!paramsToExclude || $.inArray(hash[0], paramsToExclude) == -1) && hash[1]) {
                    params.push(hash[0]);
                    params[hash[0]] = hash[1];
                }
            }
            
            return params;
        };

        function getDataFromHistory () {
            var state = History.getState();
            var data = {};
            if (state && state.data && state.data.innerData) {
                data = state.data.innerData;
            }
            return data;
        }

        function changePageTitle(isJobDetailsTab) {
            var tabName = isJobDetailsTab ? 'Job Details tab' : 'Apply tab';
            var data = getDataFromHistory();
            var jobTitle = data.jobTitle || data.title;
            var siteUrl = window.location.hostname;
            var currentSite = siteUrl.indexOf("schooljobs") != -1 ? "School Jobs" : "Government Jobs";
            if (jobTitle) {
                document.title = jobTitle + ' | ' + tabName + ' | ' + currentSite;
            }
        }

        /* Routes declaration */

        // navigation behavior for criteria tabs on browse page
        router.route('/browse/:criteria', function (criteria) {
            try {
                $("#browse-" + criteria).next().click();

            } catch (e) {
                console.error(e);
            }
        });

        var navigateToJob = function(jobId, jobName, tabIndex) {
            try {
                var state = History.getState();

                var queryParamsIndex = state.url.indexOf('?');
                var url = state.url;
                if (queryParamsIndex > 0) {
                    url = url.substring(0, queryParamsIndex);
                }

                var $job = $('[data-job-id="' + jobId + '"]');
                var title;
                if (state.data.innerData && state.data.innerData.jobTitle) {
                    title = state.data.innerData.jobTitle;
                } else {
                    // todo: Find a better way to populate job title
                    title = $job.find('a.job-details-link').text();
                }

                var jobIsFeatured = $job[0] && $job[0].dataset.jobIsfeatured;

                var requestParameters = {
                    id: jobId
                };

                if (title) {
                    requestParameters.title = title;
                }

                if (namespace('gJobs').searchPage.isSearchPage() && (!namespace('gJobs').searchPage.details.isActive() || jobId != namespace('gJobs').searchPage.details.getActiveJobId())) {
                    namespace('gJobs').searchPage.details.loadJob(jobId, title, url, tabIndex, jobIsFeatured);
                } else {
                    gJobs.searchPage.setTab(tabIndex);
                }
            } catch (e) {
                console.error(e);
            }
        };

        var getJobPosts = function (queryString) {
            var url = '/jobs?' + queryString,
                isChanged = isFilterChanged();

            if (isChanged) {
                return gJobs.searchPage.filter.getFacetsAndJobPosts(url + '&isFiltered=true');
            } else {
                return gJobs.searchPage.searchResults.getJobPosts(url);
            }
        }

        var closeFlyoutOrReload = function () {
            if (!window.disableLegacyNavigation && !gJobs.searchPage.details.viewExists()) {
                location.reload();
                return;
            }

            $(document).trigger(Events.CommonEventsNames.CloseFlyout);
        };

        router.route('/applications/submitted/offer/:offerId/?\\??*queryString',
            function (offerId) {
                namespace('gJobs').applicationsPage.openOfferFlyout(offerId);
        }, 'offerRoute');

        router.route('/applications/submitted/canvass/:canvassFormId/?\\??*queryString',
            function (canvassFormId) {
                namespace('gJobs').applicationsPage.openCanvassFormFlyout(canvassFormId);
            }, 'canvassFormRoute');

        router.route('/applications/submitted/:jobId/:jobApplicationId/:tabName/?\\??*queryString', function (jobId, jobApplicationId, tabName) {
            var state = History.getState();
            var submittedApplicationInfo = {
                id: jobId,
                jobApplicationId: jobApplicationId,
                title: ''
            }

            if (state.data.innerData) {
                if (state.data.innerData.title) {
                    submittedApplicationInfo.title = state.data.innerData.title;
                }
                if (state.data.innerData.subTitle) {
                    submittedApplicationInfo.subTitle = state.data.innerData.subTitle;
                }
            }

            namespace('gJobs').applicationsPage.openSubmittedAppFlyout(submittedApplicationInfo, tabName);
        }, 'submittedApplicationRoute');

        router.route('/jobs/canvass/:canvassFormId/?\\??*queryString',
            function (canvassFormId) {
                namespace('gJobs').applicationsPage ?
                    namespace('gJobs').applicationsPage.openCanvassFormFlyout(canvassFormId) :
                    namespace('gJobs').searchPage.openCanvassFormFlyout(canvassFormId);
            }, 'canvassFormSearchROute');

        router.route('/jobs/:jobId/:jobName/agency/:agencyName/apply/(.*?)', function (jobId, jobName) {
            navigateToJob(jobId, jobName, 1);
        });
        
        router.route('/jobs/:jobId/:jobName/agency/:agencyName', function (jobId, jobName) {
            navigateToJob(jobId, jobName, 0);
        });

        router.route('/jobs/:jobId/:jobName/agency/:agencyName/apply', function (jobId, jobName) {
            // navigate to apply tab
            navigateToJob(jobId, jobName, 1);
        });

        router.route('/jobs/:jobId/:jobName/agency/:agencyName/apply#:tabAnchor', function (jobId, jobName, agencyName, tabAnchor) {
            router.navigate('/jobs/' + jobId + '/' + jobName + '/agency/' + agencyName + '/apply', false, true);
        });

        // we need this empty route to ignore any job route actions on inner navigations inside online app
        router.route('/jobs/:jobId/:jobName(.*?)/apply/(.*?)', function (jobId, jobName) {
            navigateToJob(jobId, jobName, 1);
        }, 'jobOnlineAppRoute');

        router.route('/jobs/:jobId/:jobName/apply/?\\??*queryString', function (jobId, jobName, queryString) {
            navigateToJob(jobId, jobName, 1);
            changePageTitle(false);
        }, 'jobApplyRoute');

        router.route('/jobs/:jobId/:jobName/apply#:tabAnchor', function (jobId, jobName, tabAnchor) {
            router.navigate('/jobs/' + jobId + '/' + jobName + '/apply', false, true);
        });

        router.route('/jobs/:jobId/:jobName/?\\??*queryString', function (jobId, jobName, queryString) {
            navigateToJob(jobId, jobName, 0);
            changePageTitle(true);
        }, 'jobDetailsRoute');

        router.route('/jobs/backfill\\??*queryString', function (queryString) {
            gJobs.searchPage.searchResults.loadBackfillResultsIfGJobsResultsAreEmpty('/jobs/backfill?' + queryString);
        });

        router.route('/applications/:tabName/?\\??*queryString', function (tabName, queryString) {
            closeFlyoutOrReload();
            gJobs.applicationsPage.switchTab(tabName);

            var page = getUrlParams(queryString).page || 1;
            gJobs.applicationsPage.goToPage(page);
        });

        router.route('/inbox/:messageId/:messageSource/:filterType?\\??*queryString',
            function(messageId, messageSource, filterType) {
                try {
                    namespace('gJobs').inboxPage.loadInboxMessage(messageId, messageSource, filterType);
                } catch (e) {
                    toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                }
            }, 'inbox');

        router.route('/inbox/?\\??*queryString',
            function () {
                try {
                    namespace('gJobs').inboxPage.getMessages();
                } catch (e) {
                    toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                }
            });

        //Escaped '?' character is needed here to be a part of search string for regular expression inside Router.js
        //This is necessary to differentiate this route from job details route. 
        router.route('/jobs/?\\??*queryString', function (queryString) {
            closeFlyoutOrReload();
            getJobPosts(queryString)
                .then(gJobs.searchPage.trackJobSearchResultsClicks);
        });

        router.route('/\\??*path', function () {
            closeFlyoutOrReload();
        });

        router.route('/applications/index/?\\??*queryString', function () {
            router.navigate('/applications/submitted', true ,true, null, null, true);
        });
        
        router.route('/applications/index/:agencyName', function () {
            closeFlyoutOrReload();
        });
        
        router.route('/', function () {
            closeFlyoutOrReload();
        });

        return router;
    })();

})(window);;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').ajax = (function () {

        var _ajaxGet = function (url, data) {
            return $.ajax({
                url: url,
                type: 'GET',
                contentType: 'text/html',
                cache: false,
                data: data
            });
        };

        var _ajaxGetWithLoadingElement = function (url, loadingElementSelector, data) {
            var $loadingElement = $(loadingElementSelector);

            $loadingElement.show();

            return _ajaxGet(url, data).always(function () {
                $loadingElement.hide();
            });
        };

        var ajaxGet = function(url, loadingElementSelector, data) {
            if (loadingElementSelector) {
                return _ajaxGetWithLoadingElement(url, loadingElementSelector, data);
            }

            return _ajaxGet(url, data);
        };

        var redirectUnauthorized = function () {
            localStorage.setItem('action', 'redirect');
            localStorage.setItem('reason', 'nonauthorized');

            window.location.reload(false);
        };

        (function () {
            $.ajaxSetup({
                error: function (xhr) {
                    var isAuthorized = (xhr.status !== 401);

                    if (!isAuthorized) {
                        redirectUnauthorized();
                    }
                },
                success: function (data) {
                    var isAuthorized = data !== "NotAuthorized";

                    if (!isAuthorized) {
                        redirectUnauthorized();
                        return;
                    }
                }
            });
        })();


        return {
            ajaxGet: ajaxGet
        };
    })();

})(window);;
(function(window, undefined) {
    'use strict';

    var maxMobileScreenWidth = 767;

    function getOriginatorUrl() {
        var pageTypes = namespace('gJobs').pageInfoService.getPageTypes();
        var isSubmittedApplicationsTab = false;
        var urlParams = url.get(window.location.search.slice(1), { array: true });
        var currentPageType = urlParams.pagetype;
        delete urlParams.pagetype;

        if (!currentPageType) {
            currentPageType = namespace('gJobs').pageInfoService.getCurrentPageType().type;
            isSubmittedApplicationsTab = currentPageType === pageTypes.applications.type;
        }

        for (var param in urlParams) {
            var paramValue = urlParams[param];
            urlParams[param] = paramValue.replace(/\+/g, ' ');
        }

        var newQuery = url.buildget(urlParams);
        newQuery = newQuery ? '?' + newQuery : '';

        // IE10 does not have window.location.origin.
        if (!window.location.origin) {
            window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
        }

        var originator = window.location.origin;
        if (currentPageType === pageTypes.searchPage.type) {
            originator += '/' + pageTypes.searchPage.urlPart + newQuery;
        } else if (currentPageType === pageTypes.applications.type) {
            if (!isSubmittedApplicationsTab) {
                originator += '/' + pageTypes.applications.urlPart + '/incomplete' + newQuery;
            } else {
                originator += '/' + pageTypes.applications.urlPart + '/submitted' + newQuery;
            }
        } else if (currentPageType === pageTypes.inbox.type) {
            originator += "/" + pageTypes.inbox.urlPart + newQuery;
        }

        return originator;
    }

    /* TODO: unify, copy-pasted from SearchPage.js */

    function tryRaiseEvent(tryEventName, eventName, eventCallback) {
        var e = jQuery.Event(tryEventName);

        e.canRaiseEvent = true;
        e.callbackEventName = eventName;

        $(document).trigger(e);

        if (e.canRaiseEvent) {
            eventCallback();
        }
    }

    namespace('gJobs').Flyout = function(view) {

        var self = this;

        var elements = {
            $view: $(view),
            $body: $('body'),
            $flyoutBody: $(view).find('.flyout-window-body'),
            $flyoutHeader: $(view).find('.flyout-window-header'),
            $closeButton: $(view).find('button.close'),
            $title: $(view).find('.flyout-window-header-title'),
            $subtitle: $(view).find('.flyout-window-header-subtitle'),
            $flyoutOverlay: $(view + '-overlay')
        };

        elements.$view.addClass('hide');

        /*
            In Internet Explorer versions prior to 11, height is not correctly calculated for the nested table.
        */
        var applyIEFix = gJobs.browserDetector.isIE() <= 10;

        /*
            Set of methods for manipulation with Master Page.
        */
        var master = {
            masterPageTitle: document.title,

            setScrollable: function(scrollable) {
                elements.$body.toggleClass('inner-scrollbar', !scrollable);

                // Adds padding right to handle contents to stay at its original place
                // in Windows and Firefox in Mac when hiding the scrollbar.
                if (!scrollable) {
                    elements.$body.css('padding-right', this.getScrollbarWidth());
                } else {
                    elements.$body.css('padding-right', 0);
                }
            },
            saveOriginatorUrl: function() {
                self.originator = getOriginatorUrl();
            },
            navigateToOriginatorUrl: function () {
                if (gJobs && gJobs.router && self.originator) {
                    gJobs.router.navigate(self.originator, false);
                }
            },
            getScrollbarWidth: function() {
                var parent,
                    child,
                    width;

                parent = $('<div style="width:50px; height:50px; overflow:auto"><div/></div>').appendTo(elements.$body);
                child = parent.children();
                width = child.innerWidth() - child.height(99).innerWidth();
                parent.remove();

                return width;
            },
        };

        /*
            Set of methods for visibility control of the flyout window.
        */
        var visibility = {
            show: function () {
                elements.$view.removeClass('hide');
                elements.$view.removeClass('inactive');
                elements.$view.addClass('active');
            },
            hide: function (callback) {
                elements.$view.addClass('inactive');
                elements.$view.removeClass('active');

                elements.$view.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {
                    if (!visibility.isVisible()) {
                        elements.$view.addClass('hide');
                        if (typeof callback === 'function') {
                            callback();
                        }
                    }
                });
            },
            isVisible: function() {
                return elements.$view.hasClass('active');
            },
            //specific to IE 8-10
            setContentHeight: function () {
                var $maximizedRelativeBlock = elements.$flyoutBody.find('.position-relative-maximized');

                $maximizedRelativeBlock.height(0);

                var $contentHeader = elements.$flyoutBody.find('.content-header');
                var computedHeight = elements.$flyoutBody.height() - $contentHeader.height();

                $maximizedRelativeBlock.height(computedHeight);
            }
        };

        /*
            Set of methods for state control.
        */
        var state = {
            close: function () {
                if (!state.isActive()) {
                    return;
                }

                $(document).trigger(Events.CommonEventsNames.FlyoutClosing);

                master.setScrollable(true);
                master.navigateToOriginatorUrl();

                if (applyIEFix) {
                    $(window).off('resize deviceClassChanged', visibility.setContentHeight);
                }

                visibility.hide(function() {
                    gJobs.focusService.restoreBrowserControlsFocusBehavior();
                    setTimeout(function() {
                        gJobs.focusService.restoreFocus({
                            focusRestoringCallback: function ($restoringElement) {
                                gJobs.screenReadersService.onceNotification({
                                    $element: $restoringElement,
                                    message: 'Flyout has been closed. '
                                });
                            }
                        });
                    });
                });
            },

            tryClose: function () {
                if (!state.isActive()) {
                    return;
                }

                tryRaiseEvent(
                    Events.CommonEventsNames.TryCloseFlyout,
                    Events.CommonEventsNames.CloseFlyout,
                    self.close
                );

                if (window.enableStickyHeader) {
                    $(document).trigger(Events.CommonEventsNames.ShowStickyHeader);
                }
            },

            open: function () {
                master.saveOriginatorUrl();
                master.setScrollable(false);

                state.restoreDefaultSize();
                visibility.show();
                if (applyIEFix) {
                    visibility.setContentHeight();
                    $(window).on('resize', visibility.setContentHeight);
                }
                $(document).trigger(Events.CommonEventsNames.ShowFlyout, Areas.AreaNames.gJobs);
                gJobs.skipToContentService.showOnNextTab();
            },

            isActive: function() {
                return visibility.isVisible();
            },

            setSize: function(sizeValue) {
                if (sizeValue == parseInt(sizeValue)) {
                    elements.$view.attr('width', sizeValue);
                } else {
                    //the size is 'maximized' / 'fixed'
                    elements.$view.attr('data-size', sizeValue);
                }
                if (applyIEFix) {
                    visibility.setContentHeight();
                }
            },

            restoreDefaultSize: function() {
                elements.$view.attr('data-size', self.defaultSize);
            }
        };

        /*
            Set of methods for input handling.
        */
        var input = {
            registerBehavioralEventsHandlers: function() {
                $(document)
                    .off(Events.CommonEventsNames.CloseFlyout, null, self.close)
                    .on(Events.CommonEventsNames.CloseFlyout, null, self.close);
            },
            registerMouseEventHandlers: function() {

                elements.$closeButton.off('click').click(function() {
                    state.tryClose();
                });

                elements.$flyoutOverlay.off('click').click(function () {
                    state.tryClose();
                });
            }
        };

        self.getView = function () {
            return elements.$view;
        };

        self.create = function () {
            input.registerBehavioralEventsHandlers();
            input.registerMouseEventHandlers();

            self.defaultSize = elements.$view.attr('data-size');
        };

        self.destroy = function() {

        };

        self.open = function ($focusTarget) {
            if ($focusTarget) {
                gJobs.focusService.setFocus($focusTarget);
            }

            state.open();            
            $(document).on('keydown', arrowKeyScrollingHandler);

            SetAriaVisibility(true);
            $("#sjobs-footer-new").hide();
            $("#footer-new").hide();
            $(".twitter-timeline").hide();
        };

        self.close = function () {            
            state.close();
            $(document).off('keydown', arrowKeyScrollingHandler);

            SetAriaVisibility(false);
            $("#footer-new").show();
            $("#sjobs-footer-new").show();
            $(".twitter-timeline").show();

            document.title = master.masterPageTitle;
        };

        self.isActive = function() {
            return state.isActive();
        };

        self.getTitle = function() {
            return elements.$title.html();
        };

        self.setTitle = function(title) {
            elements.$title.html(title);
        };

        self.getSubtitle = function() {
            return elements.$subtitle.html();
        };

        self.setSubtitle = function (subtitle) {
            if (!subtitle)
                elements.$subtitle.addClass("hide");
            else {
                elements.$subtitle.removeClass("hide");
                elements.$subtitle.html(subtitle);
            }
        };

        self.maximize = function () {
            state.setSize('maximized');
        };

        var $tabbableElements;

        function arrowKeyScrollingHandler(e) {
            var event = e || window.event;
            var keyCode = event.keyCode || event.which;
            var target = event.target || event.srcElement;
            if (keyCode === $.ui.keyCode.UP || keyCode === $.ui.keyCode.DOWN || keyCode === $.ui.keyCode.PAGE_UP || keyCode === $.ui.keyCode.PAGE_DOWN) {
                var isScrollView = $(target).closest('.flyout-scroll-view').length > 0;
                if (!isScrollView) {
                    event.preventDefault();
                }
            }
        }

        function SetAriaVisibility(hide) {
            var $containersToHide = $('#job-list-container, #content-container .top-resume-external-new,' + 
                '#content-container .city-info-container, #sidebar-container, #cookie-consent, #applications');
            $containersToHide.attr('aria-hidden', hide);

            if (hide) {
                $tabbableElements = $containersToHide
                    .find(':tabbable')
                    .add($('#job-list-container .share-button, #cookie-consent'));
            }

            if ($tabbableElements) {
                $tabbableElements.attr('tabindex', hide ? '-1' : '0');
            }
        }
    };
})(window);;
(function (window, undefined) {
    'use strict';

    var AutocompleteFieldKinds = {
        ClassSpecificationTitleForJobInterestCard: 'ClassSpecificationTitleForJobInterestCard',
        DepartmentTitleForJobInterestCard: 'DepartmentTitleForJobInterestCard',
        LocationTitleForJobInterestCard: 'LocationTitleForJobInterestCard',
        ClassSpecificationsTitleForFilterCategory: 'ClassSpecificationsTitleForFilterCategory'
    };

    OnlineApp.Namespace.extend('OnlineApp', {
        AutocompleteFieldKinds: AutocompleteFieldKinds
    });

})(window);;
(function () {
    'use strict';

    var KEY_CODES = {
        TAB: 9,
        SHIFT: 16
    };

    var TABBABLE_ELEMENT_SELECTOR = ':tabbable',
        FOCUSABLE_ELEMENT_SELECTOR = ':focusable';

    function skipToContentService() {
        var self = this;
        var $document = $(document);
        var $skipToContentButton = $('#skip-to-content-button');

        var isJobSearchPage;
        checkForJobSearchPage();

        $skipToContentButton
            .on('click', onSkipToContentClick)
            .visibleOnFocus();

        $skipToContentButton.on('keyup', onKeyUp);
        function onKeyUp() {

            $skipToContentButton.focus();
        }

        self.showOnNextTab = function (callbackAfterShow, focusRestoreCallback) {
            $document.on('keydown', showOnNextTabHandler);
            $document.on('mousedown', showOnNextTabHandler);

            function showOnNextTabHandler(e) {
                $document.off('keydown', showOnNextTabHandler);
                $document.off('mousedown', showOnNextTabHandler);

                if (!e.keyCode || e.keyCode !== KEY_CODES.TAB) {
                    return;
                }

                e.stopPropagation();
                e.preventDefault();
                var $lastFocused = $(document.activeElement);
                $skipToContentButton.focus();
                if (typeof (focusRestoreCallback) == 'function') {
                    $skipToContentButton.one('keydown', function (e) {
                        if (e.keyCode !== KEY_CODES.TAB) {
                            return;
                        }
                        e.stopPropagation();
                        e.preventDefault();
                        focusRestoreCallback($lastFocused);
                    });
                }
                callbackAfterShow && callbackAfterShow();
            }
        };

        $(window).on('statechange', checkForJobSearchPage);

        function checkForJobSearchPage() {
            isJobSearchPage = window.location.pathname === '/jobs' || window.location.pathname === '/jobs/';
            var buttonText = isJobSearchPage ? 'Skip to search results' : 'Skip to main content';
            $skipToContentButton.find('.visible-on-focus-text').text(buttonText);
        }

        function getFirstFocusableElementSelector($contentContainer) {
            return $contentContainer.hasClass('no-tabbable-main-content')
                ? FOCUSABLE_ELEMENT_SELECTOR
                : TABBABLE_ELEMENT_SELECTOR;
        }

        function onSkipToContentClick() {
            var $contentContainer = getContentContainer();
            var firstFocusableElemetSelector = getFirstFocusableElementSelector($contentContainer);
            var $focusTarget = $contentContainer.find(firstFocusableElemetSelector).first();
            if ($focusTarget.length && $focusTarget[0].id == "el-candidate-keyword-search-input") {
                $("#back-eligible-list-link").focus();
            }
            else if ($contentContainer[0] && $contentContainer[0].id == "canvass-body" && $focusTarget.length == 0)
            {
                $("#last-focusable-element").focus();
            }
            else if ($focusTarget.length) {
                $focusTarget.focus();
            } else {
                $contentContainer.focus();
            }
        }

        function getContentContainer() {
            var $termsAndPrivacyPolicyChangeAnnouncement = $('#terms-and-privacy-policy-update-confirmation.active');
            if ($termsAndPrivacyPolicyChangeAnnouncement.length) {
                return $termsAndPrivacyPolicyChangeAnnouncement;
            }

            if (isJobSearchPage) {
                return $('#content-container');
            }

            var $sortFlyoutContainer = $('.new-filter-flyout.active .sort-panel').closest('.flyout');
            if ($sortFlyoutContainer.length) {
                // If there's an already selected element within the flyout, focus the first selected one.
                var $selectedLabel = $sortFlyoutContainer.find('input:checked').first();
                if ($selectedLabel.length) {
                    return $selectedLabel.parent().closest('div');
                }

                return $sortFlyoutContainer;
            }

            var $filterFlyoutContainer = $('.new-filter-flyout.active .filter-flyout-container');
            if ($filterFlyoutContainer.length) {
                return $filterFlyoutContainer;
            }

            var $flyoutDetailsContainer = $('#job-flyout-content .entity-info:visible');
            if ($flyoutDetailsContainer.length) {
                return $flyoutDetailsContainer;
            }

            var $classSpecFlyoutContent = $('.class-specs-flyout.active #class-specs-flyout-content .active .onlineapp-wrapper:visible');
            if ($classSpecFlyoutContent.length) {
                return $classSpecFlyoutContent;
            }

            var $classSpecificationsFlyout = $('.tab-content #info .info-content');
            if ($classSpecificationsFlyout.length) {
                return $classSpecificationsFlyout;
            }

            var $incompleteAppFlyoutDetailsContainer = $('#incomplete-application-flyout-content .entity-info:visible');
            if ($incompleteAppFlyoutDetailsContainer.length) {
                return $incompleteAppFlyoutDetailsContainer;
            }

            var $jobFlyoutApplicationSubmitContent = $('#online-application-block:visible > .submitted');
            if ($jobFlyoutApplicationSubmitContent.length) {
                return $jobFlyoutApplicationSubmitContent;
            }

            var $jobFlyoutContent = $('#online-application-block:visible');
            if ($jobFlyoutContent.length) {
                return $jobFlyoutContent.find('.tab-content.onlineapp-tabs');
            }

            var $infoView = $('.tab-content #info-view:visible');
            if ($infoView.length) {
                return $infoView;
            }

            var $applyTab = $('.tab-content #apply:visible');
            if ($applyTab.length) {
                return $applyTab;
            }

            var $jobInterestCardFlyoutContent = $('.job-interest-card-flyout.active #job-interest-card-flyout-content .active .onlineapp-wrapper:visible');
            if ($jobInterestCardFlyoutContent.length) {
                return $jobInterestCardFlyoutContent;
            }

            var $jobSearchHeaderContainer = $('.job-search-header-container');
            if ($jobSearchHeaderContainer.find(':focusable').length) {
                return $jobSearchHeaderContainer;
            }

            var $gJobsApplicationView = $('.application-view-page.active .flyout-content .job-details-container.active');
            if ($gJobsApplicationView.length) {
                return $gJobsApplicationView;
            }

            var $onlineApplicationView = $('.new-job-flyout.active #submitted-application-flyout-content .flyout-tab.active .entity-info, ' +
                '.new-job-flyout.active #submitted-application-flyout-content .flyout-tab.active .application-container');
            if ($onlineApplicationView.length) {
                return $onlineApplicationView;
            }

            var $jobAlertEditFlyout = $('.job-alert-edit-content #search-form:visible');
            if ($jobAlertEditFlyout.length) {
                return $jobAlertEditFlyout;
            }

            var $settings = $('#account-settings:visible, #profile-settings:visible');
            if ($settings.length) {
                return $settings.find('.tab-content');
            }

            var $convictionQuestions = $('.conviction-questionnaire-page #questions-tab, .conviction-questions:visible .box-container.edit-dialog');
            if ($convictionQuestions.length) {
                return $convictionQuestions;
            }

            var $careersScheduleFlyoutContent = $('.schedule-exam-flyout.active .content');
            if ($careersScheduleFlyoutContent.find(':focusable').length) {
                return $careersScheduleFlyoutContent;
            }

            var $careersScheduleFlyout = $('.schedule-exam-flyout.active');
            if ($careersScheduleFlyout.length) {
                return $careersScheduleFlyout;
            }

            var $careersHistoryFlyout = $('.app-history-flyout.active');
            if ($careersHistoryFlyout.length) {
                return $careersHistoryFlyout.find('.flyout-content');
            }

            var $homePageContent = $('#search-form, .search-form');
            if ($homePageContent.length) {
                return $homePageContent;
            }

            var $inboxMessageDetailsContainerBody = $(".inbox-message-view-page #inbox-message-body");
            if ($inboxMessageDetailsContainerBody.length) {
                return $inboxMessageDetailsContainerBody;
            }

            var $inboxMessageDetailsContainer = $(".inbox-message-view-page");
            if ($inboxMessageDetailsContainer.length) {
                return $inboxMessageDetailsContainer;
            }

            var $inboxContainer = $(".inbox-container");
            if ($inboxContainer.length) {
                return $inboxContainer;
            }

            var $helpAndSupport = $('.info-body:visible');
            if ($helpAndSupport.length) {
              return $helpAndSupport;
            }

            var $offerLetterFlyoutContent = $('#offer-flyout-content .header-offer-response-container:visible,'+
                '#offer-flyout-content .flyout-tab-body:visible');
            if ($offerLetterFlyoutContent.length) {
                return $offerLetterFlyoutContent;
            }

            var $canvassFormFlyoutContent = $('#canvass-flyout-content .flyout-tab-body:visible');
            if ($canvassFormFlyoutContent.length) {
                return $canvassFormFlyoutContent;
            }

            var $addSupplementalAttachmentsFlyoutContent = $('.flyout-content.supplemental-attachments-flyout-content:visible');
            if ($addSupplementalAttachmentsFlyoutContent.length) {
                return $addSupplementalAttachmentsFlyoutContent;
            }

            var $contentContainer = $('.content-container:visible');
            if ($contentContainer.length) {
                return $contentContainer;
            }

            var $scheduleFlyoutContent = $('.flyout-window.schedule-exam-page.active .content');
            if ($scheduleFlyoutContent.find(':focusable').length) {
                return $scheduleFlyoutContent;
            }

            var $scheduleFlyout = $('.flyout-window.schedule-exam-page.active');
            if ($scheduleFlyout.length) {
                return $scheduleFlyout;
            }

            var $jobDetailsFlyoutContent = $('.tab-content.job-details-tabs.flyout-content');
            if ($jobDetailsFlyoutContent.length) {
                return $jobDetailsFlyoutContent;
            }

            var $applicationHistoryContent = $('.application-history-content:visible');
            if ($applicationHistoryContent.length) {
                return $applicationHistoryContent;
            }

            var $content = $('#content:visible');
            if ($content.length) {
                return $content;
            }

            var $header = $('#header');
            if(!$header.hasClass('mobile-collapsed')){
                return $header;
            }
        }

        return self;
    };

    namespace('gJobs').skipToContentService = new skipToContentService();
})();;
(function (window, $, ko, undefined) {
    'use strict';

    if (!$ || !ko) {
        throw new Error("jQuery and Knockout should be defined");
    }

    var ApplicationMenu = function () {
        var self = this;

        self.incompleteApplicationsCount = ko.observable();

        self.unreadMessagesCount = ko.observable();
        self.displayedUnreadMessagesCount = ko.computed(function () {
            return self.unreadMessagesCount() > 99 ? "99+" : self.unreadMessagesCount();
        });

        self.showIcon = ko.computed(function () {
            var count = parseInt(self.incompleteApplicationsCount());
            return !isNaN(count) && count > 0;
        });
        self.showUnreadMessagesCount = ko.computed(function() {
            var count = parseInt(self.unreadMessagesCount());
            return !isNaN(count) && count > 0;
        });

        self.unreadMessagesLabelText = ko.computed(function(){
            var count = parseInt(self.unreadMessagesCount());
            var message = 'Inbox';
            if (!isNaN(count) && count > 0) {
                message += ', ' + count + ' unread messages';
            }
            return message;
        });
    };

    var employerFolderName;
    //Defaulting this to one when user logs in
    var siteFilterType = 1;
    namespace('gJobs').applicationMenu = (function () {
        
        var instance;

        return {
            getInstance: function () {
                if (!instance) {
                    instance = new ApplicationMenu();
                }

                return instance;
            },
            updateIncompleteApplicationsCount: function (value) {
                var countObservable = this.getInstance().incompleteApplicationsCount;
                var url = '/Applications/GetIncompleteApplicationsCount' +
                          (!!employerFolderName ? '?employerFolderName=' + employerFolderName : '');

                if (value != null) {
                    countObservable(value);
                } else {
                    gJobs
                        .ajax
                        .ajaxGet(url)
                        .done(function (count) {
                            if (count) {
                                countObservable(count);
                            }
                        });
                }
            },
            incrementIncompleteApplicationsCount: function() {
                var countObservable = this.getInstance().incompleteApplicationsCount;
                countObservable(countObservable() + 1);
            },
            decrementIncompleteApplicationsCount: function() {
                var countObservable = this.getInstance().incompleteApplicationsCount;
                countObservable(countObservable() - 1);
            },
            updateUnreadMessagesCount: function () {
                var countObservable = this.getInstance().unreadMessagesCount;

                OnlineApp.Services.authenticationService.isLoggedIn()
                    .done(function (isLoggedIn) {
                        if (isLoggedIn) {
                            $.ajax({
                                url: "/api/inbox/GetNumberOfMessagesInCategories",
                                type: "GET",
                                data: { siteFilterType: siteFilterType, employerFolderName: employerFolderName }
                                })
                                .done(function (data) {
                                    try {
                                        var numberOfUnreadMessages = parseInt(data.numberOfUnreadMessages);
                                        countObservable(numberOfUnreadMessages);
                                    }
                                    catch(ex){}
                                })
                                .fail(function (error) {
                                    console.log(error);
                                });
                        }
                    });
            },
            decrementUnreadMessagesCount: function () {
                var countObservable = this.getInstance().unreadMessagesCount;
                countObservable(countObservable() - 1);
            },
            getApplicationUserMenu: function() {
                if (revampedDesign) {
                    return $("#header .nav.right-nav");
                }

                return $("#header .application-menu-link");
            },
            isApplicationUserMenuShown: function () {
                var $applicationUserMenu = this.getApplicationUserMenu();
                return $applicationUserMenu.length ? !$applicationUserMenu.hasClass('hide') : false;
            },
            initApplicationUserMenu: function () {
                var $appMenu = this.getApplicationUserMenu();
                var appMenuElement = $appMenu.get(0);

                this.updateApplicationUserMenu();

                if (ko.dataFor(appMenuElement)) {
                    return;
                }

                var appMenuInstance = this.getInstance();

                employerFolderName = AgencyPages.pageInfoService ?
                    AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                    gJobs.pageInfoService.getCurrentAgencyPageFolderName();

                $appMenu.removeClass('hide');

                // Apply knockout bindings when DOM is ready
                ko.applyBindings(
                    appMenuInstance,
                    appMenuElement);
            },
            updateApplicationUserMenu: function() {
                gJobs.applicationMenu.updateIncompleteApplicationsCount();
                gJobs.applicationMenu.updateUnreadMessagesCount();
            }
        };
    })();

    $(function () {
        // After document is loaded and user is loggedin need to init application user menu
        if (gJobs.applicationMenu.isApplicationUserMenuShown()) {
            gJobs.applicationMenu.initApplicationUserMenu();
        }

        if (revampedDesign && gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.GJobs) {
            gJobs.nonFlickeringPopover($('.inbox-link a'), 'header-nav-popover visible-desktop');
        }
    });

    var initAsyncEventsNames =
        OnlineApp.Events.CommonEventsNames.Login + ' ' +
        Events.CommonEventsNames.Register;

    var updateAsyncEventNames =
        Events.CommonEventsNames.ApplicationSubmitted + ' ' +
        Events.CommonEventsNames.CloseFlyout;

    $(document)
        .on(initAsyncEventsNames,
            function () {
                gJobs.applicationMenu.initApplicationUserMenu();
            })
        .on(updateAsyncEventNames,
            function() {
                if (gJobs.applicationMenu.isApplicationUserMenuShown()) {
                    gJobs.applicationMenu.updateApplicationUserMenu();
                }
            })
        .on(Events.CommonEventsNames.DecreaseNumberOfUnreadMessages,
            function() {
                gJobs.applicationMenu.decrementUnreadMessagesCount();
            });

})(window, jQuery, ko);;
(function ($) {

    $.fn.addClearButton = function (shouldSubmitOnEnter, ariaLabel) {

        var that = $(this);
        var clearFieldButton =
            '<div class=\'ss-custom-scope\'>' +
            '<button type=\'reset\' class=\'clear-field-button ss-delete clearButton dynamic-tabindex\' aria-label=\'' + ariaLabel + '\' style=\'display:none;\'>' +
                '<span class="hide">Clear Search Field</span>' +
            '</button>' + 
            '</div>';

        var toggleClearButton = function () {
            if (that.val() === '') {
                that.removeClass('filled');
                that.next('.ss-custom-scope').find('.clear-field-button').hide();
            } else {
                that.addClass('filled');
                that.next('.ss-custom-scope').find('.clear-field-button').show();
                if (shouldSubmitOnEnter && e.keyCode === $.ui.keyCode.ENTER) {
                    this.closest('form').trigger('submit');
                }
            }
        }

        that.after(function () {
            var searchInput = $(this);
            return $(clearFieldButton)
                .click(function (e) {
                    searchInput.val('');
                    searchInput.focus();
                    searchInput.trigger('change');
                    searchInput.removeAttr("aria-activedescendant");
                    e.preventDefault();
                });
        });

        that.on('change keyup paste', function (e) {
            toggleClearButton();
        }); 

        toggleClearButton();
    };

}(jQuery));;
(function(window, undefined) {
    'use strict';

    var $detailsContainer = $('#content-container');

    /**
     * Gets a URL leading to Online Application scripts.
     *
     * @return {String} The URL leading to Online Application scripts.
     */
    var getOnlineApplicationScriptsUrl = function () {
        return $('#online-application-link').attr('href');
    };

    /**
     * Gets current job id.
     *
     * @return {Number} Id of currently selected job.
     */

    var initialTabId;

    /**
     * Converts html text into set of script elements
     *
     * @return {jQuery<HTMLScriptElement>} The jQuery array of script tags.
     */
    var getScriptTagsFromText = function (text) {
        var elements = $.parseHTML(text, document, true);
        var $scriptElements = $(elements).filter('script');

        return $scriptElements;
    };


    /**
     * Loads scripts asynchronously with respect to ordering.  
     *
     * @param {jQuery<HTMLScriptElement>} $scriptElements List of scripts.
     * @return {Promise} Empty.
     */
    var loadScriptsFromListAsync = function ($scriptElements) {
        var chain = $LAB.sandbox();
        var deferred = $.Deferred();

        $scriptElements.each(function () {
            var $scriptElement = $(this);
            var scriptUrl = $scriptElement.attr('src');
            var scriptContent = $scriptElement.text();

            if (scriptUrl) {
                chain = chain.script(scriptUrl).wait();
            }
            else {
                var inlineScript = new Function(scriptContent);

                chain.wait(inlineScript);
            }
        });

        chain.wait(function () {
            deferred.resolve();
        });


        return deferred.promise();
    };


    /**
     * Retrives list of Online Application scripts.
     *
     * @return {Promise} The jQuery array of script tags. 
     */
    var getListOfOnlineApplicationScriptsAsync = function () {
        var onlineApplicationScriptsUrl = getOnlineApplicationScriptsUrl();

        var promise = gJobs.ajax
            .ajaxGet(onlineApplicationScriptsUrl)
            .then(function (text) {
                return getScriptTagsFromText(text);
            });

        return promise;
    };


    /**
     * Initializes Online Application.
     */
    var initOnlineApplication = function (isOnlineAppInitAllowed) {

        //In some cases, for example when user closes the online app flyout in the middle of loading process, we should avoid initializing after the data is loaded.
        if (typeof(isOnlineAppInitAllowed) === 'function' && !isOnlineAppInitAllowed()) {
            return;
        }

        //var $apply = $('.onlineapp-wrapper');
        var $apply = $('#online-application-block');

        $apply.data('onlineApplicationLoaded', true);

        if ($apply.length !== 0) {
            var viewModel = OnlineApp.ViewModels.applicationViewModel;
            var element = $apply.get(0);

            //ko.cleanNode(element);
            ko.applyBindings(viewModel, element);
        }

        var currentJobId = gJobs.jobsDetails.getCurrentJobId();

        OnlineApp.ViewModels.applicationViewModel.jobId(currentJobId);
        if (initialTabId) {
            OnlineApp.ViewModels.applicationViewModel.initialTabId(initialTabId);
        }
    };

    namespace('gJobs').jobsDetails = {

        /*
            TODO: 
                This method clearly needs to be rewritten. As far as I can tell it was written for DEMO purposes
                and somehow managed to survive till UAC.

                Curently I see: 
                    few violations of styling guidelines, 
                    text constant abuse, 
                    code dublication, 
                    SRP violations,
                    redundant jQuery selectors.
        */
        loadOnlineApplication: function (isOnlineAppInitAllowed) {
            if (gJobs.searchPage.apply) {
                if ($('#apply').data('onlineApplicationLoaded'))
                    return;
            }

            var $onlineApplicationLink = $('#online-application-link');


            if ($onlineApplicationLink.length) {

                getListOfOnlineApplicationScriptsAsync()
                    .then(loadScriptsFromListAsync)
                    .then(function () {
                        initOnlineApplication(isOnlineAppInitAllowed);
                    });
            }
        },
        getCurrentJobId: function () {
            var jobAttribute = $('#online-application-link').attr('job');
            var jobId = parseInt(jobAttribute);
    
            return jobId;
        }
    };

    updateLinksWithIncreaseClickCountFunc($('#details-info').find('a'));

    //
    // Initializer
    //
    $(function() {
        $($detailsContainer)
            .find('#apply-button')
            .one('show', function () {
                gJobs.jobsDetails.loadOnlineApplication();
            })
            .on('click', function () {
                displayStickyHeader(true);
                increaseClickCount(true, getJobIdFromUri());
            });

        if (gJobs && gJobs.router && History) {
            var initialState = History.getState();
            if (!!initialState.url.match(/\/apply(\/|#[a-z,-]+|\?|\?[\w,\-,\.,\&,\=,\%]+)?$/)
                && gJobs.searchPage
                && gJobs.searchPage.setTab) {

                gJobs.searchPage.setTab(1);
                var hash = History.getHash();
                if (hash) {
                    initialTabId = hash;
                    gJobs.router.checkRoutes(initialState);
                }
            }
        }
    });

    function updateLinksWithIncreaseClickCountFunc(linksFromDescription) {
        var jobId = getJobIdFromUri();
        if (jobId) {

            for (var i = 0; i < linksFromDescription.length; i++) {
                linksFromDescription[i].setAttribute('onmousedown', 'increaseClickCount(false, "' + jobId + '")')
            }
        }
    }

    function getJobIdFromUri() {
        var jobAttr = $('#job-details-button').attr('data-job-url');
        return jobAttr ? jobAttr.split('/')[2] : null;
    }

    $(document).keydown(function(e) {
        if (e.keyCode === $.ui.keyCode.ESCAPE) {
            if ($(e.target).hasClass('job-details-location-icon')
                || $(e.target).hasClass('job-details-salary-icon')) {
                $(e.target).popover('hide');
            }
        }
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function flyoutTabService() {
        var self = this;
        var currentContainer;

        self.restrictTabbing = function ($container) {
            if (!$container || $container.length === 0) {
                return null;
            }
            currentContainer = $container;
            $(document).on('keydown', trapTabInFlyout);
            return function () {
                $(document).off('keydown', trapTabInFlyout);
            };
        };

        function trapTabInFlyout(e) {
            var link = window.location.href;
            var isSchoolJobs = link.toLowerCase().indexOf("schooljobs") !== -1 && link.toLowerCase().indexOf("careers") === -1 ? true : false;

            var objFirstElement = $(':tabbable', currentContainer).first();
            var $headerElementsRespectingStickyHeader = window.enableStickyHeader ? $('#header :tabbable') : isSchoolJobs ? $('#header .sjobs-header-container :tabbable'): $('#header .header-container :tabbable');
            var $headerElements = window.revampedDesign ? $headerElementsRespectingStickyHeader : $('.navbar-inner :tabbable');
            var objLastElementOnNavBar = $headerElements.last();

            if (objFirstElement.is(":focus")) {
                if ($.ui.keyCode.TAB == e.keyCode && e.shiftKey) {
                    resetTabFocus(e, objLastElementOnNavBar);
                }
            }
        };

        function resetTabFocus(e, objToFocus) {
            if (e.preventDefault)
                e.preventDefault();
            else
                e.returnValue = false;
            objToFocus.focus();
        }
    };

    namespace('gJobs').flyoutTabService = new flyoutTabService();

})(window);
;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').InitIncompleteAppView = initIncompleteAppView;

    // nextJobCallback, prevJobCallback, checkJobPositionCallback
    function initIncompleteAppView(settings) {

        var FLYOUT_EXPANDED_TEXT = 'Flyout was expanded';

        var incompleteAppFlyout = new gJobs.Flyout('.incomplete-app-view-page');
        incompleteAppFlyout.create();

        var incompleteAppView = incompleteAppFlyout.getView();

        var $jobDetailsContainer = incompleteAppView.find('.job-details-view-container');
        var applicationContainer = incompleteAppView.find('.job-apply-container');
        var openedNotification = $('.opened-notification');
        var loadedNotification = $('.loaded-notification');
        var commonNotification = $('.common-notification');
        var additionalContentContainer = incompleteAppView.find('.additional-content-container');
        var tabsContainer = incompleteAppView.find('.flyout-header-tabs');
        var tabs = incompleteAppView.find('.flyout-header-tabs a:visible');
        var applyButton = incompleteAppView.find('#applyButton');
        var $externalApplyButtonContainer = incompleteAppView.find('#external-apply');
        var jobDetailsButton = incompleteAppView.find('#jobDetailsButton');
        var infoViewAdditionalContent = additionalContentContainer
            .find('div[data-content-bind="info-view"]');
        var autosaveMessage = $('.autosave');
        var jobInfoUrl = '/jobInfo/jobDetails/';
        var appUrl = '/jobInfo/apply/';
        var jobDetailsUrl = undefined;
        var jobTitle = undefined;
        var jobPositionOnPage = undefined;
        var activeJobId;
        var areShareButtonsInitialized = false;
        var layoutHelper = OnlineApp.Helpers.layoutHelper;
        var stickyHeader = '#sticky-header';

        var arrEventHolder = [];

        var incompleteAppLinksContainer = $('#job-list-container');

        var showStickyHeaderEvents = Events.CommonEventsNames.CloseFlyout +
            ' ' + Events.CommonEventsNames.ShowStickyHeader;

        function addCommonNotification(text) {
            commonNotification.text(' ').text(text);
        }

        $(document)
            .on(Events.CommonEventsNames.ShowOnlineApp, function () {
                gJobs.router.navigate(jobDetailsUrl + '/apply', null, null, null, {
                    jobTitle: jobTitle
                }, true);
            })
            .on(Events.CommonEventsNames.FlyoutClosing, function () {
                gJobs.searchPage.searchResults.setActiveItem();
                gJobs.screenReadersService.clearNotification(loadedNotification);
                gJobs.screenReadersService.clearNotification(openedNotification);
            })
            .on(showStickyHeaderEvents, function () {
                handleDisplayOfApplicationProcessWithStickyHeader(false);
            })
            .on(Events.CommonEventsNames.HideStickyHeader, function () {
                handleDisplayOfApplicationProcessWithStickyHeader(true);
            });

        // For switching between jobs.
        var nextButton = incompleteAppView.find('button.navigate-down');
        var prevButton = incompleteAppView.find('button.navigate-up');

        var switchJobsButtonsExist = (nextButton.length !== 0) && (prevButton.length !== 0);

        incompleteAppView
            .on('click', '#jobDetailsButton', function () {

                if (jobDetailsUrl != undefined) {
                    gJobs.router.navigate(jobDetailsUrl, null, null, null, {
                        jobTitle: jobTitle
                    }, true);
                }
            })
            .on('click', '#applyButton', function () {
                handleDisplayOfApplicationProcessWithStickyHeader(true);

                increaseClickCount(true);

                OnlineApp.Services.analyticsService.trackEvent('Apply Link Clicked');
                $(document).trigger(OnlineApp.Events.CommonEventsNames.ApplyTabOpened);

                if (jobDetailsUrl != undefined) {
                    var applicationUrl = jobDetailsUrl + '/apply';
                    gJobs.router.navigate(applicationUrl, null, null, null, {
                        jobTitle: jobTitle
                    }, true);
                }
                OnlineApp.Services.authenticationService.isLoggedIn()
                    .done(function (isLoggedIn) {
                        $("#skip-to-content-button").show();
                        $("#skip-to-content-button").focus();
                        if (isLoggedIn) {
                            OnlineApp.Services.authenticationService.getUserData()
                                .done(function (getUserData) {
                                    if (getUserData) {
                                        var baseUrl = window.location.origin;
                                        if (!getUserData.email) {
                                            window.location.href = baseUrl + "/Applications/AccountSettings#contact";
                                        }
                                    }
                                });
                        }

                    });



            })
            .on('show', '#jobDetailsButton', function (e) {
                autosaveMessage.hide();
            })
            .on('show', '#applyButton', function (e) {
                autosaveMessage.hide();
            });

        // Add listener to 'shown' event for switching between content.
        incompleteAppView.on('shown', '.flyout-header-tabs', switchAdditionalContent);
        if (switchJobsButtonsExist) {
            incompleteAppView.on('shown', '.flyout-header-tabs', switchSwitchButtons);
        }

        window.increaseClickCount = function (isApplyClick, jobId) {
            var splittedJobId = jobId && jobId.split('-') || activeJobId.split('-');
            if (splittedJobId[1] === '1') {
                var link = window.jobClickCounterUrl.format(splittedJobId[0], isApplyClick);
                $.ajax({
                    type: 'GET',
                    url: '/jobInfo/IncreaseApplyClickCount/' + splittedJobId[0] + '/' + isApplyClick,
                    async: true
                });
            }
        };

        window.displayStickyHeader = function (isApplicationProcessStarted) {
            handleDisplayOfApplicationProcessWithStickyHeader(isApplicationProcessStarted)
        }

        window.increaseHitsCount = function (jobId) {
            var splittedJobId = jobId && jobId.split('-');
            if (splittedJobId[1] === '1') {
                $.ajax({
                    type: 'GET',
                    url: '/jobInfo/IncreaseHitsJobCount/' + splittedJobId[0],
                    async: true
                });
            }
        };

        function initShareButtons(jobRelativePath, jobTitle, location) {
            var jobUrl = window.location.protocol
                + '//'
                + window.location.host
                + removeApplyFromUrl(jobRelativePath);

            if (jobTitle && jobTitle == jobTitle.toUpperCase()) {
                //If job title is set to ALL CAPS, need to convert it to Title Case
                jobTitle = window.utils.toTitleCase(jobTitle);
            }

            var $addthisToolbox = infoViewAdditionalContent.find('.share-button-group');
            if ($addthisToolbox.length) {
                gJobs.common.social.init($addthisToolbox, jobTitle, jobUrl, location);
            }

            infoViewAdditionalContent
                .on('click', '.share-button', function (e) {
                    infoViewAdditionalContent.find('.share-button-group').toggle(400, function () {
                        if (!window.enableShareThis) {
                            var linkedInButton = $(this).children('a')[0];
                            $(linkedInButton).focus();
                        } else {
                            $(this).children('button')[0].focus();
                        }
                    });
                    OnlineApp.Helpers.layoutHelper.tabbing.updateIndices(incompleteAppFlyout);
                    e.preventDefault();
                });
        }

        if (nextButton.lenght != 0) {
            nextButton.removeClass('hide');

            if (settings && settings.nextJobCallback) {
                nextButton.on('click', function () {
                    settings.nextJobCallback();
                });
            }
        }
        if (prevButton.lenght != 0) {
            prevButton.removeClass('hide');

            if (settings && settings.prevJobCallback) {
                prevButton.on('click', function () {
                    settings.prevJobCallback();
                });
            }
        }

        gJobs.accessibilityHtmlTransformer.makeElementContentAccessible($('.job-details-content'));

        //In backfilled search results, all links have target=_blank, and they should not open the flyout.
        incompleteAppLinksContainer.on('click', '.job-details-link[target!="_blank"]', function (e) {
            var link = $(this);

            var jobUrl = link.attr('href');
            var title = link.text();
            jobTitle = title;

            infoViewAdditionalContent.off('click').find('.share-button-group').hide();

            var $jobLocation = link.parent().siblings('.job-location');
            if ($jobLocation.length) {
                //On Search Page, it is possible to get the Location from the link container
                var location = $jobLocation.text();
                initShareButtons(jobUrl, jobTitle, location);
                areShareButtonsInitialized = true;
            } else {
                //For pages like Applications Page it's not possible,
                //so we postpone initialization of the share buttons until the Job Details are loaded
                areShareButtonsInitialized = false;
            }

            incompleteAppFlyout.setTitle(title);
            gJobs.searchPage.details.originator = History.getLastStoredState().url;
            var pageType = namespace('gJobs').pageInfoService.getCurrentPageType().type;
            var newQuery = window.location.search ?
                window.location.search + '&pagetype=' + pageType :
                '?pagetype=' + pageType;

            gJobs.router.navigate(jobUrl + newQuery, null, null, null, {
                jobTitle: jobTitle
            });

            attachOnTabChangeEvent();

            e.preventDefault();
        });

        function handleDisplayOfApplicationProcessWithStickyHeader(isApplicationProcessStarted) {
            if (window.enableStickyHeader) {
                OnlineApp.Services.authenticationService.isLoggedIn()
                    .done(function (isLoggedIn) {
                        if (isLoggedIn) {
                            var stickyHeaderHeight = $(stickyHeader).outerHeight();

                            var $currentFlyout = $('#content .flyout-window.incomplete-app-view-page');
                            var currentFlyoutTopStyling = parseInt($currentFlyout.css('top'));

                            var $maximizedRelativeBlock = $('.position-relative-maximized');
                            var maximizedRelativeBlockHeightStyling = $maximizedRelativeBlock.height();

                            if (isApplicationProcessStarted && $(stickyHeader).is(':visible')) {
                                currentFlyoutTopStyling -= stickyHeaderHeight;
                                maximizedRelativeBlockHeightStyling += stickyHeaderHeight;
                                $(stickyHeader).hide();
                            } else if (!isApplicationProcessStarted && !$(stickyHeader).is(':visible')
                                && !$currentFlyout.hasClass('active')) {
                                currentFlyoutTopStyling += stickyHeaderHeight;
                                maximizedRelativeBlockHeightStyling -= stickyHeaderHeight;
                                $(stickyHeader).show();
                            }

                            $currentFlyout.css('top', currentFlyoutTopStyling + 'px');
                            $maximizedRelativeBlock.height(maximizedRelativeBlockHeightStyling);
                        }
                    });
            }
        }

        function handleFocusOnOpen() {
            arrEventHolder[0] = gJobs.focusService.restrictFocus(incompleteAppView, function () {
                layoutHelper.tabbing.updateIndices();
            });
            arrEventHolder[1] = gJobs.flyoutTabService.restrictTabbing(incompleteAppView);

            gJobs.focusService.enableFocusForBrowserControls();
        }

        function detachEventsAfterClosing() {
            $.each(arrEventHolder, function (key, value) {
                if (arrEventHolder[key]) {
                    arrEventHolder[key]();
                    arrEventHolder[key] = undefined;
                }
            });
        }

        function attachOnTabChangeEvent() {
            if (gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.GJobs) {
                $(document).on('shown', 'a[data-toggle="tab"]', function () {
                    OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();
                });
            }
        }

        // Function for updating flyout with new data.
        // tabIndex - opening tab.
        function updateFlyout(jobId, title, jobUrl, tabIndex, jobIsFeatured) {

            autosaveMessage.hide();

            if (switchJobsButtonsExist && settings && settings.checkJobPositionCallback) {
                jobPositionOnPage = settings.checkJobPositionCallback(jobId);
                setSwitchVisible();
            }

            activeJobId = jobId;
            jobDetailsUrl = removeApplyFromUrl(jobUrl);
            jobTitle = title;
            incompleteAppFlyout.setTitle(title);

            if (typeof tabIndex === 'number') {
                // Apply tab index in incomplete applications section.
                if (tabIndex === 1) {
                    handleDisplayOfApplicationProcessWithStickyHeader(true);
                }

                // This function is used to set active tab on the flyout before it is shown.
                activateTabByIndex(tabIndex);
            } else {
                activateDefaultTab(tabs);
            }

            incompleteAppFlyout.open();
            gJobs.screenReadersService.setNotification(openedNotification, jobTitle, 'is loading', true, true);

            $(document).one(Events.CommonEventsNames.FlyoutClosing, detachEventsAfterClosing);

            document.title = title + ' | Job Details tab | Government Jobs';

            load(jobId, tabIndex, jobIsFeatured || false);
        }

        function removeApplyFromUrl(url) {

            var index = url.indexOf('/apply');

            if (index > 0) {
                return url.substring(0, index);
            }

            return url;
        }

        function setSwitchVisible() {
            if (switchJobsButtonsExist) {
                if (!jobPositionOnPage.isLast) {
                    nextButton.removeClass('hide');
                } else {
                    nextButton.addClass('hide');
                }
                if (!jobPositionOnPage.isFirst) {
                    prevButton.removeClass('hide');
                } else {
                    prevButton.addClass('hide');
                }
            }
        }

        function setSwitchNotVisible() {
            if (switchJobsButtonsExist) {
                nextButton.addClass('hide');
                prevButton.addClass('hide');
            }
        }

        function activateDefaultTab(tabs) {

            tabs.each(function () {

                var tab = $(this);
                if (isTabActiveByDefault(tab)) {
                    tab.tab('show');
                }
            });
        }

        function activateTabByIndex(tabIndex) {
            var tabs = incompleteAppView.find('.flyout-header-tabs a');
            $(tabs[tabIndex]).tab('show');
        }

        function isTabActive(tab) {
            var tabContainer = tab.parent();
            return tabContainer.hasClass('active');
        }

        function isTabActiveByDefault(tab) {

            var isActiveTab = tab.data('active-by-default').toLowerCase();

            return isActiveTab === 'true';
        }

        function switchSwitchButtons(e) {
            var contentHref = $(e.target).attr('href');
            if (contentHref == '#info-view') {
                setSwitchVisible();
            } else {
                setSwitchNotVisible();
            }
        }

        function switchAdditionalContent(e) {

            var contentHref = $(e.target).attr('href');
            if (contentHref) {

                contentHref = contentHref.substr(1);

                var additionalContent = additionalContentContainer
                    .find('div[data-content-bind="' + contentHref + '"]');
                additionalContent.removeClass('hide');
            }

            var prevContentHref = $(e.relatedTarget).attr('href');
            if (prevContentHref) {

                prevContentHref = prevContentHref.substr(1);

                var prevAdditionalContent = additionalContentContainer
                    .find('div[data-content-bind="' + prevContentHref + '"]');
                prevAdditionalContent.addClass('hide');
            }
        }

        // Load all data.
        function load(jobId, tabIndex, jobIsFeatured) {
            applyButton.show();
            applyButton.parent().show();
            $externalApplyButtonContainer.hide();
            var jobInfo = {};
            loadJobInfo(jobId, jobIsFeatured || false, jobInfo);

            if (jobInfo.topUSAJobUrl) {
                applyButton.parent().hide();
                createTopUSAJobApplyLink(jobInfo.topUSAJobUrl);
            } else {
                loadApplication(jobId, tabIndex === 1);
            }
        }

        var defaultJobInfoContent = undefined;
        function loadJobInfo(jobId, jobIsFeatured, jobInfo) {

            if (!defaultJobInfoContent) {
                defaultJobInfoContent = $jobDetailsContainer.html();
            } else {
                $jobDetailsContainer.html(defaultJobInfoContent);
            }

            if (!$jobDetailsContainer.length) {
                return;
            }

            var $dummy = $('<div>');
            var url = jobInfoUrl + jobId + '?isFeatured=' + (jobIsFeatured || false) + '&isSubmittedApplicationPage=false';
            $.ajax({
                type: 'GET',
                url: url,
                async: false
            })
                .done(function (response) {
                    $dummy.html(response);

                    updateLinksWithIncreaseClickCountFunc($dummy.find('#details-info').find('a'));

                    $jobDetailsContainer.html($dummy.html());

                    var titleElement = $jobDetailsContainer.find('#pretty-job-title');
                    var jobSource = $dummy
                        .find('#jobDetailsTitle')
                        .data('jobsource');

                    if (titleElement && titleElement.length > 0)
                        incompleteAppFlyout.setTitle(titleElement.html());

                    var descriptionElement = $jobDetailsContainer.find('.entity-details-buttons');
                    var isDescriptionTabvisible = false;
                    if (descriptionElement && descriptionElement.length > 0) {
                        isDescriptionTabvisible = true;
                    }

                    if (isTabActive(applyButton)) {
                        OnlineApp.Services.authenticationService.isLoggedIn().done(function (isLoggedIn) {
                            var applyNotification = applyButton.attr('data-selected-notification');
                            if (!isLoggedIn) {
                                applyNotification += ' Signin form is opened';
                            }

                        });
                    } else {
                        gJobs.screenReadersService.setNotification(
                            loadedNotification,
                            jobTitle,
                            'flyout is opened, job details tab has been activated' + (jobSource === 'TopUsa' || !isDescriptionTabvisible ? '' : ' and description tab is selected' + '  ' + getWarningText()),
                            true);

                        
                    }
                    $("#jobDetailsButton").attr("role", "");
                    //initialize popovers over the salary and location flieds
                    gJobs.nonFlickeringPopover(incompleteAppView.find('[data-toggle="popover"]'), 'job-details-popover');

                    if (areShareButtonsInitialized !== true) {
                        var location = $jobDetailsContainer.find('.job-details-summary .job-location').text();
                        initShareButtons(jobDetailsUrl, jobTitle, location);
                        areShareButtonsInitialized = true;
                    }

                    var printingUrl = $dummy
                        .find('#jobDetailsTitle')
                        .data('printingurl');

                    if (jobSource === 'TopUsa') {
                        jobInfo.topUSAJobUrl = $dummy
                            .find('#jobDetailsTitle')
                            .data('url');
                    }

                    // compose url for printing
                    additionalContentContainer
                        .find('div[data-content-bind="info-view"]')
                        .find('a.print-button')
                        .attr('href', printingUrl);

                    if (isTabActiveByDefault(jobDetailsButton)) {
                        setSwitchVisible();
                    }

                    gJobs.accessibilityHtmlTransformer.makeElementContentAccessible($('.job-details-content'));

                    $dummy.remove();

                    increaseHitsCount(jobId);
                })
                .fail(function () {
                    $jobDetailsContainer.html('<h1>Job details cannot be retrieved.</h1>');
                });
        }
        function getWarningText() {
            if ($("#closingInfo") && $("#closingInfo").length > 0) {
               return $("#closingInfo").text();
            }
            return '';
        }

        function loadApplication(jobId, setActive) {
            if (applicationContainer[0] != undefined || tabsContainer[0] !== undefined) {
                var $dummy = $('<div>');
                if (applicationContainer[0] != undefined || (tabsContainer[0] !== undefined)) {
                    $dummy.load(appUrl + jobId, function (response, status, xhr) {
                        if (status != 'success') {
                            applyButton.parent().hide();
                            applyButton.hide();
                            applicationContainer.html('<h1>Cannot apply.</h1>');
                        } else {
                            if ($dummy.html()) {
                                if ($dummy.find('.job-details-grid').length || $dummy.find('.how-to-apply-container').length) {
                                    applyButton.parent().show();
                                    applyButton.show();
                                    applicationContainer.html($dummy.html());

                                    applyButton.off();

                                    if (isTabActive(applyButton)) {
                                        document.title = document.title.replace('Job Details tab', 'Apply tab');

                                        loadOnlineApp();
                                    } else {
                                        // Use '.on' instead of '.one' and manual disabling event
                                        // to support refreshing on JobDetails tab and closing flyout scenario.
                                        applyButton.on('show', loadOnlineApp);
                                        $(document).one(Events.CommonEventsNames.FlyoutClosing, function () {
                                            applyButton.off('show', loadOnlineApp);
                                        });
                                    }

                                    if (setActive) {
                                        applyButton.tab('show');
                                    }
                                } else {
                                    if ($externalApplyButtonContainer[0] === undefined) {
                                        $externalApplyButtonContainer = $('<li id="external-apply">');
                                        tabsContainer.append($externalApplyButtonContainer);
                                    }
                                    $externalApplyButtonContainer.show();
                                    $externalApplyButtonContainer.html($dummy.html());
                                }
                            } else {
                                jobDetailsButton.tab('show');
                                applyButton.parent().hide();
                                applyButton.hide();
                            }
                        }
                        $dummy.remove();
                    });
                } else {
                    applyButton.parent().hide();
                    applyButton.hide();
                }
            } else {
                applyButton.parent().hide();
                applyButton.hide();
            }
        }

        function createTopUSAJobApplyLink(topUSAJobUrl) {
            if (tabsContainer[0] !== undefined) {
                if ($externalApplyButtonContainer[0] === undefined) {
                    $externalApplyButtonContainer = $('<li id="external-apply">');
                    $externalApplyButtonContainer.append(
                        $('<a>').text('Apply')
                    );
                    $externalApplyButtonContainer.find('a').on('click', function () {
                        gJobs.common.analytics.trackEvent(
                            gJobs.common.analytics.categories.jobSearch,
                            "TopUsaJob Apply Clicks"
                        );
                    })
                    tabsContainer.append($externalApplyButtonContainer);
                }
                var $applyLinkElement = $externalApplyButtonContainer.find('a');
                $applyLinkElement.attr('href', topUSAJobUrl);
                $applyLinkElement.attr('target', '_blank');
                $applyLinkElement.attr('aria-label', 'Apply Link. Top USA job will open in a new tab.');

                $externalApplyButtonContainer.show();
            }
        }

        function loadOnlineApp() {
            applyButton.off('show', loadOnlineApp);
            setSwitchNotVisible();
            incompleteAppFlyout.maximize();
            gJobs.jobsDetails.loadOnlineApplication(function () {
                return incompleteAppFlyout.isActive();
            });
            addCommonNotification(FLYOUT_EXPANDED_TEXT);
        }


        function updateLinksWithIncreaseClickCountFunc(linksFromDescription) {
            for (var i = 0; i < linksFromDescription.length; i++) {
                linksFromDescription[i].setAttribute('onmousedown', 'increaseClickCount(false)')
            }
        }

        if (!String.prototype.format) {
            String.prototype.format = function () {
                var args = arguments;
                return this.replace(/{(\d+)}/g, function (match, number) {
                    return typeof args[number] != 'undefined'
                        ? args[number]
                        : match
                        ;
                });
            };
        }

        return {
            load: function (jobId, jobTitle, jobUrl, tabIndex, jobIsFeatured) {
                updateFlyout(jobId, jobTitle, jobUrl, tabIndex, jobIsFeatured);
                handleFocusOnOpen();
            },

            showJobDetails: function () {
                jobDetailsButton.tab('show');
            },

            showOnlineApp: function () {
                applyButton.tab('show');
            },

            getActiveJobId: function () {
                return activeJobId;
            },

            isActive: function () {
                return incompleteAppFlyout.isActive();
            },

            isApplyTabActive: function () {
                var result = isTabActive(applyButton);
                return result;
            }
        };
    }
})(window);
;
(function (window, undefined) {
    'use strict';

    var $body = $('body'),
        $detailsPage = $('.job-details-inline-page'),
        $detailsPageContent = $detailsPage.find('#job-details-flyout'),
        $detailsPageOverlay = $('#' + $detailsPage.data('overlay')),
        $facetContainer = $('#facet-container'),
        $facetAndSavedSearchContainer = $('#facet-and-saved-search-container'),
        $jobListContainer = $('#job-list-container'),
        $mainSearchContainer = $('#main-search-criteria'),
        $mainSearchContainerRevamp = $('#main-search-criteria-revamp'),
        $linksCollection = $('.links-collection'),
        $searchResultsInfoContainers = $('.search-results-info-container'),
        $categoryInfoContainer = $('#category-info-container'),
        $jobAlertContainer = $('#job-alert-out-container'),
        $navigateDownButton = $detailsPage.find('.navigate-down'),
        $navigateUpButton = $detailsPage.find('.navigate-up'),
        $printableContent = $('#printable-content'),
        $contentContainer = $('#content-container'),
        $sidebarContainer = $('#sidebar-container'),
        $adContainers = $('.ads-container'),
        $adContainerIframes = $('.ads-container').find('iframe'),
        $keywordSearch = $('#keyword-search-input'),
        $locationSearch = $('#location-search-input'),
        $adsContinerBottom = $("#adcontainer-bottom"),
        $adBanner = $('#adscontainer-banner-ad'),
        shareThisButtonGroupInlineClass = 'sharethis-button-group-inline';

    var maxSearchResultsInfoDescriptionHeight = 60;

    function tryRaiseEvent(tryEventName, eventName, eventCallback) {
        var e = jQuery.Event(tryEventName);

        e.canRaiseEvent = true;
        e.callbackEventName = eventName;

        $(document).trigger(e);

        if (e.canRaiseEvent && eventCallback) {
            eventCallback();
        }
    }

    var initPaginationItem = function(options) {
        $jobListContainer.find(options.selector).addClass(options.className).find('a').attr('aria-label', options.ariaLabel);
    }

    var initPaginationPanel = function () {
        initPaginationItem({ selector: '.PagedList-skipToFirst', className: 'first-page-link', ariaLabel: 'Skip to the first page' });
        initPaginationItem({ selector: '.PagedList-skipToPrevious', className: 'previous-page-link', ariaLabel: 'Skip to the previous page' });
        initPaginationItem({ selector: '.PagedList-skipToNext', className: 'next-page-link', ariaLabel: 'Skip to the next page' });
        initPaginationItem({ selector: '.PagedList-skipToLast', className: 'last-page-link', ariaLabel: 'Skip to the last page' });
    };

    var initCanvassFlyout = function () {
        gJobs.searchPage.canvassFormFlyout = new gJobs.Flyout('.canvass-flyout');
        gJobs.searchPage.canvassFormFlyout.create();
    
        if (!gJobs.searchPage.canvassViewModel) {
            gJobs.searchPage.canvassViewModel = new OnlineApp.ViewModels.CanvassViewModel();
        }
    
        var $canvassContainer = $('#canvass-flyout-content');
    
        if ($canvassContainer.length > 0) {
            ko.applyBindings(gJobs.searchPage.canvassViewModel, $canvassContainer.get(0));
        }
    };

    var googleBannerPositionHandler = function () {
        var $sidebarAds = $('#adscontainer-banner');
        var $bottomAds = $('#adscontainer-bottom');
        var $html = $('html');

        if ($html.hasClass('device-phone') && $adBanner.parent().get(0) !== $bottomAds.get(0)) {
            $adBanner.appendTo($bottomAds);
        } else if (!$html.hasClass('device-phone') && $adBanner.parent().get(0) !== $sidebarAds.get(0)) {
            $adBanner.appendTo($sidebarAds);
        }
    };

    var restoreBottomAds = function () {
        $jobListContainer.find("#adcontainer-bottom").replaceWith($adsContinerBottom[0]);
        googleBannerPositionHandler();
    }

    namespace('gJobs').facetContainer = {
        init: function () {

            var cookieName = 'GJobs.SearchPage.ShowFullDescription';

            var initialState = $.cookie(cookieName);

            var onCallback = function () {
                $('.job-item .description').show();

                $.cookie(cookieName, 'on');
            };
            var offCallback = function () {
                $('.job-item .description').hide();

                $.cookie(cookieName, 'off');
            };

            var jobSortDropdown = $('#job-sort-dropdown');
            if (jobSortDropdown.length) {
                ko.applyBindingsToNode(jobSortDropdown.get(0));
            }

            $facetContainer.find('.make-switch').switchButton({
                initialState: initialState,
                onCallback: onCallback,
                offCallback: offCallback
            });

            //in mobile version, hide the facet container after filters are updated
            $('html.device-phone .show-filter-label').show();
            $('html.device-phone .hide-filter-label').hide();
            $('html.device-phone #facet-container').hide();

            $facetContainer.find('.facet-list a, .clearAllFilter, .sortOrderFilter')
                .off('click')
                .on('click', function (event) {
                    var $this = $(this);
                    var facetUrl = $this.attr('href');

                    if (facetUrl) {
                        gJobs.router.navigate(facetUrl);
                    }
                    event.preventDefault();
                    event.stopPropagation();
                    gJobs.skipToContentService.showOnNextTab();

                    var screenReadersMessage = null;

                    if ($this.hasClass('facet-link')) {
                        screenReadersMessage = $this.data('facet-display-value');

                        if ($this.hasClass('remove-selected-facet')) {
                            screenReadersMessage += ' filter is removed.';
                        } else {
                            screenReadersMessage += ' filter is applied.';
                        }
                    }
                    if ($this.hasClass('clearAllFilter')) {
                        screenReadersMessage = 'All filters are removed.';
                    }

                    if (screenReadersMessage) {
                        gJobs.screenReadersService.setAriaLiveNotification(screenReadersMessage);
                    }
                });

            $facetContainer.find('#job-sort-dropdown')
                .off('change')
                .on('change', function () {
                    gJobs.router.navigate($(this).val());
                    gJobs.skipToContentService.showOnNextTab();
                });

            $facetContainer.find('.show-more-facets')
                .off('click')
                .on('click', function (e) {
                    var fiddenFacetClass = 'hidden-facet';
                    var $this = $(this);
                    var parentId = $this.data('for');
                    var showMoreCount = Number($this.data('count'));
                    if (showMoreCount) {
                        var hiddenFacets = $('#' + parentId).find('.' + fiddenFacetClass);

                        if (hiddenFacets.length < showMoreCount) {
                            $this.hide();
                        }

                        hiddenFacets
                            .slice(0, showMoreCount)
                            .hide()
                            .removeClass(fiddenFacetClass, 1000)
                            .toggle('show');
                    }

                    e.preventDefault();
                });
        }
    };

    var maxMobileScreenWidth = 767;
    var onlineAppBlockDefaultMinHeight = 0;


    var jobHeaderDefaultClasses = '';
    var loadBackfillResultsIfGJobsResultsAreEmpty = function (url) {

        var backfillElement = $('#backfillSearchResults');
        if (backfillElement.length) {

            backfillElement.find('.resultsContainer').empty();
            backfillElement.addClass('loading');
            window.scrollTo(0, 0);
            
            var adsContainers = $('.ads-container').closest('.row-fluid');
            //hides ads containers and dividers connected with them before we know there are any jobs found on the external backfilling source
            adsContainers.toggleClass('hidden');

            //if url is passed to the method, it's a query for a certain page, otherwise plain backfilling
            var backfillUrl = url;
            if (!backfillUrl) {
                backfillUrl = '/jobs/backfill?' + $.param({
                    keyword: backfillElement.data('keyword'),
                    location: backfillElement.data('location'),
                    page: backfillElement.data('page')
                });
                gJobs.router.navigate(backfillUrl, false, true);
            }

            gJobs.ajax.ajaxGet(backfillUrl, '#job-list-overlay')
            .done(function (data) {
                
                backfillElement.removeClass('loading');
                backfillElement.find('.resultsContainer').html(data.view);
                
                initPaginationPanel();

                if (data && data.areJobsFound) {
                    //shows ads containers and dividers connected with them if there are any jobs found on the external backfilling source
                    adsContainers.toggleClass('hidden');
                    $facetAndSavedSearchContainer.hide();
                }
            });
        }
    };

    namespace('gJobs').searchPage = {
        isSearchPage: function () {
            return $("html.job-page").length === 0;
        },

        setTabStyle: function (tabLink) {
            var jobHeader = $('.job-header');

            if (!jobHeaderDefaultClasses) {
                jobHeaderDefaultClasses = jobHeader.attr('class');
            }

            var tabId = tabLink.attr('href').replace('#', '');

            jobHeader.attr('class', jobHeaderDefaultClasses);

            if (tabId) {
                jobHeader.addClass('tab-' + tabId);
            }
        },

        setTab: function (index) {
            var buttons = $(".job-header-tabs a");

            // For the flyout buttons.
            if (buttons.length == 0 || incompleteAppView.isActive()) {
                buttons = $('.incomplete-app-view-page')
                    .find('.flyout-header-tabs a');
            }

            var tabLink = buttons.eq(index);

            //gJobs.searchPage.setTabStyle(tabLink);

            tabLink.tab('show');
        },

        updateFlyoutSizes: function (selectedTabSelector) {
            var $flyoutTabs = $detailsPageContent.find('.job-details-tabs'),
                $selectedTab = $detailsPageContent.find(selectedTabSelector || '.job-details-container.active'),
                $jobHeader = $detailsPageContent.find('.job-header'),
                $onlineAppBlock = $selectedTab.find('#online-application-block');

            if ($(window).width() > maxMobileScreenWidth) {
                $flyoutTabs.css('top', $jobHeader.outerHeight(true));
            } else {
                /*check hidden dropdown heights to fix overlapping */
                $flyoutTabs.css('top', 0);
            }

            if ($onlineAppBlock.length == 0) return;

            if (!onlineAppBlockDefaultMinHeight) {
                onlineAppBlockDefaultMinHeight = $onlineAppBlock.css('min-height');
            }

            var $appContainer = $selectedTab.find('.onlineapp-app-container');
            var minHeight = $appContainer.length > 0 ? $appContainer.outerHeight(true) : 0;
            if ($(window).width() <= maxMobileScreenWidth) {
                $selectedTab.find('.dropdown-nav').each(function () {
                    var $this = $(this);

                    var dropdownHeight = $this.outerHeight(true) + $this.find('.dropdown-menu').outerHeight(true);

                    if (dropdownHeight > minHeight) {
                        minHeight = dropdownHeight;
                    }
                });
            }

            if (minHeight > 0) {
                $onlineAppBlock.css('min-height', minHeight);
            } else {
                $onlineAppBlock.css('min-height', onlineAppBlockDefaultMinHeight);
            }
        },

        updateFacetsContainerDisplaying: function () {
            if ($(document).width() > maxMobileScreenWidth) {
                $("#facet-container").css('display', 'block');
            } else {
                if (($(".show-filter-label").css('display') == 'block')) {
                    $("#facet-container").css('display', 'none');
                }
            }
        },

        trackPositionClick: function () {
            $('.job-item .job-details-link').click(function () {
                var position = $(this).parents('li').index() + 1;
                gJobs.common.analytics.trackJobSearchEvent('Position ' + position + ' clicked');
            });
        },

        trackJobSearchResultsClicks: function () {
            var urlParameters = url.get(location.search.slice(1), { array: true });
            if (!urlParameters.page || urlParameters.page === '1') {
                gJobs.searchPage.trackPositionClick();
            }
        },

        trackTopUsaJobClick: function() {
            $(".topusa-job-details-link").click(function (){
                gJobs.common.analytics.trackEvent(
                    gJobs.common.analytics.categories.jobSearch,
                    "TopUsaJob open clicks"
                );
            })
        },
        
        openCanvassFormFlyout: function (canvassFormId) {
            OnlineApp.Services.canvassFlyoutService.openCanvassFormFlyout(
                canvassFormId,
                gJobs.searchPage.canvassFormFlyout,
                gJobs.searchPage.canvassViewModel);
        },

        searchResultsInfo: (function () {
            return {
                //show info block with the highest priority
                //we assume that first located info block has highest priority
                //also we should filter for empty info blocks
                showHighestPriorityInfo: function () {
                    var infoBlocksCounter = 0;

                    $searchResultsInfoContainers.each(function (index, value) {
                        var $value = $(value),
                            emptyContainerRegexp = /^\s*$/;

                        if ((!emptyContainerRegexp.test($value.text())) && (infoBlocksCounter === 0)) {
                            var $newMetaDescription = $value.find('.meta-description').first(),
                                $currentMetaDescriptionTag = $('meta[name="description"]').first();

                            $value.css('display', 'block');

                            //update meta description for page
                            if ($newMetaDescription.length !== 0 && $currentMetaDescriptionTag.length !== 0) {
                                $currentMetaDescriptionTag.attr('content', $('.meta-description').first().text());
                            }

                            infoBlocksCounter = 1;
                        } else {
                            $value.css('display', 'none');
                        }
                    });
                },
                updateEventHandlers: function () {
                    $searchResultsInfoContainers.find('.full-description-expander a')
                        .off('click')
                        .on('click', function (e) {
                            e.preventDefault();
                            var $currentContainer = $(e.target).closest('.search-results-info-container');
                            $currentContainer.find('.description-text').toggleClass('collapsed');
                            var $readMoreButtonContainer = $currentContainer.find('.read-more-button-container');
                            var $hideDetailsButtonContainer = $currentContainer.find('.hide-details-button-container');
                            $readMoreButtonContainer.toggleClass("hide");
                            $hideDetailsButtonContainer.toggleClass("hide");
                            $readMoreButtonContainer.hasClass("hide") ? $hideDetailsButtonContainer.focus() : $readMoreButtonContainer.focus();
                        });
                },
                updateFullDescriptionExpander: function () {
                    $searchResultsInfoContainers.each(function (index, value) {
                        var $container = $(value);

                        var $fullDesctiptionExpander = $container.find('.full-description-expander');

                        var $descriptionText = $container.find('.description-text');
                        if ($descriptionText.length > 0) {
                            var descriptionTextScrollHeight = $descriptionText.get(0).scrollHeight;

                            if (descriptionTextScrollHeight === undefined) {
                                return;
                            }

                            if (descriptionTextScrollHeight <= maxSearchResultsInfoDescriptionHeight) {
                                $fullDesctiptionExpander.hide();
                            } else {
                                $fullDesctiptionExpander.show();
                            }
                        }
                    });
                }
            };
        })(),

        details: (function () {

            var setTab = function (index) {
                $detailsPageContent
                    .find('.entity-details-buttons a')
                    .eq(index)
                    .tab('show');
            },

            master = {
                setScrollable: function (scrollable) {
                    $body.toggleClass('inner-scrollbar', !scrollable);

                    // Adds padding right to handle contents to stay at its original place 
                    // in Windows and Firefox in Mac when hiding the scrollbar.
                    if (!scrollable) {
                        $body.css('padding-right', this.getScrollbarWidth());
                    } else {
                        $body.css('padding-right', 0);
                    }
                },
                getScrollbarWidth: function () {
                    var parent,
                        child,
                        width;

                    parent = $('<div style="width:50px; height:50px; overflow:auto"><div/></div>').appendTo('body');
                    child = parent.children();
                    width = child.innerWidth() - child.height(99).innerWidth();
                    parent.remove();

                    return width;
                }
            },

            page = {
                clear: function () {
                    $detailsPageContent.empty();
                },

                focus: function () {
                    $detailsPage.focus();
                },

                load: function (iterator) {
                    var $currentItem = $jobListContainer.find('.job-item.active'),
                        $newItem;

                    if ($currentItem.length !== 0) {
                        $newItem = $currentItem[iterator]();

                        var isJobItem = $newItem.hasClass('job-item');
                        if (!isJobItem) {
                            $newItem = $newItem[iterator]();
                        }
                    } else {
                        // Paging silently jumped

                        if (iterator === 'next') {
                            $newItem = $jobListContainer.find('.job-item').first();
                        } else if (iterator === 'prev') {
                            $newItem = $jobListContainer.find('.job-item').last();
                        }
                    }


                    if ($newItem.length === 0) {
                        if (gJobs.searchPage.searchResults.hasPage(iterator)) {
                            gJobs.searchPage.searchResults.loadPage(iterator, function (e) {
                                if (e.loaded) {
                                    page.load(iterator);
                                }
                            });

                            page.clear();
                        }

                        return;
                    }

                    page.clear();

                    var $anchor = $newItem.find('.job-details-link');
                    var route = $anchor.attr('href');
                    var jobTitle = $anchor.text();

                    gJobs.focusService.restoreFocus();

                    gJobs.router.navigate(route, null, null, null, {
                        jobTitle: jobTitle
                    }, true);

                    gJobs.focusService.replaceLastElement($anchor);
                },

                updateLayout: function () {
                    var
                        $activeItem = $jobListContainer.find('.job-item.active'),
                        downButtonEnabled =
                            ($activeItem.next().length > 0) ||
                            (gJobs.searchPage.searchResults.hasPage('next')),
                        upButtonEnabled =
                            ($activeItem.prev().length > 0) ||
                            (gJobs.searchPage.searchResults.hasPage('prev'));


                    $navigateUpButton.toggle(upButtonEnabled);
                    $navigateDownButton.toggle(downButtonEnabled);
                },

                initUI: function () {
                    gJobs.nonFlickeringPopover($('.job-details-container span[data-toggle="popover"]'), 'job-details-popover');
                    gJobs.nonFlickeringPopover($mainSearchContainer.find('[data-toggle="popover"]'), 'main-search-criteria-popover');
                    gJobs.nonFlickeringPopover($mainSearchContainerRevamp.find('[data-toggle="popover"]'), 'main-search-criteria-popover');
                    gJobs.nonFlickeringPopover($linksCollection.find('[data-toggle="popover"]'), 'job-details-popover');

                    $('.job-header-tabs').on('shown', function (e) {
                        size.apply(e.target);
                    });

                    $('.job-header-tabs a[href="#apply"]')
                        .on('click', function () {
                            OnlineApp.Services.analyticsService.trackEvent('Apply Link Clicked');
                            $(document).trigger(OnlineApp.Events.CommonEventsNames.ApplyTabOpened);
                        });

                    size.applyForCurrentTab();
                }
            },

            overlay = {
                setVisible: function (visible) {
                    /*if (visible) {
                        $detailsPageOverlay
                            .removeClass('inactive')
                            .addClass('active');
                    } else {
                        $detailsPageOverlay
                            .removeClass('active')
                            .addClass('inactive');
                    }*/
                }
            },


            size = {
                retainSize: false,

                sizerFunctions: {
                    fixed: function () {
                        animate.maximize(false);
                    },
                    maximized: function () {
                        animate.maximize(true);
                    }
                },


                applyForCurrentTab: function () {
                    var currentTab =
                        $('.job-header-tabs > li.active a');

                    this.apply(currentTab);
                },

                apply: function (tab) {
                    var tabId = $(tab).attr('href');
                    var $tab = $(tabId);

                    if (!this.retainSize) {
                        var flyoutSize = $tab.data('flyout-size');
                        var flyoutSizer = this.sizerFunctions[flyoutSize];

                        if (typeof flyoutSizer === 'function') {
                            flyoutSizer();
                        }
                    }

                    var retainSize = $tab.data('retain-size');
                    if (retainSize) {
                        this.retainSize = true;
                    }
                }
            },

            animate = {
                show: function () {
                    $detailsPage.removeClass('center');
                    $detailsPage.removeClass('inactive');
                    $detailsPage.addClass('active');
                },
                hide: function (callback) {
                    $detailsPage.addClass('inactive');
                    $detailsPage.removeClass('active');
                    $detailsPage.removeClass('center');

                    if (typeof callback === 'function') {
                        callback();
                    }
                },
                maximize: function (state) {
                    $detailsPage.toggleClass('maximized', state);
                }
            },

            job;


            return {

                showTab: function () {
                    $detailsPageContent.find('#job-details-button').tab('show');
                },

                // close flyout in any case
                close: function () {
                    if (gJobs.searchPage.details.originator) {
                        gJobs.router.navigate(gJobs.searchPage.details.originator, false);
                    }

                    gJobs.searchPage.details.hide();

                    // flyout is now eventually closing
                    $(document).trigger(Events.CommonEventsNames.FlyoutClosing);
                },

                // try to close flyout if nothing prevents it from closure
                tryClose: function () {
                    tryRaiseEvent(
                        Events.CommonEventsNames.TryCloseFlyout,
                        Events.CommonEventsNames.CloseFlyout,
                        gJobs.searchPage.details.close.bind(this)
                    );
                },

                hide: function () {
                    if (!this.isActive()) {
                        return;
                    }

                    gJobs.searchPage.searchResults.setActiveItem();

                    animate.hide(function () {
                        master.setScrollable(true);
                        overlay.setVisible(false);
                    });


                    gJobs.common.analytics.trackJobSearchEvent('Job Details Close', JSON.stringify(job));
                },

                loadJob: function (jobId, jobTitle, jobUrl, tabIndex, jobIsFeatured) {
                    incompleteAppView.load(jobId, jobTitle, jobUrl, tabIndex, jobIsFeatured || false);
                },
                isActive: function () {
                    return incompleteAppView.isActive();
                },
                viewExists: function () {
                    return ($('.flyout-window.incomplete-app-view-page').length > 0);
                },
                getActiveJobId: function () {
                    return incompleteAppView.getActiveJobId();
                },
                next: function () {
                    page.load('next');
                },
                tryNext: function () {
                    tryRaiseEvent(
                        Events.CommonEventsNames.TryCloseFlyout,
                        Events.CommonEventsNames.ShowNext,
                        gJobs.searchPage.details.next
                    );
                },

                previous: function () {
                    page.load('prev');
                },
                tryPrevious: function () {
                    tryRaiseEvent(
                        Events.CommonEventsNames.TryCloseFlyout,
                        Events.CommonEventsNames.ShowPrevious,
                        gJobs.searchPage.details.previous
                    );
                },

                getJobPositionOnPage: function () {
                    var
                        $activeItem = $jobListContainer.find('.job-item.active'),
                        isLast =
                        !(($activeItem.next().length > 0) ||
                            (gJobs.searchPage.searchResults.hasPage('next'))),
                        isFirst =
                        !(($activeItem.prev().length > 0) ||
                            (gJobs.searchPage.searchResults.hasPage('prev')));

                    return {
                        isFirst: isFirst,
                        isLast: isLast
                    };
                },

                social: {
                    toggle: function () {
                        $('.job-header-content:last').find('.share-button-group').toggle();
                    }
                },

                initUI: function () {
                    page.initUI();
                },

                jobHeaderButtons: {
                    buttons: [$navigateUpButton, $navigateDownButton],
                    show: function () {
                        $(this.buttons).each(function () {
                            var $btn = $(this);
                            if ($btn.hasClass('apply-hidden')) {
                                $btn.removeClass('apply-hidden');
                                $btn.show();
                            }
                        });
                    },
                    hide: function () {
                        $(this.buttons).each(function () {
                            var $btn = $(this);
                            if ($btn.is(':visible')) {
                                $btn.addClass('apply-hidden');
                                $btn.hide();
                            }
                        });
                    }
                },

                updatePrintableContent: function (html) {
                    var tempDiv = $("<div>").html(html);

                    // remove unnecessary elements
                    tempDiv
                        .find(".job-header .job-header-content,.hide,.job-details-agency-info,script,noscript,iframe,.tab-pane:not(.active)")
                        .remove();

                    var htmlToPrint = tempDiv.htmlClean().html();
                    //var htmlToPrint = "<div>AAAA</div>";
                    $printableContent.html(htmlToPrint);

                    // http://stackoverflow.com/questions/1397478/forcing-a-dom-refresh-in-internet-explorer-after-javascript-dom-manipulation#answer-1397505
                    // Mozilla (maybe IE as well) will cache/delay executing changes to the DOM which affect display, so that it can calculate all the changes at once instead of repeatedly after each and every statement.
                    // To force an update (to force an immediate, synchronous reflow or relayout), your javascript should read a property that's affected by the change, e.g. the location of someSpan and otherSpan.
                    // some dummy actions
                    var printableNode = document.getElementById($printableContent.attr("id"));
                    var tmp = printableNode.offsetTop + 'px';
                    return tmp;
                }
            };
        })(),

        apply: {
            showseTab: function () {
                gJobs.searchPage.setTab(1);
            }
        },

        filter: (function () {
            return {
                getFacetsAndJobPosts: function (url) {

                    var lastFocusedId = $(document.activeElement).attr('id');

                    $facetAndSavedSearchContainer.show();

                    gJobs.common.analytics.trackJobSearchEvent('Facets Changed');
                    gJobs.common.analytics.trackJobSearchEvent('Search');

                    return gJobs.ajax.ajaxGet(url, '#job-list-overlay').done(function (data) {
                        if (data) {
                            if (data.view1) {
                                $jobListContainer.html(data.view1);
                                gJobs.searchPage.searchResults.resultsReceived();
                                initPaginationPanel();
                                restoreBottomAds();
                            }
                            if (data.view2) {
                                $facetContainer.html($(data.view2).html());
                                gJobs.facetContainer.init();
                            }
                            if (data.view3 !== undefined) {
                                $categoryInfoContainer.html(data.view3);

                                if (data.jobAlertPopup !== undefined) 
                                    $jobAlertContainer.html(data.jobAlertPopup);

                                //update search results info containers
                                $searchResultsInfoContainers = $('.search-results-info-container');
                                gJobs.searchPage.searchResultsInfo.updateEventHandlers();
                                gJobs.searchPage.searchResultsInfo.updateFullDescriptionExpander();
                            }

                            //If no jobs match the criteria, then hide the google ads. Else, show them.
                            if (data.isResultEmpty)
                                $adContainers.addClass('hide');
                            else
                                $adContainers.removeClass('hide');


                            gJobs.searchPage.searchResultsInfo.showHighestPriorityInfo();

                            loadBackfillResultsIfGJobsResultsAreEmpty();

                            if (lastFocusedId) {
                                $('#' + lastFocusedId).focus();
                            }

                            if (data.pageTitle) {
                                document.title = data.pageTitle;
                            }
                        }
                    });
                }
            };
        })(),

        size: {
            apply: function (tab) {
                var width = $(tab).data('width') || 'none';
                $contentContainer.css('max-width', width);
            },

            applyForCurrentTab: function () {
                var $activeTab = $('.job-details-tabs > .tab-pane.active');
                this.apply($activeTab);
            }
        }
    };

    namespace('gJobs').searchPage.searchResults = (function () {

        var resultsReceived = function () {
            window.scrollTo(0, 0);

            gJobs.common.social.init();
        };


        var getPageList = function () {
            return $jobListContainer.find('.pager-container li');
        };


        return {
            getJobPosts: function (url) {
                gJobs.common.analytics.trackJobSearchEvent('Search');

                return gJobs.ajax.ajaxGet(url, '#job-list-overlay').done(function (data) {
                    $jobListContainer.html(data);
                    resultsReceived();

                    initPaginationPanel();
                    restoreBottomAds();

                    $('.share-button-group svg').attr('focusable', false);

                    gJobs.nonFlickeringPopover($jobListContainer.find('[data-toggle="popover"]'), 'job-details-popover');
                });
            },

            loadPage: function (iterator, callback) {
                var nextPageUrl = getPageList()
                    .filter('.active')
                        [iterator]()
                            .find('a')
                            .attr('href');

                var returnFunction = function () {
                    if (typeof callback === 'function') {
                        callback({
                            loaded: !!nextPageUrl
                        });
                    }
                };


                if (nextPageUrl) {
                    this.getJobPosts(nextPageUrl).done(returnFunction);
                    gJobs.common.analytics.trackJobSearchEvent('Search Page Changed');
                } else {
                    returnFunction();
                }
            },

            hasPage: function (iterator) {
                var $nextPage = getPageList()
                    .filter('.active')
                        [iterator]();

                return ($nextPage.length > 0);
            },


            resultsReceived: resultsReceived,

            toggleSocialWidget: function ($element) {
                var $socialWidget = $element.siblings('.addthis_toolbox');
                if ($socialWidget) {
                    if (window.enableShareThis) {
                        $socialWidget.toggleClass(shareThisButtonGroupInlineClass);
                    } else {
                        $socialWidget.toggle();
                    }
                }
            },

            setActiveItem: function (jobId) {
                $jobListContainer.find('.job-item.active').removeClass('active');
                $jobListContainer.find('.job-item[data-job-id=' + jobId + ']').addClass('active');
            },
            
            loadBackfillResultsIfGJobsResultsAreEmpty: loadBackfillResultsIfGJobsResultsAreEmpty
        };
    })();

    // Settings for incomplete app view.
    var incompleteAppViewSettings = {
        nextJobCallback: function () {
            gJobs.searchPage.details.tryNext();
        },

        prevJobCallback: function () {
            gJobs.searchPage.details.tryPrevious();
        },

        checkJobPositionCallback: function (jobId) {

            gJobs.searchPage.searchResults.setActiveItem(jobId);

            return gJobs.searchPage.details.getJobPositionOnPage();
        },
    };

    initCanvassFlyout();

    var incompleteAppView = new gJobs.InitIncompleteAppView(incompleteAppViewSettings);

    function setTabindexForBottomAds(tabindex) {
        var $bottomAds = $('#adscontainer-bottom');

        if ($bottomAds && $bottomAds.length) {
            $bottomAds.find('iframe').attr('tabindex', tabindex);
        }
    }

    //
    // Initializer
    //
    $(function () {

        if (gJobs.browserDetector.isIE()) {
            gJobs.pageTabNavigationService.enableScrollForElements($jobListContainer, '.job-details-link', '.job-item');
        }

        $(document)
            .on(Events.CommonEventsNames.ShowNext, null, gJobs.searchPage.details.next)
            .on(Events.CommonEventsNames.ShowPrevious, null, gJobs.searchPage.details.previous);

        $(document).on(OnlineApp.Events.CommonEventsNames.ApplyTabOpened, function () {
            gJobs.skipToContentService.showOnNextTab();
        });

        $jobListContainer
            .on('click', '.share-button', function () {
                gJobs.searchPage.searchResults.toggleSocialWidget($(this));
                if (!window.enableShareThis) {
                    $(this).next().children('a')[0].focus();
                } else {
                    $(this).next().children('button')[0].focus();
                }
            })
            .on('click', '.pagination a', function (e) {
                gJobs.router.navigate($(this).attr('href'));
                e.preventDefault();

                gJobs.common.analytics.trackJobSearchEvent('Page Changed');
            })
            .addClass('js');

        $detailsPageOverlay
            .click(function () {
                gJobs.searchPage.details.tryClose();
            });

        gJobs.nonFlickeringPopover($jobListContainer.find('[data-toggle="popover"]'), 'job-details-popover');

        $(document)
            .on('keyup', function (e) {
                if (gJobs.searchPage.details.isActive()) {
                    if (!incompleteAppView.isApplyTabActive()) {
                        if (e.keyCode === $.ui.keyCode.PAGE_UP) {
                            gJobs.searchPage.details.tryPrevious();
                        }
                        else if (e.keyCode === $.ui.keyCode.PAGE_DOWN) {
                            gJobs.searchPage.details.tryNext();
                        }
                    }
                }
                if (e.keyCode === $.ui.keyCode.ESCAPE) {
                    hideSearchPopovers();
                    return false;
                }
            })
            .on(Events.CommonEventsNames.ShowFlyout, function(event) {
                setTabindexForBottomAds('-1');
            })
            .on(Events.CommonEventsNames.FlyoutClosing, function(event) {
                setTabindexForBottomAds('0');
            });

        if (!gJobs.searchPage.details.viewExists()) {

            var jobHeaderContent = $('.job-header-content');
            var shareButtonGroup = jobHeaderContent.find('.share-button-group');

            jobHeaderContent.on('click', '.share-button', function () {
                shareButtonGroup.toggle(function () {
                    if (!window.enableShareThis) {
                        $(this).children('a')[0].focus();
                    } else {
                        $(this).children('button')[0].focus();
                    }
                });
            });

            var options = jobHeaderContent.find('.share');

            if ($('#apply-button').parent().hasClass('active')) {
                options.hide();
            }

            jobHeaderContent
                .on('show', '#apply-button', function () {
                    options.hide();
                })
                .on('show', '#job-details-button', function () {
                    options.show();
                });
        }

        $(document).ready(function () {
            gJobs.searchPage.details.initUI();
            gJobs.facetContainer.init();
            initPaginationPanel();
            gJobs.searchPage.searchResultsInfo.updateEventHandlers();
            gJobs.searchPage.searchResultsInfo.updateFullDescriptionExpander();
            gJobs.searchPage.searchResultsInfo.showHighestPriorityInfo();
            gJobs.pageTabNavigationService.adjustNavigationForFixedHeader($body);

            gJobs.searchPage.trackJobSearchResultsClicks();

            gJobs.searchPage.trackTopUsaJobClick();

            if ($sidebarContainer.length !== 0) {
                ko.applyBindingsToNode($sidebarContainer.get(0));
            }

            if (window.enableAdSenseAdvertiserTracking && $adContainerIframes.length !== 0) {
                var keywords = '';
                if ($keywordSearch.length !== 0 && $keywordSearch[0].value) {
                    keywords = $keywordSearch[0].value;
                }
                $adContainerIframes.each(function() {
                    var url = this.src;
                    OnlineApp.Services.dataService.updateAdSenseDisplayInfo
                        .post({ url: url, keywords: keywords });
                });
            }

            // Add titles to iframes without one (Google ad iframes)
            // This is needed for 508c compliance, IE, WAT Toolbar -> Frames -> Frame Name/Title
            setTimeout(function () {
                $adContainerIframes.each(function (index) {
                    if (!$(this).attr("title")) {
                        $(this).attr("title", "Google Ads");
                    }
                });
            }, 1000);

            var routes = ['jobOnlineAppRoute', 'jobApplyRoute', 'jobDetailsRoute'];
            var length = routes.length;
            for (var i = 0; i < length; i++) {
                if (gJobs.router.isCurrentUrlMatchedToRoute(routes[i])) {
                    History.Adapter.trigger(window, 'statechange');
                    break;
                }
            }

            $("#keyword-search-input").addClearButton(false, 'clear search keyword');
            $("#location-search-input").addClearButton(false, 'clear search location');

            googleBannerPositionHandler();
        });
    });

    $contentContainer
        .on('shown', '.job-header-content .tabbable a[data-toggle="tab"]', function () {
            var tabId = $(this).attr('href');
            var $tab = $(tabId);

            gJobs.searchPage.updateFlyoutSizes(tabId);
            gJobs.searchPage.size.apply($tab);
        });

    gJobs.searchPage.size.applyForCurrentTab();



    // Neeeded for crossbrowser scrollbar support in job details flyout content
    $(window).resize(function () {
        gJobs.searchPage.updateFacetsContainerDisplaying();
        gJobs.searchPage.updateFlyoutSizes();
        gJobs.searchPage.searchResultsInfo.updateFullDescriptionExpander();

        googleBannerPositionHandler();
    });

    function hideSearchPopovers() {
        $mainSearchContainer.find('[data-toggle="popover"]').each(function () {
            $(this).popover("hide");
        });
        $mainSearchContainerRevamp.find('[data-toggle="popover"]').each(function () {
            $(this).popover("hide");
        });
    }

    $(function () {
        loadBackfillResultsIfGJobsResultsAreEmpty();
    });

    $keywordSearch.blur(function() {
        generateNoAlertSetView();
        $keywordSearch.siblings('.ui-helper-hidden-accessible').text('');
    });


    $locationSearch.blur(function () {
        generateNoAlertSetView();
        $locationSearch.siblings('.ui-helper-hidden-accessible').text('');
    });

    function generateNoAlertSetView() {
        var params = OnlineApp.Helpers.Url.getJsonFromUrl(location.search);
        if ($keywordSearch[0].value !== params.keyword || $locationSearch[0].value !== params.location) {
            OnlineApp.Services.jobAlertService.generateNoFilterSetView(true)
                .done(function (response) {
                    $('#job-alert-out-container').html(response);
                });
        }
        else if (!(params.category || params.organization || params.salary || params.keyword || params.location)) {
            if ($keywordSearch[0].value !== params.keyword || $locationSearch[0].value !== params.location) {
                OnlineApp.Services.jobAlertService.generateNoFilterSetView(true)
                   .done(function (response) {
                        $('#job-alert-out-container').html(response);
                   });
            }
            else {
                OnlineApp.Services.jobAlertService.generateNoFilterSetView(false)
                   .done(function (response) {
                        $('#job-alert-out-container').html(response);
                   });
            }
        }
    }

})(window);;
(function (window, undefined) {
    'use strict';

    var AUTOCOMPLETE_DELAY = 200,
        AUTOCOMPLETE_MINLENGTH = 1,
        ITEM_HEIGHT = 40;

    var keywordSearch = $('#keyword-search-input'),
        locationSearch = $('#location-search-input');

    var aria = gJobs.ariaAttributes;

    (function($) {
        $.fn.ellipsis = function(defaultOptions)
        {
            // todo: use smart logic for retrieving element's width & height
            // todo: sth. like http://jsfiddle.net/sbedulin/wXdJF/

            var maxCharacters = defaultOptions.maxCharacters || 30;

            return this.each(function()
            {
                var el = $(this);
                var text = el.html();
                var openTagIndex = 0; //current open tag start character index
                var closeTagIndex = 0; //current close tag start character index
                var currentTagsLength = 0; //current length of all tags, found in the string before
                var openTag = "<b>";
                var closeTag = "</b>";
                var textEnd = ""; //end of string which is added to cutted string

                //check if it's necessary to cut initial string and add ellipsis
                if (text.replace(openTag, '').replace(closeTag, '').length > maxCharacters) {

                    //search for tags and cut initial string
                    while (true) {
                        openTagIndex = text.indexOf(openTag, openTagIndex);
                        
                        //check if there are no other highlight tags in the string and add not bold dots
                        if (openTagIndex == -1) {
                            textEnd = "...";
                            break;
                        }
                        
                        //check if there are any other highlight tags in the string and add bold dots
                        //that condition also means that we're not cutting string between open and close highlight tags
                        if (openTagIndex > maxCharacters + currentTagsLength - 1) {
                            textEnd = openTag + "..." + closeTag;
                            break;
                        }
                        
                        //increment length of current tags by start tag length
                        currentTagsLength += openTag.length;
                        
                        closeTagIndex = text.indexOf(closeTag, closeTagIndex);
                        
                        if (closeTagIndex > maxCharacters + currentTagsLength) {
                            textEnd = "..." + closeTag;
                            break;
                        }
                        
                        //increment length of current tags by end tag length
                        currentTagsLength += closeTag.length;

                        //set current open and close tags start characters indexes for searching next tags
                        openTagIndex += openTag.length;
                        closeTagIndex += closeTag.length;
                    }

                    //building final string with highlighted tags
                    text = text.substring(0, maxCharacters + currentTagsLength) + textEnd;
                }
                el.html(text);
            });
        };

        // Add special tags to text for highlighting
        $.fn.highlightKeyword = function (substring) {
            return this.each(function () {
                substring = substring.toLowerCase();
                var el = $(this);
                var autocompleteText = el.text();
                var autocompleteTextLowCase = autocompleteText.toLowerCase();
                var newAutocompleteText = ""; //new text with highlight tags
                var substringLength = substring.length;
                var openTag = "<b>";
                var closeTag = "</b>";
                var index = 0; //substring start index from previous search 
                
                //search and replace substrings in autocomplete text with no case missing
                while (true) {
                    //current substring start index
                    var newIndex = autocompleteTextLowCase.indexOf(substring, index);

                    //check if there are no other substrings in text and copy end of initial text to new text
                    if (newIndex == -1) {
                        newAutocompleteText = newAutocompleteText.concat(autocompleteText.substring(index));
                        break;
                    }

                    //copy to new text part between previous substring end and current substring start from initial text
                    newAutocompleteText = newAutocompleteText.concat(autocompleteText.substring(index, newIndex));

                    //copy to new text substring with case from initial text and adding open and close tags to highlight
                    newAutocompleteText = newAutocompleteText.concat(
                        openTag,
                        autocompleteText.substring(newIndex, newIndex + substringLength),
                        closeTag);
                    
                    //update previous substring start index
                    index = newIndex + substringLength;
                }

                el.html(newAutocompleteText);
            });
        };
    })(jQuery);

    // Initialize autocomplete
    $(function () {
        if (!$.ui || !$.ui.autocomplete) {
            return;
        }

        $.widget('custom.catcomplete', $.ui.autocomplete, {
            options: {
                create: function () {
                    $(this).setAttributes([
                        [ aria.role, 'combobox' ],
                        [ aria.autocomplete, 'list' ]
                    ]);
                }
            },
            _renderMenu: function (ul, items) {
                var that = this,
                    currentCategory = '',
                    allAutocompleteItemsHaveJobInterestCardCategory = true,
                    allAutocompleteItemsHaveClassSpecificationsTitleForFilterCategory = true;
                ul.addClass('popover bottom');

                this._on(this.menu.element, {
                    menufocus: function (event, ui) {
                        var item = ui.item.data("ui-autocomplete-item");

                        var activeElementId = ui.item.find('a').attr('id') + '_li';

                        this.element.setAttributes([
                            [ aria.activeDescendant, activeElementId ]
                        ]);

                        this.menu.activeMenu.find('li').setAttributes([
                            [ aria.selected, 'false']
                        ]);

                        ui.item.find('a').setAttributes([
                            [ aria.label, item.category + ' ' + item.label]
                        ]);

                        ui.item.setAttributes([
                            [ aria.selected, 'true' ]
                        ]);

                        if (!item.hiddenLabel) {
                            return;
                        }

                        // #7024 - Prevent accidental activation of menu items in Firefox
                        if (this.isNewMenu) {
                            this.isNewMenu = false;
                            if (event.originalEvent && /^mouse/.test(event.originalEvent.type)) {
                                this.menu.blur();

                                this.document.one("mousemove", function() {
                                    $(event.target).trigger(event.originalEvent);
                                });

                                return;
                            }
                        }

                        if (false !== this._trigger("focus", event, { item: item })) {
                            // use value to match what will end up in the input, if it was a key event
                            if (event.originalEvent && /^key/.test(event.originalEvent.type)) {
                                $("#" + this.element.attr("description")).text(item.hiddenLabel);
                            }
                        }
                    }
                });
                
                function isJobInterestCardCategory(category) {
                    return category === OnlineApp.AutocompleteFieldKinds.ClassSpecificationTitleForJobInterestCard ||
                        category === OnlineApp.AutocompleteFieldKinds.DepartmentTitleForJobInterestCard ||
                        category === OnlineApp.AutocompleteFieldKinds.LocationTitleForJobInterestCard;
                }

                function isClassSpecificationsTitleForFilterCategory(category) {
                    return category === OnlineApp.AutocompleteFieldKinds.ClassSpecificationsTitleForFilterCategory;
                }

                $.each(items, function (index, item) {
                    if (!isJobInterestCardCategory(item.category)) {
                        allAutocompleteItemsHaveJobInterestCardCategory = false;
                    }

                    if (!isClassSpecificationsTitleForFilterCategory(item.category)) {
                        allAutocompleteItemsHaveClassSpecificationsTitleForFilterCategory = false;
                    }

                    if (isJobInterestCardCategory(item.category)
                        || isClassSpecificationsTitleForFilterCategory(item.category)) {
                        item.category = '';
                    }

                    if (item.category != currentCategory) {
                        if (index != 0) {
                            ul.append('<div class="category-placeholder"></div>');
                        }
                        ul.append('<div class="ui-autocomplete-category">' + item.category + '</div>');
                        currentCategory = item.category;
                    }

                    that._renderItemData(ul, item);
                });
                ul.append('<div class="arrow"></div>');
                ul.append('<div class="category-placeholder"></div>');

                if ((allAutocompleteItemsHaveJobInterestCardCategory && window.enableAdvancedJobInterestCards)
                    || allAutocompleteItemsHaveClassSpecificationsTitleForFilterCategory) {
                    var $currentAutocompleteMenuListItems = $('.ui-autocomplete li');

                    if ($currentAutocompleteMenuListItems && $currentAutocompleteMenuListItems.length) {
                        $currentAutocompleteMenuListItems.addClass('ui-menu-item-without-category');
                    }
                }
            },
            _suggest: function (items) {
                function resetHeight(element) {
                    element.css('height', 'auto');
                    element.css('overflow-y', 'auto');
                }

                function recalculateHeight(element) {
                    var lowerBound = element.height() + element.offset().top - $(document).scrollTop();
                    var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
                    if (viewportHeight < lowerBound) {
                        var elementHeight = element.height() - (lowerBound - viewportHeight) - 20;

                        if (elementHeight < ITEM_HEIGHT) {
                            elementHeight = ITEM_HEIGHT;
                        }

                        element.css('height', elementHeight);
                        element.css('overflow-y', 'scroll');
                    }
                }

                if ($('html').hasClass('device-phone')) {

                    var newScrollPosition = this.element.offset().top;

                    var $header = $('.floating-header, .navbar');

                    if (window.revampedDesign === true) {
                        $header = $('#header');
                    }

                    if ($header.length && $header.is(':visible')) {
                        newScrollPosition -= $header.height();
                    }

                    $('html, body').animate({ scrollTop: newScrollPosition }, 500);
                }

                function hideInputPopovers() {
                    keywordSearch.popover("hide");
                    locationSearch.popover("hide");
                }

                var ul = this.menu.element.empty(),
                    overwriteTop,
                    marginTop = 15;

                resetHeight(ul);

                this._renderMenu(ul, items);
                this.menu.refresh();

                // size and position menu
                ul.show();
                this._resizeMenu();
                ul.position($.extend({
                    of: this.element
                }, this.options.position));

                // Overwrites bootstrap styles. Needs to do in JS because jQueryUI calculates dimension and position dynamically.
                overwriteTop = parseInt(ul.css('top')) + marginTop;
                ul.css('top', (overwriteTop + "px"));
                ul.css('max-width', this.element.outerWidth());

                recalculateHeight(ul);

                if (locationSearch.width() < 237) {
                    ul.css('width', (locationSearch.css('width')));
                    ul.addClass('small-autocomplete');
                }

                if (this.options.autoFocus) {
                    this.menu.next();
                }

                if (this.options.additionalCssClassNames) {
                    // attach some additional styles to autocomplete
                    ul.addClass(this.options.additionalCssClassNames);
                }

                // todo: add this.options.useEllipsis
                ul.find("a").highlightKeyword(this.term).ellipsis({
                    maxCharacters: (Math.floor(ul.css("width").replace("px", "")) / 8)
                });

                ul.setAttributes([
                    [ aria.role, 'listbox' ],
                    [ aria.tabindex, '-1' ]
                ]);

                ul.find('li').setAttributes([
                    [ aria.role, 'option' ],
                    [ aria.tabindex, '-1'],
                    [ aria.selected, 'false' ]
                ]);

                ul.find('li').each(function () {
                    var $this = $(this);
                    $this.attr('id', $this.find('a').attr('id') + '_li');
                });

                this.element.setAttributes([
                    [ aria.controls, ul.attr('id') ]
                ]);

                hideInputPopovers();
            },
            _normalize: function (items) {
                var that = this;
                // assume all items have the right format when the first item is complete
                if (items.length && items[0].label && items[0].value) {
                    return items;
                }
                return $.map(items, function (item) {
                    if (typeof item === "string") {
                        return {
                            label: item,
                            value: item
                        };
                    }
                    return $.extend({
                        label: (item.label || item.value),
                        //Adding space to suggested value that matches search term to tell Jaws` virtual focus that focus is still in dropdown (ONLINE-2976)
                        value: (item.value || item.label) + (that.term === (item.value || item.label) ? " " : "")
                    }, item);
                });
            }
        });

        // sidebar exists => autocompletes are inside
        var isSidebarAutocomplete = $("#sidebar-container").length > 0 ? true : false;

        function initSearchFieldWithAutocomplete($searchField, options) {
            var additionalCssClassNames = undefined;
            var responseCallback = options ? options.responseCallback : undefined;

            if (isSidebarAutocomplete) {
                additionalCssClassNames = "sidebar-autocomplete";
            } else if (options && options.additionalCssClassNames) {
                additionalCssClassNames = options.additionalCssClassNames;
            }

            if ($searchField && $searchField.length && $searchField.length > 0) {
                $searchField.catcomplete({
                    minLength: AUTOCOMPLETE_MINLENGTH,
                    delay: AUTOCOMPLETE_DELAY,
                    source: $searchField.data('action'),
                    additionalCssClassNames: additionalCssClassNames,
                    response: responseCallback
                });
            }
        }

        initSearchFieldWithAutocomplete(keywordSearch);

        initSearchFieldWithAutocomplete(locationSearch);

        $(document).on(OnlineApp.Events.CommonEventsNames.InitSearchFieldsWithAutocomplete, function(event, options) {
            if (options && options.searchFieldSelectors) {
                options.searchFieldSelectors.forEach(function(searchFieldSelector) {
                    var $searchField = $(searchFieldSelector);

                    initSearchFieldWithAutocomplete($searchField, options);
                });
            }
        });
    });
})(window);;
(function (window, undefined) {
    'use strict';

    $(function () {

        // Enable placeholder for search bar location input for IE8/9
        if (!("placeholder" in document.createElement("input"))) {
            $('input[placeholder]').each(function () {

                var input = $(this);

                if (input.val() == "") {
                    input.addClass('placeholder');
                    $(input).val(input.attr('placeholder'));
                }

                $(input).focus(function () {
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                        input.removeClass('placeholder');
                    }
                });

                $(input).blur(function () {
                    if (input.val() == '' || input.val() == input.attr('placeholder')) {
                        input.val(input.attr('placeholder'));
                        input.addClass('placeholder');
                    }
                });
            });
            // Clear placeholder values upon submit
            $("#main-search-criteria form").submit(function () {
                $('input[placeholder]').each(function () {
                    var input = $(this);

                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });
            });
        }

        // Due to Bootstrap overwriting inline img tags (breaks customers html), need to append width/height to imgs to show correct sizes
        $("#info img").each(function (index) {
            if ($(this).attr("width") != null) {
                $(this).css("width", $(this).attr("width") + "px");
            }
            if ($(this).attr("height") != null) {
                $(this).css("height", $(this).attr("height") + "px");
            }
        });
    });



    // Messaging

    $(document).on(Events.CommonEventsNames.ShowMessage, function (_, messageCode) {
        var messageCodeToMessageMap = {
            'nonauthorized': 'Your session has expired. Please sign in again'
        };

        var message = messageCodeToMessageMap[messageCode];

        toastr.warning(message);
    });

    $(document).ready(function () {
        var action = localStorage.getItem('action'),
            reason = localStorage.getItem('reason');

        if (action !== undefined && action === 'redirect' && reason !== undefined) {
            window.onpageshow = function () {
                localStorage.removeItem('action');
                localStorage.removeItem('reason');
            }

            $(document).trigger(Events.CommonEventsNames.ShowMessage, reason);
        }

        if (sessionStorage.getItem(OnlineApp.SessionKeys.IsVerifyIdentityVerificationCodeVerified) === "true") {
            gJobs.screenReadersService.setAriaLiveNotification("Code is verified");
            sessionStorage.removeItem(OnlineApp.SessionKeys.IsVerifyIdentityVerificationCodeVerified);
        }
    });

    var updateFooterPosition = function () {
        var $window = $(window);
        var $content = $('#main-content-container, .page-container');

        if (window.revampedDesign) {
            var $header = $('#header');
            var $footer = $('#footer-new');
        }
        else {
            var $header = $('#header > .navbar');
            var $footer = $('#footer');
        }
        if (window.location.href.indexOf("schooljobs") != -1) {
            var $footer = $('#sjobs-footer-new');
        }

        var expectedContentHeight = $window.height() - $footer.outerHeight() - $header.outerHeight();

        if (window.enableStickyHeader) {
            var $stickyHeader = $('#sticky-header');
            expectedContentHeight += $stickyHeader.outerHeight();
        }

        var actualContentHeight = $content.outerHeight();

        if (actualContentHeight > expectedContentHeight) {
            expectedContentHeight = actualContentHeight;
        }

        $('#content').css('min-height', expectedContentHeight);
    };

    $(window).resize(function () {
        updateFooterPosition();
    });

    $(document).ready(function () {
        updateFooterPosition();
    });

    $(document).on('layoutUpdated', function () {
        //need a 1ms delay of computation for IE8 support
        setTimeout(updateFooterPosition, 1);
    });

    $(function() {
         $('#screen-reader-message').focus();
    });

    $(document).keydown(function(e) {
        if (e.keyCode === $.ui.keyCode.ESCAPE) {
            if ($(e.target).hasClass('inbox-header-id')) {
                $(e.target).popover('hide');
            }

            if ($(e.target).hasClass('flag-left')
                && $(e.target).siblings('.bs-tooltip-right').length) {
                $(e.target).siblings('.bs-tooltip-right').hide();
            }
        }
    });

})(window);

// Define global share buttons settings
var injectAddthisConfig = function (googleAnalyticsId) {
    window.addthis_config = {
        ui_508_compliant: true,
        data_track_clickback: false,
        data_ga_property: googleAnalyticsId
    };
};
var addthis_share =
{
    url_transforms: {
        shorten: {
            twitter: 'bitly'
        }
    },
    templates: {
        twitter: '{{title}} {{url}} ' + window.Resources.SocialLinks.twitterLink
    }
};;
(function (window, undefined) {
    'use strict';

    var releaseFocusFn;

    namespace('gJobs').common = {
        social: (function () {
            return {
                init: function ($element, title, url, location) {
                    var socialLinkTitle = location + ' ' + title;

                    if (window.addthis) {
                        if ($element) {
                            if (!window.enableShareThis) {
                                $element
                                    .attr('addthis:title', socialLinkTitle)
                                    .attr('addthis:url', url);
                            }
                        }

                        if (!window.enableShareThis) window.addthis.toolbox('.addthis_toolbox');
                    }

                    if (window.enableShareThis) {
                        if ($element) {
                            var $shareThisButtons = $element.find('.st-custom-button');

                            $shareThisButtons.attr('data-title', socialLinkTitle); 

                            $shareThisButtons.attr('data-url', url); 

                            var $shareThislinkedinButton = $element.find('.st-custom-button.linkedin-share-button');
                            $shareThislinkedinButton.attr('data-url', encodeURI(url + "?1"));

                            var $shareThisEmailButton = $element.find('.st-custom-button.email-share-button');

                            $shareThisEmailButton.attr('data-email-subject', socialLinkTitle);
                        }

                        if (window.__sharethis__) window.__sharethis__.initialize();
                    }
                }
            };
        })()
    };

    if (window.addthis && window.addthis.addEventListener) {
        window.addthis.addEventListener('addthis.menu.open', onAddThisModalOpen);
        window.addthis.addEventListener('addthis.menu.close', onAddThisModalClose);
    }

    function onAddThisModalOpen() {
        gJobs.focusService.restrictFocus($('#at3win'));
    }

    function onAddThisModalClose() {
        if (typeof releaseFocusFn === 'function') {
            releaseFocusFn();
        }
    }

    $(document).keydown(function (e) {
        if (e.keyCode === $.ui.keyCode.ESCAPE) {
            if ($(e.target).hasClass('st-custom-button')) {
                $(e.target).popover('hide');
            }
        }
    });

})(window);;
(function (window, undefined) {
    'use strict';

    $(document).ready(function () {
        var $twitterWidgetContainer = $('.twitter-widget-container');
        if ($twitterWidgetContainer.length !== 0) {
            ko.applyBindingsToNode($twitterWidgetContainer.get(0));
        }
        gJobs.nonFlickeringPopover($('#footer').find('[data-toggle="popover"]'), 'job-details-popover');
        gJobs.nonFlickeringPopover($('#footer-new').find('[data-toggle="popover"]'), 'job-details-popover');

        $('#access-membership-footer-link').click(function () {
            gJobs.common.analytics.trackEvent('Access Membership Gjobs Footer', 'Followed');
        });
    });
})(window);;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').signInTemplatesService = {
        getTemplates: function () {
            var signInTemplatesPath = window.signInTemplatesPath;

            return $.ajax({
                url: signInTemplatesPath,
                type: 'GET',
                cache: true
            }).done(function (data) {
                $('head').append(data);
            }).then();
        }
    };

})(window);;
(function (window, undefined) {
    'use strict';

    function VerifyIdentityService() {
        var self = this;
                 
        var verifyCodeUrl = '/api/twoFactorAuthentication/verify',
            resendVerificationCodeUrl = '/api/twoFactorAuthentication/resendEmail',
            getUserDataUrl = '/api/twoFactorAuthentication/getUserData';

        function getAgencyFolderName() {
            var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();
            var currentArea = gJobs.areaInfoService.getCurrentArea();

            var agencyFolderName = "";

            if (currentArea !== abstractAreaInfoService.areaNames.GJobs) {
                agencyFolderName = AgencyPages.pageInfoService ?
                    AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                    gJobs.pageInfoService.getCurrentAgencyPageFolderName();
            }

            return agencyFolderName;
        }

        self.verifyCode = function (
            verificationCode,
            rememberDevice,
            captchaAnswer,
            credential
        ) {
            return $.ajax({
                type: 'POST',
                url: verifyCodeUrl,
                data: {
                    alphanumericVerificationCode: verificationCode,
                    rememberDevice: rememberDevice,
                    captchaAnswer: captchaAnswer,
                    credential: credential
                }
            });
        };

        self.resendVerificationCode = function (credential, captchaAnswer) {
            var agencyFolderName = getAgencyFolderName();

            return $.ajax({
                type: 'POST',
                url: resendVerificationCodeUrl,
                data: {
                    captchaAnswer: captchaAnswer,
                    credential: credential
                }
            });
        };

        self.getUserData = function (credential) {
            return $.ajax({
                type: 'GET',
                url: getUserDataUrl + "?credential=" + credential
            });
        };
    }

    OnlineApp.Namespace.extend('gJobs.Services', {
        verifyIdentityService: new VerifyIdentityService()
    });

})(window);
;
(function(window, undefined) {
    'use strict';

    function VerifyAccountService() {
        var self = this;

        var resendVerificationLinkUrl = '/api/emailVerification/resendVerificationLink';

        function getAgencyFolderName() {
            var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();
            var currentArea = gJobs.areaInfoService.getCurrentArea();

            var agencyFolderName = "";

            if (currentArea !== abstractAreaInfoService.areaNames.GJobs) {
                agencyFolderName = AgencyPages.pageInfoService
                    ? AgencyPages.pageInfoService.getCurrentAgencyFolderName()
                    : gJobs.pageInfoService.getCurrentAgencyPageFolderName();
            }

            return agencyFolderName;
        }

        self.resendVerificationLink = function(credential, captchaAnswer, changedEmailAddressWasAdded, isOjrMaster) {
            return $.ajax({
                type: 'POST',
                url: resendVerificationLinkUrl,
                data: {
                    captchaAnswer: captchaAnswer,
                    credential: credential,
                    changedEmailAddressWasAdded: changedEmailAddressWasAdded,
                    isOjrMaster: isOjrMaster
                }
                                
            });
        };
    }

    OnlineApp.Namespace.extend('gJobs.Services', {
        verifyAccountService: new VerifyAccountService()
    });

})(window);
;
(function (window, undefined) {
    'use strict';

    var layoutHelper = OnlineApp.Helpers.layoutHelper;

    var MSEC_TO_HIDE_MESSAGE = 5000;
    var NO_RESTRICT_FOCUS_CLASS = 'no-restrict-focus';

    var mobileScreenWidth = 767;

    var $unauthorizedMenuContainer = $("#unauthorized-menu-container");
    var $signInBlock = $('#sign-in-block'),
        $standaloneSignInBlock = $('#standalone-sign-in-block'),
        $standaloneCreateAccountBlock = $("#standalone-create-account-block"),
        $signInOverlay = $('.sign-in-overlay'),
        $headerNav = $('.nav.right-nav.pull-right'),
        $signInLink = $headerNav.find('.sign-in'),
        $signOutLink = $headerNav.find('.sign-out'),
        $applicationsLink = $headerNav.find('.applications-link'),
        $accountSettingsLink = $headerNav.find('.account-setting'),
        $togglers = $signInBlock.find('.togglers a'),
        $messageContainer = $('.notification'),
        $usernameBlock = $('.username'),
        $yourAccountMenuItem = $('.your-account-menu-item'),
        $postJobLink = $('.post-job-link'),
        $jobSearchLink = $('.job-search-link'),
        $applicationMenuLinkContainer = $('.application-menu-link'),
        $applicationMenuLink = $applicationMenuLinkContainer.children('a'),
        $applicationMenuItems = $('.application-menu-items'),
        $applicationMenuItemsLinks = $applicationMenuItems.find('a'),
        $tabbableApplicationMenuElements = $applicationMenuLink.add($applicationMenuItemsLinks),
        $applicationMenu = $applicationMenuLinkContainer.find('.application-menu'),
        $html = $('html'),
        loginRegisterEvents = Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register,
        $loginButton = $('#login-button'),
        $signupButton = $('#signup-button');

    namespace('gJobs').signInForm = {

        init: function () {
            var self = this;

            OnlineApp.Services.authenticationService.isLoggedIn().done(function (data) {
                if (data) {
                    $signInLink.addClass('hide');
                    self.updateUsername();

                } else {
                    var currentUserNameFromUrlParam = window.utils.getUrlParameter('onLoadShowLoginWithUserName');
                    if (currentUserNameFromUrlParam) {
                        self.show();
                    }
                    $headerNav.addClass('hide');
                }
            });
        },

        toggleSignInOut: function (screenReaderNotificationText) {
            $headerNav.removeClass('hide');
            $signInLink.addClass('hide');

            this.hide(screenReaderNotificationText);
            
            $applicationsLink.removeClass('hide');
            $accountSettingsLink.removeClass('hide');
            $signOutLink.removeClass('hide');

            $postJobLink.addClass('hide');
            $signInLink.addClass('hide');

            $jobSearchLink.removeClass('hidden');
        },

        show: function (showJobAlert) {
            if ((!$('html').hasClass('device-phone') && !revampedDesign) || // currentScreenWidth > mobileScreenWidth
                (!$('html').hasClass('device-phone') && !$('html').hasClass('device-tablet') && revampedDesign)) {
                $signInBlock.show();
                // This stops the menu button from getting lost in the viewport
                // after a user opens the sign in block on desktop width and then zooms in to mobile width
                if (!revampedDesign) {
                    $("#menu-expander").css('left', '0');
                }
            } else {
                if ($signInBlock.css('display') == 'none') {
                    gJobs.responsive.openSignInForm(function() {
                        $signInBlock.find('input:first').focus();
                    });
                } else {
                    gJobs.responsive.closeSignInForm(function() {
                        $('li.sign-in > a').focus();
                    });
                }
            }

            $signInBlock.attr('aria-hidden', false);

            // This timeout prevents jaws from reading email field as button on sign up form opening
            setTimeout(function ()
            {
                var tabbableElements = $signInBlock.find(':tabbable');
                tabbableElements.addClass(NO_RESTRICT_FOCUS_CLASS);
            });

            $signInOverlay.show();
        },

        hide: function () {
            $signInBlock.hide();
            $signInOverlay.hide();

            $signInBlock.attr('aria-hidden', true);

            OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.isEmailTooltipFocusable(true);

            if (!window.revampedDesign) {
                $signInLink.find('> a').focus();
            } else {
                var signInClosedNotification;
                var $signInButton;

                if ($signInBlock.find('.login-container').length) {                   
                    signInClosedNotification = $($('.form-signin-heading')[0]).text() + ' form is closed';
                    $signInButton = $loginButton;
                } else {
                    signInClosedNotification = 'Create an account form is closed';
                    $signInButton = $signupButton;
                }
                gJobs.screenReadersService.setAriaLiveNotification(signInClosedNotification);
                $signInButton.focus();
            }
        },

        isOpen: function() {
            return $signInBlock.is(':visible') || !$signInBlock.is(':hidden');
        },

        toggleLogInAndRegister: function (e) {
            $togglers.toggleClass('hide');

            $(document).trigger("toggleLogInAndRegister", e);

            var tabbableElements = $signInBlock.find(':tabbable');
            tabbableElements.addClass(NO_RESTRICT_FOCUS_CLASS);
            $('#confirm-password-field, #popup-create-password-confirm-field').addClass(NO_RESTRICT_FOCUS_CLASS);

            tabbableElements.first().focus();
        },

        updateUsername: function () {
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification("You are now logged in."); }, 300);
            OnlineApp.Services.authenticationService.getUserData().done(function (data) {
                $usernameBlock.text(data.username);
                $usernameBlock.closest('a').attr('aria-label', 'Press enter to Open the User profile drop down menu of ' + data.username );
                // Set position of notification at center of username
                //var offset = $messageContainer.width() / 2 - $applicationMenuLink.width() / 2 - 30;
                //$messageContainer.css('left', -offset);
            });
        },

        updateFooterMenu: function (isAuthorized) {
            var yourAccountUrl =
                $yourAccountMenuItem.data(isAuthorized ? 'authorized-url' : 'unauthorized-url');

            $yourAccountMenuItem.attr('href', yourAccountUrl);
        },

        focusFirstTabbableElement: function() {
            $signInBlock.find(':tabbable').first().focus();
        }
    };

    //
    // Initializer
    //
    $(function () {
        gJobs.signInTemplatesService.getTemplates().done(function () {
            var $bindingElements = [$unauthorizedMenuContainer, $signInLink, $standaloneSignInBlock, $standaloneCreateAccountBlock];

            $bindingElements.map(function($element) {
                var element = $element.get(0);
                if (element) {
                    ko.applyBindings(OnlineApp.ViewModels.applicationViewModel, element);
                }
            });
        });

        gJobs.signInForm.init();

        gJobs.nonFlickeringPopover($('.header-container').find('[data-toggle="popover"]'), 'job-details-popover');

        if (gJobs.browserDetector.isIE()) {
            $.each($applicationMenuItemsLinks, function(){
                var $this = $(this);
                var applicationMenuItemTitle = $.trim($this.text().replace(/\s+/g, ' '));
                $this.attr('title', applicationMenuItemTitle);
            });
        }

        $loginButton
            .on('click', function(e) {
                if (!OnlineApp.ViewModels.applicationViewModel.loginViewModel.signInViewModel.isActive()) {
                    gJobs.signInForm.toggleLogInAndRegister(e);
                }
            });

         $signupButton
            .on('click', function(e) {
                if (!OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.isActive()) {
                    gJobs.signInForm.toggleLogInAndRegister(e);
                }
            });

        $togglers
            .on('click', function(e) {
                OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.isEmailTooltipFocusable(false);
                gJobs.signInForm.toggleLogInAndRegister(e);
            })
            .on('keydown', function(e) {
                if (e.keyCode === $.ui.keyCode.ENTER) {
                    e.preventDefault();
                    gJobs.signInForm.toggleLogInAndRegister(e);
                }
            });

        $signInOverlay.on('click', function () {
            gJobs.signInForm.hide();
            return false;
        });

        $signInBlock
            .on('click', function (e) {
                OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.isEmailTooltipFocusable(false);
            })
            .on('keydown', function(e) {
                if (e.keyCode === $.ui.keyCode.ESCAPE) {
                    if (window.revampedDesign) {
                        e.stopPropagation();
                        $("#login-menu-expander").focus();
                    }
                    if ($(e.target).hasClass('screenreader-link-required')
                        && $(e.target).siblings('.popover:visible').length) {
                        $(e.target).popover('hide');
                    } else {
                        gJobs.signInForm.hide();
                    }
                }
            });

        $signOutLink.on('click', function (e) {
            e.preventDefault();
            OnlineApp.Services.authenticationService.logout().done(function () {
                gJobs.signInForm.updateFooterMenu(false);
                location.reload();
            });
        });

        $applicationMenuLinkContainer.on('click', function (event)
        {
            if (!$html.hasClass('device-phone')) {
                toggleApplicationMenu();
            }
            event.stopPropagation();
            if (window.isJobAlertEdit === true) {
                var $tabbableElements;
                $tabbableElements = $('#account-settings')
                    .find(':tabbable');
                $tabbableElements.attr('tabindex', -1);
                $("#footer-new").hide();
            }
            
        });

        $applicationMenu.on('keydown', function (e) {
            if (e.keyCode == $.ui.keyCode.ESCAPE) {
                e.stopPropagation();
                toggleApplicationMenu();
            }
        });

        $applicationMenu.on('keydown', ':tabbable:last', function (e) {
            if (e.keyCode === $.ui.keyCode.TAB && !e.shiftKey) {
                if (!revampedDesign && $html.hasClass('device-phone')) {
                    // The tab has been hit on the last tabbable element (navigation link)
                    // therefore, focus the close button, if on a mobile viewport
                    //$('#header').find(':tabbable').first().focus();
                    $('#menu-expander').focus();
                } else {
                    toggleApplicationMenu();
                }
            }
        });

        $signInBlock.on('keydown', ':tabbable:last', function (e) {
            if (e.keyCode === $.ui.keyCode.TAB && !e.shiftKey) {
                if (window.revampedDesign) {
                    e.stopPropagation();
                }
                gJobs.signInForm.hide();
            }
        });

        $signInBlock.on('keydown', ':tabbable:first', function (e) {
            if (e.keyCode === $.ui.keyCode.TAB && e.shiftKey) {
                if (window.revampedDesign) {
                    e.stopPropagation();
                }
                gJobs.signInForm.hide();
            }
        });

        function toggleApplicationMenu() {
            $applicationMenu.toggleClass('hide');
            $applicationMenu.find(':focusable').addClass(NO_RESTRICT_FOCUS_CLASS);

            if (!$applicationMenu.hasClass('hide')) {
                function closeApplicationMenu () {
                    if (!$applicationMenu.hasClass('hide')) {
                        toggleApplicationMenu();
                    }
                }

                var $firstMenuLink = $applicationMenuItemsLinks.first();
                var $menuNotification = $('<span class="hide-notification" tabindex="-1">User Menu with ' + $applicationMenuItemsLinks.length + ' options was opened.</span>');
                $firstMenuLink.prepend($menuNotification);
                $firstMenuLink.one('focusout', function() {
                    $menuNotification.remove();
                });

                $firstMenuLink.focus();

                gJobs.arrowsNavigationService.addArrowsNavigationOnElements($tabbableApplicationMenuElements);
                $(document).one('click', function () {
                    closeApplicationMenu();
                });
           
                // Solves the problem with detecting clicks on an iframes
                $(window).one('blur', function () {
                    closeApplicationMenu();
                });

                layoutHelper.tabbing.updateIndices();
            } else {
                gJobs.arrowsNavigationService.removeArrowsNavigationOnElements($tabbableApplicationMenuElements);
            }
        }

        function loginEventHandler() {
            gJobs.signInForm.toggleSignInOut(Resources.NotificationMessages.LoginSuccess);
            gJobs.signInForm.updateUsername();
            gJobs.signInForm.updateFooterMenu(true);

            if ($('#is-reset-password-using-reset-code-success').length > 0) {
                var employerFolderName = AgencyPages.pageInfoService ?
                    AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                    gJobs.pageInfoService.getCurrentAgencyPageFolderName();
                    
                if (employerFolderName && employerFolderName.length > 0) {
                    window.location = '/Applications/Index/' + employerFolderName;
                } else {
                    window.location = '/Applications/Index';
                }
            }
        }

        function registerEventHandler() {
            gJobs.signInForm.updateUsername();

            $messageContainer.fadeIn();

            setTimeout(function () {
                $messageContainer.fadeOut();
            }, MSEC_TO_HIDE_MESSAGE);

            gJobs.signInForm.toggleLogInAndRegister();
            gJobs.signInForm.toggleSignInOut(Resources.NotificationMessages.RegistrationSuccess);
        }

        $(document).on('loginEvent', function () {
            if ($(window).width() > mobileScreenWidth) {
                loginEventHandler();
            } else {
                gJobs.responsive.closeSignInForm(loginEventHandler);
            }
        });

        $(document).on('registerEvent', function () {
            if ($(window).width() > mobileScreenWidth) {
                registerEventHandler();
            } else {
                gJobs.responsive.closeSignInForm(registerEventHandler);
            }
        });

        $(document).on(loginRegisterEvents, function () {
            $('.sign-in-block-container').hide();
        });

        $(document).on(OnlineApp.Events.CommonEventsNames.RegisterAccountFormOpened, function (e, container) {            
            $("#aria-live-message-container").text('');
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification('Create a new account form is opened.', $("#aria-live-message-container"), false); }, 500);
        });

        $(document).on(OnlineApp.Events.CommonEventsNames.LoginFormOpened, function (e, container) {
            $("#aria-live-message-container").text('');
            setTimeout(function () { gJobs.screenReadersService.setAriaLiveNotification($($('.form-signin-heading')[0]).text() + ' form is opened.', $("#aria-live-message-container"), false); },500)
            
        });
    });

    $(window).focus(function () {
        if (localStorage.getItem('updatedEmail')) {
            gJobs.signInForm.updateUsername()
        }
    });

})(window);

;
(function (window, undefined) {
    'use strict';

    $(document).on(OnlineApp.Events.CommonEventsNames.ResumeImportComplete, function (e) {
        var method = '',
            eventAction = '',
            eventLabel = '';

        switch (e.source) {
            case 'fileUpload':
                method = 'Resume Import';
                eventAction = 'submit';
                eventLabel = 'resume';
                break;

            case 'skipSection':
                method = 'Profile Created without Import';
                eventAction = 'skip';
                eventLabel = 'manual input';
                break;
        }

        gJobs.common.analytics.trackProfileCreationEvent(method, e.application);
        gJobs.common.analytics.trackApplicationEvent({
            action: eventAction,
            eventLabel: eventLabel,
            name: 'customEmployerTracker'
        });
    });

    $(document).on(OnlineApp.Events.CommonEventsNames.ResourcesLinkClicked, function (e, data) {
        var eventCategory = "Resources " + data.linkType + " link";

        gJobs.common.analytics.trackEvent(eventCategory, 'click');
    });

    namespace('gJobs').common.analytics = (function () {

        var self = {};        

        var categories = {
            application: 'Application',
            profileCreation: 'Profile Creation',
            login: 'Login',
            jobSearch: 'Job Search',
            appSubmission: 'Application Submission',
            homePage: 'Home Page',
            careerJobSearch: 'Career Job Search'
        }

        var prefixes = {
            virtualPagePrefix: '/vr/',
            virtualDimensionPrefix: 'neogov|'
        }

        function _injectGoogleAnalyticsScript(options) {
            window.GoogleAnalyticsObject = 'ga';
            if (self.isGA4Enabled) {
                var configOptions = {
                    send_page_view: false//prevent page_view as part of initial config
                }
                if (options.cookieName)
                    configOptions.cookie_prefix = options.cookieName;
                gtag('config', options.trackingId,configOptions);
            }
            else
                ga('create', options);
        }


        function _injectPageChangeTrackingCode(options, context) {
            History.Adapter.bind(window, 'statechange', function () {
                context.trackCurrentPageView(options);
            });
        }

        function _applyTracker(trackerName) {
            return trackerName ? trackerName + '.' : '';
        }

        function _suppressTrack(options, context) {
            var router = namespace('AgencyPages').router;

            if (router) {
                var isExcludedRoute = false;

                if (options.excludedRouteNames) {
                    for (var i = 0; i < options.excludedRouteNames.length; i++) {
                        if (router.isCurrentUrlMatchedToRoute(options.excludedRouteNames[i])) {
                            isExcludedRoute = true;
                            break;
                        }
                    }
                }
                if (self.isGA4Enabled)
                    return (context.ga4Trackers.map(t => t.name).indexOf(options.name) === 1) && isExcludedRoute;
                else
                    return (context.trackers.indexOf(options.name) === 1) && isExcludedRoute;
            }

            return false;
        }

        function _getCurrentArea() {
            return gJobs && gJobs.areaInfoService ? gJobs.areaInfoService.getCurrentArea() : '';
        }

        self.sendToAllTrackers = function (eventHandlerName, options) {
            delete options.sendToAllTrackers;
            if (self.isGA4Enabled)
                self.ga4Trackers.forEach(function (element) {
                    options.trackingId = element.trackingId;
                    options.name = element.name
                    self[eventHandlerName](options);
                });
            else
                self.trackers.forEach(function (element) {
                    options.name = element;
                    self[eventHandlerName](options);
                });
        }

        self.inject = function (options) {
            options = $.extend({}, options);
            options.sendPageViewEvent = (typeof options.sendPageViewEvent !== 'undefined') ?
                options.sendPageViewEvent :
                true;

            if (location.hostname === 'localhost') {
                options.cookieDomain = 'none';
            }

            if (self.isGA4Enabled) {
                if (options.trackingId)
                    self.ga4Trackers.push(options);
            }
            else {
                if (options.name) {
                    self.trackers.push(options.name);
                } else {
                    self.trackers.push(null);
                }
            }

            if (options.sampleRate) {
                options.sampleRate = Number(options.sampleRate);
            }

            _injectGoogleAnalyticsScript(options);

            if (options.properties) {
                self.setProperties({
                    properties: options.properties,
                    trackerName: options.name,
                    name: options.name,
                    trackingId: options.trackingId
                });
            }

            _injectPageChangeTrackingCode(options, self);

            if (options.sendPageViewEvent) {
                self.trackCurrentPageView(options);
            }
        }

        self.setProperties = function (options) {
            if (options.sendToAllTrackers) {
                self.sendToAllTrackers('setProperties', options);
                return;
            }

            if (self.isGA4Enabled) {
                if (!options.trackingId) {
                    if (options.name)
                        options.trackingId = self.findTrackingId(options.name);
                }
                var trackerPropertiesExist = self.trackerProperties.map(o => o.trackingId);
                if (trackerPropertiesExist && trackerPropertiesExist.indexOf(options.trackingId) == -1) {//insert tracker properties
                    var trackerProperty = { name: options.name, trackingId: options.trackingId };
                    if (options.properties)
                        trackerProperty.properties = Object.assign({}, options.properties);
                    self.trackerProperties.push(trackerProperty);
                }
                else if (options.properties) {//update tracker properties
                    var properties = findpropertiesForCurrentTracking(options.trackingId);
                    if (properties) {
                        for (const [key, value] of Object.entries(options.properties)) {
                            if (Object.keys(properties).indexOf(key) == -1)
                                properties[key] = value;
                            else if (properties[key] != options.properties[key])
                                properties[key] = options.properties[key];
                        }
                    }
                }
            }
            else {
                var trackerName = _applyTracker(options.name);
                ga(trackerName + 'set', options.properties);
            }
        }

        self.trackPageView = function (url, trackerName, trackingId) {
            if (self.isGA4Enabled) {
                if (!trackingId) {
                    if (trackerName)
                        trackingId = self.findTrackingId(trackerName);
                }
                var eventData = {
                    send_to: trackingId, page_location: url
                }
                var properties = findpropertiesForCurrentTracking(trackingId);
                if (properties)
                    $.extend(eventData, properties);
                gtag('event', 'page_view', eventData);
            }
            else {
                trackerName = _applyTracker(trackerName);
                ga(trackerName + 'send', 'pageview', {
                    'page': url
                });
            }
        }

        self.trackCurrentPageView = function (options) {
            if (_suppressTrack(options, self) && !options.ignoreExcludedRoutes) {
                return;
            }
            if(self.isGA4Enabled)
                self.trackPageView(window.location.href, options.name, options.trackingId);
            else
                self.trackPageView(window.location.href, options.name);
        }

        self.trackVirtualPageView = function (options) {

            if (options.sendToAllTrackers) {
                self.sendToAllTrackers('trackVirtualPageView', options);
                return;
            }
            if (self.isGA4Enabled) {
                if (!options.trackingId) {
                    if (options.name)
                        options.trackingId = self.findTrackingId(options.name);
                }
                options.properties = { dimension4: prefixes.virtualDimensionPrefix + options.page };
                self.setProperties(options);
                var eventData = {
                    send_to: options.trackingId,
                    page_location: prefixes.virtualPagePrefix + options.page,
                    page_title: options.title
                };
                var properties = findpropertiesForCurrentTracking(options.trackingId);
                if (properties)
                    $.extend(eventData, properties);                
                gtag('event', 'page_view', eventData);
            }
            else {
                var trackerName = _applyTracker(options.name);
                self.setProperties({
                    properties: { dimension4: prefixes.virtualDimensionPrefix + options.page },
                    name: options.name
                });
                ga(trackerName + 'send', 'pageview', {
                    page: prefixes.virtualPagePrefix + options.page,
                    title: options.title
                });
            }
        }

        function findpropertiesForCurrentTracking(trackingId) {
            var options = self.trackerProperties.find(opt => opt.trackingId === trackingId);
            return options && options.properties;
        }

        self.trackEvent = function (category, action, eventLabel, trackerName, data) {
            if (self.isGA4Enabled) {
                var trackingId;
                if (!trackerName)
                    trackingId = self.ga4Trackers[0].trackingId;//Neogov tracker to get first registered, if no tracker present
                else
                    trackingId = self.findTrackingId(trackerName);
                var eventData = {
                    'send_to': trackingId,
                    'event_category': category,
                    'event_label': eventLabel
                };
                var properties = findpropertiesForCurrentTracking(trackingId);
                if (properties)
                    $.extend(eventData, properties);
                if (data)
                    $.extend(eventData, data);
                gtag('event', action, eventData);
            }
            else {
                trackerName = _applyTracker(trackerName);

                ga(trackerName + 'send', 'event', category, action, eventLabel, data);
            }
        }

        self.findTrackingId = function (trackerName) {
            var ga4Tracker = self.ga4Trackers.find(t => t.name == trackerName);
            return ga4Tracker && ga4Tracker.trackingId;
        }

        self.trackTiming = function (category, variable, value, trackerName) {
            if (self.isGA4Enabled)//ONLINE-12843 - Timing not available in GA4, captured as custom event
            {
                self.trackEvent(
                    category,
                    'user_timings',
                    variable,
                    trackerName,
                    { user_timing: value / 1000 } //To display value in seconds in  user_timing custom dimension
                );
            }
            else {
                trackerName = _applyTracker(trackerName);

                ga(trackerName + 'send', 'timing', category, variable, value);
            }
        }

        self.trackApplicationEvent = function (options) {
            if (options.sendToAllTrackers) {
                self.sendToAllTrackers('trackApplicationEvent', options);
                return;
            }

            if (!options.eventLabel) {
                options.eventLabel = _getCurrentArea();
            }

            self.trackEvent(
                self.categories.application,
                options.action,
                options.eventLabel,
                options.name,
                options.data
            );
        }

        self.trackJobSearchEvent = function (action, eventLabel, trackerName) {
            if (!eventLabel) {
                eventLabel = _getCurrentArea();
            }
            self.trackEvent(self.categories.jobSearch, action, eventLabel, trackerName);
        }

        self.trackCareerJobSearchEvent = function (action, eventLabel, trackerName) {
            if (!eventLabel) {
                eventLabel = _getCurrentArea();
            }   
            self.trackEvent(self.categories.careerJobSearch, action, eventLabel, trackerName);
        }

        self.trackLoginEvent = function (action, eventLabel, trackerName) {
            if (!eventLabel) {
                eventLabel = _getCurrentArea();
            }
            self.trackEvent(self.categories.login, action, eventLabel, trackerName);
        }

        self.trackProfileCreationEvent = function (action, eventLabel, trackerName) {
            eventLabel += " " + _getCurrentArea();
            self.trackEvent(gJobs.common.analytics.categories.profileCreation, action, eventLabel, trackerName);
        }

        self.setUserIdentity = function (identity) {
            throw new Error('self action is not supported');
        }

        self.registerUserIdentity = function (identity) {
            throw new Error('This action is not supported');
        }
        self.removeProperty = function (trackerName, propertyName) {
            var trackingId = self.findTrackingId(trackerName);
            if (trackingId) {
                var properties = findpropertiesForCurrentTracking(trackingId);
                if (properties[propertyName])
                    delete properties[propertyName];
            }
        }

        self.messages = {
            captchaMessage: 'Captcha Modal Shown'
        }

        self.trackers = [];
        self.ga4Trackers = [];
        self.categories = categories
        self.trackerProperties = [];        

        return self;
    })();

})(window);;
(function () {
    'use strict';


    var currentDeviceClass;


    var toggleDeviceClass = function (deviceClass, deviceOrientation, state) {
        if (state) {
            currentDeviceClass = deviceClass;
        }

        $('html')
            .toggleClass('device-' + deviceClass, state)
            .toggleClass('device-orientation-' + deviceOrientation, state);
    };

    var getCurrentDeviceClasses = function () {
        var classes = $('html').attr('class');
        var classNames = classes.split(/\s+/);

        var deviceClasses = $.map(classNames, function (className) {
            var matches = className.match(/device-(\w[\w-]*)/) || [];
            var deviceClass = matches[1];

            return deviceClass;
        });

        return deviceClasses;
    };

    var resetDeviceClasses = function () {
        var deviceClasses = getCurrentDeviceClasses();

        $.each(deviceClasses, function () {
            toggleDeviceClass(this, null, false);
        });
    };



    /*
        Initialization
    */
    (function () {
        resetDeviceClasses();
    }());


    
    /*
        Large Desktop
    */
    enquire.register('screen and (min-width: 1500px)', {

        match: function () {
            toggleDeviceClass('large-desktop', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('large-desktop', 'portrait', false);
        }

    });


    /*
        Desktop
            Matches all medium-sized desktop screens (Laptops).
    */
    enquire.register('screen and (min-width: 1200px) and (max-width: 1499px)', {

        match: function () {
            toggleDeviceClass('desktop', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('desktop', 'portrait', false);
        }

    });


    /*
        Small Desktop
            Matches small desktop screens.
    */
    enquire.register('screen and (min-width: 980px) and (max-width: 1199px)', {

        match: function () {
            toggleDeviceClass('small-desktop', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('small-desktop', 'portrait', false);
        }

    });


    /*
        Tablets
    */
    enquire.register('screen and (min-width: 768px) and (max-width: 979px)', {

        match: function () {
            toggleDeviceClass('tablet', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('tablet', 'portrait', false);
        }

    });


    /*
        Phone
    */
    enquire.register('screen and (max-width: 767px)', {

        match: function () {
            toggleDeviceClass('phone', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('phone', 'portrait', false);
        }
    });
    
    /*
        Small Phone
    */
    enquire.register('screen and (max-width: 480px)', {

        match: function () {
            toggleDeviceClass('small-phone', 'portrait', true);
        },

        unmatch: function () {
            toggleDeviceClass('small-phone', 'portrait', false);
        }
    });


    namespace('gJobs').common.responsive = {
        is: function (deviceClass) {
            return (deviceClass === currentDeviceClass);
        }
    };


}());;
(function (window, undefined) {
    'use strict';

    if (revampedDesign) {
        var currentScreenWidth = $(window).width(),
            $header = $('#header'),
            $usernameLink = $header.find('.username-link').last(),
            mobileCollapseClass = "mobile-collapsed",
            $signInBlock = $('#sign-in-block'),
            menuWidth = 0,
            $notificationContainer = $('#screen-reader-message'),
            desktopScreenWidth = 980,
            $menuExpander = $("#login-menu-expander, #applicant-menu-expander"),
            $headerContainer = $('.header-navigation-container-unauthorized, .navbar'),
            $authenticatedNav = $('.authenticated-nav'),
            $skipToContent = $('#skip-to-content-button'),
            $signInOverlay = $('.sign-in-overlay'),
            $headerOverlay = $('.header-overlay'),
            $applicationMenuList = $('.application-menu-link ul.inner-menu-list'),
            applicationMenuDesktopListItemsClassName = "visible-desktop",
            applicationMenuDesktopListItems = [],
            $lastTabbableElement,
            isDropdownOpen = false,
            signInBlockWidth = $('#sign-in-block').width(),
            $firstInnerMenuItem = $header.find('ul.application-menu-items li').not('.visible-desktop').first().find('a');

        $header.removeClass(mobileCollapseClass);

        function detachApplicationMenuDesktopListItems() {
            if (applicationMenuDesktopListItems.length === 0) {
                $applicationMenuList
                    .find("li." + applicationMenuDesktopListItemsClassName)
                    .each(function (index, listItem) {
                        var nextSibling = $(listItem).next();
                        var prevSibling = $(listItem).prev();

                        if (nextSibling.hasClass(applicationMenuDesktopListItemsClassName) || nextSibling.length === 0) {
                            nextSibling = null;
                        }

                        if (prevSibling.hasClass(applicationMenuDesktopListItemsClassName) || prevSibling.length === 0) {
                            prevSibling = null;
                        }

                        applicationMenuDesktopListItems.push(
                            {
                                element: listItem,
                                nextSibling: nextSibling,
                                prevSibling: prevSibling
                            }
                        )
                    }).detach();
            }
        }

        if (currentScreenWidth < desktopScreenWidth) {
            detachApplicationMenuDesktopListItems();
        }

        if ($('html').hasClass('device-phone') || $('html').hasClass('device-tablet')) {
            $headerContainer.css('display', 'none');
        }

        $firstInnerMenuItem.on("keydown", function (e) {
            if (e.keyCode === $.ui.keyCode.UP) {
                var $outerMenuListItems = $header.find('ul:first').find('li').not('.inner-menu-list-item, .visible-desktop, .application-menu-link');
                var $lastListItemOuterMenu = $outerMenuListItems.last();

                gJobs.focusService.setFocus($lastListItemOuterMenu.find('a'));
            }

            if (e.keyCode === $.ui.keyCode.DOWN) {
                var $nextListItemInnerMenu = $header.find('li.inner-menu-list-item').first().next();

                gJobs.focusService.setFocus($nextListItemInnerMenu.find('a'));
            }
        });

        $signInOverlay.removeClass('hidden-phone');

        $headerOverlay.on('click', function () {
            gJobs.responsive.closeMenu();
            return false;
        });

        $skipToContent.click(function () {
            if (isDropdownOpen)
                gJobs.responsive.closeMenu();
        });

        namespace('gJobs').responsive = {
            openMenu: function () {
                gJobs.screenReadersService.setNotification($notificationContainer, 'Menu is opened. Press tab to move to the menu', '', true, true);
                $authenticatedNav.addClass('scrollable-list');
                if ($('.device-phone') && $('.device-phone').length > 0) {
                    $('.device-phone').css('overflow-y', 'hidden');
                }
                $('body').css('overflow-y', 'hidden');
                $menuExpander.attr('aria-label', 'Press enter to close the menu');
                $headerContainer.animate({
                    height: 'toggle',
                });
                $menuExpander.removeClass('ss-rows');
                $menuExpander.addClass('ss-delete');
                $headerOverlay.show();
                var tabbableElements = $headerContainer.find(':tabbable');
                gJobs.arrowsNavigationService.addArrowsNavigation($menuExpander.add(tabbableElements));
                if (!$lastTabbableElement || $lastTabbableElement.get(0) != tabbableElements.last().get(0)) {
                    $lastTabbableElement = tabbableElements.last();

                    $lastTabbableElement.on('keydown', function (e) {
                        if (e.keyCode === $.ui.keyCode.TAB && !e.shiftKey)
                            gJobs.responsive.closeMenu();
                    });
                }
                setTimeout(function () {
                    tabbableElements.first().focus();
                }, 300);
                isDropdownOpen = true;
            },
            closeMenu: function (skipAnimation, preventBodyScrollYChange) {
                gJobs.screenReadersService.setAriaLiveNotification('Menu is closed');
                if (!preventBodyScrollYChange) {
                    if ($('.device-phone') && $('.device-phone').length > 0) {
                        $('.device-phone').css('overflow-y', 'auto');
                    } 
                    $('body').css('overflow-y', 'auto');
                }
                $menuExpander.attr('aria-label', '');
                if (skipAnimation) {
                    $headerContainer.css('display', '');
                }
                else if ($headerContainer.is(":visible") && ($('html').hasClass('device-phone') ||
                    $('html').hasClass('device-tablet'))) {
                    $headerContainer.animate({
                        height: 'toggle',
                    });
                }

                $menuExpander.attr('aria-label', 'Press enter to open the menu');
                $menuExpander.removeClass('ss-delete');
                $menuExpander.addClass('ss-rows');
                $headerOverlay.hide();
                isDropdownOpen = false;
                if ($('.header-navigation-container-unauthorized').length)
                    $('.header-navigation-container-unauthorized').scrollTop(0);
            },
            openSignInForm: function (callback) {
                gJobs.responsive.closeMenu();
                $signInBlock.css('right', 0);
                $signInBlock.slideDown(function () {
                    $header.animate({
                        scrollTop: $signInBlock.offset().top
                    }, callback);
                });
            },
            closeSignInForm: function (callback) {
                $signInBlock.slideDown(function () {
                    $header.animate({
                        scrollTop: 0
                    }, callback);
                });
            }
        };

        function handleFacetFilterExpanderClick(event) {

            if (event.currentTarget.innerText === "Show filter") {
                gJobs.screenReadersService.setAriaLiveNotification("Filter is Shown");
            }
            else {
                gJobs.screenReadersService.setAriaLiveNotification("Filter is Hidden");
            }


            $('#facet-container').toggle('show');
            $('.show-filter-label').toggle('show');
            $('.hide-filter-label').toggle('show');
        }

        $('.filter-expander')
            .on('click', '.show-hide-filter-btn', handleFacetFilterExpanderClick)
            .keypress(function (event) {
                if (event.keyCode === $.ui.keyCode.ENTER) handleFacetFilterExpanderClick(event);
            });


        function handleMenuInteraction() {
            if ($headerContainer.is(":visible") == false) {
                gJobs.responsive.openMenu();
            } else {
                gJobs.responsive.closeMenu();
            }
        }

        $menuExpander.on('click', function () {
            handleMenuInteraction();
        });

        $menuExpander.keydown(function (e) {
            if (e.keyCode === $.ui.keyCode.ENTER) {
                handleMenuInteraction();
                e.preventDefault();
            }
        })

        $(document)
            .keydown(function (e) {
                if (
                    e.keyCode === $.ui.keyCode.ESCAPE
                    && !$header.hasClass(mobileCollapseClass)
                    && $headerContainer.is(":visible")
                    && $("html").is(".device-tablet, .device-phone")
                ) {
                    gJobs.responsive.closeMenu();
                    $menuExpander.focus();
                }

                if (e.keyCode === $.ui.keyCode.TAB && e.target.id === "employer-login-link") {
                    // Tab has been hit on the last link in the menu while not signed in.
                    // Close the sign-in form if it's open so the close button can be visible once again
                    gJobs.responsive.closeSignInForm();
                }
            })
            .click(function (e) {
                if (e.target === $('html')[0] && !$header.hasClass(mobileCollapseClass)) {
                    gJobs.responsive.closeMenu();
                }
            });

        $(window).resize(function () {
            if ($headerContainer.css('display') != 'none') {
                var skipAnimation = true;
                var preventBodyScrollYChange = $('#supplemental-attachments-flyout-content:visible').length > 0;
                gJobs.responsive.closeMenu(skipAnimation, preventBodyScrollYChange);
            }

            var prevScreenWidth = currentScreenWidth;
            currentScreenWidth = $(window).width();
            if (prevScreenWidth != currentScreenWidth) {
                var lastInsertedElement;

                if (currentScreenWidth >= desktopScreenWidth) {
                    if (applicationMenuDesktopListItems.length > 0) {
                        applicationMenuDesktopListItems.forEach(function (listItem, index) {
                            if (index === 0) {
                                lastInsertedElement = listItem.element;

                                if (listItem.nextSibling !== null) {
                                    $(listItem.element).insertBefore(listItem.nextSibling);
                                } else if (listItem.prevSibling !== null) {
                                    $(listItem.element).insertAfter(listItem.prevSibling);
                                } else {
                                    $(listItem.element).prependTo($applicationMenuList);
                                }
                            } else {
                                if (listItem.nextSibling !== null) {
                                    $(listItem.element).insertBefore(listItem.nextSibling);
                                } else if (listItem.prevSibling !== null) {
                                    $(listItem.element).insertAfter(listItem.prevSibling);
                                } else {
                                    $(listItem.element).insertAfter(lastInsertedElement);
                                }
                            }
                        });

                        applicationMenuDesktopListItems.length = 0;
                    }

                    $headerContainer.css('display', '');
                }
                else {
                    detachApplicationMenuDesktopListItems();

                    if ($signInBlock.css('display') !== 'none') {
                        $signInBlock.css('display', 'none');
                    }

                    $headerContainer.css('display', 'none');
                }
            }
        });

        $(document)
            .on(Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register,
                function () {
                    $menuExpander.toggleClass('hide');
                });

        $(document).ready(function () {
            menuExpanderWidth = $menuExpander.outerWidth();
            menuWidth = currentScreenWidth
                - menuExpanderWidth;
        });
    }
    else {
        var currentScreenWidth = $(window).width(),
            $header = $('#header'),
            $usernameLink = $header.find('.username-link').last(),
            mobileCollapseClass = "mobile-collapsed",
            $signInBlock = $('#sign-in-block'),
            menuWidth = 0,
            $notificationContainer = $('#screen-reader-message'),
            mobileScreenWidth = 767,
            $menuExpander = $("#menu-expander"),
            menuExpanderWidth = 0,
            mobileCollapseClass = "mobile-collapsed";

        namespace('gJobs').responsive = {
            openMenu: function () {
                gJobs.screenReadersService.setNotification($notificationContainer, 'Menu is opened. Press tab to move to the menu', '', true, true);
                $menuExpander.attr('aria-label', 'Press enter to close the menu');
                $menuExpander.css('position', 'fixed');
                $header.animate({
                    width: menuWidth,
                });
                $('body').animate(
                    {
                        left: currentScreenWidth,
                    },
                    function () {
                        $("#content, #footer").toggle();
                    });
                $menuExpander.animate({
                    left: menuWidth,
                });
                $usernameLink.css('display', 'none');
                $header.removeClass(mobileCollapseClass);
                $menuExpander.removeClass('ss-rows');
                $menuExpander.addClass('ss-delete');
                gJobs.arrowsNavigationService.removeArrowsNavigation();
            },
            closeMenu: function (skipAnimation) {
                gJobs.screenReadersService.setAriaLiveNotification('Menu is closed');
                $menuExpander.attr('aria-label', '');
                $menuExpander.focus();
                $("#content, #footer").toggle();
                $header.animate({
                    width: 0,
                });
                $('body').animate(
                    {
                        left: 0,
                    },
                    function () {
                        $header.addClass(mobileCollapseClass);
                        if ($('#content, #footer').css('display') == 'none') {
                            $("#content, #footer").toggle();
                        }
                    });
                $menuExpander.animate(
                    {
                        left: 0,
                    },
                    function () {
                        $menuExpander.css('position', 'absolute');
                        $menuExpander.attr('aria-label', 'Press enter to open the menu');
                    });
                $menuExpander.removeClass('ss-delete');
                $menuExpander.addClass('ss-rows');
            },
            openSignInForm: function (callback) {
                $header.animate({
                    width: "100%"
                });
                $menuExpander.animate(
                    {
                        left: $(window).width()
                    },
                    function () {
                        $signInBlock.slideDown(function () {
                            $header.animate({
                                scrollTop: $signInBlock.offset().top
                            }, callback);
                        });
                    });
            },
            closeSignInForm: function (callback) {
                if (!$header.hasClass(mobileCollapseClass)) {
                    $signInBlock.slideUp(function () {
                        $header.animate({
                            width: menuWidth
                        });
                        $menuExpander.animate({
                            left: menuWidth
                        }, callback);
                    });
                } else {
                    callback();
                }
            },
            updateMenuLocation: function () {
                $header.width(menuWidth);
                $menuExpander.css('left', menuWidth);
            },
            updateMenuLocationSignIn: function () {
                $header.width('100%');
                $menuExpander.css('left', currentScreenWidth);
            }
        };

        $('.filter-expander')
            .on('click', '.show-hide-filter-btn', function () {
                $('#facet-container').toggle('show');
                $('.show-filter-label').toggle('show');
                $('.hide-filter-label').toggle('show');
            });

        $menuExpander
            .on('click', function () {
                if ($header.hasClass(mobileCollapseClass)) {
                    gJobs.responsive.openMenu();
                } else {
                    gJobs.responsive.closeMenu();
                }
            })
            .keydown(function (e) {
                if (e.keyCode === $.ui.keyCode.ENTER) {
                    $menuExpander.trigger('click');
                }

                if (e.keyCode === $.ui.keyCode.TAB) {
                    // After tabbing on the close button, focus the first link within the sign in form
                    if (!$header.hasClass(mobileCollapseClass)) {
                        e.preventDefault();
                        e.stopPropagation();

                        var tabbableElements = $('#header').find(':tabbable');
                        if (!e.shiftKey)
                            tabbableElements.first().focus();
                        else
                            tabbableElements.last().focus();
                    }
                }
            });

        $(document)
            .keydown(function (e) {
                if (e.keyCode === $.ui.keyCode.ESCAPE && !$header.hasClass(mobileCollapseClass)) {
                    gJobs.responsive.closeMenu();
                }

                if (e.keyCode === $.ui.keyCode.TAB && e.target.id === "employer-login-link") {
                    // Tab has been hit on the last link in the menu while not signed in.
                    // Close the sign-in form if it's open so the close button can be visible once again
                    gJobs.responsive.closeSignInForm();
                }
            })
            .click(function (e) {
                if (e.target === $('html')[0] && !$header.hasClass(mobileCollapseClass)) {
                    gJobs.responsive.closeMenu();
                }
            });

        $(window).resize(function () {

            currentScreenWidth = $(window).width();
            menuWidth = currentScreenWidth - menuExpanderWidth;

            if (currentScreenWidth > mobileScreenWidth) {
                if ($usernameLink.css('display') == 'none') {
                    $usernameLink.css('display', 'list-item');
                }

                $("#content, #footer").css('display', 'block');
            }
            else {
                if (!$header.hasClass(mobileCollapseClass)) {
                    if ($signInBlock.css('display') == 'none') {
                        gJobs.responsive.updateMenuLocation();
                    } else {
                        gJobs.responsive.updateMenuLocationSignIn();
                    }
                    $usernameLink.css('display', 'none');
                    $("#content, #footer").css('display', 'none');
                }
            }
        });

        $(document).ready(function () {
            menuExpanderWidth = $menuExpander.outerWidth();
            menuWidth = currentScreenWidth
                - menuExpanderWidth;

            $menuExpander.popover();
        });
    }

})(window);;
(function (window, undefind) {
    'use strict';

    jQuery(document).ready(function() {
        var resourcesSectionSelector = ".resources-section-container",
            applicationInfoContainerSelector = ".application-info-container",
            socialContainerPageSelector = ".social-container-page",
            getResourcesSectionEndpoint = "/browse/getResourcesSection";

        if ($(resourcesSectionSelector).length) {
            $.ajax({
                type: 'GET',
                url: getResourcesSectionEndpoint
            })
            .done(function(resourcesSectionMarkup) {
                if (resourcesSectionMarkup) {
                    $(resourcesSectionSelector).html(resourcesSectionMarkup);
                    $(applicationInfoContainerSelector).css({ backgroundColor: 'white' });
                    $(socialContainerPageSelector).css({ backgroundColor: '#fafaf9' });
                }
            });
        }

        var gjobsResourcesIframeSelector = "#resources-iframe";
        var iframe = jQuery(gjobsResourcesIframeSelector)[0];    

        if (gJobs.browserDetector.isIE()) {
            getGjobsResourcesIframeScrollHeight();
        }
            
        function getGjobsResourcesIframeScrollHeight() {
            if (iframe) {
                iframe.style.height = "auto";
                iframe.contentWindow.postMessage(
                    { messageType: "getScrollHeight" },
                    "*"
                );
            }
        }
    
        window.addEventListener("message", function (e) {
            if (e.data.messageType === "gjobsResourcesScrollHeight") {
                if (iframe) {
                    iframe.style.height = e.data.iframeScrollHeight + "px";
                }
            }
        });
    
        jQuery(gjobsResourcesIframeSelector).on('load', function () {
            getGjobsResourcesIframeScrollHeight();
        });
    
        jQuery(window).resize(function () {
            getGjobsResourcesIframeScrollHeight();
        });
    });
})(window);
;
(function (window, undefined) {
    'use strict';

    var $browseContainer = $('#tab-content-container'),
        $criteriaLocationContainer = $('.criteria-location', $browseContainer),
        $criteriaLinks = $('.criteria-header', $criteriaLocationContainer).next(),
        $locationSearch = $('#location-search-input'),
        pageprefix = 'browse';

    $('.criteria-header').next().on('hidden.bs.collapse', function () {
        //IE8 needs to recalculate layout after the collapse is hidden (PF-8981)
        $(document).trigger('layoutUpdated');
    });

    $browseContainer
        .find('.criteria-location')
        .find('.criteria-header').click(function () {
            var expanded =
                $('.criteria-header')
                    .not('.collapsed').not(this);

            expanded.next().collapse('hide');
            expanded.addClass('collapsed');

            $locationSearch.val($.trim($(this).text()));
        });

    $browseContainer
        .find('.nav [id*=' + pageprefix + ']')
        .click(function (e) {
            var route = $(this).attr('href');

            gJobs.router.navigate(route);

            e.preventDefault();

            var params = route.split('/');
            updateCriteriaSelection(params[params.length - 1]);

            $(document).trigger('layoutUpdated');
        });

    $criteriaLinks.on('show.bs.collapse', function () {
        var $this = $(this);

        var locationName = getLocationName($this);

        gJobs.screenReadersService.setAriaLiveNotification(
            "List with available locations for " + locationName + " has been opened"
        );

        $this.find('.criteria-detail-container a').removeAttr('tabindex').attr('aria-hidden', 'false');

        var $locationLink = $this.closest('li').children('a');
        $locationLink.attr('aria-label', 'Press Enter to collapse List of location available under ' + $locationLink.text().trim());
        $locationLink.attr('aria-expanded', true);
    });

    $criteriaLinks.on('hide.bs.collapse', function () {
        var $this = $(this);

        var locationName = getLocationName($this);

        gJobs.screenReadersService.setAriaLiveNotification(
            "List with available locations for " + locationName + " has been closed"
        );

        $this.find('.criteria-detail-container a').attr('tabindex', '-1').attr('aria-hidden', 'true');
        
        var $locationLink = $this.closest('li').children('a');
        $locationLink.attr('aria-label', 'Press Enter to expand List of location available under ' + $locationLink.text().trim());
        $locationLink.attr('aria-expanded', false);
    });

    function getLocationName($locationsList) {
        return $locationsList.parent().find('a').first().text();
    }

    function updateCriteriaSelection(criteria) {
        criteria = criteria ? criteria : 'category';

        $(".select-criteria-label").text("Press enter to activate.");
        $("#browse-" + criteria).children(".select-criteria-label").text("");
        $(".criteria-selected-announcement").text("Press tab to navigate to " + criteria + " selection.");
    }

    $(document).ready(function () {
        var path = document.location.pathname;
        var index = path.indexOf(pageprefix);
        if (index >= 0) {
            path = path.substring(index);
            var params = path.split('/');

            updateCriteriaSelection(params[1]);

            if (params.length > 1) {
                $("#" + pageprefix + "-" + params[1]).next().click();
                $(document).trigger('layoutUpdated');
            }
        } else {
            updateCriteriaSelection();
        }
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function FocusService() {
        var self = this;

        var NO_RESTRICT_CLASS = 'no-restrict-focus',
            LAST_FOCUSABLE_ELEMENT_ID = 'last-focusable-element',
            TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT = 'keydown.tabFocusNavigation',
            SHIFT_TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT = 'keydown.shiftTabFocusNavigation';


        var $previousElement = [];
        var restrictFocusStack = [];

        var currentFocusedElement = $();

        self.LAST_TABBABLE_ELEMENT_CLASS = 'last-tabble-element';

        self.setFocus = function ($focusTarget) {
            $previousElement.push($(document.activeElement));
            $focusTarget.focus();
        };

        self.setFocusOnEmptyElement = function (element, onRemove) {
            var $emptyFocusableSpan = $('<span class="hide-notification no-restrict-focus" tabindex="-1">&nbsp;</span>');
            
            if (element) {
                $(element).append($emptyFocusableSpan);
            } else {
                $('body').append($emptyFocusableSpan);
            }

            $emptyFocusableSpan.focus();
            $emptyFocusableSpan.one('focusout', function () {
                $emptyFocusableSpan.remove();
                
                if (onRemove) {
                    onRemove();
                }
            });
        }

        self.restoreFocus = function (options) {
            if ($previousElement.length !== 0 && !self.dontRestoreFocus) {
                var $restoringElement = $previousElement.pop();
                var isLastElement = $previousElement.length === 0;
                if (options && $.isFunction(options.focusRestoringCallback)) {
                    options.focusRestoringCallback($restoringElement, isLastElement);
                }
                setTimeout(() => $restoringElement.focus(), 200);
                if (options && $.isFunction(options.focusRestoredCallback)) {
                    options.focusRestoredCallback($restoringElement, isLastElement);
                }
            }
        };

        self.replaceLastElement = function ($newElement) {
            if ($previousElement.length) {
                $previousElement[$previousElement.length - 1] = $newElement;
            }
        };

        self.restrictFocus = function ($container, onOutsideElementFocused, isModal) {
            if (!$container || $container.length === 0) {
                return null;
            }

            if (restrictFocusStack.length === 0) {
                document.addEventListener('focus', restrictFocusHandler, true);
            }

            var firstTabbable, lastTabbable = null;
            if (isModal) {
                firstTabbable = getFirstTabbableElement($container);
                lastTabbable = getLastTabbableElement($container);
                self.setFocusOnKeydown({ $element: firstTabbable, $targetElement: lastTabbable, shift: true });
                self.setFocusOnKeydown({ $element: lastTabbable, $targetElement: firstTabbable, shift: false });
            }

            restrictFocusStack.push({
                $container: $container,
                onOutsideElementFocused: onOutsideElementFocused,
                isModal: isModal,
            });

            return function () {
                var entry = restrictFocusStack.pop();
                if (restrictFocusStack.length === 0) {
                    //when no elements are left in stack, there's no point in handling document's focus events anymore
                    document.removeEventListener('focus', restrictFocusHandler, true);
                }
            };
        };

        self.restoreBrowserControlsFocusBehavior = function () {
            $('#' + LAST_FOCUSABLE_ELEMENT_ID).parent().remove();
        };

        self.enableFocusForBrowserControls = function () {
            self.restoreBrowserControlsFocusBehavior();

            var notification = "Press tab to move to the browser's controls";
            var notificationTextElement =
                $('<p>')
                    .attr({
                        'class': 'visible-on-focus-text'
                    })
                    .text(notification);
            var lastFocusableElementContainer =
                $('<div>')
                    .attr({
                        'aria-label': notification,
                        'role': 'navigation'
                    })
                    .appendTo('body');
            var lastFocusableElement =
                $('<div>')
                    .attr({
                        'id': LAST_FOCUSABLE_ELEMENT_ID,
                        'class': NO_RESTRICT_CLASS + ' visible-on-focus',
                        'tabindex': '0',
                        'role': 'link'
                    })
                    .append(notificationTextElement)
                    .on('keydown', keydownHandler)
                    .appendTo(lastFocusableElementContainer)
                    .visibleOnFocus();
        };

        self.setFocusOnKeydown = function(options) {
            if (!(options.$element && options.$element.length) ||
                !(options.$targetElement && options.$targetElement.length)) {
                return;
            }

            options.shift = options.shift || false;

            if (options.$previousElement && options.$previousElement.length) {
                self.removeFocusOnKeydownHandler(options.$previousElement, options.shift)
            }

            function targetFocusHandler(e) {
                if (options.$targetElement.is(':visible')) {
                    if (e.keyCode == $.ui.keyCode.TAB) {
                        if (options.shift === e.shiftKey) {
                            e.preventDefault();
                            options.$targetElement.focus();
                        }
                    }
                }
            }

            self.removeFocusOnKeydownHandler(options.$element, options.shift);

            options.$element.on(
                options.shift ? TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT : SHIFT_TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT,
                targetFocusHandler
            );
        }

        self.removeFocusOnKeydownHandler = function($element, shift) {
            if (!$element || !$element.length) return;
            $element.off(shift ? TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT : SHIFT_TAB_FOCUS_NAVIGATION_KEYDOWN_EVENT);
        }

        function keydownHandler(e) {
            // Skip to the last tabbable in restricted container on Shift + Tab.
            var code = (e.keyCode ? e.keyCode : e.which);
            var $restrictContainer =
                restrictFocusStack[restrictFocusStack.length - 1] &&
                restrictFocusStack[restrictFocusStack.length - 1].$container;
            if (code === $.ui.keyCode.TAB && e.shiftKey === true && $restrictContainer) {
                e.preventDefault();
                getLastTabbableElement($restrictContainer).focus();
            }
        }

        function restrictFocusHandler(e) {
            if (restrictFocusStack.length === 0) {
                return;
            }

            var flyout = restrictFocusStack[restrictFocusStack.length - 1];

            var $target = $(e.target);
            if (isValidFocusableElement($target, flyout.$container, flyout.isModal)) {
                currentFocusedElement = $target;
                return;
            }

            e.stopPropagation();

            var $firstTabbableInContainer = getFirstTabbableElement(flyout.$container);
            var isInsideFlyout = flyout.$container.find(currentFocusedElement).length !== 0;

            if (flyout.isModal || !isInsideFlyout) {
                $firstTabbableInContainer.focus();
            }

            if (flyout.onOutsideElementFocused) {
                flyout.onOutsideElementFocused();
            }
        }

        function isValidFocusableElement($target, $topmostContainer, ignoreSpecialClass) {
            var isInContainer = $.contains($topmostContainer[0], $target[0]);
            var hasSpecialClass = $target.hasClass(NO_RESTRICT_CLASS);
            var isRootElement = $target.is('html') || $target.parent().length === 0; // Preventing focus trap in browser controls
            return isInContainer || (!ignoreSpecialClass && hasSpecialClass) || isRootElement;
        }

        function getFirstTabbableElement($container) {
            if (!$container || $container.length === 0) {
                return null;
            }

            return $container.find(":tabbable").first();
        }

        function getLastTabbableElement($container) {
            if (!$container || $container.length === 0) {
                return null;
            }

            var $lastTabbableElement = $container.find('.' + self.LAST_TABBABLE_ELEMENT_CLASS);
            if ($lastTabbableElement.length) {
                return $lastTabbableElement;
            }

            return $container.find(":tabbable").last();
        }
    };

    namespace('gJobs').focusService = new FocusService();

})(window);
;
(function (window, undefined) {
    'use strict';

    function ArrowsNavigationService() {
        var self = this;

        self.addArrowsNavigation = function ($elements) {
            $(document).on('keydown', { $elements: $elements }, keydownHandler);
        }

        self.removeArrowsNavigation = function () {
            $(document).off('keydown', keydownHandler);
        }
        
        self.addArrowsNavigationOnElements = function ($elements) {
            $elements.on('keydown', { $elements: $elements }, keydownHandler);
        }

        self.removeArrowsNavigationOnElements = function ($elements) {
            $elements.off('keydown', keydownHandler);
        }
        
        function keydownHandler (e) {
            var isUpKey = e.keyCode === $.ui.keyCode.UP || e.keyCode === $.ui.keyCode.PAGE_UP;
            var isDownKey = e.keyCode === $.ui.keyCode.DOWN || e.keyCode === $.ui.keyCode.PAGE_DOWN;
            if ((!isUpKey && !isDownKey) || e.shiftKey) {
                return;
            }

            var $elements = e.data.$elements;
            var currentIndex = $elements.index($(e.target));

            if (isUpKey && currentIndex > 0 && currentIndex < $elements.length) {
                e.preventDefault();
                $elements.eq(currentIndex - 1).focus();
            } else if (isDownKey && currentIndex >= 0 && currentIndex < ($elements.length - 1)) {
                e.preventDefault();
                $elements.eq(currentIndex + 1).focus();
            }
            e.stopPropagation();
        }
    };

    namespace('gJobs').arrowsNavigationService = new ArrowsNavigationService();

})(window);
;
(function (window, undefined) {
    'use strict';

    function AbstractPageScrollService() {
        var self = this;

        self.getFlyoutScrollContainer = function () {
            return $();
        };

        /*
        metrics = {
            offset,
            position,
            padding,
            containerScroll
        };
        */
        self.scrollToView = function (metrics) {
        };
    }

    namespace('gJobs').AbstractPageScrollService = AbstractPageScrollService;
})(window);;
(function (window, undefined) {
    'use strict';

    var mobileScreenWidth = 767;

    function GJobsPageScrollService() {

        var self = gJobs.AbstractPageScrollService.call(this) || this;

        self.getFlyoutScrollContainer = function () {
            return $("div.flyout-content");
        };

        self.scrollToView = function (metrics) {
            // cover both ordinary apply flyout and incomplete apps flyout
            var $inlinePageElement = $('.incomplete-app-view-page.active .flyout-window-body');

            if ($inlinePageElement.length == 0) {
                var headerElementHeight = $('.navbar').height();
                if (headerElementHeight == null)
                    headerElementHeight = 0;
                if ($(window).width() > mobileScreenWidth) {
                    $('html, body').animate({ scrollTop: metrics.offset.top - headerElementHeight + metrics.padding }, "fast");
                } else {
                    $('html, body').animate({
                        scrollTop: metrics.offset.top + metrics.padding
                    }, "fast");
                }
            } else {
                var $flyout = $('.incomplete-app-view-page.active');
                var $container;

                if ($('html').hasClass('device-phone')) {
                    $container = $flyout;
                    var flyoutHeaderHeight = $flyout.find('.flyout-window-header')
                        .outerHeight();
                    $container.animate({
                        scrollTop: flyoutHeaderHeight + metrics.position.top - metrics.padding
                    }, "fast");
                } else {
                    $container = $flyout.find("div.flyout-content").eq(0);

                    var topPositionInScrollingViewport = metrics.offset.top - $container.offset().top;
                    $container.animate({
                        scrollTop: metrics.containerScroll + topPositionInScrollingViewport - metrics.padding
                    }, "fast");
                }
            }
        };
    }

    namespace('gJobs').pageScrollService = new GJobsPageScrollService();
})(window);;
(function (window, undefined) {
    'use strict';

    function AbstractAreaInfoService() {
        var self = this;

        self.areaNames = {
            GJobs: 'GJobs',
            Career: 'Career Pages',
            Agency: 'Agency Pages'
        };

        self.namespaceNames = {
            GJobs: 'gJobs',
            CareerPages: 'AgencyPages'
        }

        self.getCurrentArea = function () {
        };

        self.getCurrentNamespace = function () {            
        };
    }

    namespace('gJobs').AbstractAreaInfoService = AbstractAreaInfoService;
})(window);;
(function (window, undefined) {
    'use strict';

    function GJobsAreaInfoService() {
        var self = gJobs.AbstractAreaInfoService.call(this) || this;

        var agencyPagesRegExpArray = [
            /^\/jobs\/([^/]+)\/([^/]+)\/agency\/([^/]+)$/,
            /^\/jobs\/([^/]+)\/([^/]+)\/agency\/([^/]+)\/apply((\/\w+)+|\/?)$/,
            /^\/Applications\/([^/]+)\/([^/]+)$/,
            /^\/Applications\/([^/]+)\/apply\/([^/]+)$/,
            /^\/Applications\/Index\/([^/]+)\/apply\/([^/]+)$/,
            /^\/AgencyInbox\/\w+\/{0,1}[\w\/]*$/,
            /^\/ProfileSettings\/([^/]+)$/
        ];

        var agencyPagesQueryParams = [
            "employerFolderName"
        ];

        var currentArea = self.areaNames.GJobs;
        var currentNamespace = self.namespaceNames.GJobs;

        self.getCurrentArea = function () {
            currentArea = isAgencyPagesArea() ? self.areaNames.Agency : currentArea;

            return currentArea;
        };

        function isAgencyPagesArea() {
            var path = window.location.pathname;

            var result = agencyPagesRegExpArray.some(function(currentValue) {
                return currentValue.test(path);
            });

            if (!result) {
                var queryParams = url.get(window.location.search.slice(1), { array: true });

                result = agencyPagesQueryParams.some(function(currentValue) {
                    return queryParams[currentValue];
                });
            }

            return result;
        }

        self.getCurrentNamespace = function () {
            return currentNamespace;
        }
    }

    namespace('gJobs').areaInfoService = new GJobsAreaInfoService();

})(window);;
(function (window, undefined) {
    'use strict';

    namespace('gJobs').isTransitionEventSupported = function() {
        var body = document.body || document.documentElement;
        var style = body.style;

        return style.transition !== undefined ||
            style.WebkitTransition !== undefined ||
            style.MozTransition !== undefined ||
            style.MsTransition !== undefined ||
            style.OTransition !== undefined;
    };
})(window);;
(function (window, undefined) {
    'use strict';

    function PageTabNavigationService() {
        var self = this;

        self.enableScrollForElements = function ($container, tabbableElementSelector, tabbableElementContainer) {
            if (!$container || $container.length === 0) {
                return;
            }

            $container
                .on('mousedown', tabbableElementSelector, function () {
                    $(this).data('isClicking', true);
                })
                .on('focus', tabbableElementSelector, function () {
                    var $this = $(this);

                    if ($this.data('isClicking')) {
                        $this.data('isClicking', false);
                        return;
                    }

                    var $tabbableElementContainer = $this.closest(tabbableElementContainer);

                    if ($tabbableElementContainer.length !== 0) {
                        $tabbableElementContainer[0].scrollIntoView(false);
                    }
                });
        };

        self.adjustNavigationForFixedHeader = function ($container, tabbableElementSelector, tabbableElementContainer) {
            var $fixedHeader = $('.navbar-fixed-top, .navbar'); // revampedDesign. The first header selector is related to old design.
            var $manageBar = $('#manage-bar');
            if (!$fixedHeader.length) {
                $fixedHeader = $('.user-navigation');
            }
            $container.on('focus', tabbableElementSelector || '*', function (event) {
                var $target = $(event.target);

                // In IE click focuses DIV even if div is not focusable (doesn't have tabindex attribute)
                if ($target.is('div') && !$target.attr('tabindex')) {
                    return;
                }

                if ($target.closest($manageBar).length ||
                    $target.closest($fixedHeader).length ||
                    $target.closest('.disable-adjusting-navigation').length ||
                    $target.css('position') === 'fixed') {
                    return;
                }
                var headerHeight = $fixedHeader.height();

                var isManageBarFixed = $manageBar.length &&
                    ($manageBar.closest('.content-container.fixed.search-field-fixed').length ||
                    $(window).scrollTop() > $manageBar.offset().top); // When it is appearing just after flyout is closed

                if (isManageBarFixed) {
                    headerHeight += $manageBar.height();
                }

                var $targetContainer = $target.closest(tabbableElementContainer);
                $targetContainer = $targetContainer.length ? $targetContainer : $target;

                if ($targetContainer.get(0).getBoundingClientRect().top < headerHeight) {
                    var $scrollParent = $targetContainer.scrollParent();
                    if ($scrollParent.is('body')) {
                        $scrollParent = $(window); // Firefox can't scroll body
                    }

                    $scrollParent.scrollTop($targetContainer.offset().top - headerHeight);
                }
                if (!tabbableElementSelector) {
                    event.stopPropagation();
                }
            });
        };
    }

    namespace('gJobs').pageTabNavigationService = new PageTabNavigationService();

})(window);
;
(function (window, undefined) {
    'use strict';

    var pageTypes = {
        searchPage: { type: 'searchPage', urlPart: 'jobs' },
        accountSettings: { type: 'accountSettings', urlPart: 'applications/accountsettings' },
        applications: { type: 'applications', urlPart: 'applications' },
        inbox: {type: "inbox", urlPart: "inbox"},
        agencyInbox: {type: 'agencyInbox', urlPart: "AgencyInbox"},
        accessMembershipLandingPage: { type: "accessMembershipLandingPage", urlPart: "accessmembership" },
        profileSettings: {type: "profileSettings", urlPart: "profileSettings"},
        homePage: { type: 'homePage', urlPart: '' }
    };

    function PageInfoService() {
        var self = this;

        self.getCurrentPageType = function () {
            var path = window.location.pathname;

            for (var page in pageTypes) {
                if (pageTypes.hasOwnProperty(page)) {
                    var pageObject = pageTypes[page];
                    var regExp = new RegExp('^\/' + pageObject.urlPart, 'i');

                    if (regExp.test(path)) {
                        return pageObject;
                    }
                }
            }

            return pageTypes.homePage;
        };

        self.getCurrentAgencyPageFolderName = function () {
            return $('html').data('agency-folder-name')
                || $('#online-application-block').data('employer-folder-name')
                || window.agencyFolderName;
        };

        self.getPageTypes = function () {
            return pageTypes;
        };

        self.isOnApplyPage = function() {
            return window.location.href.toLowerCase().indexOf('/apply') > -1;
        };

        self.isOnPreferencesSectionPage = function() {
            return self.getCurrentPageType().type === pageTypes.accountSettings.type
                && window.location.hash.toLowerCase().indexOf('#preferences') > -1;
        };
    }

    namespace('gJobs').pageInfoService = new PageInfoService();
})(window);
;
(function() {
    'use strict';

    var CONSENT_COOKIE_NAME = 'CookieConsent';
    var cookieConsent = '#cookie-consent';
    var acceptButton = '#cookie-consent .accept-use-of-cookies';

    if ($.cookie(CONSENT_COOKIE_NAME) !== 'true') {
        $(acceptButton).on('click', setCookieConsent);
        $(cookieConsent).removeClass('hidden');

        $(document).ready(function() {
            $(cookieConsent).focus();
        });
    }

    function setCookieConsent() {
        $(cookieConsent).addClass('hidden');
        $.cookie(CONSENT_COOKIE_NAME, 'true', {expires: 365, path: '/'});
    }
})();;
(function(window) {

    $(document).ready(function() {

        var $accessMembershipDialog = $('#access-membership-dialog'),
            $body = $('body'),
            initialBodyClasses = '',
            disableScrollClasses = 'scroll-disable inner-scrollbar';

        function AccessMembershipDialogViewModel(options) {
            var self = this;

            self.init = function (talentSearchPreferences) {
                if (talentSearchPreferences) {
                    self.talentSearchPreferences = talentSearchPreferences;
                }
                else {
                    self.talentSearchPreferences = new OnlineApp.ViewModels.TalentSearchPreferencesViewModel();
                }

                self.talentSearchPreferences.beginEdit(self.talentSearchPreferences);
            };

            self.visible = ko.observable(false).extend({ ignoreOnSerialization: true });

            self.visible.subscribe(function (value) {
                showHideElementsOnDialog(value);
                if (value) {
                    setTimeout(function () {
                        focusOnFistTabbableDialogElement();
                    });
                }
            });

            self.accountUpgraded = ko.observable(false);

            self.accountUpgraded.subscribe(function(value) {
                setTimeout(function() {
                    focusOnFistTabbableDialogElement();
                });
            });

            self.enableAccessMembership = function () {
                self.talentSearchPreferences.editableItem().isAccessMembershipEnabled(true);

                return saveTalentSearchPreferences()
                    .done(function () {
                        self.accountUpgraded(true);
                        $accessMembershipDialog.attr('aria-labelledby','congratulations-tab-header');

                        gJobs.screenReadersService.setAriaLiveNotification(
                            'You have successfully upgraded your account. Congratulations dialog has been opened.'
                        );

                        gJobs.common.analytics.trackEvent(
                            'Access Membership Popup',
                            'Upgraded',
                            'After removing price label'
                        );

                        if (window.enableStickyHeader) {
                            $(document).trigger(Events.CommonEventsNames.AccessMembershipEnabled);
                        }
                    })
            };

            self.dismissAccessMembership = function () {
                self.talentSearchPreferences.editableItem().isAccessMembershipEnabled(false);

                return saveTalentSearchPreferences()
                    .done(function () {
                        showHideElementsOnDialog(false);
                        hideDialog();
                        $("#skip-to-content-button").focus();
                        gJobs.screenReadersService.setAriaLiveNotification('You did not upgrade your account. The modal dialog has been closed.');

                        gJobs.common.analytics.trackEvent(
                            'Access Membership Popup',
                            'Dismissed',
                            'After removing price label'
                        );

                        if (options && options.redirectToSearchPage) {
                            options.redirectToSearchPage();
                        }

                        $(document).trigger(
                            Events.CommonEventsNames.CloseAccessMembershipDialog
                        );
                    });
            };

            self.leaveCongratulationsTab = function () {
                hideDialog();
                gJobs.screenReadersService.setAriaLiveNotification('The modal dialog has been closed.');

                if (options && options.redirectToSearchPage) {
                    options.redirectToSearchPage();
                }

                $(document).trigger(
                    Events.CommonEventsNames.CloseAccessMembershipDialog
                );
            };

            function saveTalentSearchPreferences() {

                return self.talentSearchPreferences.saveChanges(self.talentSearchPreferences)
                    .fail(function () {
                        toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                    })
                    .always(function () {
                        self.talentSearchPreferences.endEdit(self.talentSearchPreferences);
                    });
            };

            function showHideElementsOnDialog(hide) {
                gJobs.dialogHelper.showHideElementsOnDialog(
                    {
                        selector: '#body-container, #main-container,'
                                  + '#footer, #footer-new, .new-job-flyout, #skip-to-content-button,'
                                  + '#last-focusable-element, #cookie-consent',
                        shouldDisableRestoreTabIndex: true,
                        hide: hide
                    }
                );
            }

            function hideDialog() {
                $body.attr('class', initialBodyClasses);
                $accessMembershipDialog.removeClass('active');
                self.visible(false);
            }

            function focusOnFistTabbableDialogElement() {
                $accessMembershipDialog.find(":tabbable").first().focus();
            }

            $(document).on('keydown', function(e) {
                if (e.keyCode === $.ui.keyCode.ESCAPE && self.visible()) {
                    if (self.accountUpgraded()) {
                        self.leaveCongratulationsTab();
                    } else {
                        self.dismissAccessMembership();
                    }
                }
            });
        }

        if (gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.GJobs || gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.Agency) {
            $(document).one(Events.CommonEventsNames.ShowAccessMembershipDialog, function () {
                var currentQueryParams = url.get(window.location.search.slice(1), { array: true });
                var currentPage = gJobs.pageInfoService.getCurrentPageType();
                var isOnAccountSettingsPage = currentPage == gJobs.pageInfoService.getPageTypes().accountSettings;
                var isOnApplicationsCreateAccountPage = currentPage == gJobs.pageInfoService.getPageTypes().applications &&
                    window.location.pathname.toLowerCase().indexOf('createaccount') > -1;

                var talentSearchPreferences;

                if (isOnAccountSettingsPage) {
                    var accountSettings = OnlineApp.ViewModels.accountSettingsViewModel;
                    talentSearchPreferences = (accountSettings && accountSettings.talentSearchPreferences) || null;
                }

                if (currentQueryParams.declined !== 'true' && !$('html').hasClass('error-page')) {
                    var $element = $accessMembershipDialog.get(0);
                    if (!ko.dataFor($element)) {
                        $(document).trigger(Events.CommonEventsNames.OpenAccessMembershipDialog);
                        var options;

                        if (isOnApplicationsCreateAccountPage) {
                            options = {
                                redirectToSearchPage: function () {
                                    window.location.replace('/jobs');
                                }
                            };
                        }

                        var viewModel = new AccessMembershipDialogViewModel(options);
                        viewModel.init(talentSearchPreferences);
                        ko.applyBindings(viewModel, $element);

                        $accessMembershipDialog.addClass('active');
                        viewModel.visible(true);                        
                    }

                    initialBodyClasses = $body.attr('class') || '';
                    $body.addClass(disableScrollClasses);
                }
            });
        }
    })
})(window);
(function(window) {

    $(document).ready(function() {

        var $confirmDialog = $('#confirm-dialog'),
            $body = $('body'),
            disableScrollClasses = 'scroll-disable inner-scrollbar',
            initialBodyClasses = '',
            confirmDialogHeaderSelector = '#dialog-header',
            confirmDialogSubHeaderSelector = '#dialog-subheader',
            confirmDialogCancelButtonSelector = '.cancel-button',
            lastFocusedElement;

        function ConfirmDialogViewModel() {
            var self = this;

            var closeDialog = function () {
                $("#aria-live-message-container").text('');
                self.visible(false);
                setTimeout(function () {                    
                    gJobs.screenReadersService.setAriaLiveNotification("The modal dialog has been closed.");                    
                });
            }

            var defaultViewData = {
                header: 'Proceed with an action',                
                cancelButtonText: 'Cancel',
                confirmButtonText: 'Confirm',
                additionalCssClassName: '',
                innerHtml: null,
                confirmClick: closeDialog,
                cancelClick: closeDialog
            };

            self.visible = ko.observable(false);
    
            self.additionalCssClassName = ko.observable(defaultViewData.additionalCssClassName);

            self.innerHtml = ko.observable(null);

            self.confirmDialogStateClassName = ko.observable('');

            self.confirmDialogClasses = ko.computed(function () {
                var confirmDialogStateClassName = self.confirmDialogStateClassName();
                var additionalCssClassName = self.additionalCssClassName();

                var classes = [];
                if (confirmDialogStateClassName) {
                    classes.push(confirmDialogStateClassName);
                }
                if (additionalCssClassName) {
                    classes.push(additionalCssClassName);
                }

                return classes.join(' ');
            });

            self.confirmClick = ko.observable(defaultViewData.confirmClick);
            self.cancelClick = ko.observable(defaultViewData.cancelClick);

            self.header = ko.observable(defaultViewData.header);

            self.subHeader = ko.observable(defaultViewData.subHeader);

            self.confirmButtonText = ko.observable(defaultViewData.confirmButtonText);
            self.cancelButtonText = ko.observable(defaultViewData.cancelButtonText);

            self.show = function (viewData) {
                self.confirmClick(function() {
                    defaultViewData.confirmClick();
                    if (viewData.confirmClick || viewData.confirmClick === "function") {
                        viewData.confirmClick();
                    }
                });
                self.cancelClick(function() {
                    defaultViewData.cancelClick();
                    if (viewData.cancelClick && typeof viewData.cancelClick === "function") {
                        viewData.cancelClick();
                    }
                });

                self.header(viewData.header || defaultViewData.header);
                self.subHeader(viewData.subHeader || defaultViewData.subHeader);
    
                if (viewData.hideSubHeader) {
                    self.subHeader('');
                }

                self.confirmButtonText(viewData.confirmButtonText || defaultViewData.confirmButtonText);
                self.cancelButtonText(viewData.cancelButtonText || defaultViewData.cancelButtonText);

                self.additionalCssClassName(viewData.additionalCssClassName || defaultViewData.additionalCssClassName);

                self.innerHtml(viewData.innerHtml || defaultViewData.innerHtml);

                self.visible(true);                
                self.announceConfirmDialogContent();
            };

            self.visible.subscribe(function (newValue) {
                self.confirmDialogStateClassName(newValue ? 'active' : 'inactive');

                if (newValue) {
                    $(document).on('touchmove', disableTouchMove);
    
                    var buttonSelector = $confirmDialog.find('button');
                    var firstButton = buttonSelector.eq(0); // Close button icon (X)
                    if (!firstButton.length || firstButton.css('display') === 'none') {
                        firstButton = buttonSelector.eq(1); // Cancel button
                    }

                    // Delay the focusing because of IE11
                    setTimeout(function() {
                        firstButton.focus();
                    });

                    showHideElementsOnPopup(true);
                } else {
                    $(document).off('touchmove', disableTouchMove);
                    
                    showHideElementsOnPopup(false);

                    $body.attr('class', initialBodyClasses);
                    lastFocusedElement.focus();
                    ko.cleanNode($confirmDialog[0]);
                }
            });

            self.announceConfirmDialogContent = function() {
                if (!$confirmDialog.length) return;
              

            

                var dialogSubHeaderMessage = $confirmDialog.find(confirmDialogSubHeaderSelector).text();
                var message = dialogSubHeaderMessage;
                var headerMessage = $confirmDialog.find(confirmDialogHeaderSelector).text();

                var confirmDialogCancelButton = $confirmDialog.find(confirmDialogCancelButtonSelector);

                var options = {
                    message: message,
                    $element: confirmDialogCancelButton
                }; 
                
                setTimeout(function(){
                    gJobs.screenReadersService.setAriaLiveNotification(headerMessage +"   "+ message); 
                }, 200);
               
            };
    
            function showHideElementsOnPopup(hide) {
                var selector = '#body-container, #main-container, #footer, ' 
                                + '.new-job-flyout, #skip-to-content-button, '
                                + '#last-focusable-element, #cookie-consent';

                if (window.revampedDesign) {
                    selector += ", #footer-new"
                }

                gJobs.dialogHelper.showHideElementsOnDialog(
                    {
                        selector: selector,
                        shouldDisableRestoreTabIndex: true,
                        hide: hide 
                    }
                );
            }

            function disableTouchMove(e) {
                e.preventDefault();
            }
    
            $(window).on('statechange', function () {
                if (self.visible()) {
                    self.visible(false);
                }
            });

            $(document).on('keydown', function(e) {
                if (e.keyCode === $.ui.keyCode.ESCAPE && self.visible()) {
                    self.cancelClick()();
                }
            });
        }

        $(document).on(Events.CommonEventsNames.ShowConfirmDialog, function (e, data) {
            if (!$('html').hasClass('error-page')) {
                $element = $confirmDialog[0];
                lastFocusedElement = $(document.activeElement);
                if (!ko.dataFor($element)) {
                    var viewModel = new ConfirmDialogViewModel();
                    ko.applyBindings(viewModel, $element);
                    viewModel.show(data);
                }

                initialBodyClasses = $body.attr('class') || '';
                $body.addClass(disableScrollClasses);
            }
        });
    })
})(window);
(function (window) {
    $(document).ready(function () {
        if (!window.enableStickyHeader) return;

        var accessMembershipPageUrl = '/AccessMembership?';

        var accessMembershipEnabledEndpoint = '/api/accessMembership/isAccessMembershipEnabled';

        var $accessMembershipLink = $('.sticky-header-access-membership-link'),
            $stickyHeader = $('#sticky-header'),
            $contentContainer = $('#content');

        var respectStickyHeaderClassName = 'respect-sticky-header';

        var flyoutWindowTopStylingWasRecalculated = false;

        function handleDisplayOfStickyHeaderOnCurrentPage(shouldDisplayStickyHeader) {
            if (shouldDisplayStickyHeader) {
                $stickyHeader.show();
                $contentContainer.addClass(respectStickyHeaderClassName);
                window.enableStickyHeader = true;
            } else {
                if (flyoutWindowTopStylingWasRecalculated) {
                    $(document).trigger(Events.CommonEventsNames.HideStickyHeader);
                } else {
                    $stickyHeader.hide();
                }
                $contentContainer.removeClass(respectStickyHeaderClassName);
                window.enableStickyHeader = false;
            }
        }

        OnlineApp.Services.authenticationService.isLoggedIn().done(function(isLoggedIn) {
            if (isLoggedIn) {
                if (gJobs.areaInfoService.getCurrentArea() === gJobs.areaInfoService.areaNames.Agency
                    && gJobs.pageInfoService.isOnApplyPage()) {
                    handleDisplayOfStickyHeaderOnCurrentPage(false);
                }
            }
        });

        $accessMembershipLink.click(function(event) {
            event.preventDefault();

            gJobs.common.analytics.trackEvent(
                'AM_StickyHeader',
                'Followed'
            );

            OnlineApp.Services.authenticationService.isLoggedIn().done(function(isLoggedIn) {
                if (!isLoggedIn) {
                    window.location = accessMembershipPageUrl;
                } else {
                    $(document).trigger(Events.CommonEventsNames.AccessMembershipEnabled, { ignoreFlyoutWindowTopStylingRecalculation: true });

                    var queryStringParams = { wantsToUpgrade: true };
                    var encodedQueryStringParams = $.param(queryStringParams);

                    window.open(accessMembershipPageUrl, '_blank');
                }
            });
        });

        var showStickyHeaderEvents = Events.CommonEventsNames.CloseFlyout +
            ' ' + Events.CommonEventsNames.ShowStickyHeader;

        var loginEvents = OnlineApp.Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;

        $(document)
            .on(loginEvents, function(event) {
                if (gJobs.pageInfoService.isOnPreferencesSectionPage()) {
                    $stickyHeader.hide();
                } else if (gJobs.pageInfoService.isOnApplyPage()) {
                    $(document).trigger(Events.CommonEventsNames.HideStickyHeader);
                } else {
                    $.ajax({
                        url: accessMembershipEnabledEndpoint,
                        type: 'GET',
                        cache: false
                    }).done(function(isAccessMembershipEnabled) {
                        handleDisplayOfStickyHeaderOnCurrentPage(!isAccessMembershipEnabled);
                    });
                }
            })
            .on(Events.CommonEventsNames.AccessMembershipEnabled, function(event, data) {
                if (!data || !data.ignoreFlyoutWindowTopStylingRecalculation) {
                    flyoutWindowTopStylingWasRecalculated = false;
                }

                handleDisplayOfStickyHeaderOnCurrentPage(false);
            })
            .on(Events.CommonEventsNames.JobAlertCreated, function () {
                handleDisplayOfStickyHeaderOnCurrentPage(false);
            })
            .one(showStickyHeaderEvents, function(event) {
                OnlineApp.Services.authenticationService.isLoggedIn()
                    .done(function(isLoggedIn) {
                        if (isLoggedIn) {
                            flyoutWindowTopStylingWasRecalculated = true;
                        }
                    });
            });
    });
})(window);
;
(function (window) {
    $(document).ready(function () {
        if (!window.enableChatbot) return;

        var boost,
            $chatbotOpenButton = $(".chatbot-open-button"),
            isChatBotOpened = false;

        var loginFailedCounter = 0;
        if ($chatbotOpenButton) {
            $chatbotOpenButton.css("z-index", "1");
        }
        function showChatbotOpenButton() {
            $chatbotOpenButton.show();
            $chatbotOpenButton.focus();
        }

        function hideChatbotOpenButton() {
            var showChatBotIcon = getWithExpiry("showChatBotIcon");

            if (!showChatBotIcon) {
                $chatbotOpenButton.hide();
            }
        }

        function openChatBot(isClicked) {
            gJobs.screenReadersService.setAriaLiveNotification(
                "The Governmentjobs.com's virtual agent has been opened."
            );
            boost.chatPanel.show();
            isChatBotOpened = true;

        }

        function minimizeChatBot() {
            gJobs.screenReadersService.setAriaLiveNotification(
                "The Governmentjobs.com's virtual agent has been closed."
            );

            boost.chatPanel.minimize();

            isChatBotOpened = false;
        }

        function setWithExpiry(key, value, ms) {
            const now = new Date();

            const item = {
                value: value,
                expiry: now.getTime() + ms
            }

            localStorage.setItem(key, JSON.stringify(item));
        }

        function getWithExpiry(key) {
            const itemFromStorage = localStorage.getItem(key);

            if (!itemFromStorage) {
                return null;
            }

            const item = JSON.parse(itemFromStorage);
            const now = new Date();

            if (now.getTime() > item.expiry) {
                localStorage.removeItem("showChatBotIcon");
                return null;
            }

            return item.value;
        }

        function attachChatbotEventHandlers() {
            boost.chatPanel.addEventListener(Events.CommonEventsNames.ChatbotClosed, function (event) {
                isChatBotOpened = false;

                showChatbotOpenButton();
            });
            boost.chatPanel.addEventListener(Events.CommonEventsNames.ChatPanelMinimized, function (event) {
                isChatBotOpened = false;

                showChatbotOpenButton();
            });

            boost.chatPanel.addEventListener(Events.CommonEventsNames.ChatbotConversationFeedbackTextGiven, function (event) {
                isChatBotOpened = false;
            });

            boost.chatPanel.addEventListener(Events.CommonEventsNames.ChatBotConversationDeleted, function (event) {
                isChatBotOpened = false;
            });

            boost.chatPanel.addEventListener(Events.CommonEventsNames.ChatbotPositiveMessageFeedbackGiven, function (event) {
                gJobs.screenReadersService.setAriaLiveNotification(
                    "Positive message feedback has been given."
                );
            });

            boost.chatPanel.addEventListener(Events.CommonEventsNames.ChatbotNegativeMessageFeedbackGiven, function (event) {
                gJobs.screenReadersService.setAriaLiveNotification(
                    "Negative message feedback has been given."
                );
            });

            $(document).on(Events.CommonEventsNames.LoginFailed, function (event) {
                // showChatbotOpenButton();
                loginFailedCounter++;
                if (loginFailedCounter > 1) {
                    openChatBot();
                    setWithExpiry("showChatBotIcon", true, 15 * 60 * 1000);
                }
            });

            $(document).on(Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register, function (event) {
                if (isChatBotOpened == true) {
                    minimizeChatBot();
                }
                window.localStorage.removeItem("showChatBotIcon");
                hideChatbotOpenButton();

            });

            $(document).on(Events.CommonEventsNames.HelpAndSupportPageOpened, function (event) {
                setTimeout(function () {
                    var areaInfoService = gJobs.areaInfoService;
                    var isCareerPages = areaInfoService.getCurrentArea() === areaInfoService.areaNames.Career;
                    if (isCareerPages == true) {
                        openChatBot();
                        setWithExpiry("showChatBotIcon");
                    }
                    else {
                        showChatbotOpenButton();
                        isChatBotOpened = true;
                    }
                }, 90 * 1000)
            });
        }

        (function initChatbot() {
            var areaInfoService = gJobs.areaInfoService;
            var isCareerPages = areaInfoService.getCurrentArea() === areaInfoService.areaNames.Career;

            $(".chatbot-open-button").addClass('chatbot');
            var options = {};
            $(".chatbot-open-button").css({ "position": "fixed" });

            boost = window.boostInit("governmentjobs-neogov", options);

            attachChatbotEventHandlers();

            var showChatBotIcon = getWithExpiry("showChatBotIcon");

            if (showChatBotIcon) {
                $chatbotOpenButton.show();
            }
        })();

        $chatbotOpenButton.click(function (event) {
            isChatBotOpened ? minimizeChatBot() : openChatBot(true);

        });
    });
})(window);;
(function (window) {

    $(document).ready(function () {
        if (!window.enableChatbase) return;

        var $chatbotOpenButton = $("#chatbase-bubble-button"), $chatBubbleWindow = $("#chatbase-bubble-window"), $chatMessageBubbleWindow = $("#chatbase-message-bubbles"),
            isChatBotOpened = false;
        var loginFailedCounter = 0;
        var isOpenedFromHelpAndSupport = false;
        var isloginFailed = false;
        var isChatWindowShownAutomaticallyInHelpAndSupport = false;



        if ($chatbotOpenButton) {
            $chatbotOpenButton.attr("tabindex", "0");
            $chatbotOpenButton.css("z-index", "999999");
            $chatbotOpenButton.css("height", "80px");
            $chatbotOpenButton.css("width", "80px");
            $chatbotOpenButton.css("border-radius", "50px");
            $chatbotOpenButton.css("bottom", "50px");
            $chatbotOpenButton.attr("role", "button");
        }
        $chatMessageBubbleWindow.css("z-index", "0");
        $chatMessageBubbleWindow.css("display", "none");
        if ($chatBubbleWindow) {
            $chatBubbleWindow.attr("tabindex", "0");
            $chatBubbleWindow.css("max-height", "600px");
            $chatBubbleWindow.css("max-width", "350px");
            $chatBubbleWindow.css("bottom", "1rem");
            $chatBubbleWindow.css("right", "5rem");
            $chatBubbleWindow.attr("role", "dialog");

        }

        if ($chatMessageBubbleWindow) {
            $chatMessageBubbleWindow.hide();
        }

        function showChatbotOpenButton() {
            $chatbotOpenButton.show();
            $chatbotOpenButton.focus();
        }

        function hideChatbotOpenButton() {
            setTimeout(function () {
                $chatBubbleWindow.css("display", "none");
                $chatbotOpenButton.hide();
                $chatBubbleWindow.hide();
            }, 100);
        }

        function openChatBot(isClicked) {
            gJobs.screenReadersService.setAriaLiveNotification(
                "The Governmentjobs.com's virtual agent has been opened."
            );
            $chatbotOpenButton.show();
            setTimeout(function () { 
                $chatBubbleWindow.focus();
                isChatBotOpened = true;
            }, 100);


        }

        function minimizeChatBot() {
            gJobs.screenReadersService.setAriaLiveNotification(
                "The Governmentjobs.com's virtual agent has been closed."
            );
            setTimeout(function () {              
                
                $chatbotOpenButton.focus();
                isChatBotOpened = false;
            }, 100);
        }

        function setWithExpiry(key, value, ms) {
            const now = new Date();

            const item = {
                value: value,
                expiry: now.getTime() + ms
            }

            localStorage.setItem(key, JSON.stringify(item));
        }

        function getWithExpiry(key) {
            const itemFromStorage = localStorage.getItem(key);

            if (!itemFromStorage) {
                return null;
            }

            const item = JSON.parse(itemFromStorage);
            const now = new Date();

            if (now.getTime() > item.expiry) {
                localStorage.removeItem("showChatBotIcon");
                return null;
            }

            return item.value;
        }

        function attachChatbotEventHandlers() {

            $(document).on(Events.CommonEventsNames.LoginFailed, function (event) {

                loginFailedCounter++;
                if (loginFailedCounter > 1) {
                    var element = document.getElementById('chatbase-bubble-button');
                    if (element) {
                        element.style.display = "block";
                    }
                    isloginFailed = false;
                   
                    $chatbotOpenButton.click();
                    var chatwindow = document.getElementById('chatbase-bubble-window');
                    if (chatwindow) {
                        chatwindow.style.display = "block";
                    }
                    setWithExpiry("showChatBotIcon", true, 15 * 60 * 1000);
                    
                    
                }
            });

            $("body").on('DOMSubtreeModified', $chatbotOpenButton, function () {
                if (!isOpenedFromHelpAndSupport) {
                    setTimeout(function () {
                        var isKeyAvailable = getWithExpiry("showChatBotIcon");
                        if (!isKeyAvailable) {
                            var element = document.getElementById('chatbase-bubble-button');
                            if (element) {
                                element.hidden = true;
                                $chatbotOpenButton.hide();
                                element.style.display = "none";
                            }
                        }
                        else {

                            var element = document.getElementById('chatbase-bubble-button');
                            if (element) {
                                element.hidden = false;
                                element.style.display = "block";
                                $chatbotOpenButton.show();
                                if (isChatBotOpened == false && isloginFailed) {
                                    $chatbotOpenButton.click();
                                   
                                }
                            }
                        }
                    }, 1000);
                }
                else {
                    if (isChatWindowShownAutomaticallyInHelpAndSupport == false) {
                        var isLocalStorage = getWithExpiry("showChatBotIcon");
                        if (!isLocalStorage) {
                            $chatbotOpenButton.hide();
                            var element = document.getElementById('chatbase-bubble-button');
                            if (element) {
                                element.style.display = "none";
                            }
                        }                        
                    }
                    setTimeout(function () {
                        var element = document.getElementById('chatbase-bubble-button');
                        if (element) {
                            element.hidden = false;
                            element.style.display = "block";
                            $chatbotOpenButton.show();
                        }                        
                        if (isChatBotOpened == false && isChatWindowShownAutomaticallyInHelpAndSupport == false) {
                            
                            if ($chatBubbleWindow) {      
                                $chatbotOpenButton.click();
                                var chatwindow = document.getElementById('chatbase-bubble-window');
                                if (chatwindow) {
                                    chatwindow.style.display = "block";
                                }
                                isChatWindowShownAutomaticallyInHelpAndSupport = true;
                            }
                        }
                    }, 90 * 1000)
                }
            });

            $(document).on(Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register, function (event) {

                if (isChatBotOpened == true) {
                    minimizeChatBot();
                }
                window.localStorage.removeItem("showChatBotIcon");
                hideChatbotOpenButton();
                isloginFailed = false;
                isChatBotOpened = false;
                var element = document.getElementById('chatbase-bubble-button');
                if (element) {
                    element.style.display = "none";
                }

            });



            $(document).on(Events.CommonEventsNames.HelpAndSupportPageOpened, function (event) {
                isOpenedFromHelpAndSupport = true;

                //setWithExpiry("showChatBotIcon");
                var isLocalStorage = getWithExpiry("showChatBotIcon");
                if (!isLocalStorage) {
                    $chatbotOpenButton.hide();
                }                
            });
        }

        (function initChatbot() {
            isOpenedFromHelpAndSupport = false;
            isloginFailed = false;
            isChatWindowShownAutomaticallyInHelpAndSupport = false;
            var areaInfoService = gJobs.areaInfoService;
            var isCareerPages = areaInfoService.getCurrentArea() === areaInfoService.areaNames.Career;


            attachChatbotEventHandlers();
            setTimeout(function () {
                var showChatBotIcon = getWithExpiry("showChatBotIcon");

                if (!showChatBotIcon) {
                    $chatbotOpenButton.hide();
                }
                else {
                    $chatbotOpenButton.show();
                    var element = document.getElementById('chatbase-bubble-button');
                    if (element) {
                        element.style.display = "block";
                    }
                }
                
                $chatMessageBubbleWindow.hide();
            },2000);
        })();

        $chatbotOpenButton.click(function (event) {


            isChatBotOpened ? minimizeChatBot() : openChatBot(isChatBotOpened);


        });
        $chatbotOpenButton.on('keydown', function (event) {
            if (event.keyCode === $.ui.keyCode.ENTER) {
                $chatbotOpenButton.click();
            }
        });

    });
})(window);
;
